diff --git a/.env.example b/.env.example new file mode 100644 index 000000000..a69cdd9ec --- /dev/null +++ b/.env.example @@ -0,0 +1,7 @@ +AVAX_PUBLIC_URL="https://api.avax-test.network" + +PRIVATE_KEY=... +C_CHAIN_ADDRESS=0x... +X_CHAIN_ADDRESS=X-fuji... +P_CHAIN_ADDRESS=P-fuji... +CORETH_ADDRESS=C-fuji... \ No newline at end of file diff --git a/.eslintignore b/.eslintignore index 88c2ca451..53c37a166 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,5 +1 @@ -/**/*.js -/typings/* -/tests/* -/examples/* -/web/* \ No newline at end of file +dist \ No newline at end of file diff --git a/.eslintrc.cjs b/.eslintrc.cjs new file mode 100644 index 000000000..fcdb55958 --- /dev/null +++ b/.eslintrc.cjs @@ -0,0 +1,34 @@ +module.exports = { + env: { + browser: true, + es2021: true, + node: true, + }, + extends: [ + 'eslint:recommended', + 'plugin:@typescript-eslint/recommended', + 'prettier', + 'plugin:prettier/recommended', // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array. + ], + parser: '@typescript-eslint/parser', + settings: {}, + parserOptions: { + ecmaFeatures: { + jsx: true, + }, + ecmaVersion: 12, + sourceType: 'module', + // TODO: Why does uncommenting this remove the type imports? + // project: ['./tsconfig.json'], + }, + plugins: ['@typescript-eslint'], + rules: { + '@typescript-eslint/consistent-type-imports': 'error', + '@typescript-eslint/explicit-module-boundary-types': 'off', + '@typescript-eslint/no-explicit-any': 'off', + '@typescript-eslint/no-var-requires': 'error', + // Uncomment prefer-readonly and parserOptions.project to apply the rule. + // TODO: Uncomment both permanently after fixing the type import issue. + // '@typescript-eslint/prefer-readonly': 'error', + }, +}; diff --git a/.eslintrc.js b/.eslintrc.js deleted file mode 100644 index b8479f096..000000000 --- a/.eslintrc.js +++ /dev/null @@ -1,16 +0,0 @@ -module.exports = { - plugins: ["security"], - extends: ["prettier", "plugin:security/recommended"], - parserOptions: { - project: "tsconfig.json", - ecmaVersion: 2017, - sourceType: "module" - }, - parser: "@typescript-eslint/parser", - ignorePatterns: [ - "**/*/*.d.ts", - "**/*/*.test.ts", - "e2etestlib.ts", - "__mocks__" - ] -} diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 01dff9ae4..8996c9a27 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,7 +1,10 @@ version: 2 updates: - - package-ecosystem: "npm" + - package-ecosystem: github-actions directory: "/" schedule: - interval: "weekly" - target-branch: "development" + interval: weekly + - package-ecosystem: npm + directory: "/" + schedule: + interval: weekly \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 31e6d15e9..30d361f3f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,4 +1,4 @@ -name: CI +name: PR checks on: push: @@ -6,20 +6,25 @@ on: - master pull_request: -env: - CI: true - jobs: - Test: + Lint-build-test: + name: Lint, build and test runs-on: ubuntu-latest - strategy: - matrix: - node-version: [16] steps: - - uses: actions/checkout@v2 - - uses: actions/setup-node@v2 + - name: Checkout + uses: actions/checkout@v4 + - name: Setup Node.js + uses: actions/setup-node@v4 with: + node-version: 20.x cache: yarn - node-version: ${{ matrix.node-version }} - - run: yarn install --frozen-lockfile - - run: yarn test + - name: Install dependencies + run: yarn install --frozen-lockfile + - name: Lint + run: yarn lint:check + - name: Typecheck + run: yarn typecheck + - name: Test + run: yarn test + - name: Build + run: yarn build diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index b8ee5cb84..8320553cf 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -9,16 +9,16 @@ # the `language` matrix defined below to confirm you have the correct set of # supported CodeQL languages. # -name: "CodeQL" +name: 'CodeQL' on: push: - branches: [development] + branches: [master] pull_request: # The branches below must be a subset of the branches above - branches: [development] + branches: [master] schedule: - - cron: "39 22 * * 5" + - cron: '22 1 * * 6' jobs: analyze: @@ -32,32 +32,31 @@ jobs: strategy: fail-fast: false matrix: - language: ["javascript"] - # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] - # Learn more: - # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed + language: ['javascript'] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] + # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support steps: - name: Checkout repository - uses: actions/checkout@v2 + uses: actions/checkout@v3 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@v1 + uses: github/codeql-action/init@v2 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. - # queries: ./path/to/local/query, your-org/your-repo/queries@main + queries: security-extended # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild - uses: github/codeql-action/autobuild@v1 + uses: github/codeql-action/autobuild@v2 # ℹ️ Command-line programs to run using the OS shell. - # � https://git.io/JvXDl + # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines # and modify them (or add more) to build your code if your project @@ -68,4 +67,4 @@ jobs: # make release - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v1 + uses: github/codeql-action/analyze@v2 diff --git a/.github/workflows/njsscan-analysis.yml b/.github/workflows/njsscan-analysis.yml deleted file mode 100644 index e5fdeb722..000000000 --- a/.github/workflows/njsscan-analysis.yml +++ /dev/null @@ -1,30 +0,0 @@ -# This workflow integrates njsscan with GitHub's Code Scanning feature -# nodejsscan is a static security code scanner that finds insecure code patterns in your Node.js applications - -name: njsscan sarif - -on: - push: - branches: [development] - pull_request: - # The branches below must be a subset of the branches above - branches: [development] - schedule: - - cron: "28 3 * * 6" - -jobs: - njsscan: - runs-on: ubuntu-latest - name: njsscan code scanning - steps: - - name: Checkout the code - uses: actions/checkout@v2 - - name: nodejsscan scan - id: njsscan - uses: ajinabraham/njsscan-action@master - with: - args: ". --sarif --output results.sarif || true" - - name: Upload njsscan report - uses: github/codeql-action/upload-sarif@v1 - with: - sarif_file: results.sarif diff --git a/.github/workflows/prerelease.yml b/.github/workflows/prerelease.yml new file mode 100644 index 000000000..29f9e6e22 --- /dev/null +++ b/.github/workflows/prerelease.yml @@ -0,0 +1,28 @@ +name: Prerelease +on: + push: + branches: + - master +jobs: + release: + name: Prerelease + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 20.x + - name: Install dependencies + run: yarn + - name: Build library + run: yarn build:prod + - name: Release + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} + BRANCH_NAME: ${{ github.head_ref || github.ref_name }} + run: yarn run semantic-release diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f0a0e3150..3b4d29be6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,32 +1,33 @@ -name: Push to release branch - +name: Release on: push: branches: - release - - master jobs: release: name: Release runs-on: ubuntu-latest - environment: production steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v4 with: fetch-depth: 0 - name: Setup Node.js - uses: actions/setup-node@v1 + uses: actions/setup-node@v4 with: - node-version: 16.x - - name: Create .npmrc - run: echo '//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}' >> .npmrc + node-version: 20.x - name: Install dependencies - run: yarn install + run: yarn - name: Build library - run: yarn build + run: yarn build:prod - name: Release env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - RELEASE_BRANCH: release + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} + BRANCH_NAME: ${{ github.head_ref || github.ref_name }} run: yarn run semantic-release + - name: Rebase master + run: | + git checkout master && + git rebase release && + git push origin master diff --git a/.gitignore b/.gitignore index b078d0eac..2315c1592 100644 --- a/.gitignore +++ b/.gitignore @@ -1,115 +1,14 @@ +.DS_Store -# Created by https://www.gitignore.io/api/node -# Edit at https://www.gitignore.io/?templates=node - -### Node ### -# Logs -logs -*.log -npm-debug.log* -package-lock.json -yarn-debug.log* -yarn-error.log* -lerna-debug.log* -# Diagnostic reports (https://nodejs.org/api/report.html) -report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json - -# Runtime data -pids -*.pid -*.seed -*.pid.lock - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage -*.lcov - -# nyc test coverage -.nyc_output - -# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# Stats output -stats.json - -# Bower dependency directory (https://bower.io/) -bower_components - -# node-waf configuration -.lock-wscript - -# Compiled binary addons (https://nodejs.org/api/addons.html) -build/Release - -# Dependency directories -node_modules/ -jspm_packages/ -dist/ - -# TypeScript v1 declaration files -typings/ - -# Documentation directories -docs/ -docsMD/ -docsHTML/ - -# TypeScript cache -*.tsbuildinfo - -# Optional npm cache directory -.npm - -# Optional eslint cache -.eslintcache - -# Optional REPL history -.node_repl_history - -# Output of 'npm pack' -*.tgz - -# Yarn Integrity file -.yarn-integrity - -# dotenv environment variables file -.env -.env.test - -# parcel-bundler cache (https://parceljs.org/) -.cache - -# next.js build output -.next - -# nuxt.js build output -.nuxt - -# react / gatsby -public/ - -# vuepress build output -.vuepress/dist - -# Serverless directories -.serverless/ - -# FuseBox cache -.fusebox/ - -# DynamoDB Local files -.dynamodb/ +/node_modules +/dist +/coverage +/yarn-error.log -# JetBrains IDE .idea -# MAC OS -.DS_Store - -# End of https://www.gitignore.io/api/node.idea/* +stats.html +.dccache -.markdownlint.json +todo.* +.env \ No newline at end of file diff --git a/.husky/commit-msg b/.husky/commit-msg new file mode 100755 index 000000000..4974c35b4 --- /dev/null +++ b/.husky/commit-msg @@ -0,0 +1,4 @@ +#!/usr/bin/env sh +. "$(dirname -- "$0")/_/husky.sh" + +npx commitlint --edit $1 diff --git a/.husky/pre-commit b/.husky/pre-commit index 36af21989..f3b20ac69 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1,4 +1,5 @@ -#!/bin/sh -. "$(dirname "$0")/_/husky.sh" +#!/usr/bin/env sh +. "$(dirname -- "$0")/_/husky.sh" -npx lint-staged + +yarn build && npx lint-staged \ No newline at end of file diff --git a/.npmignore b/.npmignore deleted file mode 100644 index 9496dfb91..000000000 --- a/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -coverage -docs -docsMD -tsconfig.json \ No newline at end of file diff --git a/.nvmrc b/.nvmrc deleted file mode 100644 index 99cdd8009..000000000 --- a/.nvmrc +++ /dev/null @@ -1 +0,0 @@ -16.15.0 diff --git a/.prettierignore b/.prettierignore index e9c06709e..53c37a166 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,6 +1 @@ -node_modules -dist -coverage -web/ - -*.md \ No newline at end of file +dist \ No newline at end of file diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 000000000..dcb72794f --- /dev/null +++ b/.prettierrc @@ -0,0 +1,4 @@ +{ + "singleQuote": true, + "trailingComma": "all" +} \ No newline at end of file diff --git a/.releaserc.js b/.releaserc.cjs similarity index 55% rename from .releaserc.js rename to .releaserc.cjs index b227329fc..ddd735aaa 100644 --- a/.releaserc.js +++ b/.releaserc.cjs @@ -17,79 +17,86 @@ $ run yarn run semantic-release -d */ const commitAnalyzerSetting = [ - "@semantic-release/commit-analyzer", + '@semantic-release/commit-analyzer', { - preset: "angular", + preset: 'angular', releaseRules: [ { - type: "feat", - release: "minor" + type: 'feat', + release: 'minor', }, { - type: "*", - release: "patch" - } + type: '*', + release: 'patch', + }, ], parserOpts: { - noteKeywords: ["BREAKING CHANGE", "BREAKING CHANGES"] - } - } -] + noteKeywords: ['BREAKING CHANGE', 'BREAKING CHANGES'], + }, + }, +]; const githubSetting = [ - "@semantic-release/github", + '@semantic-release/github', { - assets: [{ path: "dist/index.js", label: "SDK Distributable" }], + assets: [{ path: 'dist/index.js', label: 'SDK Distributable' }], failTitle: false, successComment: false, failComment: false, - labels: false - } -] + labels: false, + }, +]; const gitSetting = [ - "@semantic-release/git", + '@semantic-release/git', { - assets: ["package.json"], + assets: ['package.json'], message: - "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}" - } -] + 'chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}', + }, +]; const npmRelease = [ - "@semantic-release/npm", + '@semantic-release/npm', { - npmPublish: true - } -] + npmPublish: true, + }, +]; + +const changelogGen = ['@semantic-release/changelog', {}]; -const changelogGen = ["@semantic-release/changelog", {}] +const releaseNotesGen = ['@semantic-release/release-notes-generator', {}]; -const releaseNotesGen = ["@semantic-release/release-notes-generator", {}] +let plugins; -let plugins -if (process.env && process.env.RELEASE_BRANCH === "release") { +if (process.env && process.env.BRANCH_NAME === 'release') { plugins = [ commitAnalyzerSetting, githubSetting, changelogGen, releaseNotesGen, npmRelease, - gitSetting - ] + gitSetting, + ]; } else { - plugins = [githubSetting, gitSetting] + plugins = [ + commitAnalyzerSetting, + githubSetting, + changelogGen, + releaseNotesGen, + npmRelease, + ]; } module.exports = { branches: [ { - name: "release" + name: 'release', }, { - name: "master", - prerelease: "alpha" - } + name: 'master', + prerelease: 'alpha', + }, ], - plugins -} + plugins, +}; diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index 0e48bcda4..000000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "type": "node", - "request": "launch", - "name": "Launch Program", - "skipFiles": ["/**"], - "program": "${workspaceFolder}/examples/platformvm/proofOfPossession.ts", - "preLaunchTask": "npm: build", - "sourceMaps": true, - "outFiles": ["${workspaceFolder}/typings/**/*.js"] - } - ] -} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..3662b3700 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "typescript.tsdk": "node_modules/typescript/lib" +} \ No newline at end of file diff --git a/.vscode/testing.code-snippets b/.vscode/testing.code-snippets new file mode 100644 index 000000000..2a97d7163 --- /dev/null +++ b/.vscode/testing.code-snippets @@ -0,0 +1,79 @@ +{ + // Place your avalanchejs-v2 workspace snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and + // description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope + // is left empty or omitted, the snippet gets applied to all languages. The prefix is what is + // used to trigger the snippet and the body will be expanded and inserted. Possible variables are: + // $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. + // Placeholders with the same ids are connected. + // Example: + "testSerial": { + "scope": "typescript", + "prefix": "testser", + "body": [ + "testSerialization('${TM_FILENAME/(.)(.+?)\\.(.+)/${1:/upcase}$2/}', ${TM_FILENAME/(.)(.+?)\\.(.+)/${1:/upcase}$2/}, ${TM_FILENAME/\\.(.+)//g}, ${TM_FILENAME/\\.(.+)//g}Bytes, testPVMCodec);", + "$2" + ], + "description": "Log output to console" + }, + "newtx": { + "scope": "typescript", + "prefix": "newtx", + "body": [ + "import { Codec } from '../codec';", + "import { serializable } from '../../common/types';", + "import { concatBytes } from '../../utils/buffer';", + "import { pack, unpack } from '../../utils/struct';", + "", + "const _symbol = Symbol('pvm.${1:TxName}');", + "", + "/**", + " * @see ", + " */", + "@serializable()", + "export class $1 {", + " _type = _symbol;", + "", + " constructor($2 ) {}", + "", + " static fromBytes(bytes: Uint8Array, codec: Codec): [$1, Uint8Array] {", + " const [$3, rest] = unpack(bytes, [], codec);", + " return [new $1(), rest];", + " }", + "", + " toBytes(codec: Codec) {", + " return pack();", + " }", + "}" + ], + "description": "new tx type" + }, + "newtx": { + "scope": "typescript", + "prefix": "nrpc", + "body": [ + "$1(", + " $1Params: ${1/(.*)/${1:/pascalcase}/}Params,", + "): Promise<${1/(.*)/${1:/pascalcase}/}Response> {", + " return this.callRpc<${1/(.*)/${1:/pascalcase}/}Response>(", + " '$1',", + " $1Params,", + " );", + "}" + ], + "description": "new rpc" + }, + "newResponse": { + "scope": "typescript", + "prefix": "nresp", + "body": [ + "export interface ${1/(.*)/${1:/pascalcase}/}Params {", + "$2", + "}", + "", + "export interface ${1/(.*)/${1:/pascalcase}/}Response {", + " $3", + "}" + ], + "description": "new rpc response" + } +} diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index c386c4c50..000000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,87 +0,0 @@ -# CHANGELOG - -## v1.7.0 - -### Notes - -* Added Denali testnet network values -* NFTs are partially implemented in anticipation of their complete release in a future build - -### Method Signature Changes - -* `avm.makeUnsignedTx` - * Renamed to `avm.makeBaseTx` - * Now returns `UnsignedTx` instead of `TxUnsigned` -* `avm.makeCreateAssetTx` - * 4th parameter has been renamed `initialStates` from `initialState` - * Now returns `UnsignedTx` instead of `TxCreateAsset` -* `avm.signTx` - * Now accepts `UnsignedTx` instead of `TxUnsigned` -* `SelectInputClass` - * Now accepts a `number` instead of a `Buffer` -* `avm.getInputID` - * Has been renamed to `avm.getInput` and now returns an `Input` instead of a `number` - -### New Methods - -* `avm.makeNFTTransferTx` - -### New Classes - -* avm credentials - * Credential - * SecpCredential is a superset of Credential - * NFTCredential is a superset of Credential -* avm inputs - * TransferableInput - * AmountInput -* avm ops - * Operation - * TransferableOperation - * NFTTransferOperation -* avm outputs - * TransferableOutput - * AmountOutput - * SecpOutput - * NFTOutBase -* avm tx - * BaseTx - * CreateAssetTx - * OperationTx - * UnsignedTx -* avm types - * UTXOID - -### New Types - -* MergeRule - -### Updated Classes - -* Input is now `abstract` - -### Deleted Classes - -* avm utxos - * SecpUTXO -* avm outputs - * SecpOutBase -* avm tx - * TxUnsigned - * TxCreateAsset - -### New consts - -* avm credentials - * SelectCredentialClass - -### Deleted consts - -* avm utxos - * SelectUTXOClass - -### New RPC Calls - -* `platform.getSubnets` -* `avm.buildGenesis` -* `keystore.deleteUser` diff --git a/LICENSE b/LICENSE index 1d314a7bf..2ce33b2b3 100644 --- a/LICENSE +++ b/LICENSE @@ -1,29 +1,24 @@ -BSD 3-Clause License - -Copyright (c) 2020, Ava Labs, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +Copyright (C) 2020, Ava Labs, Inc. All rights reserved. + +Ecosystem License +Version 1.1 + +Subject to the terms herein, Ava Labs, Inc. (**“Ava Labs”**) hereby grants you a limited, royalty-free, worldwide, non-sublicensable, non-transferable, non-exclusive license to use, copy, modify, create derivative works based on, and redistribute the Software, in source code, binary, or any other form, including any modifications or derivative works of the Software (collectively, **“Licensed Software”**), in each case subject to this Ecosystem License (**“License”**). + +This License applies to all copies, modifications, derivative works, and any other form or usage of the Licensed Software. You will include and display this License, without modification, with all uses of the Licensed Software, regardless of form. + +You will use the Licensed Software solely (i) in connection with the Avalanche Public Blockchain platform, having a NetworkID of 1 (Mainnet) or 5 (Fuji), and associated blockchains, comprised exclusively of the Avalanche X-Chain, C-Chain, P-Chain and any subnets linked to the P-Chain (**“Avalanche Authorized Platform”**) or (ii) for non-production, testing or research purposes within the Avalanche ecosystem, in each case, without any commercial application (**“Non-Commercial Use”**); provided that this License does not permit use of the Licensed Software in connection with (a) any forks of the Avalanche Authorized Platform or (b) in any manner not operationally connected to the Avalanche Authorized Platform other than, for the avoidance of doubt, the limited exception for Non-Commercial Use. Ava Labs may publicly announce changes or additions to the Avalanche Authorized Platform, which may expand or modify usage of the Licensed Software. Upon such announcement, the Avalanche Authorized Platform will be deemed to be the then-current iteration of such platform. + +You hereby acknowledge and agree to the terms set forth at www.avalabs.org/important-notice. + +If you use the Licensed Software in violation of this License, this License will automatically terminate and Ava Labs reserves all rights to seek any remedy for such violation. + +Except for uses explicitly permitted in this License, Ava Labs retains all rights in the Licensed Software, including without limitation the ability to modify it. + +Except as required or explicitly permitted by this License, you will not use any Ava Labs names, logos, or trademarks without Ava Labs’ prior written consent. + +You may use this License for software other than the “Licensed Software” specified above, as long as the only change to this License is the definition of the term “Licensed Software.” + +The Licensed Software may reference third party components. You acknowledge and agree that these third party components may be governed by a separate license or terms and that you will comply with them. + +**TO THE MAXIMUM EXTENT PERMITTED BY LAW, THE LICENSED SOFTWARE IS PROVIDED ON AN “AS IS” BASIS, AND AVA LABS EXPRESSLY DISCLAIMS AND EXCLUDES ALL REPRESENTATIONS, WARRANTIES AND OTHER TERMS AND CONDITIONS, WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION BY OPERATION OF LAW OR BY CUSTOM, STATUTE OR OTHERWISE, AND INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED WARRANTY, TERM, OR CONDITION OF NON-INFRINGEMENT, MERCHANTABILITY, TITLE, OR FITNESS FOR PARTICULAR PURPOSE. YOU USE THE LICENSED SOFTWARE AT YOUR OWN RISK. AVA LABS EXPRESSLY DISCLAIMS ALL LIABILITY (INCLUDING FOR ALL DIRECT, CONSEQUENTIAL OR OTHER DAMAGES OR LOSSES) RELATED TO ANY USE OF THE LICENSED SOFTWARE.** \ No newline at end of file diff --git a/README.md b/README.md index f5addf239..7f7767b79 100644 --- a/README.md +++ b/README.md @@ -1,411 +1,73 @@ # AvalancheJS - The Avalanche Platform JavaScript Library -## Deprecation of avalancheJS - -The npm package `https://www.npmjs.com/package/avalanche` is being deprecated. For the latest version please use @avalabs/avalanchejs. We will no longer support the avalanche npm package. - ## Overview AvalancheJS is a JavaScript Library for interfacing with the Avalanche Platform. It is built using TypeScript and intended to support both browser and Node.js. The AvalancheJS library allows you to issue commands to the Avalanche node APIs. -The APIs currently supported by default are: - -* Admin API -* Auth API -* AVM API (X-Chain) -* EVM API (C-Chain) -* Health API -* Index API -* Info API -* Keystore API -* Metrics API -* PlatformVM API (P-Chain) -* Socket - -We built AvalancheJS with ease of use in mind. With this library, any Javascript developer is able to interact with a node on the Avalanche Platform who has enabled their API endpoints for the developer's consumption. We keep the library up-to-date with the latest changes in the [Avalanche Platform Specification](https://docs.avax.network). +Using AvalancheJS, developers can: - Using AvalancheJS, developers can: - -* Locally manage private keys -* Retrieve balances on addresses -* Get UTXOs for addresses -* Build and sign transactions -* Issue signed transactions to the X-Chain, P-Chain, and C-Chain -* Perform cross-chain swaps between the X-Chain<->P-Chain and between the X-Chain<->C-Chain -* Add Validators and Delegators to the Primary Subnetwork by staking AVAX -* Create a Subnetwork -* Administer a local node -* Retrieve Avalanche network information from a node +- Retrieve balances on addresses +- Get UTXOs for addresses +- Build and sign transactions +- Issue signed transactions to the X-Chain, P-Chain, and C-Chain +- Perform cross-chain swaps between the X, P and C chains +- Add Validators and Delegators +- Create Subnets and Blockchains ### Requirements -AvalancheJS requires Node.js LTS version 14.16.0 or higher to compile. - -### Installation - -Avalanche is available for install via `yarn`: - -`yarn add avalanche` - -You can also pull the repo down directly and build it from scratch: - -`yarn build` - -This will generate a pure Javascript library and place it in a folder named "web" in the project root. The "avalanche.js" file can then be dropped into any project as a pure javascript implementation of Avalanche. - -The AvalancheJS library can be imported into your existing Node.js project as follows: - -```js -const avalanche = require("avalanche") -``` - -Or into your TypeScript project like this: - -```js -import { Avalanche } from "avalanche" -``` - -### Importing essentials - -```js -import { Avalanche, BinTools, BN, Buffer } from "avalanche" - -const bintools = BinTools.getInstance() -``` - -The above lines import the libraries used in the tutorials. The libraries include: - -* Avalanche: Our javascript module. -* BinTools: A singleton built into AvalancheJS that is used for dealing with binary data. -* [BN](https://www.npmjs.com/package/bn.js): A bignumber module use by AvalancheJS. -* [Buffer](https://www.npmjs.com/package/buffer): A Buffer library. - -## Example 1 — Managing X-Chain Keys - -AvalancheJS comes with its own AVM Keychain. This KeyChain is used in the functions of the API, enabling them to sign using keys it's registered. The first step in this process is to create an instance of AvalancheJS connected to our Avalanche Platform endpoint of choice. - -```js -import { Avalanche, BinTools, Buffer, BN } from "avalanche" - -const bintools = BinTools.getInstance() - -const myNetworkID = 12345 //default is 1, we want to override that for our local network -const avalanche = new Avalanche("localhost", 9650, "http", myNetworkID) -const xchain = avalanche.XChain() //returns a reference to the X-Chain used by AvalancheJS -``` - -### Accessing the KeyChain - -The KeyChain is accessed through the X-Chain and can be referenced directly or through a reference variable. - -```js -const myKeychain = xchain.keyChain() -``` - -This exposes the instance of the class AVMKeyChain which is created when the X-Chain API is created. At present, this supports secp256k1 curve for ECDSA key pairs. +AvalancheJS requires Node.js LTS version 20.11.1 or higher to compile. -### Creating X-Chain key pairs +## Installation -The KeyChain has the ability to create new KeyPairs for you and return the address associated with the key pair. +### Using the NPM Package -```js -const newAddress1 = myKeychain.makeKey() // returns an instance of the KeyPair class -``` +Add AvalancheJS to your project via `npm` or `yarn`. -You may also import your existing private key into the KeyChain using either a Buffer... +For installing via `npm`: -```js -const mypk = bintools.cb58Decode( - "JaCCSxdoWfo3ao5KwenXrJjJR7cBTQ287G1C5qpv2hr2tCCdb" -) // returns a Buffer -const newAddress2 = myKeychain.importKey(mypk) // returns an instance of the KeyPair class -``` - -... or an CB58 string works, too: - -```js -const mypk = "PrivateKey-JaCCSxdoWfo3ao5KwenXrJjJR7cBTQ287G1C5qpv2hr2tCCdb" -const newAddress2 = myKeychain.importKey(mypk) // returns an instance of the KeyPair class -``` - -### Working with KeyChains - -The X-Chains's KeyChain has standardized key management capabilities. The following functions are available on any KeyChain that implements this interface. - -```js -const addresses = myKeychain.getAddresses() // returns an array of Buffers for the addresses -const addressStrings = myKeychain.getAddressStrings() // returns an array of strings for the addresses -const exists = myKeychain.hasKey(addresses[0]) // returns true if the address is managed -const keypair = myKeychain.getKey(addresses[0]) // returns the KeyPair class -``` +`npm install --save @avalabs/avalanchejs` -### Working with KeyPairs +For installing via `yarn`: -The X-Chain's KeyPair has standardized KeyPair functionality. The following operations are available on any KeyPair that implements this interface. +`yarn add @avalabs/avalanchejs` -```js -const address = keypair.getAddress() // returns Buffer -const addressString = keypair.getAddressString() // returns string +### Build from Repository -const pubk = keypair.getPublicKey() // returns Buffer -const pubkstr = keypair.getPublicKeyString() // returns a CB58 encoded string +You can also pull the repo down directly and build it from scratch. -const privk = keypair.getPrivateKey() //returns Buffer -const privkstr = keypair.getPrivateKeyString() //returns a CB58 encoded string +Clone the AvalancheJS repository: -keypair.generateKey() // creates a new random KeyPair - -const mypk = bintools.cb58Decode( - "24jUJ9vZexUM6expyMcT48LBx27k1m7xpraoV62oSQAHdziao5" -) -const successful = keypair.importKey(mypk) // returns boolean if private key imported successfully - -const message = Buffer.from("Through consensus to the stars") -const signature = keypair.sign(message) // returns a Buffer with the signature - -const signerPubk = keypair.recover(message, signature) // returns a Buffer -const isValid = keypair.verify(message, signature) // returns a boolean -``` - -## Example 2 — Creating An Asset - -This example creates an asset in the X-Chain and publishes it to the Avalanche Platform. The first step in this process is to create an instance of AvalancheJS connected to our Avalanche Platform endpoint of choice. - -```js -import { Avalanche, BinTools, Buffer, BN } from "avalanche" -import { InitialStates, SECPTransferOutput } from "avalanche/dist/apis/avm" - -const myNetworkID = 12345 // default is 1, we want to override that for our local network -const avalanche = new Avalanche("localhost", 9650, "http", myNetworkID) -const xchain = avalanche.XChain() // returns a reference to the X-Chain used by AvalancheJS -``` - -### Describe the new asset - -The first steps in creating a new asset using AvalancheJS is to determine the qualities of the asset. We will give the asset a name, a ticker symbol, as well as a denomination. - -```js -// Name our new coin and give it a symbol -const name = "TeamRocket" -const symbol = "ROKT" - -// Where is the decimal point indicate what 1 asset is and where fractional assets begin -// Ex: 1 AVAX is denomination 9, so the smallest unit of AVAX is nanoAVAX (nAVAX) at 10^-9 AVAX -const denomination = 9 -``` +`git clone https://github.com/ava-labs/avalanchejs.git` -### Creating the initial state +Then build it: -We want to mint an asset with 400 coins to all of our managed keys, 500 to the second address we know of, and 600 to the second and third address. This sets up the state that will result from the Create Asset transaction. +`npm run build` -_Note: This example assumes we have the keys already managed in our X-Chain's Keychain._ +or -```js -const addresses = xchain.keyChain().getAddresses() - -// Create outputs for the asset's initial state -const secpOutput1 = new SECPTransferOutput( - new BN(400), - new BN(400), - 1, - addresses -) -const secpOutput2 = new SECPTransferOutput(new BN(500), new BN(400), 1, [ - addresses[1], -]) -const secpOutput3 = new SECPTransferOutput(new BN(600), new BN(400), 1, [ - addresses[1], - addresses[2], -]) - -// Populate the initialStates with the outputs -const initialState = new InitialStates() -initialState.addOutput(secpOutput1) -initialState.addOutput(secpOutput2) -initialState.addOutput(secpOutput3) -``` - -### Creating the signed transaction - -Now that we know what we want an asset to look like, we create an output to send to the network. There is an AVM helper function `buildCreateAssetTx()` which does just that. - -```js -// Fetch the UTXOSet for our addresses -const utxos = await xchain.getUTXOs(addresses) - -// Make an unsigned Create Asset transaction from the data compiled earlier -const unsigned = await xchain.buildCreateAssetTx( - utxos, // the UTXOSet containing the UTXOs we're going to spend - addresses, // the addresses which will pay the fees - addresses, // the addresses which recieve the change from the spent UTXOs - initialState, // the initial state to be created for this new asset - name, // the full name of the asset - symbol, // a short ticker symbol for the asset - denomination // the asse's denomination -) - -const signed = unsigned.sign(xchain) // returns a Tx class -``` - -### Issue the signed transaction - -Now that we have a signed transaction ready to send to the network, let's issue it! - -Using the AvalancheJS X-Chain API, we going to call the `issueTx` function. This function can take either the Tx class returned in the previous step, a CB58 representation of the transaction, or a raw Buffer class with the data for the transaction. Examples of each are below: - -```js -// using the Tx class -const txid = await xchain.issueTx(signed) // returns a CB58 serialized string for the TxID -``` - -```js -// using the base-58 representation -const txid = await xchain.issueTx(signed.toString()) // returns a CB58 serialized string for the TxID -``` - -```js -// using the transaction Buffer -const txid = await xchain.issueTx(signed.toBuffer()) // returns a CB58 serialized string for the TxID -``` - -We assume ONE of those methods are used to issue the transaction. - -### Get the status of the transaction - -Now that we sent the transaction to the network, it takes a few seconds to determine if the transaction has gone through. We can get an updated status on the transaction using the TxID through the AVM API. - -```js -// returns one of: "Accepted", "Processing", "Unknown", and "Rejected" -const status = await xchain.getTxStatus(txid) -``` - -The statuses can be one of "Accepted", "Processing", "Unknown", and "Rejected": - -* "Accepted" indicates that the transaction has been accepted as valid by the network and executed -* "Processing" indicates that the transaction is being voted on. -* "Unknown" indicates that node knows nothing about the transaction, indicating the node doesn't have it -* "Rejected" indicates the node knows about the transaction, but it conflicted with an accepted transaction - -### Identifying the newly created asset - -The X-Chain uses the TxID of the transaction which created the asset as the unique identifier for the asset. This unique identifier is henceforth known as the "AssetID" of the asset. When assets are traded around the X-Chain, they always reference the AssetID that they represent. - -## Example 3 — Sending An Asset - -This example sends an asset in the X-Chain to a single recipient. The first step in this process is to create an instance of Avalanche connected to our Avalanche Platform endpoint of choice. - -```js -import { Avalanche, BinTools, Buffer, BN } from "avalanche" - -const myNetworkID = 12345 // default is 1, we want to override that for our local network -const avalanche = new avalanche.Avalanche( - "localhost", - 9650, - "http", - myNetworkID -) -const xchain = avalanche.XChain() // returns a reference to the X-Chain used by AvalancheJS -``` - -We're also assuming that the keystore contains a list of addresses used in this transaction. - -### Getting the UTXO Set - -The X-Chain stores all available balances in a datastore called Unspent Transaction Outputs (UTXOs). A UTXO Set is the unique list of outputs produced by transactions, addresses that can spend those outputs, and other variables such as lockout times (a timestamp after which the output can be spent) and thresholds (how many signers are required to spend the output). - -For the case of this example, we're going to create a simple transaction that spends an amount of available coins and sends it to a single address without any restrictions. The management of the UTXOs will mostly be abstracted away. - -However, we do need to get the UTXO Set for the addresses we're managing. - -```js -const myAddresses = xchain.keyChain().getAddresses() // returns an array of addresses the KeyChain manages as buffers -const addressStrings = xchain.keyChain().getAddressStrings() // returns an array of addresses the KeyChain manages as strings -const u = await xchain.getUTXOs(myAddresses) -const utxos = u.utxos -``` - -### Spending the UTXOs - -The `buildBaseTx()` helper function sends a single asset type. We have a particular assetID whose coins we want to send to a recipient address. This is an imaginary asset for this example which we believe to have 400 coins. Let's verify that we have the funds available for the transaction. - -```js -const assetID = "8pfG5CTyL5KBVaKrEnCvNJR95dUWAKc1hrffcVxfgi8qGhqjm" // cb58 string -const mybalance = utxos.getBalance(myAddresses, assetID) // returns 400 as a BN -``` - -We have 400 coins! We're going to now send 100 of those coins to our friend's address. - -```js -const sendAmount = new BN(100) // amounts are in BN format -const friendsAddress = "X-avax1k26jvfdzyukms95puxcceyzsa3lzwf5ftt0fjk" // address format is Bech32 - -// The below returns a UnsignedTx -// Parameters sent are (in order of appearance): -// * The UTXO Set -// * The amount being sent as a BN -// * An array of addresses to send the funds -// * An array of addresses sending the funds -// * An array of addresses any leftover funds are sent -// * The AssetID of the funds being sent -const unsignedTx = await xchain.buildBaseTx( - utxos, - sendAmount, - [friendsAddress], - addressStrings, - addressStrings, - assetID -) -const signedTx = xchain.signTx(unsignedTx) -const txid = await xchain.issueTx(signedTx) -``` - -And the transaction is sent! +`yarn build` -### Get the status of the transaction +## Use AvalancheJS in Projects -Now that we sent the transaction to the network, it takes a few seconds to determine if the transaction has gone through. We can get an updated status on the transaction using the TxID through the X-Chain. +The AvalancheJS library can be imported into your existing project as follows: -```js -// returns one of: "Accepted", "Processing", "Unknown", and "Rejected" -const status = await xchain.getTxStatus(txid) +```ts +import { avm, pvm, evm } from '@avalabs/avalanchejs'; ``` -The statuses can be one of "Accepted", "Processing", "Unknown", and "Rejected": - -* "Accepted" indicates that the transaction has been accepted as valid by the network and executed -* "Processing" indicates that the transaction is being voted on. -* "Unknown" indicates that node knows nothing about the transaction, indicating the node doesn't have it -* "Rejected" indicates the node knows about the transaction, but it conflicted with an accepted transaction +## Importing Essentials -### Check the results +```ts +import { avm /** X-chain */, pvm /** P-chain */, evm /** C-chain */, utils } from "@avalabs/avalanchejs" -The transaction finally came back as "Accepted", now let's update the UTXOSet and verify that the transaction balance is as we expected. +// example calls +const exportTx = avm.newExportTx(...) // constructs a new export tx from X +const addValidatorTx = pvm.newAddPermissionlessValidatorTx(...) // constructs a new add validator tx on P +const importTx = evm.newImportTx(...) // constructs a new import tx to C -*Note: In a real network the balance isn't guaranteed to match this scenario. Transaction fees or additional spends may vary the balance. For the purpose of this example, we assume neither of those cases.* - -```js -const updatedU = await xchain.getUTXOs() -const updatedUTXOs = updatedU.utxos -const newBalance = updatedUTXOs.getBalance(myAddresses, assetID) -if (newBalance.toNumber() != mybalance.sub(sendAmount).toNumber()) { - throw Error("heyyy these should equal!") -} +const publicKeyBytes = utils.hexToBuffer(publicKeyHex) +const signature = utils.signHash(bytes, privateKeyBytes) ``` -### Repo Dependency Updates - -Dependabot will make pull requests against the development branch. If all tests pass, it is safe to merge into development, but for redundancy you want to try to build it locally. - -```zsh -git fetch origin -git checkout -b -git merge development -yarn build && yarn test -``` - -If the E2E check does not pass, go into the 'checks' section of the PR. -`https://github.com/ava-labs/avalanchejs/pull//checks` - -* Click on the `> E2E` tab on the left -* Click 'Re-run jobs' on the right - +Please check out the `examples` folder for more info. diff --git a/__mocks__/axios.ts b/__mocks__/axios.ts deleted file mode 100644 index 50ab9bec4..000000000 --- a/__mocks__/axios.ts +++ /dev/null @@ -1,4 +0,0 @@ -// ./__mocks__/axios.js -import mockAxios from "jest-mock-axios" - -export default mockAxios diff --git a/commitlint.config.cjs b/commitlint.config.cjs new file mode 100644 index 000000000..1003d75be --- /dev/null +++ b/commitlint.config.cjs @@ -0,0 +1,7 @@ +module.exports = { + extends: ['@commitlint/config-conventional'], + rules: { + 'body-max-line-length': [0], + 'footer-max-line-length': [0], + }, +}; diff --git a/documentation/README.md b/documentation/README.md deleted file mode 100644 index 889511be8..000000000 --- a/documentation/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# Documentation - -* [ESLint](./eslint.md) -* [E2E Tests](./e2e_tests.md) diff --git a/documentation/eslint.md b/documentation/eslint.md deleted file mode 100644 index d34f26bae..000000000 --- a/documentation/eslint.md +++ /dev/null @@ -1,64 +0,0 @@ -# AvalancheJS - ESlint Documentation - -## Overview - -`yarn lint` - -to run the linter against the repo. - -### Common warnings - -* [Generic Object Injection Sink](https://github.com/nodesecurity/eslint-plugin-security/blob/master/docs/the-dangers-of-square-bracket-notation.md) -* Function Call Object Injection Sink -* Variable Assigned to Object Injection Sink - -To resolve these warnings, - -```js - example[value] -``` - -you will need to wrap the variable name inside "`" literals; - -```js - example[`${value}`] -``` - -or - -```js - example[value.toString()] -``` - -#### Helpers - -If you are running VSCode, you can use these snippets to automate the repetive tasks. - -* highlight the variable that ESlint warns about -* press shift+` - -To get this to work you'll need to add this code snippet - -``` -{ - "generic object injection": { - "prefix": ["detect", "`"], - "body": ["`${${TM_SELECTED_TEXT}}`"], - "description": "Wrap in `` literals to remove ESling warning" - } -} - -``` - -you then need to append this to `keybindings.json` - -``` - { - "key": "shift+`", - "command": "editor.action.insertSnippet", - "args": { "name": "generic object injection" } - } -``` - -the name `generic object injection` can be changed , but just has to match the keybinding argument. - diff --git a/documentation/generating-typedoc.md b/documentation/generating-typedoc.md deleted file mode 100644 index 8bcdd2663..000000000 --- a/documentation/generating-typedoc.md +++ /dev/null @@ -1,58 +0,0 @@ -# AvalancheJS - Typedoc Documentation - -## Overview - -We use [typedoc](https://typedoc.org) to turn comments in our typescript into markdown pages which can be copied into [the Avalanche Docs repo](https://github.com/ava-labs/avalanche-docs) and [the AvalancheJS Docs repo](https://github.com/ava-labs/avalanchejs-docs). Each time a new version of AvalancheJS gets deployed to [npm](https://www.npmjs.com/package/avalanche) then typedocs should be regenerated and pasted into the both docs repo previously mentioned. - -## Steps - -### Dependencies - -A recent build of one of the typedoc dependencies broke this workflow so for now make sure that the dependencies are the following versions. - -```json -"typedoc": "^0.18.0", -"typedoc-plugin-external-module-name": "^4.0.3", -"typedoc-plugin-markdown": "^2.4.0", -``` - -### Generate Docs - -#### Checkout the Latest and Greatest Release - -```zsh -# if you need to refresh your memory for the latest tag -git tag -l - -# now checkout the tag/release that you want to build docs off of -git checkout v1.13.0 -``` - -Generate typedocs using the `docsmd` yarn/npm script. - -```zsh -yarn docsmd -Rendering [========================================] 100% - -Documentation generated at /path/to/avalanchejs/docsMD - -✨ Done in 8.09s. -``` - -This will generate `README.md` and 3 directories, `classes/`, `interfaces/` and `modules/` in the `docsMD/` directory of your local `avalanchejs/` repo. - -### API - -First, if any new files were generated in `README.md` then rename the newly generated `README.md` to `api.md`. Next open `api.md` and clean up the formatting. - -* Remove the generated headers and replace them w/ API and AvalancheJS w/ a link to the current build -* Nest the list items per their parent category -* Clean up the body copy. Ex: `API-AVM` -> `AVM` and `API-AVM-Credentials` -> `Credentials` - -## Copy to Docs Repo - -Now copy the `api.md` file into the `/path/to/docs/apis/tools/avalanchejs/` directory of your local `avalanche-docs/` repo. - -Next copy 3 directories, `classes/`, `interfaces/` and `modules/` into the `/path/to/avalanchejs-docs/` directory of your local `avalanchejs-docs/` repo. - -Confirm that everything worked by running `yarn start` and viewing the new AvalancheJS docs on `localhost`. If that is successful next run `yarn build` to confirm that docusaurus is able to properly build. Once that is successful, branch off of `master`, commit your changes and push them on your new feature branch to the remote `avalanche-docs` repo and create a PR. \ No newline at end of file diff --git a/documentation/new-build.md b/documentation/new-build.md deleted file mode 100644 index 4074da8d1..000000000 --- a/documentation/new-build.md +++ /dev/null @@ -1,11 +0,0 @@ -# Creating a new AvalancheJS build - -First, all changes to the `master` branch of the AvalancheJS repo should be done solely via github pull requests. This is to ensure that only code which has been peer-reviewed ends up in `master`. Next, you need your username added to the [`avalanche` npm package](https://www.npmjs.com/package/avalanche) and also confirm that you enable 2fa on your npm account. - -After all the desired changes have been peer-reviewed and merged into the `development` branch then create a final PR to merge `development` in to `master`. Name the PR the new AvalancheJS version name. Ex: `v3.0.4`. In the description list a changelog of the changes which are included in the PR. - -When you merge the PR and the latest and greatest are on the `master` branch then run `yarn release:prepare`. This command removes the existing `dist/` and `node_modules/` directories in addition to removing the `yarn.lock` file. Next it installs the dependencies, builds AvalancheJS, bundles the build with webpack and runs the test suite. If all of this is successful then you are ready to push a new build to npm. - -For this we use the [`np` lib](https://www.npmjs.com/package/np) to push a new build to npm. `np` will prompt you to answer if this is a PATCH, MINOR or MAJOR release and it will handle bumping the version in `package.json` for you. You will be prompted for your `OTP` which stands for "one time password." This is your 2fa code which you will get from having enabled 2fa on your npm account. - -After this is successful you can confirm that the version number was bumped for the npm [`avalanche` npm package](https://www.npmjs.com/package/avalanche). Once you confirm that then the final step is to merge `master` in to the `development` branch. This ensures that the newly bumped version gets added to any future dev work which branches off of `development`. \ No newline at end of file diff --git a/documentation/unit_tests.md b/documentation/unit_tests.md deleted file mode 100644 index 81d2e377f..000000000 --- a/documentation/unit_tests.md +++ /dev/null @@ -1,35 +0,0 @@ -# Unit Tests - -## Run All Tests - -```zsh -yarn build && yarn test -``` - -## Run Granular Tests - -You can also be more granular and run individual tests or suites of test. When defining tests you can pass in a string as the first argument to `describe` and `test`. - -```ts -describe("SECP256K1", (): void => { - test("addressFromPublicKey", (): void => { - // tests - }) -}) -``` - -You can run an individual test by searching off of the text which you passed into `describe` and/or `test`. - -```zsh -jest -t "SECP256K1" - -PASS tests/common/secp256k1.test.ts - SECP256K1 - ✓ addressFromPublicKey (4 ms) - -Test Suites: 41 skipped, 1 passed, 1 of 42 total -Tests: 541 skipped, 1 passed, 542 total -Snapshots: 0 total -Time: 11.42 s -Ran all test suites with tests matching "SECP256K1". -``` diff --git a/e2eSequencer.js b/e2eSequencer.js deleted file mode 100644 index f4399f25f..000000000 --- a/e2eSequencer.js +++ /dev/null @@ -1,10 +0,0 @@ -const Sequencer = require("@jest/test-sequencer").default - -class CustomSequencer extends Sequencer { - sort(tests) { - const copyTests = Array.from(tests) - return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)) - } -} - -module.exports = CustomSequencer diff --git a/examples/admin/README.md b/examples/admin/README.md deleted file mode 100644 index 7e16ec937..000000000 --- a/examples/admin/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# Admin RPC - -Example scripts for the Avalanche [Admin RPC](https://docs.avax.network/build/avalanchego-apis/admin-api) - -* [alias.ts](./alias.ts) -* [aliasChain.ts](./aliasChain.ts) -* [getChainAliases.ts](./getChainAliases.ts) -* [getLoggerLevel.ts](./getLoggerLevel.ts) -* [loadVMs.ts](./loadVMs.ts) -* [lockProfile.ts](./lockProfile.ts) -* [memoryProfile.ts](./memoryProfile.ts) -* [startCPUProfiler.ts](./startCPUProfiler.ts) -* [setLoggerLevel.ts](./setLoggerLevel.ts) -* [stopCPUProfiler.ts](./stopCPUProfiler.ts) diff --git a/examples/admin/alias.ts b/examples/admin/alias.ts deleted file mode 100644 index 0942fef6e..000000000 --- a/examples/admin/alias.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AdminAPI } from "avalanche/dist/apis/admin" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const admin: AdminAPI = avalanche.Admin() - -const main = async (): Promise => { - const endpoint: string = "/ext/bc/X" - const alias: string = "xchain" - const successful: boolean = await admin.alias(endpoint, alias) - console.log(successful) -} - -main() diff --git a/examples/admin/aliasChain.ts b/examples/admin/aliasChain.ts deleted file mode 100644 index 96ebd0900..000000000 --- a/examples/admin/aliasChain.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AdminAPI } from "avalanche/dist/apis/admin" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const admin: AdminAPI = avalanche.Admin() - -const main = async (): Promise => { - const blockchain: string = "X" - const alias: string = "xchain" - const successful: boolean = await admin.aliasChain(blockchain, alias) - console.log(successful) -} - -main() diff --git a/examples/admin/getChainAliases.ts b/examples/admin/getChainAliases.ts deleted file mode 100644 index c3d220e0b..000000000 --- a/examples/admin/getChainAliases.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AdminAPI } from "avalanche/dist/apis/admin" -import { Defaults } from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const admin: AdminAPI = avalanche.Admin() - -const main = async (): Promise => { - const blockchain: string = Defaults.network[networkID].X.blockchainID - const aliases: string[] = await admin.getChainAliases(blockchain) - console.log(aliases) -} - -main() diff --git a/examples/admin/getLoggerLevel.ts b/examples/admin/getLoggerLevel.ts deleted file mode 100644 index 075b3f1ef..000000000 --- a/examples/admin/getLoggerLevel.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AdminAPI } from "avalanche/dist/apis/admin" -import { GetLoggerLevelResponse } from "avalanche/dist/apis/admin/interfaces" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const admin: AdminAPI = avalanche.Admin() - -const main = async (): Promise => { - const loggerName: string = "C" - const loggerLevel: GetLoggerLevelResponse = await admin.getLoggerLevel( - loggerName - ) - console.log(loggerLevel) -} - -main() diff --git a/examples/admin/loadVMs.ts b/examples/admin/loadVMs.ts deleted file mode 100644 index 2850faf12..000000000 --- a/examples/admin/loadVMs.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AdminAPI } from "avalanche/dist/apis/admin" -import { LoadVMsResponse } from "avalanche/dist/apis/admin/interfaces" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const admin: AdminAPI = avalanche.Admin() - -const main = async (): Promise => { - const loggerLevel: LoadVMsResponse = await admin.loadVMs() - console.log(loggerLevel) -} - -main() diff --git a/examples/admin/lockProfile.ts b/examples/admin/lockProfile.ts deleted file mode 100644 index 0e36884b4..000000000 --- a/examples/admin/lockProfile.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AdminAPI } from "avalanche/dist/apis/admin" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const admin: AdminAPI = avalanche.Admin() - -const main = async (): Promise => { - const successful: boolean = await admin.lockProfile() - console.log(successful) -} - -main() diff --git a/examples/admin/memoryProfile.ts b/examples/admin/memoryProfile.ts deleted file mode 100644 index 95ce916c8..000000000 --- a/examples/admin/memoryProfile.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AdminAPI } from "avalanche/dist/apis/admin" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const admin: AdminAPI = avalanche.Admin() - -const main = async (): Promise => { - const successful: boolean = await admin.memoryProfile() - console.log(successful) -} - -main() diff --git a/examples/admin/setLoggerLevel.ts b/examples/admin/setLoggerLevel.ts deleted file mode 100644 index e3cf4136c..000000000 --- a/examples/admin/setLoggerLevel.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AdminAPI } from "avalanche/dist/apis/admin" -import { SetLoggerLevelResponse } from "avalanche/dist/apis/admin/interfaces" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const admin: AdminAPI = avalanche.Admin() - -const main = async (): Promise => { - const loggerName: string = "C" - const logLevel: string = "DEBUG" - const displayLevel: string = "INFO" - const loggerLevel: SetLoggerLevelResponse = await admin.setLoggerLevel( - loggerName, - logLevel, - displayLevel - ) - console.log(loggerLevel) -} - -main() diff --git a/examples/admin/startCPUProfiler.ts b/examples/admin/startCPUProfiler.ts deleted file mode 100644 index fa826f21b..000000000 --- a/examples/admin/startCPUProfiler.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AdminAPI } from "avalanche/dist/apis/admin" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const admin: AdminAPI = avalanche.Admin() - -const main = async (): Promise => { - const successful: boolean = await admin.startCPUProfiler() - console.log(successful) -} - -main() diff --git a/examples/admin/stopCPUProfiler.ts b/examples/admin/stopCPUProfiler.ts deleted file mode 100644 index a44a7a6d0..000000000 --- a/examples/admin/stopCPUProfiler.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AdminAPI } from "avalanche/dist/apis/admin" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const admin: AdminAPI = avalanche.Admin() - -const main = async (): Promise => { - const successful: boolean = await admin.stopCPUProfiler() - console.log(successful) -} - -main() diff --git a/examples/auth/README.md b/examples/auth/README.md deleted file mode 100644 index 73f12890f..000000000 --- a/examples/auth/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Auth RPC - -Example scripts for the Avalanche [Auth RPC](https://docs.avax.network/build/avalanchego-apis/auth-api) - -* [changePassword.ts](./changePassword.ts) -* [newToken.ts](./newToken.ts) -* [revokeToken.ts](./revokeToken.ts) diff --git a/examples/auth/changePassword.ts b/examples/auth/changePassword.ts deleted file mode 100644 index 851b03804..000000000 --- a/examples/auth/changePassword.ts +++ /dev/null @@ -1,33 +0,0 @@ -// This file read secrets from a separate file called "secrets.json" -// which you can create based on "secrets.example" which is in the -// root of the `examples/` directory. -// Unlike "secrets.example", "secrets.json" should never be committed to git. -import { Avalanche } from "avalanche/dist" -import { AuthAPI } from "avalanche/dist/apis/auth" -import { readFile } from "fs" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const auth: AuthAPI = avalanche.Auth() - -const main = async (): Promise => { - const path: string = "./examples/secrets.json" - const encoding: "utf8" = "utf8" - const cb = async (err: any, data: any): Promise => { - if (err) throw err - const jsonData: any = JSON.parse(data) - const oldPassword: string = jsonData.oldPassword - const newPassword: string = jsonData.newPassword - const successful: boolean = await auth.changePassword( - oldPassword, - newPassword - ) - console.log(successful) - } - readFile(path, encoding, cb) -} - -main() diff --git a/examples/auth/newToken.ts b/examples/auth/newToken.ts deleted file mode 100644 index 5845afea8..000000000 --- a/examples/auth/newToken.ts +++ /dev/null @@ -1,34 +0,0 @@ -// This file read secrets from a separate file called "secrets.json" -// which you can create based on "secrets.example" which is in the -// root of the `examples/` directory. -// Unlike "secrets.example", "secrets.json" should never be committed to git. -import { readFile } from "fs" -import { Avalanche } from "avalanche/dist" -import { AuthAPI } from "avalanche/dist/apis/auth" -import { ErrorResponseObject } from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const auth: AuthAPI = avalanche.Auth() - -const main = async (): Promise => { - const path: string = "./examples/secrets.json" - const encoding: "utf8" = "utf8" - const cb = async (err: any, data: any): Promise => { - if (err) throw err - const jsonData: any = JSON.parse(data) - const password: string = jsonData.password - const endpoints: string[] = ["*"] - const token: string | ErrorResponseObject = await auth.newToken( - password, - endpoints - ) - console.log(token) - } - readFile(path, encoding, cb) -} - -main() diff --git a/examples/auth/revokeToken.ts b/examples/auth/revokeToken.ts deleted file mode 100644 index 784d6113b..000000000 --- a/examples/auth/revokeToken.ts +++ /dev/null @@ -1,30 +0,0 @@ -// This file read secrets from a separate file called "secrets.json" -// which you can create based on "secrets.example" which is in the -// root of the `examples/` directory. -// Unlike "secrets.example", "secrets.json" should never be committed to git. -import { readFile } from "fs" -import { Avalanche } from "avalanche/dist" -import { AuthAPI } from "avalanche/dist/apis/auth" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const auth: AuthAPI = avalanche.Auth() - -const main = async (): Promise => { - const path: string = "./examples/secrets.json" - const encoding: "utf8" = "utf8" - const cb = async (err: any, data: any): Promise => { - if (err) throw err - const jsonData: any = JSON.parse(data) - const password: string = jsonData.password - const token: string = jsonData.token - const successful: boolean = await auth.revokeToken(password, token) - console.log(successful) - } - readFile(path, encoding, cb) -} - -main() diff --git a/examples/avm/JSONXChainTx.ts b/examples/avm/JSONXChainTx.ts deleted file mode 100644 index 469243d89..000000000 --- a/examples/avm/JSONXChainTx.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { Avalanche, Buffer } from "../../src" -import { AVMAPI, Tx } from "../../src/apis/avm" - -const ip: string = "api.avax.network" -const port: number = 443 -const protocol: string = "https" -const networkID: number = 1 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const txID: string = "2fJer7o3HpPYxqyHXo23G4HoPvfEqcUXYojMULi2mbBEoBFqoM" - const hex = (await xchain.getTx(txID)) as string - const buf: Buffer = new Buffer(hex.slice(2), "hex") - const tx: Tx = new Tx() - tx.fromBuffer(buf) - const jsonStr: string = JSON.stringify(tx) - console.log(jsonStr) - const jsn: Object = JSON.parse(jsonStr) - console.log(jsn) -} - -main() diff --git a/examples/avm/README.md b/examples/avm/README.md deleted file mode 100644 index 83bea03ff..000000000 --- a/examples/avm/README.md +++ /dev/null @@ -1,58 +0,0 @@ -# AVM - -Example scripts for the [Avalanche Virtual Machine](https://docs.avax.network/build/references/avm-transaction-serialization) - -* [addressFromBuffer.ts](./addressFromBuffer.ts) -* [baseEndpoint.ts](./baseEndpoint.ts) -* [baseTx-ant.ts](./baseTx-ant.ts) -* [baseTx-avax-create-multisig.ts](./baseTx-avax-create-multisig.ts) -* [baseTx-avax-send-multisig.ts](./baseTx-avax-send-multisig.ts) -* [baseTx-avax.ts](./baseTx-avax.ts) -* [buildBaseTx-ant.ts](./buildBaseTx-ant.ts) -* [buildBaseTx-avax.ts](./buildBaseTx-avax.ts) -* [buildCreateAssetTx.ts](./buildCreateAssetTx.ts) -* [buildCreateNFTAssetTx.ts](./buildCreateNFTAssetTx.ts) -* [buildCreateNFTMintTx.ts](./buildCreateNFTMintTx.ts) -* [buildExportTx-cchain-ant.ts](./buildExportTx-cchain-ant.ts) -* [buildExportTx-cchain-avax.ts](./buildExportTx-cchain-avax.ts) -* [buildExportTx-pchain.ts](./buildExportTx-pchain.ts) -* [buildImportTx-cchain.ts](./buildImportTx-cchain.ts) -* [buildImportTx-pchain.ts](./buildImportTx-pchain.ts) -* [buildNFTTransferTx.ts](./buildNFTTransferTx.ts) -* [buildSECPMintTx.ts](./buildSECPMintTx.ts) -* [createAddress.ts](./createAddress.ts) -* [createAssetTx-ant.ts](./createAssetTx-ant.ts) -* [createAssetTx-nft.ts](./createAssetTx-nft.ts) -* [createKeypair.ts](./createKeypair.ts) -* [createTXID.ts](./createTXID.ts) -* [exportTx-ant-cchain.ts](./exportTx-ant-cchain.ts) -* [exportTx-avax-cchain.ts](./exportTx-avax-cchain.ts) -* [exportTx-avax-pchain.ts](./exportTx-avax-pchain.ts) -* [genesisData.ts](./genesisData.ts) -* [getAllBalances.ts](./getAllBalances.ts) -* [getAssetDescription.ts](./getAssetDescription.ts) -* [getAVAXAssetID.ts](./getAVAXAssetID.ts) -* [getBalance.ts](./getBalance.ts) -* [getBlockchainAlias.ts](./getBlockchainAlias.ts) -* [getBlockchainID.ts](./getBlockchainID.ts) -* [getCreationTxFee.ts](./getCreationTxFee.ts) -* [getDefaultCreationTxFee.ts](./getDefaultCreationTxFee.ts) -* [getDefaultTxFee.ts](./getDefaultTxFee.ts) -* [getInterfaces.ts](./getInterfaces.ts) -* [getTx.ts](./getTx.ts) -* [getTxFee.ts](./getTxFee.ts) -* [getTxStatus.ts](./getTxStatus.ts) -* [importTx-cchain.ts](./importTx-cchain.ts) -* [importTx-cchain.ts](./importTx-cchain.ts) -* [JSONXChainTx.ts](./JSONXChainTx.ts) -* [keyChain.ts](./keyChain.ts) -* [listAddresses.ts](./listAddresses.ts) -* [newKeyChain.ts](./newKeyChain.ts) -* [operationTx-mint-ant.ts](./operationTx-mint-ant.ts) -* [operationTx-mint-avax.ts](./operationTx-mint-avax.ts) -* [parseAddress.ts](./parseAddress.ts) -* [refreshBlockchainID.ts](./refreshBlockchainID.ts) -* [setAVAXAssetID.ts](./setAVAXAssetID.ts) -* [setBlockchainAlias.ts](./setBlockchainAlias.ts) -* [setCreationTxFee.ts](./setCreationTxFee.ts) -* [setTxFee.ts](./setTxFee.ts) diff --git a/examples/avm/addressFromBuffer.ts b/examples/avm/addressFromBuffer.ts deleted file mode 100644 index 9fb6bc0b3..000000000 --- a/examples/avm/addressFromBuffer.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { Avalanche, Buffer } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" -import { UTXOSet, UTXO } from "avalanche/dist/apis/platformvm" -import { Output } from "avalanche/dist/common" -// Change the networkID to affect the HRP of the bech32 encoded address -// NetworkID - Bech32 Address - ChainPrefix-HRP1AddressChecksum -// 0 - X-custom19rknw8l0grnfunjrzwxlxync6zrlu33yeg5dya -// 1 - X-avax19rknw8l0grnfunjrzwxlxync6zrlu33y2jxhrg -// 2 - X-cascade19rknw8l0grnfunjrzwxlxync6zrlu33ypmtvnh -// 3 - X-denali19rknw8l0grnfunjrzwxlxync6zrlu33yhc357h -// 4 - X-everest19rknw8l0grnfunjrzwxlxync6zrlu33yn44wty -// 5 - X-fuji19rknw8l0grnfunjrzwxlxync6zrlu33yxqzg0h -// 1337 - X-custom19rknw8l0grnfunjrzwxlxync6zrlu33yeg5dya -// 12345 - X-local19rknw8l0grnfunjrzwxlxync6zrlu33ynpm3qq -const networkID: number = 12345 -const avalanche: Avalanche = new Avalanche( - undefined, - undefined, - undefined, - networkID -) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const utxoset: UTXOSet = new UTXOSet() - utxoset.addArray([ - "11Zf8cc55Qy1rVgy3t87MJVCSEu539whRSwpdbrtHS6oh5Hnwv1gz8G3BtLJ73MPspLkD93cygZufT4TPYZCmuxW5cRdPrVMbZAHfb6uyGM1jNGBhBiQAgQ6V1yceYf825g27TT6WU4bTdbniWdECDWdGdi84hdiqSJH2y", - "11Zf8cc55Qy1rVgy3t87MJVCSEu539whRSwpdbrtHS6oh5Hnwv1NjNhqZnievVs2kBD9qTrayBYRs91emGTtmnu2wzqpLstbAPJDdVjf3kjwGWywNCdjV6TPGojVR5vHpJhBVRtHTQXR9VP9MBdHXge8zEBsQJAoZhTbr2" - ]) - const utxos: UTXO[] = utxoset.getAllUTXOs() - - utxos.map((utxo: UTXO): void => { - const output: Output = utxo.getOutput() - const addresses: string[] = output - .getAddresses() - .map((x: Buffer): string => { - const addy: string = xchain.addressFromBuffer(x) - return addy - }) - console.log(addresses) - }) -} - -main() diff --git a/examples/avm/baseEndpoint.ts b/examples/avm/baseEndpoint.ts deleted file mode 100644 index 0dd0934bf..000000000 --- a/examples/avm/baseEndpoint.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const baseEndpoint: string = "rpc" -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -avalanche.setAddress(ip, port, protocol, baseEndpoint) - -const main = async (): Promise => { - const baseEndpoint: string = avalanche.getBaseEndpoint() - console.log(baseEndpoint) -} - -main() diff --git a/examples/avm/baseTx-ant.ts b/examples/avm/baseTx-ant.ts deleted file mode 100644 index 64c02edfd..000000000 --- a/examples/avm/baseTx-ant.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - BaseTx -} from "avalanche/dist/apis/avm" -import { - Defaults, - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const bintools: BinTools = BinTools.getInstance() -const xKeychain: KeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const blockchainID: string = Defaults.network[networkID].X.blockchainID -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const avaxAssetIDBuf: Buffer = bintools.cb58Decode(avaxAssetID) -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = xchain.getDefaultTxFee() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from("AVM manual BaseTx to send AVAX and ANT") -// Uncomment for codecID 00 01 -// const codecID: number = 1 - -const main = async (): Promise => { - const avmUTXOResponse: any = await xchain.getUTXOs(xAddressStrings) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO): void => { - const typeID: number = utxo.getOutput().getTypeID() - if (typeID != 6) { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txID: Buffer = utxo.getTxID() - const outputIDX: Buffer = utxo.getOutputIdx() - const assetID: Buffer = utxo.getAssetID() - - if (assetID.toString("hex") === avaxAssetIDBuf.toString("hex")) { - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - amt.sub(fee), - xAddresses, - locktime, - threshold - ) - // Uncomment for codecID 00 01 - // secpTransferOutput.setCodecID(codecID) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetIDBuf, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - // Uncomment for codecID 00 01 - // secpTransferInput.setCodecID(codecID) - secpTransferInput.addSignatureIdx(0, xAddresses[0]) - const input: TransferableInput = new TransferableInput( - txID, - outputIDX, - avaxAssetIDBuf, - secpTransferInput - ) - inputs.push(input) - } else { - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - amt, - xAddresses, - locktime, - threshold - ) - // Uncomment for codecID 00 01 - // secpTransferOutput.setCodecID(codecID) - const transferableOutput: TransferableOutput = new TransferableOutput( - assetID, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - // Uncomment for codecID 00 01 - // secpTransferInput.setCodecID(codecID) - secpTransferInput.addSignatureIdx(0, xAddresses[0]) - const input: TransferableInput = new TransferableInput( - txID, - outputIDX, - assetID, - secpTransferInput - ) - inputs.push(input) - } - } - }) - - const baseTx: BaseTx = new BaseTx( - networkID, - bintools.cb58Decode(blockchainID), - outputs, - inputs, - memo - ) - // Uncomment for codecID 00 01 - // baseTx.setCodecID(codecID) - const unsignedTx: UnsignedTx = new UnsignedTx(baseTx) - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/baseTx-avax-create-multisig.ts b/examples/avm/baseTx-avax-create-multisig.ts deleted file mode 100644 index ae5dd2670..000000000 --- a/examples/avm/baseTx-avax-create-multisig.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - BaseTx -} from "avalanche/dist/apis/avm" -import { GetBalanceResponse } from "avalanche/dist/apis/avm/interfaces" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const bintools: BinTools = BinTools.getInstance() -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const xBlockchainID: string = Defaults.network[networkID].X.blockchainID -const xBlockchainIDBuf: Buffer = bintools.cb58Decode(xBlockchainID) -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const avaxAssetIDBuf: Buffer = bintools.cb58Decode(avaxAssetID) -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const xKeychain: KeyChain = xchain.keyChain() -let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -// X-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p -xKeychain.importKey(privKey) -privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4" -// X-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj -xKeychain.importKey(privKey) -privKey = "PrivateKey-24b2s6EqkBp9bFG5S3Xxi4bjdxFqeRk56ck7QdQArVbwKkAvxz" -// X-custom1aekly2mwnsz6lswd6u0jqvd9u6yddt5884pyuc -xKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = xchain.getDefaultTxFee() -const threshold: number = 3 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "AVM manual create multisig BaseTx to send AVAX" -) -// Uncomment for codecID 00 01 -// const codecID: number = 1 - -const main = async (): Promise => { - const getBalanceResponse: GetBalanceResponse = await xchain.getBalance( - xAddressStrings[0], - avaxAssetID - ) - const balance: BN = new BN(getBalanceResponse.balance) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - balance.sub(fee), - xAddresses, - locktime, - threshold - ) - // Uncomment for codecID 00 01 - // secpTransferOutput.setCodecID(codecID) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetIDBuf, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const avmUTXOResponse: any = await xchain.getUTXOs(xAddressStrings) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO): void => { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - // Uncomment for codecID 00 01 - // secpTransferInput.setCodecID(codecID) - secpTransferInput.addSignatureIdx(0, xAddresses[0]) - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetIDBuf, - secpTransferInput - ) - inputs.push(input) - }) - - const baseTx: BaseTx = new BaseTx( - networkID, - xBlockchainIDBuf, - outputs, - inputs, - memo - ) - // Uncomment for codecID 00 01 - // baseTx.setCodecID(codecID) - const unsignedTx: UnsignedTx = new UnsignedTx(baseTx) - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} -main() diff --git a/examples/avm/baseTx-avax-send-multisig.ts b/examples/avm/baseTx-avax-send-multisig.ts deleted file mode 100644 index 3c2f4cfd7..000000000 --- a/examples/avm/baseTx-avax-send-multisig.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - BaseTx -} from "avalanche/dist/apis/avm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const bintools: BinTools = BinTools.getInstance() -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const xBlockchainID: string = Defaults.network[networkID].X.blockchainID -const xBlockchainIDBuf: Buffer = bintools.cb58Decode(xBlockchainID) -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const avaxAssetIDBuf: Buffer = bintools.cb58Decode(avaxAssetID) -const avalanche: Avalanche = new Avalanche( - ip, - port, - protocol, - networkID, - xBlockchainID -) -const xchain: AVMAPI = avalanche.XChain() -const xKeychain: KeyChain = xchain.keyChain() -let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -// X-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p -xKeychain.importKey(privKey) -privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4" -// X-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj -xKeychain.importKey(privKey) -privKey = "PrivateKey-24b2s6EqkBp9bFG5S3Xxi4bjdxFqeRk56ck7QdQArVbwKkAvxz" -// X-custom1aekly2mwnsz6lswd6u0jqvd9u6yddt5884pyuc -xKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = xchain.getDefaultTxFee() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "AVM manual spend multisig BaseTx to send AVAX" -) -// Uncomment for codecID 00 01 -// const codecID: number = 1 - -const main = async (): Promise => { - const getBalanceResponse: any = await xchain.getBalance( - xAddressStrings[0], - avaxAssetID - ) - const balance: BN = new BN(getBalanceResponse.balance) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - balance.sub(fee), - [xAddresses[0]], - locktime, - threshold - ) - // Uncomment for codecID 00 01 - // secpTransferOutput.setCodecID(codecID) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetIDBuf, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const avmUTXOResponse: any = await xchain.getUTXOs(xAddressStrings) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO): void => { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - // Uncomment for codecID 00 01 - // secpTransferInput.setCodecID(codecID) - xAddresses.forEach((xAddress: Buffer, index: number): void => { - if (index < 3) { - secpTransferInput.addSignatureIdx(index, xAddress) - } - }) - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetIDBuf, - secpTransferInput - ) - inputs.push(input) - }) - - const baseTx: BaseTx = new BaseTx( - networkID, - xBlockchainIDBuf, - outputs, - inputs, - memo - ) - // Uncomment for codecID 00 01 - // baseTx.setCodecID(codecID) - const unsignedTx: UnsignedTx = new UnsignedTx(baseTx) - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/baseTx-avax.ts b/examples/avm/baseTx-avax.ts deleted file mode 100644 index e459993fd..000000000 --- a/examples/avm/baseTx-avax.ts +++ /dev/null @@ -1,124 +0,0 @@ -import createHash from "create-hash" -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - BaseTx -} from "avalanche/dist/apis/avm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const bintools: BinTools = BinTools.getInstance() -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 - -const xBlockchainID: string = Defaults.network[networkID].X.blockchainID -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const avaxAssetIDBuf: Buffer = bintools.cb58Decode(avaxAssetID) -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const xKeychain: KeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = xchain.getDefaultTxFee() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from("AVM manual BaseTx to send AVAX") -// Uncomment for codecID 00 01 -// const codecID: number = 1 - -const main = async (): Promise => { - const getBalanceResponse: any = await xchain.getBalance( - xAddressStrings[0], - avaxAssetID - ) - const balance: BN = new BN(getBalanceResponse.balance) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - balance.sub(fee), - xAddresses, - locktime, - threshold - ) - // Uncomment for codecID 00 01 - // secpTransferOutput.setCodecID(codecID) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetIDBuf, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const avmUTXOResponse: any = await xchain.getUTXOs(xAddressStrings) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO) => { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - // Uncomment for codecID 00 01 - // secpTransferInput.setCodecID(codecID) - secpTransferInput.addSignatureIdx(0, xAddresses[0]) - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetIDBuf, - secpTransferInput - ) - inputs.push(input) - }) - - const baseTx: BaseTx = new BaseTx( - networkID, - bintools.cb58Decode(xBlockchainID), - outputs, - inputs, - memo - ) - // Uncomment for codecID 00 01 - // baseTx.setCodecID(codecID) - const unsignedTx: UnsignedTx = new UnsignedTx(baseTx) - const tx: Tx = unsignedTx.sign(xKeychain) - const txBuf: Buffer = tx.toBuffer() - - // Start example script for generating the TxID in - // advance of issuing the tx to a full node - - // Create sha256 hash of the tx buffer - const sha256Hash: Buffer = Buffer.from( - createHash("sha256").update(txBuf).digest().buffer - ) - - // cb58 the sha256 hash - const generatedTxID: string = bintools.cb58Encode(sha256Hash) - console.log(`Generated TXID: ${generatedTxID}`) - - // End example script for generating the TxID in - // advance of issuing the tx to a full node - - // get the actual txID from the full node - const actualTxID: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${actualTxID}`) -} - -main() diff --git a/examples/avm/buildBaseTx-ant.ts b/examples/avm/buildBaseTx-ant.ts deleted file mode 100644 index 83e8b9717..000000000 --- a/examples/avm/buildBaseTx-ant.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { GetUTXOsResponse } from "avalanche/dist/apis/avm/interfaces" -import { Avalanche, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - UTXOSet, - UnsignedTx, - Tx -} from "avalanche/dist/apis/avm" -import { UnixNow } from "avalanche/dist/utils" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const xKeychain: KeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const asOf: BN = UnixNow() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "AVM utility method buildBaseTx to send an ANT" -) - -const main = async (): Promise => { - const amount: BN = new BN(5) - const avmUTXOResponse: GetUTXOsResponse = await xchain.getUTXOs( - xAddressStrings - ) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const assetID: string = "KD4byR998qmVivF2zmrhLb6gjwKGSB5xCerV2nYXb4XNXVGEP" - const toAddresses: string[] = [xAddressStrings[0]] - - const unsignedTx: UnsignedTx = await xchain.buildBaseTx( - utxoSet, - amount, - assetID, - toAddresses, - xAddressStrings, - xAddressStrings, - memo, - asOf, - locktime, - threshold - ) - - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/buildBaseTx-avax.ts b/examples/avm/buildBaseTx-avax.ts deleted file mode 100644 index fe4dbd281..000000000 --- a/examples/avm/buildBaseTx-avax.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { Avalanche, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - UTXOSet, - UnsignedTx, - Tx -} from "avalanche/dist/apis/avm" -import { - GetBalanceResponse, - GetUTXOsResponse -} from "avalanche/dist/apis/avm/interfaces" -import { Defaults } from "avalanche/dist/utils" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - UnixNow -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const xBlockchainID: string = Defaults.network[networkID].X.blockchainID -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const avalanche: Avalanche = new Avalanche( - ip, - port, - protocol, - networkID, - xBlockchainID -) -const xchain: AVMAPI = avalanche.XChain() -const xKeychain: KeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const asOf: BN = UnixNow() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from("AVM utility method buildBaseTx to send AVAX") -const fee: BN = xchain.getDefaultTxFee() - -const main = async (): Promise => { - const getBalanceResponse: GetBalanceResponse = await xchain.getBalance( - xAddressStrings[0], - avaxAssetID - ) - const balance: BN = new BN(getBalanceResponse.balance) - const avmUTXOResponse: GetUTXOsResponse = await xchain.getUTXOs( - xAddressStrings - ) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const amount: BN = balance.sub(fee) - - const unsignedTx: UnsignedTx = await xchain.buildBaseTx( - utxoSet, - amount, - avaxAssetID, - xAddressStrings, - xAddressStrings, - xAddressStrings, - memo, - asOf, - locktime, - threshold - ) - - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/buildCreateAssetTx.ts b/examples/avm/buildCreateAssetTx.ts deleted file mode 100644 index 15db25411..000000000 --- a/examples/avm/buildCreateAssetTx.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { Avalanche, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - UTXOSet, - UnsignedTx, - Tx, - InitialStates, - SECPMintOutput, - SECPTransferOutput -} from "avalanche/dist/apis/avm" -import { GetUTXOsResponse } from "avalanche/dist/apis/avm/interfaces" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const xKeychain: KeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const outputs: SECPMintOutput[] = [] -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "AVM utility method buildCreateAssetTx to create an ANT" -) -const name: string = "TestToken" -const symbol: string = "TEST" -const denomination: number = 3 - -const main = async (): Promise => { - const avmUTXOResponse: GetUTXOsResponse = await xchain.getUTXOs( - xAddressStrings - ) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - - const amount: BN = new BN(507) - const vcapSecpOutput = new SECPTransferOutput( - amount, - xAddresses, - locktime, - threshold - ) - const initialStates: InitialStates = new InitialStates() - initialStates.addOutput(vcapSecpOutput) - - const secpMintOutput: SECPMintOutput = new SECPMintOutput( - xAddresses, - locktime, - threshold - ) - outputs.push(secpMintOutput) - - const unsignedTx: UnsignedTx = await xchain.buildCreateAssetTx( - utxoSet, - xAddressStrings, - xAddressStrings, - initialStates, - name, - symbol, - denomination, - outputs, - memo - ) - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/buildCreateNFTAssetTx.ts b/examples/avm/buildCreateNFTAssetTx.ts deleted file mode 100644 index 80959b32b..000000000 --- a/examples/avm/buildCreateNFTAssetTx.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { Avalanche, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain as AVMKeyChain, - UTXOSet, - UnsignedTx, - Tx, - MinterSet -} from "avalanche/dist/apis/avm" -import { GetUTXOsResponse } from "avalanche/dist/apis/avm/interfaces" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - UnixNow -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const xKeychain: AVMKeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const threshold: number = 1 -const locktime: BN = new BN(0) -const asOf: BN = UnixNow() -const memo: Buffer = Buffer.from( - "AVM utility method buildCreateNFTAssetTx to create an NFT" -) -const name: string = "non fungible token" -const symbol: string = "NFT" - -const main = async (): Promise => { - const avmUTXOResponse: GetUTXOsResponse = await xchain.getUTXOs( - xAddressStrings - ) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const minterSets: MinterSet[] = [new MinterSet(threshold, xAddresses)] - const unsignedTx: UnsignedTx = await xchain.buildCreateNFTAssetTx( - utxoSet, - xAddressStrings, - xAddressStrings, - minterSets, - name, - symbol, - memo, - asOf, - locktime - ) - - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/buildCreateNFTMintTx.ts b/examples/avm/buildCreateNFTMintTx.ts deleted file mode 100644 index 808e11d7a..000000000 --- a/examples/avm/buildCreateNFTMintTx.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - UTXOSet, - UnsignedTx, - Tx, - AVMConstants, - UTXO -} from "avalanche/dist/apis/avm" -import { GetUTXOsResponse } from "avalanche/dist/apis/avm/interfaces" -import { OutputOwners } from "avalanche/dist/common" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - UnixNow -} from "avalanche/dist/utils" - -// run ts-node examples/avm/buildCreateNFTMintTx.ts -// before you run this example buildCreateNFTAssetTx.ts - -const getUTXOIDs = ( - utxoSet: UTXOSet, - txid: string, - outputType: number = AVMConstants.SECPXFEROUTPUTID_CODECONE, - assetID = "2fSX8P4vhGNZsD3WELwwTxx4XzCNwicyFiYbp3Q965BMgJ8g9" -): string[] => { - const utxoids: string[] = utxoSet.getUTXOIDs() - let result: string[] = [] - for (let index: number = 0; index < utxoids.length; ++index) { - if ( - utxoids[index].indexOf(txid.slice(0, 10)) != -1 && - utxoSet.getUTXO(utxoids[index]).getOutput().getOutputID() == outputType && - assetID == - bintools.cb58Encode(utxoSet.getUTXO(utxoids[index]).getAssetID()) - ) { - result.push(utxoids[index]) - } - } - return result -} - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const bintools: BinTools = BinTools.getInstance() -const xKeychain: KeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "AVM utility method buildCreateNFTMintTx to mint an ANT" -) -const payload: Buffer = Buffer.from("NFT Payload") -const asOf: BN = UnixNow() - -const main = async (): Promise => { - const avmUTXOResponse: GetUTXOsResponse = await xchain.getUTXOs( - xAddressStrings - ) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const outputOwners: OutputOwners = new OutputOwners( - xAddresses, - locktime, - threshold - ) - const utxos: UTXO[] = utxoSet.getAllUTXOs() - let txid: Buffer = Buffer.from( - "2fSX8P4vhGNZsD3WELwwTxx4XzCNwicyFiYbp3Q965BMgJ8g9" - ) - let assetID: Buffer = Buffer.from( - "2fSX8P4vhGNZsD3WELwwTxx4XzCNwicyFiYbp3Q965BMgJ8g9" - ) - utxos.forEach((utxo: UTXO): void => { - if (utxo.getOutput().getTypeID() === 10) { - txid = utxo.getTxID() - assetID = utxo.getAssetID() - } - }) - const nftMintOutputUTXOIDs: string[] = getUTXOIDs( - utxoSet, - bintools.cb58Encode(txid), - AVMConstants.NFTMINTOUTPUTID, - bintools.cb58Encode(assetID) - ) - const nftMintOutputUTXOID: string = nftMintOutputUTXOIDs[0] - const groupID: number = 0 - - const unsignedTx: UnsignedTx = await xchain.buildCreateNFTMintTx( - utxoSet, - outputOwners, - xAddressStrings, - xAddressStrings, - nftMintOutputUTXOID, - groupID, - payload, - memo, - asOf - ) - - const tx: Tx = unsignedTx.sign(xKeychain) - const id: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${id}`) -} - -main() diff --git a/examples/avm/buildExportTx-PChain.ts b/examples/avm/buildExportTx-PChain.ts deleted file mode 100644 index 9ae104dab..000000000 --- a/examples/avm/buildExportTx-PChain.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { Avalanche, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain as AVMKeyChain, - UTXOSet, - UnsignedTx, - Tx -} from "avalanche/dist/apis/avm" -import { - GetBalanceResponse, - GetUTXOsResponse -} from "avalanche/dist/apis/avm/interfaces" -import { - KeyChain as PlatformVMKeyChain, - PlatformVMAPI -} from "avalanche/dist/apis/platformvm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - UnixNow -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const pchain: PlatformVMAPI = avalanche.PChain() -const xKeychain: AVMKeyChain = xchain.keyChain() -const pKeychain: PlatformVMKeyChain = pchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -pKeychain.importKey(privKey) -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const pChainBlockchainID: string = Defaults.network[networkID].P.blockchainID -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const locktime: BN = new BN(0) -const asOf: BN = UnixNow() -const memo: Buffer = Buffer.from( - "AVM utility method buildExportTx to export AVAX to the P-Chain from the X-Chain" -) -const fee: BN = xchain.getDefaultTxFee() - -const main = async (): Promise => { - const avmUTXOResponse: GetUTXOsResponse = await xchain.getUTXOs( - xAddressStrings - ) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const getBalanceResponse: GetBalanceResponse = await xchain.getBalance( - xAddressStrings[0], - avaxAssetID - ) - const balance: BN = new BN(getBalanceResponse.balance) - const amount: BN = balance.sub(fee) - - const unsignedTx: UnsignedTx = await xchain.buildExportTx( - utxoSet, - amount, - pChainBlockchainID, - pAddressStrings, - xAddressStrings, - xAddressStrings, - memo, - asOf, - locktime - ) - - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/buildExportTx-cchain-ant.ts b/examples/avm/buildExportTx-cchain-ant.ts deleted file mode 100644 index c48b1172d..000000000 --- a/examples/avm/buildExportTx-cchain-ant.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { Avalanche, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain as AVMKeyChain, - UTXOSet, - UnsignedTx, - Tx -} from "avalanche/dist/apis/avm" -import { GetUTXOsResponse } from "avalanche/dist/apis/avm/interfaces" -import { KeyChain as EVMKeyChain, EVMAPI } from "avalanche/dist/apis/evm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - UnixNow -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const cchain: EVMAPI = avalanche.CChain() -const xKeychain: AVMKeyChain = xchain.keyChain() -const cKeychain: EVMKeyChain = cchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -cKeychain.importKey(privKey) -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const cAddressStrings: string[] = cchain.keyChain().getAddressStrings() -const cChainBlockchainID: string = Defaults.network[networkID].C.blockchainID -const locktime: BN = new BN(0) -const asOf: BN = UnixNow() -const memo: Buffer = Buffer.from( - "AVM utility method buildExportTx to export ANT to the C-Chain from the X-Chain" -) - -const main = async (): Promise => { - const avmUTXOResponse: GetUTXOsResponse = await xchain.getUTXOs( - xAddressStrings - ) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const amount: BN = new BN(350) - const threshold: number = 1 - const assetID: string = "Ycg5QzddNwe3ebfFXhoGUDnWgC6GE88QRakRnn9dp3nGwqCwD" - - const unsignedTx: UnsignedTx = await xchain.buildExportTx( - utxoSet, - amount, - cChainBlockchainID, - cAddressStrings, - xAddressStrings, - xAddressStrings, - memo, - asOf, - locktime, - threshold, - assetID - ) - - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/buildExportTx-cchain-avax.ts b/examples/avm/buildExportTx-cchain-avax.ts deleted file mode 100644 index 06bdd269a..000000000 --- a/examples/avm/buildExportTx-cchain-avax.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { Avalanche, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain as AVMKeyChain, - UTXOSet, - UnsignedTx, - Tx -} from "avalanche/dist/apis/avm" -import { - GetBalanceResponse, - GetUTXOsResponse -} from "avalanche/dist/apis/avm/interfaces" -import { KeyChain as EVMKeyChain, EVMAPI } from "avalanche/dist/apis/evm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - UnixNow -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const cchain: EVMAPI = avalanche.CChain() -const xKeychain: AVMKeyChain = xchain.keyChain() -const cKeychain: EVMKeyChain = cchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -cKeychain.importKey(privKey) -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const cAddressStrings: string[] = cchain.keyChain().getAddressStrings() -const cChainBlockchainID: string = Defaults.network[networkID].C.blockchainID -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const locktime: BN = new BN(0) -const asOf: BN = UnixNow() -const memo: Buffer = Buffer.from( - "AVM utility method buildExportTx to export AVAX to the C-Chain from the X-Chain" -) -const fee: BN = xchain.getDefaultTxFee() - -const main = async (): Promise => { - const avmUTXOResponse: GetUTXOsResponse = await xchain.getUTXOs( - xAddressStrings - ) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const getBalanceResponse: GetBalanceResponse = await xchain.getBalance( - xAddressStrings[0], - avaxAssetID - ) - const balance: BN = new BN(getBalanceResponse.balance) - const amount: BN = balance.sub(fee) - - const unsignedTx: UnsignedTx = await xchain.buildExportTx( - utxoSet, - amount, - cChainBlockchainID, - cAddressStrings, - xAddressStrings, - xAddressStrings, - memo, - asOf, - locktime - ) - - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/buildImportTx-PChain.ts b/examples/avm/buildImportTx-PChain.ts deleted file mode 100644 index 060005586..000000000 --- a/examples/avm/buildImportTx-PChain.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { Avalanche, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - UTXOSet, - UnsignedTx, - Tx -} from "avalanche/dist/apis/avm" -import { GetUTXOsResponse } from "avalanche/dist/apis/avm/interfaces" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - UnixNow -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const xKeychain: KeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const pChainBlockchainID: string = Defaults.network[networkID].P.blockchainID -const threshold: number = 1 -const locktime: BN = new BN(0) -const asOf: BN = UnixNow() -const memo: Buffer = Buffer.from( - "AVM utility method buildImportTx to import AVAX to the X-Chain from the P-Chain" -) - -const main = async (): Promise => { - const avmUTXOResponse: GetUTXOsResponse = await xchain.getUTXOs( - xAddressStrings, - pChainBlockchainID - ) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - - const unsignedTx: UnsignedTx = await xchain.buildImportTx( - utxoSet, - xAddressStrings, - pChainBlockchainID, - xAddressStrings, - xAddressStrings, - xAddressStrings, - memo, - asOf, - locktime, - threshold - ) - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/buildImportTx-cchain.ts b/examples/avm/buildImportTx-cchain.ts deleted file mode 100644 index f41b373a6..000000000 --- a/examples/avm/buildImportTx-cchain.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { Avalanche, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - UTXOSet, - UnsignedTx, - Tx -} from "avalanche/dist/apis/avm" -import { GetUTXOsResponse } from "avalanche/dist/apis/avm/interfaces" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - UnixNow -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const xKeychain: KeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const cChainBlockchainID: string = Defaults.network[networkID].C.blockchainID -const threshold: number = 1 -const locktime: BN = new BN(0) -const asOf: BN = UnixNow() -const memo: Buffer = Buffer.from( - "AVM utility method buildImportTx to import AVAX to the X-Chain from the C-Chain" -) - -const main = async (): Promise => { - const avmUTXOResponse: GetUTXOsResponse = await xchain.getUTXOs( - xAddressStrings, - cChainBlockchainID - ) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - - const unsignedTx: UnsignedTx = await xchain.buildImportTx( - utxoSet, - xAddressStrings, - cChainBlockchainID, - xAddressStrings, - xAddressStrings, - xAddressStrings, - memo, - asOf, - locktime, - threshold - ) - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/buildNFTTransferTx.ts b/examples/avm/buildNFTTransferTx.ts deleted file mode 100644 index 407da8e0e..000000000 --- a/examples/avm/buildNFTTransferTx.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - UTXOSet, - UnsignedTx, - Tx, - AVMConstants, - UTXO -} from "avalanche/dist/apis/avm" -import { GetUTXOsResponse } from "avalanche/dist/apis/avm/interfaces" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - UnixNow -} from "avalanche/dist/utils" - -const getUTXOIDs = ( - utxoSet: UTXOSet, - txid: string, - outputType: number = AVMConstants.SECPXFEROUTPUTID_CODECONE, - assetID = "2fombhL7aGPwj3KH4bfrmJwW6PVnMobf9Y2fn9GwxiAAJyFDbe" -): string[] => { - const utxoids: string[] = utxoSet.getUTXOIDs() - let result: string[] = [] - for (let index: number = 0; index < utxoids.length; ++index) { - if ( - utxoids[index].indexOf(txid.slice(0, 10)) != -1 && - utxoSet.getUTXO(utxoids[index]).getOutput().getOutputID() == outputType && - assetID == - bintools.cb58Encode(utxoSet.getUTXO(utxoids[index]).getAssetID()) - ) { - result.push(utxoids[index]) - } - } - return result -} - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const bintools: BinTools = BinTools.getInstance() -const xKeychain: KeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "AVM utility method buildNFTTransferTx to transfer an ANT" -) -const asOf: BN = UnixNow() - -const main = async (): Promise => { - const avmUTXOResponse: GetUTXOsResponse = await xchain.getUTXOs( - xAddressStrings - ) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - let txid: Buffer = Buffer.from("") - let assetID: Buffer = Buffer.from("") - utxos.forEach((utxo: UTXO) => { - if (utxo.getOutput().getTypeID() === 11) { - txid = utxo.getTxID() - assetID = utxo.getAssetID() - } - }) - const nftTransferOutputUTXOIDs: string[] = getUTXOIDs( - utxoSet, - bintools.cb58Encode(txid), - AVMConstants.NFTXFEROUTPUTID, - bintools.cb58Encode(assetID) - ) - const nftTransferOutputUTXOID: string = nftTransferOutputUTXOIDs[0] - - const unsignedTx: UnsignedTx = await xchain.buildNFTTransferTx( - utxoSet, - xAddressStrings, - xAddressStrings, - xAddressStrings, - nftTransferOutputUTXOID, - memo, - asOf, - locktime, - threshold - ) - - const tx: Tx = unsignedTx.sign(xKeychain) - const id: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${id}`) -} - -main() diff --git a/examples/avm/buildSECPMintTx.ts b/examples/avm/buildSECPMintTx.ts deleted file mode 100644 index 3a2ad57b4..000000000 --- a/examples/avm/buildSECPMintTx.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - UTXOSet, - UnsignedTx, - Tx, - SECPMintOutput, - AVMConstants, - SECPTransferOutput, - UTXO -} from "avalanche/dist/apis/avm" -import { GetUTXOsResponse } from "avalanche/dist/apis/avm/interfaces" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - UnixNow -} from "avalanche/dist/utils" - -// assetID is generated from running -// ts-node examples/avm/buildCreateAssetTx.ts -// if you run the avm.getAllBalances method you will see the asset alongside AVAX, and a balance of 507 - -const getUTXOIDs = ( - utxoSet: UTXOSet, - txid: string, - outputType: number = AVMConstants.SECPXFEROUTPUTID_CODECONE, - assetID = "Ycg5QzddNwe3ebfFXhoGUDnWgC6GE88QRakRnn9dp3nGwqCwD" -): string[] => { - const utxoids: string[] = utxoSet.getUTXOIDs() - let result: string[] = [] - for (let index: number = 0; index < utxoids.length; ++index) { - if ( - utxoids[index].indexOf(txid.slice(0, 10)) != -1 && - utxoSet.getUTXO(utxoids[index]).getOutput().getOutputID() == outputType && - assetID == - bintools.cb58Encode(utxoSet.getUTXO(utxoids[index]).getAssetID()) - ) { - result.push(utxoids[index]) - } - } - return result -} - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const bintools: BinTools = BinTools.getInstance() -const xKeychain: KeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "AVM utility method buildSECPMintTx to mint an ANT" -) -const asOf: BN = UnixNow() - -const main = async (): Promise => { - const avmUTXOResponse: GetUTXOsResponse = await xchain.getUTXOs( - xAddressStrings - ) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - let mintUTXOID: string = "" - let mintOwner: SECPMintOutput = new SECPMintOutput() - let secpTransferOutput: SECPTransferOutput = new SECPTransferOutput() - let txid: Buffer = Buffer.from("") - let assetID: Buffer = Buffer.from("") - utxos.forEach((utxo: UTXO) => { - if (utxo.getOutput().getTypeID() === 6) { - txid = utxo.getTxID() - assetID = utxo.getAssetID() - } - }) - const secpMintOutputUTXOIDs: string[] = getUTXOIDs( - utxoSet, - bintools.cb58Encode(txid), - AVMConstants.SECPMINTOUTPUTID, - bintools.cb58Encode(assetID) - ) - mintUTXOID = secpMintOutputUTXOIDs[0] - const utxo: UTXO = utxoSet.getUTXO(secpMintOutputUTXOIDs[0]) - mintOwner = utxo.getOutput() as SECPMintOutput - const amount: BN = new BN(54321) - secpTransferOutput = new SECPTransferOutput( - amount, - xAddresses, - locktime, - threshold - ) - - const unsignedTx: UnsignedTx = await xchain.buildSECPMintTx( - utxoSet, - mintOwner, - secpTransferOutput, - xAddressStrings, - xAddressStrings, - mintUTXOID, - memo, - asOf - ) - - const tx: Tx = unsignedTx.sign(xKeychain) - const id: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${id}`) -} - -main() diff --git a/examples/avm/createAddress.ts b/examples/avm/createAddress.ts deleted file mode 100644 index da5962e77..000000000 --- a/examples/avm/createAddress.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const username: string = "username" - const password: string = "Vz48jjHLTCcAepH95nT4B" - const address: string = await xchain.createAddress(username, password) - console.log(address) -} - -main() diff --git a/examples/avm/createAssetTx-ant.ts b/examples/avm/createAssetTx-ant.ts deleted file mode 100644 index 2fb948dd9..000000000 --- a/examples/avm/createAssetTx-ant.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain as AVMKeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - CreateAssetTx, - SECPMintOutput, - InitialStates -} from "avalanche/dist/apis/avm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const bintools: BinTools = BinTools.getInstance() -const xKeychain: AVMKeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const blockchainID: string = Defaults.network[networkID].X.blockchainID -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const avaxAssetIDBuf: Buffer = bintools.cb58Decode(avaxAssetID) -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = xchain.getDefaultTxFee() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from("AVM manual CreateAssetTx to create an ANT") -const name: string = "TestToken" -const symbol: string = "TEST" -const denomination: number = 3 -// Uncomment for codecID 00 01 -// const codecID: number = 1 - -const main = async (): Promise => { - const getBalanceResponse: any = await xchain.getBalance( - xAddressStrings[0], - avaxAssetID - ) - const balance: BN = new BN(getBalanceResponse.balance) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - balance.sub(fee), - xAddresses, - locktime, - threshold - ) - // Uncomment for codecID 00 01 - // secpTransferOutput.setCodecID(codecID) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetIDBuf, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const avmUTXOResponse: any = await xchain.getUTXOs(xAddressStrings) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO) => { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - // Uncomment for codecID 00 01 - // secpTransferInput.setCodecID(codecID) - secpTransferInput.addSignatureIdx(0, xAddresses[0]) - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetIDBuf, - secpTransferInput - ) - inputs.push(input) - }) - - const amount: BN = new BN(507) - const vcapSecpOutput = new SECPTransferOutput( - amount, - xAddresses, - locktime, - threshold - ) - // Uncomment for codecID 00 01 - // vcapSecpOutput.setCodecID(codecID) - const secpMintOutput: SECPMintOutput = new SECPMintOutput( - xAddresses, - locktime, - threshold - ) - // Uncomment for codecID 00 01 - // secpMintOutput.setCodecID(codecID) - - const initialStates: InitialStates = new InitialStates() - initialStates.addOutput(vcapSecpOutput) - initialStates.addOutput(secpMintOutput) - - const createAssetTx: CreateAssetTx = new CreateAssetTx( - networkID, - bintools.cb58Decode(blockchainID), - outputs, - inputs, - memo, - name, - symbol, - denomination, - initialStates - ) - // Uncomment for codecID 00 01 - // createAssetTx.setCodecID(codecID) - const unsignedTx: UnsignedTx = new UnsignedTx(createAssetTx) - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/createAssetTx-nft.ts b/examples/avm/createAssetTx-nft.ts deleted file mode 100644 index 2047e3785..000000000 --- a/examples/avm/createAssetTx-nft.ts +++ /dev/null @@ -1,137 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - CreateAssetTx, - InitialStates, - AVMConstants, - MinterSet, - NFTMintOutput -} from "avalanche/dist/apis/avm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const bintools: BinTools = BinTools.getInstance() -const xKeychain: KeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const blockchainID: string = Defaults.network[networkID].X.blockchainID -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const avaxAssetIDBuf: Buffer = bintools.cb58Decode(avaxAssetID) -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = xchain.getDefaultTxFee() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from("AVM manual CreateAssetTx to create an NFT") -const name: string = "non fungible token" -const symbol: string = "NFT" -const denomination: number = 0 // NFTs are non-fungible -const groupID: number = 0 -// Uncomment for codecID 00 01 -// const codecID: number = 1 - -const main = async (): Promise => { - const getBalanceResponse: any = await xchain.getBalance( - xAddressStrings[0], - avaxAssetID - ) - const balance: BN = new BN(getBalanceResponse.balance) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - balance.sub(fee), - xAddresses, - locktime, - threshold - ) - // Uncomment for codecID 00 01 - // secpTransferOutput.setCodecID(codecID) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetIDBuf, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const avmUTXOResponse: any = await xchain.getUTXOs(xAddressStrings) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO): void => { - const outputID: number = utxo.getOutput().getTypeID() - const assetID: Buffer = utxo.getAssetID() - if ( - outputID === 7 && - assetID.toString("hex") === avaxAssetIDBuf.toString("hex") - ) { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - // Uncomment for codecID 00 01 - // secpTransferInput.setCodecID(codecID) - secpTransferInput.addSignatureIdx(0, xAddresses[0]) - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetIDBuf, - secpTransferInput - ) - inputs.push(input) - } - }) - - const initialStates: InitialStates = new InitialStates() - const minterSets: MinterSet[] = [new MinterSet(threshold, xAddresses)] - for (let i: number = 0; i <= 5; i++) { - const nftMintOutput: NFTMintOutput = new NFTMintOutput( - groupID, - minterSets[0].getMinters(), - locktime, - minterSets[0].getThreshold() - ) - // Uncomment for codecID 00 01 - // nftMintOutput.setCodecID(codecID) - initialStates.addOutput(nftMintOutput, AVMConstants.NFTFXID) - } - - const createAssetTx: CreateAssetTx = new CreateAssetTx( - networkID, - bintools.cb58Decode(blockchainID), - outputs, - inputs, - memo, - name, - symbol, - denomination, - initialStates - ) - // Uncomment for codecID 00 01 - // createAssetTx.setCodecID(codecID) - const unsignedTx: UnsignedTx = new UnsignedTx(createAssetTx) - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/createKeypair.ts b/examples/avm/createKeypair.ts deleted file mode 100644 index a88692dfa..000000000 --- a/examples/avm/createKeypair.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AVMAPI, KeyChain, KeyPair } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const keychain: KeyChain = xchain.keyChain() - const keypair: KeyPair = keychain.makeKey() - - const response: { - address: string - publicKey: string - privateKey: string - } = { - address: keypair.getAddressString(), - publicKey: keypair.getPublicKeyString(), - privateKey: keypair.getPrivateKeyString() - } - console.log(response) -} - -main() diff --git a/examples/avm/createTXID.ts b/examples/avm/createTXID.ts deleted file mode 100644 index 94975b07e..000000000 --- a/examples/avm/createTXID.ts +++ /dev/null @@ -1,79 +0,0 @@ -import createHash from "create-hash" -import { Avalanche, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain as AVMKeyChain, - UTXOSet, - UnsignedTx, - Tx -} from "avalanche/dist/apis/avm" -import { - KeyChain as PlatformVMKeyChain, - PlatformVMAPI -} from "avalanche/dist/apis/platformvm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - UnixNow, - SerializedType -} from "avalanche/dist/utils" -import { Serialization } from "avalanche/dist/utils" - -const serialization: Serialization = Serialization.getInstance() -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const pchain: PlatformVMAPI = avalanche.PChain() -const xKeychain: AVMKeyChain = xchain.keyChain() -const pKeychain: PlatformVMKeyChain = pchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -pKeychain.importKey(privKey) -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const pChainBlockchainID: string = Defaults.network[networkID].P.blockchainID -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const locktime: BN = new BN(0) -const asOf: BN = UnixNow() -const memo: Buffer = Buffer.from( - "AVM utility method buildExportTx to export AVAX to the P-Chain from the X-Chain" -) -const fee: BN = xchain.getDefaultTxFee() -const cb58: SerializedType = "cb58" - -const main = async (): Promise => { - const avmUTXOResponse: any = await xchain.getUTXOs(xAddressStrings) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const getBalanceResponse: any = await xchain.getBalance( - xAddressStrings[0], - avaxAssetID - ) - const balance: BN = new BN(getBalanceResponse.balance) - const amount: BN = balance.sub(fee) - - const unsignedTx: UnsignedTx = await xchain.buildExportTx( - utxoSet, - amount, - pChainBlockchainID, - pAddressStrings, - xAddressStrings, - xAddressStrings, - memo, - asOf, - locktime - ) - - const tx: Tx = unsignedTx.sign(xKeychain) - const buffer: Buffer = Buffer.from( - createHash("sha256").update(tx.toBuffer()).digest().buffer - ) - const txid: string = serialization.bufferToType(buffer, cb58) - console.log(txid) - // APfkX9NduHkZtghRpQASNZJjLut4ZAkVhkTGeazQerLSRa36t -} - -main() diff --git a/examples/avm/exportTx-ant-cchain.ts b/examples/avm/exportTx-ant-cchain.ts deleted file mode 100644 index 5caac0e50..000000000 --- a/examples/avm/exportTx-ant-cchain.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - ExportTx -} from "avalanche/dist/apis/avm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const bintools: BinTools = BinTools.getInstance() -const xKeychain: KeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const blockchainID: string = Defaults.network[networkID].X.blockchainID -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const cChainBlockchainID: string = Defaults.network[networkID].C.blockchainID -const avaxAssetIDBuf: Buffer = bintools.cb58Decode(avaxAssetID) -const exportedOuts: TransferableOutput[] = [] -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = xchain.getDefaultTxFee() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "Manually Export AVAX and ANT from X-Chain to C-Chain" -) -// Uncomment for codecID 00 01 -// const codecID: number = 1 - -const main = async (): Promise => { - const avmUTXOResponse: any = await xchain.getUTXOs(xAddressStrings) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO) => { - if (utxo.getOutput().getTypeID() != 6) { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - let amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - let assetID: Buffer = utxo.getAssetID() - const outputidx: Buffer = utxo.getOutputIdx() - let secpTransferOutput: SECPTransferOutput = new SECPTransferOutput() - if (avaxAssetIDBuf.toString("hex") === assetID.toString("hex")) { - secpTransferOutput = new SECPTransferOutput( - amt.sub(fee), - xAddresses, - locktime, - threshold - ) - } else { - secpTransferOutput = new SECPTransferOutput( - amt, - xAddresses, - locktime, - threshold - ) - } - // Uncomment for codecID 00 01 - // secpTransferOutput.setCodecID(codecID) - const transferableOutput: TransferableOutput = new TransferableOutput( - assetID, - secpTransferOutput - ) - exportedOuts.push(transferableOutput) - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - // Uncomment for codecID 00 01 - // secpTransferInput.setCodecID(codecID) - secpTransferInput.addSignatureIdx(0, xAddresses[0]) - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - assetID, - secpTransferInput - ) - inputs.push(input) - } - }) - - const exportTx: ExportTx = new ExportTx( - networkID, - bintools.cb58Decode(blockchainID), - outputs, - inputs, - memo, - bintools.cb58Decode(cChainBlockchainID), - exportedOuts - ) - // Uncomment for codecID 00 01 - // exportTx.setCodecID(codecID) - const unsignedTx: UnsignedTx = new UnsignedTx(exportTx) - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/exportTx-avax-cchain.ts b/examples/avm/exportTx-avax-cchain.ts deleted file mode 100644 index 73f34ff0b..000000000 --- a/examples/avm/exportTx-avax-cchain.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - ExportTx -} from "avalanche/dist/apis/avm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const bintools: BinTools = BinTools.getInstance() -const xKeychain: KeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const blockchainID: string = Defaults.network[networkID].X.blockchainID -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const avaxAssetIDBuf: Buffer = bintools.cb58Decode(avaxAssetID) -const cChainBlockchainID: string = Defaults.network[networkID].C.blockchainID -const exportedOuts: TransferableOutput[] = [] -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = xchain.getDefaultTxFee() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from("Manually Export AVAX from X-Chain to C-Chain") -// Uncomment for codecID 00 01 -// const codecID: number = 1 - -const main = async (): Promise => { - const getBalanceResponse: any = await xchain.getBalance( - xAddressStrings[0], - avaxAssetID - ) - const balance: BN = new BN(getBalanceResponse.balance) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - balance.sub(fee), - xAddresses, - locktime, - threshold - ) - // Uncomment for codecID 00 01 - // secpTransferOutput.setCodecID(codecID) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetIDBuf, - secpTransferOutput - ) - exportedOuts.push(transferableOutput) - - const avmUTXOResponse: any = await xchain.getUTXOs(xAddressStrings) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO) => { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - secpTransferInput.addSignatureIdx(0, xAddresses[0]) - // Uncomment for codecID 00 01 - // secpTransferOutput.setCodecID(codecID) - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetIDBuf, - secpTransferInput - ) - inputs.push(input) - }) - - const exportTx: ExportTx = new ExportTx( - networkID, - bintools.cb58Decode(blockchainID), - outputs, - inputs, - memo, - bintools.cb58Decode(cChainBlockchainID), - exportedOuts - ) - // Uncomment for codecID 00 01 - // exportTx.setCodecID(codecID) - const unsignedTx: UnsignedTx = new UnsignedTx(exportTx) - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/exportTx-avax-pchain.ts b/examples/avm/exportTx-avax-pchain.ts deleted file mode 100644 index f0ccb28ea..000000000 --- a/examples/avm/exportTx-avax-pchain.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - ExportTx -} from "avalanche/dist/apis/avm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const bintools: BinTools = BinTools.getInstance() -const xKeychain: KeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const blockchainID: string = Defaults.network[networkID].X.blockchainID -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const avaxAssetIDBuf: Buffer = bintools.cb58Decode(avaxAssetID) -const pChainBlockchainID: string = Defaults.network[networkID].P.blockchainID -const exportedOuts: TransferableOutput[] = [] -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = xchain.getDefaultTxFee() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from("Manually Export AVAX from X-Chain to P-Chain") - -const main = async (): Promise => { - const getBalanceResponse: any = await xchain.getBalance( - xAddressStrings[0], - avaxAssetID - ) - const balance: BN = new BN(getBalanceResponse.balance) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - balance.sub(fee), - xAddresses, - locktime, - threshold - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetIDBuf, - secpTransferOutput - ) - exportedOuts.push(transferableOutput) - - const avmUTXOResponse: any = await xchain.getUTXOs(xAddressStrings) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO) => { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - secpTransferInput.addSignatureIdx(0, xAddresses[0]) - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetIDBuf, - secpTransferInput - ) - inputs.push(input) - }) - - const exportTx: ExportTx = new ExportTx( - networkID, - bintools.cb58Decode(blockchainID), - outputs, - inputs, - memo, - bintools.cb58Decode(pChainBlockchainID), - exportedOuts - ) - const unsignedTx: UnsignedTx = new UnsignedTx(exportTx) - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/exportTx-avax-to-the-pchain-and-create-a-multisig-atomic-utxo.ts b/examples/avm/exportTx-avax-to-the-pchain-and-create-a-multisig-atomic-utxo.ts deleted file mode 100644 index e98a6281a..000000000 --- a/examples/avm/exportTx-avax-to-the-pchain-and-create-a-multisig-atomic-utxo.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - ExportTx -} from "avalanche/dist/apis/avm" -import { - PlatformVMAPI, - KeyChain as PlatformVMKeyChain -} from "avalanche/dist/apis/platformvm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const pchain: PlatformVMAPI = avalanche.PChain() -const bintools: BinTools = BinTools.getInstance() -const xKeychain: KeyChain = xchain.keyChain() -const pKeychain: PlatformVMKeyChain = pchain.keyChain() -let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -// P-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p -xKeychain.importKey(privKey) -pKeychain.importKey(privKey) - -privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4" -// X-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj -xKeychain.importKey(privKey) -pKeychain.importKey(privKey) - -privKey = "PrivateKey-rKsiN3X4NSJcPpWxMSh7WcuY653NGQ7tfADgQwDZ9yyUPPDG9" -// P-custom1jwwk62ktygl0w29rsq2hq55amamhpvx82kfnte -xKeychain.importKey(privKey) -pKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const pAddresses: Buffer[] = pchain.keyChain().getAddresses() -const xChainID: string = Defaults.network[networkID].X.blockchainID -const xChainIDBuf: Buffer = bintools.cb58Decode(xChainID) -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const avaxAssetIDBuf: Buffer = bintools.cb58Decode(avaxAssetID) -const pChainID: string = Defaults.network[networkID].P.blockchainID -const pChainIDBuf: Buffer = bintools.cb58Decode(pChainID) -const exportedOuts: TransferableOutput[] = [] -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = xchain.getDefaultTxFee() -const threshold: number = 2 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "Export AVAX from the X-Chain to the P-Chain and create a multisig atomic utxo" -) - -const main = async (): Promise => { - const getBalanceResponse: any = await xchain.getBalance( - xAddressStrings[0], - avaxAssetID - ) - const balance: BN = new BN(getBalanceResponse.balance) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - balance.sub(fee), - pAddresses, - locktime, - threshold - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetIDBuf, - secpTransferOutput - ) - exportedOuts.push(transferableOutput) - - const avmUTXOResponse: any = await xchain.getUTXOs(xAddressStrings) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO): void => { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amount: BN = amountOutput.getAmount().clone() - const txID: Buffer = utxo.getTxID() - const outputIdx: Buffer = utxo.getOutputIdx() - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amount) - secpTransferInput.addSignatureIdx(0, xAddresses[0]) - - const input: TransferableInput = new TransferableInput( - txID, - outputIdx, - avaxAssetIDBuf, - secpTransferInput - ) - inputs.push(input) - }) - - const exportTx: ExportTx = new ExportTx( - networkID, - xChainIDBuf, - outputs, - inputs, - memo, - pChainIDBuf, - exportedOuts - ) - const unsignedTx: UnsignedTx = new UnsignedTx(exportTx) - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/genesisData.ts b/examples/avm/genesisData.ts deleted file mode 100644 index 6de3a771c..000000000 --- a/examples/avm/genesisData.ts +++ /dev/null @@ -1,86 +0,0 @@ -import Avalanche, { BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - GenesisAsset, - GenesisData, - InitialStates, - KeyChain, - SECPMintOutput, - SECPTransferOutput -} from "avalanche/dist/apis/avm" -import { - DefaultLocalGenesisPrivateKey, - PrivateKeyPrefix, - Serialization, - SerializedType -} from "avalanche/dist/utils" -const serialization: Serialization = Serialization.getInstance() -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const xKeychain: KeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const cb58: SerializedType = "cb58" -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = serialization.typeToBuffer( - "2Zc54v4ek37TEwu4LiV3j41PUMRd6acDDU3ZCVSxE7X", - cb58 -) -let assetAlias: string = "asset1" -let name: string = "asset1" -let symbol: string = "MFCA" -let denomination: number = 1 - -const main = async (): Promise => { - const amount: BN = new BN(1000000000000) - const vcapSecpOutput = new SECPTransferOutput( - amount, - xAddresses, - locktime, - threshold - ) - let initialStates: InitialStates = new InitialStates() - initialStates.addOutput(vcapSecpOutput) - - let genesisAsset: GenesisAsset = new GenesisAsset( - assetAlias, - name, - symbol, - denomination, - initialStates, - memo - ) - const genesisAssets: GenesisAsset[] = [genesisAsset] - assetAlias = "asset2" - name = "asset2" - symbol = "MVCA" - denomination = 2 - initialStates = new InitialStates() - const secpMintOutput: SECPMintOutput = new SECPMintOutput( - xAddresses, - locktime, - threshold - ) - initialStates.addOutput(secpMintOutput) - genesisAsset = new GenesisAsset( - assetAlias, - name, - symbol, - denomination, - initialStates, - memo - ) - genesisAssets.push(genesisAsset) - const genesisData: GenesisData = new GenesisData(genesisAssets, networkID) - const c: string = serialization.bufferToType(genesisData.toBuffer(), cb58) - console.log(c) - // 111113q4vh8kDKrDmvmGm1zGBKURDLcikSCbPQBjEmfnzmW5QkZpQUAXck5gt5XCgehm4HDjgj2yiTS6nekoVUgoLkQ2hQrCwc7Y7uDC99h6ThzwMz3dCLQMmfSXyuCmqwK1fw4mPnKowzxjAjchJ6w1JSxLdhTd2R9tB3qaNTPGE5BRjkZtrMyxVvWR5qxrWPhyEqy5yjxtjG2Jva2NN34tYRePo2GdKpaTwxvxguFNGTW6kUe3pu6uKVEc8Staet1xYeUa4SZnYi5Lv6xnXvc6Sj8ve1ZyRHdHkq1rCMdyKvegUXjsaT7YVYcdAG21y8sxN3FEe7eBAcLmGa8U44bN1tB8ddCWag1tusHkYjiKivWQNyMYJsavbfP5Y8gAw51YmuYy1XbiKwLJCWnj6jNG5PZE4p4anJNy3y4tj2An5ZhH -} - -main() diff --git a/examples/avm/getAVAXAssetID.ts b/examples/avm/getAVAXAssetID.ts deleted file mode 100644 index 43314d7a6..000000000 --- a/examples/avm/getAVAXAssetID.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche, Buffer } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const assetID: Buffer = await xchain.getAVAXAssetID() - console.log(assetID) -} - -main() diff --git a/examples/avm/getAllBalances.ts b/examples/avm/getAllBalances.ts deleted file mode 100644 index 002b72d95..000000000 --- a/examples/avm/getAllBalances.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const address: string = "X-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p" - const balances: object[] = await xchain.getAllBalances(address) - console.log(balances) -} - -main() diff --git a/examples/avm/getAssetDescription.ts b/examples/avm/getAssetDescription.ts deleted file mode 100644 index aa0b751a8..000000000 --- a/examples/avm/getAssetDescription.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const assetDescription: any = await xchain.getAssetDescription("AVAX") - console.log(assetDescription) -} - -main() diff --git a/examples/avm/getBalance.ts b/examples/avm/getBalance.ts deleted file mode 100644 index b53c2e6e3..000000000 --- a/examples/avm/getBalance.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const address: string = "X-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p" - const balance: object = await xchain.getBalance(address, "AVAX") - console.log(balance) -} - -main() diff --git a/examples/avm/getBlockchainAlias.ts b/examples/avm/getBlockchainAlias.ts deleted file mode 100644 index e0e785d6b..000000000 --- a/examples/avm/getBlockchainAlias.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const alias: string = xchain.getBlockchainAlias() - console.log(alias) -} - -main() diff --git a/examples/avm/getBlockchainID.ts b/examples/avm/getBlockchainID.ts deleted file mode 100644 index 402a444cc..000000000 --- a/examples/avm/getBlockchainID.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const blockchainID: string = xchain.getBlockchainID() - console.log(blockchainID) -} - -main() diff --git a/examples/avm/getCreationTxFee.ts b/examples/avm/getCreationTxFee.ts deleted file mode 100644 index 3920789a5..000000000 --- a/examples/avm/getCreationTxFee.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche, BN } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const txFee: BN = xchain.getCreationTxFee() - console.log(txFee) -} - -main() diff --git a/examples/avm/getDefaultCreationTxFee.ts b/examples/avm/getDefaultCreationTxFee.ts deleted file mode 100644 index a01a1353d..000000000 --- a/examples/avm/getDefaultCreationTxFee.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche, BN } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const txFee: BN = xchain.getDefaultCreationTxFee() - console.log(txFee) -} - -main() diff --git a/examples/avm/getDefaultTxFee.ts b/examples/avm/getDefaultTxFee.ts deleted file mode 100644 index cedaf2d14..000000000 --- a/examples/avm/getDefaultTxFee.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche, BN } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const defaultTxFee: BN = xchain.getDefaultTxFee() - console.log(defaultTxFee.toString()) -} - -main() diff --git a/examples/avm/getInterfaces.ts b/examples/avm/getInterfaces.ts deleted file mode 100644 index 28a7f2619..000000000 --- a/examples/avm/getInterfaces.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { SendResponse } from "avalanche/dist/apis/avm" - -const main = async (): Promise => { - const sendResponse: SendResponse = { - txID: "2wYzSintaK3NWk71CGBvzuieFeAzJBLYpwfypGwQMsyotcK8Zs", - changeAddr: "X-avax1vwf7dg22l9c0lnt92kq3urf0h9j3x6296sue77" - } - console.log(sendResponse) -} - -main() diff --git a/examples/avm/getTx.ts b/examples/avm/getTx.ts deleted file mode 100644 index c793c9dc1..000000000 --- a/examples/avm/getTx.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const txID: string = "Ycg5QzddNwe3ebfFXhoGUDnWgC6GE88QRakRnn9dp3nGwqCwD" - const encoding: string = "json" - const tx: string | object = await xchain.getTx(txID, encoding) - console.log(tx) -} - -main() diff --git a/examples/avm/getTxFee.ts b/examples/avm/getTxFee.ts deleted file mode 100644 index aa593102d..000000000 --- a/examples/avm/getTxFee.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche, BN } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const txFee: BN = await xchain.getTxFee() - console.log(txFee) -} - -main() diff --git a/examples/avm/getTxStatus.ts b/examples/avm/getTxStatus.ts deleted file mode 100644 index 05d033371..000000000 --- a/examples/avm/getTxStatus.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const status: string = await xchain.getTxStatus( - "2WdpWdsqE26Qypmf66No8KeBYbNhdk3zSG7a5uNYZ3FLSvCu1D" - ) - console.log(status) -} - -main() diff --git a/examples/avm/importTx-cchain.ts b/examples/avm/importTx-cchain.ts deleted file mode 100644 index 84911ba58..000000000 --- a/examples/avm/importTx-cchain.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - ImportTx -} from "avalanche/dist/apis/avm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const bintools: BinTools = BinTools.getInstance() -const xKeychain: KeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const blockchainID: string = Defaults.network[networkID].X.blockchainID -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const avaxAssetIDBuf: Buffer = bintools.cb58Decode(avaxAssetID) -const cChainBlockchainID: string = Defaults.network[networkID].C.blockchainID -const importedInputs: TransferableInput[] = [] -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = xchain.getDefaultTxFee() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "Manually Import AVAX and ANT to the X-Chain from the C-Chain" -) -// Uncomment for codecID 00 01 -// const codecID: number = 1 - -const main = async (): Promise => { - const avmUTXOResponse: any = await xchain.getUTXOs( - xAddressStrings, - cChainBlockchainID - ) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO) => { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - let assetID: Buffer = utxo.getAssetID() - const outputidx: Buffer = utxo.getOutputIdx() - let secpTransferOutput: SECPTransferOutput = new SECPTransferOutput() - if (avaxAssetIDBuf.toString("hex") === assetID.toString("hex")) { - secpTransferOutput = new SECPTransferOutput( - amt.sub(fee), - xAddresses, - locktime, - threshold - ) - } else { - secpTransferOutput = new SECPTransferOutput( - amt, - xAddresses, - locktime, - threshold - ) - } - // Uncomment for codecID 00 01 - // secpTransferOutput.setCodecID(codecID) - - const transferableOutput: TransferableOutput = new TransferableOutput( - assetID, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - secpTransferInput.addSignatureIdx(0, xAddresses[0]) - // Uncomment for codecID 00 01 - // secpTransferInput.setCodecID(codecID) - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - assetID, - secpTransferInput - ) - importedInputs.push(input) - }) - - const importTx: ImportTx = new ImportTx( - networkID, - bintools.cb58Decode(blockchainID), - outputs, - inputs, - memo, - bintools.cb58Decode(cChainBlockchainID), - importedInputs - ) - // Uncomment for codecID 00 01 - // importTx.setCodecID(codecID) - - const unsignedTx: UnsignedTx = new UnsignedTx(importTx) - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/importTx-pchain.ts b/examples/avm/importTx-pchain.ts deleted file mode 100644 index 3d0cbe7f5..000000000 --- a/examples/avm/importTx-pchain.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - ImportTx -} from "avalanche/dist/apis/avm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const bintools: BinTools = BinTools.getInstance() -const xKeychain: KeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const blockchainID: string = Defaults.network[networkID].X.blockchainID -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const avaxAssetIDBuf: Buffer = bintools.cb58Decode(avaxAssetID) -const cChainBlockchainID: string = Defaults.network[networkID].P.blockchainID -const importedInputs: TransferableInput[] = [] -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = xchain.getDefaultTxFee() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "Manually Import AVAX to the X-Chain from the P-Chain" -) -// Uncomment for codecID 00 01 -// const codecID: number = 1 - -const main = async (): Promise => { - const avmUTXOResponse: any = await xchain.getUTXOs( - xAddressStrings, - cChainBlockchainID - ) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const utxo: UTXO = utxoSet.getAllUTXOs()[0] - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - secpTransferInput.addSignatureIdx(0, xAddresses[0]) - // Uncomment for codecID 00 01 - // secpTransferInput.setCodecID(codecID) - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetIDBuf, - secpTransferInput - ) - importedInputs.push(input) - - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - amt.sub(fee), - xAddresses, - locktime, - threshold - ) - // Uncomment for codecID 00 01 - // secpTransferOutput.setCodecID(codecID) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetIDBuf, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const importTx: ImportTx = new ImportTx( - networkID, - bintools.cb58Decode(blockchainID), - outputs, - inputs, - memo, - bintools.cb58Decode(cChainBlockchainID), - importedInputs - ) - // Uncomment for codecID 00 01 - // importTx.setCodecID(codecID) - - const unsignedTx: UnsignedTx = new UnsignedTx(importTx) - const tx: Tx = unsignedTx.sign(xKeychain) - const id: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${id}`) -} - -main() diff --git a/examples/avm/keyChain.ts b/examples/avm/keyChain.ts deleted file mode 100644 index 3fb5c0b23..000000000 --- a/examples/avm/keyChain.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AVMAPI, KeyChain } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const keyChain: KeyChain = xchain.keyChain() - console.log(keyChain) -} - -main() diff --git a/examples/avm/listAddresses.ts b/examples/avm/listAddresses.ts deleted file mode 100644 index 599afd97b..000000000 --- a/examples/avm/listAddresses.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const username: string = "username" - const password: string = "Vz48jjHLTCcAepH95nT4B" - const addresses: string[] = await xchain.listAddresses(username, password) - console.log(addresses) -} - -main() diff --git a/examples/avm/newKeyChain.ts b/examples/avm/newKeyChain.ts deleted file mode 100644 index 99d87f671..000000000 --- a/examples/avm/newKeyChain.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AVMAPI, KeyChain } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const keyChain: KeyChain = xchain.newKeyChain() - console.log(keyChain) -} - -main() diff --git a/examples/avm/operationTx-mint-ant.ts b/examples/avm/operationTx-mint-ant.ts deleted file mode 100644 index 87e065ad6..000000000 --- a/examples/avm/operationTx-mint-ant.ts +++ /dev/null @@ -1,197 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - AVMConstants, - OperationTx, - SECPMintOperation, - SECPMintOutput, - TransferableOperation, - Tx -} from "avalanche/dist/apis/avm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -// before you run this example buildCreateNFTAssetTx.ts - -const getUTXOIDs = ( - utxoSet: UTXOSet, - txid: string, - outputType: number = AVMConstants.SECPXFEROUTPUTID_CODECONE, - assetID = "2fombhL7aGPwj3KH4bfrmJwW6PVnMobf9Y2fn9GwxiAAJyFDbe" -): string[] => { - const utxoids: string[] = utxoSet.getUTXOIDs() - let result: string[] = [] - for (let index: number = 0; index < utxoids.length; ++index) { - if ( - utxoids[index].indexOf(txid.slice(0, 10)) != -1 && - utxoSet.getUTXO(utxoids[index]).getOutput().getOutputID() == outputType && - assetID == - bintools.cb58Encode(utxoSet.getUTXO(utxoids[index]).getAssetID()) - ) { - result.push(utxoids[index]) - } - } - return result -} - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const bintools: BinTools = BinTools.getInstance() -const xKeychain: KeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const blockchainID: string = Defaults.network[networkID].X.blockchainID -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const avaxAssetIDBuf: Buffer = bintools.cb58Decode(avaxAssetID) -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const operations: TransferableOperation[] = [] -const fee: BN = xchain.getDefaultTxFee() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from("AVM manual OperationTx to mint an ANT") -// Uncomment for codecID 00 01 -// const codecID: number = 1 - -const main = async (): Promise => { - const avmUTXOResponse: any = await xchain.getUTXOs(xAddressStrings) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO): void => { - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - const assetID: Buffer = utxo.getAssetID() - if (utxo.getOutput().getTypeID() != 6) { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - - if (assetID.toString("hex") === avaxAssetIDBuf.toString("hex")) { - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - amt.sub(fee), - xAddresses, - locktime, - threshold - ) - // Uncomment for codecID 00 01 - // secpTransferOutput.setCodecID(codecID) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetIDBuf, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - // Uncomment for codecID 00 01 - // secpTransferInput.setCodecID(codecID) - secpTransferInput.addSignatureIdx(0, xAddresses[0]) - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetIDBuf, - secpTransferInput - ) - inputs.push(input) - } else { - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - amt, - xAddresses, - locktime, - threshold - ) - // Uncomment for codecID 00 01 - // secpTransferOutput.setCodecID(codecID) - const transferableOutput: TransferableOutput = new TransferableOutput( - assetID, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - // Uncomment for codecID 00 01 - // secpTransferInput.setCodecID(codecID) - secpTransferInput.addSignatureIdx(0, xAddresses[0]) - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - assetID, - secpTransferInput - ) - inputs.push(input) - } - } else { - const vcapAmount: BN = new BN(507) - const vcapSecpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - vcapAmount, - xAddresses, - locktime, - threshold - ) - // Uncomment for codecID 00 01 - // vcapSecpTransferOutput.setCodecID(codecID) - const secpMintOutputUTXOIDs: string[] = getUTXOIDs( - utxoSet, - bintools.cb58Encode(txid), - AVMConstants.SECPMINTOUTPUTID, - bintools.cb58Encode(assetID) - ) - const mintOwner: SECPMintOutput = utxo.getOutput() as SECPMintOutput - // Uncomment for codecID 00 01 - // mintOwner.setCodecID(codecID) - const secpMintOperation: SECPMintOperation = new SECPMintOperation( - mintOwner, - vcapSecpTransferOutput - ) - // Uncomment for codecID 00 01 - // secpMintOperation.setCodecID(codecID) - const spenders: Buffer[] = mintOwner.getSpenders(xAddresses) - - spenders.forEach((spender: Buffer) => { - const idx: number = mintOwner.getAddressIdx(spender) - secpMintOperation.addSignatureIdx(idx, spender) - }) - - const transferableOperation: TransferableOperation = - new TransferableOperation( - utxo.getAssetID(), - secpMintOutputUTXOIDs, - secpMintOperation - ) - operations.push(transferableOperation) - } - }) - const operationTx: OperationTx = new OperationTx( - networkID, - bintools.cb58Decode(blockchainID), - outputs, - inputs, - memo, - operations - ) - - // Uncomment for codecID 00 01 - // operationTx.setCodecID(codecID) - const unsignedTx: UnsignedTx = new UnsignedTx(operationTx) - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/operationTx-mint-nft.ts b/examples/avm/operationTx-mint-nft.ts deleted file mode 100644 index d578d0c36..000000000 --- a/examples/avm/operationTx-mint-nft.ts +++ /dev/null @@ -1,205 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - AVMAPI, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - AVMConstants, - OperationTx, - TransferableOperation, - Tx, - KeyChain, - NFTMintOperation, - NFTMintOutput -} from "avalanche/dist/apis/avm" -import { OutputOwners } from "avalanche/dist/common" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -// before you run this example buildCreateNFTAssetTx.ts - -const getUTXOIDs = ( - utxoSet: UTXOSet, - txid: string, - outputType: number = AVMConstants.SECPXFEROUTPUTID_CODECONE, - assetID = "2fombhL7aGPwj3KH4bfrmJwW6PVnMobf9Y2fn9GwxiAAJyFDbe" -): string[] => { - const utxoids: string[] = utxoSet.getUTXOIDs() - let result: string[] = [] - for (let index: number = 0; index < utxoids.length; ++index) { - if ( - utxoids[index].indexOf(txid.slice(0, 10)) != -1 && - utxoSet.getUTXO(utxoids[index]).getOutput().getOutputID() == outputType && - assetID == - bintools.cb58Encode(utxoSet.getUTXO(utxoids[index]).getAssetID()) - ) { - result.push(utxoids[index]) - } - } - return result -} - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const bintools: BinTools = BinTools.getInstance() -const xKeychain: KeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const blockchainID: string = Defaults.network[networkID].X.blockchainID -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const avaxAssetIDBuf: Buffer = bintools.cb58Decode(avaxAssetID) -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const operations: TransferableOperation[] = [] -const fee: BN = xchain.getDefaultTxFee() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from("AVM manual OperationTx to mint an NFT") -const payload: Buffer = Buffer.from("NFT Payload") -const groupID: number = 0 -// Uncomment for codecID 00 01 -// const codecID: number = 1 - -const main = async (): Promise => { - const avmUTXOResponse: any = await xchain.getUTXOs(xAddressStrings) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO): void => { - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - const assetID: Buffer = utxo.getAssetID() - if ( - utxo.getOutput().getTypeID() != 10 && - utxo.getOutput().getTypeID() != 11 - ) { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - - if (assetID.toString("hex") === avaxAssetIDBuf.toString("hex")) { - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - amt.sub(fee), - xAddresses, - locktime, - threshold - ) - // Uncomment for codecID 00 01 - // secpTransferOutput.setCodecID(codecID) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetIDBuf, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - // Uncomment for codecID 00 01 - // secpTransferInput.setCodecID(codecID) - secpTransferInput.addSignatureIdx(0, xAddresses[0]) - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetIDBuf, - secpTransferInput - ) - inputs.push(input) - } else { - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - amt, - xAddresses, - locktime, - threshold - ) - // Uncomment for codecID 00 01 - // secpTransferOutput.setCodecID(codecID) - const transferableOutput: TransferableOutput = new TransferableOutput( - assetID, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - // Uncomment for codecID 00 01 - // secpTransferInput.setCodecID(codecID) - secpTransferInput.addSignatureIdx(0, xAddresses[0]) - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - assetID, - secpTransferInput - ) - inputs.push(input) - } - } else if ( - utxo.getOutput().getTypeID() != 7 && - utxo.getOutput().getTypeID() != 11 - ) { - const outputOwners: OutputOwners = new OutputOwners( - xAddresses, - locktime, - threshold - ) - const nftMintOutputUTXOIDs: string[] = getUTXOIDs( - utxoSet, - bintools.cb58Encode(txid), - AVMConstants.NFTMINTOUTPUTID, - bintools.cb58Encode(assetID) - ) - const mintOwner: NFTMintOutput = utxo.getOutput() as NFTMintOutput - // Uncomment for codecID 00 01 - // mintOwner.setCodecID(codecID) - const nftMintOperation: NFTMintOperation = new NFTMintOperation( - groupID, - payload, - [outputOwners] - ) - // Uncomment for codecID 00 01 - // nftMintOperation.setCodecID(codecID) - const spenders: Buffer[] = mintOwner.getSpenders(xAddresses) - const nftMintOutputUTXOID: string = utxo.getUTXOID() - if (nftMintOutputUTXOID === nftMintOutputUTXOIDs[0]) { - spenders.forEach((spender: Buffer) => { - const idx: number = mintOwner.getAddressIdx(spender) - nftMintOperation.addSignatureIdx(idx, spender) - }) - - const transferableOperation: TransferableOperation = - new TransferableOperation( - utxo.getAssetID(), - [nftMintOutputUTXOID], - nftMintOperation - ) - operations.push(transferableOperation) - } - } - }) - const operationTx: OperationTx = new OperationTx( - networkID, - bintools.cb58Decode(blockchainID), - outputs, - inputs, - memo, - operations - ) - // Uncomment for codecID 00 01 - // operationTx.setCodecID(codecID) - - const unsignedTx: UnsignedTx = new UnsignedTx(operationTx) - const tx: Tx = unsignedTx.sign(xKeychain) - const txid: string = await xchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/avm/parseAddress.ts b/examples/avm/parseAddress.ts deleted file mode 100644 index c12ecef79..000000000 --- a/examples/avm/parseAddress.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Avalanche, Buffer } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const addressString: string = "X-local18jma8ppw3nhx5r4ap8clazz0dps7rv5u00z96u" - const addressBuffer: Buffer = xchain.parseAddress(addressString) - console.log(addressBuffer) -} - -main() diff --git a/examples/avm/refreshBlockchainID.ts b/examples/avm/refreshBlockchainID.ts deleted file mode 100644 index b2f5df3c1..000000000 --- a/examples/avm/refreshBlockchainID.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const success: boolean = xchain.refreshBlockchainID() - console.log(success) -} - -main() diff --git a/examples/avm/setAVAXAssetID.ts b/examples/avm/setAVAXAssetID.ts deleted file mode 100644 index 6f85c4eac..000000000 --- a/examples/avm/setAVAXAssetID.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Avalanche, Buffer } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const newAssetID: string = "11FtAxv" - xchain.setAVAXAssetID(newAssetID) - const assetID: Buffer = await xchain.getAVAXAssetID() - console.log(assetID) -} - -main() diff --git a/examples/avm/setBlockchainAlias.ts b/examples/avm/setBlockchainAlias.ts deleted file mode 100644 index 52e88bda7..000000000 --- a/examples/avm/setBlockchainAlias.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const newAlias: string = "myXChain" - xchain.setBlockchainAlias(newAlias) -} - -main() diff --git a/examples/avm/setCreationTxFee.ts b/examples/avm/setCreationTxFee.ts deleted file mode 100644 index f56c924ec..000000000 --- a/examples/avm/setCreationTxFee.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Avalanche, BN } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const fee: BN = new BN(507) - xchain.setCreationTxFee(fee) - const txFee: BN = xchain.getCreationTxFee() - console.log(txFee) -} - -main() diff --git a/examples/avm/setTxFee.ts b/examples/avm/setTxFee.ts deleted file mode 100644 index add7b2d34..000000000 --- a/examples/avm/setTxFee.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Avalanche, BN } from "avalanche/dist" -import { AVMAPI } from "avalanche/dist/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() - -const main = async (): Promise => { - const fee: BN = new BN(507) - xchain.setTxFee(fee) - const txFee: BN = xchain.getTxFee() - console.log(txFee) -} - -main() diff --git a/examples/bintools/README.md b/examples/bintools/README.md deleted file mode 100644 index 8ca624947..000000000 --- a/examples/bintools/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# BinTools - -Example scripts for the Avalanche [BinTools lib](https://github.com/ava-labs/avalanche-docs/blob/master/build/tools/avalanchejs/classes/utils_bintools.bintools.md) - -* [isCB58.ts](./isCB58.ts) -* [isBase58.ts](./isBase58.ts) -* [isHex.ts](./isHex.ts) diff --git a/examples/bintools/isBase58.ts b/examples/bintools/isBase58.ts deleted file mode 100644 index 2caa38c88..000000000 --- a/examples/bintools/isBase58.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { BinTools } from "avalanche/dist" -const bintools: BinTools = BinTools.getInstance() -const validBase581: string = "isGvtnDqETNmmFw7guSJ7mmWhCqboExrpmC8VsWxckHcH9oXb" -const validBase582: string = - "2PwX8qwMHbwVAm28howu3Ef7Lk4ib2XG7AaY9aK8dTTGNXQkCz" -const invalidBase581: string = - "ddd.tnDqETNmmFw7guSJ7mmWhCqboExrpmC8VsWxckHcHzzzz" -const invalidBase582: string = "" - -const main = async (): Promise => { - console.log(`validBase581 is ${bintools.isBase58(validBase581)}`) - console.log(`validBase582 is ${bintools.isBase58(validBase582)}`) - console.log(`invalidBase581 is ${bintools.isBase58(invalidBase581)}`) - console.log(`invalidBase582 is ${bintools.isBase58(invalidBase582)}`) -} - -main() diff --git a/examples/bintools/isCB58.ts b/examples/bintools/isCB58.ts deleted file mode 100644 index a8ba88ba9..000000000 --- a/examples/bintools/isCB58.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { BinTools } from "avalanche/dist" -const bintools: BinTools = BinTools.getInstance() -const validCB581: string = "isGvtnDqETNmmFw7guSJ7mmWhCqboExrpmC8VsWxckHcH9oXb" -const validCB582: string = "2PwX8qwMHbwVAm28howu3Ef7Lk4ib2XG7AaY9aK8dTTGNXQkCz" -const invalidCB581: string = "ddd.tnDqETNmmFw7guSJ7mmWhCqboExrpmC8VsWxckHcHzzzz" -const invalidCB582: string = "" - -const main = async (): Promise => { - console.log(`validCB581 is ${bintools.isCB58(validCB581)}`) - console.log(`validCB582 is ${bintools.isCB58(validCB582)}`) - console.log(`invalidCB581 is ${bintools.isCB58(invalidCB581)}`) - console.log(`invalidCB582 is ${bintools.isCB58(invalidCB582)}`) -} - -main() diff --git a/examples/bintools/isHex.ts b/examples/bintools/isHex.ts deleted file mode 100644 index 55ccf2693..000000000 --- a/examples/bintools/isHex.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { BinTools } from "avalanche/dist" -const bintools: BinTools = BinTools.getInstance() -const validHex1: string = - "0x95eaac2b7a6ee7ad7e597c2f5349b03e461c36c2e1e50fc98a84d01612940bd5" -const validHex2: string = - "95eaac2b7a6ee7ad7e597c2f5349b03e461c36c2e1e50fc98a84d01612940bd5" -const invalidHex1: string = - "rrrrr.c2b7a6ee7ad7e597c2f5349b03e461c36c2e1e5.fc98a84d016129zzzzz" -const invalidHex2: string = "" - -const main = async (): Promise => { - console.log(`validHex1 is ${bintools.isHex(validHex1)}`) - console.log(`validHex2 is ${bintools.isHex(validHex2)}`) - console.log(`invalidHex1 is ${bintools.isHex(invalidHex1)}`) - console.log(`invalidHex2 is ${bintools.isHex(invalidHex2)}`) -} - -main() diff --git a/examples/c-chain/export.ts b/examples/c-chain/export.ts new file mode 100644 index 000000000..1df339c15 --- /dev/null +++ b/examples/c-chain/export.ts @@ -0,0 +1,44 @@ +import { JsonRpcProvider } from 'ethers'; +import { addTxSignatures } from '../../src/signer'; +import { bech32ToBytes, hexToBuffer } from '../../src/utils'; +import { getContextFromURI } from '../../src/vms/context'; +import { newExportTxFromBaseFee } from '../../src/vms/evm'; +import { evmapi } from '../chain_apis'; + +const C_CHAIN_ADDRESS = process.env.C_CHAIN_ADDRESS; +const X_CHAIN_ADDRESS = process.env.X_CHAIN_ADDRESS; +const PRIVATE_KEY = process.env.PRIVATE_KEY; + +const main = async () => { + if (!C_CHAIN_ADDRESS || !X_CHAIN_ADDRESS || !PRIVATE_KEY) { + throw new Error('Missing environment variable(s).'); + } + + const provider = new JsonRpcProvider( + process.env.AVAX_PUBLIC_URL + '/ext/bc/C/rpc', + ); + + const context = await getContextFromURI(process.env.AVAX_PUBLIC_URL); + const txCount = await provider.getTransactionCount(C_CHAIN_ADDRESS); + const baseFee = await evmapi.getBaseFee(); + const xAddressBytes = bech32ToBytes(X_CHAIN_ADDRESS); + + const tx = newExportTxFromBaseFee( + context, + baseFee / BigInt(1e9), + BigInt(0.1 * 1e9), + context.xBlockchainID, + hexToBuffer(C_CHAIN_ADDRESS), + [xAddressBytes], + BigInt(txCount), + ); + + await addTxSignatures({ + unsignedTx: tx, + privateKeys: [hexToBuffer(PRIVATE_KEY)], + }); + + return evmapi.issueSignedTx(tx.getSignedTx()); +}; + +main().then(console.log); diff --git a/examples/c-chain/import.ts b/examples/c-chain/import.ts new file mode 100644 index 000000000..4df8a1165 --- /dev/null +++ b/examples/c-chain/import.ts @@ -0,0 +1,42 @@ +import { addTxSignatures } from '../../src/signer'; +import { bech32ToBytes, hexToBuffer } from '../../src/utils'; +import { getContextFromURI } from '../../src/vms/context'; +import { newImportTxFromBaseFee } from '../../src/vms/evm'; +import { evmapi } from '../chain_apis'; +import { getChainIdFromContext } from '../utils/getChainIdFromContext'; + +const C_CHAIN_ADDRESS = process.env.C_CHAIN_ADDRESS; +const CORETH_ADDRESS = process.env.CORETH_ADDRESS; +const PRIVATE_KEY = process.env.PRIVATE_KEY; + +const main = async (sourceChain: 'X' | 'P') => { + if (!C_CHAIN_ADDRESS || !CORETH_ADDRESS || !PRIVATE_KEY) { + throw new Error('Missing environment variable(s).'); + } + + const baseFee = await evmapi.getBaseFee(); + const context = await getContextFromURI(process.env.AVAX_PUBLIC_URL); + + const { utxos } = await evmapi.getUTXOs({ + sourceChain, + addresses: [CORETH_ADDRESS], + }); + + const tx = newImportTxFromBaseFee( + context, + hexToBuffer(C_CHAIN_ADDRESS), + [bech32ToBytes(CORETH_ADDRESS)], + utxos, + getChainIdFromContext(sourceChain, context), + baseFee / BigInt(1e9), + ); + + await addTxSignatures({ + unsignedTx: tx, + privateKeys: [hexToBuffer(PRIVATE_KEY)], + }); + + return evmapi.issueSignedTx(tx.getSignedTx()); +}; + +main('X').then(console.log); diff --git a/examples/chain_apis.ts b/examples/chain_apis.ts new file mode 100644 index 000000000..4f559a337 --- /dev/null +++ b/examples/chain_apis.ts @@ -0,0 +1,15 @@ +import fetch from 'node-fetch'; +import { config } from 'dotenv'; + +config(); + +import { AVMApi } from '../src/vms/avm/api'; +import { EVMApi } from '../src/vms/evm/api'; +import { PVMApi } from '../src/vms/pvm/api'; + +// polyfill fetch if it doesnt exist in the global space +global.fetch = global.fetch || fetch; + +export const evmapi = new EVMApi(process.env.AVAX_PUBLIC_URL); +export const avmapi = new AVMApi(process.env.AVAX_PUBLIC_URL); +export const pvmapi = new PVMApi(process.env.AVAX_PUBLIC_URL); diff --git a/examples/evm/JSONCChainTx.ts b/examples/evm/JSONCChainTx.ts deleted file mode 100644 index 4c907010c..000000000 --- a/examples/evm/JSONCChainTx.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { Avalanche, Buffer } from "../../src" -import { EVMAPI, Tx } from "../../src/apis/evm" - -const ip: string = "api.avax.network" -const port: number = 443 -const protocol: string = "https" -const networkID: number = 1 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const cchain: EVMAPI = avalanche.CChain() - -const main = async (): Promise => { - const txID: string = "2jfJtniC8MpnCZTAVo4snyepds33MBGB4Yf1QiPjhCeRYv7gZ5" - const hex: string = await cchain.getAtomicTx(txID) - const buf: Buffer = new Buffer(hex.slice(2), "hex") - const tx: Tx = new Tx() - tx.fromBuffer(buf) - const jsonStr: string = JSON.stringify(tx) - console.log(jsonStr) - const jsn: Object = JSON.parse(jsonStr) - console.log(jsn) -} - -main() diff --git a/examples/evm/README.md b/examples/evm/README.md deleted file mode 100644 index 5822d0c96..000000000 --- a/examples/evm/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# EVM - -Example scripts for the Avalanche [EVM](https://docs.avax.network/build/avalanchego-apis/contract-chain-c-chain-api) - -* [buildExportTx-xchain-ant.ts](./buildExportTx-xchain-ant.ts) -* [buildExportTx-xchain-avax.ts](./buildExportTx-xchain-avax.ts) -* [buildImportTx-xchain.ts](./buildImportTx-xchain.ts) -* [createKeypair.ts](./createKeypair.ts) -* [exportTx-ant-xchain.ts](./exportTx-ant-xchain.ts) -* [exportTx-avax-xchain.ts](./exportTx-avax-xchain.ts) -* [getAssetBalance.ts](./getAssetBalance.ts) -* [getBaseFee.ts](./getBaseFee.ts) -* [getMaxPriorityFeePerGas.ts](./getMaxPriorityFeePerGas.ts) -* [getAtomicTx.ts](./getAtomicTx.ts) -* [getAtomicTxStatus.ts](./getAtomicTxStatus.ts) -* [getInterfaces.ts](./getInterfaces.ts) -* [importTx-xchain.ts](./importTx-xchain.ts) -* [JSONCChainTx.ts](./JSONCChainTx.ts) diff --git a/examples/evm/buildExportTx-pchain.ts b/examples/evm/buildExportTx-pchain.ts deleted file mode 100644 index 51429cf9a..000000000 --- a/examples/evm/buildExportTx-pchain.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { Avalanche, BN } from "avalanche/dist" -import { - PlatformVMAPI, - KeyChain as PlatformKeyChain -} from "avalanche/dist/apis/platformvm" -import { - EVMAPI, - KeyChain as EVMKeyChain, - UnsignedTx, - Tx -} from "avalanche/dist/apis/evm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - costExportTx -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -const cchain: EVMAPI = avalanche.CChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -const pKeychain: PlatformKeyChain = pchain.keyChain() -const cKeychain: EVMKeyChain = cchain.keyChain() -pKeychain.importKey(privKey) -cKeychain.importKey(privKey) -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const cAddressStrings: string[] = cchain.keyChain().getAddressStrings() -const pChainBlockchainIdStr: string = Defaults.network[networkID].P.blockchainID -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const cHexAddress: string = "0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC" -const Web3 = require("web3") -const path: string = "/ext/bc/C/rpc" -const web3: any = new Web3(`${protocol}://${ip}:${port}${path}`) -const threshold: number = 1 - -const main = async (): Promise => { - let balance: BN = await web3.eth.getBalance(cHexAddress) - balance = new BN(balance.toString().substring(0, 17)) - const baseFeeResponse: string = await cchain.getBaseFee() - const baseFee = new BN(parseInt(baseFeeResponse, 16)) - const txcount = await web3.eth.getTransactionCount(cHexAddress) - const nonce: number = txcount - const locktime: BN = new BN(0) - let avaxAmount: BN = new BN(1e7) - let fee: BN = baseFee.div(new BN(1e9)) - fee = fee.add(new BN(1e6)) - - let unsignedTx: UnsignedTx = await cchain.buildExportTx( - avaxAmount, - avaxAssetID, - pChainBlockchainIdStr, - cHexAddress, - cAddressStrings[0], - pAddressStrings, - nonce, - locktime, - threshold, - fee - ) - - const tx: Tx = unsignedTx.sign(cKeychain) - const txid: string = await cchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/evm/buildExportTx-xchain-ant.ts b/examples/evm/buildExportTx-xchain-ant.ts deleted file mode 100644 index 823a817b5..000000000 --- a/examples/evm/buildExportTx-xchain-ant.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { Avalanche, BN } from "avalanche/dist" -import { AVMAPI, KeyChain as AVMKeyChain } from "avalanche/dist/apis/avm" -import { - EVMAPI, - KeyChain as EVMKeyChain, - UnsignedTx, - Tx -} from "avalanche/dist/apis/evm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - costExportTx -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const cchain: EVMAPI = avalanche.CChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -const xKeychain: AVMKeyChain = xchain.keyChain() -const cKeychain: EVMKeyChain = cchain.keyChain() -xKeychain.importKey(privKey) -cKeychain.importKey(privKey) -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const cAddressStrings: string[] = cchain.keyChain().getAddressStrings() -const xChainBlockchainIdStr: string = Defaults.network[networkID].X.blockchainID -const cHexAddress: string = "0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC" -const Web3 = require("web3") -const path: string = "/ext/bc/C/rpc" -const web3 = new Web3(`${protocol}://${ip}:${port}${path}`) -const threshold: number = 1 -const assetID: string = "8eqonZUiJZ655TLQdhFDCqY8oV4SPDMPzqfoVMVsSNE4wSMWu" - -const main = async (): Promise => { - let balance: BN = await web3.eth.getBalance(cHexAddress) - balance = new BN(balance.toString().substring(0, 17)) - const baseFeeResponse: string = await cchain.getBaseFee() - const baseFee = new BN(parseInt(baseFeeResponse, 16)) - const txcount = await web3.eth.getTransactionCount(cHexAddress) - const nonce: number = txcount - const locktime: BN = new BN(0) - let amount: BN = new BN(100) - let fee: BN = baseFee - - let unsignedTx: UnsignedTx = await cchain.buildExportTx( - amount, - assetID, - xChainBlockchainIdStr, - cHexAddress, - cAddressStrings[0], - xAddressStrings, - nonce, - locktime, - threshold, - fee - ) - const exportCost: number = costExportTx(unsignedTx) - fee = baseFee.mul(new BN(exportCost)) - unsignedTx = await cchain.buildExportTx( - amount, - assetID, - xChainBlockchainIdStr, - cHexAddress, - cAddressStrings[0], - xAddressStrings, - nonce, - locktime, - threshold, - fee - ) - - const tx: Tx = unsignedTx.sign(cKeychain) - const txid: string = await cchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/evm/buildExportTx-xchain-avax.ts b/examples/evm/buildExportTx-xchain-avax.ts deleted file mode 100644 index 3b8a617d8..000000000 --- a/examples/evm/buildExportTx-xchain-avax.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { Avalanche, BN } from "avalanche/dist" -import { AVMAPI, KeyChain as AVMKeyChain } from "avalanche/dist/apis/avm" -import { - EVMAPI, - KeyChain as EVMKeyChain, - UnsignedTx, - Tx -} from "avalanche/dist/apis/evm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - costExportTx -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const cchain: EVMAPI = avalanche.CChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -const xKeychain: AVMKeyChain = xchain.keyChain() -const cKeychain: EVMKeyChain = cchain.keyChain() -xKeychain.importKey(privKey) -cKeychain.importKey(privKey) -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const cAddressStrings: string[] = cchain.keyChain().getAddressStrings() -const xChainBlockchainIdStr: string = Defaults.network[networkID].X.blockchainID -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const cHexAddress: string = "0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC" -const Web3 = require("web3") -const path: string = "/ext/bc/C/rpc" -const web3 = new Web3(`${protocol}://${ip}:${port}${path}`) -const threshold: number = 1 - -const main = async (): Promise => { - let balance: BN = await web3.eth.getBalance(cHexAddress) - balance = new BN(balance.toString().substring(0, 17)) - const baseFeeResponse: string = await cchain.getBaseFee() - const baseFee = new BN(parseInt(baseFeeResponse, 16)) - const txcount = await web3.eth.getTransactionCount(cHexAddress) - const nonce: number = txcount - const locktime: BN = new BN(0) - let avaxAmount: BN = new BN(1e7) - let fee: BN = baseFee.div(new BN(1e9)) - fee = fee.add(new BN(1e6)) - - let unsignedTx: UnsignedTx = await cchain.buildExportTx( - avaxAmount, - avaxAssetID, - xChainBlockchainIdStr, - cHexAddress, - cAddressStrings[0], - xAddressStrings, - nonce, - locktime, - threshold, - fee - ) - - const tx: Tx = unsignedTx.sign(cKeychain) - const txid: string = await cchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/evm/buildImportTx-PChain.ts b/examples/evm/buildImportTx-PChain.ts deleted file mode 100644 index 447aba670..000000000 --- a/examples/evm/buildImportTx-PChain.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { Avalanche, BN } from "avalanche/dist" -import { - PlatformVMAPI, - KeyChain as PlatformVMKeyChain -} from "avalanche/dist/apis/platformvm" -import { - EVMAPI, - KeyChain as EVMKeyChain, - UnsignedTx, - Tx, - UTXOSet -} from "avalanche/dist/apis/evm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - costImportTx -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -const cchain: EVMAPI = avalanche.CChain() -const pKeychain: PlatformVMKeyChain = pchain.keyChain() -const cHexAddress: string = "0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC" -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -const cKeychain: EVMKeyChain = cchain.keyChain() -pKeychain.importKey(privKey) -cKeychain.importKey(privKey) -const cAddressStrings: string[] = cchain.keyChain().getAddressStrings() -const pChainBlockchainId: string = Defaults.network[networkID].P.blockchainID - -const main = async (): Promise => { - const baseFeeResponse: string = await cchain.getBaseFee() - const baseFee = new BN(parseInt(baseFeeResponse, 16) / 1e9) - let fee: BN = baseFee - const evmUTXOResponse: any = await cchain.getUTXOs( - cAddressStrings, - pChainBlockchainId - ) - const utxoSet: UTXOSet = evmUTXOResponse.utxos - let unsignedTx: UnsignedTx = await cchain.buildImportTx( - utxoSet, - cHexAddress, - cAddressStrings, - pChainBlockchainId, - cAddressStrings, - fee - ) - const importCost: number = costImportTx(unsignedTx) - fee = baseFee.mul(new BN(importCost)) - - unsignedTx = await cchain.buildImportTx( - utxoSet, - cHexAddress, - cAddressStrings, - pChainBlockchainId, - cAddressStrings, - fee - ) - - const tx: Tx = unsignedTx.sign(cKeychain) - const txid: string = await cchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/evm/buildImportTx-xchain.ts b/examples/evm/buildImportTx-xchain.ts deleted file mode 100644 index 8d0c94c8b..000000000 --- a/examples/evm/buildImportTx-xchain.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { Avalanche, BN } from "avalanche/dist" -import { AVMAPI, KeyChain as AVMKeyChain } from "avalanche/dist/apis/avm" -import { - EVMAPI, - KeyChain as EVMKeyChain, - UnsignedTx, - Tx, - UTXOSet -} from "avalanche/dist/apis/evm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - costImportTx -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const cchain: EVMAPI = avalanche.CChain() -const xKeychain: AVMKeyChain = xchain.keyChain() -const cHexAddress: string = "0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC" -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -const cKeychain: EVMKeyChain = cchain.keyChain() -xKeychain.importKey(privKey) -cKeychain.importKey(privKey) -const cAddressStrings: string[] = cchain.keyChain().getAddressStrings() -const xChainBlockchainId: string = Defaults.network[networkID].X.blockchainID - -const main = async (): Promise => { - const baseFeeResponse: string = await cchain.getBaseFee() - const baseFee = new BN(parseInt(baseFeeResponse, 16) / 1e9) - let fee: BN = baseFee - const evmUTXOResponse: any = await cchain.getUTXOs( - cAddressStrings, - xChainBlockchainId - ) - const utxoSet: UTXOSet = evmUTXOResponse.utxos - let unsignedTx: UnsignedTx = await cchain.buildImportTx( - utxoSet, - cHexAddress, - cAddressStrings, - xChainBlockchainId, - cAddressStrings, - fee - ) - const importCost: number = costImportTx(unsignedTx) - fee = baseFee.mul(new BN(importCost)) - - unsignedTx = await cchain.buildImportTx( - utxoSet, - cHexAddress, - cAddressStrings, - xChainBlockchainId, - cAddressStrings, - fee - ) - - const tx: Tx = unsignedTx.sign(cKeychain) - const txid: string = await cchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/evm/createKeypair.ts b/examples/evm/createKeypair.ts deleted file mode 100644 index edba89905..000000000 --- a/examples/evm/createKeypair.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { EVMAPI, KeyChain, KeyPair } from "avalanche/dist/apis/evm" -import { CreateKeyPairResponse } from "avalanche/dist/apis/evm/interfaces" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const cchain: EVMAPI = avalanche.CChain() - -const main = async (): Promise => { - const keychain: KeyChain = cchain.keyChain() - const keypair: KeyPair = keychain.makeKey() - const address: string = keypair.getAddressString() - const publicKey: string = keypair.getPublicKeyString() - const privateKey: string = keypair.getPrivateKeyString() - const createKeypairResponse: CreateKeyPairResponse = { - address: address, - publicKey: publicKey, - privateKey: privateKey - } - console.log(createKeypairResponse) -} - -main() diff --git a/examples/evm/exportTx-ant-xchain.ts b/examples/evm/exportTx-ant-xchain.ts deleted file mode 100644 index 9a71eb4d3..000000000 --- a/examples/evm/exportTx-ant-xchain.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { AVMAPI, KeyChain as AVMKeyChain } from "avalanche/dist/apis/avm" -import { - EVMAPI, - KeyChain as EVMKeyChain, - UnsignedTx, - Tx, - EVMInput, - ExportTx, - SECPTransferOutput, - TransferableOutput -} from "avalanche/dist/apis/evm" -import { RequestResponseData } from "avalanche/dist/common" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const cchain: EVMAPI = avalanche.CChain() -const bintools: BinTools = BinTools.getInstance() -const xKeychain: AVMKeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -const cKeychain: EVMKeyChain = cchain.keyChain() -xKeychain.importKey(privKey) -cKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const cAddresses: Buffer[] = cchain.keyChain().getAddresses() -const xChainBlockchainIdStr: string = Defaults.network[networkID].X.blockchainID -const xChainBlockchainIdBuf: Buffer = bintools.cb58Decode(xChainBlockchainIdStr) -const cChainBlockchainIdStr: string = Defaults.network[networkID].C.blockchainID -const cChainBlockchainIdBuf: Buffer = bintools.cb58Decode(cChainBlockchainIdStr) -const cHexAddress: string = "0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC" -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const avaxAssetIDBuf: Buffer = bintools.cb58Decode(avaxAssetID) -const evmInputs: EVMInput[] = [] -let exportedOuts: TransferableOutput[] = [] -const Web3 = require("web3") -const path: string = "/ext/bc/C/rpc" -const web3 = new Web3(`${protocol}://${ip}:${port}${path}`) -const threshold: number = 1 - -const main = async (): Promise => { - const antAssetIDStr: string = - "verma4Pa9biWKbjDGNsTXU47cYCyDSNGSU1iBkxucfVSFVXdv" - const antAssetIDBuf: Buffer = bintools.cb58Decode(antAssetIDStr) - const antAssetBalanceResponse: RequestResponseData = await cchain.callMethod( - "eth_getAssetBalance", - [cHexAddress, "latest", antAssetIDStr], - "ext/bc/C/rpc" - ) - const antAssetBalance: number = parseInt( - antAssetBalanceResponse.data.result, - 16 - ) - let avaxBalance: BN = await web3.eth.getBalance(cHexAddress) - avaxBalance = new BN(avaxBalance.toString().substring(0, 17)) - const fee: BN = cchain.getDefaultTxFee() - const txcount = await web3.eth.getTransactionCount(cHexAddress) - const nonce: number = txcount - const locktime: BN = new BN(0) - - let evmInput: EVMInput = new EVMInput( - cHexAddress, - avaxBalance, - avaxAssetID, - nonce - ) - evmInput.addSignatureIdx(0, cAddresses[0]) - evmInputs.push(evmInput) - - evmInput = new EVMInput(cHexAddress, antAssetBalance, antAssetIDStr, nonce) - evmInput.addSignatureIdx(0, cAddresses[0]) - evmInputs.push(evmInput) - - let secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - avaxBalance.sub(fee), - xAddresses, - locktime, - threshold - ) - let transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetIDBuf, - secpTransferOutput - ) - exportedOuts.push(transferableOutput) - - secpTransferOutput = new SECPTransferOutput( - new BN(antAssetBalance), - xAddresses, - locktime, - threshold - ) - transferableOutput = new TransferableOutput(antAssetIDBuf, secpTransferOutput) - exportedOuts.push(transferableOutput) - exportedOuts = exportedOuts.sort(TransferableOutput.comparator()) - - const exportTx: ExportTx = new ExportTx( - networkID, - cChainBlockchainIdBuf, - xChainBlockchainIdBuf, - evmInputs, - exportedOuts - ) - - const unsignedTx: UnsignedTx = new UnsignedTx(exportTx) - const tx: Tx = unsignedTx.sign(cKeychain) - const txid: string = await cchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/evm/exportTx-avax-pchain-create-multisig-atomic-output.ts b/examples/evm/exportTx-avax-pchain-create-multisig-atomic-output.ts deleted file mode 100644 index 1784b4fc2..000000000 --- a/examples/evm/exportTx-avax-pchain-create-multisig-atomic-output.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - PlatformVMAPI, - KeyChain as PlatformVMKeyChain -} from "avalanche/dist/apis/platformvm" -import { - EVMAPI, - KeyChain as EVMKeyChain, - UnsignedTx, - Tx, - EVMInput, - ExportTx, - SECPTransferOutput, - TransferableOutput -} from "avalanche/dist/apis/evm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - ONEAVAX -} from "avalanche/dist/utils" -const Web3 = require("web3") - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -const cchain: EVMAPI = avalanche.CChain() -const bintools: BinTools = BinTools.getInstance() -const pKeychain: PlatformVMKeyChain = pchain.keyChain() -let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -// X-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p - -// let privKey: string = "PrivateKey-2PvNEohp3sNL41g4XcCBym5hpeT1szSTZXxL7VGS28eoGvq3k7" -const cKeychain: EVMKeyChain = cchain.keyChain() -cKeychain.importKey(privKey) - -privKey = "PrivateKey-24gdABgapjnsJfnYkfev6YPyQhTaCU72T9bavtDNTYivBLp2eW" -// P-custom1u6eth2fg33ye63mnyu5jswtj326jaypvhyar45 -pKeychain.importKey(privKey) - -// privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4" -// X-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj - -privKey = "PrivateKey-rKsiN3X4NSJcPpWxMSh7WcuY653NGQ7tfADgQwDZ9yyUPPDG9" -// P-custom1jwwk62ktygl0w29rsq2hq55amamhpvx82kfnte -pKeychain.importKey(privKey) -const pAddresses: Buffer[] = pchain.keyChain().getAddresses() -const cAddresses: Buffer[] = cchain.keyChain().getAddresses() -const pChainId: string = Defaults.network[networkID].P.blockchainID -const pChainIdBuf: Buffer = bintools.cb58Decode(pChainId) -const cChainId: string = Defaults.network[networkID].C.blockchainID -const cChainIdBuf: Buffer = bintools.cb58Decode(cChainId) -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const avaxAssetIDBuf: Buffer = bintools.cb58Decode(avaxAssetID) -const cHexAddress: string = "0xeA6B543A9E625C04745EcA3D7a74D74B733b8C15" -const evmInputs: EVMInput[] = [] -const exportedOuts: TransferableOutput[] = [] -const path: string = "/ext/bc/C/rpc" -const web3 = new Web3(`${protocol}://${ip}:${port}${path}`) -const threshold: number = 2 - -const main = async (): Promise => { - let balance: BN = await web3.eth.getBalance(cHexAddress) - balance = new BN(balance.toString().substring(0, 17)) - const fee: BN = cchain.getDefaultTxFee() - const txcount = await web3.eth.getTransactionCount(cHexAddress) - const nonce: number = txcount - const locktime: BN = new BN(0) - - const evmInput: EVMInput = new EVMInput( - cHexAddress, - ONEAVAX, - avaxAssetID, - nonce - ) - evmInput.addSignatureIdx(0, cAddresses[0]) - evmInputs.push(evmInput) - - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - ONEAVAX.sub(fee.mul(new BN(2))), - pAddresses, - locktime, - threshold - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetIDBuf, - secpTransferOutput - ) - exportedOuts.push(transferableOutput) - - const exportTx: ExportTx = new ExportTx( - networkID, - cChainIdBuf, - pChainIdBuf, - evmInputs, - exportedOuts - ) - - const unsignedTx: UnsignedTx = new UnsignedTx(exportTx) - const tx: Tx = unsignedTx.sign(cKeychain) - const txid: string = await cchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/evm/exportTx-avax-xchain.ts b/examples/evm/exportTx-avax-xchain.ts deleted file mode 100644 index 13efc54ea..000000000 --- a/examples/evm/exportTx-avax-xchain.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { AVMAPI, KeyChain as AVMKeyChain } from "avalanche/dist/apis/avm" -import { - EVMAPI, - KeyChain as EVMKeyChain, - UnsignedTx, - Tx, - EVMInput, - ExportTx, - SECPTransferOutput, - TransferableOutput -} from "avalanche/dist/apis/evm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const cchain: EVMAPI = avalanche.CChain() -const bintools: BinTools = BinTools.getInstance() -const xKeychain: AVMKeyChain = xchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -const cKeychain: EVMKeyChain = cchain.keyChain() -xKeychain.importKey(privKey) -cKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const cAddresses: Buffer[] = cchain.keyChain().getAddresses() -const xChainBlockchainIdStr: string = Defaults.network[networkID].X.blockchainID -const xChainBlockchainIdBuf: Buffer = bintools.cb58Decode(xChainBlockchainIdStr) -const cChainBlockchainIdStr: string = Defaults.network[networkID].C.blockchainID -const cChainBlockchainIdBuf: Buffer = bintools.cb58Decode(cChainBlockchainIdStr) -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const avaxAssetIDBuf: Buffer = bintools.cb58Decode(avaxAssetID) -const cHexAddress: string = "0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC" -const evmInputs: EVMInput[] = [] -const exportedOuts: TransferableOutput[] = [] -const Web3 = require("web3") -const path: string = "/ext/bc/C/rpc" -const web3 = new Web3(`${protocol}://${ip}:${port}${path}`) -const threshold: number = 1 - -const main = async (): Promise => { - let balance: BN = await web3.eth.getBalance(cHexAddress) - balance = new BN(balance.toString().substring(0, 17)) - const fee: BN = cchain.getDefaultTxFee() - const txcount = await web3.eth.getTransactionCount(cHexAddress) - const nonce: number = txcount - const locktime: BN = new BN(0) - - const evmInput: EVMInput = new EVMInput( - cHexAddress, - balance, - avaxAssetID, - nonce - ) - evmInput.addSignatureIdx(0, cAddresses[0]) - evmInputs.push(evmInput) - - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - balance.sub(fee), - xAddresses, - locktime, - threshold - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetIDBuf, - secpTransferOutput - ) - exportedOuts.push(transferableOutput) - - const exportTx: ExportTx = new ExportTx( - networkID, - cChainBlockchainIdBuf, - xChainBlockchainIdBuf, - evmInputs, - exportedOuts - ) - - const unsignedTx: UnsignedTx = new UnsignedTx(exportTx) - const tx: Tx = unsignedTx.sign(cKeychain) - const txid: string = await cchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/evm/getAssetBalance.ts b/examples/evm/getAssetBalance.ts deleted file mode 100644 index 15fe8543d..000000000 --- a/examples/evm/getAssetBalance.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { EVMAPI } from "avalanche/dist/apis/evm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const cchain: EVMAPI = avalanche.CChain() - -const main = async (): Promise => { - const address: string = "0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC" - const blockHeight: string = "latest" - const assetID: string = "8eqonZUiJZ655TLQdhFDCqY8oV4SPDMPzqfoVMVsSNE4wSMWu" - const balance: object = await cchain.getAssetBalance( - address, - blockHeight, - assetID - ) - console.log(balance) -} - -main() diff --git a/examples/evm/getAtomicTx.ts b/examples/evm/getAtomicTx.ts deleted file mode 100644 index 33c1f37aa..000000000 --- a/examples/evm/getAtomicTx.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { EVMAPI } from "avalanche/dist/apis/evm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const cchain: EVMAPI = avalanche.CChain() - -const main = async (): Promise => { - const txID: string = "2GD5SRYJQr2kw5jE73trBFiAgVQyrCaeg223TaTyJFYXf2kPty" - const status: string = await cchain.getAtomicTx(txID) - console.log(status) -} - -main() diff --git a/examples/evm/getAtomicTxStatus.ts b/examples/evm/getAtomicTxStatus.ts deleted file mode 100644 index 9b9ec3647..000000000 --- a/examples/evm/getAtomicTxStatus.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { EVMAPI } from "avalanche/dist/apis/evm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const cchain: EVMAPI = avalanche.CChain() - -const main = async (): Promise => { - const txID: string = "FCry2Z1Su9KZqK1XRMhxQS6XuPorxDm3C3RBT7hw32ojiqyvP" - const status: string = await cchain.getAtomicTxStatus(txID) - console.log(status) -} - -main() diff --git a/examples/evm/getBaseFee.ts b/examples/evm/getBaseFee.ts deleted file mode 100644 index 314524fa4..000000000 --- a/examples/evm/getBaseFee.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Avalanche, BN } from "avalanche/dist" -import { EVMAPI } from "avalanche/dist/apis/evm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const cchain: EVMAPI = avalanche.CChain() - -const main = async (): Promise => { - const baseFeeResponse: string = await cchain.getBaseFee() - const baseFee: BN = new BN(parseInt(baseFeeResponse)) - console.log(`BaseFee: ${baseFee.toString()}`) -} - -main() diff --git a/examples/evm/getInterfaces.ts b/examples/evm/getInterfaces.ts deleted file mode 100644 index cd766dc3e..000000000 --- a/examples/evm/getInterfaces.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { GetAtomicTxParams } from "avalanche/dist/apis/evm" - -const main = async (): Promise => { - const getAtomicTxParams: GetAtomicTxParams = { - txID: "2wYzSintaK3NWk71CGBvzuieFeAzJBLYpwfypGwQMsyotcK8Zs" - } - console.log(getAtomicTxParams) -} - -main() diff --git a/examples/evm/getMaxPriorityFeePerGas.ts b/examples/evm/getMaxPriorityFeePerGas.ts deleted file mode 100644 index fe2582355..000000000 --- a/examples/evm/getMaxPriorityFeePerGas.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche, BN } from "avalanche/dist" -import { EVMAPI } from "avalanche/dist/apis/evm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const cchain: EVMAPI = avalanche.CChain() - -const main = async (): Promise => { - const maxPriorityFeePerGas: string = await cchain.getMaxPriorityFeePerGas() - console.log(maxPriorityFeePerGas) -} - -main() diff --git a/examples/evm/importTx-avax-to-the-pchain-and-consume-a-multisig-output.ts b/examples/evm/importTx-avax-to-the-pchain-and-consume-a-multisig-output.ts deleted file mode 100644 index b5cc457e2..000000000 --- a/examples/evm/importTx-avax-to-the-pchain-and-consume-a-multisig-output.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - EVMAPI, - EVMOutput, - ImportTx, - TransferableInput, - KeyChain, - UTXO, - UTXOSet, - SECPTransferInput, - AmountOutput, - UnsignedTx, - Tx -} from "avalanche/dist/apis/evm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const cchain: EVMAPI = avalanche.CChain() -const bintools: BinTools = BinTools.getInstance() -const cKeychain: KeyChain = cchain.keyChain() -const cHexAddress: string = "0xeA6B543A9E625C04745EcA3D7a74D74B733b8C15" -let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -// X-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p -cKeychain.importKey(privKey) - -// let privKey: string = "PrivateKey-24gdABgapjnsJfnYkfev6YPyQhTaCU72T9bavtDNTYivBLp2eW" -// P-custom1u6eth2fg33ye63mnyu5jswtj326jaypvhyar45 - -// privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4" -// X-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj - -privKey = "PrivateKey-rKsiN3X4NSJcPpWxMSh7WcuY653NGQ7tfADgQwDZ9yyUPPDG9" -// P-custom1jwwk62ktygl0w29rsq2hq55amamhpvx82kfnte -cKeychain.importKey(privKey) -const cAddresses: Buffer[] = cchain.keyChain().getAddresses() -const cAddressStrings: string[] = cchain.keyChain().getAddressStrings() -const cChainId: string = Defaults.network[networkID].C.blockchainID -const cChainIdBuf: Buffer = bintools.cb58Decode(cChainId) -const pChainId: string = Defaults.network[networkID].P.blockchainID -const pChainIdBuf: Buffer = bintools.cb58Decode(pChainId) -const importedIns: TransferableInput[] = [] -const evmOutputs: EVMOutput[] = [] -const fee: BN = cchain.getDefaultTxFee() - -const main = async (): Promise => { - const u: any = await cchain.getUTXOs(cAddressStrings, "P") - const utxoSet: UTXOSet = u.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO): void => { - const assetID: Buffer = utxo.getAssetID() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - const output: AmountOutput = utxo.getOutput() as AmountOutput - const amount: BN = output.getAmount() - const input: SECPTransferInput = new SECPTransferInput(amount) - input.addSignatureIdx(0, cAddresses[1]) - input.addSignatureIdx(1, cAddresses[0]) - const xferin: TransferableInput = new TransferableInput( - txid, - outputidx, - assetID, - input - ) - importedIns.push(xferin) - - const evmOutput: EVMOutput = new EVMOutput( - cHexAddress, - amount.sub(fee.mul(new BN(3))), - assetID - ) - evmOutputs.push(evmOutput) - }) - - const importTx: ImportTx = new ImportTx( - networkID, - cChainIdBuf, - pChainIdBuf, - importedIns, - evmOutputs - ) - - const unsignedTx: UnsignedTx = new UnsignedTx(importTx) - const tx: Tx = unsignedTx.sign(cKeychain) - const txid: string = await cchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/evm/importTx-xchain.ts b/examples/evm/importTx-xchain.ts deleted file mode 100644 index 0cd1feebb..000000000 --- a/examples/evm/importTx-xchain.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - EVMAPI, - EVMOutput, - ImportTx, - TransferableInput, - KeyChain, - UTXO, - UTXOSet, - SECPTransferInput, - AmountOutput, - UnsignedTx, - Tx -} from "avalanche/dist/apis/evm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const cchain: EVMAPI = avalanche.CChain() -const bintools: BinTools = BinTools.getInstance() -const cKeychain: KeyChain = cchain.keyChain() -const cHexAddress: string = "0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC" -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -cKeychain.importKey(privKey) -const cAddresses: Buffer[] = cchain.keyChain().getAddresses() -const cAddressStrings: string[] = cchain.keyChain().getAddressStrings() -const cChainBlockchainIdStr: string = Defaults.network[networkID].C.blockchainID -const cChainBlockchainIdBuf: Buffer = bintools.cb58Decode(cChainBlockchainIdStr) -const xChainBlockchainIdStr: string = Defaults.network[networkID].X.blockchainID -const xChainBlockchainIdBuf: Buffer = bintools.cb58Decode(xChainBlockchainIdStr) -const importedIns: TransferableInput[] = [] -const evmOutputs: EVMOutput[] = [] -const fee: BN = cchain.getDefaultTxFee() - -const main = async (): Promise => { - const u: any = await cchain.getUTXOs(cAddressStrings[0], "X") - const utxoSet: UTXOSet = u.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO) => { - const assetID: Buffer = utxo.getAssetID() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - const output: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = output.getAmount().clone() - const input: SECPTransferInput = new SECPTransferInput(amt) - input.addSignatureIdx(0, cAddresses[0]) - const xferin: TransferableInput = new TransferableInput( - txid, - outputidx, - assetID, - input - ) - importedIns.push(xferin) - - const evmOutput: EVMOutput = new EVMOutput( - cHexAddress, - amt.sub(fee), - assetID - ) - evmOutputs.push(evmOutput) - }) - - const importTx: ImportTx = new ImportTx( - networkID, - cChainBlockchainIdBuf, - xChainBlockchainIdBuf, - importedIns, - evmOutputs - ) - - const unsignedTx: UnsignedTx = new UnsignedTx(importTx) - const tx: Tx = unsignedTx.sign(cKeychain) - const txid: string = await cchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/hdnode/README.md b/examples/hdnode/README.md deleted file mode 100644 index 1ec0ce4ca..000000000 --- a/examples/hdnode/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# HDNode - -Scripts for creating BIP32 hierarchical deterministic keys. - -* [derive.ts](./derive.ts) -* [fromMasterSeedBuffer.ts](./fromMasterSeedBuffer.ts) -* [fromMasterSeedString.ts](./fromMasterSeedString.ts) -* [fromXPriv.ts](./fromXPriv.ts) -* [fromXPub.ts](./fromXPub.ts) -* [sign.ts](./sign.ts) -* [verify.ts](./verify.ts) -* [wipePrivateData.ts](./wipePrivateData.ts) \ No newline at end of file diff --git a/examples/hdnode/derive.ts b/examples/hdnode/derive.ts deleted file mode 100644 index d0e21de8c..000000000 --- a/examples/hdnode/derive.ts +++ /dev/null @@ -1,11 +0,0 @@ -import HDNode from "avalanche/dist/utils/hdnode" - -const main = async (): Promise => { - const seed: string = - "a0c42a9c3ac6abf2ba6a9946ae83af18f51bf1c9fa7dacc4c92513cc4dd015834341c775dcd4c0fac73547c5662d81a9e9361a0aac604a73a321bd9103bce8af" - const fromSeed: HDNode = new HDNode(seed) - const child = fromSeed.derive("m/9000'/2614666'/4849181'/4660'/2'/1/3") - console.log(child) -} - -main() diff --git a/examples/hdnode/fromMasterSeedBuffer.ts b/examples/hdnode/fromMasterSeedBuffer.ts deleted file mode 100644 index 963054ca5..000000000 --- a/examples/hdnode/fromMasterSeedBuffer.ts +++ /dev/null @@ -1,11 +0,0 @@ -import HDNode from "avalanche/dist/utils/hdnode" -import { Buffer } from "buffer/" - -const main = async (): Promise => { - const seed: string = - "a0c42a9c3ac6abf2ba6a9946ae83af18f51bf1c9fa7dacc4c92513cc4dd015834341c775dcd4c0fac73547c5662d81a9e9361a0aac604a73a321bd9103bce8af" - const fromSeed: HDNode = new HDNode(Buffer.from(seed)) - console.log(fromSeed) -} - -main() diff --git a/examples/hdnode/fromMasterSeedString.ts b/examples/hdnode/fromMasterSeedString.ts deleted file mode 100644 index 3466d8e54..000000000 --- a/examples/hdnode/fromMasterSeedString.ts +++ /dev/null @@ -1,10 +0,0 @@ -import HDNode from "avalanche/dist/utils/hdnode" - -const main = async (): Promise => { - const seed: string = - "a0c42a9c3ac6abf2ba6a9946ae83af18f51bf1c9fa7dacc4c92513cc4dd015834341c775dcd4c0fac73547c5662d81a9e9361a0aac604a73a321bd9103bce8af" - const fromSeed: HDNode = new HDNode(seed) - console.log(fromSeed) -} - -main() diff --git a/examples/hdnode/fromXPriv.ts b/examples/hdnode/fromXPriv.ts deleted file mode 100644 index cf79a0b1a..000000000 --- a/examples/hdnode/fromXPriv.ts +++ /dev/null @@ -1,10 +0,0 @@ -import HDNode from "avalanche/dist/utils/hdnode" - -const main = async (): Promise => { - const xpriv: string = - "xprv9s21ZrQH143K4RH1nRkHwuVz3qGREBLobwUoUBowLDucQXm4do8jvz12agvjHrAwjJXtq9BZ87WBPUPScDBnjKvBKVQ5xbS7GQwJKW7vXLD" - const hdnode: HDNode = new HDNode(xpriv) - console.log(hdnode) -} - -main() diff --git a/examples/hdnode/fromXPub.ts b/examples/hdnode/fromXPub.ts deleted file mode 100644 index 18133f343..000000000 --- a/examples/hdnode/fromXPub.ts +++ /dev/null @@ -1,10 +0,0 @@ -import HDNode from "avalanche/dist/utils/hdnode" - -const main = async (): Promise => { - const xpub: string = - "xpub661MyMwAqRbcGuMUtTHJK3Sibs6ude4eyAQQGaDYtZSbHL6DBLSzUnKWRwuXU8ZhzLCNaE1WSZqJfnn1APCJcx4y5RvuyE6Upw6yTHFuARG" - const hdnode: HDNode = new HDNode(xpub) - console.log(hdnode) -} - -main() diff --git a/examples/hdnode/sign.ts b/examples/hdnode/sign.ts deleted file mode 100644 index df3ca4b63..000000000 --- a/examples/hdnode/sign.ts +++ /dev/null @@ -1,13 +0,0 @@ -import HDNode from "avalanche/dist/utils/hdnode" -import { Buffer } from "buffer/" - -const main = async (): Promise => { - const seed: string = - "a0c42a9c3ac6abf2ba6a9946ae83af18f51bf1c9fa7dacc4c92513cc4dd015834341c775dcd4c0fac73547c5662d81a9e9361a0aac604a73a321bd9103bce8af" - const fromSeed: HDNode = new HDNode(seed) - const msg: string = "bb413645935a9bf1ecf0c3d30df2d573" - const sig: Buffer = fromSeed.sign(Buffer.from(msg)) - console.log(sig) -} - -main() diff --git a/examples/hdnode/verify.ts b/examples/hdnode/verify.ts deleted file mode 100644 index ffab823ad..000000000 --- a/examples/hdnode/verify.ts +++ /dev/null @@ -1,14 +0,0 @@ -import HDNode from "avalanche/dist/utils/hdnode" -import { Buffer } from "buffer/" - -const main = async (): Promise => { - const seed: string = - "a0c42a9c3ac6abf2ba6a9946ae83af18f51bf1c9fa7dacc4c92513cc4dd015834341c775dcd4c0fac73547c5662d81a9e9361a0aac604a73a321bd9103bce8af" - const fromSeed: HDNode = new HDNode(seed) - const msg: string = "bb413645935a9bf1ecf0c3d30df2d573" - const sig: Buffer = fromSeed.sign(Buffer.from(msg)) - const verify: boolean = fromSeed.verify(Buffer.from(msg), sig) - console.log(verify) -} - -main() diff --git a/examples/hdnode/wipePrivateData.ts b/examples/hdnode/wipePrivateData.ts deleted file mode 100644 index 5838b8f28..000000000 --- a/examples/hdnode/wipePrivateData.ts +++ /dev/null @@ -1,11 +0,0 @@ -import HDNode from "avalanche/dist/utils/hdnode" - -const main = async (): Promise => { - const seed: string = - "a0c42a9c3ac6abf2ba6a9946ae83af18f51bf1c9fa7dacc4c92513cc4dd015834341c775dcd4c0fac73547c5662d81a9e9361a0aac604a73a321bd9103bce8af" - const fromSeed: HDNode = new HDNode(seed) - fromSeed.wipePrivateData() - console.log(fromSeed.privateKey === null) -} - -main() diff --git a/examples/health/README.md b/examples/health/README.md deleted file mode 100644 index cce74d95d..000000000 --- a/examples/health/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Auth RPC - -Example scripts for the Avalanche [Health RPC](https://docs.avax.network/build/avalanchego-apis/health-api) - -* [health.ts](./health.ts) diff --git a/examples/health/health.ts b/examples/health/health.ts deleted file mode 100644 index 895521e24..000000000 --- a/examples/health/health.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { HealthAPI } from "avalanche/dist/apis/health" -import { HealthResponse } from "avalanche/dist/apis/health/interfaces" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const health: HealthAPI = avalanche.Health() - -const main = async (): Promise => { - const healthResponse: HealthResponse = await health.health() - console.log(healthResponse) -} - -main() diff --git a/examples/index/README.md b/examples/index/README.md deleted file mode 100644 index 79af9b3e2..000000000 --- a/examples/index/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# Index RPC - -Example scripts for the Avalanche [Index RPC](https://docs.avax.network/build/avalanchego-apis/index-api) - -* [getContainerByID.ts](./getContainerByID.ts) -* [getContainerByIndex.ts](./getContainerByIndex.ts) -* [getContainerRange.ts](./getContainerRange.ts) -* [getIndex.ts](./getIndex.ts) -* [getLastAccepted.ts](./getLastAccepted.ts) -* [isAccepted.ts](./isAccepted.ts) diff --git a/examples/index/getContainerByID.ts b/examples/index/getContainerByID.ts deleted file mode 100644 index 2760a3fd5..000000000 --- a/examples/index/getContainerByID.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { IndexAPI } from "avalanche/dist/apis/index" -import { GetContainerByIDResponse } from "avalanche/dist/apis/index/interfaces" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const index: IndexAPI = avalanche.Index() - -const main = async (): Promise => { - const id: string = "eLXEKFFMgGmK7ZLokCFjppdBfGy5hDuRqh5uJVyXXPaRErpAX" - const encoding: string = "hex" - const baseurl: string = "/ext/index/X/tx" - const containerByIndex: GetContainerByIDResponse = - await index.getContainerByID(id, encoding, baseurl) - console.log(containerByIndex) -} - -main() diff --git a/examples/index/getContainerByIndex.ts b/examples/index/getContainerByIndex.ts deleted file mode 100644 index 0895b34ff..000000000 --- a/examples/index/getContainerByIndex.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { IndexAPI } from "avalanche/dist/apis/index" -import { GetContainerByIndexResponse } from "avalanche/dist/apis/index/interfaces" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const index: IndexAPI = avalanche.Index() - -const main = async (): Promise => { - const idx: string = "0" - const encoding: string = "hex" - const baseurl: string = "/ext/index/X/tx" - const containerByIndex: GetContainerByIndexResponse = - await index.getContainerByIndex(idx, encoding, baseurl) - console.log(containerByIndex) -} - -main() diff --git a/examples/index/getContainerRange.ts b/examples/index/getContainerRange.ts deleted file mode 100644 index 3480711f3..000000000 --- a/examples/index/getContainerRange.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { IndexAPI } from "avalanche/dist/apis/index" -import { GetContainerRangeResponse } from "avalanche/dist/apis/index/interfaces" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const index: IndexAPI = avalanche.Index() - -const main = async (): Promise => { - const startIndex: number = 0 - const numToFetch: number = 100 - const encoding: string = "hex" - const baseurl: string = "/ext/index/X/tx" - const containerRange: GetContainerRangeResponse[] = - await index.getContainerRange(startIndex, numToFetch, encoding, baseurl) - console.log(containerRange) -} - -main() diff --git a/examples/index/getIndex.ts b/examples/index/getIndex.ts deleted file mode 100644 index 85f492c81..000000000 --- a/examples/index/getIndex.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { IndexAPI } from "avalanche/dist/apis/index" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const index: IndexAPI = avalanche.Index() - -const main = async (): Promise => { - const id: string = "eLXEKFFMgGmK7ZLokCFjppdBfGy5hDuRqh5uJVyXXPaRErpAX" - const encoding: string = "hex" - const baseurl: string = "/ext/index/X/tx" - const containerIndex: string = await index.getIndex(id, encoding, baseurl) - console.log(containerIndex) -} - -main() diff --git a/examples/index/getLastAccepted.ts b/examples/index/getLastAccepted.ts deleted file mode 100644 index f6cbf707d..000000000 --- a/examples/index/getLastAccepted.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { IndexAPI } from "avalanche/dist/apis/index" -import { GetLastAcceptedResponse } from "avalanche/dist/apis/index/interfaces" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const index: IndexAPI = avalanche.Index() - -const main = async (): Promise => { - const encoding: string = "hex" - const baseurl: string = "/ext/index/X/tx" - const lastAccepted: GetLastAcceptedResponse = await index.getLastAccepted( - encoding, - baseurl - ) - console.log(lastAccepted) -} - -main() diff --git a/examples/index/getLastVertex.ts b/examples/index/getLastVertex.ts deleted file mode 100644 index 08efcb431..000000000 --- a/examples/index/getLastVertex.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { Avalanche, BinTools, Buffer } from "../../src" -import { IndexAPI } from "../../src/apis/index/index" -import { GetLastAcceptedResponse } from "../../src/apis/index/interfaces" -import { Vertex } from "../../src/apis/avm" - -const ip: string = "indexer-demo.avax.network" -const port: number = 443 -const protocol: string = "https" -const networkID: number = 1 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const index: IndexAPI = avalanche.Index() -const bintools: BinTools = BinTools.getInstance() - -const main = async (): Promise => { - const encoding: string = "cb58" - const baseurl: string = "/ext/index/X/vtx" - const lastVertex: GetLastAcceptedResponse = await index.getLastAccepted( - encoding, - baseurl - ) - console.log(lastVertex) - - const vertex: Vertex = new Vertex() - vertex.fromBuffer(bintools.cb58Decode(lastVertex.bytes)) - console.log(vertex) - console.log("--------") - - const buf: Buffer = vertex.toBuffer() - const v: Vertex = new Vertex() - v.fromBuffer(buf) - console.log(v) -} - -main() diff --git a/examples/index/isAccepted.ts b/examples/index/isAccepted.ts deleted file mode 100644 index c8f6be9ba..000000000 --- a/examples/index/isAccepted.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { IndexAPI } from "avalanche/dist/apis/index" -import { IsAcceptedResponse } from "avalanche/dist/apis/index/interfaces" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const index: IndexAPI = avalanche.Index() - -const main = async (): Promise => { - const id: string = "eLXEKFFMgGmK7ZLokCFjppdBfGy5hDuRqh5uJVyXXPaRErpAX" - const encoding: string = "hex" - const baseurl: string = "/ext/index/X/tx" - const isContainerAccepted: IsAcceptedResponse = await index.isAccepted( - id, - encoding, - baseurl - ) - console.log(isContainerAccepted) -} - -main() diff --git a/examples/index/traverseDAG.ts b/examples/index/traverseDAG.ts deleted file mode 100644 index 0e75d7d2d..000000000 --- a/examples/index/traverseDAG.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { Avalanche, Buffer } from "../../src" -import { Vertex } from "../../src/apis/avm" -import { IndexAPI } from "../../src/apis/index" -import { - GetContainerByIndexResponse, - GetLastAcceptedResponse -} from "../../src/apis/index/interfaces" - -const ip: string = "indexer-demo.avax.network" -const port: number = 443 -const protocol: string = "https" -const networkID: number = 1 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const index: IndexAPI = avalanche.Index() - -const sleep = (ms: number): Promise => { - return new Promise((resolve) => setTimeout(resolve, ms)) -} -const mstimeout: number = 1000 - -const main = async (): Promise => { - const encoding: string = "hex" - const baseurl: string = "/ext/index/X/vtx" - const lastAccepted: GetLastAcceptedResponse = await index.getLastAccepted( - encoding, - baseurl - ) - console.log("LAST ACCEPTED", lastAccepted) - - await sleep(mstimeout) - - let idx: string = (parseInt(lastAccepted.index) - 1).toString() - while (parseInt(idx) >= 1) { - const containerByIndex: GetContainerByIndexResponse = - await index.getContainerByIndex(idx, encoding, baseurl) - console.log(`CONTAINER BY INDEX: ${idx}`, containerByIndex) - idx = (parseInt(containerByIndex.index) - 1).toString() - - const buffer: Buffer = new Buffer(containerByIndex.bytes.slice(2), "hex") - // console.log(buffer) - const vertex: Vertex = new Vertex() - vertex.fromBuffer(buffer) - // const b: Buffer = vertex.toBuffer() - // console.log(b.toString("hex")) - console.log(vertex) - console.log("-------------") - } -} - -main() diff --git a/examples/info/README.md b/examples/info/README.md deleted file mode 100644 index 3cc61664a..000000000 --- a/examples/info/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# Info RPC - -Example scripts for the Avalanche [Info RPC](https://docs.avax.network/build/avalanchego-apis/info-api) - -* [getBlockchainID.ts](./getBlockchainID.ts) -* [getNetworkID.ts](./getNetworkID.ts) -* [getNetworkName.ts](./getNetworkName.ts) -* [getNodeID.ts](./getNodeID.ts) -* [getNodeIP.ts](./getNodeIP.ts) -* [getNodeVersion.ts](./getNodeVersion.ts) -* [getTxFee.ts](./getTxFee.ts) -* [isBootstrapped.ts](./isBootstrapped.ts) -* [peers.ts](./peers.ts) -* [uptime.ts](./uptime.ts) diff --git a/examples/info/getBlockchainID.ts b/examples/info/getBlockchainID.ts deleted file mode 100644 index fe7ddb1f1..000000000 --- a/examples/info/getBlockchainID.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { InfoAPI } from "avalanche/dist/apis/info" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const info: InfoAPI = avalanche.Info() - -const main = async (): Promise => { - const alias: string = "X" - const blockchainID: string = await info.getBlockchainID(alias) - console.log(blockchainID) -} - -main() diff --git a/examples/info/getNetworkID.ts b/examples/info/getNetworkID.ts deleted file mode 100644 index 0ce7dfc2b..000000000 --- a/examples/info/getNetworkID.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { InfoAPI } from "avalanche/dist/apis/info" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const info: InfoAPI = avalanche.Info() - -const main = async (): Promise => { - const networkID: number = await info.getNetworkID() - console.log(networkID) -} - -main() diff --git a/examples/info/getNetworkName.ts b/examples/info/getNetworkName.ts deleted file mode 100644 index 33846f915..000000000 --- a/examples/info/getNetworkName.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { InfoAPI } from "avalanche/dist/apis/info" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const info: InfoAPI = avalanche.Info() - -const main = async (): Promise => { - const networkName: string = await info.getNetworkName() - console.log(networkName) -} - -main() diff --git a/examples/info/getNodeID.ts b/examples/info/getNodeID.ts deleted file mode 100644 index feac87dda..000000000 --- a/examples/info/getNodeID.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { InfoAPI } from "avalanche/dist/apis/info" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const info: InfoAPI = avalanche.Info() - -const main = async (): Promise => { - const nodeID: string = await info.getNodeID() - console.log(nodeID) -} - -main() diff --git a/examples/info/getNodeVersion.ts b/examples/info/getNodeVersion.ts deleted file mode 100644 index 57444e54f..000000000 --- a/examples/info/getNodeVersion.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { InfoAPI } from "avalanche/dist/apis/info" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const info: InfoAPI = avalanche.Info() - -const main = async (): Promise => { - const nodeVersion: string = await info.getNodeVersion() - console.log(nodeVersion) -} - -main() diff --git a/examples/info/getTxFee.ts b/examples/info/getTxFee.ts deleted file mode 100644 index 17b62d1d7..000000000 --- a/examples/info/getTxFee.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { InfoAPI } from "avalanche/dist/apis/info" -import { GetTxFeeResponse } from "avalanche/dist/apis/info/interfaces" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const info: InfoAPI = avalanche.Info() - -const main = async (): Promise => { - const iGetTxFeeResponse: GetTxFeeResponse = await info.getTxFee() - console.log(iGetTxFeeResponse) -} - -main() diff --git a/examples/info/isBootstrapped.ts b/examples/info/isBootstrapped.ts deleted file mode 100644 index e75c95d46..000000000 --- a/examples/info/isBootstrapped.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { InfoAPI } from "avalanche/dist/apis/info" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const info: InfoAPI = avalanche.Info() - -const main = async (): Promise => { - const chain: string = "X" - const bootstrapped: boolean = await info.isBootstrapped(chain) - console.log(bootstrapped) -} - -main() diff --git a/examples/info/peers.ts b/examples/info/peers.ts deleted file mode 100644 index 51e8c198d..000000000 --- a/examples/info/peers.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { InfoAPI } from "avalanche/dist/apis/info" -import { PeersResponse } from "avalanche/dist/apis/info/interfaces" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const info: InfoAPI = avalanche.Info() - -const main = async (): Promise => { - const peers: PeersResponse[] = await info.peers([]) - console.log(peers) -} - -main() diff --git a/examples/info/uptime.ts b/examples/info/uptime.ts deleted file mode 100644 index 2e6c803b4..000000000 --- a/examples/info/uptime.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { InfoAPI } from "avalanche/dist/apis/info" -import { UptimeResponse } from "avalanche/dist/apis/info/interfaces" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const info: InfoAPI = avalanche.Info() - -const main = async (): Promise => { - const uptimeResponse: UptimeResponse = await info.uptime() - console.log(uptimeResponse) -} - -main() diff --git a/examples/keystore/README.md b/examples/keystore/README.md deleted file mode 100644 index 22ab14f45..000000000 --- a/examples/keystore/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# Keystore RPC - -Example scripts for the Avalanche [Keystore RPC](https://docs.avax.network/build/avalanchego-apis/keystore) - -* [createUser.ts](./createUser.ts) -* [deleteUser.ts](./deleteUser.ts) -* [exportUser.ts](./exportUser.ts) -* [importUser.ts](./importUser.ts) -* [listUsers.ts](./listUsers.ts) diff --git a/examples/keystore/createUser.ts b/examples/keystore/createUser.ts deleted file mode 100644 index 360dcf3e8..000000000 --- a/examples/keystore/createUser.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { KeystoreAPI } from "avalanche/dist/apis/keystore" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const keystore: KeystoreAPI = avalanche.NodeKeys() - -const main = async (): Promise => { - const username: string = "username" - const password: string = "Vz48jjHLTCcAepH95nT4B" - const successful: boolean = await keystore.createUser(username, password) - console.log(successful) -} - -main() diff --git a/examples/keystore/deleteUser.ts b/examples/keystore/deleteUser.ts deleted file mode 100644 index 563e9b3d3..000000000 --- a/examples/keystore/deleteUser.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { KeystoreAPI } from "avalanche/dist/apis/keystore" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const keystore: KeystoreAPI = avalanche.NodeKeys() - -const main = async (): Promise => { - const username: string = "username" - const password: string = "Vz48jjHLTCcAepH95nT4B" - const successful: boolean = await keystore.deleteUser(username, password) - console.log(successful) -} - -main() diff --git a/examples/keystore/exportUser.ts b/examples/keystore/exportUser.ts deleted file mode 100644 index e7f7b6aad..000000000 --- a/examples/keystore/exportUser.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { KeystoreAPI } from "avalanche/dist/apis/keystore" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const keystore: KeystoreAPI = avalanche.NodeKeys() - -const main = async (): Promise => { - const username: string = "username" - const password: string = "Vz48jjHLTCcAepH95nT4B" - const user: string = await keystore.exportUser(username, password) - console.log(user) -} - -main() diff --git a/examples/keystore/importUser.ts b/examples/keystore/importUser.ts deleted file mode 100644 index 49fc372ac..000000000 --- a/examples/keystore/importUser.ts +++ /dev/null @@ -1,35 +0,0 @@ -// This file read secrets from a separate file called "secrets.json" -// which you can create based on "secrets.example" which is in the -// root of the `examples/` directory. -// Unlike "secrets.example", "secrets.json" should never be committed to git. -import { readFile } from "fs" -import { Avalanche } from "avalanche/dist" -import { KeystoreAPI } from "avalanche/dist/apis/keystore" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const keystore: KeystoreAPI = avalanche.NodeKeys() - -const main = async (): Promise => { - const path: string = "./examples/secrets.json" - const encoding: "utf8" = "utf8" - const cb = async (err: any, data: any): Promise => { - if (err) throw err - const jsonData: any = JSON.parse(data) - const username: string = "username" - const password: string = jsonData.password - const user: string = jsonData.user - const successful: boolean = await keystore.importUser( - username, - user, - password - ) - console.log(successful) - } - readFile(path, encoding, cb) -} - -main() diff --git a/examples/keystore/listUsers.ts b/examples/keystore/listUsers.ts deleted file mode 100644 index e8e8e5e7a..000000000 --- a/examples/keystore/listUsers.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { KeystoreAPI } from "avalanche/dist/apis/keystore" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const keystore: KeystoreAPI = avalanche.NodeKeys() - -const main = async (): Promise => { - const users: string[] = await keystore.listUsers() - console.log(users) -} - -main() diff --git a/examples/metrics/README.md b/examples/metrics/README.md deleted file mode 100644 index 0132fbf44..000000000 --- a/examples/metrics/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Metrics RPC - -Example scripts for the Avalanche [Metrics RPC](https://docs.avax.network/build/avalanchego-apis/metrics-api) - -* [getMetrics.ts](./getMetrics.ts) \ No newline at end of file diff --git a/examples/metrics/getMetrics.ts b/examples/metrics/getMetrics.ts deleted file mode 100644 index 8b997684a..000000000 --- a/examples/metrics/getMetrics.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { MetricsAPI } from "avalanche/dist/apis/metrics" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const metrics: MetricsAPI = avalanche.Metrics() - -const main = async (): Promise => { - const m: string = await metrics.getMetrics() - console.log(m) -} - -main() diff --git a/examples/mnemonic/README.md b/examples/mnemonic/README.md deleted file mode 100644 index b51791f3a..000000000 --- a/examples/mnemonic/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# Mnemonic - -Example scripts for creating and validating mnemonics in multiple languages. - -* [entropyToMnemonic.ts](./entropyToMnemonic.ts) -* [generateMnemonic.ts](./generateMnemonic.ts) -* [getDefaultWordlist.ts](./getDefaultWordlist.ts) -* [getWordlists.ts](./getWordlists.ts) -* [mnemonicToEntropy.ts](./mnemonicToEntropy.ts) -* [mnemonicToSeed.ts](./mnemonicToSeed.ts) -* [mnemonicToSeedSync.ts](./mnemonicToSeedSync.ts) -* [setDefaultWordlist.ts](./setDefaultWordlist.ts) -* [validateMnemonic.ts](./validateMnemonic.ts) \ No newline at end of file diff --git a/examples/mnemonic/entropyToMnemonic.ts b/examples/mnemonic/entropyToMnemonic.ts deleted file mode 100644 index d87d31d20..000000000 --- a/examples/mnemonic/entropyToMnemonic.ts +++ /dev/null @@ -1,15 +0,0 @@ -import Mnemonic from "avalanche/dist/utils/mnemonic" -const mnemonic: Mnemonic = Mnemonic.getInstance() - -const main = async (): Promise => { - const wordlist = mnemonic.getWordlists("EN") as string[] - const entropy: string = - "9d7c99e77261acb88a5ed717f625d5d3ed5569e0f60429cc6eb9c4e91f48fb7c" - const entropyToMnemonic: string = mnemonic.entropyToMnemonic( - entropy, - wordlist - ) - console.log(entropyToMnemonic) -} - -main() diff --git a/examples/mnemonic/generateMnemonic.ts b/examples/mnemonic/generateMnemonic.ts deleted file mode 100644 index a784d2b5c..000000000 --- a/examples/mnemonic/generateMnemonic.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { randomBytes } from "randombytes" -import Mnemonic from "avalanche/dist/utils/mnemonic" -const mnemonic: Mnemonic = Mnemonic.getInstance() - -const main = async (): Promise => { - const strength: number = 256 - const wordlist = mnemonic.getWordlists("czech") as string[] - const m: string = mnemonic.generateMnemonic(strength, randomBytes, wordlist) - console.log(m) -} - -main() diff --git a/examples/mnemonic/getDefaultWordlist.ts b/examples/mnemonic/getDefaultWordlist.ts deleted file mode 100644 index 0a0b37f55..000000000 --- a/examples/mnemonic/getDefaultWordlist.ts +++ /dev/null @@ -1,9 +0,0 @@ -import Mnemonic from "avalanche/dist/utils/mnemonic" -const mnemonic: Mnemonic = Mnemonic.getInstance() - -const main = async (): Promise => { - mnemonic.setDefaultWordlist("japanese") - const getDefaultWordlist: string = mnemonic.getDefaultWordlist() - console.log(getDefaultWordlist) -} -main() diff --git a/examples/mnemonic/getWordlists.ts b/examples/mnemonic/getWordlists.ts deleted file mode 100644 index 6efdfba56..000000000 --- a/examples/mnemonic/getWordlists.ts +++ /dev/null @@ -1,9 +0,0 @@ -import Mnemonic from "avalanche/dist/utils/mnemonic" -const mnemonic: Mnemonic = Mnemonic.getInstance() - -const main = async (): Promise => { - console.log(mnemonic.getWordlists("czech")) - // console.log(mnemonic.getWordlists()) -} - -main() diff --git a/examples/mnemonic/mnemonicToEntropy.ts b/examples/mnemonic/mnemonicToEntropy.ts deleted file mode 100644 index 9e80ab114..000000000 --- a/examples/mnemonic/mnemonicToEntropy.ts +++ /dev/null @@ -1,12 +0,0 @@ -import Mnemonic from "avalanche/dist/utils/mnemonic" -const mnemonic: Mnemonic = Mnemonic.getInstance() - -const main = async (): Promise => { - const m: string = - "output tooth keep tooth bracket fox city sustain blood raise install pond stem reject long scene clap gloom purpose mean music piece unknown light" - const wordlist = mnemonic.getWordlists("EN") as string[] - const mnemonicToEntropy: string = mnemonic.mnemonicToEntropy(m, wordlist) - console.log(mnemonicToEntropy) -} - -main() diff --git a/examples/mnemonic/mnemonicToSeed.ts b/examples/mnemonic/mnemonicToSeed.ts deleted file mode 100644 index 16d9e61f0..000000000 --- a/examples/mnemonic/mnemonicToSeed.ts +++ /dev/null @@ -1,12 +0,0 @@ -import Mnemonic from "avalanche/dist/utils/mnemonic" -import { Buffer } from "avalanche/dist" -const mnemonic: Mnemonic = Mnemonic.getInstance() - -const main = async (): Promise => { - const m: string = - "output tooth keep tooth bracket fox city sustain blood raise install pond stem reject long scene clap gloom purpose mean music piece unknown light" - const password: string = "password" - const mnemonicToSeed: Buffer = await mnemonic.mnemonicToSeed(m, password) - console.log(mnemonicToSeed) -} -main() diff --git a/examples/mnemonic/mnemonicToSeedSync.ts b/examples/mnemonic/mnemonicToSeedSync.ts deleted file mode 100644 index a98e7b775..000000000 --- a/examples/mnemonic/mnemonicToSeedSync.ts +++ /dev/null @@ -1,12 +0,0 @@ -import Mnemonic from "avalanche/dist/utils/mnemonic" -import { Buffer } from "avalanche/dist" -const mnemonic: Mnemonic = Mnemonic.getInstance() - -const main = async (): Promise => { - const m: string = - "output tooth keep tooth bracket fox city sustain blood raise install pond stem reject long scene clap gloom purpose mean music piece unknown light" - const password: string = "password" - const mnemonicToSeedSync: Buffer = mnemonic.mnemonicToSeedSync(m, password) - console.log(mnemonicToSeedSync) -} -main() diff --git a/examples/mnemonic/setDefaultWordlist.ts b/examples/mnemonic/setDefaultWordlist.ts deleted file mode 100644 index 9e284f9d0..000000000 --- a/examples/mnemonic/setDefaultWordlist.ts +++ /dev/null @@ -1,8 +0,0 @@ -import Mnemonic from "avalanche/dist/utils/mnemonic" -const mnemonic: Mnemonic = Mnemonic.getInstance() - -const main = async (): Promise => { - const lang: string = "spanish" - mnemonic.setDefaultWordlist(lang) -} -main() diff --git a/examples/mnemonic/validateMnemonic.ts b/examples/mnemonic/validateMnemonic.ts deleted file mode 100644 index e20f596bd..000000000 --- a/examples/mnemonic/validateMnemonic.ts +++ /dev/null @@ -1,11 +0,0 @@ -import Mnemonic from "avalanche/dist/utils/mnemonic" -const mnemonic: Mnemonic = Mnemonic.getInstance() - -const main = async (): Promise => { - const m: string = - "output tooth keep tooth bracket fox city sustain blood raise install pond stem reject long scene clap gloom purpose mean music piece unknown light" - const wordlist = mnemonic.getWordlists("english") as string[] - const validateMnemonic: string = mnemonic.validateMnemonic(m, wordlist) - console.log(validateMnemonic) -} -main() diff --git a/examples/p-chain/delegate.ts b/examples/p-chain/delegate.ts new file mode 100644 index 000000000..c490aa453 --- /dev/null +++ b/examples/p-chain/delegate.ts @@ -0,0 +1,46 @@ +import { PrimaryNetworkID } from '../../src/constants/networkIDs'; +import { addTxSignatures } from '../../src/signer'; +import { bech32ToBytes, hexToBuffer } from '../../src/utils'; +import { getContextFromURI } from '../../src/vms/context'; +import { PVMApi, newAddPermissionlessDelegatorTx } from '../../src/vms/pvm'; +import { pvmapi } from '../chain_apis'; + +const P_CHAIN_ADDRESS = process.env.P_CHAIN_ADDRESS; +const PRIVATE_KEY = process.env.PRIVATE_KEY; + +const main = async () => { + if (!P_CHAIN_ADDRESS || !PRIVATE_KEY) { + throw new Error('Missing environment variable(s).'); + } + + const { utxos } = await pvmapi.getUTXOs({ addresses: [P_CHAIN_ADDRESS] }); + const context = await getContextFromURI(process.env.AVAX_PUBLIC_URL); + const startTime = await new PVMApi().getTimestamp(); + const startDate = new Date(startTime.timestamp); + const start = BigInt(startDate.getTime() / 1000); + const endTime = new Date(startTime.timestamp); + endTime.setDate(endTime.getDate() + 21); + const end = BigInt(endTime.getTime() / 1000); + const nodeID = 'NodeID-HKLp5269LH8DcrLvHPc2PHjGczBQD3td4'; + + const tx = newAddPermissionlessDelegatorTx( + context, + utxos, + [bech32ToBytes(P_CHAIN_ADDRESS)], + nodeID, + PrimaryNetworkID.toString(), + start, + end, + BigInt(1e9), + [bech32ToBytes(P_CHAIN_ADDRESS)], + ); + + await addTxSignatures({ + unsignedTx: tx, + privateKeys: [hexToBuffer(PRIVATE_KEY)], + }); + + return pvmapi.issueSignedTx(tx.getSignedTx()); +}; + +main().then(console.log); diff --git a/examples/p-chain/export.ts b/examples/p-chain/export.ts new file mode 100644 index 000000000..5f1f13c60 --- /dev/null +++ b/examples/p-chain/export.ts @@ -0,0 +1,44 @@ +import { TransferableOutput } from '../../src/serializable/avax'; +import { addTxSignatures } from '../../src/signer'; +import { bech32ToBytes, hexToBuffer } from '../../src/utils'; +import { getContextFromURI } from '../../src/vms/context'; +import { newExportTx } from '../../src/vms/pvm'; +import { pvmapi } from '../chain_apis'; +import { getChainIdFromContext } from '../utils/getChainIdFromContext'; + +const P_CHAIN_ADDRESS = process.env.P_CHAIN_ADDRESS; +const X_CHAIN_ADDRESS = process.env.X_CHAIN_ADDRESS; +const PRIVATE_KEY = process.env.PRIVATE_KEY; + +const main = async () => { + if (!P_CHAIN_ADDRESS || !X_CHAIN_ADDRESS || !PRIVATE_KEY) { + throw new Error('Missing environment variable(s).'); + } + + const context = await getContextFromURI(process.env.AVAX_PUBLIC_URL); + + const { utxos } = await pvmapi.getUTXOs({ + addresses: [P_CHAIN_ADDRESS], + }); + + const tx = newExportTx( + context, + getChainIdFromContext('X', context), + [bech32ToBytes(P_CHAIN_ADDRESS)], + utxos, + [ + TransferableOutput.fromNative(context.avaxAssetID, BigInt(0.1 * 1e9), [ + bech32ToBytes(X_CHAIN_ADDRESS), + ]), + ], + ); + + await addTxSignatures({ + unsignedTx: tx, + privateKeys: [hexToBuffer(PRIVATE_KEY)], + }); + + return pvmapi.issueSignedTx(tx.getSignedTx()); +}; + +main().then(console.log); diff --git a/examples/p-chain/import.ts b/examples/p-chain/import.ts new file mode 100644 index 000000000..890ac2cb5 --- /dev/null +++ b/examples/p-chain/import.ts @@ -0,0 +1,40 @@ +import { addTxSignatures } from '../../src/signer'; +import { bech32ToBytes, hexToBuffer } from '../../src/utils'; +import { getContextFromURI } from '../../src/vms/context'; +import { newImportTx } from '../../src/vms/pvm'; +import { pvmapi } from '../chain_apis'; +import { getChainIdFromContext } from '../utils/getChainIdFromContext'; + +const P_CHAIN_ADDRESS = process.env.P_CHAIN_ADDRESS; +const X_CHAIN_ADDRESS = process.env.X_CHAIN_ADDRESS; +const PRIVATE_KEY = process.env.PRIVATE_KEY; + +const main = async () => { + if (!P_CHAIN_ADDRESS || !X_CHAIN_ADDRESS || !PRIVATE_KEY) { + throw new Error('Missing environment variable(s).'); + } + + const context = await getContextFromURI(process.env.AVAX_PUBLIC_URL); + + const { utxos } = await pvmapi.getUTXOs({ + sourceChain: 'X', + addresses: [P_CHAIN_ADDRESS], + }); + + const importTx = newImportTx( + context, + getChainIdFromContext('X', context), + utxos, + [bech32ToBytes(P_CHAIN_ADDRESS)], + [bech32ToBytes(X_CHAIN_ADDRESS)], + ); + + await addTxSignatures({ + unsignedTx: importTx, + privateKeys: [hexToBuffer(PRIVATE_KEY)], + }); + + return pvmapi.issueSignedTx(importTx.getSignedTx()); +}; + +main().then(console.log); diff --git a/examples/p-chain/validate.ts b/examples/p-chain/validate.ts new file mode 100644 index 000000000..fefcd9ffd --- /dev/null +++ b/examples/p-chain/validate.ts @@ -0,0 +1,48 @@ +import { PrimaryNetworkID } from '../../src/constants/networkIDs'; +import { addTxSignatures } from '../../src/signer'; +import { bech32ToBytes, hexToBuffer } from '../../src/utils'; +import { getContextFromURI } from '../../src/vms/context'; +import { PVMApi, newAddPermissionlessValidatorTx } from '../../src/vms/pvm'; +import { pvmapi } from '../chain_apis'; + +const P_CHAIN_ADDRESS = process.env.P_CHAIN_ADDRESS; +const PRIVATE_KEY = process.env.PRIVATE_KEY; + +const main = async () => { + if (!P_CHAIN_ADDRESS || !PRIVATE_KEY) { + throw new Error('Missing environment variable(s).'); + } + + const { utxos } = await pvmapi.getUTXOs({ addresses: [P_CHAIN_ADDRESS] }); + const context = await getContextFromURI(process.env.AVAX_PUBLIC_URL); + const startTime = await new PVMApi().getTimestamp(); + const startDate = new Date(startTime.timestamp); + const start = BigInt(startDate.getTime() / 1000); + const endTime = new Date(startTime.timestamp); + endTime.setDate(endTime.getDate() + 21); + const end = BigInt(endTime.getTime() / 1000); + const nodeID = 'NodeID-HKLp5269LH8DcrLvNDoJquQs2w1LwLCga'; + + const tx = newAddPermissionlessValidatorTx( + context, + utxos, + [bech32ToBytes(P_CHAIN_ADDRESS)], + nodeID, + PrimaryNetworkID.toString(), + start, + end, + BigInt(1e9), + [bech32ToBytes(P_CHAIN_ADDRESS)], + [bech32ToBytes(P_CHAIN_ADDRESS)], + 1e4 * 20, + ); + + await addTxSignatures({ + unsignedTx: tx, + privateKeys: [hexToBuffer(PRIVATE_KEY)], + }); + + return pvmapi.issueSignedTx(tx.getSignedTx()); +}; + +main().then(console.log); diff --git a/examples/platformvm/JSONPChainTx.ts b/examples/platformvm/JSONPChainTx.ts deleted file mode 100644 index 02a944828..000000000 --- a/examples/platformvm/JSONPChainTx.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { Avalanche, Buffer } from "../../src" -import { PlatformVMAPI, Tx } from "../../src/apis/platformvm" - -const ip: string = "api.avax.network" -const port: number = 443 -const protocol: string = "https" -const networkID: number = 1 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() - -const main = async (): Promise => { - const txID: string = "7mnY7SqR1s8aTJShjvW1Yebe4snCzsjhonFrrXiWBE4L9x9A6" - const hex = (await pchain.getTx(txID)) as string - const buf: Buffer = new Buffer(hex.slice(2), "hex") - const tx: Tx = new Tx() - tx.fromBuffer(buf) - const jsonStr: string = JSON.stringify(tx) - console.log(jsonStr) - const jsn: Object = JSON.parse(jsonStr) - console.log(jsn) -} - -main() diff --git a/examples/platformvm/README.md b/examples/platformvm/README.md deleted file mode 100644 index a29c94ada..000000000 --- a/examples/platformvm/README.md +++ /dev/null @@ -1,34 +0,0 @@ -# PlatformVM - -Example scripts for the Avalanche [PlatformVM RPC](https://docs.avax.network/build/avalanchego-apis/platform-chain-p-chain-api) - -* [addDelegatorTx.ts](./addDelegatorTx.ts) -* [addValidatorTx.ts](./addValidatorTx.ts) -* [buildAddDelegatorTx.ts](./buildAddDelegatorTx.ts) -* [buildAddValidatorTx.ts](./buildAddValidatorTx.ts) -* [buildCreateSubnetTx.ts](./buildCreateSubnetTx.ts) -* [buildExportTx.ts](./buildExportTx.ts) -* [buildImportTx.ts](./buildImportTx.ts) -* [createKeypair.ts](./createKeypair.ts) -* [createChainTx.ts](./createChainTx.ts) -* [createSubnetTx.ts](./createSubnetTx.ts) -* [exportTx-xchain.ts](./exportTx-xchain.ts) -* [getBalance.ts](./getBalance.ts) -* [getBlockchains.ts](./getBlockchains.ts) -* [getBlockchainStatus.ts](./getBlockchainStatus.ts) -* [getCurrentSupply.ts](./getCurrentSupply.ts) -* [getCurrentValidators.ts](./getCurrentValidators.ts) -* [getInterfaces.ts](./getInterfaces.ts) -* [getPendingValidators.ts](./getPendingValidators.ts) -* [getRewardUTXOs.ts](./getRewardUTXOs.ts) -* [getStake.ts](./getStake.ts) -* [getStakingAssetID.ts](./getStakingAssetID.ts) -* [getSubnets.ts](./getSubnets.ts) -* [getTx.ts](./getTx.ts) -* [getTxStatus.ts](./getTxStatus.ts) -* [getValidatorsAt.ts](./getValidatorsAt.ts) -* [importTx-xchain.ts](./importTx-xchain.ts) -* [JSONPChainTx.ts](./JSONPChainTx.ts) -* [proofOfPossession.ts](./proofOfPossession.ts) -* [removeSubnetValidatorTx.ts](./removeSubnetValidatorTx.ts) -* [subnetAuth.ts](./subnetAuth.ts) diff --git a/examples/platformvm/addDelegatorTx.ts b/examples/platformvm/addDelegatorTx.ts deleted file mode 100644 index 7e9a8e5fd..000000000 --- a/examples/platformvm/addDelegatorTx.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - PlatformVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - AddDelegatorTx, - Tx, - SECPOwnerOutput, - ParseableOutput -} from "avalanche/dist/apis/platformvm" -import { Output } from "avalanche/dist/common" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - NodeIDStringToBuffer, - UnixNow -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -const bintools: BinTools = BinTools.getInstance() -const pKeychain: KeyChain = pchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -pKeychain.importKey(privKey) -const pAddresses: Buffer[] = pchain.keyChain().getAddresses() -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const pChainBlockchainID: string = Defaults.network[networkID].P.blockchainID -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const stakeOuts: TransferableOutput[] = [] -const fee: BN = pchain.getDefaultTxFee() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "Manually add a delegator to the primary subnet" -) -const nodeID: string = "NodeID-DueWyGi3B9jtKfa9mPoecd4YSDJ1ftF69" -const startTime: BN = UnixNow().add(new BN(60 * 1)) -const endTime: BN = startTime.add(new BN(2630000)) - -const main = async (): Promise => { - const stakeAmount: any = await pchain.getMinStake() - const avaxAssetID: Buffer = await pchain.getAVAXAssetID() - const getBalanceResponse: any = await pchain.getBalance(pAddressStrings[0]) - const unlocked: BN = new BN(getBalanceResponse.unlocked) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - unlocked.sub(fee).sub(stakeAmount.minValidatorStake), - pAddresses, - locktime, - threshold - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const stakeSECPTransferOutput: SECPTransferOutput = new SECPTransferOutput( - stakeAmount.minValidatorStake, - pAddresses, - locktime, - threshold - ) - const stakeTransferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - stakeSECPTransferOutput - ) - stakeOuts.push(stakeTransferableOutput) - - const rewardOutputOwners: SECPOwnerOutput = new SECPOwnerOutput( - pAddresses, - locktime, - threshold - ) - const rewardOwners: ParseableOutput = new ParseableOutput(rewardOutputOwners) - - const platformVMUTXOResponse: any = await pchain.getUTXOs(pAddressStrings) - const utxoSet: UTXOSet = platformVMUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO) => { - const output: Output = utxo.getOutput() - if (output.getOutputID() === 7) { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - secpTransferInput.addSignatureIdx(0, pAddresses[0]) - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetID, - secpTransferInput - ) - inputs.push(input) - } - }) - - const addDelegatorTx: AddDelegatorTx = new AddDelegatorTx( - networkID, - bintools.cb58Decode(pChainBlockchainID), - outputs, - inputs, - memo, - NodeIDStringToBuffer(nodeID), - startTime, - endTime, - stakeAmount.minDelegatorStake, - stakeOuts, - rewardOwners - ) - - const unsignedTx: UnsignedTx = new UnsignedTx(addDelegatorTx) - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/addSubnetValidatorTx.ts b/examples/platformvm/addSubnetValidatorTx.ts deleted file mode 100644 index c53e43119..000000000 --- a/examples/platformvm/addSubnetValidatorTx.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "../../src" -import { - PlatformVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - AddSubnetValidatorTx -} from "../../src/apis/platformvm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - NodeIDStringToBuffer, - Defaults -} from "../../src/utils" -import { Output } from "../../src/common" - -const bintools: BinTools = BinTools.getInstance() -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -// Keychain with 4 keys-A, B, C, and D -const pKeychain: KeyChain = pchain.keyChain() -// Keypair A -let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -// P-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p -pKeychain.importKey(privKey) - -// Keypair B -privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4" -// P-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj -pKeychain.importKey(privKey) - -// Keypair C -privKey = "PrivateKey-24gdABgapjnsJfnYkfev6YPyQhTaCU72T9bavtDNTYivBLp2eW" -// P-custom1u6eth2fg33ye63mnyu5jswtj326jaypvhyar45 -pKeychain.importKey(privKey) - -// Keypair D -privKey = "PrivateKey-2uWuEQbY5t7NPzgqzDrXSgGPhi3uyKj2FeAvPUHYo6CmENHJfn" -// P-custom1t3qjau2pf3ys83yallqt4y5xc3l6ya5f7wr6aq -pKeychain.importKey(privKey) -const pAddresses: Buffer[] = pchain.keyChain().getAddresses() -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const pChainBlockchainID: string = Defaults.network[networkID].P.blockchainID -const pChainBlockchainIDBuf: Buffer = bintools.cb58Decode(pChainBlockchainID) -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = pchain.getDefaultTxFee() -const threshold: number = 1 -const locktime: BN = new BN(0) -const nodeID: string = "NodeID-NFBbbJ4qCmNaCzeW7sxErhvWqvEQMnYcN" -const startTime: BN = new BN(1672245821) -const endTime: BN = new BN(1673541715) -const memo: Buffer = Buffer.from( - "Manually create a AddSubnetValidatorTx which creates a 1-of-2 AVAX utxo and adds a validator to a subnet by correctly signing the 2-of-3 SubnetAuth" -) -const avaxUTXOKeychain: Buffer[] = [pAddresses[0], pAddresses[1]] - -const main = async (): Promise => { - const avaxAssetID: Buffer = await pchain.getAVAXAssetID() - const getBalanceResponse: any = await pchain.getBalance(pAddressStrings[0]) - const unlocked: BN = new BN(getBalanceResponse.unlocked) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - unlocked.sub(fee), - avaxUTXOKeychain, - locktime, - threshold - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const platformVMUTXOResponse: any = await pchain.getUTXOs(pAddressStrings) - const utxoSet: UTXOSet = platformVMUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO): void => { - const output: Output = utxo.getOutput() - if(output.getTypeID() === 7) { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - secpTransferInput.addSignatureIdx(0, pAddresses[0]) - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetID, - secpTransferInput - ) - inputs.push(input) - } - }) - - const weight: BN = new BN(1) - const subnetID: Buffer = bintools.cb58Decode( - "8T4oUrP7kXzetGF2bYWF21oJHUT18rJCjfBt3J299hA1Smcqa" - ) - const nodeIDBuf: Buffer = NodeIDStringToBuffer(nodeID) - const addSubnetValidatorTx: AddSubnetValidatorTx = new AddSubnetValidatorTx( - networkID, - pChainBlockchainIDBuf, - outputs, - inputs, - memo, - nodeIDBuf, - startTime, - endTime, - weight, - subnetID - ) - addSubnetValidatorTx.addSignatureIdx(0, pAddresses[3]) - addSubnetValidatorTx.addSignatureIdx(1, pAddresses[1]) - const unsignedTx: UnsignedTx = new UnsignedTx(addSubnetValidatorTx) - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/addValidatorTx.ts b/examples/platformvm/addValidatorTx.ts deleted file mode 100644 index 05b7e872a..000000000 --- a/examples/platformvm/addValidatorTx.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - PlatformVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - AddValidatorTx, - Tx, - SECPOwnerOutput, - ParseableOutput -} from "avalanche/dist/apis/platformvm" -import { Output } from "avalanche/dist/common" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - NodeIDStringToBuffer, - UnixNow -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -const bintools: BinTools = BinTools.getInstance() -const pKeychain: KeyChain = pchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -pKeychain.importKey(privKey) -const pAddresses: Buffer[] = pchain.keyChain().getAddresses() -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const pChainBlockchainID: string = Defaults.network[networkID].P.blockchainID -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const stakeOuts: TransferableOutput[] = [] -const fee: BN = pchain.getDefaultTxFee() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "Manually add a validator to the primary subnet" -) -const nodeID: string = "NodeID-DueWyGi3B9jtKfa9mPoecd4YSDJ1ftF69" -const startTime: BN = UnixNow().add(new BN(60 * 1)) -const endTime: BN = startTime.add(new BN(26300000)) -const delegationFee: number = 10 - -const main = async (): Promise => { - const stakeAmount: any = await pchain.getMinStake() - const avaxAssetID: Buffer = await pchain.getAVAXAssetID() - const getBalanceResponse: any = await pchain.getBalance(pAddressStrings[0]) - const unlocked: BN = new BN(getBalanceResponse.unlocked) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - unlocked.sub(fee).sub(stakeAmount.minValidatorStake), - pAddresses, - locktime, - threshold - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const stakeSECPTransferOutput: SECPTransferOutput = new SECPTransferOutput( - stakeAmount.minValidatorStake, - pAddresses, - locktime, - threshold - ) - const stakeTransferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - stakeSECPTransferOutput - ) - stakeOuts.push(stakeTransferableOutput) - - const rewardOutputOwners: SECPOwnerOutput = new SECPOwnerOutput( - pAddresses, - locktime, - threshold - ) - const rewardOwners: ParseableOutput = new ParseableOutput(rewardOutputOwners) - - const platformVMUTXOResponse: any = await pchain.getUTXOs(pAddressStrings) - const utxoSet: UTXOSet = platformVMUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO) => { - const output: Output = utxo.getOutput() - if (output.getOutputID() === 7) { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - secpTransferInput.addSignatureIdx(0, pAddresses[0]) - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetID, - secpTransferInput - ) - inputs.push(input) - } - }) - - const addValidatorTx: AddValidatorTx = new AddValidatorTx( - networkID, - bintools.cb58Decode(pChainBlockchainID), - outputs, - inputs, - memo, - NodeIDStringToBuffer(nodeID), - startTime, - endTime, - stakeAmount.minValidatorStake, - stakeOuts, - rewardOwners, - delegationFee - ) - const unsignedTx: UnsignedTx = new UnsignedTx(addValidatorTx) - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/baseTx-avax-create-multisig.ts b/examples/platformvm/baseTx-avax-create-multisig.ts deleted file mode 100644 index a5dafba18..000000000 --- a/examples/platformvm/baseTx-avax-create-multisig.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - PlatformVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - BaseTx -} from "avalanche/dist/apis/platformvm" -import { GetBalanceResponse } from "avalanche/dist/apis/avm/interfaces" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const bintools: BinTools = BinTools.getInstance() -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const xBlockchainID: string = Defaults.network[networkID].X.blockchainID -const xBlockchainIDBuf: Buffer = bintools.cb58Decode(xBlockchainID) -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const avaxAssetIDBuf: Buffer = bintools.cb58Decode(avaxAssetID) -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -const pKeychain: KeyChain = pchain.keyChain() -let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -// X-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p -pKeychain.importKey(privKey) - -privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4" -// X-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj -pKeychain.importKey(privKey) - -privKey = "PrivateKey-24b2s6EqkBp9bFG5S3Xxi4bjdxFqeRk56ck7QdQArVbwKkAvxz" -// X-custom1aekly2mwnsz6lswd6u0jqvd9u6yddt5884pyuc -pKeychain.importKey(privKey) -const xAddresses: Buffer[] = pchain.keyChain().getAddresses() -const xAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = pchain.getDefaultTxFee() -const threshold: number = 3 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "AVM manual create multisig BaseTx to send AVAX" -) -// Uncomment for codecID 00 01 -// const codecID: number = 1 - -const main = async (): Promise => { - const getBalanceResponse: GetBalanceResponse = await pchain.getBalance( - xAddressStrings[0] - ) - const balance: BN = new BN(getBalanceResponse.balance) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - balance.sub(fee), - xAddresses, - locktime, - threshold - ) - // Uncomment for codecID 00 01 - // secpTransferOutput.setCodecID(codecID) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetIDBuf, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const avmUTXOResponse: any = await pchain.getUTXOs(xAddressStrings) - const utxoSet: UTXOSet = avmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO): void => { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - // Uncomment for codecID 00 01 - // secpTransferInput.setCodecID(codecID) - secpTransferInput.addSignatureIdx(0, xAddresses[0]) - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetIDBuf, - secpTransferInput - ) - inputs.push(input) - }) - - const baseTx: BaseTx = new BaseTx( - networkID, - xBlockchainIDBuf, - outputs, - inputs, - memo - ) - // Uncomment for codecID 00 01 - // baseTx.setCodecID(codecID) - const unsignedTx: UnsignedTx = new UnsignedTx(baseTx) - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} -main() diff --git a/examples/platformvm/buildAddDelegatorTx.ts b/examples/platformvm/buildAddDelegatorTx.ts deleted file mode 100644 index f163c53b7..000000000 --- a/examples/platformvm/buildAddDelegatorTx.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { Avalanche, BN, Buffer } from "avalanche/dist" -import { - PlatformVMAPI, - KeyChain, - UTXOSet, - UnsignedTx, - Tx -} from "avalanche/dist/apis/platformvm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - UnixNow -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -const pKeychain: KeyChain = pchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -pKeychain.importKey(privKey) -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "PlatformVM utility method buildAddDelegatorTx to add a delegator to the primary subnet" -) -const asOf: BN = UnixNow() -const nodeID: string = "NodeID-DueWyGi3B9jtKfa9mPoecd4YSDJ1ftF69" -const startTime: BN = UnixNow().add(new BN(60 * 1)) -const endTime: BN = startTime.add(new BN(2630000)) - -const main = async (): Promise => { - const stakeAmount: any = await pchain.getMinStake() - const platformVMUTXOResponse: any = await pchain.getUTXOs(pAddressStrings) - const utxoSet: UTXOSet = platformVMUTXOResponse.utxos - - const unsignedTx: UnsignedTx = await pchain.buildAddDelegatorTx( - utxoSet, - pAddressStrings, - pAddressStrings, - pAddressStrings, - nodeID, - startTime, - endTime, - stakeAmount.minDelegatorStake, - pAddressStrings, - locktime, - threshold, - memo, - asOf - ) - - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/buildAddSubnetValidatorTx.ts b/examples/platformvm/buildAddSubnetValidatorTx.ts deleted file mode 100644 index 35bb92030..000000000 --- a/examples/platformvm/buildAddSubnetValidatorTx.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { Avalanche, BN, Buffer } from "avalanche/dist" -import { - PlatformVMAPI, - KeyChain, - UTXOSet, - UnsignedTx, - Tx -} from "avalanche/dist/apis/platformvm" -import { GetUTXOsResponse } from "avalanche/dist/apis/platformvm/interfaces" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - UnixNow -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -// Keychain with 4 keys-A, B, C, and D -const pKeychain: KeyChain = pchain.keyChain() -// Keypair A -let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -// P-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p -pKeychain.importKey(privKey) - -// Keypair B -privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4" -// P-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj -pKeychain.importKey(privKey) - -// Keypair C -privKey = "PrivateKey-24gdABgapjnsJfnYkfev6YPyQhTaCU72T9bavtDNTYivBLp2eW" -// P-custom1u6eth2fg33ye63mnyu5jswtj326jaypvhyar45 -pKeychain.importKey(privKey) - -// Keypair D -privKey = "PrivateKey-2uWuEQbY5t7NPzgqzDrXSgGPhi3uyKj2FeAvPUHYo6CmENHJfn" -// P-custom1t3qjau2pf3ys83yallqt4y5xc3l6ya5f7wr6aq -pKeychain.importKey(privKey) -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const nodeID: string = "NodeID-NFBbbJ4qCmNaCzeW7sxErhvWqvEQMnYcN" -const startTime: BN = new BN(1652217329) -const endTime: BN = new BN(1653511017) -const asOf: BN = UnixNow() - -const main = async (): Promise => { - const platformVMUTXOResponse: GetUTXOsResponse = await pchain.getUTXOs( - pAddressStrings - ) - const pAddresses: Buffer[] = pchain.keyChain().getAddresses() - const utxoSet: UTXOSet = platformVMUTXOResponse.utxos - - const weight: BN = new BN(1) - const subnetID: string = "2tFRAeosSsgd1XV9Bn2y9VEHKPkeuk41RdnAZh9PuZJDWWkR5" - const memo: Buffer = Buffer.from( - "Utility function to create a AddSubnetValidatorTx transaction" - ) - const subnetAuthCredentials: [number, Buffer][] = [ - [0, pAddresses[3]], - [1, pAddresses[1]] - ] - const unsignedTx: UnsignedTx = await pchain.buildAddSubnetValidatorTx( - utxoSet, - pAddressStrings, - pAddressStrings, - nodeID, - startTime, - endTime, - weight, - subnetID, - memo, - asOf, - subnetAuthCredentials - ) - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/buildAddValidatorTx.ts b/examples/platformvm/buildAddValidatorTx.ts deleted file mode 100644 index 20c217547..000000000 --- a/examples/platformvm/buildAddValidatorTx.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { Avalanche, BN, Buffer } from "avalanche/dist" -import { - PlatformVMAPI, - KeyChain, - UTXOSet, - UnsignedTx, - Tx -} from "avalanche/dist/apis/platformvm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - UnixNow -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -const pKeychain: KeyChain = pchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -pKeychain.importKey(privKey) -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "PlatformVM utility method buildAddValidatorTx to add a validator to the primary subnet" -) -const asOf: BN = UnixNow() -const nodeID: string = "NodeID-DueWyGi3B9jtKfa9mPoecd4YSDJ1ftF69" -const startTime: BN = UnixNow().add(new BN(60 * 1)) -const endTime: BN = startTime.add(new BN(26300000)) -const delegationFee: number = 10 - -const main = async (): Promise => { - const stakeAmount: any = await pchain.getMinStake() - const platformVMUTXOResponse: any = await pchain.getUTXOs(pAddressStrings) - const utxoSet: UTXOSet = platformVMUTXOResponse.utxos - - const unsignedTx: UnsignedTx = await pchain.buildAddValidatorTx( - utxoSet, - pAddressStrings, - pAddressStrings, - pAddressStrings, - nodeID, - startTime, - endTime, - stakeAmount.minValidatorStake, - pAddressStrings, - delegationFee, - locktime, - threshold, - memo, - asOf - ) - - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/buildCreateChainTx.ts b/examples/platformvm/buildCreateChainTx.ts deleted file mode 100644 index bb5763af9..000000000 --- a/examples/platformvm/buildCreateChainTx.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer, GenesisData } from "avalanche/dist" -import { - PlatformVMAPI, - KeyChain, - UTXOSet, - UnsignedTx, - Tx -} from "avalanche/dist/apis/platformvm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - UnixNow -} from "avalanche/dist/utils" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -// Keychain with 4 keys-A, B, C, and D -const pKeychain: KeyChain = pchain.keyChain() -// Keypair A -let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -// P-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p -pKeychain.importKey(privKey) - -// Keypair B -privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4" -// P-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj -pKeychain.importKey(privKey) - -// Keypair C -privKey = "PrivateKey-24gdABgapjnsJfnYkfev6YPyQhTaCU72T9bavtDNTYivBLp2eW" -// P-custom1u6eth2fg33ye63mnyu5jswtj326jaypvhyar45 -pKeychain.importKey(privKey) - -// Keypair D -privKey = "PrivateKey-2uWuEQbY5t7NPzgqzDrXSgGPhi3uyKj2FeAvPUHYo6CmENHJfn" -// P-custom1t3qjau2pf3ys83yallqt4y5xc3l6ya5f7wr6aq -pKeychain.importKey(privKey) -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const pAddresses: Buffer[] = pchain.keyChain().getAddresses() -const asOf: BN = UnixNow() - -const main = async (): Promise => { - const platformVMUTXOResponse: any = await pchain.getUTXOs(pAddressStrings) - const utxoSet: UTXOSet = platformVMUTXOResponse.utxos - - const genesisDataStr: string = - "11111DdZMhYXUZiFV9FNpfpTSQroysjHyMuT5zapYkPYrmap7t7S3sDNNwFzngxR9x1XmoRj5JK1XomX8RHvXYY5h3qYeEsMQRF8Ypia7p1CFHDo6KGSjMdiQkrmpvL8AvoezSxVWKXt2ubmBCnSkpPjnQbBSF7gNg4sPu1PXdh1eKgthaSFREqqG5FKMrWNiS6U87kxCmbKjkmBvwnAd6TpNx75YEiS9YKMyHaBZjkRDNf6Nj1" - const subnetIDStr: string = - "2cXEvbdDaP6q6srB6x1T14raebpJaM4s2t9NE5kiXzLqLXQDWm" - const memo: Buffer = Buffer.from( - "Utility function to create a CreateChainTx transaction" - ) - const subnetID: Buffer = bintools.cb58Decode(subnetIDStr) - const chainName: string = "EPIC AVM" - const vmID: string = "avm" - const fxIDs: string[] = ["secp256k1fx", "nftfx", "propertyfx"] - - // Only for AVM serialization. For other VMs comment these 2 lines - const genesisData: GenesisData = new GenesisData() - genesisData.fromBuffer(bintools.cb58Decode(genesisDataStr)) - - // For VMs other than AVM. For AVM comment this line - // const genesisData = genesisDataStr - const subnetAuthCredentials: [number, Buffer][] = [ - [0, pAddresses[3]], - [1, pAddresses[1]] - ] - - const unsignedTx: UnsignedTx = await pchain.buildCreateChainTx( - utxoSet, - pAddressStrings, - pAddressStrings, - subnetID, - chainName, - vmID, - fxIDs, - genesisData, - memo, - asOf, - subnetAuthCredentials - ) - - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/buildCreateSubnetTx.ts b/examples/platformvm/buildCreateSubnetTx.ts deleted file mode 100644 index a5748b490..000000000 --- a/examples/platformvm/buildCreateSubnetTx.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { Avalanche, BN, Buffer } from "avalanche/dist" -import { - PlatformVMAPI, - KeyChain, - UTXOSet, - UnsignedTx, - Tx -} from "avalanche/dist/apis/platformvm" -import { GetUTXOsResponse } from "avalanche/dist/apis/platformvm/interfaces" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - UnixNow -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -// Keychain with 4 keys-A, B, C, and D -const pKeychain: KeyChain = pchain.keyChain() -// Keypair A -let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -// P-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p -pKeychain.importKey(privKey) - -// Keypair B -privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4" -// P-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj -pKeychain.importKey(privKey) - -// Keypair C -privKey = "PrivateKey-24gdABgapjnsJfnYkfev6YPyQhTaCU72T9bavtDNTYivBLp2eW" -// P-custom1u6eth2fg33ye63mnyu5jswtj326jaypvhyar45 -pKeychain.importKey(privKey) - -// Keypair D -privKey = "PrivateKey-2uWuEQbY5t7NPzgqzDrXSgGPhi3uyKj2FeAvPUHYo6CmENHJfn" -// P-custom1t3qjau2pf3ys83yallqt4y5xc3l6ya5f7wr6aq -pKeychain.importKey(privKey) -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const threshold: number = 2 -const memo: Buffer = Buffer.from( - "PlatformVM utility method buildCreateSubnetTx to create a CreateSubnetTx which creates a 1-of-2 AVAX utxo and a 2-of-3 SubnetAuth" -) -const asOf: BN = UnixNow() -const subnetAuthKeychain: string[] = [ - pAddressStrings[1], - pAddressStrings[2], - pAddressStrings[3] -] - -const main = async (): Promise => { - const platformVMUTXOResponse: GetUTXOsResponse = await pchain.getUTXOs( - pAddressStrings - ) - const utxoSet: UTXOSet = platformVMUTXOResponse.utxos - - const unsignedTx: UnsignedTx = await pchain.buildCreateSubnetTx( - utxoSet, - pAddressStrings, - pAddressStrings, - subnetAuthKeychain, - threshold, - memo, - asOf - ) - - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/buildExportTx-CChain.ts b/examples/platformvm/buildExportTx-CChain.ts deleted file mode 100644 index ea03a8102..000000000 --- a/examples/platformvm/buildExportTx-CChain.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { Avalanche, BN, Buffer } from "avalanche/dist" -import { AVMAPI, KeyChain as AVMKeyChain } from "avalanche/dist/apis/avm" -import { - PlatformVMAPI, - KeyChain, - UTXOSet, - UnsignedTx, - Tx -} from "avalanche/dist/apis/platformvm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - UnixNow -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const pchain: PlatformVMAPI = avalanche.PChain() -const xKeychain: AVMKeyChain = xchain.keyChain() -const pKeychain: KeyChain = pchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -pKeychain.importKey(privKey) -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const cChainBlockchainID: string = Defaults.network[networkID].C.blockchainID -const fee: BN = pchain.getDefaultTxFee() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "PlatformVM utility method buildExportTx to export AVAX from the P-Chain to the C-Chain" -) -const asOf: BN = UnixNow() - -const main = async (): Promise => { - const getBalanceResponse: any = await pchain.getBalance(pAddressStrings[0]) - const unlocked: BN = new BN(getBalanceResponse.unlocked) - const platformVMUTXOResponse: any = await pchain.getUTXOs(pAddressStrings) - const utxoSet: UTXOSet = platformVMUTXOResponse.utxos - const unsignedTx: UnsignedTx = await pchain.buildExportTx( - utxoSet, - unlocked.sub(fee), - cChainBlockchainID, - xAddressStrings, - pAddressStrings, - pAddressStrings, - memo, - asOf, - locktime, - threshold - ) - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/buildExportTx-XChain.ts b/examples/platformvm/buildExportTx-XChain.ts deleted file mode 100644 index 4532e05fd..000000000 --- a/examples/platformvm/buildExportTx-XChain.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { Avalanche, BN, Buffer } from "avalanche/dist" -import { AVMAPI, KeyChain as AVMKeyChain } from "avalanche/dist/apis/avm" -import { - PlatformVMAPI, - KeyChain, - UTXOSet, - UnsignedTx, - Tx -} from "avalanche/dist/apis/platformvm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - UnixNow -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const pchain: PlatformVMAPI = avalanche.PChain() -const xKeychain: AVMKeyChain = xchain.keyChain() -const pKeychain: KeyChain = pchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -pKeychain.importKey(privKey) -const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const xChainBlockchainID: string = Defaults.network[networkID].X.blockchainID -const fee: BN = pchain.getDefaultTxFee() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "PlatformVM utility method buildExportTx to export AVAX from the P-Chain to the X-Chain" -) -const asOf: BN = UnixNow() - -const main = async (): Promise => { - const getBalanceResponse: any = await pchain.getBalance(pAddressStrings[0]) - const unlocked: BN = new BN(getBalanceResponse.unlocked) - const platformVMUTXOResponse: any = await pchain.getUTXOs(pAddressStrings) - const utxoSet: UTXOSet = platformVMUTXOResponse.utxos - const unsignedTx: UnsignedTx = await pchain.buildExportTx( - utxoSet, - unlocked.sub(fee), - xChainBlockchainID, - xAddressStrings, - pAddressStrings, - pAddressStrings, - memo, - asOf, - locktime, - threshold - ) - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/buildImportTx-CChain.ts b/examples/platformvm/buildImportTx-CChain.ts deleted file mode 100644 index 29ff27b43..000000000 --- a/examples/platformvm/buildImportTx-CChain.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { Avalanche, BN, Buffer } from "avalanche/dist" -import { - PlatformVMAPI, - KeyChain, - UTXOSet, - UnsignedTx, - Tx -} from "avalanche/dist/apis/platformvm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - UnixNow -} from "avalanche/dist//utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -const pKeychain: KeyChain = pchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -pKeychain.importKey(privKey) -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const cChainBlockchainID: string = Defaults.network[networkID].C.blockchainID -const pChainBlockchainID: string = Defaults.network[networkID].P.blockchainID -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "PlatformVM utility method buildImportTx to import AVAX to the P-Chain from the X-Chain" -) -const asOf: BN = UnixNow() - -const main = async (): Promise => { - const platformVMUTXOResponse: any = await pchain.getUTXOs( - pAddressStrings, - cChainBlockchainID - ) - const utxoSet: UTXOSet = platformVMUTXOResponse.utxos - const unsignedTx: UnsignedTx = await pchain.buildImportTx( - utxoSet, - pAddressStrings, - cChainBlockchainID, - pAddressStrings, - pAddressStrings, - pAddressStrings, - memo, - asOf, - locktime, - threshold - ) - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/buildImportTx-XChain.ts b/examples/platformvm/buildImportTx-XChain.ts deleted file mode 100644 index 2e1c1f14e..000000000 --- a/examples/platformvm/buildImportTx-XChain.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { Avalanche, BN, Buffer } from "avalanche/dist" -import { - PlatformVMAPI, - KeyChain, - UTXOSet, - UnsignedTx, - Tx -} from "avalanche/dist/apis/platformvm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - UnixNow -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -const pKeychain: KeyChain = pchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -pKeychain.importKey(privKey) -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const xChainBlockchainID: string = Defaults.network[networkID].X.blockchainID -const pChainBlockchainID: string = Defaults.network[networkID].P.blockchainID -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "PlatformVM utility method buildImportTx to import AVAX to the P-Chain from the X-Chain" -) -const asOf: BN = UnixNow() - -const main = async (): Promise => { - const platformVMUTXOResponse: any = await pchain.getUTXOs( - pAddressStrings, - pChainBlockchainID - ) - const utxoSet: UTXOSet = platformVMUTXOResponse.utxos - const unsignedTx: UnsignedTx = await pchain.buildImportTx( - utxoSet, - pAddressStrings, - xChainBlockchainID, - pAddressStrings, - pAddressStrings, - pAddressStrings, - memo, - asOf, - locktime, - threshold - ) - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/createChainTx.ts b/examples/platformvm/createChainTx.ts deleted file mode 100644 index 98b00e369..000000000 --- a/examples/platformvm/createChainTx.ts +++ /dev/null @@ -1,171 +0,0 @@ -import { - Avalanche, - BinTools, - BN, - Buffer, - GenesisAsset, - GenesisData -} from "avalanche/dist" -import { InitialStates } from "avalanche/dist/apis/avm" -import { - PlatformVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - CreateChainTx, - Tx -} from "avalanche/dist/apis/platformvm" -import { Output } from "avalanche/dist/common" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - ONEAVAX -} from "avalanche/dist/utils" - -const bintools: BinTools = BinTools.getInstance() -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -// Keychain with 4 keys-A, B, C, and D -const pKeychain: KeyChain = pchain.keyChain() -// Keypair A -let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -// P-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p -pKeychain.importKey(privKey) - -// Keypair B -privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4" -// P-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj -pKeychain.importKey(privKey) - -// Keypair C -privKey = "PrivateKey-24gdABgapjnsJfnYkfev6YPyQhTaCU72T9bavtDNTYivBLp2eW" -// P-custom1u6eth2fg33ye63mnyu5jswtj326jaypvhyar45 -pKeychain.importKey(privKey) - -// Keypair D -privKey = "PrivateKey-2uWuEQbY5t7NPzgqzDrXSgGPhi3uyKj2FeAvPUHYo6CmENHJfn" -// P-custom1t3qjau2pf3ys83yallqt4y5xc3l6ya5f7wr6aq -pKeychain.importKey(privKey) -const pAddresses: Buffer[] = pchain.keyChain().getAddresses() -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const pChainBlockchainID: string = "11111111111111111111111111111111LpoYY" -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = ONEAVAX -const threshold: number = 1 -const locktime: BN = new BN(0) -const avaxUTXOKeychain: Buffer[] = [pAddresses[0], pAddresses[1]] -const avaxUTXOKeychainStrings: string[] = [ - pAddressStrings[0], - pAddressStrings[1] -] - -const main = async (): Promise => { - const assetAlias: string = "AssetAliasTest" - const name: string = "Test Asset" - const symbol: string = "TEST" - const denomination: number = 0 - const amount: BN = new BN(507) - const vcapSecpOutput = new SECPTransferOutput( - amount, - avaxUTXOKeychain, - locktime, - threshold - ) - const initialStates: InitialStates = new InitialStates() - initialStates.addOutput(vcapSecpOutput) - const memo: Buffer = Buffer.from( - "Manually create a CreateChainTx which creates a 1-of-2 AVAX utxo and instantiates a VM into a blockchain by correctly signing the 2-of-3 SubnetAuth" - ) - const genesisAsset = new GenesisAsset( - assetAlias, - name, - symbol, - denomination, - initialStates, - memo - ) - const genesisAssets: GenesisAsset[] = [] - genesisAssets.push(genesisAsset) - const genesisData: GenesisData = new GenesisData(genesisAssets, networkID) - const avaxAssetID: Buffer = await pchain.getAVAXAssetID() - const getBalanceResponse: any = await pchain.getBalance(pAddressStrings[0]) - const unlocked: BN = new BN(getBalanceResponse.unlocked) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - unlocked.sub(fee), - avaxUTXOKeychain, - locktime, - threshold - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const platformVMUTXOResponse: any = await pchain.getUTXOs( - avaxUTXOKeychainStrings - ) - const utxoSet: UTXOSet = platformVMUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO) => { - const output: Output = utxo.getOutput() - if (output.getOutputID() === 7) { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - secpTransferInput.addSignatureIdx(0, pAddresses[0]) - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetID, - secpTransferInput - ) - inputs.push(input) - } - }) - - const subnetID: Buffer = bintools.cb58Decode( - "yKRV4EvGYWj7HHXUxSYzaAQVazEvaFPKPhJie4paqbrML5dub" - ) - const chainName: string = "EPIC AVM" - const vmID: string = "avm" - const fxIDs: string[] = ["secp256k1fx", "nftfx", "propertyfx"] - fxIDs.sort() - const blockchainID: Buffer = bintools.cb58Decode(pChainBlockchainID) - const createChainTx: CreateChainTx = new CreateChainTx( - networkID, - blockchainID, - outputs, - inputs, - memo, - subnetID, - chainName, - vmID, - fxIDs, - genesisData - ) - - createChainTx.addSignatureIdx(0, pAddresses[3]) - createChainTx.addSignatureIdx(1, pAddresses[1]) - const unsignedTx: UnsignedTx = new UnsignedTx(createChainTx) - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/createKeypair.ts b/examples/platformvm/createKeypair.ts deleted file mode 100644 index 5e1191d49..000000000 --- a/examples/platformvm/createKeypair.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { - PlatformVMAPI, - KeyChain, - KeyPair -} from "avalanche/dist/apis/platformvm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() - -const main = async (): Promise => { - const keychain: KeyChain = pchain.keyChain() - const keypair: KeyPair = keychain.makeKey() - const response: { - address: string - publicKey: string - privateKey: string - } = { - address: keypair.getAddressString(), - publicKey: keypair.getPublicKeyString(), - privateKey: keypair.getPrivateKeyString() - } - console.log(response) -} - -main() diff --git a/examples/platformvm/createSubnetTx.ts b/examples/platformvm/createSubnetTx.ts deleted file mode 100644 index 04c15a01f..000000000 --- a/examples/platformvm/createSubnetTx.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "../../src" -import { - PlatformVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - CreateSubnetTx, - Tx, - SECPOwnerOutput -} from "../../src/apis/platformvm" -import { Output } from "../../src/common" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "../../src/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -const bintools: BinTools = BinTools.getInstance() -// Keychain with 4 keys-A, B, C, and D -const pKeychain: KeyChain = pchain.keyChain() -// Keypair A -let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -// P-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p -pKeychain.importKey(privKey) - -// Keypair B -privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4" -// P-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj -pKeychain.importKey(privKey) - -// Keypair C -privKey = "PrivateKey-24gdABgapjnsJfnYkfev6YPyQhTaCU72T9bavtDNTYivBLp2eW" -// P-custom1u6eth2fg33ye63mnyu5jswtj326jaypvhyar45 -pKeychain.importKey(privKey) - -// Keypair D -privKey = "PrivateKey-2uWuEQbY5t7NPzgqzDrXSgGPhi3uyKj2FeAvPUHYo6CmENHJfn" -// P-custom1t3qjau2pf3ys83yallqt4y5xc3l6ya5f7wr6aq -pKeychain.importKey(privKey) -const pAddresses: Buffer[] = pchain.keyChain().getAddresses() -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const pChainBlockchainID: string = Defaults.network[networkID].P.blockchainID -const pChainBlockchainIDBuf: Buffer = bintools.cb58Decode(pChainBlockchainID) -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = pchain.getCreateSubnetTxFee() -const threshold: number = 1 -const threshold2: number = 2 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "Manually create a CreateSubnetTx which creates a 1-of-2 AVAX utxo and a 2-of-3 SubnetAuth" -) -const avaxUTXOKeychain: Buffer[] = [pAddresses[0], pAddresses[1]] -const subnetAuthKeychain: Buffer[] = [ - pAddresses[1], - pAddresses[2], - pAddresses[3] -] - -const main = async (): Promise => { - const avaxAssetID: Buffer = await pchain.getAVAXAssetID() - const getBalanceResponse: any = await pchain.getBalance(pAddressStrings[0]) - const unlocked: BN = new BN(getBalanceResponse.unlocked) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - unlocked.sub(fee), - avaxUTXOKeychain, - locktime, - threshold - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const platformVMUTXOResponse: any = await pchain.getUTXOs(pAddressStrings) - const utxoSet: UTXOSet = platformVMUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO): void => { - const output: Output = utxo.getOutput() - if(output.getTypeID() === 7) { - const amountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - secpTransferInput.addSignatureIdx(0, pAddresses[0]) - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetID, - secpTransferInput - ) - inputs.push(input) - } - }) - - const subnetOwner: SECPOwnerOutput = new SECPOwnerOutput( - subnetAuthKeychain, - locktime, - threshold2 - ) - const createSubnetTx: CreateSubnetTx = new CreateSubnetTx( - networkID, - pChainBlockchainIDBuf, - outputs, - inputs, - memo, - subnetOwner - ) - - const unsignedTx: UnsignedTx = new UnsignedTx(createSubnetTx) - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/exportTx-AVAX-from-the-cchain-and-create-a-multisig-atomic-output.ts b/examples/platformvm/exportTx-AVAX-from-the-cchain-and-create-a-multisig-atomic-output.ts deleted file mode 100644 index 4697f6612..000000000 --- a/examples/platformvm/exportTx-AVAX-from-the-cchain-and-create-a-multisig-atomic-output.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { EVMAPI, KeyChain as EVMKeyChain } from "avalanche/dist/apis/evm" -import { - PlatformVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - ExportTx -} from "avalanche/dist/apis/platformvm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - MILLIAVAX -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const cchain: EVMAPI = avalanche.CChain() -const pchain: PlatformVMAPI = avalanche.PChain() -const bintools: BinTools = BinTools.getInstance() -const cKeychain: EVMKeyChain = cchain.keyChain() -const pKeychain: KeyChain = pchain.keyChain() -let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -// X-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p -cKeychain.importKey(privKey) -pKeychain.importKey(privKey) - -// let privKey: string = "PrivateKey-24gdABgapjnsJfnYkfev6YPyQhTaCU72T9bavtDNTYivBLp2eW" -// P-custom1u6eth2fg33ye63mnyu5jswtj326jaypvhyar45 - -// privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4" -// P-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj - -privKey = "PrivateKey-rKsiN3X4NSJcPpWxMSh7WcuY653NGQ7tfADgQwDZ9yyUPPDG9" -// P-custom1jwwk62ktygl0w29rsq2hq55amamhpvx82kfnte -cKeychain.importKey(privKey) -pKeychain.importKey(privKey) -const cAddresses: Buffer[] = cchain.keyChain().getAddresses() -const pAddresses: Buffer[] = pchain.keyChain().getAddresses() -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const cChainID: string = Defaults.network[networkID].C.blockchainID -const cChainIDBuf: Buffer = bintools.cb58Decode(cChainID) -const pChainID: string = Defaults.network[networkID].P.blockchainID -const pChainIDBuf: Buffer = bintools.cb58Decode(pChainID) -const exportedOuts: TransferableOutput[] = [] -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = MILLIAVAX -const threshold: number = 2 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "Export AVAX from P-Chain to C-Chain and consume a multisig output and create a multisig atomic output" -) - -const main = async (): Promise => { - const avaxAssetID: Buffer = await pchain.getAVAXAssetID() - const getBalanceResponse: any = await pchain.getBalance(pAddressStrings[0]) - const unlocked: BN = new BN(getBalanceResponse.unlocked) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - unlocked.sub(fee), - cAddresses, - locktime, - threshold - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - secpTransferOutput - ) - exportedOuts.push(transferableOutput) - - const platformVMUTXOResponse: any = await pchain.getUTXOs(pAddressStrings) - const utxoSet: UTXOSet = platformVMUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO): void => { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - secpTransferInput.addSignatureIdx(0, pAddresses[1]) - if (utxo.getOutput().getThreshold() === 2) { - secpTransferInput.addSignatureIdx(1, pAddresses[0]) - } - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetID, - secpTransferInput - ) - inputs.push(input) - }) - - const exportTx: ExportTx = new ExportTx( - networkID, - pChainIDBuf, - outputs, - inputs, - memo, - cChainIDBuf, - exportedOuts - ) - - const unsignedTx: UnsignedTx = new UnsignedTx(exportTx) - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/exportTx-cchain.ts b/examples/platformvm/exportTx-cchain.ts deleted file mode 100644 index a091d8ea8..000000000 --- a/examples/platformvm/exportTx-cchain.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { EVMAPI, KeyChain as EVMKeyChain } from "avalanche/dist/apis/evm" -import { - PlatformVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - ExportTx -} from "avalanche/dist/apis/platformvm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - MILLIAVAX -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const cchain: EVMAPI = avalanche.CChain() -const pchain: PlatformVMAPI = avalanche.PChain() -const bintools: BinTools = BinTools.getInstance() -const cKeychain: EVMKeyChain = cchain.keyChain() -const pKeychain: KeyChain = pchain.keyChain() -let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -// X-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p -cKeychain.importKey(privKey) -pKeychain.importKey(privKey) - -privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4" -// P-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj -cKeychain.importKey(privKey) -pKeychain.importKey(privKey) -const cAddresses: Buffer[] = cchain.keyChain().getAddresses() -const pAddresses: Buffer[] = pchain.keyChain().getAddresses() -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const cChainBlockchainID: string = Defaults.network[networkID].C.blockchainID -const pChainBlockchainID: string = Defaults.network[networkID].P.blockchainID -const exportedOuts: TransferableOutput[] = [] -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = MILLIAVAX -const threshold: number = 2 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from("Manually Export AVAX from P-Chain to C-Chain") - -const main = async (): Promise => { - const avaxAssetID: Buffer = await pchain.getAVAXAssetID() - const getBalanceResponse: any = await pchain.getBalance(pAddressStrings[0]) - const unlocked: BN = new BN(getBalanceResponse.unlocked) - console.log(unlocked.sub(fee).toString()) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - unlocked.sub(fee), - cAddresses, - locktime, - threshold - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - secpTransferOutput - ) - exportedOuts.push(transferableOutput) - - const platformVMUTXOResponse: any = await pchain.getUTXOs(pAddressStrings) - const utxoSet: UTXOSet = platformVMUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO): void => { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - secpTransferInput.addSignatureIdx(0, pAddresses[0]) - if (utxo.getOutput().getThreshold() === 2) { - secpTransferInput.addSignatureIdx(1, pAddresses[1]) - } - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetID, - secpTransferInput - ) - inputs.push(input) - }) - - const exportTx: ExportTx = new ExportTx( - networkID, - bintools.cb58Decode(pChainBlockchainID), - outputs, - inputs, - memo, - bintools.cb58Decode(cChainBlockchainID), - exportedOuts - ) - - const unsignedTx: UnsignedTx = new UnsignedTx(exportTx) - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/exportTx-xchain.ts b/examples/platformvm/exportTx-xchain.ts deleted file mode 100644 index 38db0a7a1..000000000 --- a/examples/platformvm/exportTx-xchain.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { AVMAPI, KeyChain as AVMKeyChain } from "avalanche/dist/apis/avm" -import { - PlatformVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - ExportTx -} from "avalanche/dist/apis/platformvm" -import { Output } from "avalanche/dist/common" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults, - MILLIAVAX -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const xchain: AVMAPI = avalanche.XChain() -const pchain: PlatformVMAPI = avalanche.PChain() -const bintools: BinTools = BinTools.getInstance() -const xKeychain: AVMKeyChain = xchain.keyChain() -const pKeychain: KeyChain = pchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -xKeychain.importKey(privKey) -pKeychain.importKey(privKey) -const xAddresses: Buffer[] = xchain.keyChain().getAddresses() -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const xChainBlockchainID: string = Defaults.network[networkID].X.blockchainID -const pChainBlockchainID: string = Defaults.network[networkID].P.blockchainID -const exportedOuts: TransferableOutput[] = [] -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = MILLIAVAX -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from("Manually Export AVAX from P-Chain to X-Chain") - -const main = async (): Promise => { - const avaxAssetID: Buffer = await pchain.getAVAXAssetID() - const getBalanceResponse: any = await pchain.getBalance(pAddressStrings[0]) - const unlocked: BN = new BN(getBalanceResponse.unlocked) - console.log(unlocked.sub(fee).toString()) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - unlocked.sub(fee), - xAddresses, - locktime, - threshold - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - secpTransferOutput - ) - exportedOuts.push(transferableOutput) - - const platformVMUTXOResponse: any = await pchain.getUTXOs(pAddressStrings) - const utxoSet: UTXOSet = platformVMUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO) => { - const output: Output = utxo.getOutput() - // if (output.getOutputID() === 7) { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - secpTransferInput.addSignatureIdx(0, xAddresses[0]) - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetID, - secpTransferInput - ) - inputs.push(input) - // } - }) - - const exportTx: ExportTx = new ExportTx( - networkID, - bintools.cb58Decode(pChainBlockchainID), - outputs, - inputs, - memo, - bintools.cb58Decode(xChainBlockchainID), - exportedOuts - ) - - const unsignedTx: UnsignedTx = new UnsignedTx(exportTx) - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/getBalance.ts b/examples/platformvm/getBalance.ts deleted file mode 100644 index 81ad2287e..000000000 --- a/examples/platformvm/getBalance.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { PlatformVMAPI } from "avalanche/dist/apis/platformvm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() - -const main = async (): Promise => { - const address: string = "P-local18jma8ppw3nhx5r4ap8clazz0dps7rv5u00z96u" - const balance: object = await pchain.getBalance(address) - console.log(balance) -} - -main() diff --git a/examples/platformvm/getBlockchainStatus.ts b/examples/platformvm/getBlockchainStatus.ts deleted file mode 100644 index 7b769bb0c..000000000 --- a/examples/platformvm/getBlockchainStatus.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { PlatformVMAPI } from "avalanche/dist/apis/platformvm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() - -const main = async (): Promise => { - const blockchainID: string = - "2AymB4Mb6mErFNsDB8aWb77Ui8oyogXgDyRe9RVQBtqfXzKoUc" - const blockchainStatus: string = await pchain.getBlockchainStatus( - blockchainID - ) - console.log(blockchainStatus) -} - -main() diff --git a/examples/platformvm/getBlockchains.ts b/examples/platformvm/getBlockchains.ts deleted file mode 100644 index 2608b5096..000000000 --- a/examples/platformvm/getBlockchains.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { PlatformVMAPI } from "avalanche/dist/apis/platformvm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() - -const main = async (): Promise => { - const blockchains: object[] = await pchain.getBlockchains() - console.log(blockchains) -} - -main() diff --git a/examples/platformvm/getCurrentSupply.ts b/examples/platformvm/getCurrentSupply.ts deleted file mode 100644 index 617cc9f49..000000000 --- a/examples/platformvm/getCurrentSupply.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche, BN } from "avalanche/dist" -import { PlatformVMAPI } from "avalanche/dist/apis/platformvm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() - -const main = async (): Promise => { - const currentSupply: BN = await pchain.getCurrentSupply() - console.log(currentSupply.toString()) -} - -main() diff --git a/examples/platformvm/getCurrentValidators.ts b/examples/platformvm/getCurrentValidators.ts deleted file mode 100644 index 182d10c88..000000000 --- a/examples/platformvm/getCurrentValidators.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { PlatformVMAPI } from "avalanche/dist/apis/platformvm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() - -const main = async (): Promise => { - const subnetID: string = "11111111111111111111111111111111LpoYY" - const nodeIDs: string[] = [] - const currentValidators: object = await pchain.getCurrentValidators(subnetID) - console.log(currentValidators) -} - -main() diff --git a/examples/platformvm/getInterfaces.ts b/examples/platformvm/getInterfaces.ts deleted file mode 100644 index 1885ffedc..000000000 --- a/examples/platformvm/getInterfaces.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { GetStakeParams } from "avalanche/dist/apis/platformvm" - -const main = async (): Promise => { - const getStakeParams: GetStakeParams = { - addresses: ["P-local18jma8ppw3nhx5r4ap8clazz0dps7rv5u00z96u"], - encoding: "cb58" - } - console.log(getStakeParams) -} - -main() diff --git a/examples/platformvm/getPendingValidators.ts b/examples/platformvm/getPendingValidators.ts deleted file mode 100644 index 54149cb1e..000000000 --- a/examples/platformvm/getPendingValidators.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { PlatformVMAPI } from "avalanche/dist/apis/platformvm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() - -const main = async (): Promise => { - const subnetID: string = "11111111111111111111111111111111LpoYY" - const nodeIDs: string[] = [] - const pendingValidators: object = await pchain.getPendingValidators(subnetID) - console.log(pendingValidators) -} - -main() diff --git a/examples/platformvm/getRewardUTXOs.ts b/examples/platformvm/getRewardUTXOs.ts deleted file mode 100644 index fb33a588b..000000000 --- a/examples/platformvm/getRewardUTXOs.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { GetRewardUTXOsResponse } from "avalanche/dist/apis/platformvm/interfaces" -import { PlatformVMAPI } from "avalanche/dist/apis/platformvm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() - -const main = async (): Promise => { - const txID: string = "2nmH8LithVbdjaXsxVQCQfXtzN9hBbmebrsaEYnLM9T32Uy2Y4" - const encoding: string = "hex" - const rewardUTXOs: GetRewardUTXOsResponse = await pchain.getRewardUTXOs( - txID, - encoding - ) - console.log(rewardUTXOs) -} - -main() diff --git a/examples/platformvm/getStake.ts b/examples/platformvm/getStake.ts deleted file mode 100644 index 56313a3be..000000000 --- a/examples/platformvm/getStake.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { PlatformVMAPI, KeyChain } from "avalanche/dist/apis/platformvm" -import { GetStakeResponse } from "avalanche/dist/apis/platformvm/interfaces" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -const pKeychain: KeyChain = pchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -pKeychain.importKey(privKey) -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const encoding: string = "hex" - -const main = async (): Promise => { - const getStakeResponse: GetStakeResponse = await pchain.getStake( - pAddressStrings, - encoding - ) - console.log(getStakeResponse) -} - -main() diff --git a/examples/platformvm/getStakingAssetID.ts b/examples/platformvm/getStakingAssetID.ts deleted file mode 100644 index 017b04809..000000000 --- a/examples/platformvm/getStakingAssetID.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { PlatformVMAPI } from "avalanche/dist/apis/platformvm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() - -const main = async (): Promise => { - const stakingAssetID: string = await pchain.getStakingAssetID() - console.log(stakingAssetID) -} - -main() diff --git a/examples/platformvm/getSubnets.ts b/examples/platformvm/getSubnets.ts deleted file mode 100644 index 656be271a..000000000 --- a/examples/platformvm/getSubnets.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { PlatformVMAPI } from "avalanche/dist/apis/platformvm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() - -const main = async (): Promise => { - const ids: string[] = [] - const subnets: object[] = await pchain.getSubnets(ids) - console.log(subnets) -} - -main() diff --git a/examples/platformvm/getTx.ts b/examples/platformvm/getTx.ts deleted file mode 100644 index 81ee0a29f..000000000 --- a/examples/platformvm/getTx.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { PlatformVMAPI } from "avalanche/dist/apis/platformvm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() - -const main = async (): Promise => { - const txID: string = "2T7F1AzTLPzZrUcw22JLcC8yZ8o2muhjrM5zoQ3TBuENbAUvZd" - const encoding: string = "json" - const tx: string | object = await pchain.getTx(txID, encoding) - console.log(tx) -} - -main() diff --git a/examples/platformvm/getTxStatus.ts b/examples/platformvm/getTxStatus.ts deleted file mode 100644 index 254bed58a..000000000 --- a/examples/platformvm/getTxStatus.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { PlatformVMAPI } from "avalanche/dist/apis/platformvm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() - -const main = async (): Promise => { - const txID: string = "x1NLb9JaHkKTXvSRReVSsFwQ38mY7bfD1Ky1BPv721VhrpuSE" - const includeReason: boolean = true - const tx: string | object = await pchain.getTxStatus(txID, includeReason) - console.log(tx) -} - -main() diff --git a/examples/platformvm/getValidatorsAt.ts b/examples/platformvm/getValidatorsAt.ts deleted file mode 100644 index c1c7dacfd..000000000 --- a/examples/platformvm/getValidatorsAt.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Avalanche } from "avalanche/dist" -import { GetValidatorsAtResponse } from "avalanche/dist/apis/platformvm/interfaces" -import { PlatformVMAPI } from "avalanche/dist/apis/platformvm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() - -const main = async (): Promise => { - const height: number = 0 - const subnetID: string = "11111111111111111111111111111111LpoYY" - const validators: GetValidatorsAtResponse = await pchain.getValidatorsAt( - height, - subnetID - ) - console.log(validators) -} - -main() diff --git a/examples/platformvm/importTx-avax-cchain-create-multisig.ts b/examples/platformvm/importTx-avax-cchain-create-multisig.ts deleted file mode 100644 index 77e86b0ec..000000000 --- a/examples/platformvm/importTx-avax-cchain-create-multisig.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - PlatformVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - ImportTx -} from "avalanche/dist/apis/platformvm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -const bintools: BinTools = BinTools.getInstance() -const pKeychain: KeyChain = pchain.keyChain() -let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -// X-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p -pKeychain.importKey(privKey) - -// let privKey: string = "PrivateKey-24gdABgapjnsJfnYkfev6YPyQhTaCU72T9bavtDNTYivBLp2eW" -// P-custom1u6eth2fg33ye63mnyu5jswtj326jaypvhyar45 - -// privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4" -// P-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj - -privKey = "PrivateKey-rKsiN3X4NSJcPpWxMSh7WcuY653NGQ7tfADgQwDZ9yyUPPDG9" -// P-custom1jwwk62ktygl0w29rsq2hq55amamhpvx82kfnte -pKeychain.importKey(privKey) -const pAddresses: Buffer[] = pchain.keyChain().getAddresses() -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const cChainID: string = Defaults.network[networkID].C.blockchainID -const cChainIDBuf: Buffer = bintools.cb58Decode(cChainID) -const pChainID: string = Defaults.network[networkID].P.blockchainID -const pChainIDBuf: Buffer = bintools.cb58Decode(pChainID) -const importedInputs: TransferableInput[] = [] -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = pchain.getDefaultTxFee() -const threshold: number = 2 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "Import AVAX to the P-Chain from the C-Chain and consume a multisig atomic output and a create multisig output" -) - -const main = async (): Promise => { - const avaxAssetID: Buffer = await pchain.getAVAXAssetID() - const platformvmUTXOResponse: any = await pchain.getUTXOs( - pAddressStrings, - cChainID - ) - const utxoSet: UTXOSet = platformvmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - let amount: BN = new BN(0) - utxos.forEach((utxo: UTXO): void => { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - const assetID: Buffer = utxo.getAssetID() - - if (avaxAssetID.toString("hex") === assetID.toString("hex")) { - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - secpTransferInput.addSignatureIdx(0, pAddresses[1]) - secpTransferInput.addSignatureIdx(1, pAddresses[0]) - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetID, - secpTransferInput - ) - importedInputs.push(input) - amount = amount.add(amt) - } - }) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - amount.sub(fee), - pAddresses, - locktime, - threshold - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const importTx: ImportTx = new ImportTx( - networkID, - pChainIDBuf, - outputs, - inputs, - memo, - cChainIDBuf, - importedInputs - ) - - const unsignedTx: UnsignedTx = new UnsignedTx(importTx) - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/importTx-avax-from-the-xchain-and-create-a-multisig-utxo.ts b/examples/platformvm/importTx-avax-from-the-xchain-and-create-a-multisig-utxo.ts deleted file mode 100644 index 927b81587..000000000 --- a/examples/platformvm/importTx-avax-from-the-xchain-and-create-a-multisig-utxo.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - PlatformVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - ImportTx -} from "avalanche/dist/apis/platformvm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -const bintools: BinTools = BinTools.getInstance() -const pKeychain: KeyChain = pchain.keyChain() -let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -// X-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p -pKeychain.importKey(privKey) - -privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4" -// P-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj -pKeychain.importKey(privKey) - -privKey = "PrivateKey-rKsiN3X4NSJcPpWxMSh7WcuY653NGQ7tfADgQwDZ9yyUPPDG9" -// P-custom1jwwk62ktygl0w29rsq2hq55amamhpvx82kfnte -pKeychain.importKey(privKey) -const pAddresses: Buffer[] = pchain.keyChain().getAddresses() -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const xChainID: string = Defaults.network[networkID].X.blockchainID -const xChainIDBuf: Buffer = bintools.cb58Decode(xChainID) -const pChainID: string = Defaults.network[networkID].P.blockchainID -const pChainIDBuf: Buffer = bintools.cb58Decode(pChainID) -const importedInputs: TransferableInput[] = [] -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = pchain.getDefaultTxFee() -const threshold: number = 2 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "Import AVAX to P-Chain from X-Chain and consume a multisig atomic output and create a multisig utxo" -) - -const main = async (): Promise => { - const avaxAssetID: Buffer = await pchain.getAVAXAssetID() - const platformvmUTXOResponse: any = await pchain.getUTXOs( - pAddressStrings, - xChainID - ) - const utxoSet: UTXOSet = platformvmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - let amount: BN = new BN(0) - utxos.forEach((utxo: UTXO): void => { - console.log(utxo.getOutput().getAddresses()) - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - const assetID: Buffer = utxo.getAssetID() - - if (avaxAssetID.toString("hex") === assetID.toString("hex")) { - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - secpTransferInput.addSignatureIdx(1, pAddresses[2]) - secpTransferInput.addSignatureIdx(2, pAddresses[1]) - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetID, - secpTransferInput - ) - importedInputs.push(input) - amount = amount.add(amt) - } - }) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - amount.sub(fee), - pAddresses, - locktime, - threshold - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const importTx: ImportTx = new ImportTx( - networkID, - pChainIDBuf, - outputs, - inputs, - memo, - xChainIDBuf, - importedInputs - ) - - const unsignedTx: UnsignedTx = new UnsignedTx(importTx) - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/importTx-avax-to-the-P-Chain-from-the-C-Chain-and-consume-a-multisig-atomic-output-and-a-create-multisig-output.ts b/examples/platformvm/importTx-avax-to-the-P-Chain-from-the-C-Chain-and-consume-a-multisig-atomic-output-and-a-create-multisig-output.ts deleted file mode 100644 index 77e86b0ec..000000000 --- a/examples/platformvm/importTx-avax-to-the-P-Chain-from-the-C-Chain-and-consume-a-multisig-atomic-output-and-a-create-multisig-output.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - PlatformVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - ImportTx -} from "avalanche/dist/apis/platformvm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -const bintools: BinTools = BinTools.getInstance() -const pKeychain: KeyChain = pchain.keyChain() -let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -// X-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p -pKeychain.importKey(privKey) - -// let privKey: string = "PrivateKey-24gdABgapjnsJfnYkfev6YPyQhTaCU72T9bavtDNTYivBLp2eW" -// P-custom1u6eth2fg33ye63mnyu5jswtj326jaypvhyar45 - -// privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4" -// P-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj - -privKey = "PrivateKey-rKsiN3X4NSJcPpWxMSh7WcuY653NGQ7tfADgQwDZ9yyUPPDG9" -// P-custom1jwwk62ktygl0w29rsq2hq55amamhpvx82kfnte -pKeychain.importKey(privKey) -const pAddresses: Buffer[] = pchain.keyChain().getAddresses() -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const cChainID: string = Defaults.network[networkID].C.blockchainID -const cChainIDBuf: Buffer = bintools.cb58Decode(cChainID) -const pChainID: string = Defaults.network[networkID].P.blockchainID -const pChainIDBuf: Buffer = bintools.cb58Decode(pChainID) -const importedInputs: TransferableInput[] = [] -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = pchain.getDefaultTxFee() -const threshold: number = 2 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "Import AVAX to the P-Chain from the C-Chain and consume a multisig atomic output and a create multisig output" -) - -const main = async (): Promise => { - const avaxAssetID: Buffer = await pchain.getAVAXAssetID() - const platformvmUTXOResponse: any = await pchain.getUTXOs( - pAddressStrings, - cChainID - ) - const utxoSet: UTXOSet = platformvmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - let amount: BN = new BN(0) - utxos.forEach((utxo: UTXO): void => { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - const assetID: Buffer = utxo.getAssetID() - - if (avaxAssetID.toString("hex") === assetID.toString("hex")) { - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - secpTransferInput.addSignatureIdx(0, pAddresses[1]) - secpTransferInput.addSignatureIdx(1, pAddresses[0]) - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetID, - secpTransferInput - ) - importedInputs.push(input) - amount = amount.add(amt) - } - }) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - amount.sub(fee), - pAddresses, - locktime, - threshold - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const importTx: ImportTx = new ImportTx( - networkID, - pChainIDBuf, - outputs, - inputs, - memo, - cChainIDBuf, - importedInputs - ) - - const unsignedTx: UnsignedTx = new UnsignedTx(importTx) - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/importTx-xchain.ts b/examples/platformvm/importTx-xchain.ts deleted file mode 100644 index cab84a281..000000000 --- a/examples/platformvm/importTx-xchain.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "avalanche/dist" -import { - PlatformVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - ImportTx -} from "avalanche/dist/apis/platformvm" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - Defaults -} from "avalanche/dist/utils" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -const bintools: BinTools = BinTools.getInstance() -const pKeychain: KeyChain = pchain.keyChain() -const privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -pKeychain.importKey(privKey) -const pAddresses: Buffer[] = pchain.keyChain().getAddresses() -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const xChainID: string = Defaults.network[networkID].X.blockchainID -const pChainID: string = Defaults.network[networkID].P.blockchainID -const importedInputs: TransferableInput[] = [] -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = pchain.getDefaultTxFee() -const threshold: number = 1 -const locktime: BN = new BN(0) -const memo: Buffer = Buffer.from( - "Manually Import AVAX to the P-Chain from the X-Chain" -) - -const main = async (): Promise => { - const avaxAssetID: Buffer = await pchain.getAVAXAssetID() - const platformvmUTXOResponse: any = await pchain.getUTXOs( - pAddressStrings, - xChainID - ) - const utxoSet: UTXOSet = platformvmUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - let amount: BN = new BN(0) - utxos.forEach((utxo: UTXO) => { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - const assetID: Buffer = utxo.getAssetID() - - if (avaxAssetID.toString("hex") === assetID.toString("hex")) { - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - secpTransferInput.addSignatureIdx(0, pAddresses[0]) - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetID, - secpTransferInput - ) - importedInputs.push(input) - amount = amount.add(amt) - } - }) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - amount.sub(fee), - pAddresses, - locktime, - threshold - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const importTx: ImportTx = new ImportTx( - networkID, - bintools.cb58Decode(pChainID), - outputs, - inputs, - memo, - bintools.cb58Decode(xChainID), - importedInputs - ) - - const unsignedTx: UnsignedTx = new UnsignedTx(importTx) - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/proofOfPossession.ts b/examples/platformvm/proofOfPossession.ts deleted file mode 100644 index 7c4c852c3..000000000 --- a/examples/platformvm/proofOfPossession.ts +++ /dev/null @@ -1,44 +0,0 @@ -// using https://www.npmjs.com/package/@noble/bls12-381 -// import { getPublicKey, sign, verify } from "@noble/bls12-381" -import { Avalanche, Buffer } from "../../src" -import { - KeyChain, - KeyPair, - PlatformVMAPI, - ProofOfPossession -} from "../../src/apis/platformvm" - -// start placeholder functions -const getPublicKey = (privateKey): Buffer => {return new Buffer("00")} -const sign = (publicKey, privateKey): Buffer => {return new Buffer("00")} -const verify = (signature, message, publicKey): boolean => {return true} -// end placeholder functions - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -const keychain: KeyChain = pchain.keyChain() -const keypair: KeyPair = keychain.makeKey() - -const main = async (): Promise => { - const privateKey: string = keypair.getPrivateKey().toString("hex") - // 48 byte public key - const publicKey = getPublicKey(privateKey) as Buffer - // 96 byte signature - const signature = await sign(publicKey, privateKey) as Buffer - const proofOfPossession: ProofOfPossession = new ProofOfPossession( - publicKey, - signature - ) - const isValid: boolean = await verify(signature, publicKey, publicKey) - console.log(isValid) - const pubKey: Buffer = proofOfPossession.getPublicKey() - const sig: Buffer = proofOfPossession.getSignature() - console.log(`Public Key:`, pubKey === publicKey) - console.log(`Signature:`, sig === signature) -} - -main() diff --git a/examples/platformvm/removeSubnetValidatorTx.ts b/examples/platformvm/removeSubnetValidatorTx.ts deleted file mode 100644 index 539dcb7ba..000000000 --- a/examples/platformvm/removeSubnetValidatorTx.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { Avalanche, BinTools, BN, Buffer } from "../../src" -import { - PlatformVMAPI, - KeyChain, - SECPTransferOutput, - SECPTransferInput, - TransferableOutput, - TransferableInput, - UTXOSet, - UTXO, - AmountOutput, - UnsignedTx, - Tx, - RemoveSubnetValidatorTx -} from "../../src/apis/platformvm" -import { Output } from "../../src/common" -import { - PrivateKeyPrefix, - DefaultLocalGenesisPrivateKey, - NodeIDStringToBuffer, - Defaults -} from "../../src/utils" - -const bintools: BinTools = BinTools.getInstance() -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1337 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const pchain: PlatformVMAPI = avalanche.PChain() -// Keychain with 4 keys-A, B, C, and D -const pKeychain: KeyChain = pchain.keyChain() -// Keypair A -let privKey: string = `${PrivateKeyPrefix}${DefaultLocalGenesisPrivateKey}` -// P-custom18jma8ppw3nhx5r4ap8clazz0dps7rv5u9xde7p -pKeychain.importKey(privKey) - -// Keypair B -privKey = "PrivateKey-R6e8f5QSa89DjpvL9asNdhdJ4u8VqzMJStPV8VVdDmLgPd8a4" -// P-custom15s7p7mkdev0uajrd0pzxh88kr8ryccztnlmzvj -pKeychain.importKey(privKey) - -// Keypair C -privKey = "PrivateKey-24gdABgapjnsJfnYkfev6YPyQhTaCU72T9bavtDNTYivBLp2eW" -// P-custom1u6eth2fg33ye63mnyu5jswtj326jaypvhyar45 -pKeychain.importKey(privKey) - -// Keypair D -privKey = "PrivateKey-2uWuEQbY5t7NPzgqzDrXSgGPhi3uyKj2FeAvPUHYo6CmENHJfn" -// P-custom1t3qjau2pf3ys83yallqt4y5xc3l6ya5f7wr6aq -pKeychain.importKey(privKey) -const pAddresses: Buffer[] = pchain.keyChain().getAddresses() -const pAddressStrings: string[] = pchain.keyChain().getAddressStrings() -const pChainBlockchainID: string = Defaults.network[networkID].P.blockchainID -const pChainBlockchainIDBuf: Buffer = bintools.cb58Decode(pChainBlockchainID) -const outputs: TransferableOutput[] = [] -const inputs: TransferableInput[] = [] -const fee: BN = pchain.getDefaultTxFee() -const threshold: number = 1 -const locktime: BN = new BN(0) -const nodeID: string = "NodeID-NFBbbJ4qCmNaCzeW7sxErhvWqvEQMnYcN" -const memo: Buffer = Buffer.from( - "Manually create a removeSubnetValidatorTx which creates a 1-of-2 AVAX utxo and removes a validator from a subnet by correctly signing the 2-of-3 SubnetAuth" -) -const avaxUTXOKeychain: Buffer[] = [pAddresses[0], pAddresses[1]] - -const main = async (): Promise => { - const avaxAssetID: Buffer = await pchain.getAVAXAssetID() - const getBalanceResponse: any = await pchain.getBalance(pAddressStrings[0]) - const unlocked: BN = new BN(getBalanceResponse.unlocked) - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - unlocked.sub(fee), - avaxUTXOKeychain, - locktime, - threshold - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - secpTransferOutput - ) - outputs.push(transferableOutput) - - const platformVMUTXOResponse: any = await pchain.getUTXOs(pAddressStrings) - const utxoSet: UTXOSet = platformVMUTXOResponse.utxos - const utxos: UTXO[] = utxoSet.getAllUTXOs() - utxos.forEach((utxo: UTXO): void => { - const output: Output = utxo.getOutput() - if(output.getTypeID() === 7) { - const amountOutput: AmountOutput = utxo.getOutput() as AmountOutput - const amt: BN = amountOutput.getAmount().clone() - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - - const secpTransferInput: SECPTransferInput = new SECPTransferInput(amt) - secpTransferInput.addSignatureIdx(0, pAddresses[0]) - - const input: TransferableInput = new TransferableInput( - txid, - outputidx, - avaxAssetID, - secpTransferInput - ) - inputs.push(input) - } - }) - - const subnetID: Buffer = bintools.cb58Decode( - "8T4oUrP7kXzetGF2bYWF21oJHUT18rJCjfBt3J299hA1Smcqa" - ) - const nodeIDBuf: Buffer = NodeIDStringToBuffer(nodeID) - const removeSubnetValidatorTx: RemoveSubnetValidatorTx = new RemoveSubnetValidatorTx( - networkID, - pChainBlockchainIDBuf, - outputs, - inputs, - memo, - nodeIDBuf, - subnetID - ) - removeSubnetValidatorTx.addSignatureIdx(0, pAddresses[3]) - removeSubnetValidatorTx.addSignatureIdx(1, pAddresses[1]) - const unsignedTx: UnsignedTx = new UnsignedTx(removeSubnetValidatorTx) - const tx: Tx = unsignedTx.sign(pKeychain) - const txid: string = await pchain.issueTx(tx) - console.log(`Success! TXID: ${txid}`) -} - -main() diff --git a/examples/platformvm/subnetAuth.ts b/examples/platformvm/subnetAuth.ts deleted file mode 100644 index b8dd78b07..000000000 --- a/examples/platformvm/subnetAuth.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { Buffer } from "avalanche/dist" -import { SubnetAuth } from "avalanche/dist/apis/platformvm" - -const address1: Buffer = Buffer.alloc(4) -const address2: Buffer = Buffer.alloc(4) -address2.writeUIntBE(0x01, 0, 4) -const addresses: Buffer[] = [address1, address2] -const subnetAuth: SubnetAuth = new SubnetAuth(addresses) - -const main = async (): Promise => { - console.log(subnetAuth) - const typeName: string = subnetAuth.getTypeName() - const typeID: number = subnetAuth.getTypeID() - const numAddressIndices: number = subnetAuth.getNumAddressIndices() - console.log("TypeName: ", typeName) - console.log("TypeID: ", typeID) - console.log("NumAddressIndices: ", numAddressIndices) -} - -main() diff --git a/examples/pubsub/README.md b/examples/pubsub/README.md deleted file mode 100644 index 0f78e23f9..000000000 --- a/examples/pubsub/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# PubSub Utility - -Example scripts for the Avalanche PubSub Utility - -* [addAddresses.ts](./addAddresses.ts) -* [newBloom.ts](./newBloom.ts) -* [newSet.ts](./newSet.ts) diff --git a/examples/pubsub/addAddresses.ts b/examples/pubsub/addAddresses.ts deleted file mode 100644 index e3aad5105..000000000 --- a/examples/pubsub/addAddresses.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { PubSub } from "avalanche/dist" - -const main = async (): Promise => { - const pubsub: PubSub = new PubSub() - const addresses: string[] = ["X-avax1wst8jt3z3fm9ce0z6akj3266zmgccdp03hjlaj"] - const addAddresses: string = pubsub.addAddresses(addresses) - console.log(addAddresses) -} - -main() diff --git a/examples/pubsub/newBloom.ts b/examples/pubsub/newBloom.ts deleted file mode 100644 index 9da08aa4a..000000000 --- a/examples/pubsub/newBloom.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { PubSub } from "avalanche/dist" - -const main = async (): Promise => { - const pubsub: PubSub = new PubSub() - const maxElements: number = 1000 - const collisionProb: number = 0.0001 - const newBloom: string = pubsub.newBloom() - console.log(newBloom) -} - -main() diff --git a/examples/pubsub/newSet.ts b/examples/pubsub/newSet.ts deleted file mode 100644 index 13be7acba..000000000 --- a/examples/pubsub/newSet.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { PubSub } from "avalanche/dist" - -const main = async (): Promise => { - const pubsub: PubSub = new PubSub() - const newSet: string = pubsub.newSet() - console.log(newSet) -} - -main() diff --git a/examples/secrets.example b/examples/secrets.example deleted file mode 100644 index 25e59edbe..000000000 --- a/examples/secrets.example +++ /dev/null @@ -1,7 +0,0 @@ -{ - "newPassword": "newPassword", - "oldPassword": "oldPassword", - "password": "password", - "token": "token", - "user": "user" -} \ No newline at end of file diff --git a/examples/socket/README.md b/examples/socket/README.md deleted file mode 100644 index 39239af2d..000000000 --- a/examples/socket/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# Socket API - -Example scripts for the Avalanche [Socket](https://docs.avax.network/build/avalanchego-apis/exchange-chain-x-chain-api#events) API - -* [newBloom.ts](./newBloom.ts) -* [newSet.ts](./newSet.ts) diff --git a/examples/socket/newBloom.ts b/examples/socket/newBloom.ts deleted file mode 100644 index d7db53522..000000000 --- a/examples/socket/newBloom.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { PubSub, Socket } from "avalanche/dist" - -const protocol: string = "ws" -const host: string = "localhost" -const port: number = 9650 -const addresses: string[] = ["X-local18jma8ppw3nhx5r4ap8clazz0dps7rv5u00z96u"] - -const main = async (): Promise => { - const pubsub: PubSub = new PubSub() - const newBloom: string = pubsub.newBloom() - const addAddresses: string = pubsub.addAddresses(addresses) - const socket: Socket = new Socket( - `${protocol}://${host}:${port}/ext/bc/X/events` - ) - socket.onopen = () => { - console.log("Socket Connected") - socket.send(newBloom) - socket.send(addAddresses) - } - socket.onmessage = (msg: any) => { - console.log(msg.data) - socket.close() - } - socket.onclose = () => { - console.log("Socket Disconnected") - } - socket.onerror = (error: any) => { - console.log(error) - } -} - -main() diff --git a/examples/socket/newSet.ts b/examples/socket/newSet.ts deleted file mode 100644 index d52203a17..000000000 --- a/examples/socket/newSet.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { PubSub, Socket } from "avalanche/dist" - -const protocol: string = "ws" -const host: string = "localhost" -const port: number = 9650 -const addresses: string[] = ["X-local18jma8ppw3nhx5r4ap8clazz0dps7rv5u00z96u"] - -const main = async (): Promise => { - const pubsub: PubSub = new PubSub() - const newSet: string = pubsub.newSet() - const addAddresses: string = pubsub.addAddresses(addresses) - const socket: Socket = new Socket( - `${protocol}://${host}:${port}/ext/bc/X/events` - ) - socket.onopen = () => { - console.log("Socket Connected") - socket.send(newSet) - socket.send(addAddresses) - } - socket.onmessage = (msg: any) => { - console.log(msg.data) - socket.close() - } - socket.onclose = () => { - console.log("Socket Disconnected") - } - socket.onerror = (error: any) => { - console.log(error) - } -} - -main() diff --git a/examples/utils/getChainIdFromContext.ts b/examples/utils/getChainIdFromContext.ts new file mode 100644 index 000000000..efa25274e --- /dev/null +++ b/examples/utils/getChainIdFromContext.ts @@ -0,0 +1,12 @@ +import type { Context } from '../../src/vms/context'; + +export function getChainIdFromContext( + sourceChain: 'X' | 'P' | 'C', + context: Context, +) { + return sourceChain === 'C' + ? context.cBlockchainID + : sourceChain === 'P' + ? context.pBlockchainID + : context.xBlockchainID; +} diff --git a/examples/x-chain/export.ts b/examples/x-chain/export.ts new file mode 100644 index 000000000..38864b1f5 --- /dev/null +++ b/examples/x-chain/export.ts @@ -0,0 +1,44 @@ +import { TransferableOutput } from '../../src/serializable/avax'; +import { addTxSignatures } from '../../src/signer'; +import { bech32ToBytes, hexToBuffer } from '../../src/utils'; +import { newExportTx } from '../../src/vms/avm'; +import { getContextFromURI } from '../../src/vms/context'; +import { avmapi } from '../chain_apis'; +import { getChainIdFromContext } from '../utils/getChainIdFromContext'; + +const P_CHAIN_ADDRESS = process.env.P_CHAIN_ADDRESS; +const X_CHAIN_ADDRESS = process.env.X_CHAIN_ADDRESS; +const PRIVATE_KEY = process.env.PRIVATE_KEY; + +const main = async () => { + if (!P_CHAIN_ADDRESS || !X_CHAIN_ADDRESS || !PRIVATE_KEY) { + throw new Error('Missing environment variable(s).'); + } + + const context = await getContextFromURI(process.env.AVAX_PUBLIC_URL); + + const { utxos } = await avmapi.getUTXOs({ + addresses: [X_CHAIN_ADDRESS], + }); + + const tx = newExportTx( + context, + getChainIdFromContext('P', context), + [bech32ToBytes(X_CHAIN_ADDRESS)], + utxos, + [ + TransferableOutput.fromNative(context.avaxAssetID, BigInt(0.1 * 1e9), [ + bech32ToBytes(P_CHAIN_ADDRESS), + ]), + ], + ); + + await addTxSignatures({ + unsignedTx: tx, + privateKeys: [hexToBuffer(PRIVATE_KEY)], + }); + + return avmapi.issueSignedTx(tx.getSignedTx()); +}; + +main().then(console.log); diff --git a/examples/x-chain/import.ts b/examples/x-chain/import.ts new file mode 100644 index 000000000..88f5c8bc3 --- /dev/null +++ b/examples/x-chain/import.ts @@ -0,0 +1,40 @@ +import { addTxSignatures } from '../../src/signer'; +import { bech32ToBytes, hexToBuffer } from '../../src/utils'; +import { newImportTx } from '../../src/vms/avm'; +import { getContextFromURI } from '../../src/vms/context'; +import { avmapi } from '../chain_apis'; +import { getChainIdFromContext } from '../utils/getChainIdFromContext'; + +const P_CHAIN_ADDRESS = process.env.P_CHAIN_ADDRESS; +const X_CHAIN_ADDRESS = process.env.X_CHAIN_ADDRESS; +const PRIVATE_KEY = process.env.PRIVATE_KEY; + +export const main = async () => { + if (!P_CHAIN_ADDRESS || !X_CHAIN_ADDRESS || !PRIVATE_KEY) { + throw new Error('Missing environment variable(s).'); + } + + const context = await getContextFromURI(process.env.AVAX_PUBLIC_URL); + + const { utxos } = await avmapi.getUTXOs({ + sourceChain: 'P', + addresses: [X_CHAIN_ADDRESS], + }); + + const tx = newImportTx( + context, + getChainIdFromContext('P', context), + utxos, + [bech32ToBytes(X_CHAIN_ADDRESS)], + [bech32ToBytes(P_CHAIN_ADDRESS)], + ); + + await addTxSignatures({ + unsignedTx: tx, + privateKeys: [hexToBuffer(PRIVATE_KEY)], + }); + + return avmapi.issueSignedTx(tx.getSignedTx()); +}; + +main().then(console.log); diff --git a/jest.config.js b/jest.config.js deleted file mode 100644 index d5f5eeaab..000000000 --- a/jest.config.js +++ /dev/null @@ -1,28 +0,0 @@ -module.exports = { - preset: "ts-jest", - verbose: true, - testEnvironment: "node", - roots: ["/src", "/tests", "/__mocks__"], - testMatch: [ - "**/__tests__/**/*.+(ts|tsx|js)", - "**/?(*.)+(spec|test).+(ts|tsx|js)" - ], - transform: { - "^.+\\.(ts|tsx)$": "ts-jest" - }, - transformIgnorePatterns: ["/node_modules/"], - moduleFileExtensions: ["ts", "tsx", "js", "jsx"], - moduleDirectories: ["node_modules", "src"], - collectCoverage: true, - coverageReporters: ["html"], - modulePathIgnorePatterns: ["node_modules"], - globals: { - "ts-jest": { - tsconfig: "tsconfig.json" - } - }, - moduleNameMapper: { - "^src(.*)$": "/src$1" - }, - testSequencer: "/e2eSequencer.js" -} diff --git a/jest.config.ts b/jest.config.ts new file mode 100644 index 000000000..6d70b66db --- /dev/null +++ b/jest.config.ts @@ -0,0 +1,18 @@ +/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ +module.exports = { + moduleFileExtensions: ['js', 'json', 'ts'], + rootDir: 'src', + transform: { + '^.+\\.tsx?$': [ + 'ts-jest', + { + useESM: true, + }, + ], + }, + collectCoverageFrom: ['**/*.(t|j)s'], + coverageDirectory: '../coverage', + testEnvironment: 'node', + coverageProvider: 'v8', + extensionsToTreatAsEsm: ['.ts'], +}; diff --git a/package.json b/package.json index ceca4f593..787b89e65 100644 --- a/package.json +++ b/package.json @@ -1,21 +1,88 @@ { "name": "@avalabs/avalanchejs", - "version": "3.17.0", + "version": "4.0.0", "description": "Avalanche Platform JS Library", "main": "dist/index.js", + "types": "dist/index.d.ts", + "typings": "dist/index.d.ts", + "type": "module", + "exports": { + "import": "./dist/es/index.js", + "require": "./dist/index.js" + }, + "publishConfig": { + "access": "restricted" + }, + "files": [ + "dist", + "src" + ], + "sideEffects": false, + "module": "dist/es/index.js", "scripts": { - "build": "rm -rf dist/ && npx tsc -b", - "prebundle": "yarn build", - "bundle": "webpack --mode production", - "lint": "eslint ./ --ext js,ts --fix", - "prepublish": "yarn build", - "release:prepare": "rm -rf ./dist ./node_modules && yarn install && yarn test && yarn build && yarn bundle && git status", - "test": "jest", - "test-watch": "jest --watch", - "docs": "rm -rf docsMD && yarn build && npx typedoc --readme none --theme markdown --out docs", - "prettier": "npx prettier --write .", + "start": "rollup -c --watch", + "build": "rollup -c", + "build:prod": "rollup -c --environment BUILD:production", + "test": "NODE_OPTIONS=--experimental-vm-modules jest", + "test:path": "NODE_OPTIONS=--experimental-vm-modules jest --watch --testPathPattern", + "test:cov": "NODE_OPTIONS=--experimental-vm-modules jest --collect-coverage=true", + "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch", + "lint": "eslint --fix --ignore-path .gitignore \"./**/*.ts*\"", + "lint:check": "eslint --ignore-path .gitignore \"./**/*.ts*\"", + "typecheck": "tsc --skipLibCheck --noEmit", + "example": "NODE_OPTIONS='--loader ts-node/esm' ts-node examples/c-chain/export.ts", "prepare": "husky install" }, + "dependencies": { + "@noble/hashes": "1.3.3", + "@noble/secp256k1": "2.0.0", + "@scure/base": "1.1.5", + "micro-eth-signer": "0.7.2" + }, + "devDependencies": { + "@commitlint/cli": "17.7.1", + "@commitlint/config-conventional": "17.7.0", + "@jest/globals": "29.7.0", + "@rollup/plugin-node-resolve": "15.2.3", + "@rollup/plugin-terser": "0.4.3", + "@rollup/plugin-typescript": "11.1.6", + "@semantic-release/changelog": "6.0.3", + "@semantic-release/commit-analyzer": "11.1.0", + "@semantic-release/git": "10.0.1", + "@semantic-release/github": "9.2.6", + "@semantic-release/npm": "11.0.2", + "@types/node": "20.11.10", + "@types/jest": "29.5.11", + "@typescript-eslint/eslint-plugin": "6.18.1", + "@typescript-eslint/parser": "6.18.1", + "commitizen": "4.3.0", + "cz-conventional-changelog": "3.3.0", + "dotenv": "16.4.2", + "eslint": "8.49.0", + "eslint-config-prettier": "9.1.0", + "eslint-plugin-prettier": "4.2.1", + "ethers": "6.11.0", + "husky": "8.0.3", + "jest": "29.7.0", + "jest-mock": "29.7.0", + "lint-staged": "15.2.2", + "node-fetch": "3.3.2", + "prettier": "2.8.7", + "rollup": "4.9.6", + "rollup-plugin-filesize": "10.0.0", + "semantic-release": "21.0.1", + "ts-jest": "29.1.2", + "ts-node": "10.9.2", + "typescript": "5.3.3" + }, + "packageManager": "yarn@1.22.19", + "engines": { + "node": "^20" + }, + "volta": { + "node": "20.11.0", + "yarn": "1.22.19" + }, "repository": { "type": "git", "url": "git+https://github.com/ava-labs/avalanchejs.git" @@ -25,84 +92,18 @@ "blockchain", "defi" ], - "author": "Gabriel Cardona ", - "contributors": [ - "Evan Richard ", - "Paul Kim ", - "Raj Ranjan ", - "Gergely Lovas ", - "Dhruba Basu " - ], - "license": "BSD-3-Clause", + "author": "", "bugs": { "url": "https://github.com/ava-labs/avalanchejs/issues" }, "homepage": "https://github.com/ava-labs/avalanchejs#readme", - "devDependencies": { - "@semantic-release/changelog": "6.0.2", - "@semantic-release/git": "10.0.1", - "@types/bech32": "1.1.4", - "@types/bn.js": "5.1.1", - "@types/create-hash": "1.2.2", - "@types/hdkey": "2.0.1", - "@types/jest": "29.4.0", - "@types/node": "18.14.2", - "@typescript-eslint/eslint-plugin": "5.54.0", - "@typescript-eslint/parser": "5.54.0", - "clean-webpack-plugin": "4.0.0", - "eslint": "7.32.0", - "eslint-config-prettier": "8.6.0", - "eslint-plugin-prettier": "4.2.1", - "eslint-plugin-security": "1.7.1", - "git-revision-webpack-plugin": "5.0.0", - "html-webpack-plugin": "5.5.0", - "husky": "8.0.3", - "jest": "29.4.3", - "jest-mock-axios": "4.5.0", - "lint-staged": "13.1.2", - "prettier": "2.8.4", - "semantic-release": "19.0.5", - "terser-webpack-plugin": "5.3.6", - "ts-jest": "29.0.5", - "ts-loader": "9.4.2", - "typedoc": "0.23.26", - "typedoc-plugin-external-module-name": "4.0.6", - "typedoc-plugin-markdown": "3.14.0", - "typescript": "4.9.5", - "webpack": "5.74.0", - "webpack-cli": "4.10.0" - }, - "engines": { - "node": ">=14.0.0" - }, - "dependencies": { - "assert": "2.0.0", - "axios": "0.27.2", - "bech32": "2.0.0", - "bip39": "3.1.0", - "bn.js": "5.2.1", - "buffer": "6.0.3", - "create-hash": "1.2.0", - "crypto-browserify": "3.12.0", - "elliptic": "6.5.4", - "ethers": "6.0.8", - "hdkey": "2.1.0", - "isomorphic-ws": "5.0.0", - "randombytes": "^2.1.0", - "store2": "2.14.2", - "stream-browserify": "3.0.0", - "ws": "8.12.1", - "xss": "1.0.14" - }, - "prettier": { - "tabWidth": 2, - "useTabs": false, - "semi": false, - "singleQuote": false, - "jsxBracketSameLine": false, - "trailingComma": "none" + "config": { + "commitizen": { + "path": "./node_modules/cz-conventional-changelog" + } }, "resolutions": { + "http-cache-semantics": "4.1.1", "json5": "2.2.3" }, "lint-staged": { diff --git a/rollup.config.mjs b/rollup.config.mjs new file mode 100644 index 000000000..ebe67c25d --- /dev/null +++ b/rollup.config.mjs @@ -0,0 +1,29 @@ +import { nodeResolve } from '@rollup/plugin-node-resolve'; +import filesize from 'rollup-plugin-filesize'; +import typescript from '@rollup/plugin-typescript'; +import terser from '@rollup/plugin-terser'; + +export default { + input: './src/index.ts', + external: [ + '@noble/hashes/ripemd160', + '@noble/hashes/sha256', + '@noble/hashes/utils', + '@scure/base', + ], // we don't want these dependencies bundled in the dist folder + output: [ + { + file: 'dist/index.js', + format: 'cjs', + plugins: [terser()], + sourcemap: process.env.BUILD === 'production' ? false : true, + }, + { + file: 'dist/es/index.js', + format: 'esm', + plugins: [terser()], + sourcemap: process.env.BUILD === 'production' ? false : true, + }, + ], + plugins: [filesize(), nodeResolve(), typescript()], +}; diff --git a/src/apis/admin/api.ts b/src/apis/admin/api.ts deleted file mode 100644 index 48c392561..000000000 --- a/src/apis/admin/api.ts +++ /dev/null @@ -1,227 +0,0 @@ -/** - * @packageDocumentation - * @module API-Admin - */ -import AvalancheCore from "../../avalanche" -import { JRPCAPI } from "../../common/jrpcapi" -import { RequestResponseData } from "../../common/apibase" -import { - AliasChainParams, - AliasParams, - GetChainAliasesParams, - GetLoggerLevelParams, - GetLoggerLevelResponse, - LoadVMsResponse, - SetLoggerLevelParams, - SetLoggerLevelResponse -} from "./interfaces" - -/** - * Class for interacting with a node's AdminAPI. - * - * @category RPCAPIs - * - * @remarks This extends the [[JRPCAPI]] class. This class should not be directly called. - * Instead, use the [[Avalanche.addAPI]] function to register this interface with Avalanche. - */ - -export class AdminAPI extends JRPCAPI { - /** - * Assign an API an alias, a different endpoint for the API. The original endpoint will still - * work. This change only affects this node other nodes will not know about this alias. - * - * @param endpoint The original endpoint of the API. endpoint should only include the part of - * the endpoint after /ext/ - * @param alias The API being aliased can now be called at ext/alias - * - * @returns Returns a Promise boolean containing success, true for success, false for failure. - */ - alias = async (endpoint: string, alias: string): Promise => { - const params: AliasParams = { - endpoint, - alias - } - const response: RequestResponseData = await this.callMethod( - "admin.alias", - params - ) - return response.data.result.success - ? response.data.result.success - : response.data.result - } - - /** - * Give a blockchain an alias, a different name that can be used any place the blockchain’s - * ID is used. - * - * @param chain The blockchain’s ID - * @param alias Can now be used in place of the blockchain’s ID (in API endpoints, for example) - * - * @returns Returns a Promise boolean containing success, true for success, false for failure. - */ - aliasChain = async (chain: string, alias: string): Promise => { - const params: AliasChainParams = { - chain, - alias - } - const response: RequestResponseData = await this.callMethod( - "admin.aliasChain", - params - ) - return response.data.result.success - ? response.data.result.success - : response.data.result - } - - /** - * Get all aliases for given blockchain - * - * @param chain The blockchain’s ID - * - * @returns Returns a Promise string[] containing aliases of the blockchain. - */ - getChainAliases = async (chain: string): Promise => { - const params: GetChainAliasesParams = { - chain - } - const response: RequestResponseData = await this.callMethod( - "admin.getChainAliases", - params - ) - return response.data.result.aliases - ? response.data.result.aliases - : response.data.result - } - - /** - * Returns log and display levels of loggers - * - * @param loggerName the name of the logger to be returned. This is an optional argument. If not specified, it returns all possible loggers. - * - * @returns Returns a Promise containing logger levels - */ - getLoggerLevel = async ( - loggerName?: string - ): Promise => { - const params: GetLoggerLevelParams = {} - if (typeof loggerName !== "undefined") { - params.loggerName = loggerName - } - const response: RequestResponseData = await this.callMethod( - "admin.getLoggerLevel", - params - ) - return response.data.result - } - - /** - * Dynamically loads any virtual machines installed on the node as plugins - * - * @returns Returns a Promise containing new VMs and failed VMs - */ - loadVMs = async (): Promise => { - const response: RequestResponseData = await this.callMethod("admin.loadVMs") - return response.data.result.aliases - ? response.data.result.aliases - : response.data.result - } - - /** - * Dump the mutex statistics of the node to the specified file. - * - * @returns Promise for a boolean that is true on success. - */ - lockProfile = async (): Promise => { - const response: RequestResponseData = await this.callMethod( - "admin.lockProfile" - ) - return response.data.result.success - ? response.data.result.success - : response.data.result - } - - /** - * Dump the current memory footprint of the node to the specified file. - * - * @returns Promise for a boolean that is true on success. - */ - memoryProfile = async (): Promise => { - const response: RequestResponseData = await this.callMethod( - "admin.memoryProfile" - ) - return response.data.result.success - ? response.data.result.success - : response.data.result - } - - /** - * Sets log and display levels of loggers. - * - * @param loggerName the name of the logger to be changed. This is an optional parameter. - * @param logLevel the log level of written logs, can be omitted. - * @param displayLevel the log level of displayed logs, can be omitted. - * - * @returns Returns a Promise containing logger levels - */ - setLoggerLevel = async ( - loggerName?: string, - logLevel?: string, - displayLevel?: string - ): Promise => { - const params: SetLoggerLevelParams = {} - if (typeof loggerName !== "undefined") { - params.loggerName = loggerName - } - if (typeof logLevel !== "undefined") { - params.logLevel = logLevel - } - if (typeof displayLevel !== "undefined") { - params.displayLevel = displayLevel - } - const response: RequestResponseData = await this.callMethod( - "admin.setLoggerLevel", - params - ) - return response.data.result - } - - /** - * Start profiling the cpu utilization of the node. Will dump the profile information into - * the specified file on stop. - * - * @returns Promise for a boolean that is true on success. - */ - startCPUProfiler = async (): Promise => { - const response: RequestResponseData = await this.callMethod( - "admin.startCPUProfiler" - ) - return response.data.result.success - ? response.data.result.success - : response.data.result - } - - /** - * Stop the CPU profile that was previously started. - * - * @returns Promise for a boolean that is true on success. - */ - stopCPUProfiler = async (): Promise => { - const response: RequestResponseData = await this.callMethod( - "admin.stopCPUProfiler" - ) - return response.data.result.success - ? response.data.result.success - : response.data.result - } - - /** - * This class should not be instantiated directly. Instead use the [[Avalanche.addAPI]] - * method. - * - * @param core A reference to the Avalanche class - * @param baseURL Defaults to the string "/ext/admin" as the path to rpc's baseURL - */ - constructor(core: AvalancheCore, baseURL: string = "/ext/admin") { - super(core, baseURL) - } -} diff --git a/src/apis/admin/index.ts b/src/apis/admin/index.ts deleted file mode 100644 index e1a716605..000000000 --- a/src/apis/admin/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./api" diff --git a/src/apis/admin/interfaces.ts b/src/apis/admin/interfaces.ts deleted file mode 100644 index e59a452a4..000000000 --- a/src/apis/admin/interfaces.ts +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @packageDocumentation - * @module Admin-Interfaces - */ - -export interface AliasParams { - endpoint: string - alias: string -} - -export interface AliasChainParams { - chain: string - alias: string -} - -export interface GetChainAliasesParams { - chain: string -} - -export interface GetLoggerLevelParams { - loggerName?: string -} - -export interface Level { - logLevel: string - displayLevel: string -} - -export interface LoggerLevels { - C: Level - "C.http": Level - P: Level - "P.http": Level - X: Level - "X.http": Level - http: Level - main: Level -} - -export interface GetLoggerLevelResponse { - loggerLevels: LoggerLevels -} - -export interface LoadVMsResponse { - newVMs: object - failedVMs?: object -} - -export interface SetLoggerLevelParams { - loggerName?: string - logLevel?: string - displayLevel?: string -} - -export interface SetLoggerLevelResponse { - success: boolean -} diff --git a/src/apis/auth/api.ts b/src/apis/auth/api.ts deleted file mode 100644 index 0005417dd..000000000 --- a/src/apis/auth/api.ts +++ /dev/null @@ -1,101 +0,0 @@ -/** - * @packageDocumentation - * @module API-Auth - */ -import AvalancheCore from "../../avalanche" -import { JRPCAPI } from "../../common/jrpcapi" -import { RequestResponseData } from "../../common/apibase" -import { ErrorResponseObject } from "../../utils/errors" -import { - ChangePasswordInterface, - NewTokenInterface, - RevokeTokenInterface -} from "./interfaces" - -/** - * Class for interacting with a node's AuthAPI. - * - * @category RPCAPIs - * - * @remarks This extends the [[JRPCAPI]] class. This class should not be directly called. Instead, use the [[Avalanche.addAPI]] function to register this interface with Avalanche. - */ -export class AuthAPI extends JRPCAPI { - /** - * Creates a new authorization token that grants access to one or more API endpoints. - * - * @param password This node's authorization token password, set through the CLI when the node was launched. - * @param endpoints A list of endpoints that will be accessible using the generated token. If there"s an element that is "*", this token can reach any endpoint. - * - * @returns Returns a Promise string containing the authorization token. - */ - newToken = async ( - password: string, - endpoints: string[] - ): Promise => { - const params: NewTokenInterface = { - password, - endpoints - } - const response: RequestResponseData = await this.callMethod( - "auth.newToken", - params - ) - return response.data.result.token - ? response.data.result.token - : response.data.result - } - - /** - * Revokes an authorization token, removing all of its rights to access endpoints. - * - * @param password This node's authorization token password, set through the CLI when the node was launched. - * @param token An authorization token whose access should be revoked. - * - * @returns Returns a Promise boolean indicating if a token was successfully revoked. - */ - revokeToken = async (password: string, token: string): Promise => { - const params: RevokeTokenInterface = { - password, - token - } - const response: RequestResponseData = await this.callMethod( - "auth.revokeToken", - params - ) - return response.data.result.success - } - - /** - * Change this node's authorization token password. **Any authorization tokens created under an old password will become invalid.** - * - * @param oldPassword This node's authorization token password, set through the CLI when the node was launched. - * @param newPassword A new password for this node's authorization token issuance. - * - * @returns Returns a Promise boolean indicating if the password was successfully changed. - */ - changePassword = async ( - oldPassword: string, - newPassword: string - ): Promise => { - const params: ChangePasswordInterface = { - oldPassword, - newPassword - } - const response: RequestResponseData = await this.callMethod( - "auth.changePassword", - params - ) - return response.data.result.success - } - - /** - * This class should not be instantiated directly. Instead use the [[Avalanche.addAPI]] - * method. - * - * @param core A reference to the Avalanche class - * @param baseURL Defaults to the string "/ext/auth" as the path to rpc's baseURL - */ - constructor(core: AvalancheCore, baseURL: string = "/ext/auth") { - super(core, baseURL) - } -} diff --git a/src/apis/auth/index.ts b/src/apis/auth/index.ts deleted file mode 100644 index e1a716605..000000000 --- a/src/apis/auth/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./api" diff --git a/src/apis/auth/interfaces.ts b/src/apis/auth/interfaces.ts deleted file mode 100644 index d892e9509..000000000 --- a/src/apis/auth/interfaces.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * @packageDocumentation - * @module Auth-Interfaces - */ - -export interface NewTokenInterface { - password: string - endpoints: string[] -} - -export interface RevokeTokenInterface { - password: string - token: string -} - -export interface ChangePasswordInterface { - oldPassword: string - newPassword: string -} diff --git a/src/apis/avm/api.ts b/src/apis/avm/api.ts deleted file mode 100644 index 37a505c77..000000000 --- a/src/apis/avm/api.ts +++ /dev/null @@ -1,2101 +0,0 @@ -/** - * @packageDocumentation - * @module API-AVM - */ -import BN from "bn.js" -import { Buffer } from "buffer/" -import AvalancheCore from "../../avalanche" -import BinTools from "../../utils/bintools" -import { UTXO, UTXOSet } from "./utxos" -import { AVMConstants } from "./constants" -import { KeyChain } from "./keychain" -import { Tx, UnsignedTx } from "./tx" -import { PayloadBase } from "../../utils/payload" -import { SECPMintOutput } from "./outputs" -import { InitialStates } from "./initialstates" -import { UnixNow } from "../../utils/helperfunctions" -import { JRPCAPI } from "../../common/jrpcapi" -import { RequestResponseData } from "../../common/apibase" -import { Defaults, PrimaryAssetAlias, ONEAVAX } from "../../utils/constants" -import { MinterSet } from "./minterset" -import { PersistanceOptions } from "../../utils/persistenceoptions" -import { OutputOwners } from "../../common/output" -import { SECPTransferOutput } from "./outputs" -import { - AddressError, - GooseEggCheckError, - ChainIdError, - NoAtomicUTXOsError, - SymbolError, - NameError, - TransactionError -} from "../../utils/errors" -import { Serialization, SerializedType } from "../../utils" -import { - BuildGenesisParams, - CreateAddressParams, - CreateFixedCapAssetParams, - CreateVariableCapAssetParams, - ExportParams, - ExportKeyParams, - GetAllBalancesParams, - GetAssetDescriptionParams, - GetAVAXAssetIDParams, - GetBalanceParams, - GetTxParams, - GetTxStatusParams, - GetUTXOsParams, - ImportParams, - ImportKeyParams, - ListAddressesParams, - MintParams, - SendMultipleParams, - SOutputsParams, - GetUTXOsResponse, - GetAssetDescriptionResponse, - GetBalanceResponse, - SendParams, - SendResponse, - SendMultipleResponse, - GetAddressTxsParams, - GetAddressTxsResponse, - CreateNFTAssetParams, - SendNFTParams, - MintNFTParams, - IMinterSet -} from "./interfaces" -import { IssueTxParams } from "../../common" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Class for interacting with a node endpoint that is using the AVM. - * - * @category RPCAPIs - * - * @remarks This extends the [[JRPCAPI]] class. This class should not be directly called. Instead, use the [[Avalanche.addAPI]] function to register this interface with Avalanche. - */ -export class AVMAPI extends JRPCAPI { - /** - * @ignore - */ - protected keychain: KeyChain = new KeyChain("", "") - protected blockchainID: string = "" - protected blockchainAlias: string = undefined - protected AVAXAssetID: Buffer = undefined - protected txFee: BN = undefined - protected creationTxFee: BN = undefined - protected mintTxFee: BN = undefined - - /** - * Gets the alias for the blockchainID if it exists, otherwise returns `undefined`. - * - * @returns The alias for the blockchainID - */ - getBlockchainAlias = (): string => { - if (typeof this.blockchainAlias === "undefined") { - const netid: number = this.core.getNetworkID() - if ( - netid in Defaults.network && - this.blockchainID in Defaults.network[`${netid}`] - ) { - this.blockchainAlias = - Defaults.network[`${netid}`][this.blockchainID]["alias"] - return this.blockchainAlias - } else { - /* istanbul ignore next */ - return undefined - } - } - return this.blockchainAlias - } - - /** - * Sets the alias for the blockchainID. - * - * @param alias The alias for the blockchainID. - * - */ - setBlockchainAlias = (alias: string): undefined => { - this.blockchainAlias = alias - /* istanbul ignore next */ - return undefined - } - - /** - * Gets the blockchainID and returns it. - * - * @returns The blockchainID - */ - getBlockchainID = (): string => this.blockchainID - - /** - * Refresh blockchainID, and if a blockchainID is passed in, use that. - * - * @param Optional. BlockchainID to assign, if none, uses the default based on networkID. - * - * @returns The blockchainID - */ - refreshBlockchainID = (blockchainID: string = undefined): boolean => { - const netid: number = this.core.getNetworkID() - if ( - typeof blockchainID === "undefined" && - typeof Defaults.network[`${netid}`] !== "undefined" - ) { - this.blockchainID = Defaults.network[`${netid}`].X.blockchainID //default to X-Chain - return true - } - if (typeof blockchainID === "string") { - this.blockchainID = blockchainID - return true - } - return false - } - - /** - * Takes an address string and returns its {@link https://github.com/feross/buffer|Buffer} representation if valid. - * - * @returns A {@link https://github.com/feross/buffer|Buffer} for the address if valid, undefined if not valid. - */ - parseAddress = (addr: string): Buffer => { - const alias: string = this.getBlockchainAlias() - const blockchainID: string = this.getBlockchainID() - return bintools.parseAddress( - addr, - blockchainID, - alias, - AVMConstants.ADDRESSLENGTH - ) - } - - addressFromBuffer = (address: Buffer): string => { - const chainID: string = this.getBlockchainAlias() - ? this.getBlockchainAlias() - : this.getBlockchainID() - const type: SerializedType = "bech32" - const hrp: string = this.core.getHRP() - return serialization.bufferToType(address, type, hrp, chainID) - } - - /** - * Fetches the AVAX AssetID and returns it in a Promise. - * - * @param refresh This function caches the response. Refresh = true will bust the cache. - * - * @returns The the provided string representing the AVAX AssetID - */ - getAVAXAssetID = async (refresh: boolean = false): Promise => { - if (typeof this.AVAXAssetID === "undefined" || refresh) { - const asset: GetAVAXAssetIDParams = await this.getAssetDescription( - PrimaryAssetAlias - ) - this.AVAXAssetID = asset.assetID - } - return this.AVAXAssetID - } - - /** - * Overrides the defaults and sets the cache to a specific AVAX AssetID - * - * @param avaxAssetID A cb58 string or Buffer representing the AVAX AssetID - * - * @returns The the provided string representing the AVAX AssetID - */ - setAVAXAssetID = (avaxAssetID: string | Buffer) => { - if (typeof avaxAssetID === "string") { - avaxAssetID = bintools.cb58Decode(avaxAssetID) - } - this.AVAXAssetID = avaxAssetID - } - - /** - * Gets the default tx fee for this chain. - * - * @returns The default tx fee as a {@link https://github.com/indutny/bn.js/|BN} - */ - getDefaultTxFee = (): BN => { - return this.core.getNetworkID() in Defaults.network - ? new BN(Defaults.network[this.core.getNetworkID()]["X"]["txFee"]) - : new BN(0) - } - - /** - * Gets the tx fee for this chain. - * - * @returns The tx fee as a {@link https://github.com/indutny/bn.js/|BN} - */ - getTxFee = (): BN => { - if (typeof this.txFee === "undefined") { - this.txFee = this.getDefaultTxFee() - } - return this.txFee - } - - /** - * Sets the tx fee for this chain. - * - * @param fee The tx fee amount to set as {@link https://github.com/indutny/bn.js/|BN} - */ - setTxFee = (fee: BN): void => { - this.txFee = fee - } - - /** - * Gets the default creation fee for this chain. - * - * @returns The default creation fee as a {@link https://github.com/indutny/bn.js/|BN} - */ - getDefaultCreationTxFee = (): BN => { - return this.core.getNetworkID() in Defaults.network - ? new BN(Defaults.network[this.core.getNetworkID()]["X"]["creationTxFee"]) - : new BN(0) - } - - /** - * Gets the default mint fee for this chain. - * - * @returns The default mint fee as a {@link https://github.com/indutny/bn.js/|BN} - */ - getDefaultMintTxFee = (): BN => { - return this.core.getNetworkID() in Defaults.network - ? new BN(Defaults.network[this.core.getNetworkID()]["X"]["mintTxFee"]) - : new BN(0) - } - - /** - * Gets the mint fee for this chain. - * - * @returns The mint fee as a {@link https://github.com/indutny/bn.js/|BN} - */ - getMintTxFee = (): BN => { - if (typeof this.mintTxFee === "undefined") { - this.mintTxFee = this.getDefaultMintTxFee() - } - return this.mintTxFee - } - - /** - * Gets the creation fee for this chain. - * - * @returns The creation fee as a {@link https://github.com/indutny/bn.js/|BN} - */ - getCreationTxFee = (): BN => { - if (typeof this.creationTxFee === "undefined") { - this.creationTxFee = this.getDefaultCreationTxFee() - } - return this.creationTxFee - } - - /** - * Sets the mint fee for this chain. - * - * @param fee The mint fee amount to set as {@link https://github.com/indutny/bn.js/|BN} - */ - setMintTxFee = (fee: BN): void => { - this.mintTxFee = fee - } - - /** - * Sets the creation fee for this chain. - * - * @param fee The creation fee amount to set as {@link https://github.com/indutny/bn.js/|BN} - */ - setCreationTxFee = (fee: BN): void => { - this.creationTxFee = fee - } - - /** - * Gets a reference to the keychain for this class. - * - * @returns The instance of [[KeyChain]] for this class - */ - keyChain = (): KeyChain => this.keychain - - /** - * @ignore - */ - newKeyChain = (): KeyChain => { - // warning, overwrites the old keychain - const alias: string = this.getBlockchainAlias() - if (alias) { - this.keychain = new KeyChain(this.core.getHRP(), alias) - } else { - this.keychain = new KeyChain(this.core.getHRP(), this.blockchainID) - } - return this.keychain - } - - /** - * Helper function which determines if a tx is a goose egg transaction. - * - * @param utx An UnsignedTx - * - * @returns boolean true if passes goose egg test and false if fails. - * - * @remarks - * A "Goose Egg Transaction" is when the fee far exceeds a reasonable amount - */ - checkGooseEgg = async ( - utx: UnsignedTx, - outTotal: BN = new BN(0) - ): Promise => { - const avaxAssetID: Buffer = await this.getAVAXAssetID() - const outputTotal: BN = outTotal.gt(new BN(0)) - ? outTotal - : utx.getOutputTotal(avaxAssetID) - const fee: BN = utx.getBurn(avaxAssetID) - if (fee.lte(ONEAVAX.mul(new BN(10))) || fee.lte(outputTotal)) { - return true - } else { - return false - } - } - - /** - * Gets the balance of a particular asset on a blockchain. - * - * @param address The address to pull the asset balance from - * @param assetID The assetID to pull the balance from - * @param includePartial If includePartial=false, returns only the balance held solely - * - * @returns Promise with the balance of the assetID as a {@link https://github.com/indutny/bn.js/|BN} on the provided address for the blockchain. - */ - getBalance = async ( - address: string, - assetID: string, - includePartial: boolean = false - ): Promise => { - if (typeof this.parseAddress(address) === "undefined") { - /* istanbul ignore next */ - throw new AddressError( - "Error - AVMAPI.getBalance: Invalid address format" - ) - } - const params: GetBalanceParams = { - address, - assetID, - includePartial - } - const response: RequestResponseData = await this.callMethod( - "avm.getBalance", - params - ) - return response.data.result - } - - /** - * Creates an address (and associated private keys) on a user on a blockchain. - * - * @param username Name of the user to create the address under - * @param password Password to unlock the user and encrypt the private key - * - * @returns Promise for a string representing the address created by the vm. - */ - createAddress = async ( - username: string, - password: string - ): Promise => { - const params: CreateAddressParams = { - username, - password - } - const response: RequestResponseData = await this.callMethod( - "avm.createAddress", - params - ) - return response.data.result.address - } - - /** - * Create a new fixed-cap, fungible asset. A quantity of it is created at initialization and there no more is ever created. - * - * @param username The user paying the transaction fee (in $AVAX) for asset creation - * @param password The password for the user paying the transaction fee (in $AVAX) for asset creation - * @param name The human-readable name for the asset - * @param symbol Optional. The shorthand symbol for the asset. Between 0 and 4 characters - * @param denomination Optional. Determines how balances of this asset are displayed by user interfaces. Default is 0 - * @param initialHolders An array of objects containing the field "address" and "amount" to establish the genesis values for the new asset - * - * ```js - * Example initialHolders: - * [ - * { - * "address": "X-avax1kj06lhgx84h39snsljcey3tpc046ze68mek3g5", - * "amount": 10000 - * }, - * { - * "address": "X-avax1am4w6hfrvmh3akduzkjthrtgtqafalce6an8cr", - * "amount": 50000 - * } - * ] - * ``` - * - * @returns Returns a Promise string containing the base 58 string representation of the ID of the newly created asset. - */ - createFixedCapAsset = async ( - username: string, - password: string, - name: string, - symbol: string, - denomination: number, - initialHolders: object[] - ): Promise => { - const params: CreateFixedCapAssetParams = { - name, - symbol, - denomination, - username, - password, - initialHolders - } - const response: RequestResponseData = await this.callMethod( - "avm.createFixedCapAsset", - params - ) - return response.data.result.assetID - } - - /** - * Create a new variable-cap, fungible asset. No units of the asset exist at initialization. Minters can mint units of this asset using createMintTx, signMintTx and sendMintTx. - * - * @param username The user paying the transaction fee (in $AVAX) for asset creation - * @param password The password for the user paying the transaction fee (in $AVAX) for asset creation - * @param name The human-readable name for the asset - * @param symbol Optional. The shorthand symbol for the asset -- between 0 and 4 characters - * @param denomination Optional. Determines how balances of this asset are displayed by user interfaces. Default is 0 - * @param minterSets is a list where each element specifies that threshold of the addresses in minters may together mint more of the asset by signing a minting transaction - * - * ```js - * Example minterSets: - * [ - * { - * "minters":[ - * "X-avax1am4w6hfrvmh3akduzkjthrtgtqafalce6an8cr" - * ], - * "threshold": 1 - * }, - * { - * "minters": [ - * "X-avax1am4w6hfrvmh3akduzkjthrtgtqafalce6an8cr", - * "X-avax1kj06lhgx84h39snsljcey3tpc046ze68mek3g5", - * "X-avax1yell3e4nln0m39cfpdhgqprsd87jkh4qnakklx" - * ], - * "threshold": 2 - * } - * ] - * ``` - * - * @returns Returns a Promise string containing the base 58 string representation of the ID of the newly created asset. - */ - createVariableCapAsset = async ( - username: string, - password: string, - name: string, - symbol: string, - denomination: number, - minterSets: object[] - ): Promise => { - const params: CreateVariableCapAssetParams = { - name, - symbol, - denomination, - username, - password, - minterSets - } - const response: RequestResponseData = await this.callMethod( - "avm.createVariableCapAsset", - params - ) - return response.data.result.assetID - } - - /** - * Creates a family of NFT Asset. No units of the asset exist at initialization. Minters can mint units of this asset using createMintTx, signMintTx and sendMintTx. - * - * @param username The user paying the transaction fee (in $AVAX) for asset creation - * @param password The password for the user paying the transaction fee (in $AVAX) for asset creation - * @param from Optional. An array of addresses managed by the node's keystore for this blockchain which will fund this transaction - * @param changeAddr Optional. An address to send the change - * @param name The human-readable name for the asset - * @param symbol Optional. The shorthand symbol for the asset -- between 0 and 4 characters - * @param minterSets is a list where each element specifies that threshold of the addresses in minters may together mint more of the asset by signing a minting transaction - * - * @returns Returns a Promise string containing the base 58 string representation of the ID of the newly created asset. - */ - createNFTAsset = async ( - username: string, - password: string, - from: string[] | Buffer[] = undefined, - changeAddr: string, - name: string, - symbol: string, - minterSet: IMinterSet - ): Promise => { - const params: CreateNFTAssetParams = { - username, - password, - name, - symbol, - minterSet - } - - const caller: string = "createNFTAsset" - from = this._cleanAddressArray(from, caller) - if (typeof from !== "undefined") { - params["from"] = from - } - - if (typeof changeAddr !== "undefined") { - if (typeof this.parseAddress(changeAddr) === "undefined") { - /* istanbul ignore next */ - throw new AddressError( - "Error - AVMAPI.createNFTAsset: Invalid address format" - ) - } - params["changeAddr"] = changeAddr - } - - const response: RequestResponseData = await this.callMethod( - "avm.createNFTAsset", - params - ) - return response.data.result.assetID - } - - /** - * Create an unsigned transaction to mint more of an asset. - * - * @param amount The units of the asset to mint - * @param assetID The ID of the asset to mint - * @param to The address to assign the units of the minted asset - * @param minters Addresses of the minters responsible for signing the transaction - * - * @returns Returns a Promise string containing the base 58 string representation of the unsigned transaction. - */ - mint = async ( - username: string, - password: string, - amount: number | BN, - assetID: Buffer | string, - to: string, - minters: string[] - ): Promise => { - let asset: string - let amnt: BN - if (typeof assetID !== "string") { - asset = bintools.cb58Encode(assetID) - } else { - asset = assetID - } - if (typeof amount === "number") { - amnt = new BN(amount) - } else { - amnt = amount - } - const params: MintParams = { - username: username, - password: password, - amount: amnt, - assetID: asset, - to, - minters - } - const response: RequestResponseData = await this.callMethod( - "avm.mint", - params - ) - return response.data.result.txID - } - - /** - * Mint non-fungible tokens which were created with AVMAPI.createNFTAsset - * - * @param username The user paying the transaction fee (in $AVAX) for asset creation - * @param password The password for the user paying the transaction fee (in $AVAX) for asset creation - * @param from Optional. An array of addresses managed by the node's keystore for this blockchain which will fund this transaction - * @param changeAddr Optional. An address to send the change - * @param assetID The asset id which is being sent - * @param to Address on X-Chain of the account to which this NFT is being sent - * @param encoding Optional. is the encoding format to use for the payload argument. Can be either "cb58" or "hex". Defaults to "hex". - * - * @returns ID of the transaction - */ - mintNFT = async ( - username: string, - password: string, - from: string[] | Buffer[] = undefined, - changeAddr: string = undefined, - payload: string, - assetID: string | Buffer, - to: string, - encoding: string = "hex" - ): Promise => { - let asset: string - - if (typeof this.parseAddress(to) === "undefined") { - /* istanbul ignore next */ - throw new AddressError("Error - AVMAPI.mintNFT: Invalid address format") - } - - if (typeof assetID !== "string") { - asset = bintools.cb58Encode(assetID) - } else { - asset = assetID - } - - const params: MintNFTParams = { - username, - password, - assetID: asset, - payload, - to, - encoding - } - - const caller: string = "mintNFT" - from = this._cleanAddressArray(from, caller) - if (typeof from !== "undefined") { - params["from"] = from - } - - if (typeof changeAddr !== "undefined") { - if (typeof this.parseAddress(changeAddr) === "undefined") { - /* istanbul ignore next */ - throw new AddressError("Error - AVMAPI.mintNFT: Invalid address format") - } - params["changeAddr"] = changeAddr - } - - const response: RequestResponseData = await this.callMethod( - "avm.mintNFT", - params - ) - return response.data.result.txID - } - - /** - * Send NFT from one account to another on X-Chain - * - * @param username The user paying the transaction fee (in $AVAX) for asset creation - * @param password The password for the user paying the transaction fee (in $AVAX) for asset creation - * @param from Optional. An array of addresses managed by the node's keystore for this blockchain which will fund this transaction - * @param changeAddr Optional. An address to send the change - * @param assetID The asset id which is being sent - * @param groupID The group this NFT is issued to. - * @param to Address on X-Chain of the account to which this NFT is being sent - * - * @returns ID of the transaction - */ - sendNFT = async ( - username: string, - password: string, - from: string[] | Buffer[] = undefined, - changeAddr: string = undefined, - assetID: string | Buffer, - groupID: number, - to: string - ): Promise => { - let asset: string - - if (typeof this.parseAddress(to) === "undefined") { - /* istanbul ignore next */ - throw new AddressError("Error - AVMAPI.sendNFT: Invalid address format") - } - - if (typeof assetID !== "string") { - asset = bintools.cb58Encode(assetID) - } else { - asset = assetID - } - - const params: SendNFTParams = { - username, - password, - assetID: asset, - groupID, - to - } - - const caller: string = "sendNFT" - from = this._cleanAddressArray(from, caller) - if (typeof from !== "undefined") { - params["from"] = from - } - - if (typeof changeAddr !== "undefined") { - if (typeof this.parseAddress(changeAddr) === "undefined") { - /* istanbul ignore next */ - throw new AddressError("Error - AVMAPI.sendNFT: Invalid address format") - } - params["changeAddr"] = changeAddr - } - - const response: RequestResponseData = await this.callMethod( - "avm.sendNFT", - params - ) - return response.data.result.txID - } - - /** - * Exports the private key for an address. - * - * @param username The name of the user with the private key - * @param password The password used to decrypt the private key - * @param address The address whose private key should be exported - * - * @returns Promise with the decrypted private key as store in the database - */ - exportKey = async ( - username: string, - password: string, - address: string - ): Promise => { - if (typeof this.parseAddress(address) === "undefined") { - /* istanbul ignore next */ - throw new AddressError("Error - AVMAPI.exportKey: Invalid address format") - } - const params: ExportKeyParams = { - username, - password, - address - } - const response: RequestResponseData = await this.callMethod( - "avm.exportKey", - params - ) - return response.data.result.privateKey - } - - /** - * Imports a private key into the node's keystore under an user and for a blockchain. - * - * @param username The name of the user to store the private key - * @param password The password that unlocks the user - * @param privateKey A string representing the private key in the vm's format - * - * @returns The address for the imported private key. - */ - importKey = async ( - username: string, - password: string, - privateKey: string - ): Promise => { - const params: ImportKeyParams = { - username, - password, - privateKey - } - const response: RequestResponseData = await this.callMethod( - "avm.importKey", - params - ) - return response.data.result.address - } - - /** - * Send ANT (Avalanche Native Token) assets including AVAX from the X-Chain to an account on the P-Chain or C-Chain. - * - * After calling this method, you must call the P-Chain's `import` or the C-Chain’s `import` method to complete the transfer. - * - * @param username The Keystore user that controls the P-Chain or C-Chain account specified in `to` - * @param password The password of the Keystore user - * @param to The account on the P-Chain or C-Chain to send the asset to. - * @param amount Amount of asset to export as a {@link https://github.com/indutny/bn.js/|BN} - * @param assetID The asset id which is being sent - * - * @returns String representing the transaction id - */ - export = async ( - username: string, - password: string, - to: string, - amount: BN, - assetID: string - ): Promise => { - const params: ExportParams = { - username, - password, - to, - amount: amount, - assetID - } - const response: RequestResponseData = await this.callMethod( - "avm.export", - params - ) - return response.data.result.txID - } - - /** - * Send ANT (Avalanche Native Token) assets including AVAX from an account on the P-Chain or C-Chain to an address on the X-Chain. This transaction - * must be signed with the key of the account that the asset is sent from and which pays - * the transaction fee. - * - * @param username The Keystore user that controls the account specified in `to` - * @param password The password of the Keystore user - * @param to The address of the account the asset is sent to. - * @param sourceChain The chainID where the funds are coming from. Ex: "C" - * - * @returns Promise for a string for the transaction, which should be sent to the network - * by calling issueTx. - */ - import = async ( - username: string, - password: string, - to: string, - sourceChain: string - ): Promise => { - const params: ImportParams = { - username, - password, - to, - sourceChain - } - const response: RequestResponseData = await this.callMethod( - "avm.import", - params - ) - return response.data.result.txID - } - - /** - * Lists all the addresses under a user. - * - * @param username The user to list addresses - * @param password The password of the user to list the addresses - * - * @returns Promise of an array of address strings in the format specified by the blockchain. - */ - listAddresses = async ( - username: string, - password: string - ): Promise => { - const params: ListAddressesParams = { - username, - password - } - const response: RequestResponseData = await this.callMethod( - "avm.listAddresses", - params - ) - return response.data.result.addresses - } - - /** - * Retrieves all assets for an address on a server and their associated balances. - * - * @param address The address to get a list of assets - * - * @returns Promise of an object mapping assetID strings with {@link https://github.com/indutny/bn.js/|BN} balance for the address on the blockchain. - */ - getAllBalances = async (address: string): Promise => { - if (typeof this.parseAddress(address) === "undefined") { - /* istanbul ignore next */ - throw new AddressError( - "Error - AVMAPI.getAllBalances: Invalid address format" - ) - } - const params: GetAllBalancesParams = { - address - } - const response: RequestResponseData = await this.callMethod( - "avm.getAllBalances", - params - ) - return response.data.result.balances - } - - /** - * Retrieves an assets name and symbol. - * - * @param assetID Either a {@link https://github.com/feross/buffer|Buffer} or an b58 serialized string for the AssetID or its alias. - * - * @returns Returns a Promise object with keys "name" and "symbol". - */ - getAssetDescription = async ( - assetID: Buffer | string - ): Promise => { - let asset: string - if (typeof assetID !== "string") { - asset = bintools.cb58Encode(assetID) - } else { - asset = assetID - } - const params: GetAssetDescriptionParams = { - assetID: asset - } - const response: RequestResponseData = await this.callMethod( - "avm.getAssetDescription", - params - ) - return { - name: response.data.result.name, - symbol: response.data.result.symbol, - assetID: bintools.cb58Decode(response.data.result.assetID), - denomination: parseInt(response.data.result.denomination, 10) - } - } - - /** - * Returns the transaction data of a provided transaction ID by calling the node's `getTx` method. - * - * @param txID The string representation of the transaction ID - * @param encoding sets the format of the returned transaction. Can be, "cb58", "hex" or "json". Defaults to "cb58". - * - * @returns Returns a Promise string or object containing the bytes retrieved from the node - */ - getTx = async ( - txID: string, - encoding: string = "hex" - ): Promise => { - const params: GetTxParams = { - txID, - encoding - } - const response: RequestResponseData = await this.callMethod( - "avm.getTx", - params - ) - return response.data.result.tx - } - - /** - * Returns the status of a provided transaction ID by calling the node's `getTxStatus` method. - * - * @param txID The string representation of the transaction ID - * - * @returns Returns a Promise string containing the status retrieved from the node - */ - getTxStatus = async (txID: string): Promise => { - const params: GetTxStatusParams = { - txID - } - const response: RequestResponseData = await this.callMethod( - "avm.getTxStatus", - params - ) - return response.data.result.status - } - - /** - * Retrieves the UTXOs related to the addresses provided from the node's `getUTXOs` method. - * - * @param addresses An array of addresses as cb58 strings or addresses as {@link https://github.com/feross/buffer|Buffer}s - * @param sourceChain A string for the chain to look for the UTXO's. Default is to use this chain, but if exported UTXOs exist from other chains, this can used to pull them instead. - * @param limit Optional. Returns at most [limit] addresses. If [limit] == 0 or > [maxUTXOsToFetch], fetches up to [maxUTXOsToFetch]. - * @param startIndex Optional. [StartIndex] defines where to start fetching UTXOs (for pagination.) - * UTXOs fetched are from addresses equal to or greater than [StartIndex.Address] - * For address [StartIndex.Address], only UTXOs with IDs greater than [StartIndex.Utxo] will be returned. - * @param persistOpts Options available to persist these UTXOs in local storage - * - * @remarks - * persistOpts is optional and must be of type [[PersistanceOptions]] - * - */ - getUTXOs = async ( - addresses: string[] | string, - sourceChain: string = undefined, - limit: number = 0, - startIndex: { address: string; utxo: string } = undefined, - persistOpts: PersistanceOptions = undefined, - encoding: string = "hex" - ): Promise => { - if (typeof addresses === "string") { - addresses = [addresses] - } - - const params: GetUTXOsParams = { - addresses: addresses, - limit, - encoding - } - if (typeof startIndex !== "undefined" && startIndex) { - params.startIndex = startIndex - } - - if (typeof sourceChain !== "undefined") { - params.sourceChain = sourceChain - } - - const response: RequestResponseData = await this.callMethod( - "avm.getUTXOs", - params - ) - const utxos: UTXOSet = new UTXOSet() - let data = response.data.result.utxos - if (persistOpts && typeof persistOpts === "object") { - if (this.db.has(persistOpts.getName())) { - const selfArray: string[] = this.db.get(persistOpts.getName()) - if (Array.isArray(selfArray)) { - utxos.addArray(data) - const utxoSet: UTXOSet = new UTXOSet() - utxoSet.addArray(selfArray) - utxoSet.mergeByRule(utxos, persistOpts.getMergeRule()) - data = utxoSet.getAllUTXOStrings() - } - } - this.db.set(persistOpts.getName(), data, persistOpts.getOverwrite()) - } - if (data.length > 0 && data[0].substring(0, 2) === "0x") { - const cb58Strs: string[] = [] - data.forEach((str: string): void => { - cb58Strs.push(bintools.cb58Encode(new Buffer(str.slice(2), "hex"))) - }) - - utxos.addArray(cb58Strs, false) - } else { - utxos.addArray(data, false) - } - response.data.result.utxos = utxos - return response.data.result - } - - /** - * Helper function which creates an unsigned transaction. For more granular control, you may create your own - * [[UnsignedTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s, and [[TransferOperation]]s). - * - * @param utxoset A set of UTXOs that the transaction is built on - * @param amount The amount of AssetID to be spent in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN}. - * @param assetID The assetID of the value being sent - * @param toAddresses The addresses to send the funds - * @param fromAddresses The addresses being used to send the funds from the UTXOs provided - * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs - * @param memo Optional CB58 Buffer or String which contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param locktime Optional. The locktime field created in the resulting outputs - * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO - * - * @returns An unsigned transaction ([[UnsignedTx]]) which contains a [[BaseTx]]. - * - * @remarks - * This helper exists because the endpoint API should be the primary point of entry for most functionality. - */ - buildBaseTx = async ( - utxoset: UTXOSet, - amount: BN, - assetID: Buffer | string = undefined, - toAddresses: string[], - fromAddresses: string[], - changeAddresses: string[], - memo: PayloadBase | Buffer = undefined, - asOf: BN = UnixNow(), - locktime: BN = new BN(0), - threshold: number = 1 - ): Promise => { - const caller: string = "buildBaseTx" - const to: Buffer[] = this._cleanAddressArray(toAddresses, caller).map( - (a: string): Buffer => bintools.stringToAddress(a) - ) - const from: Buffer[] = this._cleanAddressArray(fromAddresses, caller).map( - (a: string): Buffer => bintools.stringToAddress(a) - ) - const change: Buffer[] = this._cleanAddressArray( - changeAddresses, - caller - ).map((a: string): Buffer => bintools.stringToAddress(a)) - - if (typeof assetID === "string") { - assetID = bintools.cb58Decode(assetID) - } - - if (memo instanceof PayloadBase) { - memo = memo.getPayload() - } - - const networkID: number = this.core.getNetworkID() - const blockchainIDBuf: Buffer = bintools.cb58Decode(this.blockchainID) - const fee: BN = this.getTxFee() - const feeAssetID: Buffer = await this.getAVAXAssetID() - const builtUnsignedTx: UnsignedTx = utxoset.buildBaseTx( - networkID, - blockchainIDBuf, - amount, - assetID, - to, - from, - change, - fee, - feeAssetID, - memo, - asOf, - locktime, - threshold - ) - - if (!(await this.checkGooseEgg(builtUnsignedTx))) { - /* istanbul ignore next */ - throw new GooseEggCheckError( - "Error - AVMAPI.buildBaseTx:Failed Goose Egg Check" - ) - } - - return builtUnsignedTx - } - - /** - * Helper function which creates an unsigned NFT Transfer. For more granular control, you may create your own - * [[UnsignedTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s, and [[TransferOperation]]s). - * - * @param utxoset A set of UTXOs that the transaction is built on - * @param toAddresses The addresses to send the NFT - * @param fromAddresses The addresses being used to send the NFT from the utxoID provided - * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs - * @param utxoid A base58 utxoID or an array of base58 utxoIDs for the nfts this transaction is sending - * @param memo Optional CB58 Buffer or String which contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param locktime Optional. The locktime field created in the resulting outputs - * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO - * - * @returns An unsigned transaction ([[UnsignedTx]]) which contains a [[NFTTransferTx]]. - * - * @remarks - * This helper exists because the endpoint API should be the primary point of entry for most functionality. - */ - buildNFTTransferTx = async ( - utxoset: UTXOSet, - toAddresses: string[], - fromAddresses: string[], - changeAddresses: string[], - utxoid: string | string[], - memo: PayloadBase | Buffer = undefined, - asOf: BN = UnixNow(), - locktime: BN = new BN(0), - threshold: number = 1 - ): Promise => { - const caller: string = "buildNFTTransferTx" - const to: Buffer[] = this._cleanAddressArray(toAddresses, caller).map( - (a: string): Buffer => bintools.stringToAddress(a) - ) - const from: Buffer[] = this._cleanAddressArray(fromAddresses, caller).map( - (a: string): Buffer => bintools.stringToAddress(a) - ) - const change: Buffer[] = this._cleanAddressArray( - changeAddresses, - caller - ).map((a: string): Buffer => bintools.stringToAddress(a)) - - if (memo instanceof PayloadBase) { - memo = memo.getPayload() - } - const avaxAssetID: Buffer = await this.getAVAXAssetID() - - let utxoidArray: string[] = [] - if (typeof utxoid === "string") { - utxoidArray = [utxoid] - } else if (Array.isArray(utxoid)) { - utxoidArray = utxoid - } - - const builtUnsignedTx: UnsignedTx = utxoset.buildNFTTransferTx( - this.core.getNetworkID(), - bintools.cb58Decode(this.blockchainID), - to, - from, - change, - utxoidArray, - this.getTxFee(), - avaxAssetID, - memo, - asOf, - locktime, - threshold - ) - - if (!(await this.checkGooseEgg(builtUnsignedTx))) { - /* istanbul ignore next */ - throw new GooseEggCheckError( - "Error - AVMAPI.buildNFTTransferTx:Failed Goose Egg Check" - ) - } - - return builtUnsignedTx - } - - /** - * Helper function which creates an unsigned Import Tx. For more granular control, you may create your own - * [[UnsignedTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s, and [[TransferOperation]]s). - * - * @param utxoset A set of UTXOs that the transaction is built on - * @param ownerAddresses The addresses being used to import - * @param sourceChain The chainid for where the import is coming from - * @param toAddresses The addresses to send the funds - * @param fromAddresses The addresses being used to send the funds from the UTXOs provided - * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs - * @param memo Optional CB58 Buffer or String which contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param locktime Optional. The locktime field created in the resulting outputs - * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO - * - * @returns An unsigned transaction ([[UnsignedTx]]) which contains a [[ImportTx]]. - * - * @remarks - * This helper exists because the endpoint API should be the primary point of entry for most functionality. - */ - buildImportTx = async ( - utxoset: UTXOSet, - ownerAddresses: string[], - sourceChain: Buffer | string, - toAddresses: string[], - fromAddresses: string[], - changeAddresses: string[] = undefined, - memo: PayloadBase | Buffer = undefined, - asOf: BN = UnixNow(), - locktime: BN = new BN(0), - threshold: number = 1 - ): Promise => { - const caller: string = "buildImportTx" - const to: Buffer[] = this._cleanAddressArray(toAddresses, caller).map( - (a: string): Buffer => bintools.stringToAddress(a) - ) - const from: Buffer[] = this._cleanAddressArray(fromAddresses, caller).map( - (a: string): Buffer => bintools.stringToAddress(a) - ) - const change: Buffer[] = this._cleanAddressArray( - changeAddresses, - caller - ).map((a: string): Buffer => bintools.stringToAddress(a)) - - let srcChain: string = undefined - - if (typeof sourceChain === "undefined") { - throw new ChainIdError( - "Error - AVMAPI.buildImportTx: Source ChainID is undefined." - ) - } else if (typeof sourceChain === "string") { - srcChain = sourceChain - sourceChain = bintools.cb58Decode(sourceChain) - } else if (!(sourceChain instanceof Buffer)) { - throw new ChainIdError( - "Error - AVMAPI.buildImportTx: Invalid destinationChain type: " + - typeof sourceChain - ) - } - - const atomicUTXOs: UTXOSet = ( - await this.getUTXOs(ownerAddresses, srcChain, 0, undefined) - ).utxos - const avaxAssetID: Buffer = await this.getAVAXAssetID() - const atomics: UTXO[] = atomicUTXOs.getAllUTXOs() - - if (atomics.length === 0) { - throw new NoAtomicUTXOsError( - "Error - AVMAPI.buildImportTx: No atomic UTXOs to import from " + - srcChain + - " using addresses: " + - ownerAddresses.join(", ") - ) - } - - if (memo instanceof PayloadBase) { - memo = memo.getPayload() - } - - const builtUnsignedTx: UnsignedTx = utxoset.buildImportTx( - this.core.getNetworkID(), - bintools.cb58Decode(this.blockchainID), - to, - from, - change, - atomics, - sourceChain, - this.getTxFee(), - avaxAssetID, - memo, - asOf, - locktime, - threshold - ) - - if (!(await this.checkGooseEgg(builtUnsignedTx))) { - /* istanbul ignore next */ - throw new GooseEggCheckError( - "Error - AVMAPI.buildImportTx:Failed Goose Egg Check" - ) - } - - return builtUnsignedTx - } - - /** - * Helper function which creates an unsigned Export Tx. For more granular control, you may create your own - * [[UnsignedTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s, and [[TransferOperation]]s). - * - * @param utxoset A set of UTXOs that the transaction is built on - * @param amount The amount being exported as a {@link https://github.com/indutny/bn.js/|BN} - * @param destinationChain The chainid for where the assets will be sent. - * @param toAddresses The addresses to send the funds - * @param fromAddresses The addresses being used to send the funds from the UTXOs provided - * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs - * @param memo Optional CB58 Buffer or String which contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param locktime Optional. The locktime field created in the resulting outputs - * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO - * @param assetID Optional. The assetID of the asset to send. Defaults to AVAX assetID. - * Regardless of the asset which you"re exporting, all fees are paid in AVAX. - * - * @returns An unsigned transaction ([[UnsignedTx]]) which contains an [[ExportTx]]. - */ - buildExportTx = async ( - utxoset: UTXOSet, - amount: BN, - destinationChain: Buffer | string, - toAddresses: string[], - fromAddresses: string[], - changeAddresses: string[] = undefined, - memo: PayloadBase | Buffer = undefined, - asOf: BN = UnixNow(), - locktime: BN = new BN(0), - threshold: number = 1, - assetID: string = undefined - ): Promise => { - const prefixes: object = {} - toAddresses.map((a: string): void => { - prefixes[a.split("-")[0]] = true - }) - if (Object.keys(prefixes).length !== 1) { - throw new AddressError( - "Error - AVMAPI.buildExportTx: To addresses must have the same chainID prefix." - ) - } - - if (typeof destinationChain === "undefined") { - throw new ChainIdError( - "Error - AVMAPI.buildExportTx: Destination ChainID is undefined." - ) - } else if (typeof destinationChain === "string") { - destinationChain = bintools.cb58Decode(destinationChain) // - } else if (!(destinationChain instanceof Buffer)) { - throw new ChainIdError( - "Error - AVMAPI.buildExportTx: Invalid destinationChain type: " + - typeof destinationChain - ) - } - if (destinationChain.length !== 32) { - throw new ChainIdError( - "Error - AVMAPI.buildExportTx: Destination ChainID must be 32 bytes in length." - ) - } - - const to: Buffer[] = [] - toAddresses.map((a: string): void => { - to.push(bintools.stringToAddress(a)) - }) - - const caller: string = "buildExportTx" - const from: Buffer[] = this._cleanAddressArray(fromAddresses, caller).map( - (a: string): Buffer => bintools.stringToAddress(a) - ) - - const change: Buffer[] = this._cleanAddressArray( - changeAddresses, - caller - ).map((a: string): Buffer => bintools.stringToAddress(a)) - - if (memo instanceof PayloadBase) { - memo = memo.getPayload() - } - - const avaxAssetID: Buffer = await this.getAVAXAssetID() - if (typeof assetID === "undefined") { - assetID = bintools.cb58Encode(avaxAssetID) - } - - const networkID: number = this.core.getNetworkID() - const blockchainID: Buffer = bintools.cb58Decode(this.blockchainID) - const assetIDBuf: Buffer = bintools.cb58Decode(assetID) - const fee: BN = this.getTxFee() - const builtUnsignedTx: UnsignedTx = utxoset.buildExportTx( - networkID, - blockchainID, - amount, - assetIDBuf, - to, - from, - change, - destinationChain, - fee, - avaxAssetID, - memo, - asOf, - locktime, - threshold - ) - - if (!(await this.checkGooseEgg(builtUnsignedTx))) { - /* istanbul ignore next */ - throw new GooseEggCheckError( - "Error - AVMAPI.buildExportTx:Failed Goose Egg Check" - ) - } - - return builtUnsignedTx - } - - /** - * Creates an unsigned transaction. For more granular control, you may create your own - * [[UnsignedTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s, and [[TransferOperation]]s). - * - * @param utxoset A set of UTXOs that the transaction is built on - * @param fromAddresses The addresses being used to send the funds from the UTXOs {@link https://github.com/feross/buffer|Buffer} - * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs - * @param initialState The [[InitialStates]] that represent the intial state of a created asset - * @param name String for the descriptive name of the asset - * @param symbol String for the ticker symbol of the asset - * @param denomination Number for the denomination which is 10^D. D must be >= 0 and <= 32. Ex: $1 AVAX = 10^9 $nAVAX - * @param mintOutputs Optional. Array of [[SECPMintOutput]]s to be included in the transaction. These outputs can be spent to mint more tokens. - * @param memo Optional CB58 Buffer or String which contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * - * @returns An unsigned transaction ([[UnsignedTx]]) which contains a [[CreateAssetTx]]. - * - */ - buildCreateAssetTx = async ( - utxoset: UTXOSet, - fromAddresses: string[], - changeAddresses: string[], - initialStates: InitialStates, - name: string, - symbol: string, - denomination: number, - mintOutputs: SECPMintOutput[] = undefined, - memo: PayloadBase | Buffer = undefined, - asOf: BN = UnixNow() - ): Promise => { - const caller: string = "buildCreateAssetTx" - const from: Buffer[] = this._cleanAddressArray(fromAddresses, caller).map( - (a: string): Buffer => bintools.stringToAddress(a) - ) - const change: Buffer[] = this._cleanAddressArray( - changeAddresses, - caller - ).map((a: string): Buffer => bintools.stringToAddress(a)) - - if (memo instanceof PayloadBase) { - memo = memo.getPayload() - } - - if (symbol.length > AVMConstants.SYMBOLMAXLEN) { - throw new SymbolError( - "Error - AVMAPI.buildCreateAssetTx: Symbols may not exceed length of " + - AVMConstants.SYMBOLMAXLEN - ) - } - if (name.length > AVMConstants.ASSETNAMELEN) { - throw new NameError( - "Error - AVMAPI.buildCreateAssetTx: Names may not exceed length of " + - AVMConstants.ASSETNAMELEN - ) - } - - const networkID: number = this.core.getNetworkID() - const blockchainID: Buffer = bintools.cb58Decode(this.blockchainID) - const avaxAssetID: Buffer = await this.getAVAXAssetID() - const fee: BN = this.getDefaultCreationTxFee() - const builtUnsignedTx: UnsignedTx = utxoset.buildCreateAssetTx( - networkID, - blockchainID, - from, - change, - initialStates, - name, - symbol, - denomination, - mintOutputs, - fee, - avaxAssetID, - memo, - asOf - ) - - if (!(await this.checkGooseEgg(builtUnsignedTx, fee))) { - /* istanbul ignore next */ - throw new GooseEggCheckError( - "Error - AVMAPI.buildCreateAssetTx:Failed Goose Egg Check" - ) - } - - return builtUnsignedTx - } - - buildSECPMintTx = async ( - utxoset: UTXOSet, - mintOwner: SECPMintOutput, - transferOwner: SECPTransferOutput, - fromAddresses: string[], - changeAddresses: string[], - mintUTXOID: string, - memo: PayloadBase | Buffer = undefined, - asOf: BN = UnixNow() - ): Promise => { - const caller: string = "buildSECPMintTx" - const from: Buffer[] = this._cleanAddressArray(fromAddresses, caller).map( - (a: string): Buffer => bintools.stringToAddress(a) - ) - const change: Buffer[] = this._cleanAddressArray( - changeAddresses, - caller - ).map((a: string): Buffer => bintools.stringToAddress(a)) - - if (memo instanceof PayloadBase) { - memo = memo.getPayload() - } - - const networkID: number = this.core.getNetworkID() - const blockchainID: Buffer = bintools.cb58Decode(this.blockchainID) - const avaxAssetID: Buffer = await this.getAVAXAssetID() - const fee: BN = this.getMintTxFee() - const builtUnsignedTx: UnsignedTx = utxoset.buildSECPMintTx( - networkID, - blockchainID, - mintOwner, - transferOwner, - from, - change, - mintUTXOID, - fee, - avaxAssetID, - memo, - asOf - ) - if (!(await this.checkGooseEgg(builtUnsignedTx))) { - /* istanbul ignore next */ - throw new GooseEggCheckError( - "Error - AVMAPI.buildSECPMintTx:Failed Goose Egg Check" - ) - } - return builtUnsignedTx - } - - /** - * Creates an unsigned transaction. For more granular control, you may create your own - * [[UnsignedTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s, and [[TransferOperation]]s). - * - * @param utxoset A set of UTXOs that the transaction is built on - * @param fromAddresses The addresses being used to send the funds from the UTXOs {@link https://github.com/feross/buffer|Buffer} - * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs - * @param minterSets is a list where each element specifies that threshold of the addresses in minters may together mint more of the asset by signing a minting transaction - * @param name String for the descriptive name of the asset - * @param symbol String for the ticker symbol of the asset - * @param memo Optional CB58 Buffer or String which contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param locktime Optional. The locktime field created in the resulting mint output - * - * ```js - * Example minterSets: - * [ - * { - * "minters":[ - * "X-avax1ghstjukrtw8935lryqtnh643xe9a94u3tc75c7" - * ], - * "threshold": 1 - * }, - * { - * "minters": [ - * "X-avax1yell3e4nln0m39cfpdhgqprsd87jkh4qnakklx", - * "X-avax1k4nr26c80jaquzm9369j5a4shmwcjn0vmemcjz", - * "X-avax1ztkzsrjnkn0cek5ryvhqswdtcg23nhge3nnr5e" - * ], - * "threshold": 2 - * } - * ] - * ``` - * - * @returns An unsigned transaction ([[UnsignedTx]]) which contains a [[CreateAssetTx]]. - * - */ - buildCreateNFTAssetTx = async ( - utxoset: UTXOSet, - fromAddresses: string[], - changeAddresses: string[], - minterSets: MinterSet[], - name: string, - symbol: string, - memo: PayloadBase | Buffer = undefined, - asOf: BN = UnixNow(), - locktime: BN = new BN(0) - ): Promise => { - const caller: string = "buildCreateNFTAssetTx" - const from: Buffer[] = this._cleanAddressArray(fromAddresses, caller).map( - (a: string): Buffer => bintools.stringToAddress(a) - ) - const change: Buffer[] = this._cleanAddressArray( - changeAddresses, - caller - ).map((a: string): Buffer => bintools.stringToAddress(a)) - - if (memo instanceof PayloadBase) { - memo = memo.getPayload() - } - - if (name.length > AVMConstants.ASSETNAMELEN) { - /* istanbul ignore next */ - throw new NameError( - "Error - AVMAPI.buildCreateNFTAssetTx: Names may not exceed length of " + - AVMConstants.ASSETNAMELEN - ) - } - if (symbol.length > AVMConstants.SYMBOLMAXLEN) { - /* istanbul ignore next */ - throw new SymbolError( - "Error - AVMAPI.buildCreateNFTAssetTx: Symbols may not exceed length of " + - AVMConstants.SYMBOLMAXLEN - ) - } - const networkID: number = this.core.getNetworkID() - const blockchainID: Buffer = bintools.cb58Decode(this.blockchainID) - const creationTxFee: BN = this.getCreationTxFee() - const avaxAssetID: Buffer = await this.getAVAXAssetID() - const builtUnsignedTx: UnsignedTx = utxoset.buildCreateNFTAssetTx( - networkID, - blockchainID, - from, - change, - minterSets, - name, - symbol, - creationTxFee, - avaxAssetID, - memo, - asOf, - locktime - ) - if (!(await this.checkGooseEgg(builtUnsignedTx, creationTxFee))) { - /* istanbul ignore next */ - throw new GooseEggCheckError( - "Error - AVMAPI.buildCreateNFTAssetTx:Failed Goose Egg Check" - ) - } - return builtUnsignedTx - } - - /** - * Creates an unsigned transaction. For more granular control, you may create your own - * [[UnsignedTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s, and [[TransferOperation]]s). - * - * @param utxoset A set of UTXOs that the transaction is built on - * @param owners Either a single or an array of [[OutputOwners]] to send the nft output - * @param fromAddresses The addresses being used to send the NFT from the utxoID provided - * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs - * @param utxoid A base58 utxoID or an array of base58 utxoIDs for the nft mint output this transaction is sending - * @param groupID Optional. The group this NFT is issued to. - * @param payload Optional. Data for NFT Payload as either a [[PayloadBase]] or a {@link https://github.com/feross/buffer|Buffer} - * @param memo Optional CB58 Buffer or String which contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * - * @returns An unsigned transaction ([[UnsignedTx]]) which contains an [[OperationTx]]. - * - */ - buildCreateNFTMintTx = async ( - utxoset: UTXOSet, - owners: OutputOwners[] | OutputOwners, - fromAddresses: string[], - changeAddresses: string[], - utxoid: string | string[], - groupID: number = 0, - payload: PayloadBase | Buffer = undefined, - memo: PayloadBase | Buffer = undefined, - asOf: BN = UnixNow() - ): Promise => { - const caller: string = "buildCreateNFTMintTx" - const from: Buffer[] = this._cleanAddressArray(fromAddresses, caller).map( - (a: string): Buffer => bintools.stringToAddress(a) - ) - const change: Buffer[] = this._cleanAddressArray( - changeAddresses, - caller - ).map((a: string): Buffer => bintools.stringToAddress(a)) - - if (memo instanceof PayloadBase) { - memo = memo.getPayload() - } - - if (payload instanceof PayloadBase) { - payload = payload.getPayload() - } - - if (typeof utxoid === "string") { - utxoid = [utxoid] - } - - const avaxAssetID: Buffer = await this.getAVAXAssetID() - - if (owners instanceof OutputOwners) { - owners = [owners] - } - - const networkID: number = this.core.getNetworkID() - const blockchainID: Buffer = bintools.cb58Decode(this.blockchainID) - const txFee: BN = this.getTxFee() - const builtUnsignedTx: UnsignedTx = utxoset.buildCreateNFTMintTx( - networkID, - blockchainID, - owners, - from, - change, - utxoid, - groupID, - payload, - txFee, - avaxAssetID, - memo, - asOf - ) - if (!(await this.checkGooseEgg(builtUnsignedTx))) { - /* istanbul ignore next */ - throw new GooseEggCheckError( - "Error - AVMAPI.buildCreateNFTMintTx:Failed Goose Egg Check" - ) - } - return builtUnsignedTx - } - - /** - * Helper function which takes an unsigned transaction and signs it, returning the resulting [[Tx]]. - * - * @param utx The unsigned transaction of type [[UnsignedTx]] - * - * @returns A signed transaction of type [[Tx]] - */ - signTx = (utx: UnsignedTx): Tx => utx.sign(this.keychain) - - /** - * Calls the node's issueTx method from the API and returns the resulting transaction ID as a string. - * - * @param tx A string, {@link https://github.com/feross/buffer|Buffer}, or [[Tx]] representing a transaction - * - * @returns A Promise string representing the transaction ID of the posted transaction. - */ - issueTx = async (tx: string | Buffer | Tx): Promise => { - let Transaction = "" - if (typeof tx === "string") { - Transaction = tx - } else if (tx instanceof Buffer) { - const txobj: Tx = new Tx() - txobj.fromBuffer(tx) - Transaction = txobj.toStringHex() - } else if (tx instanceof Tx) { - Transaction = tx.toStringHex() - } else { - /* istanbul ignore next */ - throw new TransactionError( - "Error - AVMAPI.issueTx: provided tx is not expected type of string, Buffer, or Tx" - ) - } - const params: IssueTxParams = { - tx: Transaction.toString(), - encoding: "hex" - } - const response: RequestResponseData = await this.callMethod( - "avm.issueTx", - params - ) - return response.data.result.txID - } - - /** - * Calls the node's getAddressTxs method from the API and returns transactions corresponding to the provided address and assetID - * - * @param address The address for which we're fetching related transactions. - * @param cursor Page number or offset. - * @param pageSize Number of items to return per page. Optional. Defaults to 1024. If [pageSize] == 0 or [pageSize] > [maxPageSize], then it fetches at max [maxPageSize] transactions - * @param assetID Only return transactions that changed the balance of this asset. Must be an ID or an alias for an asset. - * - * @returns A promise object representing the array of transaction IDs and page offset - */ - getAddressTxs = async ( - address: string, - cursor: number, - pageSize: number | undefined, - assetID: string | Buffer - ): Promise => { - let asset: string - let pageSizeNum: number - - if (typeof assetID !== "string") { - asset = bintools.cb58Encode(assetID) - } else { - asset = assetID - } - - if (typeof pageSize !== "number") { - pageSizeNum = 0 - } else { - pageSizeNum = pageSize - } - - const params: GetAddressTxsParams = { - address, - cursor, - pageSize: pageSizeNum, - assetID: asset - } - - const response: RequestResponseData = await this.callMethod( - "avm.getAddressTxs", - params - ) - return response.data.result - } - - /** - * Sends an amount of assetID to the specified address from a list of owned of addresses. - * - * @param username The user that owns the private keys associated with the `from` addresses - * @param password The password unlocking the user - * @param assetID The assetID of the asset to send - * @param amount The amount of the asset to be sent - * @param to The address of the recipient - * @param from Optional. An array of addresses managed by the node's keystore for this blockchain which will fund this transaction - * @param changeAddr Optional. An address to send the change - * @param memo Optional. CB58 Buffer or String which contains arbitrary bytes, up to 256 bytes - * - * @returns Promise for the string representing the transaction's ID. - */ - send = async ( - username: string, - password: string, - assetID: string | Buffer, - amount: number | BN, - to: string, - from: string[] | Buffer[] = undefined, - changeAddr: string = undefined, - memo: string | Buffer = undefined - ): Promise => { - let asset: string - let amnt: BN - - if (typeof this.parseAddress(to) === "undefined") { - /* istanbul ignore next */ - throw new AddressError("Error - AVMAPI.send: Invalid address format") - } - - if (typeof assetID !== "string") { - asset = bintools.cb58Encode(assetID) - } else { - asset = assetID - } - if (typeof amount === "number") { - amnt = new BN(amount) - } else { - amnt = amount - } - - const params: SendParams = { - username: username, - password: password, - assetID: asset, - amount: amnt.toString(10), - to: to - } - - const caller: string = "send" - from = this._cleanAddressArray(from, caller) - if (typeof from !== "undefined") { - params["from"] = from - } - - if (typeof changeAddr !== "undefined") { - if (typeof this.parseAddress(changeAddr) === "undefined") { - /* istanbul ignore next */ - throw new AddressError("Error - AVMAPI.send: Invalid address format") - } - params["changeAddr"] = changeAddr - } - - if (typeof memo !== "undefined") { - if (typeof memo !== "string") { - params["memo"] = bintools.cb58Encode(memo) - } else { - params["memo"] = memo - } - } - const response: RequestResponseData = await this.callMethod( - "avm.send", - params - ) - return response.data.result - } - - /** - * Sends an amount of assetID to an array of specified addresses from a list of owned of addresses. - * - * @param username The user that owns the private keys associated with the `from` addresses - * @param password The password unlocking the user - * @param sendOutputs The array of SendOutputs. A SendOutput is an object literal which contains an assetID, amount, and to. - * @param from Optional. An array of addresses managed by the node's keystore for this blockchain which will fund this transaction - * @param changeAddr Optional. An address to send the change - * @param memo Optional. CB58 Buffer or String which contains arbitrary bytes, up to 256 bytes - * - * @returns Promise for the string representing the transaction"s ID. - */ - sendMultiple = async ( - username: string, - password: string, - sendOutputs: { - assetID: string | Buffer - amount: number | BN - to: string - }[], - from: string[] | Buffer[] = undefined, - changeAddr: string = undefined, - memo: string | Buffer = undefined - ): Promise => { - let asset: string - let amnt: BN - const sOutputs: SOutputsParams[] = [] - - sendOutputs.forEach( - (output: { - assetID: string | Buffer - amount: number | BN - to: string - }) => { - if (typeof this.parseAddress(output.to) === "undefined") { - /* istanbul ignore next */ - throw new AddressError( - "Error - AVMAPI.sendMultiple: Invalid address format" - ) - } - if (typeof output.assetID !== "string") { - asset = bintools.cb58Encode(output.assetID) - } else { - asset = output.assetID - } - if (typeof output.amount === "number") { - amnt = new BN(output.amount) - } else { - amnt = output.amount - } - sOutputs.push({ - to: output.to, - assetID: asset, - amount: amnt.toString(10) - }) - } - ) - - const params: SendMultipleParams = { - username: username, - password: password, - outputs: sOutputs - } - - const caller: string = "send" - from = this._cleanAddressArray(from, caller) - if (typeof from !== "undefined") { - params.from = from - } - - if (typeof changeAddr !== "undefined") { - if (typeof this.parseAddress(changeAddr) === "undefined") { - /* istanbul ignore next */ - throw new AddressError("Error - AVMAPI.send: Invalid address format") - } - params.changeAddr = changeAddr - } - - if (typeof memo !== "undefined") { - if (typeof memo !== "string") { - params.memo = bintools.cb58Encode(memo) - } else { - params.memo = memo - } - } - const response: RequestResponseData = await this.callMethod( - "avm.sendMultiple", - params - ) - return response.data.result - } - - /** - * Given a JSON representation of this Virtual Machine’s genesis state, create the byte representation of that state. - * - * @param genesisData The blockchain's genesis data object - * - * @returns Promise of a string of bytes - */ - buildGenesis = async (genesisData: object): Promise => { - const params: BuildGenesisParams = { - genesisData - } - const response: RequestResponseData = await this.callMethod( - "avm.buildGenesis", - params - ) - return response.data.result.bytes - } - - /** - * @ignore - */ - protected _cleanAddressArray( - addresses: string[] | Buffer[], - caller: string - ): string[] { - const addrs: string[] = [] - const chainID: string = this.getBlockchainAlias() - ? this.getBlockchainAlias() - : this.getBlockchainID() - if (addresses && addresses.length > 0) { - for (let i: number = 0; i < addresses.length; i++) { - if (typeof addresses[`${i}`] === "string") { - if ( - typeof this.parseAddress(addresses[`${i}`] as string) === - "undefined" - ) { - /* istanbul ignore next */ - throw new AddressError( - "Error - AVMAPI.${caller}: Invalid address format" - ) - } - addrs.push(addresses[`${i}`] as string) - } else { - const type: SerializedType = "bech32" - addrs.push( - serialization.bufferToType( - addresses[`${i}`] as Buffer, - type, - this.core.getHRP(), - chainID - ) - ) - } - } - } - return addrs - } - - /** - * This class should not be instantiated directly. Instead use the [[Avalanche.addAP`${I}`]] method. - * - * @param core A reference to the Avalanche class - * @param baseURL Defaults to the string "/ext/bc/X" as the path to blockchain's baseURL - * @param blockchainID The Blockchain"s ID. Defaults to an empty string: "" - */ - constructor( - core: AvalancheCore, - baseURL: string = "/ext/bc/X", - blockchainID: string = "" - ) { - super(core, baseURL) - this.blockchainID = blockchainID - const netID: number = core.getNetworkID() - if ( - netID in Defaults.network && - blockchainID in Defaults.network[`${netID}`] - ) { - const alias: string = - Defaults.network[`${netID}`][`${blockchainID}`]["alias"] - this.keychain = new KeyChain(this.core.getHRP(), alias) - } else { - this.keychain = new KeyChain(this.core.getHRP(), blockchainID) - } - } -} diff --git a/src/apis/avm/basetx.ts b/src/apis/avm/basetx.ts deleted file mode 100644 index 472ca491f..000000000 --- a/src/apis/avm/basetx.ts +++ /dev/null @@ -1,209 +0,0 @@ -/** - * @packageDocumentation - * @module API-AVM-BaseTx - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { AVMConstants } from "./constants" -import { TransferableOutput } from "./outputs" -import { TransferableInput } from "./inputs" -import { SelectCredentialClass } from "./credentials" -import { KeyChain, KeyPair } from "./keychain" -import { StandardBaseTx } from "../../common/tx" -import { Signature, SigIdx, Credential } from "../../common/credentials" -import { DefaultNetworkID } from "../../utils/constants" -import { SelectTxClass } from "./tx" -import { - Serialization, - SerializedEncoding, - SerializedType -} from "../../utils/serialization" -import { CodecIdError } from "../../utils/errors" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() -const decimalString: SerializedType = "decimalString" -const buffer: SerializedType = "Buffer" -const display: SerializedEncoding = "display" - -/** - * Class representing a base for all transactions. - */ -export class BaseTx extends StandardBaseTx { - protected _typeName = "BaseTx" - protected _codecID = AVMConstants.LATESTCODEC - protected _typeID = - this._codecID === 0 ? AVMConstants.BASETX : AVMConstants.BASETX_CODECONE - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.outs = fields["outs"].map((o: TransferableOutput) => { - let newOut: TransferableOutput = new TransferableOutput() - newOut.deserialize(o, encoding) - return newOut - }) - this.ins = fields["ins"].map((i: TransferableInput) => { - let newIn: TransferableInput = new TransferableInput() - newIn.deserialize(i, encoding) - return newIn - }) - this.numouts = serialization.decoder( - this.outs.length.toString(), - display, - decimalString, - buffer, - 4 - ) - this.numins = serialization.decoder( - this.ins.length.toString(), - display, - decimalString, - buffer, - 4 - ) - } - - getOuts(): TransferableOutput[] { - return this.outs as TransferableOutput[] - } - - getIns(): TransferableInput[] { - return this.ins as TransferableInput[] - } - - getTotalOuts(): TransferableOutput[] { - return this.getOuts() as TransferableOutput[] - } - - /** - * Set the codecID - * - * @param codecID The codecID to set - */ - setCodecID(codecID: number): void { - if (codecID !== 0 && codecID !== 1) { - /* istanbul ignore next */ - throw new CodecIdError( - "Error - BaseTx.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - } - this._codecID = codecID - this._typeID = - this._codecID === 0 ? AVMConstants.BASETX : AVMConstants.BASETX_CODECONE - } - - /** - * Returns the id of the [[BaseTx]] - */ - getTxType(): number { - return this._typeID - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[BaseTx]], parses it, populates the class, and returns the length of the BaseTx in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[BaseTx]] - * - * @returns The length of the raw [[BaseTx]] - * - * @remarks assume not-checksummed - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.networkID = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - this.blockchainID = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - this.numouts = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const outcount: number = this.numouts.readUInt32BE(0) - this.outs = [] - for (let i: number = 0; i < outcount; i++) { - const xferout: TransferableOutput = new TransferableOutput() - offset = xferout.fromBuffer(bytes, offset) - this.outs.push(xferout) - } - - this.numins = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const incount: number = this.numins.readUInt32BE(0) - this.ins = [] - for (let i: number = 0; i < incount; i++) { - const xferin: TransferableInput = new TransferableInput() - offset = xferin.fromBuffer(bytes, offset) - this.ins.push(xferin) - } - let memolen: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.memo = bintools.copyFrom(bytes, offset, offset + memolen) - offset += memolen - return offset - } - - /** - * Takes the bytes of an [[UnsignedTx]] and returns an array of [[Credential]]s - * - * @param msg A Buffer for the [[UnsignedTx]] - * @param kc An [[KeyChain]] used in signing - * - * @returns An array of [[Credential]]s - */ - sign(msg: Buffer, kc: KeyChain): Credential[] { - const creds: Credential[] = [] - for (let i: number = 0; i < this.ins.length; i++) { - const cred: Credential = SelectCredentialClass( - this.ins[`${i}`].getInput().getCredentialID() - ) - const sigidxs: SigIdx[] = this.ins[`${i}`].getInput().getSigIdxs() - for (let j: number = 0; j < sigidxs.length; j++) { - const keypair: KeyPair = kc.getKey(sigidxs[`${j}`].getSource()) - const signval: Buffer = keypair.sign(msg) - const sig: Signature = new Signature() - sig.fromBuffer(signval) - cred.addSignature(sig) - } - creds.push(cred) - } - return creds - } - - clone(): this { - let newbase: BaseTx = new BaseTx() - newbase.fromBuffer(this.toBuffer()) - return newbase as this - } - - create(...args: any[]): this { - return new BaseTx(...args) as this - } - - select(id: number, ...args: any[]): this { - let newbasetx: BaseTx = SelectTxClass(id, ...args) - return newbasetx as this - } - - /** - * Class representing a BaseTx which is the foundation for all transactions. - * - * @param networkID Optional networkID, [[DefaultNetworkID]] - * @param blockchainID Optional blockchainID, default Buffer.alloc(32, 16) - * @param outs Optional array of the [[TransferableOutput]]s - * @param ins Optional array of the [[TransferableInput]]s - * @param memo Optional {@link https://github.com/feross/buffer|Buffer} for the memo field - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: Buffer = Buffer.alloc(32, 16), - outs: TransferableOutput[] = undefined, - ins: TransferableInput[] = undefined, - memo: Buffer = undefined - ) { - super(networkID, blockchainID, outs, ins, memo) - } -} diff --git a/src/apis/avm/constants.ts b/src/apis/avm/constants.ts deleted file mode 100644 index 05a15ef55..000000000 --- a/src/apis/avm/constants.ts +++ /dev/null @@ -1,86 +0,0 @@ -/** - * @packageDocumentation - * @module API-AVM-Constants - */ - -export class AVMConstants { - static LATESTCODEC: number = 0 - - static SECPFXID: number = 0 - - static NFTFXID: number = 1 - - static SECPMINTOUTPUTID: number = 6 - - static SECPMINTOUTPUTID_CODECONE: number = 65537 - - static SECPXFEROUTPUTID: number = 7 - - static SECPXFEROUTPUTID_CODECONE: number = 65538 - - static NFTXFEROUTPUTID: number = 11 - - static NFTXFEROUTPUTID_CODECONE: number = 131073 - - static NFTMINTOUTPUTID: number = 10 - - static NFTMINTOUTPUTID_CODECONE: number = 131072 - - static SECPINPUTID: number = 5 - - static SECPINPUTID_CODECONE: number = 65536 - - static SECPMINTOPID: number = 8 - - static SECPMINTOPID_CODECONE: number = 65539 - - static NFTMINTOPID: number = 12 - - static NFTMINTOPID_CODECONE: number = 131074 - - static NFTXFEROPID: number = 13 - - static NFTXFEROPID_CODECONE: number = 131075 - - static VERTEX: number = 0 - - static VERTEX_CODECONE: number = 0 - - static BASETX: number = 0 - - static BASETX_CODECONE: number = 0 - - static CREATEASSETTX: number = 1 - - static CREATEASSETTX_CODECONE: number = 1 - - static OPERATIONTX: number = 2 - - static OPERATIONTX_CODECONE: number = 2 - - static IMPORTTX: number = 3 - - static IMPORTTX_CODECONE: number = 3 - - static EXPORTTX: number = 4 - - static EXPORTTX_CODECONE: number = 4 - - static SECPCREDENTIAL: number = 9 - - static SECPCREDENTIAL_CODECONE: number = 65540 - - static NFTCREDENTIAL: number = 14 - - static NFTCREDENTIAL_CODECONE: number = 131076 - - static ASSETIDLEN: number = 32 - - static BLOCKCHAINIDLEN: number = 32 - - static SYMBOLMAXLEN: number = 4 - - static ASSETNAMELEN: number = 128 - - static ADDRESSLENGTH: number = 20 -} diff --git a/src/apis/avm/createassettx.ts b/src/apis/avm/createassettx.ts deleted file mode 100644 index 7b065ffe7..000000000 --- a/src/apis/avm/createassettx.ts +++ /dev/null @@ -1,260 +0,0 @@ -/** - * @packageDocumentation - * @module API-AVM-CreateAssetTx - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { AVMConstants } from "./constants" -import { TransferableOutput } from "./outputs" -import { TransferableInput } from "./inputs" -import { InitialStates } from "./initialstates" -import { BaseTx } from "./basetx" -import { DefaultNetworkID } from "../../utils/constants" -import { - Serialization, - SerializedEncoding, - SerializedType -} from "../../utils/serialization" -import { CodecIdError } from "../../utils/errors" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() -const utf8: SerializedType = "utf8" -const decimalString: SerializedType = "decimalString" -const buffer: SerializedType = "Buffer" - -export class CreateAssetTx extends BaseTx { - protected _typeName = "CreateAssetTx" - protected _codecID = AVMConstants.LATESTCODEC - protected _typeID = - this._codecID === 0 - ? AVMConstants.CREATEASSETTX - : AVMConstants.CREATEASSETTX_CODECONE - - serialize(encoding: SerializedEncoding = "hex"): object { - const fields: object = super.serialize(encoding) - return { - ...fields, - name: serialization.encoder(this.name, encoding, utf8, utf8), - symbol: serialization.encoder(this.symbol, encoding, utf8, utf8), - denomination: serialization.encoder( - this.denomination, - encoding, - buffer, - decimalString, - 1 - ), - initialState: this.initialState.serialize(encoding) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.name = serialization.decoder(fields["name"], encoding, utf8, utf8) - this.symbol = serialization.decoder(fields["symbol"], encoding, utf8, utf8) - this.denomination = serialization.decoder( - fields["denomination"], - encoding, - decimalString, - buffer, - 1 - ) - this.initialState = new InitialStates() - this.initialState.deserialize(fields["initialState"], encoding) - } - - protected name: string = "" - protected symbol: string = "" - protected denomination: Buffer = Buffer.alloc(1) - protected initialState: InitialStates = new InitialStates() - - /** - * Set the codecID - * - * @param codecID The codecID to set - */ - setCodecID(codecID: number): void { - if (codecID !== 0 && codecID !== 1) { - /* istanbul ignore next */ - throw new CodecIdError( - "Error - CreateAssetTx.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - } - this._codecID = codecID - this._typeID = - this._codecID === 0 - ? AVMConstants.CREATEASSETTX - : AVMConstants.CREATEASSETTX_CODECONE - } - - /** - * Returns the id of the [[CreateAssetTx]] - */ - getTxType(): number { - return this._typeID - } - - /** - * Returns the array of array of [[Output]]s for the initial state - */ - getInitialStates(): InitialStates { - return this.initialState - } - - /** - * Returns the string representation of the name - */ - getName(): string { - return this.name - } - - /** - * Returns the string representation of the symbol - */ - getSymbol(): string { - return this.symbol - } - - /** - * Returns the numeric representation of the denomination - */ - getDenomination(): number { - return this.denomination.readUInt8(0) - } - - /** - * Returns the {@link https://github.com/feross/buffer|Buffer} representation of the denomination - */ - getDenominationBuffer(): Buffer { - return this.denomination - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[CreateAssetTx]], parses it, populates the class, and returns the length of the [[CreateAssetTx]] in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[CreateAssetTx]] - * - * @returns The length of the raw [[CreateAssetTx]] - * - * @remarks assume not-checksummed - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - - const namesize: number = bintools - .copyFrom(bytes, offset, offset + 2) - .readUInt16BE(0) - offset += 2 - this.name = bintools - .copyFrom(bytes, offset, offset + namesize) - .toString("utf8") - offset += namesize - - const symsize: number = bintools - .copyFrom(bytes, offset, offset + 2) - .readUInt16BE(0) - offset += 2 - this.symbol = bintools - .copyFrom(bytes, offset, offset + symsize) - .toString("utf8") - offset += symsize - - this.denomination = bintools.copyFrom(bytes, offset, offset + 1) - offset += 1 - - const inits: InitialStates = new InitialStates() - offset = inits.fromBuffer(bytes, offset) - this.initialState = inits - - return offset - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[CreateAssetTx]]. - */ - toBuffer(): Buffer { - const superbuff: Buffer = super.toBuffer() - const initstatebuff: Buffer = this.initialState.toBuffer() - - const namebuff: Buffer = Buffer.alloc(this.name.length) - namebuff.write(this.name, 0, this.name.length, utf8) - const namesize: Buffer = Buffer.alloc(2) - namesize.writeUInt16BE(this.name.length, 0) - - const symbuff: Buffer = Buffer.alloc(this.symbol.length) - symbuff.write(this.symbol, 0, this.symbol.length, utf8) - const symsize: Buffer = Buffer.alloc(2) - symsize.writeUInt16BE(this.symbol.length, 0) - - const bsize: number = - superbuff.length + - namesize.length + - namebuff.length + - symsize.length + - symbuff.length + - this.denomination.length + - initstatebuff.length - const barr: Buffer[] = [ - superbuff, - namesize, - namebuff, - symsize, - symbuff, - this.denomination, - initstatebuff - ] - return Buffer.concat(barr, bsize) - } - - clone(): this { - let newbase: CreateAssetTx = new CreateAssetTx() - newbase.fromBuffer(this.toBuffer()) - return newbase as this - } - - create(...args: any[]): this { - return new CreateAssetTx(...args) as this - } - - /** - * Class representing an unsigned Create Asset transaction. - * - * @param networkID Optional networkID, [[DefaultNetworkID]] - * @param blockchainID Optional blockchainID, default Buffer.alloc(32, 16) - * @param outs Optional array of the [[TransferableOutput]]s - * @param ins Optional array of the [[TransferableInput]]s - * @param memo Optional {@link https://github.com/feross/buffer|Buffer} for the memo field - * @param name String for the descriptive name of the asset - * @param symbol String for the ticker symbol of the asset - * @param denomination Optional number for the denomination which is 10^D. D must be >= 0 and <= 32. Ex: $1 AVAX = 10^9 $nAVAX - * @param initialState Optional [[InitialStates]] that represent the intial state of a created asset - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: Buffer = Buffer.alloc(32, 16), - outs: TransferableOutput[] = undefined, - ins: TransferableInput[] = undefined, - memo: Buffer = undefined, - name: string = undefined, - symbol: string = undefined, - denomination: number = undefined, - initialState: InitialStates = undefined - ) { - super(networkID, blockchainID, outs, ins, memo) - if ( - typeof name === "string" && - typeof symbol === "string" && - typeof denomination === "number" && - denomination >= 0 && - denomination <= 32 && - typeof initialState !== "undefined" - ) { - this.initialState = initialState - this.name = name - this.symbol = symbol - this.denomination.writeUInt8(denomination, 0) - } - } -} diff --git a/src/apis/avm/credentials.ts b/src/apis/avm/credentials.ts deleted file mode 100644 index d22714be8..000000000 --- a/src/apis/avm/credentials.ts +++ /dev/null @@ -1,133 +0,0 @@ -/** - * @packageDocumentation - * @module API-AVM-Credentials - */ - -import { AVMConstants } from "./constants" -import { Credential } from "../../common/credentials" -import { CredIdError, CodecIdError } from "../../utils/errors" - -/** - * Takes a buffer representing the credential and returns the proper [[Credential]] instance. - * - * @param credid A number representing the credential ID parsed prior to the bytes passed in - * - * @returns An instance of an [[Credential]]-extended class. - */ -export const SelectCredentialClass = ( - credid: number, - ...args: any[] -): Credential => { - if ( - credid === AVMConstants.SECPCREDENTIAL || - credid === AVMConstants.SECPCREDENTIAL_CODECONE - ) { - return new SECPCredential(...args) - } - if ( - credid === AVMConstants.NFTCREDENTIAL || - credid === AVMConstants.NFTCREDENTIAL_CODECONE - ) { - return new NFTCredential(...args) - } - /* istanbul ignore next */ - throw new CredIdError("Error - SelectCredentialClass: unknown credid") -} - -export class SECPCredential extends Credential { - protected _typeName = "SECPCredential" - protected _codecID = AVMConstants.LATESTCODEC - protected _typeID = - this._codecID === 0 - ? AVMConstants.SECPCREDENTIAL - : AVMConstants.SECPCREDENTIAL_CODECONE - - //serialize and deserialize both are inherited - - /** - * Set the codecID - * - * @param codecID The codecID to set - */ - setCodecID(codecID: number): void { - if (codecID !== 0 && codecID !== 1) { - /* istanbul ignore next */ - throw new CodecIdError( - "Error - SECPCredential.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - } - this._codecID = codecID - this._typeID = - this._codecID === 0 - ? AVMConstants.SECPCREDENTIAL - : AVMConstants.SECPCREDENTIAL_CODECONE - } - - getCredentialID(): number { - return this._typeID - } - - clone(): this { - let newbase: SECPCredential = new SECPCredential() - newbase.fromBuffer(this.toBuffer()) - return newbase as this - } - - create(...args: any[]): this { - return new SECPCredential(...args) as this - } - - select(id: number, ...args: any[]): Credential { - let newbasetx: Credential = SelectCredentialClass(id, ...args) - return newbasetx - } -} - -export class NFTCredential extends Credential { - protected _typeName = "NFTCredential" - protected _codecID = AVMConstants.LATESTCODEC - protected _typeID = - this._codecID === 0 - ? AVMConstants.NFTCREDENTIAL - : AVMConstants.NFTCREDENTIAL_CODECONE - - //serialize and deserialize both are inherited - - /** - * Set the codecID - * - * @param codecID The codecID to set - */ - setCodecID(codecID: number): void { - if (codecID !== 0 && codecID !== 1) { - /* istanbul ignore next */ - throw new CodecIdError( - "Error - NFTCredential.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - } - this._codecID = codecID - this._typeID = - this._codecID === 0 - ? AVMConstants.NFTCREDENTIAL - : AVMConstants.NFTCREDENTIAL_CODECONE - } - - getCredentialID(): number { - return this._typeID - } - - clone(): this { - let newbase: NFTCredential = new NFTCredential() - newbase.fromBuffer(this.toBuffer()) - return newbase as this - } - - create(...args: any[]): this { - return new NFTCredential(...args) as this - } - - select(id: number, ...args: any[]): Credential { - let newbasetx: Credential = SelectCredentialClass(id, ...args) - return newbasetx - } -} diff --git a/src/apis/avm/exporttx.ts b/src/apis/avm/exporttx.ts deleted file mode 100644 index 80b0a5eb0..000000000 --- a/src/apis/avm/exporttx.ts +++ /dev/null @@ -1,223 +0,0 @@ -/** - * @packageDocumentation - * @module API-AVM-ExportTx - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { AVMConstants } from "./constants" -import { TransferableOutput, AmountOutput } from "./outputs" -import { TransferableInput } from "./inputs" -import { BaseTx } from "./basetx" -import { DefaultNetworkID } from "../../utils/constants" -import BN from "bn.js" -import { - Serialization, - SerializedEncoding, - SerializedType -} from "../../utils/serialization" -import { - CodecIdError, - ChainIdError, - TransferableOutputError -} from "../../utils/errors" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() -const cb58: SerializedType = "cb58" -const buffer: SerializedType = "Buffer" - -/** - * Class representing an unsigned Export transaction. - */ -export class ExportTx extends BaseTx { - protected _typeName = "ExportTx" - protected _codecID = AVMConstants.LATESTCODEC - protected _typeID = - this._codecID === 0 ? AVMConstants.EXPORTTX : AVMConstants.EXPORTTX_CODECONE - - serialize(encoding: SerializedEncoding = "hex"): object { - const fields: object = super.serialize(encoding) - return { - ...fields, - destinationChain: serialization.encoder( - this.destinationChain, - encoding, - buffer, - cb58 - ), - exportOuts: this.exportOuts.map((e) => e.serialize(encoding)) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.destinationChain = serialization.decoder( - fields["destinationChain"], - encoding, - cb58, - buffer, - 32 - ) - this.exportOuts = fields["exportOuts"].map( - (e: object): TransferableOutput => { - let eo: TransferableOutput = new TransferableOutput() - eo.deserialize(e, encoding) - return eo - } - ) - this.numOuts = Buffer.alloc(4) - this.numOuts.writeUInt32BE(this.exportOuts.length, 0) - } - - protected destinationChain: Buffer = undefined - protected numOuts: Buffer = Buffer.alloc(4) - protected exportOuts: TransferableOutput[] = [] - - /** - * Set the codecID - * - * @param codecID The codecID to set - */ - setCodecID(codecID: number): void { - if (codecID !== 0 && codecID !== 1) { - /* istanbul ignore next */ - throw new CodecIdError( - "Error - ExportTx.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - } - this._codecID = codecID - this._typeID = - this._codecID === 0 - ? AVMConstants.EXPORTTX - : AVMConstants.EXPORTTX_CODECONE - } - - /** - * Returns the id of the [[ExportTx]] - */ - getTxType(): number { - return this._typeID - } - - /** - * Returns an array of [[TransferableOutput]]s in this transaction. - */ - getExportOutputs(): TransferableOutput[] { - return this.exportOuts - } - - /** - * Returns the totall exported amount as a {@link https://github.com/indutny/bn.js/|BN}. - */ - getExportTotal(): BN { - let val: BN = new BN(0) - for (let i: number = 0; i < this.exportOuts.length; i++) { - val = val.add( - (this.exportOuts[`${i}`].getOutput() as AmountOutput).getAmount() - ) - } - return val - } - - getTotalOuts(): TransferableOutput[] { - return [ - ...(this.getOuts() as TransferableOutput[]), - ...this.getExportOutputs() - ] - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} for the destination chainid. - */ - getDestinationChain(): Buffer { - return this.destinationChain - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[ExportTx]], parses it, populates the class, and returns the length of the [[ExportTx]] in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[ExportTx]] - * - * @returns The length of the raw [[ExportTx]] - * - * @remarks assume not-checksummed - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - this.destinationChain = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - this.numOuts = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const numOuts: number = this.numOuts.readUInt32BE(0) - for (let i: number = 0; i < numOuts; i++) { - const anOut: TransferableOutput = new TransferableOutput() - offset = anOut.fromBuffer(bytes, offset) - this.exportOuts.push(anOut) - } - return offset - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[ExportTx]]. - */ - toBuffer(): Buffer { - if (typeof this.destinationChain === "undefined") { - throw new ChainIdError( - "ExportTx.toBuffer -- this.destinationChain is undefined" - ) - } - this.numOuts.writeUInt32BE(this.exportOuts.length, 0) - let barr: Buffer[] = [super.toBuffer(), this.destinationChain, this.numOuts] - this.exportOuts = this.exportOuts.sort(TransferableOutput.comparator()) - for (let i: number = 0; i < this.exportOuts.length; i++) { - barr.push(this.exportOuts[`${i}`].toBuffer()) - } - return Buffer.concat(barr) - } - - clone(): this { - let newbase: ExportTx = new ExportTx() - newbase.fromBuffer(this.toBuffer()) - return newbase as this - } - - create(...args: any[]): this { - return new ExportTx(...args) as this - } - - /** - * Class representing an unsigned Export transaction. - * - * @param networkID Optional networkID, [[DefaultNetworkID]] - * @param blockchainID Optional blockchainID, default Buffer.alloc(32, 16) - * @param outs Optional array of the [[TransferableOutput]]s - * @param ins Optional array of the [[TransferableInput]]s - * @param memo Optional {@link https://github.com/feross/buffer|Buffer} for the memo field - * @param destinationChain Optional chainid which identifies where the funds will sent to - * @param exportOuts Array of [[TransferableOutputs]]s used in the transaction - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: Buffer = Buffer.alloc(32, 16), - outs: TransferableOutput[] = undefined, - ins: TransferableInput[] = undefined, - memo: Buffer = undefined, - destinationChain: Buffer = undefined, - exportOuts: TransferableOutput[] = undefined - ) { - super(networkID, blockchainID, outs, ins, memo) - this.destinationChain = destinationChain // no correction, if they don"t pass a chainid here, it will BOMB on toBuffer - if (typeof exportOuts !== "undefined" && Array.isArray(exportOuts)) { - for (let i: number = 0; i < exportOuts.length; i++) { - if (!(exportOuts[`${i}`] instanceof TransferableOutput)) { - throw new TransferableOutputError( - `Error - ExportTx.constructor: invalid TransferableOutput in array parameter ${exportOuts}` - ) - } - } - this.exportOuts = exportOuts - } - } -} diff --git a/src/apis/avm/genesisasset.ts b/src/apis/avm/genesisasset.ts deleted file mode 100644 index 53323ec73..000000000 --- a/src/apis/avm/genesisasset.ts +++ /dev/null @@ -1,217 +0,0 @@ -/** - * @packageDocumentation - * @module API-AVM-GenesisAsset - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { InitialStates } from "./initialstates" -import { DefaultNetworkID } from "../../utils/constants" -import { - Serialization, - SerializedEncoding, - SerializedType -} from "../../utils/serialization" -import { CreateAssetTx } from "./createassettx" -import BN from "bn.js" - -/** - * @ignore - */ -const serialization: Serialization = Serialization.getInstance() -const bintools: BinTools = BinTools.getInstance() -const utf8: SerializedType = "utf8" -const buffer: SerializedType = "Buffer" -const decimalString: SerializedType = "decimalString" - -export class GenesisAsset extends CreateAssetTx { - protected _typeName = "GenesisAsset" - protected _codecID = undefined - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - const fields: object = super.serialize(encoding) - delete fields["blockchainID"] - delete fields["outs"] - delete fields["ins"] - return { - ...fields, - assetAlias: serialization.encoder(this.assetAlias, encoding, utf8, utf8), - name: serialization.encoder(this.name, encoding, utf8, utf8), - symbol: serialization.encoder(this.symbol, encoding, utf8, utf8), - denomination: serialization.encoder( - this.denomination, - encoding, - buffer, - decimalString, - 1 - ), - initialState: this.initialState.serialize(encoding) - } - } - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - fields["blockchainID"] = Buffer.alloc(32, 16).toString("hex") - fields["outs"] = [] - fields["ins"] = [] - super.deserialize(fields, encoding) - this.assetAlias = serialization.decoder( - fields["assetAlias"], - encoding, - utf8, - utf8 - ) - this.name = serialization.decoder(fields["name"], encoding, utf8, utf8) - this.symbol = serialization.decoder(fields["symbol"], encoding, utf8, utf8) - this.denomination = serialization.decoder( - fields["denomination"], - encoding, - decimalString, - buffer, - 1 - ) - this.initialState = new InitialStates() - this.initialState.deserialize(fields["initialState"], encoding) - } - - protected assetAlias: string = "" - - /** - * Returns the string representation of the assetAlias - */ - getAssetAlias = (): string => this.assetAlias - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[GenesisAsset]], parses it, populates the class, and returns the length of the [[GenesisAsset]] in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[GenesisAsset]] - * - * @returns The length of the raw [[GenesisAsset]] - * - * @remarks assume not-checksummed - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - const assetAliasSize: number = bintools - .copyFrom(bytes, offset, offset + 2) - .readUInt16BE(0) - offset += 2 - this.assetAlias = bintools - .copyFrom(bytes, offset, offset + assetAliasSize) - .toString("utf8") - offset += assetAliasSize - offset += super.fromBuffer(bytes, offset) - return offset - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[GenesisAsset]]. - */ - toBuffer(networkID: number = DefaultNetworkID): Buffer { - // asset alias - const assetAlias: string = this.getAssetAlias() - const assetAliasbuffSize: Buffer = Buffer.alloc(2) - assetAliasbuffSize.writeUInt16BE(assetAlias.length, 0) - let bsize: number = assetAliasbuffSize.length - let barr: Buffer[] = [assetAliasbuffSize] - const assetAliasbuff: Buffer = Buffer.alloc(assetAlias.length) - assetAliasbuff.write(assetAlias, 0, assetAlias.length, utf8) - bsize += assetAliasbuff.length - barr.push(assetAliasbuff) - - const networkIDBuff: Buffer = Buffer.alloc(4) - networkIDBuff.writeUInt32BE(new BN(networkID).toNumber(), 0) - bsize += networkIDBuff.length - barr.push(networkIDBuff) - - // Blockchain ID - bsize += 32 - barr.push(Buffer.alloc(32)) - - // num Outputs - bsize += 4 - barr.push(Buffer.alloc(4)) - - // num Inputs - bsize += 4 - barr.push(Buffer.alloc(4)) - - // memo - const memo: Buffer = this.getMemo() - const memobuffSize: Buffer = Buffer.alloc(4) - memobuffSize.writeUInt32BE(memo.length, 0) - bsize += memobuffSize.length - barr.push(memobuffSize) - - bsize += memo.length - barr.push(memo) - - // asset name - const name: string = this.getName() - const namebuffSize: Buffer = Buffer.alloc(2) - namebuffSize.writeUInt16BE(name.length, 0) - bsize += namebuffSize.length - barr.push(namebuffSize) - const namebuff: Buffer = Buffer.alloc(name.length) - namebuff.write(name, 0, name.length, utf8) - bsize += namebuff.length - barr.push(namebuff) - - // symbol - const symbol: string = this.getSymbol() - const symbolbuffSize: Buffer = Buffer.alloc(2) - symbolbuffSize.writeUInt16BE(symbol.length, 0) - bsize += symbolbuffSize.length - barr.push(symbolbuffSize) - - const symbolbuff: Buffer = Buffer.alloc(symbol.length) - symbolbuff.write(symbol, 0, symbol.length, utf8) - bsize += symbolbuff.length - barr.push(symbolbuff) - - // denomination - const denomination: number = this.getDenomination() - const denominationbuffSize: Buffer = Buffer.alloc(1) - denominationbuffSize.writeUInt8(denomination, 0) - bsize += denominationbuffSize.length - barr.push(denominationbuffSize) - - bsize += this.initialState.toBuffer().length - barr.push(this.initialState.toBuffer()) - return Buffer.concat(barr, bsize) - } - - /** - * Class representing a GenesisAsset - * - * @param assetAlias Optional String for the asset alias - * @param name Optional String for the descriptive name of the asset - * @param symbol Optional String for the ticker symbol of the asset - * @param denomination Optional number for the denomination which is 10^D. D must be >= 0 and <= 32. Ex: $1 AVAX = 10^9 $nAVAX - * @param initialState Optional [[InitialStates]] that represent the intial state of a created asset - * @param memo Optional {@link https://github.com/feross/buffer|Buffer} for the memo field - */ - constructor( - assetAlias: string = undefined, - name: string = undefined, - symbol: string = undefined, - denomination: number = undefined, - initialState: InitialStates = undefined, - memo: Buffer = undefined - ) { - super(DefaultNetworkID, Buffer.alloc(32), [], [], memo) - if ( - typeof assetAlias === "string" && - typeof name === "string" && - typeof symbol === "string" && - typeof denomination === "number" && - denomination >= 0 && - denomination <= 32 && - typeof initialState !== "undefined" - ) { - this.assetAlias = assetAlias - this.name = name - this.symbol = symbol - this.denomination.writeUInt8(denomination, 0) - this.initialState = initialState - } - } -} diff --git a/src/apis/avm/genesisdata.ts b/src/apis/avm/genesisdata.ts deleted file mode 100644 index 673113712..000000000 --- a/src/apis/avm/genesisdata.ts +++ /dev/null @@ -1,140 +0,0 @@ -/** - * @packageDocumentation - * @module API-AVM-GenesisData - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { - Serializable, - Serialization, - SerializedEncoding -} from "../../utils/serialization" -import { AVMConstants } from "./constants" -import { GenesisAsset } from "." -import { DefaultNetworkID, SerializedType } from "../../utils" - -/** - * @ignore - */ -const serialization: Serialization = Serialization.getInstance() -const bintools: BinTools = BinTools.getInstance() -const decimalString: SerializedType = "decimalString" -const buffer: SerializedType = "Buffer" - -export class GenesisData extends Serializable { - protected _typeName = "GenesisData" - protected _codecID = AVMConstants.LATESTCODEC - - // TODO - setCodecID? - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - genesisAssets: this.genesisAssets.map((genesisAsset: GenesisAsset) => - genesisAsset.serialize(encoding) - ), - networkID: serialization.encoder( - this.networkID, - encoding, - buffer, - decimalString - ) - } - } - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.genesisAssets = fields["genesisAssets"].map( - (genesisAsset: GenesisAsset): GenesisAsset => { - let g: GenesisAsset = new GenesisAsset() - g.deserialize(genesisAsset, encoding) - return g - } - ) - this.networkID = serialization.decoder( - fields["networkID"], - encoding, - decimalString, - buffer, - 4 - ) - } - - protected genesisAssets: GenesisAsset[] - protected networkID: Buffer = Buffer.alloc(4) - - /** - * Returns the GenesisAssets[] - */ - getGenesisAssets = (): GenesisAsset[] => this.genesisAssets - - /** - * Returns the NetworkID as a number - */ - getNetworkID = (): number => this.networkID.readUInt32BE(0) - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[GenesisAsset]], parses it, populates the class, and returns the length of the [[GenesisAsset]] in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[GenesisAsset]] - * - * @returns The length of the raw [[GenesisAsset]] - * - * @remarks assume not-checksummed - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - this._codecID = bintools.copyFrom(bytes, offset, offset + 2).readUInt16BE(0) - offset += 2 - const numGenesisAssets = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const assetCount: number = numGenesisAssets.readUInt32BE(0) - this.genesisAssets = [] - for (let i: number = 0; i < assetCount; i++) { - const genesisAsset: GenesisAsset = new GenesisAsset() - offset = genesisAsset.fromBuffer(bytes, offset) - this.genesisAssets.push(genesisAsset) - if (i === 0) { - this.networkID.writeUInt32BE(genesisAsset.getNetworkID(), 0) - } - } - return offset - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[GenesisData]]. - */ - toBuffer(): Buffer { - // codec id - const codecbuffSize: Buffer = Buffer.alloc(2) - codecbuffSize.writeUInt16BE(this._codecID, 0) - - // num assets - const numAssetsbuffSize: Buffer = Buffer.alloc(4) - numAssetsbuffSize.writeUInt32BE(this.genesisAssets.length, 0) - - let bsize: number = codecbuffSize.length + numAssetsbuffSize.length - let barr: Buffer[] = [codecbuffSize, numAssetsbuffSize] - - this.genesisAssets.forEach((genesisAsset: GenesisAsset): void => { - const b: Buffer = genesisAsset.toBuffer(this.getNetworkID()) - bsize += b.length - barr.push(b) - }) - return Buffer.concat(barr, bsize) - } - - /** - * Class representing AVM GenesisData - * - * @param genesisAssets Optional GenesisAsset[] - * @param networkID Optional DefaultNetworkID - */ - constructor( - genesisAssets: GenesisAsset[] = [], - networkID: number = DefaultNetworkID - ) { - super() - this.genesisAssets = genesisAssets - this.networkID.writeUInt32BE(networkID, 0) - } -} diff --git a/src/apis/avm/importtx.ts b/src/apis/avm/importtx.ts deleted file mode 100644 index 3458dddb0..000000000 --- a/src/apis/avm/importtx.ts +++ /dev/null @@ -1,229 +0,0 @@ -/** - * @packageDocumentation - * @module API-AVM-ImportTx - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { AVMConstants } from "./constants" -import { TransferableOutput } from "./outputs" -import { TransferableInput } from "./inputs" -import { BaseTx } from "./basetx" -import { SelectCredentialClass } from "./credentials" -import { Signature, SigIdx, Credential } from "../../common/credentials" -import { KeyChain, KeyPair } from "./keychain" -import { DefaultNetworkID } from "../../utils/constants" -import { - Serialization, - SerializedEncoding, - SerializedType -} from "../../utils/serialization" -import { - CodecIdError, - ChainIdError, - TransferableInputError -} from "../../utils/errors" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() -const cb58: SerializedType = "cb58" -const buffer: SerializedType = "Buffer" - -/** - * Class representing an unsigned Import transaction. - */ -export class ImportTx extends BaseTx { - protected _typeName = "ImportTx" - protected _codecID = AVMConstants.LATESTCODEC - protected _typeID = - this._codecID === 0 ? AVMConstants.IMPORTTX : AVMConstants.IMPORTTX_CODECONE - - serialize(encoding: SerializedEncoding = "hex"): object { - const fields: object = super.serialize(encoding) - return { - ...fields, - sourceChain: serialization.encoder( - this.sourceChain, - encoding, - buffer, - cb58 - ), - importIns: this.importIns.map((i) => i.serialize(encoding)) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.sourceChain = serialization.decoder( - fields["sourceChain"], - encoding, - cb58, - buffer, - 32 - ) - this.importIns = fields["importIns"].map((i: object): TransferableInput => { - let ii: TransferableInput = new TransferableInput() - ii.deserialize(i, encoding) - return ii - }) - this.numIns = Buffer.alloc(4) - this.numIns.writeUInt32BE(this.importIns.length, 0) - } - - protected sourceChain: Buffer = Buffer.alloc(32) - protected numIns: Buffer = Buffer.alloc(4) - protected importIns: TransferableInput[] = [] - - /** - * Set the codecID - * - * @param codecID The codecID to set - */ - setCodecID(codecID: number): void { - if (codecID !== 0 && codecID !== 1) { - /* istanbul ignore next */ - throw new CodecIdError( - "Error - ImportTx.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - } - this._codecID = codecID - this._typeID = - this._codecID === 0 - ? AVMConstants.IMPORTTX - : AVMConstants.IMPORTTX_CODECONE - } - - /** - * Returns the id of the [[ImportTx]] - */ - getTxType(): number { - return this._typeID - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} for the source chainid. - */ - getSourceChain(): Buffer { - return this.sourceChain - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[ImportTx]], parses it, populates the class, and returns the length of the [[ImportTx]] in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[ImportTx]] - * - * @returns The length of the raw [[ImportTx]] - * - * @remarks assume not-checksummed - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - this.sourceChain = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - this.numIns = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const numIns: number = this.numIns.readUInt32BE(0) - for (let i: number = 0; i < numIns; i++) { - const anIn: TransferableInput = new TransferableInput() - offset = anIn.fromBuffer(bytes, offset) - this.importIns.push(anIn) - } - return offset - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[ImportTx]]. - */ - toBuffer(): Buffer { - if (typeof this.sourceChain === "undefined") { - throw new ChainIdError( - "ImportTx.toBuffer -- this.sourceChain is undefined" - ) - } - this.numIns.writeUInt32BE(this.importIns.length, 0) - let barr: Buffer[] = [super.toBuffer(), this.sourceChain, this.numIns] - this.importIns = this.importIns.sort(TransferableInput.comparator()) - for (let i: number = 0; i < this.importIns.length; i++) { - barr.push(this.importIns[`${i}`].toBuffer()) - } - return Buffer.concat(barr) - } - /** - * Returns an array of [[TransferableInput]]s in this transaction. - */ - getImportInputs(): TransferableInput[] { - return this.importIns - } - - clone(): this { - let newbase: ImportTx = new ImportTx() - newbase.fromBuffer(this.toBuffer()) - return newbase as this - } - - create(...args: any[]): this { - return new ImportTx(...args) as this - } - - /** - * Takes the bytes of an [[UnsignedTx]] and returns an array of [[Credential]]s - * - * @param msg A Buffer for the [[UnsignedTx]] - * @param kc An [[KeyChain]] used in signing - * - * @returns An array of [[Credential]]s - */ - sign(msg: Buffer, kc: KeyChain): Credential[] { - const creds: Credential[] = super.sign(msg, kc) - for (let i: number = 0; i < this.importIns.length; i++) { - const cred: Credential = SelectCredentialClass( - this.importIns[`${i}`].getInput().getCredentialID() - ) - const sigidxs: SigIdx[] = this.importIns[`${i}`].getInput().getSigIdxs() - for (let j: number = 0; j < sigidxs.length; j++) { - const keypair: KeyPair = kc.getKey(sigidxs[`${j}`].getSource()) - const signval: Buffer = keypair.sign(msg) - const sig: Signature = new Signature() - sig.fromBuffer(signval) - cred.addSignature(sig) - } - creds.push(cred) - } - return creds - } - - /** - * Class representing an unsigned Import transaction. - * - * @param networkID Optional networkID, [[DefaultNetworkID]] - * @param blockchainID Optional blockchainID, default Buffer.alloc(32, 16) - * @param outs Optional array of the [[TransferableOutput]]s - * @param ins Optional array of the [[TransferableInput]]s - * @param memo Optional {@link https://github.com/feross/buffer|Buffer} for the memo field - * @param sourceChain Optional chainid for the source inputs to import. Default platform chainid. - * @param importIns Array of [[TransferableInput]]s used in the transaction - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: Buffer = Buffer.alloc(32, 16), - outs: TransferableOutput[] = undefined, - ins: TransferableInput[] = undefined, - memo: Buffer = undefined, - sourceChain: Buffer = undefined, - importIns: TransferableInput[] = undefined - ) { - super(networkID, blockchainID, outs, ins, memo) - this.sourceChain = sourceChain // do not correct, if it's wrong it'll bomb on toBuffer - if (typeof importIns !== "undefined" && Array.isArray(importIns)) { - for (let i: number = 0; i < importIns.length; i++) { - if (!(importIns[`${i}`] instanceof TransferableInput)) { - throw new TransferableInputError( - `Error - ImportTx.constructor: invalid TransferableInput in array parameter ${importIns}` - ) - } - } - this.importIns = importIns - } - } -} diff --git a/src/apis/avm/index.ts b/src/apis/avm/index.ts deleted file mode 100644 index 3151a258a..000000000 --- a/src/apis/avm/index.ts +++ /dev/null @@ -1,20 +0,0 @@ -export * from "./api" -export * from "./basetx" -export * from "./constants" -export * from "./createassettx" -export * from "./credentials" -export * from "./exporttx" -export * from "./genesisasset" -export * from "./genesisdata" -export * from "./importtx" -export * from "./initialstates" -export * from "./inputs" -export * from "./interfaces" -export * from "./keychain" -export * from "./minterset" -export * from "./operationtx" -export * from "./ops" -export * from "./outputs" -export * from "./tx" -export * from "./utxos" -export * from "./vertex" diff --git a/src/apis/avm/initialstates.ts b/src/apis/avm/initialstates.ts deleted file mode 100644 index b06539363..000000000 --- a/src/apis/avm/initialstates.ts +++ /dev/null @@ -1,117 +0,0 @@ -/** - * @packageDocumentation - * @module API-AVM-InitialStates - */ - -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { Output } from "../../common/output" -import { SelectOutputClass } from "./outputs" -import { AVMConstants } from "./constants" -import { Serializable, SerializedEncoding } from "../../utils/serialization" -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() - -/** - * Class for creating initial output states used in asset creation - */ -export class InitialStates extends Serializable { - protected _typeName = "InitialStates" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - const fields: object = super.serialize(encoding) - const flatfxs: object = {} - for (let fxid in this.fxs) { - flatfxs[`${fxid}`] = this.fxs[`${fxid}`].map((o: Output): object => - o.serialize(encoding) - ) - } - return { - ...fields, - fxs: flatfxs - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - const unflat: { [fxid: number]: Output[] } = {} - for (let fxid in fields["fxs"]) { - unflat[`${fxid}`] = fields["fxs"][`${fxid}`].map((o: object) => { - const out: Output = SelectOutputClass(o["_typeID"]) - out.deserialize(o, encoding) - return out - }) - } - this.fxs = unflat - } - - protected fxs: { [fxid: number]: Output[] } = {} - - /** - * - * @param out The output state to add to the collection - * @param fxid The FxID that will be used for this output, default AVMConstants.SECPFXID - */ - addOutput(out: Output, fxid: number = AVMConstants.SECPFXID): void { - if (!(fxid in this.fxs)) { - this.fxs[`${fxid}`] = [] - } - this.fxs[`${fxid}`].push(out) - } - - fromBuffer(bytes: Buffer, offset: number = 0): number { - const result: { [fxid: number]: Output[] } = [] - const klen: Buffer = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const klennum: number = klen.readUInt32BE(0) - for (let i: number = 0; i < klennum; i++) { - const fxidbuff: Buffer = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const fxid: number = fxidbuff.readUInt32BE(0) - result[`${fxid}`] = [] - const statelenbuff: Buffer = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const statelen: number = statelenbuff.readUInt32BE(0) - for (let j: number = 0; j < statelen; j++) { - const outputid: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - const out: Output = SelectOutputClass(outputid) - offset = out.fromBuffer(bytes, offset) - result[`${fxid}`].push(out) - } - } - this.fxs = result - return offset - } - - toBuffer(): Buffer { - const buff: Buffer[] = [] - const keys: number[] = Object.keys(this.fxs) - .map((k: string): number => parseInt(k, 10)) - .sort() - const klen: Buffer = Buffer.alloc(4) - klen.writeUInt32BE(keys.length, 0) - buff.push(klen) - for (let i: number = 0; i < keys.length; i++) { - const fxid: number = keys[`${i}`] - const fxidbuff: Buffer = Buffer.alloc(4) - fxidbuff.writeUInt32BE(fxid, 0) - buff.push(fxidbuff) - const initialState = this.fxs[`${fxid}`].sort(Output.comparator()) - const statelen: Buffer = Buffer.alloc(4) - statelen.writeUInt32BE(initialState.length, 0) - buff.push(statelen) - for (let j: number = 0; j < initialState.length; j++) { - const outputid: Buffer = Buffer.alloc(4) - outputid.writeInt32BE(initialState[`${j}`].getOutputID(), 0) - buff.push(outputid) - buff.push(initialState[`${j}`].toBuffer()) - } - } - return Buffer.concat(buff) - } -} diff --git a/src/apis/avm/inputs.ts b/src/apis/avm/inputs.ts deleted file mode 100644 index 94f80b5ef..000000000 --- a/src/apis/avm/inputs.ts +++ /dev/null @@ -1,142 +0,0 @@ -/** - * @packageDocumentation - * @module API-AVM-Inputs - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { AVMConstants } from "./constants" -import { - Input, - StandardTransferableInput, - StandardAmountInput -} from "../../common/input" -import { SerializedEncoding } from "../../utils/serialization" -import { InputIdError, CodecIdError } from "../../utils/errors" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() - -/** - * Takes a buffer representing the output and returns the proper [[Input]] instance. - * - * @param inputid A number representing the inputID parsed prior to the bytes passed in - * - * @returns An instance of an [[Input]]-extended class. - */ -export const SelectInputClass = (inputid: number, ...args: any[]): Input => { - if ( - inputid === AVMConstants.SECPINPUTID || - inputid === AVMConstants.SECPINPUTID_CODECONE - ) { - return new SECPTransferInput(...args) - } - /* istanbul ignore next */ - throw new InputIdError("Error - SelectInputClass: unknown inputid") -} - -export class TransferableInput extends StandardTransferableInput { - protected _typeName = "TransferableInput" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.input = SelectInputClass(fields["input"]["_typeID"]) - this.input.deserialize(fields["input"], encoding) - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing a [[TransferableInput]], parses it, populates the class, and returns the length of the [[TransferableInput]] in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[TransferableInput]] - * - * @returns The length of the raw [[TransferableInput]] - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.txid = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - this.outputidx = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - this.assetID = bintools.copyFrom( - bytes, - offset, - offset + AVMConstants.ASSETIDLEN - ) - offset += 32 - const inputid: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.input = SelectInputClass(inputid) - return this.input.fromBuffer(bytes, offset) - } -} - -export abstract class AmountInput extends StandardAmountInput { - protected _typeName = "AmountInput" - protected _typeID = undefined - - //serialize and deserialize both are inherited - - select(id: number, ...args: any[]): Input { - return SelectInputClass(id, ...args) - } -} - -export class SECPTransferInput extends AmountInput { - protected _typeName = "SECPTransferInput" - protected _codecID = AVMConstants.LATESTCODEC - protected _typeID = - this._codecID === 0 - ? AVMConstants.SECPINPUTID - : AVMConstants.SECPINPUTID_CODECONE - - //serialize and deserialize both are inherited - - /** - * Set the codecID - * - * @param codecID The codecID to set - */ - setCodecID(codecID: number): void { - if (codecID !== 0 && codecID !== 1) { - /* istanbul ignore next */ - throw new CodecIdError( - "Error - SECPTransferInput.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - } - this._codecID = codecID - this._typeID = - this._codecID === 0 - ? AVMConstants.SECPINPUTID - : AVMConstants.SECPINPUTID_CODECONE - } - - /** - * Returns the inputID for this input - */ - getInputID(): number { - return this._typeID - } - - getCredentialID(): number { - if (this._codecID === 0) { - return AVMConstants.SECPCREDENTIAL - } else if (this._codecID === 1) { - return AVMConstants.SECPCREDENTIAL_CODECONE - } - } - - create(...args: any[]): this { - return new SECPTransferInput(...args) as this - } - - clone(): this { - const newout: SECPTransferInput = this.create() - newout.fromBuffer(this.toBuffer()) - return newout as this - } -} diff --git a/src/apis/avm/interfaces.ts b/src/apis/avm/interfaces.ts deleted file mode 100644 index afffbbb6b..000000000 --- a/src/apis/avm/interfaces.ts +++ /dev/null @@ -1,210 +0,0 @@ -/** - * @packageDocumentation - * @module AVM-Interfaces - */ - -import { Buffer } from "buffer/" -import BN from "bn.js" -import { CredsInterface } from "../../common" -import { UTXOSet } from "./utxos" - -export interface GetAVAXAssetIDParams { - name: string - symbol: string - assetID: Buffer - denomination: number -} - -export interface GetBalanceParams { - address: string - assetID: string - includePartial: boolean -} - -export interface GetBalanceResponse { - balance: number | BN - utxoIDs: iUTXOID[] -} - -export interface iUTXOID { - txID: string - outputIndex: number -} - -export interface CreateAddressParams extends CredsInterface {} - -export interface CreateFixedCapAssetParams extends CredsInterface { - name: string - symbol: string - denomination: number - initialHolders: object[] -} - -export interface CreateVariableCapAssetParams extends CredsInterface { - name: string - symbol: string - denomination: number - minterSets: object[] -} - -export interface MintParams extends CredsInterface { - amount: number | BN - assetID: Buffer | string - to: string - minters: string[] -} - -export interface ExportKeyParams extends CredsInterface { - address: string -} - -export interface ImportKeyParams extends CredsInterface { - privateKey: string -} - -export interface ExportParams extends CredsInterface { - to: string - amount: BN - assetID: string -} - -export interface ImportParams extends CredsInterface { - to: string - sourceChain: string -} - -export interface ListAddressesParams extends CredsInterface {} - -export interface GetAllBalancesParams { - address: string -} - -export interface GetAssetDescriptionParams { - assetID: string -} - -export interface GetAssetDescriptionResponse { - name: string - symbol: string - assetID: Buffer - denomination: number -} - -export interface GetTxParams { - txID: string - encoding: string -} - -export interface GetTxStatusParams { - txID: string -} - -export interface StartIndexInterface { - address: string - utxo: string -} - -export interface GetUTXOsParams { - addresses: string[] | string - limit: number - sourceChain?: string - startIndex?: StartIndexInterface - encoding?: string -} - -export interface EndIndex { - address: string - utxo: string -} - -export interface GetUTXOsResponse { - numFetched: number - utxos: UTXOSet - endIndex: EndIndex -} - -export interface SOutputsParams { - assetID: string - amount: string - to: string -} - -export interface SendParams { - username: string - password: string - assetID: string | Buffer - amount: string - to: string - from?: string[] | Buffer[] | undefined - changeAddr?: string | undefined - memo?: string | Buffer | undefined -} - -export interface SendResponse { - txID: string - changeAddr: string -} - -export interface SendMultipleParams extends CredsInterface { - outputs: SOutputsParams[] - from?: string[] | Buffer[] - changeAddr?: string - memo?: string | Buffer -} - -export interface SendMultipleResponse { - txID: string - changeAddr: string -} - -export interface BuildGenesisParams { - genesisData: object -} - -export interface GetAddressTxsParams { - address: string - cursor: number - pageSize: number - assetID: string -} - -export interface GetAddressTxsResponse { - txIDs: string[] - cursor: number -} - -export interface CreateNFTAssetParams { - username: string - password: string - from?: string[] - changeAddr?: string - name: string - symbol: string - minterSet: IMinterSet -} - -export interface SendNFTParams { - username: string - password: string - from?: string[] - changeAddr?: string - assetID: string - groupID: number - to: string -} - -export interface MintNFTParams { - username: string - password: string - from?: string[] - changeAddr?: string - assetID: string - payload: string - to: string - encoding: string -} - -export interface IMinterSet { - threshold: number - minters: string[] -} diff --git a/src/apis/avm/keychain.ts b/src/apis/avm/keychain.ts deleted file mode 100644 index 8231c15fa..000000000 --- a/src/apis/avm/keychain.ts +++ /dev/null @@ -1,112 +0,0 @@ -/** - * @packageDocumentation - * @module API-AVM-KeyChain - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { SECP256k1KeyChain, SECP256k1KeyPair } from "../../common/secp256k1" -import { Serialization, SerializedType } from "../../utils" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Class for representing a private and public keypair on an AVM Chain. - */ -export class KeyPair extends SECP256k1KeyPair { - clone(): this { - const newkp: KeyPair = new KeyPair(this.hrp, this.chainID) - newkp.importKey(bintools.copyFrom(this.getPrivateKey())) - return newkp as this - } - - create(...args: any[]): this { - if (args.length == 2) { - return new KeyPair(args[0], args[1]) as this - } - return new KeyPair(this.hrp, this.chainID) as this - } -} - -/** - * Class for representing a key chain in Avalanche. - * - * @typeparam KeyPair Class extending [[SECP256k1KeyChain]] which is used as the key in [[KeyChain]] - */ -export class KeyChain extends SECP256k1KeyChain { - hrp: string = "" - chainid: string = "" - - /** - * Makes a new key pair, returns the address. - * - * @returns The new key pair - */ - makeKey = (): KeyPair => { - let keypair: KeyPair = new KeyPair(this.hrp, this.chainid) - this.addKey(keypair) - return keypair - } - - addKey = (newKey: KeyPair) => { - newKey.setChainID(this.chainid) - super.addKey(newKey) - } - - /** - * Given a private key, makes a new key pair, returns the address. - * - * @param privk A {@link https://github.com/feross/buffer|Buffer} or cb58 serialized string representing the private key - * - * @returns The new key pair - */ - importKey = (privk: Buffer | string): KeyPair => { - let keypair: KeyPair = new KeyPair(this.hrp, this.chainid) - let pk: Buffer - if (typeof privk === "string") { - pk = bintools.cb58Decode(privk.split("-")[1]) - } else { - pk = bintools.copyFrom(privk) - } - keypair.importKey(pk) - if (!(keypair.getAddress().toString("hex") in this.keys)) { - this.addKey(keypair) - } - return keypair - } - - create(...args: any[]): this { - if (args.length == 2) { - return new KeyChain(args[0], args[1]) as this - } - return new KeyChain(this.hrp, this.chainid) as this - } - - clone(): this { - const newkc: KeyChain = new KeyChain(this.hrp, this.chainid) - for (let k in this.keys) { - newkc.addKey(this.keys[`${k}`].clone()) - } - return newkc as this - } - - union(kc: this): this { - let newkc: KeyChain = kc.clone() - for (let k in this.keys) { - newkc.addKey(this.keys[`${k}`].clone()) - } - return newkc as this - } - - /** - * Returns instance of KeyChain. - */ - constructor(hrp: string, chainid: string) { - super() - this.hrp = hrp - this.chainid = chainid - } -} diff --git a/src/apis/avm/minterset.ts b/src/apis/avm/minterset.ts deleted file mode 100644 index 4a0e02c82..000000000 --- a/src/apis/avm/minterset.ts +++ /dev/null @@ -1,103 +0,0 @@ -/** - * @packageDocumentation - * @module API-AVM-MinterSet - */ - -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { - Serializable, - Serialization, - SerializedEncoding, - SerializedType -} from "../../utils/serialization" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() -const decimalString: SerializedType = "decimalString" -const cb58: SerializedType = "cb58" -const num: SerializedType = "number" -const buffer: SerializedType = "Buffer" - -/** - * Class for representing a threshold and set of minting addresses in Avalanche. - * - * @typeparam MinterSet including a threshold and array of addresses - */ -export class MinterSet extends Serializable { - protected _typeName = "MinterSet" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - const fields: object = super.serialize(encoding) - return { - ...fields, - threshold: serialization.encoder( - this.threshold, - encoding, - num, - decimalString, - 4 - ), - minters: this.minters.map((m) => - serialization.encoder(m, encoding, buffer, cb58, 20) - ) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.threshold = serialization.decoder( - fields["threshold"], - encoding, - decimalString, - num, - 4 - ) - this.minters = fields["minters"].map((m: string) => - serialization.decoder(m, encoding, cb58, buffer, 20) - ) - } - - protected threshold: number - protected minters: Buffer[] = [] - - /** - * Returns the threshold. - */ - getThreshold = (): number => { - return this.threshold - } - - /** - * Returns the minters. - */ - getMinters = (): Buffer[] => { - return this.minters - } - - protected _cleanAddresses = (addresses: string[] | Buffer[]): Buffer[] => { - let addrs: Buffer[] = [] - for (let i: number = 0; i < addresses.length; i++) { - if (typeof addresses[`${i}`] === "string") { - addrs.push(bintools.stringToAddress(addresses[`${i}`] as string)) - } else if (addresses[`${i}`] instanceof Buffer) { - addrs.push(addresses[`${i}`] as Buffer) - } - } - return addrs - } - - /** - * - * @param threshold The number of signatures required to mint more of an asset by signing a minting transaction - * @param minters Array of addresss which are authorized to sign a minting transaction - */ - constructor(threshold: number = 1, minters: string[] | Buffer[] = []) { - super() - this.threshold = threshold - this.minters = this._cleanAddresses(minters) - } -} diff --git a/src/apis/avm/operationtx.ts b/src/apis/avm/operationtx.ts deleted file mode 100644 index c4288f3b6..000000000 --- a/src/apis/avm/operationtx.ts +++ /dev/null @@ -1,186 +0,0 @@ -/** - * @packageDocumentation - * @module API-AVM-OperationTx - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { AVMConstants } from "./constants" -import { TransferableOutput } from "./outputs" -import { TransferableInput } from "./inputs" -import { TransferableOperation } from "./ops" -import { SelectCredentialClass } from "./credentials" -import { KeyChain, KeyPair } from "./keychain" -import { Signature, SigIdx, Credential } from "../../common/credentials" -import { BaseTx } from "./basetx" -import { DefaultNetworkID } from "../../utils/constants" -import { SerializedEncoding } from "../../utils/serialization" -import { CodecIdError, OperationError } from "../../utils/errors" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() - -/** - * Class representing an unsigned Operation transaction. - */ -export class OperationTx extends BaseTx { - protected _typeName = "OperationTx" - protected _codecID = AVMConstants.LATESTCODEC - protected _typeID = - this._codecID === 0 - ? AVMConstants.OPERATIONTX - : AVMConstants.OPERATIONTX_CODECONE - - serialize(encoding: SerializedEncoding = "hex"): object { - const fields: object = super.serialize(encoding) - return { - ...fields, - ops: this.ops.map((o) => o.serialize(encoding)) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.ops = fields["ops"].map((o: object) => { - let op: TransferableOperation = new TransferableOperation() - op.deserialize(o, encoding) - return op - }) - this.numOps = Buffer.alloc(4) - this.numOps.writeUInt32BE(this.ops.length, 0) - } - - protected numOps: Buffer = Buffer.alloc(4) - protected ops: TransferableOperation[] = [] - - setCodecID(codecID: number): void { - if (codecID !== 0 && codecID !== 1) { - /* istanbul ignore next */ - throw new CodecIdError( - "Error - OperationTx.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - } - this._codecID = codecID - this._typeID = - this._codecID === 0 - ? AVMConstants.OPERATIONTX - : AVMConstants.OPERATIONTX_CODECONE - } - - /** - * Returns the id of the [[OperationTx]] - */ - getTxType(): number { - return this._typeID - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[OperationTx]], parses it, populates the class, and returns the length of the [[OperationTx]] in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[OperationTx]] - * - * @returns The length of the raw [[OperationTx]] - * - * @remarks assume not-checksummed - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - this.numOps = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const numOps: number = this.numOps.readUInt32BE(0) - for (let i: number = 0; i < numOps; i++) { - const op: TransferableOperation = new TransferableOperation() - offset = op.fromBuffer(bytes, offset) - this.ops.push(op) - } - return offset - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[OperationTx]]. - */ - toBuffer(): Buffer { - this.numOps.writeUInt32BE(this.ops.length, 0) - let barr: Buffer[] = [super.toBuffer(), this.numOps] - this.ops = this.ops.sort(TransferableOperation.comparator()) - for (let i: number = 0; i < this.ops.length; i++) { - barr.push(this.ops[`${i}`].toBuffer()) - } - return Buffer.concat(barr) - } - - /** - * Returns an array of [[TransferableOperation]]s in this transaction. - */ - getOperations(): TransferableOperation[] { - return this.ops - } - - /** - * Takes the bytes of an [[UnsignedTx]] and returns an array of [[Credential]]s - * - * @param msg A Buffer for the [[UnsignedTx]] - * @param kc An [[KeyChain]] used in signing - * - * @returns An array of [[Credential]]s - */ - sign(msg: Buffer, kc: KeyChain): Credential[] { - const creds: Credential[] = super.sign(msg, kc) - for (let i: number = 0; i < this.ops.length; i++) { - const cred: Credential = SelectCredentialClass( - this.ops[`${i}`].getOperation().getCredentialID() - ) - const sigidxs: SigIdx[] = this.ops[`${i}`].getOperation().getSigIdxs() - for (let j: number = 0; j < sigidxs.length; j++) { - const keypair: KeyPair = kc.getKey(sigidxs[`${j}`].getSource()) - const signval: Buffer = keypair.sign(msg) - const sig: Signature = new Signature() - sig.fromBuffer(signval) - cred.addSignature(sig) - } - creds.push(cred) - } - return creds - } - - clone(): this { - const newbase: OperationTx = new OperationTx() - newbase.fromBuffer(this.toBuffer()) - return newbase as this - } - - create(...args: any[]): this { - return new OperationTx(...args) as this - } - - /** - * Class representing an unsigned Operation transaction. - * - * @param networkID Optional networkID, [[DefaultNetworkID]] - * @param blockchainID Optional blockchainID, default Buffer.alloc(32, 16) - * @param outs Optional array of the [[TransferableOutput]]s - * @param ins Optional array of the [[TransferableInput]]s - * @param memo Optional {@link https://github.com/feross/buffer|Buffer} for the memo field - * @param ops Array of [[Operation]]s used in the transaction - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: Buffer = Buffer.alloc(32, 16), - outs: TransferableOutput[] = undefined, - ins: TransferableInput[] = undefined, - memo: Buffer = undefined, - ops: TransferableOperation[] = undefined - ) { - super(networkID, blockchainID, outs, ins, memo) - if (typeof ops !== "undefined" && Array.isArray(ops)) { - for (let i: number = 0; i < ops.length; i++) { - if (!(ops[`${i}`] instanceof TransferableOperation)) { - throw new OperationError( - `Error - OperationTx.constructor: invalid op in array parameter ${ops}` - ) - } - } - this.ops = ops - } - } -} diff --git a/src/apis/avm/ops.ts b/src/apis/avm/ops.ts deleted file mode 100644 index a803a1cc1..000000000 --- a/src/apis/avm/ops.ts +++ /dev/null @@ -1,847 +0,0 @@ -/** - * @packageDocumentation - * @module API-AVM-Operations - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { AVMConstants } from "./constants" -import { - NFTTransferOutput, - SECPMintOutput, - SECPTransferOutput -} from "./outputs" -import { NBytes } from "../../common/nbytes" -import { SigIdx } from "../../common/credentials" -import { OutputOwners } from "../../common/output" -import { - Serializable, - Serialization, - SerializedEncoding, - SerializedType -} from "../../utils/serialization" -import { - InvalidOperationIdError, - CodecIdError, - ChecksumError, - AddressError -} from "../../utils/errors" - -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() -const cb58: SerializedType = "cb58" -const buffer: SerializedType = "Buffer" -const hex: SerializedType = "hex" -const decimalString: SerializedType = "decimalString" - -/** - * Takes a buffer representing the output and returns the proper [[Operation]] instance. - * - * @param opid A number representing the operation ID parsed prior to the bytes passed in - * - * @returns An instance of an [[Operation]]-extended class. - */ -export const SelectOperationClass = ( - opid: number, - ...args: any[] -): Operation => { - if ( - opid === AVMConstants.SECPMINTOPID || - opid === AVMConstants.SECPMINTOPID_CODECONE - ) { - return new SECPMintOperation(...args) - } else if ( - opid === AVMConstants.NFTMINTOPID || - opid === AVMConstants.NFTMINTOPID_CODECONE - ) { - return new NFTMintOperation(...args) - } else if ( - opid === AVMConstants.NFTXFEROPID || - opid === AVMConstants.NFTXFEROPID_CODECONE - ) { - return new NFTTransferOperation(...args) - } - /* istanbul ignore next */ - throw new InvalidOperationIdError( - `Error - SelectOperationClass: unknown opid ${opid}` - ) -} - -/** - * A class representing an operation. All operation types must extend on this class. - */ -export abstract class Operation extends Serializable { - protected _typeName = "Operation" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - sigIdxs: this.sigIdxs.map((s: SigIdx): object => s.serialize(encoding)) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.sigIdxs = fields["sigIdxs"].map((s: object): SigIdx => { - let sidx: SigIdx = new SigIdx() - sidx.deserialize(s, encoding) - return sidx - }) - this.sigCount.writeUInt32BE(this.sigIdxs.length, 0) - } - - protected sigCount: Buffer = Buffer.alloc(4) - protected sigIdxs: SigIdx[] = [] // idxs of signers from utxo - - static comparator = - (): ((a: Operation, b: Operation) => 1 | -1 | 0) => - (a: Operation, b: Operation): 1 | -1 | 0 => { - const aoutid: Buffer = Buffer.alloc(4) - aoutid.writeUInt32BE(a.getOperationID(), 0) - const abuff: Buffer = a.toBuffer() - - const boutid: Buffer = Buffer.alloc(4) - boutid.writeUInt32BE(b.getOperationID(), 0) - const bbuff: Buffer = b.toBuffer() - - const asort: Buffer = Buffer.concat( - [aoutid, abuff], - aoutid.length + abuff.length - ) - const bsort: Buffer = Buffer.concat( - [boutid, bbuff], - boutid.length + bbuff.length - ) - return Buffer.compare(asort, bsort) as 1 | -1 | 0 - } - - abstract getOperationID(): number - - /** - * Returns the array of [[SigIdx]] for this [[Operation]] - */ - getSigIdxs = (): SigIdx[] => this.sigIdxs - - /** - * Returns the credential ID. - */ - abstract getCredentialID(): number - - /** - * Creates and adds a [[SigIdx]] to the [[Operation]]. - * - * @param addressIdx The index of the address to reference in the signatures - * @param address The address of the source of the signature - */ - addSignatureIdx = (addressIdx: number, address: Buffer) => { - const sigidx: SigIdx = new SigIdx() - const b: Buffer = Buffer.alloc(4) - b.writeUInt32BE(addressIdx, 0) - sigidx.fromBuffer(b) - sigidx.setSource(address) - this.sigIdxs.push(sigidx) - this.sigCount.writeUInt32BE(this.sigIdxs.length, 0) - } - - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.sigCount = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const sigCount: number = this.sigCount.readUInt32BE(0) - this.sigIdxs = [] - for (let i: number = 0; i < sigCount; i++) { - const sigidx: SigIdx = new SigIdx() - const sigbuff: Buffer = bintools.copyFrom(bytes, offset, offset + 4) - sigidx.fromBuffer(sigbuff) - offset += 4 - this.sigIdxs.push(sigidx) - } - return offset - } - - toBuffer(): Buffer { - this.sigCount.writeUInt32BE(this.sigIdxs.length, 0) - let bsize: number = this.sigCount.length - const barr: Buffer[] = [this.sigCount] - for (let i: number = 0; i < this.sigIdxs.length; i++) { - const b: Buffer = this.sigIdxs[`${i}`].toBuffer() - barr.push(b) - bsize += b.length - } - return Buffer.concat(barr, bsize) - } - - /** - * Returns a base-58 string representing the [[NFTMintOperation]]. - */ - toString(): string { - return bintools.bufferToB58(this.toBuffer()) - } -} - -/** - * A class which contains an [[Operation]] for transfers. - * - */ -export class TransferableOperation extends Serializable { - protected _typeName = "TransferableOperation" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - assetID: serialization.encoder(this.assetID, encoding, buffer, cb58, 32), - utxoIDs: this.utxoIDs.map((u) => u.serialize(encoding)), - operation: this.operation.serialize(encoding) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.assetID = serialization.decoder( - fields["assetID"], - encoding, - cb58, - buffer, - 32 - ) - this.utxoIDs = fields["utxoIDs"].map((u: object) => { - let utxoid: UTXOID = new UTXOID() - utxoid.deserialize(u, encoding) - return utxoid - }) - this.operation = SelectOperationClass(fields["operation"]["_typeID"]) - this.operation.deserialize(fields["operation"], encoding) - } - - protected assetID: Buffer = Buffer.alloc(32) - protected utxoIDs: UTXOID[] = [] - protected operation: Operation - - /** - * Returns a function used to sort an array of [[TransferableOperation]]s - */ - static comparator = (): (( - a: TransferableOperation, - b: TransferableOperation - ) => 1 | -1 | 0) => { - return function ( - a: TransferableOperation, - b: TransferableOperation - ): 1 | -1 | 0 { - return Buffer.compare(a.toBuffer(), b.toBuffer()) as 1 | -1 | 0 - } - } - /** - * Returns the assetID as a {@link https://github.com/feross/buffer|Buffer}. - */ - getAssetID = (): Buffer => this.assetID - - /** - * Returns an array of UTXOIDs in this operation. - */ - getUTXOIDs = (): UTXOID[] => this.utxoIDs - - /** - * Returns the operation - */ - getOperation = (): Operation => this.operation - - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.assetID = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - const numutxoIDs: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.utxoIDs = [] - for (let i: number = 0; i < numutxoIDs; i++) { - const utxoid: UTXOID = new UTXOID() - offset = utxoid.fromBuffer(bytes, offset) - this.utxoIDs.push(utxoid) - } - const opid: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.operation = SelectOperationClass(opid) - return this.operation.fromBuffer(bytes, offset) - } - - toBuffer(): Buffer { - const numutxoIDs = Buffer.alloc(4) - numutxoIDs.writeUInt32BE(this.utxoIDs.length, 0) - let bsize: number = this.assetID.length + numutxoIDs.length - const barr: Buffer[] = [this.assetID, numutxoIDs] - this.utxoIDs = this.utxoIDs.sort(UTXOID.comparator()) - for (let i: number = 0; i < this.utxoIDs.length; i++) { - const b: Buffer = this.utxoIDs[`${i}`].toBuffer() - barr.push(b) - bsize += b.length - } - const opid: Buffer = Buffer.alloc(4) - opid.writeUInt32BE(this.operation.getOperationID(), 0) - barr.push(opid) - bsize += opid.length - const b: Buffer = this.operation.toBuffer() - bsize += b.length - barr.push(b) - return Buffer.concat(barr, bsize) - } - - constructor( - assetID: Buffer = undefined, - utxoids: UTXOID[] | string[] | Buffer[] = undefined, - operation: Operation = undefined - ) { - super() - if ( - typeof assetID !== "undefined" && - assetID.length === AVMConstants.ASSETIDLEN && - operation instanceof Operation && - typeof utxoids !== "undefined" && - Array.isArray(utxoids) - ) { - this.assetID = assetID - this.operation = operation - for (let i: number = 0; i < utxoids.length; i++) { - const utxoid: UTXOID = new UTXOID() - if (typeof utxoids[`${i}`] === "string") { - utxoid.fromString(utxoids[`${i}`] as string) - } else if (utxoids[`${i}`] instanceof Buffer) { - utxoid.fromBuffer(utxoids[`${i}`] as Buffer) - } else if (utxoids[`${i}`] instanceof UTXOID) { - utxoid.fromString(utxoids[`${i}`].toString()) // clone - } - this.utxoIDs.push(utxoid) - } - } - } -} - -/** - * An [[Operation]] class which specifies a SECP256k1 Mint Op. - */ -export class SECPMintOperation extends Operation { - protected _typeName = "SECPMintOperation" - protected _codecID = AVMConstants.LATESTCODEC - protected _typeID = - this._codecID === 0 - ? AVMConstants.SECPMINTOPID - : AVMConstants.SECPMINTOPID_CODECONE - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - mintOutput: this.mintOutput.serialize(encoding), - transferOutputs: this.transferOutput.serialize(encoding) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.mintOutput = new SECPMintOutput() - this.mintOutput.deserialize(fields["mintOutput"], encoding) - this.transferOutput = new SECPTransferOutput() - this.transferOutput.deserialize(fields["transferOutputs"], encoding) - } - - protected mintOutput: SECPMintOutput = undefined - protected transferOutput: SECPTransferOutput = undefined - - /** - * Set the codecID - * - * @param codecID The codecID to set - */ - setCodecID(codecID: number): void { - if (codecID !== 0 && codecID !== 1) { - /* istanbul ignore next */ - throw new CodecIdError( - "Error - SECPMintOperation.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - } - this._codecID = codecID - this._typeID = - this._codecID === 0 - ? AVMConstants.SECPMINTOPID - : AVMConstants.SECPMINTOPID_CODECONE - } - - /** - * Returns the operation ID. - */ - getOperationID(): number { - return this._typeID - } - - /** - * Returns the credential ID. - */ - getCredentialID(): number { - if (this._codecID === 0) { - return AVMConstants.SECPCREDENTIAL - } else if (this._codecID === 1) { - return AVMConstants.SECPCREDENTIAL_CODECONE - } - } - - /** - * Returns the [[SECPMintOutput]] to be produced by this operation. - */ - getMintOutput(): SECPMintOutput { - return this.mintOutput - } - - /** - * Returns [[SECPTransferOutput]] to be produced by this operation. - */ - getTransferOutput(): SECPTransferOutput { - return this.transferOutput - } - - /** - * Popuates the instance from a {@link https://github.com/feross/buffer|Buffer} representing the [[SECPMintOperation]] and returns the updated offset. - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - this.mintOutput = new SECPMintOutput() - offset = this.mintOutput.fromBuffer(bytes, offset) - this.transferOutput = new SECPTransferOutput() - offset = this.transferOutput.fromBuffer(bytes, offset) - return offset - } - - /** - * Returns the buffer representing the [[SECPMintOperation]] instance. - */ - toBuffer(): Buffer { - const superbuff: Buffer = super.toBuffer() - const mintoutBuff: Buffer = this.mintOutput.toBuffer() - const transferOutBuff: Buffer = this.transferOutput.toBuffer() - const bsize: number = - superbuff.length + mintoutBuff.length + transferOutBuff.length - - const barr: Buffer[] = [superbuff, mintoutBuff, transferOutBuff] - - return Buffer.concat(barr, bsize) - } - - /** - * An [[Operation]] class which mints new tokens on an assetID. - * - * @param mintOutput The [[SECPMintOutput]] that will be produced by this transaction. - * @param transferOutput A [[SECPTransferOutput]] that will be produced from this minting operation. - */ - constructor( - mintOutput: SECPMintOutput = undefined, - transferOutput: SECPTransferOutput = undefined - ) { - super() - if (typeof mintOutput !== "undefined") { - this.mintOutput = mintOutput - } - if (typeof transferOutput !== "undefined") { - this.transferOutput = transferOutput - } - } -} - -/** - * An [[Operation]] class which specifies a NFT Mint Op. - */ -export class NFTMintOperation extends Operation { - protected _typeName = "NFTMintOperation" - protected _codecID = AVMConstants.LATESTCODEC - protected _typeID = - this._codecID === 0 - ? AVMConstants.NFTMINTOPID - : AVMConstants.NFTMINTOPID_CODECONE - - serialize(encoding: SerializedEncoding = "hex"): object { - const fields: object = super.serialize(encoding) - return { - ...fields, - groupID: serialization.encoder( - this.groupID, - encoding, - buffer, - decimalString, - 4 - ), - payload: serialization.encoder(this.payload, encoding, buffer, hex), - outputOwners: this.outputOwners.map((o) => o.serialize(encoding)) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.groupID = serialization.decoder( - fields["groupID"], - encoding, - decimalString, - buffer, - 4 - ) - this.payload = serialization.decoder( - fields["payload"], - encoding, - hex, - buffer - ) - // this.outputOwners = fields["outputOwners"].map((o: NFTMintOutput) => { - // let oo: NFTMintOutput = new NFTMintOutput() - // oo.deserialize(o, encoding) - // return oo - // }) - this.outputOwners = fields["outputOwners"].map( - (o: object): OutputOwners => { - let oo: OutputOwners = new OutputOwners() - oo.deserialize(o, encoding) - return oo - } - ) - } - - protected groupID: Buffer = Buffer.alloc(4) - protected payload: Buffer - protected outputOwners: OutputOwners[] = [] - - /** - * Set the codecID - * - * @param codecID The codecID to set - */ - setCodecID(codecID: number): void { - if (codecID !== 0 && codecID !== 1) { - /* istanbul ignore next */ - throw new CodecIdError( - "Error - NFTMintOperation.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - } - this._codecID = codecID - this._typeID = - this._codecID === 0 - ? AVMConstants.NFTMINTOPID - : AVMConstants.NFTMINTOPID_CODECONE - } - - /** - * Returns the operation ID. - */ - getOperationID(): number { - return this._typeID - } - - /** - * Returns the credential ID. - */ - getCredentialID = (): number => { - if (this._codecID === 0) { - return AVMConstants.NFTCREDENTIAL - } else if (this._codecID === 1) { - return AVMConstants.NFTCREDENTIAL_CODECONE - } - } - - /** - * Returns the payload. - */ - getGroupID = (): Buffer => { - return bintools.copyFrom(this.groupID, 0) - } - - /** - * Returns the payload. - */ - getPayload = (): Buffer => { - return bintools.copyFrom(this.payload, 0) - } - - /** - * Returns the payload's raw {@link https://github.com/feross/buffer|Buffer} with length prepended, for use with [[PayloadBase]]'s fromBuffer - */ - getPayloadBuffer = (): Buffer => { - let payloadlen: Buffer = Buffer.alloc(4) - payloadlen.writeUInt32BE(this.payload.length, 0) - return Buffer.concat([payloadlen, bintools.copyFrom(this.payload, 0)]) - } - - /** - * Returns the outputOwners. - */ - getOutputOwners = (): OutputOwners[] => { - return this.outputOwners - } - - /** - * Popuates the instance from a {@link https://github.com/feross/buffer|Buffer} representing the [[NFTMintOperation]] and returns the updated offset. - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - this.groupID = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - let payloadLen: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.payload = bintools.copyFrom(bytes, offset, offset + payloadLen) - offset += payloadLen - let numoutputs: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.outputOwners = [] - for (let i: number = 0; i < numoutputs; i++) { - let outputOwner: OutputOwners = new OutputOwners() - offset = outputOwner.fromBuffer(bytes, offset) - this.outputOwners.push(outputOwner) - } - return offset - } - - /** - * Returns the buffer representing the [[NFTMintOperation]] instance. - */ - toBuffer(): Buffer { - const superbuff: Buffer = super.toBuffer() - const payloadlen: Buffer = Buffer.alloc(4) - payloadlen.writeUInt32BE(this.payload.length, 0) - - const outputownerslen: Buffer = Buffer.alloc(4) - outputownerslen.writeUInt32BE(this.outputOwners.length, 0) - - let bsize: number = - superbuff.length + - this.groupID.length + - payloadlen.length + - this.payload.length + - outputownerslen.length - - const barr: Buffer[] = [ - superbuff, - this.groupID, - payloadlen, - this.payload, - outputownerslen - ] - - for (let i: number = 0; i < this.outputOwners.length; i++) { - let b: Buffer = this.outputOwners[`${i}`].toBuffer() - barr.push(b) - bsize += b.length - } - - return Buffer.concat(barr, bsize) - } - - /** - * Returns a base-58 string representing the [[NFTMintOperation]]. - */ - toString(): string { - return bintools.bufferToB58(this.toBuffer()) - } - - /** - * An [[Operation]] class which contains an NFT on an assetID. - * - * @param groupID The group to which to issue the NFT Output - * @param payload A {@link https://github.com/feross/buffer|Buffer} of the NFT payload - * @param outputOwners An array of outputOwners - */ - constructor( - groupID: number = undefined, - payload: Buffer = undefined, - outputOwners: OutputOwners[] = undefined - ) { - super() - if ( - typeof groupID !== "undefined" && - typeof payload !== "undefined" && - outputOwners.length - ) { - this.groupID.writeUInt32BE(groupID ? groupID : 0, 0) - this.payload = payload - this.outputOwners = outputOwners - } - } -} - -/** - * A [[Operation]] class which specifies a NFT Transfer Op. - */ -export class NFTTransferOperation extends Operation { - protected _typeName = "NFTTransferOperation" - protected _codecID = AVMConstants.LATESTCODEC - protected _typeID = - this._codecID === 0 - ? AVMConstants.NFTXFEROPID - : AVMConstants.NFTXFEROPID_CODECONE - - serialize(encoding: SerializedEncoding = "hex"): object { - const fields: object = super.serialize(encoding) - return { - ...fields, - output: this.output.serialize(encoding) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.output = new NFTTransferOutput() - this.output.deserialize(fields["output"], encoding) - } - - protected output: NFTTransferOutput - - /** - * Set the codecID - * - * @param codecID The codecID to set - */ - setCodecID(codecID: number): void { - if (codecID !== 0 && codecID !== 1) { - /* istanbul ignore next */ - throw new CodecIdError( - "Error - NFTTransferOperation.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - } - this._codecID = codecID - this._typeID = - this._codecID === 0 - ? AVMConstants.NFTXFEROPID - : AVMConstants.NFTXFEROPID_CODECONE - } - - /** - * Returns the operation ID. - */ - getOperationID(): number { - return this._typeID - } - - /** - * Returns the credential ID. - */ - getCredentialID(): number { - if (this._codecID === 0) { - return AVMConstants.NFTCREDENTIAL - } else if (this._codecID === 1) { - return AVMConstants.NFTCREDENTIAL_CODECONE - } - } - - getOutput = (): NFTTransferOutput => this.output - - /** - * Popuates the instance from a {@link https://github.com/feross/buffer|Buffer} representing the [[NFTTransferOperation]] and returns the updated offset. - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - this.output = new NFTTransferOutput() - return this.output.fromBuffer(bytes, offset) - } - - /** - * Returns the buffer representing the [[NFTTransferOperation]] instance. - */ - toBuffer(): Buffer { - const superbuff: Buffer = super.toBuffer() - const outbuff: Buffer = this.output.toBuffer() - const bsize: number = superbuff.length + outbuff.length - const barr: Buffer[] = [superbuff, outbuff] - return Buffer.concat(barr, bsize) - } - - /** - * Returns a base-58 string representing the [[NFTTransferOperation]]. - */ - toString(): string { - return bintools.bufferToB58(this.toBuffer()) - } - - /** - * An [[Operation]] class which contains an NFT on an assetID. - * - * @param output An [[NFTTransferOutput]] - */ - constructor(output: NFTTransferOutput = undefined) { - super() - if (typeof output !== "undefined") { - this.output = output - } - } -} - -/** - * Class for representing a UTXOID used in [[TransferableOp]] types - */ -export class UTXOID extends NBytes { - protected _typeName = "UTXOID" - protected _typeID = undefined - - //serialize and deserialize both are inherited - - protected bytes = Buffer.alloc(36) - protected bsize = 36 - - /** - * Returns a function used to sort an array of [[UTXOID]]s - */ - static comparator = - (): ((a: UTXOID, b: UTXOID) => 1 | -1 | 0) => - (a: UTXOID, b: UTXOID): 1 | -1 | 0 => - Buffer.compare(a.toBuffer(), b.toBuffer()) as 1 | -1 | 0 - - /** - * Returns a base-58 representation of the [[UTXOID]]. - */ - toString(): string { - return bintools.cb58Encode(this.toBuffer()) - } - - /** - * Takes a base-58 string containing an [[UTXOID]], parses it, populates the class, and returns the length of the UTXOID in bytes. - * - * @param bytes A base-58 string containing a raw [[UTXOID]] - * - * @returns The length of the raw [[UTXOID]] - */ - fromString(utxoid: string): number { - const utxoidbuff: Buffer = bintools.b58ToBuffer(utxoid) - if (utxoidbuff.length === 40 && bintools.validateChecksum(utxoidbuff)) { - const newbuff: Buffer = bintools.copyFrom( - utxoidbuff, - 0, - utxoidbuff.length - 4 - ) - if (newbuff.length === 36) { - this.bytes = newbuff - } - } else if (utxoidbuff.length === 40) { - throw new ChecksumError( - "Error - UTXOID.fromString: invalid checksum on address" - ) - } else if (utxoidbuff.length === 36) { - this.bytes = utxoidbuff - } else { - /* istanbul ignore next */ - throw new AddressError("Error - UTXOID.fromString: invalid address") - } - return this.getSize() - } - - clone(): this { - const newbase: UTXOID = new UTXOID() - newbase.fromBuffer(this.toBuffer()) - return newbase as this - } - - create(...args: any[]): this { - return new UTXOID() as this - } - - /** - * Class for representing a UTXOID used in [[TransferableOp]] types - */ - constructor() { - super() - } -} diff --git a/src/apis/avm/outputs.ts b/src/apis/avm/outputs.ts deleted file mode 100644 index 2262028cf..000000000 --- a/src/apis/avm/outputs.ts +++ /dev/null @@ -1,470 +0,0 @@ -/** - * @packageDocumentation - * @module API-AVM-Outputs - */ -import { Buffer } from "buffer/" -import BN from "bn.js" -import BinTools from "../../utils/bintools" -import { AVMConstants } from "./constants" -import { - Output, - StandardAmountOutput, - StandardTransferableOutput, - BaseNFTOutput -} from "../../common/output" -import { Serialization, SerializedEncoding } from "../../utils/serialization" -import { OutputIdError, CodecIdError } from "../../utils/errors" - -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Takes a buffer representing the output and returns the proper Output instance. - * - * @param outputid A number representing the inputID parsed prior to the bytes passed in - * - * @returns An instance of an [[Output]]-extended class. - */ -export const SelectOutputClass = (outputid: number, ...args: any[]): Output => { - if ( - outputid === AVMConstants.SECPXFEROUTPUTID || - outputid === AVMConstants.SECPXFEROUTPUTID_CODECONE - ) { - return new SECPTransferOutput(...args) - } else if ( - outputid === AVMConstants.SECPMINTOUTPUTID || - outputid === AVMConstants.SECPMINTOUTPUTID_CODECONE - ) { - return new SECPMintOutput(...args) - } else if ( - outputid === AVMConstants.NFTMINTOUTPUTID || - outputid === AVMConstants.NFTMINTOUTPUTID_CODECONE - ) { - return new NFTMintOutput(...args) - } else if ( - outputid === AVMConstants.NFTXFEROUTPUTID || - outputid === AVMConstants.NFTXFEROUTPUTID_CODECONE - ) { - return new NFTTransferOutput(...args) - } - throw new OutputIdError( - "Error - SelectOutputClass: unknown outputid " + outputid - ) -} - -export class TransferableOutput extends StandardTransferableOutput { - protected _typeName = "TransferableOutput" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.output = SelectOutputClass(fields["output"]["_typeID"]) - this.output.deserialize(fields["output"], encoding) - } - - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.assetID = bintools.copyFrom( - bytes, - offset, - offset + AVMConstants.ASSETIDLEN - ) - offset += AVMConstants.ASSETIDLEN - const outputid: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.output = SelectOutputClass(outputid) - return this.output.fromBuffer(bytes, offset) - } -} - -export abstract class AmountOutput extends StandardAmountOutput { - protected _typeName = "AmountOutput" - protected _typeID = undefined - - //serialize and deserialize both are inherited - - /** - * - * @param assetID An assetID which is wrapped around the Buffer of the Output - */ - makeTransferable(assetID: Buffer): TransferableOutput { - return new TransferableOutput(assetID, this) - } - - select(id: number, ...args: any[]): Output { - return SelectOutputClass(id, ...args) - } -} - -export abstract class NFTOutput extends BaseNFTOutput { - protected _typeName = "NFTOutput" - protected _typeID = undefined - - //serialize and deserialize both are inherited - - /** - * - * @param assetID An assetID which is wrapped around the Buffer of the Output - */ - makeTransferable(assetID: Buffer): TransferableOutput { - return new TransferableOutput(assetID, this) - } - - select(id: number, ...args: any[]): Output { - return SelectOutputClass(id, ...args) - } -} - -/** - * An [[Output]] class which specifies an Output that carries an ammount for an assetID and uses secp256k1 signature scheme. - */ -export class SECPTransferOutput extends AmountOutput { - protected _typeName = "SECPTransferOutput" - protected _codecID = AVMConstants.LATESTCODEC - protected _typeID = - this._codecID === 0 - ? AVMConstants.SECPXFEROUTPUTID - : AVMConstants.SECPXFEROUTPUTID_CODECONE - - //serialize and deserialize both are inherited - - /** - * Set the codecID - * - * @param codecID The codecID to set - */ - setCodecID(codecID: number): void { - if (codecID !== 0 && codecID !== 1) { - /* istanbul ignore next */ - throw new CodecIdError( - "Error - SECPTransferOutput.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - } - this._codecID = codecID - this._typeID = - this._codecID === 0 - ? AVMConstants.SECPXFEROUTPUTID - : AVMConstants.SECPXFEROUTPUTID_CODECONE - } - - /** - * Returns the outputID for this output - */ - getOutputID(): number { - return this._typeID - } - - create(...args: any[]): this { - return new SECPTransferOutput(...args) as this - } - - clone(): this { - const newout: SECPTransferOutput = this.create() - newout.fromBuffer(this.toBuffer()) - return newout as this - } -} - -/** - * An [[Output]] class which specifies an Output that carries an ammount for an assetID and uses secp256k1 signature scheme. - */ -export class SECPMintOutput extends Output { - protected _typeName = "SECPMintOutput" - protected _codecID = AVMConstants.LATESTCODEC - protected _typeID = - this._codecID === 0 - ? AVMConstants.SECPMINTOUTPUTID - : AVMConstants.SECPMINTOUTPUTID_CODECONE - - //serialize and deserialize both are inherited - - /** - * Set the codecID - * - * @param codecID The codecID to set - */ - setCodecID(codecID: number): void { - if (codecID !== 0 && codecID !== 1) { - /* istanbul ignore next */ - throw new CodecIdError( - "Error - SECPMintOutput.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - } - this._codecID = codecID - this._typeID = - this._codecID === 0 - ? AVMConstants.SECPMINTOUTPUTID - : AVMConstants.SECPMINTOUTPUTID_CODECONE - } - - /** - * Returns the outputID for this output - */ - getOutputID(): number { - return this._typeID - } - - /** - * - * @param assetID An assetID which is wrapped around the Buffer of the Output - */ - makeTransferable(assetID: Buffer): TransferableOutput { - return new TransferableOutput(assetID, this) - } - - create(...args: any[]): this { - return new SECPMintOutput(...args) as this - } - - clone(): this { - const newout: SECPMintOutput = this.create() - newout.fromBuffer(this.toBuffer()) - return newout as this - } - - select(id: number, ...args: any[]): Output { - return SelectOutputClass(id, ...args) - } -} - -/** - * An [[Output]] class which specifies an Output that carries an NFT Mint and uses secp256k1 signature scheme. - */ -export class NFTMintOutput extends NFTOutput { - protected _typeName = "NFTMintOutput" - protected _codecID = AVMConstants.LATESTCODEC - protected _typeID = - this._codecID === 0 - ? AVMConstants.NFTMINTOUTPUTID - : AVMConstants.NFTMINTOUTPUTID_CODECONE - - //serialize and deserialize both are inherited - - /** - * Set the codecID - * - * @param codecID The codecID to set - */ - setCodecID(codecID: number): void { - if (codecID !== 0 && codecID !== 1) { - /* istanbul ignore next */ - throw new CodecIdError( - "Error - NFTMintOutput.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - } - this._codecID = codecID - this._typeID = - this._codecID === 0 - ? AVMConstants.NFTMINTOUTPUTID - : AVMConstants.NFTMINTOUTPUTID_CODECONE - } - - /** - * Returns the outputID for this output - */ - getOutputID(): number { - return this._typeID - } - - /** - * Popuates the instance from a {@link https://github.com/feross/buffer|Buffer} representing the [[NFTMintOutput]] and returns the size of the output. - */ - fromBuffer(utxobuff: Buffer, offset: number = 0): number { - this.groupID = bintools.copyFrom(utxobuff, offset, offset + 4) - offset += 4 - return super.fromBuffer(utxobuff, offset) - } - - /** - * Returns the buffer representing the [[NFTMintOutput]] instance. - */ - toBuffer(): Buffer { - let superbuff: Buffer = super.toBuffer() - let bsize: number = this.groupID.length + superbuff.length - let barr: Buffer[] = [this.groupID, superbuff] - return Buffer.concat(barr, bsize) - } - - create(...args: any[]): this { - return new NFTMintOutput(...args) as this - } - - clone(): this { - const newout: NFTMintOutput = this.create() - newout.fromBuffer(this.toBuffer()) - return newout as this - } - - /** - * An [[Output]] class which contains an NFT mint for an assetID. - * - * @param groupID A number specifies the group this NFT is issued to - * @param addresses An array of {@link https://github.com/feross/buffer|Buffer}s representing addresses - * @param locktime A {@link https://github.com/indutny/bn.js/|BN} representing the locktime - * @param threshold A number representing the the threshold number of signers required to sign the transaction - - */ - constructor( - groupID: number = undefined, - addresses: Buffer[] = undefined, - locktime: BN = undefined, - threshold: number = undefined - ) { - super(addresses, locktime, threshold) - if (typeof groupID !== "undefined") { - this.groupID.writeUInt32BE(groupID, 0) - } - } -} - -/** - * An [[Output]] class which specifies an Output that carries an NFT and uses secp256k1 signature scheme. - */ -export class NFTTransferOutput extends NFTOutput { - protected _typeName = "NFTTransferOutput" - protected _codecID = AVMConstants.LATESTCODEC - protected _typeID = - this._codecID === 0 - ? AVMConstants.NFTXFEROUTPUTID - : AVMConstants.NFTXFEROUTPUTID_CODECONE - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - payload: serialization.encoder( - this.payload, - encoding, - "Buffer", - "hex", - this.payload.length - ) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.payload = serialization.decoder( - fields["payload"], - encoding, - "hex", - "Buffer" - ) - this.sizePayload = Buffer.alloc(4) - this.sizePayload.writeUInt32BE(this.payload.length, 0) - } - - protected sizePayload: Buffer = Buffer.alloc(4) - protected payload: Buffer - - /** - * Set the codecID - * - * @param codecID The codecID to set - */ - setCodecID(codecID: number): void { - if (codecID !== 0 && codecID !== 1) { - /* istanbul ignore next */ - throw new CodecIdError( - "Error - NFTTransferOutput.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - } - this._codecID = codecID - this._typeID = - this._codecID === 0 - ? AVMConstants.NFTXFEROUTPUTID - : AVMConstants.NFTXFEROUTPUTID_CODECONE - } - - /** - * Returns the outputID for this output - */ - getOutputID(): number { - return this._typeID - } - - /** - * Returns the payload as a {@link https://github.com/feross/buffer|Buffer} with content only. - */ - getPayload = (): Buffer => bintools.copyFrom(this.payload) - - /** - * Returns the payload as a {@link https://github.com/feross/buffer|Buffer} with length of payload prepended. - */ - getPayloadBuffer = (): Buffer => - Buffer.concat([ - bintools.copyFrom(this.sizePayload), - bintools.copyFrom(this.payload) - ]) - - /** - * Popuates the instance from a {@link https://github.com/feross/buffer|Buffer} representing the [[NFTTransferOutput]] and returns the size of the output. - */ - fromBuffer(utxobuff: Buffer, offset: number = 0): number { - this.groupID = bintools.copyFrom(utxobuff, offset, offset + 4) - offset += 4 - this.sizePayload = bintools.copyFrom(utxobuff, offset, offset + 4) - let psize: number = this.sizePayload.readUInt32BE(0) - offset += 4 - this.payload = bintools.copyFrom(utxobuff, offset, offset + psize) - offset = offset + psize - return super.fromBuffer(utxobuff, offset) - } - - /** - * Returns the buffer representing the [[NFTTransferOutput]] instance. - */ - toBuffer(): Buffer { - const superbuff: Buffer = super.toBuffer() - const bsize: number = - this.groupID.length + - this.sizePayload.length + - this.payload.length + - superbuff.length - this.sizePayload.writeUInt32BE(this.payload.length, 0) - const barr: Buffer[] = [ - this.groupID, - this.sizePayload, - this.payload, - superbuff - ] - return Buffer.concat(barr, bsize) - } - - create(...args: any[]): this { - return new NFTTransferOutput(...args) as this - } - - clone(): this { - const newout: NFTTransferOutput = this.create() - newout.fromBuffer(this.toBuffer()) - return newout as this - } - - /** - * An [[Output]] class which contains an NFT on an assetID. - * - * @param groupID A number representing the amount in the output - * @param payload A {@link https://github.com/feross/buffer|Buffer} of max length 1024 - * @param addresses An array of {@link https://github.com/feross/buffer|Buffer}s representing addresses - * @param locktime A {@link https://github.com/indutny/bn.js/|BN} representing the locktime - * @param threshold A number representing the the threshold number of signers required to sign the transaction - - */ - constructor( - groupID: number = undefined, - payload: Buffer = undefined, - addresses: Buffer[] = undefined, - locktime: BN = undefined, - threshold: number = undefined - ) { - super(addresses, locktime, threshold) - if (typeof groupID !== "undefined" && typeof payload !== "undefined") { - this.groupID.writeUInt32BE(groupID, 0) - this.sizePayload.writeUInt32BE(payload.length, 0) - this.payload = bintools.copyFrom(payload, 0, payload.length) - } - } -} diff --git a/src/apis/avm/tx.ts b/src/apis/avm/tx.ts deleted file mode 100644 index d9b8adca7..000000000 --- a/src/apis/avm/tx.ts +++ /dev/null @@ -1,140 +0,0 @@ -/** - * @packageDocumentation - * @module API-AVM-Transactions - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { AVMConstants } from "./constants" -import { SelectCredentialClass } from "./credentials" -import { KeyChain, KeyPair } from "./keychain" -import { Credential } from "../../common/credentials" -import { StandardTx, StandardUnsignedTx } from "../../common/tx" -import createHash from "create-hash" -import { BaseTx } from "./basetx" -import { CreateAssetTx } from "./createassettx" -import { OperationTx } from "./operationtx" -import { ImportTx } from "./importtx" -import { ExportTx } from "./exporttx" -import { SerializedEncoding } from "../../utils/serialization" -import { TransactionError } from "../../utils/errors" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() - -/** - * Takes a buffer representing the output and returns the proper [[BaseTx]] instance. - * - * @param txtype The id of the transaction type - * - * @returns An instance of an [[BaseTx]]-extended class. - */ -export const SelectTxClass = (txtype: number, ...args: any[]): BaseTx => { - if (txtype === AVMConstants.BASETX) { - return new BaseTx(...args) - } else if (txtype === AVMConstants.CREATEASSETTX) { - return new CreateAssetTx(...args) - } else if (txtype === AVMConstants.OPERATIONTX) { - return new OperationTx(...args) - } else if (txtype === AVMConstants.IMPORTTX) { - return new ImportTx(...args) - } else if (txtype === AVMConstants.EXPORTTX) { - return new ExportTx(...args) - } - /* istanbul ignore next */ - throw new TransactionError("Error - SelectTxClass: unknown txtype") -} - -export class UnsignedTx extends StandardUnsignedTx { - protected _typeName = "UnsignedTx" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.transaction = SelectTxClass(fields["transaction"]["_typeID"]) - this.transaction.deserialize(fields["transaction"], encoding) - } - - getTransaction(): BaseTx { - return this.transaction as BaseTx - } - - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.codecID = bintools.copyFrom(bytes, offset, offset + 2).readUInt16BE(0) - offset += 2 - const txtype: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.transaction = SelectTxClass(txtype) - return this.transaction.fromBuffer(bytes, offset) - } - - /** - * Signs this [[UnsignedTx]] and returns signed [[StandardTx]] - * - * @param kc An [[KeyChain]] used in signing - * - * @returns A signed [[StandardTx]] - */ - sign(kc: KeyChain): Tx { - const txbuff = this.toBuffer() - const msg: Buffer = Buffer.from( - createHash("sha256").update(txbuff).digest() - ) - const creds: Credential[] = this.transaction.sign(msg, kc) - return new Tx(this, creds) - } -} - -export class Tx extends StandardTx { - protected _typeName = "Tx" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.unsignedTx = new UnsignedTx() - this.unsignedTx.deserialize(fields["unsignedTx"], encoding) - this.credentials = [] - for (let i: number = 0; i < fields["credentials"].length; i++) { - const cred: Credential = SelectCredentialClass( - fields["credentials"][`${i}`]["_typeID"] - ) - cred.deserialize(fields["credentials"][`${i}`], encoding) - this.credentials.push(cred) - } - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[Tx]], parses it, populates the class, and returns the length of the Tx in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[Tx]] - * @param offset A number representing the starting point of the bytes to begin parsing - * - * @returns The length of the raw [[Tx]] - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.unsignedTx = new UnsignedTx() - offset = this.unsignedTx.fromBuffer(bytes, offset) - const numcreds: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.credentials = [] - for (let i: number = 0; i < numcreds; i++) { - const credid: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - const cred: Credential = SelectCredentialClass(credid) - offset = cred.fromBuffer(bytes, offset) - this.credentials.push(cred) - } - return offset - } -} diff --git a/src/apis/avm/utxos.ts b/src/apis/avm/utxos.ts deleted file mode 100644 index 7234bc3b0..000000000 --- a/src/apis/avm/utxos.ts +++ /dev/null @@ -1,1105 +0,0 @@ -/** - * @packageDocumentation - * @module API-AVM-UTXOs - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import BN from "bn.js" -import { - AmountOutput, - SelectOutputClass, - TransferableOutput, - NFTTransferOutput, - NFTMintOutput, - SECPMintOutput, - SECPTransferOutput -} from "./outputs" -import { AVMConstants } from "./constants" -import { UnsignedTx } from "./tx" -import { SECPTransferInput, TransferableInput } from "./inputs" -import { - NFTTransferOperation, - TransferableOperation, - NFTMintOperation, - SECPMintOperation -} from "./ops" -import { Output, OutputOwners } from "../../common/output" -import { UnixNow } from "../../utils/helperfunctions" -import { InitialStates } from "./initialstates" -import { MinterSet } from "./minterset" -import { StandardUTXO, StandardUTXOSet } from "../../common/utxos" -import { CreateAssetTx } from "./createassettx" -import { OperationTx } from "./operationtx" -import { BaseTx } from "./basetx" -import { ExportTx } from "./exporttx" -import { ImportTx } from "./importtx" -import { PlatformChainID } from "../../utils/constants" -import { - StandardAssetAmountDestination, - AssetAmount -} from "../../common/assetamount" -import { Serialization, SerializedEncoding } from "../../utils/serialization" -import { - UTXOError, - AddressError, - InsufficientFundsError, - ThresholdError, - SECPMintOutputError -} from "../../utils/errors" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Class for representing a single UTXO. - */ -export class UTXO extends StandardUTXO { - protected _typeName = "UTXO" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.output = SelectOutputClass(fields["output"]["_typeID"]) - this.output.deserialize(fields["output"], encoding) - } - - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.codecID = bintools.copyFrom(bytes, offset, offset + 2) - offset += 2 - this.txid = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - this.outputidx = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - this.assetID = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - const outputid: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.output = SelectOutputClass(outputid) - return this.output.fromBuffer(bytes, offset) - } - - /** - * Takes a base-58 string containing a [[UTXO]], parses it, populates the class, and returns the length of the StandardUTXO in bytes. - * - * @param serialized A base-58 string containing a raw [[UTXO]] - * - * @returns The length of the raw [[UTXO]] - * - * @remarks - * unlike most fromStrings, it expects the string to be serialized in cb58 format - */ - fromString(serialized: string): number { - /* istanbul ignore next */ - return this.fromBuffer(bintools.cb58Decode(serialized)) - } - - /** - * Returns a base-58 representation of the [[UTXO]]. - * - * @remarks - * unlike most toStrings, this returns in cb58 serialization format - */ - toString(): string { - /* istanbul ignore next */ - return bintools.cb58Encode(this.toBuffer()) - } - - clone(): this { - const utxo: UTXO = new UTXO() - utxo.fromBuffer(this.toBuffer()) - return utxo as this - } - - create( - codecID: number = AVMConstants.LATESTCODEC, - txid: Buffer = undefined, - outputidx: Buffer | number = undefined, - assetID: Buffer = undefined, - output: Output = undefined - ): this { - return new UTXO(codecID, txid, outputidx, assetID, output) as this - } -} - -export class AssetAmountDestination extends StandardAssetAmountDestination< - TransferableOutput, - TransferableInput -> {} - -/** - * Class representing a set of [[UTXO]]s. - */ -export class UTXOSet extends StandardUTXOSet { - protected _typeName = "UTXOSet" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - let utxos = {} - for (let utxoid in fields["utxos"]) { - let utxoidCleaned: string = serialization.decoder( - utxoid, - encoding, - "base58", - "base58" - ) - utxos[`${utxoidCleaned}`] = new UTXO() - utxos[`${utxoidCleaned}`].deserialize( - fields["utxos"][`${utxoid}`], - encoding - ) - } - let addressUTXOs = {} - for (let address in fields["addressUTXOs"]) { - let addressCleaned: string = serialization.decoder( - address, - encoding, - "cb58", - "hex" - ) - let utxobalance: {} = {} - for (let utxoid in fields["addressUTXOs"][`${address}`]) { - let utxoidCleaned: string = serialization.decoder( - utxoid, - encoding, - "base58", - "base58" - ) - utxobalance[`${utxoidCleaned}`] = serialization.decoder( - fields["addressUTXOs"][`${address}`][`${utxoid}`], - encoding, - "decimalString", - "BN" - ) - } - addressUTXOs[`${addressCleaned}`] = utxobalance - } - this.utxos = utxos - this.addressUTXOs = addressUTXOs - } - - parseUTXO(utxo: UTXO | string): UTXO { - const utxovar: UTXO = new UTXO() - // force a copy - if (typeof utxo === "string") { - utxovar.fromBuffer(bintools.cb58Decode(utxo)) - } else if (utxo instanceof UTXO) { - utxovar.fromBuffer(utxo.toBuffer()) // forces a copy - } else { - /* istanbul ignore next */ - throw new UTXOError( - "Error - UTXO.parseUTXO: utxo parameter is not a UTXO or string" - ) - } - return utxovar - } - - create(...args: any[]): this { - return new UTXOSet() as this - } - - clone(): this { - const newset: UTXOSet = this.create() - const allUTXOs: UTXO[] = this.getAllUTXOs() - newset.addArray(allUTXOs) - return newset as this - } - - _feeCheck(fee: BN, feeAssetID: Buffer): boolean { - return ( - typeof fee !== "undefined" && - typeof feeAssetID !== "undefined" && - fee.gt(new BN(0)) && - feeAssetID instanceof Buffer - ) - } - - getMinimumSpendable = ( - aad: AssetAmountDestination, - asOf: BN = UnixNow(), - locktime: BN = new BN(0), - threshold: number = 1 - ): Error => { - const utxoArray: UTXO[] = this.getAllUTXOs() - const outids: object = {} - for (let i: number = 0; i < utxoArray.length && !aad.canComplete(); i++) { - const u: UTXO = utxoArray[`${i}`] - const assetKey: string = u.getAssetID().toString("hex") - const fromAddresses: Buffer[] = aad.getSenders() - if ( - u.getOutput() instanceof AmountOutput && - aad.assetExists(assetKey) && - u.getOutput().meetsThreshold(fromAddresses, asOf) - ) { - const am: AssetAmount = aad.getAssetAmount(assetKey) - if (!am.isFinished()) { - const uout: AmountOutput = u.getOutput() as AmountOutput - outids[`${assetKey}`] = uout.getOutputID() - const amount = uout.getAmount() - am.spendAmount(amount) - const txid: Buffer = u.getTxID() - const outputidx: Buffer = u.getOutputIdx() - const input: SECPTransferInput = new SECPTransferInput(amount) - const xferin: TransferableInput = new TransferableInput( - txid, - outputidx, - u.getAssetID(), - input - ) - const spenders: Buffer[] = uout.getSpenders(fromAddresses, asOf) - for (let j: number = 0; j < spenders.length; j++) { - const idx: number = uout.getAddressIdx(spenders[`${j}`]) - if (idx === -1) { - /* istanbul ignore next */ - throw new AddressError( - "Error - UTXOSet.getMinimumSpendable: no such " + - `address in output: ${spenders[`${j}`]}` - ) - } - xferin.getInput().addSignatureIdx(idx, spenders[`${j}`]) - } - aad.addInput(xferin) - } else if ( - aad.assetExists(assetKey) && - !(u.getOutput() instanceof AmountOutput) - ) { - /** - * Leaving the below lines, not simply for posterity, but for clarification. - * AssetIDs may have mixed OutputTypes. - * Some of those OutputTypes may implement AmountOutput. - * Others may not. - * Simply continue in this condition. - */ - /*return new Error('Error - UTXOSet.getMinimumSpendable: outputID does not ' - + `implement AmountOutput: ${u.getOutput().getOutputID}`)*/ - continue - } - } - } - if (!aad.canComplete()) { - return new InsufficientFundsError( - "Error - UTXOSet.getMinimumSpendable: insufficient " + - "funds to create the transaction" - ) - } - const amounts: AssetAmount[] = aad.getAmounts() - const zero: BN = new BN(0) - for (let i: number = 0; i < amounts.length; i++) { - const assetKey: string = amounts[`${i}`].getAssetIDString() - const amount: BN = amounts[`${i}`].getAmount() - if (amount.gt(zero)) { - const spendout: AmountOutput = SelectOutputClass( - outids[`${assetKey}`], - amount, - aad.getDestinations(), - locktime, - threshold - ) as AmountOutput - const xferout: TransferableOutput = new TransferableOutput( - amounts[`${i}`].getAssetID(), - spendout - ) - aad.addOutput(xferout) - } - const change: BN = amounts[`${i}`].getChange() - if (change.gt(zero)) { - const changeout: AmountOutput = SelectOutputClass( - outids[`${assetKey}`], - change, - aad.getChangeAddresses() - ) as AmountOutput - const chgxferout: TransferableOutput = new TransferableOutput( - amounts[`${i}`].getAssetID(), - changeout - ) - aad.addChange(chgxferout) - } - } - return undefined - } - - /** - * Creates an [[UnsignedTx]] wrapping a [[BaseTx]]. For more granular control, you may create your own - * [[UnsignedTx]] wrapping a [[BaseTx]] manually (with their corresponding [[TransferableInput]]s and [[TransferableOutput]]s). - * - * @param networkID The number representing NetworkID of the node - * @param blockchainID The {@link https://github.com/feross/buffer|Buffer} representing the BlockchainID for the transaction - * @param amount The amount of the asset to be spent in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN}. - * @param assetID {@link https://github.com/feross/buffer|Buffer} of the asset ID for the UTXO - * @param toAddresses The addresses to send the funds - * @param fromAddresses The addresses being used to send the funds from the UTXOs {@link https://github.com/feross/buffer|Buffer} - * @param changeAddresses Optional. The addresses that can spend the change remaining from the spent UTXOs. Default: toAddresses - * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN} - * @param feeAssetID Optional. The assetID of the fees being burned. Default: assetID - * @param memo Optional. Contains arbitrary data, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param locktime Optional. The locktime field created in the resulting outputs - * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO - * - * @returns An unsigned transaction created from the passed in parameters. - * - */ - buildBaseTx = ( - networkID: number, - blockchainID: Buffer, - amount: BN, - assetID: Buffer, - toAddresses: Buffer[], - fromAddresses: Buffer[], - changeAddresses: Buffer[] = undefined, - fee: BN = undefined, - feeAssetID: Buffer = undefined, - memo: Buffer = undefined, - asOf: BN = UnixNow(), - locktime: BN = new BN(0), - threshold: number = 1 - ): UnsignedTx => { - if (threshold > toAddresses.length) { - /* istanbul ignore next */ - throw new ThresholdError( - "Error - UTXOSet.buildBaseTx: threshold is greater than number of addresses" - ) - } - - if (typeof changeAddresses === "undefined") { - changeAddresses = toAddresses - } - - if (typeof feeAssetID === "undefined") { - feeAssetID = assetID - } - - const zero: BN = new BN(0) - - if (amount.eq(zero)) { - return undefined - } - - const aad: AssetAmountDestination = new AssetAmountDestination( - toAddresses, - fromAddresses, - changeAddresses - ) - if (assetID.toString("hex") === feeAssetID.toString("hex")) { - aad.addAssetAmount(assetID, amount, fee) - } else { - aad.addAssetAmount(assetID, amount, zero) - if (this._feeCheck(fee, feeAssetID)) { - aad.addAssetAmount(feeAssetID, zero, fee) - } - } - - let ins: TransferableInput[] = [] - let outs: TransferableOutput[] = [] - - const success: Error = this.getMinimumSpendable( - aad, - asOf, - locktime, - threshold - ) - if (typeof success === "undefined") { - ins = aad.getInputs() - outs = aad.getAllOutputs() - } else { - throw success - } - - const baseTx: BaseTx = new BaseTx(networkID, blockchainID, outs, ins, memo) - return new UnsignedTx(baseTx) - } - - /** - * Creates an unsigned Create Asset transaction. For more granular control, you may create your own - * [[CreateAssetTX]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s). - * - * @param networkID The number representing NetworkID of the node - * @param blockchainID The {@link https://github.com/feross/buffer|Buffer} representing the BlockchainID for the transaction - * @param fromAddresses The addresses being used to send the funds from the UTXOs {@link https://github.com/feross/buffer|Buffer} - * @param changeAddresses Optional. The addresses that can spend the change remaining from the spent UTXOs - * @param initialState The [[InitialStates]] that represent the intial state of a created asset - * @param name String for the descriptive name of the asset - * @param symbol String for the ticker symbol of the asset - * @param denomination Optional number for the denomination which is 10^D. D must be >= 0 and <= 32. Ex: $1 AVAX = 10^9 $nAVAX - * @param mintOutputs Optional. Array of [[SECPMintOutput]]s to be included in the transaction. These outputs can be spent to mint more tokens. - * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN} - * @param feeAssetID Optional. The assetID of the fees being burned. - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * - * @returns An unsigned transaction created from the passed in parameters. - * - */ - buildCreateAssetTx = ( - networkID: number, - blockchainID: Buffer, - fromAddresses: Buffer[], - changeAddresses: Buffer[], - initialState: InitialStates, - name: string, - symbol: string, - denomination: number, - mintOutputs: SECPMintOutput[] = undefined, - fee: BN = undefined, - feeAssetID: Buffer = undefined, - memo: Buffer = undefined, - asOf: BN = UnixNow() - ): UnsignedTx => { - const zero: BN = new BN(0) - let ins: TransferableInput[] = [] - let outs: TransferableOutput[] = [] - - if (this._feeCheck(fee, feeAssetID)) { - const aad: AssetAmountDestination = new AssetAmountDestination( - fromAddresses, - fromAddresses, - changeAddresses - ) - aad.addAssetAmount(feeAssetID, zero, fee) - const success: Error = this.getMinimumSpendable(aad, asOf) - if (typeof success === "undefined") { - ins = aad.getInputs() - outs = aad.getAllOutputs() - } else { - throw success - } - } - if (typeof mintOutputs !== "undefined") { - for (let i: number = 0; i < mintOutputs.length; i++) { - if (mintOutputs[`${i}`] instanceof SECPMintOutput) { - initialState.addOutput(mintOutputs[`${i}`]) - } else { - throw new SECPMintOutputError( - "Error - UTXOSet.buildCreateAssetTx: A submitted mintOutput was not of type SECPMintOutput" - ) - } - } - } - - let CAtx: CreateAssetTx = new CreateAssetTx( - networkID, - blockchainID, - outs, - ins, - memo, - name, - symbol, - denomination, - initialState - ) - return new UnsignedTx(CAtx) - } - - /** - * Creates an unsigned Secp mint transaction. For more granular control, you may create your own - * [[OperationTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s, and [[TransferOperation]]s). - * - * @param networkID The number representing NetworkID of the node - * @param blockchainID The {@link https://github.com/feross/buffer|Buffer} representing the BlockchainID for the transaction - * @param mintOwner A [[SECPMintOutput]] which specifies the new set of minters - * @param transferOwner A [[SECPTransferOutput]] which specifies where the minted tokens will go - * @param fromAddresses The addresses being used to send the funds from the UTXOs {@link https://github.com/feross/buffer|Buffer} - * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs - * @param mintUTXOID The UTXOID for the [[SCPMintOutput]] being spent to produce more tokens - * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN} - * @param feeAssetID Optional. The assetID of the fees being burned. - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - */ - buildSECPMintTx = ( - networkID: number, - blockchainID: Buffer, - mintOwner: SECPMintOutput, - transferOwner: SECPTransferOutput, - fromAddresses: Buffer[], - changeAddresses: Buffer[], - mintUTXOID: string, - fee: BN = undefined, - feeAssetID: Buffer = undefined, - memo: Buffer = undefined, - asOf: BN = UnixNow() - ): UnsignedTx => { - const zero: BN = new BN(0) - let ins: TransferableInput[] = [] - let outs: TransferableOutput[] = [] - - if (this._feeCheck(fee, feeAssetID)) { - const aad: AssetAmountDestination = new AssetAmountDestination( - fromAddresses, - fromAddresses, - changeAddresses - ) - aad.addAssetAmount(feeAssetID, zero, fee) - const success: Error = this.getMinimumSpendable(aad, asOf) - if (typeof success === "undefined") { - ins = aad.getInputs() - outs = aad.getAllOutputs() - } else { - throw success - } - } - - let ops: TransferableOperation[] = [] - let mintOp: SECPMintOperation = new SECPMintOperation( - mintOwner, - transferOwner - ) - - let utxo: UTXO = this.getUTXO(mintUTXOID) - if (typeof utxo === "undefined") { - throw new UTXOError("Error - UTXOSet.buildSECPMintTx: UTXOID not found") - } - if (utxo.getOutput().getOutputID() !== AVMConstants.SECPMINTOUTPUTID) { - throw new SECPMintOutputError( - "Error - UTXOSet.buildSECPMintTx: UTXO is not a SECPMINTOUTPUTID" - ) - } - let out: SECPMintOutput = utxo.getOutput() as SECPMintOutput - let spenders: Buffer[] = out.getSpenders(fromAddresses, asOf) - - for (let j: number = 0; j < spenders.length; j++) { - let idx: number = out.getAddressIdx(spenders[`${j}`]) - if (idx == -1) { - /* istanbul ignore next */ - throw new Error( - "Error - UTXOSet.buildSECPMintTx: no such address in output" - ) - } - mintOp.addSignatureIdx(idx, spenders[`${j}`]) - } - - let transferableOperation: TransferableOperation = - new TransferableOperation(utxo.getAssetID(), [`${mintUTXOID}`], mintOp) - ops.push(transferableOperation) - - let operationTx: OperationTx = new OperationTx( - networkID, - blockchainID, - outs, - ins, - memo, - ops - ) - return new UnsignedTx(operationTx) - } - - /** - * Creates an unsigned Create Asset transaction. For more granular control, you may create your own - * [[CreateAssetTX]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s). - * - * @param networkID The number representing NetworkID of the node - * @param blockchainID The {@link https://github.com/feross/buffer|Buffer} representing the BlockchainID for the transaction - * @param fromAddresses The addresses being used to send the funds from the UTXOs {@link https://github.com/feross/buffer|Buffer} - * @param changeAddresses Optional. The addresses that can spend the change remaining from the spent UTXOs. - * @param minterSets The minters and thresholds required to mint this nft asset - * @param name String for the descriptive name of the nft asset - * @param symbol String for the ticker symbol of the nft asset - * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN} - * @param feeAssetID Optional. The assetID of the fees being burned. - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param locktime Optional. The locktime field created in the resulting mint output - * - * @returns An unsigned transaction created from the passed in parameters. - * - */ - buildCreateNFTAssetTx = ( - networkID: number, - blockchainID: Buffer, - fromAddresses: Buffer[], - changeAddresses: Buffer[], - minterSets: MinterSet[], - name: string, - symbol: string, - fee: BN = undefined, - feeAssetID: Buffer = undefined, - memo: Buffer = undefined, - asOf: BN = UnixNow(), - locktime: BN = undefined - ): UnsignedTx => { - const zero: BN = new BN(0) - let ins: TransferableInput[] = [] - let outs: TransferableOutput[] = [] - - if (this._feeCheck(fee, feeAssetID)) { - const aad: AssetAmountDestination = new AssetAmountDestination( - fromAddresses, - fromAddresses, - changeAddresses - ) - aad.addAssetAmount(feeAssetID, zero, fee) - const success: Error = this.getMinimumSpendable(aad, asOf) - if (typeof success === "undefined") { - ins = aad.getInputs() - outs = aad.getAllOutputs() - } else { - throw success - } - } - let initialState: InitialStates = new InitialStates() - for (let i: number = 0; i < minterSets.length; i++) { - let nftMintOutput: NFTMintOutput = new NFTMintOutput( - i, - minterSets[`${i}`].getMinters(), - locktime, - minterSets[`${i}`].getThreshold() - ) - initialState.addOutput(nftMintOutput, AVMConstants.NFTFXID) - } - let denomination: number = 0 // NFTs are non-fungible - let CAtx: CreateAssetTx = new CreateAssetTx( - networkID, - blockchainID, - outs, - ins, - memo, - name, - symbol, - denomination, - initialState - ) - return new UnsignedTx(CAtx) - } - - /** - * Creates an unsigned NFT mint transaction. For more granular control, you may create your own - * [[OperationTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s, and [[TransferOperation]]s). - * - * @param networkID The number representing NetworkID of the node - * @param blockchainID The {@link https://github.com/feross/buffer|Buffer} representing the BlockchainID for the transaction - * @param owners An array of [[OutputOwners]] who will be given the NFTs. - * @param fromAddresses The addresses being used to send the funds from the UTXOs - * @param changeAddresses Optional. The addresses that can spend the change remaining from the spent UTXOs. - * @param utxoids An array of strings for the NFTs being transferred - * @param groupID Optional. The group this NFT is issued to. - * @param payload Optional. Data for NFT Payload. - * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN} - * @param feeAssetID Optional. The assetID of the fees being burned. - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * - * @returns An unsigned transaction created from the passed in parameters. - * - */ - buildCreateNFTMintTx = ( - networkID: number, - blockchainID: Buffer, - owners: OutputOwners[], - fromAddresses: Buffer[], - changeAddresses: Buffer[], - utxoids: string[], - groupID: number = 0, - payload: Buffer = undefined, - fee: BN = undefined, - feeAssetID: Buffer = undefined, - memo: Buffer = undefined, - asOf: BN = UnixNow() - ): UnsignedTx => { - const zero: BN = new BN(0) - let ins: TransferableInput[] = [] - let outs: TransferableOutput[] = [] - - if (this._feeCheck(fee, feeAssetID)) { - const aad: AssetAmountDestination = new AssetAmountDestination( - fromAddresses, - fromAddresses, - changeAddresses - ) - aad.addAssetAmount(feeAssetID, zero, fee) - const success: Error = this.getMinimumSpendable(aad, asOf) - if (typeof success === "undefined") { - ins = aad.getInputs() - outs = aad.getAllOutputs() - } else { - throw success - } - } - let ops: TransferableOperation[] = [] - - let nftMintOperation: NFTMintOperation = new NFTMintOperation( - groupID, - payload, - owners - ) - - for (let i: number = 0; i < utxoids.length; i++) { - let utxo: UTXO = this.getUTXO(utxoids[`${i}`]) - let out: NFTTransferOutput = utxo.getOutput() as NFTTransferOutput - let spenders: Buffer[] = out.getSpenders(fromAddresses, asOf) - - for (let j: number = 0; j < spenders.length; j++) { - let idx: number - idx = out.getAddressIdx(spenders[`${j}`]) - if (idx == -1) { - /* istanbul ignore next */ - throw new AddressError( - "Error - UTXOSet.buildCreateNFTMintTx: no such address in output" - ) - } - nftMintOperation.addSignatureIdx(idx, spenders[`${j}`]) - } - - let transferableOperation: TransferableOperation = - new TransferableOperation(utxo.getAssetID(), utxoids, nftMintOperation) - ops.push(transferableOperation) - } - - let operationTx: OperationTx = new OperationTx( - networkID, - blockchainID, - outs, - ins, - memo, - ops - ) - return new UnsignedTx(operationTx) - } - - /** - * Creates an unsigned NFT transfer transaction. For more granular control, you may create your own - * [[OperationTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s, and [[TransferOperation]]s). - * - * @param networkID The number representing NetworkID of the node - * @param blockchainID The {@link https://github.com/feross/buffer|Buffer} representing the BlockchainID for the transaction - * @param toAddresses An array of {@link https://github.com/feross/buffer|Buffer}s which indicate who recieves the NFT - * @param fromAddresses An array for {@link https://github.com/feross/buffer|Buffer} who owns the NFT - * @param changeAddresses Optional. The addresses that can spend the change remaining from the spent UTXOs. - * @param utxoids An array of strings for the NFTs being transferred - * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN} - * @param feeAssetID Optional. The assetID of the fees being burned. - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param locktime Optional. The locktime field created in the resulting outputs - * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO - * - * @returns An unsigned transaction created from the passed in parameters. - * - */ - buildNFTTransferTx = ( - networkID: number, - blockchainID: Buffer, - toAddresses: Buffer[], - fromAddresses: Buffer[], - changeAddresses: Buffer[], - utxoids: string[], - fee: BN = undefined, - feeAssetID: Buffer = undefined, - memo: Buffer = undefined, - asOf: BN = UnixNow(), - locktime: BN = new BN(0), - threshold: number = 1 - ): UnsignedTx => { - const zero: BN = new BN(0) - let ins: TransferableInput[] = [] - let outs: TransferableOutput[] = [] - - if (this._feeCheck(fee, feeAssetID)) { - const aad: AssetAmountDestination = new AssetAmountDestination( - fromAddresses, - fromAddresses, - changeAddresses - ) - aad.addAssetAmount(feeAssetID, zero, fee) - const success: Error = this.getMinimumSpendable(aad, asOf) - if (typeof success === "undefined") { - ins = aad.getInputs() - outs = aad.getAllOutputs() - } else { - throw success - } - } - const ops: TransferableOperation[] = [] - for (let i: number = 0; i < utxoids.length; i++) { - const utxo: UTXO = this.getUTXO(utxoids[`${i}`]) - - const out: NFTTransferOutput = utxo.getOutput() as NFTTransferOutput - const spenders: Buffer[] = out.getSpenders(fromAddresses, asOf) - - const outbound: NFTTransferOutput = new NFTTransferOutput( - out.getGroupID(), - out.getPayload(), - toAddresses, - locktime, - threshold - ) - const op: NFTTransferOperation = new NFTTransferOperation(outbound) - - for (let j: number = 0; j < spenders.length; j++) { - const idx: number = out.getAddressIdx(spenders[`${j}`]) - if (idx === -1) { - /* istanbul ignore next */ - throw new AddressError( - "Error - UTXOSet.buildNFTTransferTx: " + - `no such address in output: ${spenders[`${j}`]}` - ) - } - op.addSignatureIdx(idx, spenders[`${j}`]) - } - - const xferop: TransferableOperation = new TransferableOperation( - utxo.getAssetID(), - [utxoids[`${i}`]], - op - ) - ops.push(xferop) - } - const OpTx: OperationTx = new OperationTx( - networkID, - blockchainID, - outs, - ins, - memo, - ops - ) - return new UnsignedTx(OpTx) - } - - /** - * Creates an unsigned ImportTx transaction. - * - * @param networkID The number representing NetworkID of the node - * @param blockchainID The {@link https://github.com/feross/buffer|Buffer} representing the BlockchainID for the transaction - * @param toAddresses The addresses to send the funds - * @param fromAddresses The addresses being used to send the funds from the UTXOs {@link https://github.com/feross/buffer|Buffer} - * @param changeAddresses Optional. The addresses that can spend the change remaining from the spent UTXOs. - * @param importIns An array of [[TransferableInput]]s being imported - * @param sourceChain A {@link https://github.com/feross/buffer|Buffer} for the chainid where the imports are coming from. - * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN}. Fee will come from the inputs first, if they can. - * @param feeAssetID Optional. The assetID of the fees being burned. - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param locktime Optional. The locktime field created in the resulting outputs - * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO - * @returns An unsigned transaction created from the passed in parameters. - * - */ - buildImportTx = ( - networkID: number, - blockchainID: Buffer, - toAddresses: Buffer[], - fromAddresses: Buffer[], - changeAddresses: Buffer[], - atomics: UTXO[], - sourceChain: Buffer = undefined, - fee: BN = undefined, - feeAssetID: Buffer = undefined, - memo: Buffer = undefined, - asOf: BN = UnixNow(), - locktime: BN = new BN(0), - threshold: number = 1 - ): UnsignedTx => { - const zero: BN = new BN(0) - let ins: TransferableInput[] = [] - let outs: TransferableOutput[] = [] - if (typeof fee === "undefined") { - fee = zero.clone() - } - - const importIns: TransferableInput[] = [] - let feepaid: BN = new BN(0) - let feeAssetStr: string = feeAssetID.toString("hex") - for (let i: number = 0; i < atomics.length; i++) { - const utxo: UTXO = atomics[`${i}`] - const assetID: Buffer = utxo.getAssetID() - const output: AmountOutput = utxo.getOutput() as AmountOutput - let amt: BN = output.getAmount().clone() - - let infeeamount = amt.clone() - let assetStr: string = assetID.toString("hex") - if ( - typeof feeAssetID !== "undefined" && - fee.gt(zero) && - feepaid.lt(fee) && - assetStr === feeAssetStr - ) { - feepaid = feepaid.add(infeeamount) - if (feepaid.gt(fee)) { - infeeamount = feepaid.sub(fee) - feepaid = fee.clone() - } else { - infeeamount = zero.clone() - } - } - - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - const input: SECPTransferInput = new SECPTransferInput(amt) - const xferin: TransferableInput = new TransferableInput( - txid, - outputidx, - assetID, - input - ) - const from: Buffer[] = output.getAddresses() - const spenders: Buffer[] = output.getSpenders(from, asOf) - for (let j: number = 0; j < spenders.length; j++) { - const idx: number = output.getAddressIdx(spenders[`${j}`]) - if (idx === -1) { - /* istanbul ignore next */ - throw new AddressError( - "Error - UTXOSet.buildImportTx: no such " + - `address in output: ${spenders[`${j}`]}` - ) - } - xferin.getInput().addSignatureIdx(idx, spenders[`${j}`]) - } - importIns.push(xferin) - - //add extra outputs for each amount (calculated from the imported inputs), minus fees - if (infeeamount.gt(zero)) { - const spendout: AmountOutput = SelectOutputClass( - output.getOutputID(), - infeeamount, - toAddresses, - locktime, - threshold - ) as AmountOutput - const xferout: TransferableOutput = new TransferableOutput( - assetID, - spendout - ) - outs.push(xferout) - } - } - - // get remaining fees from the provided addresses - let feeRemaining: BN = fee.sub(feepaid) - if (feeRemaining.gt(zero) && this._feeCheck(feeRemaining, feeAssetID)) { - const aad: AssetAmountDestination = new AssetAmountDestination( - toAddresses, - fromAddresses, - changeAddresses - ) - aad.addAssetAmount(feeAssetID, zero, feeRemaining) - const success: Error = this.getMinimumSpendable( - aad, - asOf, - locktime, - threshold - ) - if (typeof success === "undefined") { - ins = aad.getInputs() - outs = aad.getAllOutputs() - } else { - throw success - } - } - - const importTx: ImportTx = new ImportTx( - networkID, - blockchainID, - outs, - ins, - memo, - sourceChain, - importIns - ) - return new UnsignedTx(importTx) - } - - /** - * Creates an unsigned ExportTx transaction. - * - * @param networkID The number representing NetworkID of the node - * @param blockchainID The {@link https://github.com/feross/buffer|Buffer} representing the BlockchainID for the transaction - * @param amount The amount being exported as a {@link https://github.com/indutny/bn.js/|BN} - * @param avaxAssetID {@link https://github.com/feross/buffer|Buffer} of the asset ID for AVAX - * @param toAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who recieves the AVAX - * @param fromAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who owns the AVAX - * @param changeAddresses Optional. The addresses that can spend the change remaining from the spent UTXOs. - * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN} - * @param destinationChain Optional. A {@link https://github.com/feross/buffer|Buffer} for the chainid where to send the asset. - * @param feeAssetID Optional. The assetID of the fees being burned. - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param locktime Optional. The locktime field created in the resulting outputs - * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO - * @returns An unsigned transaction created from the passed in parameters. - * - */ - buildExportTx = ( - networkID: number, - blockchainID: Buffer, - amount: BN, - assetID: Buffer, - toAddresses: Buffer[], - fromAddresses: Buffer[], - changeAddresses: Buffer[] = undefined, - destinationChain: Buffer = undefined, - fee: BN = undefined, - feeAssetID: Buffer = undefined, - memo: Buffer = undefined, - asOf: BN = UnixNow(), - locktime: BN = new BN(0), - threshold: number = 1 - ): UnsignedTx => { - let ins: TransferableInput[] = [] - let outs: TransferableOutput[] = [] - let exportouts: TransferableOutput[] = [] - - if (typeof changeAddresses === "undefined") { - changeAddresses = toAddresses - } - - const zero: BN = new BN(0) - - if (amount.eq(zero)) { - return undefined - } - - if (typeof feeAssetID === "undefined") { - feeAssetID = assetID - } - - if (typeof destinationChain === "undefined") { - destinationChain = bintools.cb58Decode(PlatformChainID) - } - - const aad: AssetAmountDestination = new AssetAmountDestination( - toAddresses, - fromAddresses, - changeAddresses - ) - if (assetID.toString("hex") === feeAssetID.toString("hex")) { - aad.addAssetAmount(assetID, amount, fee) - } else { - aad.addAssetAmount(assetID, amount, zero) - if (this._feeCheck(fee, feeAssetID)) { - aad.addAssetAmount(feeAssetID, zero, fee) - } - } - const success: Error = this.getMinimumSpendable( - aad, - asOf, - locktime, - threshold - ) - if (typeof success === "undefined") { - ins = aad.getInputs() - outs = aad.getChangeOutputs() - exportouts = aad.getOutputs() - } else { - throw success - } - - const exportTx: ExportTx = new ExportTx( - networkID, - blockchainID, - outs, - ins, - memo, - destinationChain, - exportouts - ) - return new UnsignedTx(exportTx) - } -} diff --git a/src/apis/avm/vertex.ts b/src/apis/avm/vertex.ts deleted file mode 100644 index 1cfab4d36..000000000 --- a/src/apis/avm/vertex.ts +++ /dev/null @@ -1,242 +0,0 @@ -/** - * @packageDocumentation - * @module API-AVM-Vertex - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { AVMConstants } from "./constants" -import { Tx, UnsignedTx } from "./tx" -import { Serializable, CodecIdError, DefaultNetworkID } from "../../utils" -import BN from "bn.js" -import { BaseTx } from "." - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() - -/** - * Class representing a Vertex - */ -export class Vertex extends Serializable { - protected _typeName = "Vertex" - protected _codecID = AVMConstants.LATESTCODEC - // serialize is inherited - // deserialize is inherited - protected networkID: number - protected blockchainID: Buffer - protected height: BN - protected epoch: number - protected parentIDs: Buffer[] - protected numParentIDs: number - protected txs: Tx[] - protected numTxs: number - protected restrictions: Buffer[] - protected numRestrictions: number - - /** - * Returns the NetworkID as a number - */ - getNetworkID(): number { - return this.networkID - } - /** - * Returns the BlockchainID as a CB58 string - */ - getBlockchainID(): string { - return bintools.cb58Encode(this.blockchainID) - } - - /** - * Returns the Height as a {@link https://github.com/indutny/bn.js/|BN}. - */ - getHeight(): BN { - return this.height - } - - /** - * Returns the Epoch as a number. - */ - getEpoch(): number { - return this.epoch - } - - /** - * @returns An array of Buffers - */ - getParentIDs(): Buffer[] { - return this.parentIDs - } - - /** - * Returns array of UnsignedTxs. - */ - getTxs(): Tx[] { - return this.txs - } - - /** - * @returns An array of Buffers - */ - getRestrictions(): Buffer[] { - return this.restrictions - } - - /** - * Set the codecID - * - * @param codecID The codecID to set - */ - setCodecID(codecID: number): void { - if (codecID !== 0 && codecID !== 1) { - /* istanbul ignore next */ - throw new CodecIdError( - "Error - Vertex.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - } - this._codecID = codecID - this._typeID = - this._codecID === 0 ? AVMConstants.VERTEX : AVMConstants.VERTEX_CODECONE - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[Vertex]], parses it, populates the class, and returns the length of the Vertex in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[Vertex]] - * - * @returns The length of the raw [[Vertex]] - * - * @remarks assume not-checksummed - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset += 2 - this.blockchainID = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - - const h: Buffer = bintools.copyFrom(bytes, offset, offset + 8) - this.height = bintools.fromBufferToBN(h) - offset += 8 - - const e: Buffer = bintools.copyFrom(bytes, offset, offset + 4) - this.epoch = e.readInt32BE(0) - offset += 4 - - const nPIDs: Buffer = bintools.copyFrom(bytes, offset, offset + 4) - this.numParentIDs = nPIDs.readInt32BE(0) - offset += 4 - - for (let i: number = 0; i < this.numParentIDs; i++) { - const parentID: Buffer = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - this.parentIDs.push(parentID) - } - - const nTxs: Buffer = bintools.copyFrom(bytes, offset, offset + 4) - this.numTxs = nTxs.readInt32BE(0) - // account for tx-size bytes - offset += 8 - - for (let i: number = 0; i < this.numTxs; i++) { - const tx: Tx = new Tx() - offset += tx.fromBuffer(bintools.copyFrom(bytes, offset)) - this.txs.push(tx) - } - - if (bytes.byteLength > offset && bytes.byteLength - offset > 4) { - const nRs: Buffer = bintools.copyFrom(bytes, offset, offset + 4) - this.numRestrictions = nRs.readInt32BE(0) - offset += 4 - for (let i: number = 0; i < this.numRestrictions; i++) { - const tx: Buffer = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - this.restrictions.push(tx) - } - } - - return offset - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[Vertex]]. - */ - toBuffer(): Buffer { - const codec: number = this.getCodecID() - const codecBuf: Buffer = Buffer.alloc(2) - codecBuf.writeUInt16BE(codec, 0) - - const epochBuf: Buffer = Buffer.alloc(4) - epochBuf.writeInt32BE(this.epoch, 0) - - const numParentIDsBuf: Buffer = Buffer.alloc(4) - numParentIDsBuf.writeInt32BE(this.numParentIDs, 0) - let barr: Buffer[] = [ - codecBuf, - this.blockchainID, - bintools.fromBNToBuffer(this.height, 8), - epochBuf, - numParentIDsBuf - ] - this.parentIDs.forEach((parentID: Buffer): void => { - barr.push(parentID) - }) - - const txs: Tx[] = this.getTxs() - const numTxs: Buffer = Buffer.alloc(4) - numTxs.writeUInt32BE(txs.length, 0) - barr.push(numTxs) - - let size: number = 0 - const txSize: Buffer = Buffer.alloc(4) - txs.forEach((tx: Tx): void => { - const b: Buffer = tx.toBuffer() - size += b.byteLength - }) - txSize.writeUInt32BE(size, 0) - barr.push(txSize) - - txs.forEach((tx: Tx): void => { - const b: Buffer = tx.toBuffer() - barr.push(b) - }) - - return Buffer.concat(barr) - } - - clone(): this { - let vertex: Vertex = new Vertex() - vertex.fromBuffer(this.toBuffer()) - return vertex as this - } - /** - * Class representing a Vertex which is a container for AVM Transactions. - * - * @param networkID Optional, [[DefaultNetworkID]] - * @param blockchainID Optional, default "2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM" - * @param height Optional, default new BN(0) - * @param epoch Optional, default new BN(0) - * @param parentIDs Optional, default [] - * @param txs Optional, default [] - * @param restrictions Optional, default [] - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: string = "2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM", - height: BN = new BN(0), - epoch: number = 0, - parentIDs: Buffer[] = [], - txs: Tx[] = [], - restrictions: Buffer[] = [] - ) { - super() - this.networkID = networkID - this.blockchainID = bintools.cb58Decode(blockchainID) - this.height = height - this.epoch = epoch - this.parentIDs = parentIDs - this.numParentIDs = parentIDs.length - this.txs = txs - this.numTxs = txs.length - this.restrictions = restrictions - this.numRestrictions = restrictions.length - } -} diff --git a/src/apis/evm/api.ts b/src/apis/evm/api.ts deleted file mode 100644 index 3ce257bd7..000000000 --- a/src/apis/evm/api.ts +++ /dev/null @@ -1,922 +0,0 @@ -/** - * @packageDocumentation - * @module API-EVM - */ - -import { Buffer } from "buffer/" -import BN from "bn.js" -import AvalancheCore from "../../avalanche" -import { JRPCAPI } from "../../common/jrpcapi" -import { RequestResponseData } from "../../common/apibase" -import BinTools from "../../utils/bintools" -import { UTXOSet, UTXO } from "./utxos" -import { KeyChain } from "./keychain" -import { Defaults, PrimaryAssetAlias } from "../../utils/constants" -import { Tx, UnsignedTx } from "./tx" -import { EVMConstants } from "./constants" -import { - Asset, - Index, - IssueTxParams, - UTXOResponse -} from "./../../common/interfaces" -import { EVMInput } from "./inputs" -import { SECPTransferOutput, TransferableOutput } from "./outputs" -import { ExportTx } from "./exporttx" -import { - TransactionError, - ChainIdError, - NoAtomicUTXOsError, - AddressError -} from "../../utils/errors" -import { Serialization, SerializedType } from "../../utils" -import { - ExportAVAXParams, - ExportKeyParams, - ExportParams, - GetAtomicTxParams, - GetAssetDescriptionParams, - GetAtomicTxStatusParams, - GetUTXOsParams, - ImportAVAXParams, - ImportKeyParams, - ImportParams -} from "./interfaces" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Class for interacting with a node's EVMAPI - * - * @category RPCAPIs - * - * @remarks This extends the [[JRPCAPI]] class. This class should not be directly called. Instead, use the [[Avalanche.addAPI]] function to register this interface with Avalanche. - */ -export class EVMAPI extends JRPCAPI { - /** - * @ignore - */ - protected keychain: KeyChain = new KeyChain("", "") - protected blockchainID: string = "" - protected blockchainAlias: string = undefined - protected AVAXAssetID: Buffer = undefined - protected txFee: BN = undefined - - /** - * Gets the alias for the blockchainID if it exists, otherwise returns `undefined`. - * - * @returns The alias for the blockchainID - */ - getBlockchainAlias = (): string => { - if (typeof this.blockchainAlias === "undefined") { - const netID: number = this.core.getNetworkID() - if ( - netID in Defaults.network && - this.blockchainID in Defaults.network[`${netID}`] - ) { - this.blockchainAlias = - Defaults.network[`${netID}`][this.blockchainID]["alias"] - return this.blockchainAlias - } else { - /* istanbul ignore next */ - return undefined - } - } - return this.blockchainAlias - } - - /** - * Sets the alias for the blockchainID. - * - * @param alias The alias for the blockchainID. - * - */ - setBlockchainAlias = (alias: string): string => { - this.blockchainAlias = alias - /* istanbul ignore next */ - return undefined - } - - /** - * Gets the blockchainID and returns it. - * - * @returns The blockchainID - */ - getBlockchainID = (): string => this.blockchainID - - /** - * Refresh blockchainID, and if a blockchainID is passed in, use that. - * - * @param Optional. BlockchainID to assign, if none, uses the default based on networkID. - * - * @returns A boolean if the blockchainID was successfully refreshed. - */ - refreshBlockchainID = (blockchainID: string = undefined): boolean => { - const netID: number = this.core.getNetworkID() - if ( - typeof blockchainID === "undefined" && - typeof Defaults.network[`${netID}`] !== "undefined" - ) { - this.blockchainID = Defaults.network[`${netID}`].C.blockchainID //default to C-Chain - return true - } - - if (typeof blockchainID === "string") { - this.blockchainID = blockchainID - return true - } - - return false - } - - /** - * Takes an address string and returns its {@link https://github.com/feross/buffer|Buffer} representation if valid. - * - * @returns A {@link https://github.com/feross/buffer|Buffer} for the address if valid, undefined if not valid. - */ - parseAddress = (addr: string): Buffer => { - const alias: string = this.getBlockchainAlias() - const blockchainID: string = this.getBlockchainID() - return bintools.parseAddress( - addr, - blockchainID, - alias, - EVMConstants.ADDRESSLENGTH - ) - } - - addressFromBuffer = (address: Buffer): string => { - const chainID: string = this.getBlockchainAlias() - ? this.getBlockchainAlias() - : this.getBlockchainID() - const type: SerializedType = "bech32" - return serialization.bufferToType( - address, - type, - this.core.getHRP(), - chainID - ) - } - - /** - * Retrieves an assets name and symbol. - * - * @param assetID Either a {@link https://github.com/feross/buffer|Buffer} or an b58 serialized string for the AssetID or its alias. - * - * @returns Returns a Promise Asset with keys "name", "symbol", "assetID" and "denomination". - */ - getAssetDescription = async (assetID: Buffer | string): Promise => { - let asset: string - if (typeof assetID !== "string") { - asset = bintools.cb58Encode(assetID) - } else { - asset = assetID - } - - const params: GetAssetDescriptionParams = { - assetID: asset - } - - const tmpBaseURL: string = this.getBaseURL() - - // set base url to get asset description - this.setBaseURL("/ext/bc/X") - const response: RequestResponseData = await this.callMethod( - "avm.getAssetDescription", - params - ) - - // set base url back what it originally was - this.setBaseURL(tmpBaseURL) - return { - name: response.data.result.name, - symbol: response.data.result.symbol, - assetID: bintools.cb58Decode(response.data.result.assetID), - denomination: parseInt(response.data.result.denomination, 10) - } - } - - /** - * Fetches the AVAX AssetID and returns it in a Promise. - * - * @param refresh This function caches the response. Refresh = true will bust the cache. - * - * @returns The the provided string representing the AVAX AssetID - */ - getAVAXAssetID = async (refresh: boolean = false): Promise => { - if (typeof this.AVAXAssetID === "undefined" || refresh) { - const asset: Asset = await this.getAssetDescription(PrimaryAssetAlias) - this.AVAXAssetID = asset.assetID - } - return this.AVAXAssetID - } - - /** - * Overrides the defaults and sets the cache to a specific AVAX AssetID - * - * @param avaxAssetID A cb58 string or Buffer representing the AVAX AssetID - * - * @returns The the provided string representing the AVAX AssetID - */ - setAVAXAssetID = (avaxAssetID: string | Buffer) => { - if (typeof avaxAssetID === "string") { - avaxAssetID = bintools.cb58Decode(avaxAssetID) - } - this.AVAXAssetID = avaxAssetID - } - - /** - * Gets the default tx fee for this chain. - * - * @returns The default tx fee as a {@link https://github.com/indutny/bn.js/|BN} - */ - getDefaultTxFee = (): BN => { - return this.core.getNetworkID() in Defaults.network - ? new BN(Defaults.network[this.core.getNetworkID()]["C"]["txFee"]) - : new BN(0) - } - - /** - * returns the amount of [assetID] for the given address in the state of the given block number. - * "latest", "pending", and "accepted" meta block numbers are also allowed. - * - * @param hexAddress The hex representation of the address - * @param blockHeight The block height - * @param assetID The asset ID - * - * @returns Returns a Promise object containing the balance - */ - getAssetBalance = async ( - hexAddress: string, - blockHeight: string, - assetID: string - ): Promise => { - const params: string[] = [hexAddress, blockHeight, assetID] - - const method: string = "eth_getAssetBalance" - const path: string = "ext/bc/C/rpc" - const response: RequestResponseData = await this.callMethod( - method, - params, - path - ) - return response.data - } - - /** - * Returns the status of a provided atomic transaction ID by calling the node's `getAtomicTxStatus` method. - * - * @param txID The string representation of the transaction ID - * - * @returns Returns a Promise string containing the status retrieved from the node - */ - getAtomicTxStatus = async (txID: string): Promise => { - const params: GetAtomicTxStatusParams = { - txID - } - - const response: RequestResponseData = await this.callMethod( - "avax.getAtomicTxStatus", - params - ) - return response.data.result.status - ? response.data.result.status - : response.data.result - } - - /** - * Returns the transaction data of a provided transaction ID by calling the node's `getAtomicTx` method. - * - * @param txID The string representation of the transaction ID - * - * @returns Returns a Promise string containing the bytes retrieved from the node - */ - getAtomicTx = async (txID: string): Promise => { - const params: GetAtomicTxParams = { - txID - } - - const response: RequestResponseData = await this.callMethod( - "avax.getAtomicTx", - params - ) - return response.data.result.tx - } - - /** - * Gets the tx fee for this chain. - * - * @returns The tx fee as a {@link https://github.com/indutny/bn.js/|BN} - */ - getTxFee = (): BN => { - if (typeof this.txFee === "undefined") { - this.txFee = this.getDefaultTxFee() - } - return this.txFee - } - - /** - * Send ANT (Avalanche Native Token) assets including AVAX from the C-Chain to an account on the X-Chain. - * - * After calling this method, you must call the X-Chain’s import method to complete the transfer. - * - * @param username The Keystore user that controls the X-Chain account specified in `to` - * @param password The password of the Keystore user - * @param to The account on the X-Chain to send the AVAX to. - * @param amount Amount of asset to export as a {@link https://github.com/indutny/bn.js/|BN} - * @param assetID The asset id which is being sent - * - * @returns String representing the transaction id - */ - export = async ( - username: string, - password: string, - to: string, - amount: BN, - assetID: string - ): Promise => { - const params: ExportParams = { - to, - amount: amount.toString(10), - username, - password, - assetID - } - const response: RequestResponseData = await this.callMethod( - "avax.export", - params - ) - return response.data.result.txID - ? response.data.result.txID - : response.data.result - } - - /** - * Send AVAX from the C-Chain to an account on the X-Chain. - * - * After calling this method, you must call the X-Chain’s importAVAX method to complete the transfer. - * - * @param username The Keystore user that controls the X-Chain account specified in `to` - * @param password The password of the Keystore user - * @param to The account on the X-Chain to send the AVAX to. - * @param amount Amount of AVAX to export as a {@link https://github.com/indutny/bn.js/|BN} - * - * @returns String representing the transaction id - */ - exportAVAX = async ( - username: string, - password: string, - to: string, - amount: BN - ): Promise => { - const params: ExportAVAXParams = { - to, - amount: amount.toString(10), - username, - password - } - const response: RequestResponseData = await this.callMethod( - "avax.exportAVAX", - params - ) - return response.data.result.txID - ? response.data.result.txID - : response.data.result - } - - /** - * Retrieves the UTXOs related to the addresses provided from the node's `getUTXOs` method. - * - * @param addresses An array of addresses as cb58 strings or addresses as {@link https://github.com/feross/buffer|Buffer}s - * @param sourceChain A string for the chain to look for the UTXO's. Default is to use this chain, but if exported UTXOs exist - * from other chains, this can used to pull them instead. - * @param limit Optional. Returns at most [limit] addresses. If [limit] == 0 or > [maxUTXOsToFetch], fetches up to [maxUTXOsToFetch]. - * @param startIndex Optional. [StartIndex] defines where to start fetching UTXOs (for pagination.) - * UTXOs fetched are from addresses equal to or greater than [StartIndex.Address] - * For address [StartIndex.Address], only UTXOs with IDs greater than [StartIndex.Utxo] will be returned. - */ - getUTXOs = async ( - addresses: string[] | string, - sourceChain: string = undefined, - limit: number = 0, - startIndex: Index = undefined, - encoding: string = "hex" - ): Promise<{ - numFetched: number - utxos - endIndex: Index - }> => { - if (typeof addresses === "string") { - addresses = [addresses] - } - - const params: GetUTXOsParams = { - addresses: addresses, - limit, - encoding - } - if (typeof startIndex !== "undefined" && startIndex) { - params.startIndex = startIndex - } - - if (typeof sourceChain !== "undefined") { - params.sourceChain = sourceChain - } - - const response: RequestResponseData = await this.callMethod( - "avax.getUTXOs", - params - ) - const utxos: UTXOSet = new UTXOSet() - const data: any = response.data.result.utxos - if (data.length > 0 && data[0].substring(0, 2) === "0x") { - const cb58Strs: string[] = [] - data.forEach((str: string): void => { - cb58Strs.push(bintools.cb58Encode(new Buffer(str.slice(2), "hex"))) - }) - - utxos.addArray(cb58Strs, false) - } else { - utxos.addArray(data, false) - } - response.data.result.utxos = utxos - return response.data.result - } - - /** - * Send ANT (Avalanche Native Token) assets including AVAX from an account on the X-Chain to an address on the C-Chain. This transaction - * must be signed with the key of the account that the asset is sent from and which pays - * the transaction fee. - * - * @param username The Keystore user that controls the account specified in `to` - * @param password The password of the Keystore user - * @param to The address of the account the asset is sent to. - * @param sourceChain The chainID where the funds are coming from. Ex: "X" - * - * @returns Promise for a string for the transaction, which should be sent to the network - * by calling issueTx. - */ - import = async ( - username: string, - password: string, - to: string, - sourceChain: string - ): Promise => { - const params: ImportParams = { - to, - sourceChain, - username, - password - } - const response: RequestResponseData = await this.callMethod( - "avax.import", - params - ) - return response.data.result.txID - ? response.data.result.txID - : response.data.result - } - - /** - * Send AVAX from an account on the X-Chain to an address on the C-Chain. This transaction - * must be signed with the key of the account that the AVAX is sent from and which pays - * the transaction fee. - * - * @param username The Keystore user that controls the account specified in `to` - * @param password The password of the Keystore user - * @param to The address of the account the AVAX is sent to. This must be the same as the to - * argument in the corresponding call to the X-Chain’s exportAVAX - * @param sourceChain The chainID where the funds are coming from. - * - * @returns Promise for a string for the transaction, which should be sent to the network - * by calling issueTx. - */ - importAVAX = async ( - username: string, - password: string, - to: string, - sourceChain: string - ): Promise => { - const params: ImportAVAXParams = { - to, - sourceChain, - username, - password - } - const response: RequestResponseData = await this.callMethod( - "avax.importAVAX", - params - ) - return response.data.result.txID - ? response.data.result.txID - : response.data.result - } - - /** - * Give a user control over an address by providing the private key that controls the address. - * - * @param username The name of the user to store the private key - * @param password The password that unlocks the user - * @param privateKey A string representing the private key in the vm"s format - * - * @returns The address for the imported private key. - */ - importKey = async ( - username: string, - password: string, - privateKey: string - ): Promise => { - const params: ImportKeyParams = { - username, - password, - privateKey - } - const response: RequestResponseData = await this.callMethod( - "avax.importKey", - params - ) - return response.data.result.address - ? response.data.result.address - : response.data.result - } - - /** - * Calls the node's issueTx method from the API and returns the resulting transaction ID as a string. - * - * @param tx A string, {@link https://github.com/feross/buffer|Buffer}, or [[Tx]] representing a transaction - * - * @returns A Promise string representing the transaction ID of the posted transaction. - */ - issueTx = async (tx: string | Buffer | Tx): Promise => { - let Transaction: string = "" - if (typeof tx === "string") { - Transaction = tx - } else if (tx instanceof Buffer) { - const txobj: Tx = new Tx() - txobj.fromBuffer(tx) - Transaction = txobj.toStringHex() - } else if (tx instanceof Tx) { - Transaction = tx.toStringHex() - } else { - /* istanbul ignore next */ - throw new TransactionError( - "Error - avax.issueTx: provided tx is not expected type of string, Buffer, or Tx" - ) - } - const params: IssueTxParams = { - tx: Transaction.toString(), - encoding: "hex" - } - const response: RequestResponseData = await this.callMethod( - "avax.issueTx", - params - ) - return response.data.result.txID - ? response.data.result.txID - : response.data.result - } - - /** - * Exports the private key for an address. - * - * @param username The name of the user with the private key - * @param password The password used to decrypt the private key - * @param address The address whose private key should be exported - * - * @returns Promise with the decrypted private key and private key hex as store in the database - */ - exportKey = async ( - username: string, - password: string, - address: string - ): Promise => { - const params: ExportKeyParams = { - username, - password, - address - } - const response: RequestResponseData = await this.callMethod( - "avax.exportKey", - params - ) - return response.data.result - } - - /** - * Helper function which creates an unsigned Import Tx. For more granular control, you may create your own - * [[UnsignedTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s). - * - * @param utxoset A set of UTXOs that the transaction is built on - * @param toAddress The address to send the funds - * @param ownerAddresses The addresses being used to import - * @param sourceChain The chainid for where the import is coming from - * @param fromAddresses The addresses being used to send the funds from the UTXOs provided - * - * @returns An unsigned transaction ([[UnsignedTx]]) which contains a [[ImportTx]]. - * - * @remarks - * This helper exists because the endpoint API should be the primary point of entry for most functionality. - */ - buildImportTx = async ( - utxoset: UTXOSet, - toAddress: string, - ownerAddresses: string[], - sourceChain: Buffer | string, - fromAddresses: string[], - fee: BN = new BN(0) - ): Promise => { - const from: Buffer[] = this._cleanAddressArray( - fromAddresses, - "buildImportTx" - ).map((a: string): Buffer => bintools.stringToAddress(a)) - let srcChain: string = undefined - - if (typeof sourceChain === "string") { - // if there is a sourceChain passed in and it's a string then save the string value and cast the original - // variable from a string to a Buffer - srcChain = sourceChain - sourceChain = bintools.cb58Decode(sourceChain) - } else if ( - typeof sourceChain === "undefined" || - !(sourceChain instanceof Buffer) - ) { - // if there is no sourceChain passed in or the sourceChain is any data type other than a Buffer then throw an error - throw new ChainIdError( - "Error - EVMAPI.buildImportTx: sourceChain is undefined or invalid sourceChain type." - ) - } - const utxoResponse: UTXOResponse = await this.getUTXOs( - ownerAddresses, - srcChain, - 0, - undefined - ) - const atomicUTXOs: UTXOSet = utxoResponse.utxos - const networkID: number = this.core.getNetworkID() - const avaxAssetID: string = Defaults.network[`${networkID}`].X.avaxAssetID - const avaxAssetIDBuf: Buffer = bintools.cb58Decode(avaxAssetID) - const atomics: UTXO[] = atomicUTXOs.getAllUTXOs() - - if (atomics.length === 0) { - throw new NoAtomicUTXOsError( - "Error - EVMAPI.buildImportTx: no atomic utxos to import" - ) - } - - const builtUnsignedTx: UnsignedTx = utxoset.buildImportTx( - networkID, - bintools.cb58Decode(this.blockchainID), - toAddress, - atomics, - sourceChain, - fee, - avaxAssetIDBuf - ) - - return builtUnsignedTx - } - - /** - * Helper function which creates an unsigned Export Tx. For more granular control, you may create your own - * [[UnsignedTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s). - * - * @param amount The amount being exported as a {@link https://github.com/indutny/bn.js/|BN} - * @param assetID The asset id which is being sent - * @param destinationChain The chainid for where the assets will be sent. - * @param toAddresses The addresses to send the funds - * @param fromAddresses The addresses being used to send the funds from the UTXOs provided - * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param locktime Optional. The locktime field created in the resulting outputs - * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO - * - * @returns An unsigned transaction ([[UnsignedTx]]) which contains an [[ExportTx]]. - */ - buildExportTx = async ( - amount: BN, - assetID: Buffer | string, - destinationChain: Buffer | string, - fromAddressHex: string, - fromAddressBech: string, - toAddresses: string[], - nonce: number = 0, - locktime: BN = new BN(0), - threshold: number = 1, - fee: BN = new BN(0) - ): Promise => { - const prefixes: object = {} - toAddresses.map((address: string) => { - prefixes[address.split("-")[0]] = true - }) - if (Object.keys(prefixes).length !== 1) { - throw new AddressError( - "Error - EVMAPI.buildExportTx: To addresses must have the same chainID prefix." - ) - } - - if (typeof destinationChain === "undefined") { - throw new ChainIdError( - "Error - EVMAPI.buildExportTx: Destination ChainID is undefined." - ) - } else if (typeof destinationChain === "string") { - destinationChain = bintools.cb58Decode(destinationChain) - } else if (!(destinationChain instanceof Buffer)) { - throw new ChainIdError( - "Error - EVMAPI.buildExportTx: Invalid destinationChain type" - ) - } - if (destinationChain.length !== 32) { - throw new ChainIdError( - "Error - EVMAPI.buildExportTx: Destination ChainID must be 32 bytes in length." - ) - } - const assetDescription: any = await this.getAssetDescription("AVAX") - let evmInputs: EVMInput[] = [] - if (bintools.cb58Encode(assetDescription.assetID) === assetID) { - const evmInput: EVMInput = new EVMInput( - fromAddressHex, - amount.add(fee), - assetID, - nonce - ) - evmInput.addSignatureIdx(0, bintools.stringToAddress(fromAddressBech)) - evmInputs.push(evmInput) - } else { - // if asset id isn't AVAX asset id then create 2 inputs - // first input will be AVAX and will be for the amount of the fee - // second input will be the ANT - const evmAVAXInput: EVMInput = new EVMInput( - fromAddressHex, - fee, - assetDescription.assetID, - nonce - ) - evmAVAXInput.addSignatureIdx(0, bintools.stringToAddress(fromAddressBech)) - evmInputs.push(evmAVAXInput) - - const evmANTInput: EVMInput = new EVMInput( - fromAddressHex, - amount, - assetID, - nonce - ) - evmANTInput.addSignatureIdx(0, bintools.stringToAddress(fromAddressBech)) - evmInputs.push(evmANTInput) - } - - const to: Buffer[] = [] - toAddresses.map((address: string): void => { - to.push(bintools.stringToAddress(address)) - }) - - let exportedOuts: TransferableOutput[] = [] - const secpTransferOutput: SECPTransferOutput = new SECPTransferOutput( - amount, - to, - locktime, - threshold - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - bintools.cb58Decode(assetID), - secpTransferOutput - ) - exportedOuts.push(transferableOutput) - - // lexicographically sort ins and outs - evmInputs = evmInputs.sort(EVMInput.comparator()) - exportedOuts = exportedOuts.sort(TransferableOutput.comparator()) - - const exportTx: ExportTx = new ExportTx( - this.core.getNetworkID(), - bintools.cb58Decode(this.blockchainID), - destinationChain, - evmInputs, - exportedOuts - ) - - const unsignedTx: UnsignedTx = new UnsignedTx(exportTx) - return unsignedTx - } - - /** - * Gets a reference to the keychain for this class. - * - * @returns The instance of [[KeyChain]] for this class - */ - keyChain = (): KeyChain => this.keychain - - /** - * - * @returns new instance of [[KeyChain]] - */ - newKeyChain = (): KeyChain => { - // warning, overwrites the old keychain - const alias = this.getBlockchainAlias() - if (alias) { - this.keychain = new KeyChain(this.core.getHRP(), alias) - } else { - this.keychain = new KeyChain(this.core.getHRP(), this.blockchainID) - } - return this.keychain - } - - /** - * @ignore - */ - protected _cleanAddressArray( - addresses: string[] | Buffer[], - caller: string - ): string[] { - const addrs: string[] = [] - const chainid: string = this.getBlockchainAlias() - ? this.getBlockchainAlias() - : this.getBlockchainID() - if (addresses && addresses.length > 0) { - addresses.forEach((address: string | Buffer) => { - if (typeof address === "string") { - if (typeof this.parseAddress(address as string) === "undefined") { - /* istanbul ignore next */ - throw new AddressError("Error - Invalid address format") - } - addrs.push(address as string) - } else { - const type: SerializedType = "bech32" - addrs.push( - serialization.bufferToType( - address as Buffer, - type, - this.core.getHRP(), - chainid - ) - ) - } - }) - } - return addrs - } - - /** - * This class should not be instantiated directly. - * Instead use the [[Avalanche.addAPI]] method. - * - * @param core A reference to the Avalanche class - * @param baseURL Defaults to the string "/ext/bc/C/avax" as the path to blockchain's baseURL - * @param blockchainID The Blockchain's ID. Defaults to an empty string: "" - */ - constructor( - core: AvalancheCore, - baseURL: string = "/ext/bc/C/avax", - blockchainID: string = "" - ) { - super(core, baseURL) - this.blockchainID = blockchainID - const netID: number = core.getNetworkID() - if ( - netID in Defaults.network && - blockchainID in Defaults.network[`${netID}`] - ) { - const alias: string = - Defaults.network[`${netID}`][`${blockchainID}`]["alias"] - this.keychain = new KeyChain(this.core.getHRP(), alias) - } else { - this.keychain = new KeyChain(this.core.getHRP(), blockchainID) - } - } - - /** - * @returns a Promise string containing the base fee for the next block. - */ - getBaseFee = async (): Promise => { - const params: string[] = [] - const method: string = "eth_baseFee" - const path: string = "ext/bc/C/rpc" - const response: RequestResponseData = await this.callMethod( - method, - params, - path - ) - return response.data.result - } - - /** - * returns the priority fee needed to be included in a block. - * - * @returns Returns a Promise string containing the priority fee needed to be included in a block. - */ - getMaxPriorityFeePerGas = async (): Promise => { - const params: string[] = [] - - const method: string = "eth_maxPriorityFeePerGas" - const path: string = "ext/bc/C/rpc" - const response: RequestResponseData = await this.callMethod( - method, - params, - path - ) - return response.data.result - } -} diff --git a/src/apis/evm/basetx.ts b/src/apis/evm/basetx.ts deleted file mode 100644 index 11e663889..000000000 --- a/src/apis/evm/basetx.ts +++ /dev/null @@ -1,97 +0,0 @@ -/** - * @packageDocumentation - * @module API-EVM-BaseTx - */ - -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { KeyChain, KeyPair } from "./keychain" -import { EVMStandardBaseTx } from "../../common/evmtx" -import { Credential } from "../../common/credentials" -import { DefaultNetworkID } from "../../utils/constants" -import { SelectTxClass } from "./tx" -import { SerializedEncoding } from "../../utils/serialization" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() - -/** - * Class representing a base for all transactions. - */ -export class EVMBaseTx extends EVMStandardBaseTx { - protected _typeName = "BaseTx" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - } - - /** - * Returns the id of the [[BaseTx]] - */ - getTxType(): number { - return this._typeID - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[BaseTx]], parses it, populates the class, and returns the length of the BaseTx in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[BaseTx]] - * - * @returns The length of the raw [[BaseTx]] - * - * @remarks assume not-checksummed - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.networkID = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - this.blockchainID = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - return offset - } - - /** - * Takes the bytes of an [[UnsignedTx]] and returns an array of [[Credential]]s - * - * @param msg A Buffer for the [[UnsignedTx]] - * @param kc An [[KeyChain]] used in signing - * - * @returns An array of [[Credential]]s - */ - sign(msg: Buffer, kc: KeyChain): Credential[] { - const creds: Credential[] = [] - return creds - } - - clone(): this { - const newEVMBaseTx: EVMBaseTx = new EVMBaseTx() - newEVMBaseTx.fromBuffer(this.toBuffer()) - return newEVMBaseTx as this - } - - create(...args: any[]): this { - return new EVMBaseTx(...args) as this - } - - select(id: number, ...args: any[]): this { - const newEVMBaseTx: EVMBaseTx = SelectTxClass(id, ...args) - return newEVMBaseTx as this - } - - /** - * Class representing an EVMBaseTx which is the foundation for all EVM transactions. - * - * @param networkID Optional networkID, [[DefaultNetworkID]] - * @param blockchainID Optional blockchainID, default Buffer.alloc(32, 16) - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: Buffer = Buffer.alloc(32, 16) - ) { - super(networkID, blockchainID) - } -} diff --git a/src/apis/evm/constants.ts b/src/apis/evm/constants.ts deleted file mode 100644 index ae85d27a0..000000000 --- a/src/apis/evm/constants.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** - * @packageDocumentation - * @module API-EVM-Constants - */ - -import BN from "bn.js" - -export class EVMConstants { - static SECPCREDENTIAL: number = 9 - - static IMPORTTX: number = 0 - - static EXPORTTX: number = 1 - - static SECPINPUTID: number = 5 - - static ASSETIDLEN: number = 32 - - static SECPXFEROUTPUTID: number = 7 - - static LATESTCODEC: number = 0 - - static ADDRESSLENGTH: number = 20 -} diff --git a/src/apis/evm/credentials.ts b/src/apis/evm/credentials.ts deleted file mode 100644 index e4b0c6bf0..000000000 --- a/src/apis/evm/credentials.ts +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @packageDocumentation - * @module API-EVM-Credentials - */ - -import { EVMConstants } from "./constants" -import { Credential } from "../../common/credentials" -import { CredIdError } from "../../utils/errors" - -/** - * Takes a buffer representing the credential and returns the proper [[Credential]] instance. - * - * @param credid A number representing the credential ID parsed prior to the bytes passed in - * - * @returns An instance of an [[Credential]]-extended class. - */ -export const SelectCredentialClass = ( - credid: number, - ...args: any[] -): Credential => { - if (credid === EVMConstants.SECPCREDENTIAL) { - return new SECPCredential(...args) - } - /* istanbul ignore next */ - throw new CredIdError("Error - SelectCredentialClass: unknown credid") -} - -export class SECPCredential extends Credential { - protected _typeName: string = "SECPCredential" - protected _typeID: number = EVMConstants.SECPCREDENTIAL - - //serialize and deserialize both are inherited - - getCredentialID(): number { - return this._typeID - } - - clone(): this { - let newbase: SECPCredential = new SECPCredential() - newbase.fromBuffer(this.toBuffer()) - return newbase as this - } - - create(...args: any[]): this { - return new SECPCredential(...args) as this - } - - select(id: number, ...args: any[]): Credential { - let credential: Credential = SelectCredentialClass(id, ...args) - return credential - } -} diff --git a/src/apis/evm/exporttx.ts b/src/apis/evm/exporttx.ts deleted file mode 100644 index 1419a6088..000000000 --- a/src/apis/evm/exporttx.ts +++ /dev/null @@ -1,226 +0,0 @@ -/** - * @packageDocumentation - * @module API-EVM-ExportTx - */ - -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { EVMConstants } from "./constants" -import { KeyChain, KeyPair } from "./keychain" -import { EVMBaseTx } from "./basetx" -import { SelectCredentialClass } from "./credentials" -import { Signature, SigIdx, Credential } from "../../common/credentials" -import { EVMInput } from "./inputs" -import { Serialization, SerializedEncoding } from "../../utils/serialization" -import { TransferableOutput } from "./outputs" -import { - ChainIdError, - EVMInputError, - TransferableOutputError -} from "../../utils/errors" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serializer: Serialization = Serialization.getInstance() - -export class ExportTx extends EVMBaseTx { - protected _typeName = "ExportTx" - protected _typeID = EVMConstants.EXPORTTX - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - destinationChain: serializer.encoder( - this.destinationChain, - encoding, - "Buffer", - "cb58" - ), - exportedOutputs: this.exportedOutputs.map((i) => i.serialize(encoding)) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.destinationChain = serializer.decoder( - fields["destinationChain"], - encoding, - "cb58", - "Buffer", - 32 - ) - this.exportedOutputs = fields["exportedOutputs"].map((i: object) => { - let eo: TransferableOutput = new TransferableOutput() - eo.deserialize(i, encoding) - return eo - }) - this.numExportedOutputs = Buffer.alloc(4) - this.numExportedOutputs.writeUInt32BE(this.exportedOutputs.length, 0) - } - - protected destinationChain: Buffer = Buffer.alloc(32) - protected numInputs: Buffer = Buffer.alloc(4) - protected inputs: EVMInput[] = [] - protected numExportedOutputs: Buffer = Buffer.alloc(4) - protected exportedOutputs: TransferableOutput[] = [] - - /** - * Returns the destinationChain as a {@link https://github.com/feross/buffer|Buffer} - */ - getDestinationChain(): Buffer { - return this.destinationChain - } - - /** - * Returns the inputs as an array of [[EVMInputs]] - */ - getInputs(): EVMInput[] { - return this.inputs - } - - /** - * Returns the outs as an array of [[EVMOutputs]] - */ - getExportedOutputs(): TransferableOutput[] { - return this.exportedOutputs - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[ExportTx]]. - */ - toBuffer(): Buffer { - if (typeof this.destinationChain === "undefined") { - throw new ChainIdError( - "ExportTx.toBuffer -- this.destinationChain is undefined" - ) - } - this.numInputs.writeUInt32BE(this.inputs.length, 0) - this.numExportedOutputs.writeUInt32BE(this.exportedOutputs.length, 0) - let barr: Buffer[] = [ - super.toBuffer(), - this.destinationChain, - this.numInputs - ] - let bsize: number = - super.toBuffer().length + - this.destinationChain.length + - this.numInputs.length - this.inputs.forEach((importIn: EVMInput) => { - bsize += importIn.toBuffer().length - barr.push(importIn.toBuffer()) - }) - bsize += this.numExportedOutputs.length - barr.push(this.numExportedOutputs) - this.exportedOutputs.forEach((out: TransferableOutput) => { - bsize += out.toBuffer().length - barr.push(out.toBuffer()) - }) - return Buffer.concat(barr, bsize) - } - - /** - * Decodes the [[ExportTx]] as a {@link https://github.com/feross/buffer|Buffer} and returns the size. - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - this.destinationChain = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - this.numInputs = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const numInputs: number = this.numInputs.readUInt32BE(0) - for (let i: number = 0; i < numInputs; i++) { - const anIn: EVMInput = new EVMInput() - offset = anIn.fromBuffer(bytes, offset) - this.inputs.push(anIn) - } - this.numExportedOutputs = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const numExportedOutputs: number = this.numExportedOutputs.readUInt32BE(0) - for (let i: number = 0; i < numExportedOutputs; i++) { - const anOut: TransferableOutput = new TransferableOutput() - offset = anOut.fromBuffer(bytes, offset) - this.exportedOutputs.push(anOut) - } - return offset - } - - /** - * Returns a base-58 representation of the [[ExportTx]]. - */ - toString(): string { - return bintools.bufferToB58(this.toBuffer()) - } - - /** - * Takes the bytes of an [[UnsignedTx]] and returns an array of [[Credential]]s - * - * @param msg A Buffer for the [[UnsignedTx]] - * @param kc An [[KeyChain]] used in signing - * - * @returns An array of [[Credential]]s - */ - sign(msg: Buffer, kc: KeyChain): Credential[] { - const creds: Credential[] = super.sign(msg, kc) - this.inputs.forEach((input: EVMInput) => { - const cred: Credential = SelectCredentialClass(input.getCredentialID()) - const sigidxs: SigIdx[] = input.getSigIdxs() - sigidxs.forEach((sigidx: SigIdx) => { - const keypair: KeyPair = kc.getKey(sigidx.getSource()) - const signval: Buffer = keypair.sign(msg) - const sig: Signature = new Signature() - sig.fromBuffer(signval) - cred.addSignature(sig) - }) - creds.push(cred) - }) - return creds - } - - /** - * Class representing a ExportTx. - * - * @param networkID Optional networkID - * @param blockchainID Optional blockchainID, default Buffer.alloc(32, 16) - * @param destinationChain Optional destinationChain, default Buffer.alloc(32, 16) - * @param inputs Optional array of the [[EVMInputs]]s - * @param exportedOutputs Optional array of the [[EVMOutputs]]s - */ - constructor( - networkID: number = undefined, - blockchainID: Buffer = Buffer.alloc(32, 16), - destinationChain: Buffer = Buffer.alloc(32, 16), - inputs: EVMInput[] = undefined, - exportedOutputs: TransferableOutput[] = undefined - ) { - super(networkID, blockchainID) - this.destinationChain = destinationChain - if (typeof inputs !== "undefined" && Array.isArray(inputs)) { - inputs.forEach((input: EVMInput) => { - if (!(input instanceof EVMInput)) { - throw new EVMInputError( - "Error - ExportTx.constructor: invalid EVMInput in array parameter 'inputs'" - ) - } - }) - if (inputs.length > 1) { - inputs = inputs.sort(EVMInput.comparator()) - } - this.inputs = inputs - } - if ( - typeof exportedOutputs !== "undefined" && - Array.isArray(exportedOutputs) - ) { - exportedOutputs.forEach((exportedOutput: TransferableOutput) => { - if (!(exportedOutput instanceof TransferableOutput)) { - throw new TransferableOutputError( - "Error - ExportTx.constructor: TransferableOutput EVMInput in array parameter 'exportedOutputs'" - ) - } - }) - this.exportedOutputs = exportedOutputs - } - } -} diff --git a/src/apis/evm/importtx.ts b/src/apis/evm/importtx.ts deleted file mode 100644 index 0ca6b7560..000000000 --- a/src/apis/evm/importtx.ts +++ /dev/null @@ -1,317 +0,0 @@ -/** - * @packageDocumentation - * @module API-EVM-ImportTx - */ - -import { Buffer } from "buffer/" -import BN from "bn.js" -import BinTools from "../../utils/bintools" -import { EVMConstants } from "./constants" -import { EVMOutput } from "./outputs" -import { TransferableInput } from "./inputs" -import { EVMBaseTx } from "./basetx" -import { SelectCredentialClass } from "./credentials" -import { Signature, SigIdx, Credential } from "../../common/credentials" -import { StandardAmountInput } from "../../common/input" -import { KeyChain, KeyPair } from "./keychain" -import { DefaultNetworkID, Defaults } from "../../utils/constants" -import { Serialization, SerializedEncoding } from "../../utils/serialization" -import { - ChainIdError, - TransferableInputError, - EVMOutputError, - EVMFeeError -} from "../../utils/errors" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serializer: Serialization = Serialization.getInstance() - -/** - * Class representing an unsigned Import transaction. - */ -export class ImportTx extends EVMBaseTx { - protected _typeName = "ImportTx" - protected _typeID = EVMConstants.IMPORTTX - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - sourceChain: serializer.encoder( - this.sourceChain, - encoding, - "Buffer", - "cb58" - ), - importIns: this.importIns.map((i) => i.serialize(encoding)) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.sourceChain = serializer.decoder( - fields["sourceChain"], - encoding, - "cb58", - "Buffer", - 32 - ) - this.importIns = fields["importIns"].map((i: object) => { - let ii: TransferableInput = new TransferableInput() - ii.deserialize(i, encoding) - return ii - }) - this.numIns = Buffer.alloc(4) - this.numIns.writeUInt32BE(this.importIns.length, 0) - } - - protected sourceChain: Buffer = Buffer.alloc(32) - protected numIns: Buffer = Buffer.alloc(4) - protected importIns: TransferableInput[] = [] - protected numOuts: Buffer = Buffer.alloc(4) - protected outs: EVMOutput[] = [] - - /** - * Returns the id of the [[ImportTx]] - */ - getTxType(): number { - return this._typeID - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} for the source chainid. - */ - getSourceChain(): Buffer { - return this.sourceChain - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[ImportTx]], parses it, - * populates the class, and returns the length of the [[ImportTx]] in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[ImportTx]] - * @param offset A number representing the byte offset. Defaults to 0. - * - * @returns The length of the raw [[ImportTx]] - * - * @remarks assume not-checksummed - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - this.sourceChain = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - this.numIns = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const numIns: number = this.numIns.readUInt32BE(0) - for (let i: number = 0; i < numIns; i++) { - const anIn: TransferableInput = new TransferableInput() - offset = anIn.fromBuffer(bytes, offset) - this.importIns.push(anIn) - } - this.numOuts = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const numOuts: number = this.numOuts.readUInt32BE(0) - for (let i: number = 0; i < numOuts; i++) { - const anOut: EVMOutput = new EVMOutput() - offset = anOut.fromBuffer(bytes, offset) - this.outs.push(anOut) - } - return offset - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[ImportTx]]. - */ - toBuffer(): Buffer { - if (typeof this.sourceChain === "undefined") { - throw new ChainIdError( - "ImportTx.toBuffer -- this.sourceChain is undefined" - ) - } - this.numIns.writeUInt32BE(this.importIns.length, 0) - this.numOuts.writeUInt32BE(this.outs.length, 0) - let barr: Buffer[] = [super.toBuffer(), this.sourceChain, this.numIns] - let bsize: number = - super.toBuffer().length + this.sourceChain.length + this.numIns.length - this.importIns = this.importIns.sort(TransferableInput.comparator()) - this.importIns.forEach((importIn: TransferableInput) => { - bsize += importIn.toBuffer().length - barr.push(importIn.toBuffer()) - }) - bsize += this.numOuts.length - barr.push(this.numOuts) - this.outs.forEach((out: EVMOutput) => { - bsize += out.toBuffer().length - barr.push(out.toBuffer()) - }) - return Buffer.concat(barr, bsize) - } - - /** - * Returns an array of [[TransferableInput]]s in this transaction. - */ - getImportInputs(): TransferableInput[] { - return this.importIns - } - - /** - * Returns an array of [[EVMOutput]]s in this transaction. - */ - getOuts(): EVMOutput[] { - return this.outs - } - - clone(): this { - let newImportTx: ImportTx = new ImportTx() - newImportTx.fromBuffer(this.toBuffer()) - return newImportTx as this - } - - create(...args: any[]): this { - return new ImportTx(...args) as this - } - - /** - * Takes the bytes of an [[UnsignedTx]] and returns an array of [[Credential]]s - * - * @param msg A Buffer for the [[UnsignedTx]] - * @param kc An [[KeyChain]] used in signing - * - * @returns An array of [[Credential]]s - */ - sign(msg: Buffer, kc: KeyChain): Credential[] { - const creds: Credential[] = super.sign(msg, kc) - this.importIns.forEach((importIn: TransferableInput) => { - const cred: Credential = SelectCredentialClass( - importIn.getInput().getCredentialID() - ) - const sigidxs: SigIdx[] = importIn.getInput().getSigIdxs() - sigidxs.forEach((sigidx: SigIdx) => { - const keypair: KeyPair = kc.getKey(sigidx.getSource()) - const signval: Buffer = keypair.sign(msg) - const sig: Signature = new Signature() - sig.fromBuffer(signval) - cred.addSignature(sig) - }) - creds.push(cred) - }) - return creds - } - - /** - * Class representing an unsigned Import transaction. - * - * @param networkID Optional networkID, [[DefaultNetworkID]] - * @param blockchainID Optional blockchainID, default Buffer.alloc(32, 16) - * @param sourceChainID Optional chainID for the source inputs to import. Default Buffer.alloc(32, 16) - * @param importIns Optional array of [[TransferableInput]]s used in the transaction - * @param outs Optional array of the [[EVMOutput]]s - * @param fee Optional the fee as a BN - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: Buffer = Buffer.alloc(32, 16), - sourceChainID: Buffer = Buffer.alloc(32, 16), - importIns: TransferableInput[] = undefined, - outs: EVMOutput[] = undefined, - fee: BN = new BN(0) - ) { - super(networkID, blockchainID) - this.sourceChain = sourceChainID - let inputsPassed: boolean = false - let outputsPassed: boolean = false - if ( - typeof importIns !== "undefined" && - Array.isArray(importIns) && - importIns.length > 0 - ) { - importIns.forEach((importIn: TransferableInput) => { - if (!(importIn instanceof TransferableInput)) { - throw new TransferableInputError( - "Error - ImportTx.constructor: invalid TransferableInput in array parameter 'importIns'" - ) - } - }) - inputsPassed = true - this.importIns = importIns - } - if (typeof outs !== "undefined" && Array.isArray(outs) && outs.length > 0) { - outs.forEach((out: EVMOutput) => { - if (!(out instanceof EVMOutput)) { - throw new EVMOutputError( - "Error - ImportTx.constructor: invalid EVMOutput in array parameter 'outs'" - ) - } - }) - if (outs.length > 1) { - outs = outs.sort(EVMOutput.comparator()) - } - outputsPassed = true - this.outs = outs - } - if (inputsPassed && outputsPassed) { - this.validateOuts(fee) - } - } - - private validateOuts(fee: BN): void { - // This Map enforces uniqueness of pair(address, assetId) for each EVMOutput. - // For each imported assetID, each ETH-style C-Chain address can - // have exactly 1 EVMOutput. - // Map(2) { - // '0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC' => [ - // 'FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z', - // 'F4MyJcUvq3Rxbqgd4Zs8sUpvwLHApyrp4yxJXe2bAV86Vvp38' - // ], - // '0xecC3B2968B277b837a81A7181e0b94EB1Ca54EdE' => [ - // 'FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z', - // '2Df96yHyhNc3vooieNNhyKwrjEfTsV2ReMo5FKjMpr8vwN4Jqy', - // 'SfSXBzDb9GZ9R2uH61qZKe8nxQHW9KERW9Kq9WRe4vHJZRN3e' - // ] - // } - const seenAssetSends: Map = new Map() - this.outs.forEach((evmOutput: EVMOutput): void => { - const address: string = evmOutput.getAddressString() - const assetId: string = bintools.cb58Encode(evmOutput.getAssetID()) - if (seenAssetSends.has(address)) { - const assetsSentToAddress: string[] = seenAssetSends.get(address) - if (assetsSentToAddress.includes(assetId)) { - const errorMessage: string = `Error - ImportTx: duplicate (address, assetId) pair found in outputs: (0x${address}, ${assetId})` - throw new EVMOutputError(errorMessage) - } - assetsSentToAddress.push(assetId) - } else { - seenAssetSends.set(address, [assetId]) - } - }) - // make sure this transaction pays the required avax fee - const selectedNetwork: number = this.getNetworkID() - const feeDiff: BN = new BN(0) - const avaxAssetID: string = - Defaults.network[`${selectedNetwork}`].X.avaxAssetID - // sum incoming AVAX - this.importIns.forEach((input: TransferableInput): void => { - // only check StandardAmountInputs - if ( - input.getInput() instanceof StandardAmountInput && - avaxAssetID === bintools.cb58Encode(input.getAssetID()) - ) { - const ui = input.getInput() as unknown - const i = ui as StandardAmountInput - feeDiff.iadd(i.getAmount()) - } - }) - // subtract all outgoing AVAX - this.outs.forEach((evmOutput: EVMOutput): void => { - if (avaxAssetID === bintools.cb58Encode(evmOutput.getAssetID())) { - feeDiff.isub(evmOutput.getAmount()) - } - }) - if (feeDiff.lt(fee)) { - const errorMessage: string = `Error - ${fee} nAVAX required for fee and only ${feeDiff} nAVAX provided` - throw new EVMFeeError(errorMessage) - } - } -} diff --git a/src/apis/evm/index.ts b/src/apis/evm/index.ts deleted file mode 100644 index c84a779b1..000000000 --- a/src/apis/evm/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -export * from "./api" -export * from "./basetx" -export * from "./constants" -export * from "./credentials" -export * from "./inputs" -export * from "./interfaces" -export * from "./exporttx" -export * from "./importtx" -export * from "./keychain" -export * from "./outputs" -export * from "./tx" -export * from "./utxos" diff --git a/src/apis/evm/inputs.ts b/src/apis/evm/inputs.ts deleted file mode 100644 index e14043d49..000000000 --- a/src/apis/evm/inputs.ts +++ /dev/null @@ -1,229 +0,0 @@ -/** - * @packageDocumentation - * @module API-EVM-Inputs - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { EVMConstants } from "./constants" -import { - Input, - StandardTransferableInput, - StandardAmountInput -} from "../../common/input" -import { SerializedEncoding } from "../../utils/serialization" -import { EVMOutput } from "./outputs" -import BN from "bn.js" -import { SigIdx } from "../../common/credentials" -import { InputIdError } from "../../utils/errors" -import { Defaults } from "../../utils" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() - -/** - * Takes a buffer representing the output and returns the proper [[Input]] instance. - * - * @param inputID A number representing the inputID parsed prior to the bytes passed in - * - * @returns An instance of an [[Input]]-extended class. - */ -export const SelectInputClass = (inputID: number, ...args: any[]): Input => { - if (inputID === EVMConstants.SECPINPUTID) { - return new SECPTransferInput(...args) - } - /* istanbul ignore next */ - throw new InputIdError("Error - SelectInputClass: unknown inputID") -} - -export class TransferableInput extends StandardTransferableInput { - protected _typeName = "TransferableInput" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.input = SelectInputClass(fields["input"]["_typeID"]) - this.input.deserialize(fields["input"], encoding) - } - - /** - * - * Assesses the amount to be paid based on the number of signatures required - * @returns the amount to be paid - */ - getCost = (): number => { - const numSigs: number = this.getInput().getSigIdxs().length - return numSigs * Defaults.network[1].C.costPerSignature - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing a [[TransferableInput]], parses it, populates the class, and returns the length of the [[TransferableInput]] in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[TransferableInput]] - * - * @returns The length of the raw [[TransferableInput]] - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.txid = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - this.outputidx = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - this.assetID = bintools.copyFrom( - bytes, - offset, - offset + EVMConstants.ASSETIDLEN - ) - offset += 32 - const inputid: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.input = SelectInputClass(inputid) - return this.input.fromBuffer(bytes, offset) - } -} - -export abstract class AmountInput extends StandardAmountInput { - protected _typeName = "AmountInput" - protected _typeID = undefined - - //serialize and deserialize both are inherited - - select(id: number, ...args: any[]): Input { - return SelectInputClass(id, ...args) - } -} - -export class SECPTransferInput extends AmountInput { - protected _typeName = "SECPTransferInput" - protected _typeID = EVMConstants.SECPINPUTID - - //serialize and deserialize both are inherited - - /** - * Returns the inputID for this input - */ - getInputID(): number { - return EVMConstants.SECPINPUTID - } - - getCredentialID = (): number => EVMConstants.SECPCREDENTIAL - - create(...args: any[]): this { - return new SECPTransferInput(...args) as this - } - - clone(): this { - const newout: SECPTransferInput = this.create() - newout.fromBuffer(this.toBuffer()) - return newout as this - } -} - -export class EVMInput extends EVMOutput { - protected nonce: Buffer = Buffer.alloc(8) - protected nonceValue: BN = new BN(0) - protected sigCount: Buffer = Buffer.alloc(4) - protected sigIdxs: SigIdx[] = [] // idxs of signers from utxo - - /** - * Returns the array of [[SigIdx]] for this [[Input]] - */ - getSigIdxs = (): SigIdx[] => this.sigIdxs - - /** - * Creates and adds a [[SigIdx]] to the [[Input]]. - * - * @param addressIdx The index of the address to reference in the signatures - * @param address The address of the source of the signature - */ - addSignatureIdx = (addressIdx: number, address: Buffer) => { - const sigidx: SigIdx = new SigIdx() - const b: Buffer = Buffer.alloc(4) - b.writeUInt32BE(addressIdx, 0) - sigidx.fromBuffer(b) - sigidx.setSource(address) - this.sigIdxs.push(sigidx) - this.sigCount.writeUInt32BE(this.sigIdxs.length, 0) - } - - /** - * Returns the nonce as a {@link https://github.com/indutny/bn.js/|BN}. - */ - getNonce = (): BN => this.nonceValue.clone() - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[EVMOutput]]. - */ - toBuffer(): Buffer { - let superbuff: Buffer = super.toBuffer() - let bsize: number = superbuff.length + this.nonce.length - let barr: Buffer[] = [superbuff, this.nonce] - return Buffer.concat(barr, bsize) - } - - getCredentialID = (): number => EVMConstants.SECPCREDENTIAL - - /** - * Decodes the [[EVMInput]] as a {@link https://github.com/feross/buffer|Buffer} and returns the size. - * - * @param bytes The bytes as a {@link https://github.com/feross/buffer|Buffer}. - * @param offset An offset as a number. - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - this.nonce = bintools.copyFrom(bytes, offset, offset + 8) - offset += 8 - return offset - } - - /** - * Returns a base-58 representation of the [[EVMInput]]. - */ - toString(): string { - return bintools.bufferToB58(this.toBuffer()) - } - - create(...args: any[]): this { - return new EVMInput(...args) as this - } - - clone(): this { - const newEVMInput: EVMInput = this.create() - newEVMInput.fromBuffer(this.toBuffer()) - return newEVMInput as this - } - - /** - * An [[EVMInput]] class which contains address, amount, assetID, nonce. - * - * @param address is the EVM address from which to transfer funds. - * @param amount is the amount of the asset to be transferred (specified in nAVAX for AVAX and the smallest denomination for all other assets). - * @param assetID The assetID which is being sent as a {@link https://github.com/feross/buffer|Buffer} or as a string. - * @param nonce A {@link https://github.com/indutny/bn.js/|BN} or a number representing the nonce. - */ - constructor( - address: Buffer | string = undefined, - amount: BN | number = undefined, - assetID: Buffer | string = undefined, - nonce: BN | number = undefined - ) { - super(address, amount, assetID) - - if (typeof nonce !== "undefined") { - // convert number nonce to BN - let n: BN - if (typeof nonce === "number") { - n = new BN(nonce) - } else { - n = nonce - } - - this.nonceValue = n.clone() - this.nonce = bintools.fromBNToBuffer(n, 8) - } - } -} diff --git a/src/apis/evm/interfaces.ts b/src/apis/evm/interfaces.ts deleted file mode 100644 index 6f40e7bcf..000000000 --- a/src/apis/evm/interfaces.ts +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @packageDocumentation - * @module EVM-Interfaces - */ - -import { Buffer } from "buffer/" -import { Index, CredsInterface } from "../../common" - -export interface GetAssetDescriptionParams { - assetID: Buffer | string -} - -export interface GetAtomicTxStatusParams { - txID: string -} - -export interface GetAtomicTxParams { - txID: string -} - -export interface ExportAVAXParams extends CredsInterface { - to: string - amount: string -} - -export interface ExportParams extends ExportAVAXParams { - assetID: string -} - -export interface GetUTXOsParams { - addresses: string[] | string - limit: number - sourceChain?: string - startIndex?: Index - encoding?: string -} - -export interface ImportAVAXParams extends CredsInterface { - to: string - sourceChain: string -} - -export interface ImportParams extends ImportAVAXParams {} - -export interface ImportKeyParams extends CredsInterface { - privateKey: string -} - -export interface ExportKeyParams extends CredsInterface { - address: string -} - -export interface CreateKeyPairResponse { - address: string - publicKey: string - privateKey: string -} diff --git a/src/apis/evm/keychain.ts b/src/apis/evm/keychain.ts deleted file mode 100644 index 76f24a025..000000000 --- a/src/apis/evm/keychain.ts +++ /dev/null @@ -1,114 +0,0 @@ -/** - * @packageDocumentation - * @module API-EVM-KeyChain - */ - -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { SECP256k1KeyChain, SECP256k1KeyPair } from "../../common/secp256k1" -import { Serialization, SerializedType } from "../../utils" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Class for representing a private and public keypair on an AVM Chain. - */ -export class KeyPair extends SECP256k1KeyPair { - clone(): this { - const newkp: KeyPair = new KeyPair(this.hrp, this.chainID) - newkp.importKey(bintools.copyFrom(this.getPrivateKey())) - return newkp as this - } - - create(...args: any[]): this { - if (args.length == 2) { - return new KeyPair(args[0], args[1]) as this - } - return new KeyPair(this.hrp, this.chainID) as this - } -} - -/** - * Class for representing a key chain in Avalanche. - * - * @typeparam KeyPair Class extending [[SECP256k1KeyChain]] which is used as the key in [[KeyChain]] - */ -export class KeyChain extends SECP256k1KeyChain { - hrp: string = "" - chainID: string = "" - - /** - * Makes a new key pair, returns the address. - * - * @returns The new key pair - */ - makeKey = (): KeyPair => { - const keypair: KeyPair = new KeyPair(this.hrp, this.chainID) - this.addKey(keypair) - return keypair - } - - addKey = (newKey: KeyPair) => { - newKey.setChainID(this.chainID) - super.addKey(newKey) - } - - /** - * Given a private key, makes a new key pair, returns the address. - * - * @param privk A {@link https://github.com/feross/buffer|Buffer} - * or cb58 serialized string representing the private key - * - * @returns The new key pair - */ - importKey = (privk: Buffer | string): KeyPair => { - const keypair: KeyPair = new KeyPair(this.hrp, this.chainID) - let pk: Buffer - if (typeof privk === "string") { - pk = bintools.cb58Decode(privk.split("-")[1]) - } else { - pk = bintools.copyFrom(privk) - } - keypair.importKey(pk) - if (!(keypair.getAddress().toString("hex") in this.keys)) { - this.addKey(keypair) - } - return keypair - } - - create(...args: any[]): this { - if (args.length == 2) { - return new KeyChain(args[0], args[1]) as this - } - return new KeyChain(this.hrp, this.chainID) as this - } - - clone(): this { - const newkc: KeyChain = new KeyChain(this.hrp, this.chainID) - for (let k in this.keys) { - newkc.addKey(this.keys[`${k}`].clone()) - } - return newkc as this - } - - union(kc: this): this { - const newkc: KeyChain = kc.clone() - for (let k in this.keys) { - newkc.addKey(this.keys[`${k}`].clone()) - } - return newkc as this - } - - /** - * Returns instance of KeyChain. - */ - constructor(hrp: string, chainID: string) { - super() - this.hrp = hrp - this.chainID = chainID - } -} diff --git a/src/apis/evm/outputs.ts b/src/apis/evm/outputs.ts deleted file mode 100644 index 2b7a5b1fa..000000000 --- a/src/apis/evm/outputs.ts +++ /dev/null @@ -1,238 +0,0 @@ -/** - * @packageDocumentation - * @module API-EVM-Outputs - */ -import { Buffer } from "buffer/" -import BN from "bn.js" -import BinTools from "../../utils/bintools" -import { EVMConstants } from "./constants" -import { - Output, - StandardAmountOutput, - StandardTransferableOutput -} from "../../common/output" -import { SerializedEncoding } from "../../utils/serialization" -import { EVMInput } from "./inputs" -import { OutputIdError } from "../../utils/errors" - -const bintools: BinTools = BinTools.getInstance() - -/** - * Takes a buffer representing the output and returns the proper Output instance. - * - * @param outputID A number representing the outputID parsed prior to the bytes passed in - * - * @returns An instance of an [[Output]]-extended class. - */ -export const SelectOutputClass = (outputID: number, ...args: any[]): Output => { - if (outputID == EVMConstants.SECPXFEROUTPUTID) { - return new SECPTransferOutput(...args) - } - throw new OutputIdError("Error - SelectOutputClass: unknown outputID") -} - -export class TransferableOutput extends StandardTransferableOutput { - protected _typeName = "TransferableOutput" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.output = SelectOutputClass(fields["output"]["_typeID"]) - this.output.deserialize(fields["output"], encoding) - } - - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.assetID = bintools.copyFrom( - bytes, - offset, - offset + EVMConstants.ASSETIDLEN - ) - offset += EVMConstants.ASSETIDLEN - const outputid: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.output = SelectOutputClass(outputid) - return this.output.fromBuffer(bytes, offset) - } -} - -export abstract class AmountOutput extends StandardAmountOutput { - protected _typeName = "AmountOutput" - protected _typeID = undefined - - //serialize and deserialize both are inherited - - /** - * - * @param assetID An assetID which is wrapped around the Buffer of the Output - */ - makeTransferable(assetID: Buffer): TransferableOutput { - return new TransferableOutput(assetID, this) - } - - select(id: number, ...args: any[]): Output { - return SelectOutputClass(id, ...args) - } -} - -/** - * An [[Output]] class which specifies an Output that carries an ammount for an assetID and uses secp256k1 signature scheme. - */ -export class SECPTransferOutput extends AmountOutput { - protected _typeName = "SECPTransferOutput" - protected _typeID = EVMConstants.SECPXFEROUTPUTID - - //serialize and deserialize both are inherited - - /** - * Returns the outputID for this output - */ - getOutputID(): number { - return this._typeID - } - - create(...args: any[]): this { - return new SECPTransferOutput(...args) as this - } - - clone(): this { - const newout: SECPTransferOutput = this.create() - newout.fromBuffer(this.toBuffer()) - return newout as this - } -} - -export class EVMOutput { - protected address: Buffer = Buffer.alloc(20) - protected amount: Buffer = Buffer.alloc(8) - protected amountValue: BN = new BN(0) - protected assetID: Buffer = Buffer.alloc(32) - - /** - * Returns a function used to sort an array of [[EVMOutput]]s - */ - static comparator = - (): ((a: EVMOutput | EVMInput, b: EVMOutput | EVMInput) => 1 | -1 | 0) => - (a: EVMOutput | EVMInput, b: EVMOutput | EVMInput): 1 | -1 | 0 => { - // primarily sort by address - let sorta: Buffer = a.getAddress() - let sortb: Buffer = b.getAddress() - // secondarily sort by assetID - if (sorta.equals(sortb)) { - sorta = a.getAssetID() - sortb = b.getAssetID() - } - return Buffer.compare(sorta, sortb) as 1 | -1 | 0 - } - - /** - * Returns the address of the input as {@link https://github.com/feross/buffer|Buffer} - */ - getAddress = (): Buffer => this.address - - /** - * Returns the address as a bech32 encoded string. - */ - getAddressString = (): string => this.address.toString("hex") - - /** - * Returns the amount as a {@link https://github.com/indutny/bn.js/|BN}. - */ - getAmount = (): BN => this.amountValue.clone() - - /** - * Returns the assetID of the input as {@link https://github.com/feross/buffer|Buffer} - */ - getAssetID = (): Buffer => this.assetID - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[EVMOutput]]. - */ - toBuffer(): Buffer { - const bsize: number = - this.address.length + this.amount.length + this.assetID.length - const barr: Buffer[] = [this.address, this.amount, this.assetID] - const buff: Buffer = Buffer.concat(barr, bsize) - return buff - } - - /** - * Decodes the [[EVMOutput]] as a {@link https://github.com/feross/buffer|Buffer} and returns the size. - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.address = bintools.copyFrom(bytes, offset, offset + 20) - offset += 20 - this.amount = bintools.copyFrom(bytes, offset, offset + 8) - offset += 8 - this.assetID = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - this.amountValue = new BN(this.amount) - return offset - } - - /** - * Returns a base-58 representation of the [[EVMOutput]]. - */ - toString(): string { - return bintools.bufferToB58(this.toBuffer()) - } - - create(...args: any[]): this { - return new EVMOutput(...args) as this - } - - clone(): this { - const newEVMOutput: EVMOutput = this.create() - newEVMOutput.fromBuffer(this.toBuffer()) - return newEVMOutput as this - } - - /** - * An [[EVMOutput]] class which contains address, amount, and assetID. - * - * @param address The address recieving the asset as a {@link https://github.com/feross/buffer|Buffer} or a string. - * @param amount A {@link https://github.com/indutny/bn.js/|BN} or number representing the amount. - * @param assetID The assetID which is being sent as a {@link https://github.com/feross/buffer|Buffer} or a string. - */ - constructor( - address: Buffer | string = undefined, - amount: BN | number = undefined, - assetID: Buffer | string = undefined - ) { - if ( - typeof address !== "undefined" && - typeof amount !== "undefined" && - typeof assetID !== "undefined" - ) { - if (typeof address === "string") { - // if present then remove `0x` prefix - const prefix: string = address.substring(0, 2) - if (prefix === "0x") { - address = address.split("x")[1] - } - address = Buffer.from(address, "hex") - } - - // convert number amount to BN - let amnt: BN - if (typeof amount === "number") { - amnt = new BN(amount) - } else { - amnt = amount - } - - // convert string assetID to Buffer - if (!(assetID instanceof Buffer)) { - assetID = bintools.cb58Decode(assetID) - } - - this.address = address - this.amountValue = amnt.clone() - this.amount = bintools.fromBNToBuffer(amnt, 8) - this.assetID = assetID - } - } -} diff --git a/src/apis/evm/tx.ts b/src/apis/evm/tx.ts deleted file mode 100644 index ddfc3cbe5..000000000 --- a/src/apis/evm/tx.ts +++ /dev/null @@ -1,138 +0,0 @@ -/** - * @packageDocumentation - * @module API-EVM-Transactions - */ - -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { EVMConstants } from "./constants" -import { SelectCredentialClass } from "./credentials" -import { KeyChain, KeyPair } from "./keychain" -import { Credential } from "../../common/credentials" -import { EVMStandardTx, EVMStandardUnsignedTx } from "../../common/evmtx" -import createHash from "create-hash" -import { EVMBaseTx } from "./basetx" -import { ImportTx } from "./importtx" -import { ExportTx } from "./exporttx" -import { SerializedEncoding } from "../../utils/serialization" -import { TransactionError } from "../../utils/errors" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() - -/** - * Takes a buffer representing the output and returns the proper [[EVMBaseTx]] instance. - * - * @param txTypeID The id of the transaction type - * - * @returns An instance of an [[EVMBaseTx]]-extended class. - */ -export const SelectTxClass = (txTypeID: number, ...args: any[]): EVMBaseTx => { - if (txTypeID === EVMConstants.IMPORTTX) { - return new ImportTx(...args) - } else if (txTypeID === EVMConstants.EXPORTTX) { - return new ExportTx(...args) - } - /* istanbul ignore next */ - throw new Error("TransactionError - SelectTxClass: unknown txType") -} - -export class UnsignedTx extends EVMStandardUnsignedTx< - KeyPair, - KeyChain, - EVMBaseTx -> { - protected _typeName = "UnsignedTx" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.transaction = SelectTxClass(fields["transaction"]["_typeID"]) - this.transaction.deserialize(fields["transaction"], encoding) - } - - getTransaction(): EVMBaseTx { - return this.transaction as EVMBaseTx - } - - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.codecID = bintools.copyFrom(bytes, offset, offset + 2).readUInt16BE(0) - offset += 2 - const txtype: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.transaction = SelectTxClass(txtype) - return this.transaction.fromBuffer(bytes, offset) - } - - /** - * Signs this [[UnsignedTx]] and returns signed [[StandardTx]] - * - * @param kc An [[KeyChain]] used in signing - * - * @returns A signed [[StandardTx]] - */ - sign(kc: KeyChain): Tx { - const txbuff: Buffer = this.toBuffer() - const msg: Buffer = Buffer.from( - createHash("sha256").update(txbuff).digest() - ) - const creds: Credential[] = this.transaction.sign(msg, kc) - return new Tx(this, creds) - } -} - -export class Tx extends EVMStandardTx { - protected _typeName = "Tx" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.unsignedTx = new UnsignedTx() - this.unsignedTx.deserialize(fields["unsignedTx"], encoding) - this.credentials = [] - for (let i: number = 0; i < fields["credentials"].length; i++) { - const cred: Credential = SelectCredentialClass( - fields["credentials"][`${i}`]["_typeID"] - ) - cred.deserialize(fields["credentials"][`${i}`], encoding) - this.credentials.push(cred) - } - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[Tx]], parses it, - * populates the class, and returns the length of the Tx in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[Tx]] - * @param offset A number representing the starting point of the bytes to begin parsing - * - * @returns The length of the raw [[Tx]] - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.unsignedTx = new UnsignedTx() - offset = this.unsignedTx.fromBuffer(bytes, offset) - const numcreds: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.credentials = [] - for (let i: number = 0; i < numcreds; i++) { - const credid: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - const cred: Credential = SelectCredentialClass(credid) - offset = cred.fromBuffer(bytes, offset) - this.credentials.push(cred) - } - return offset - } -} diff --git a/src/apis/evm/utxos.ts b/src/apis/evm/utxos.ts deleted file mode 100644 index 889722465..000000000 --- a/src/apis/evm/utxos.ts +++ /dev/null @@ -1,518 +0,0 @@ -/** - * @packageDocumentation - * @module API-EVM-UTXOs - */ - -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import BN from "bn.js" -import { - AmountOutput, - SelectOutputClass, - TransferableOutput, - EVMOutput -} from "./outputs" -import { EVMConstants } from "./constants" -import { EVMInput, SECPTransferInput, TransferableInput } from "./inputs" -import { Output } from "../../common/output" -import { UnixNow } from "../../utils/helperfunctions" -import { StandardUTXO, StandardUTXOSet } from "../../common/utxos" -import { PlatformChainID } from "../../utils/constants" -import { - StandardAssetAmountDestination, - AssetAmount -} from "../../common/assetamount" -import { Serialization, SerializedEncoding } from "../../utils/serialization" -import { UnsignedTx } from "./tx" -import { ImportTx } from "./importtx" -import { ExportTx } from "./exporttx" -import { - UTXOError, - AddressError, - InsufficientFundsError, - FeeAssetError -} from "../../utils/errors" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serializer: Serialization = Serialization.getInstance() - -/** - * Class for representing a single UTXO. - */ -export class UTXO extends StandardUTXO { - protected _typeName = "UTXO" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.output = SelectOutputClass(fields["output"]["_typeID"]) - this.output.deserialize(fields["output"], encoding) - } - - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.codecID = bintools.copyFrom(bytes, offset, offset + 2) - offset += 2 - this.txid = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - this.outputidx = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - this.assetID = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - const outputid: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.output = SelectOutputClass(outputid) - return this.output.fromBuffer(bytes, offset) - } - - /** - * Takes a base-58 string containing a [[UTXO]], parses it, populates the class, and returns the length of the StandardUTXO in bytes. - * - * @param serialized A base-58 string containing a raw [[UTXO]] - * - * @returns The length of the raw [[UTXO]] - * - * @remarks - * unlike most fromStrings, it expects the string to be serialized in cb58 format - */ - fromString(serialized: string): number { - /* istanbul ignore next */ - return this.fromBuffer(bintools.cb58Decode(serialized)) - } - - /** - * Returns a base-58 representation of the [[UTXO]]. - * - * @remarks - * unlike most toStrings, this returns in cb58 serialization format - */ - toString(): string { - /* istanbul ignore next */ - return bintools.cb58Encode(this.toBuffer()) - } - - clone(): this { - const utxo: UTXO = new UTXO() - utxo.fromBuffer(this.toBuffer()) - return utxo as this - } - - create( - codecID: number = EVMConstants.LATESTCODEC, - txID: Buffer = undefined, - outputidx: Buffer | number = undefined, - assetID: Buffer = undefined, - output: Output = undefined - ): this { - return new UTXO(codecID, txID, outputidx, assetID, output) as this - } -} - -export class AssetAmountDestination extends StandardAssetAmountDestination< - TransferableOutput, - TransferableInput -> {} - -/** - * Class representing a set of [[UTXO]]s. - */ -export class UTXOSet extends StandardUTXOSet { - protected _typeName = "UTXOSet" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex"): void { - super.deserialize(fields, encoding) - const utxos: {} = {} - for (let utxoid in fields["utxos"]) { - let utxoidCleaned: string = serializer.decoder( - utxoid, - encoding, - "base58", - "base58" - ) - utxos[`${utxoidCleaned}`] = new UTXO() - utxos[`${utxoidCleaned}`].deserialize( - fields["utxos"][`${utxoid}`], - encoding - ) - } - let addressUTXOs: {} = {} - for (let address in fields["addressUTXOs"]) { - let addressCleaned: string = serializer.decoder( - address, - encoding, - "cb58", - "hex" - ) - let utxobalance: {} = {} - for (let utxoid in fields["addressUTXOs"][`${address}`]) { - let utxoidCleaned: string = serializer.decoder( - utxoid, - encoding, - "base58", - "base58" - ) - utxobalance[`${utxoidCleaned}`] = serializer.decoder( - fields["addressUTXOs"][`${address}`][`${utxoid}`], - encoding, - "decimalString", - "BN" - ) - } - addressUTXOs[`${addressCleaned}`] = utxobalance - } - this.utxos = utxos - this.addressUTXOs = addressUTXOs - } - - parseUTXO(utxo: UTXO | string): UTXO { - const utxovar: UTXO = new UTXO() - // force a copy - if (typeof utxo === "string") { - utxovar.fromBuffer(bintools.cb58Decode(utxo)) - } else if (utxo instanceof UTXO) { - utxovar.fromBuffer(utxo.toBuffer()) // forces a copy - } else { - /* istanbul ignore next */ - throw new UTXOError( - "Error - UTXO.parseUTXO: utxo parameter is not a UTXO or string" - ) - } - return utxovar - } - - create(): this { - return new UTXOSet() as this - } - - clone(): this { - const newset: UTXOSet = this.create() - const allUTXOs: UTXO[] = this.getAllUTXOs() - newset.addArray(allUTXOs) - return newset as this - } - - _feeCheck(fee: BN, feeAssetID: Buffer): boolean { - return ( - typeof fee !== "undefined" && - typeof feeAssetID !== "undefined" && - fee.gt(new BN(0)) && - feeAssetID instanceof Buffer - ) - } - - getMinimumSpendable = ( - aad: AssetAmountDestination, - asOf: BN = UnixNow(), - locktime: BN = new BN(0), - threshold: number = 1 - ): Error => { - const utxoArray: UTXO[] = this.getAllUTXOs() - const outids: object = {} - for (let i: number = 0; i < utxoArray.length && !aad.canComplete(); i++) { - const u: UTXO = utxoArray[`${i}`] - const assetKey: string = u.getAssetID().toString("hex") - const fromAddresses: Buffer[] = aad.getSenders() - if ( - u.getOutput() instanceof AmountOutput && - aad.assetExists(assetKey) && - u.getOutput().meetsThreshold(fromAddresses, asOf) - ) { - const am: AssetAmount = aad.getAssetAmount(assetKey) - if (!am.isFinished()) { - const uout: AmountOutput = u.getOutput() as AmountOutput - outids[`${assetKey}`] = uout.getOutputID() - const amount = uout.getAmount() - am.spendAmount(amount) - const txid: Buffer = u.getTxID() - const outputidx: Buffer = u.getOutputIdx() - const input: SECPTransferInput = new SECPTransferInput(amount) - const xferin: TransferableInput = new TransferableInput( - txid, - outputidx, - u.getAssetID(), - input - ) - const spenders: Buffer[] = uout.getSpenders(fromAddresses, asOf) - spenders.forEach((spender: Buffer) => { - const idx: number = uout.getAddressIdx(spender) - if (idx === -1) { - /* istanbul ignore next */ - throw new AddressError( - "Error - UTXOSet.getMinimumSpendable: no such address in output" - ) - } - xferin.getInput().addSignatureIdx(idx, spender) - }) - aad.addInput(xferin) - } else if ( - aad.assetExists(assetKey) && - !(u.getOutput() instanceof AmountOutput) - ) { - /** - * Leaving the below lines, not simply for posterity, but for clarification. - * AssetIDs may have mixed OutputTypes. - * Some of those OutputTypes may implement AmountOutput. - * Others may not. - * Simply continue in this condition. - */ - /*return new Error('Error - UTXOSet.getMinimumSpendable: outputID does not ' - + `implement AmountOutput: ${u.getOutput().getOutputID}`);*/ - continue - } - } - } - if (!aad.canComplete()) { - return new InsufficientFundsError( - `Error - UTXOSet.getMinimumSpendable: insufficient funds to create the transaction` - ) - } - const amounts: AssetAmount[] = aad.getAmounts() - const zero: BN = new BN(0) - for (let i: number = 0; i < amounts.length; i++) { - const assetKey: string = amounts[`${i}`].getAssetIDString() - const amount: BN = amounts[`${i}`].getAmount() - if (amount.gt(zero)) { - const spendout: AmountOutput = SelectOutputClass( - outids[`${assetKey}`], - amount, - aad.getDestinations(), - locktime, - threshold - ) as AmountOutput - const xferout: TransferableOutput = new TransferableOutput( - amounts[`${i}`].getAssetID(), - spendout - ) - aad.addOutput(xferout) - } - const change: BN = amounts[`${i}`].getChange() - if (change.gt(zero)) { - const changeout: AmountOutput = SelectOutputClass( - outids[`${assetKey}`], - change, - aad.getChangeAddresses() - ) as AmountOutput - const chgxferout: TransferableOutput = new TransferableOutput( - amounts[`${i}`].getAssetID(), - changeout - ) - aad.addChange(chgxferout) - } - } - return undefined - } - - /** - * Creates an unsigned ImportTx transaction. - * - * @param networkID The number representing NetworkID of the node - * @param blockchainID The {@link https://github.com/feross/buffer|Buffer} representing the BlockchainID for the transaction - * @param toAddress The address to send the funds - * @param importIns An array of [[TransferableInput]]s being imported - * @param sourceChain A {@link https://github.com/feross/buffer|Buffer} for the chainid where the imports are coming from. - * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN}. Fee will come from the inputs first, if they can. - * @param feeAssetID Optional. The assetID of the fees being burned. - * @returns An unsigned transaction created from the passed in parameters. - * - */ - buildImportTx = ( - networkID: number, - blockchainID: Buffer, - toAddress: string, - atomics: UTXO[], - sourceChain: Buffer = undefined, - fee: BN = undefined, - feeAssetID: Buffer = undefined - ): UnsignedTx => { - const zero: BN = new BN(0) - const map: Map = new Map() - - let ins: TransferableInput[] = [] - let outs: EVMOutput[] = [] - let feepaid: BN = new BN(0) - - if (typeof fee === "undefined") { - fee = zero.clone() - } - - // build a set of inputs which covers the fee - atomics.forEach((atomic: UTXO): void => { - const assetIDBuf: Buffer = atomic.getAssetID() - const assetID: string = bintools.cb58Encode(atomic.getAssetID()) - const output: AmountOutput = atomic.getOutput() as AmountOutput - const amount: BN = output.getAmount().clone() - let infeeamount: BN = amount.clone() - - if ( - typeof feeAssetID !== "undefined" && - fee.gt(zero) && - feepaid.lt(fee) && - Buffer.compare(feeAssetID, assetIDBuf) === 0 - ) { - feepaid = feepaid.add(infeeamount) - if (feepaid.gt(fee)) { - infeeamount = feepaid.sub(fee) - feepaid = fee.clone() - } else { - infeeamount = zero.clone() - } - } - - const txid: Buffer = atomic.getTxID() - const outputidx: Buffer = atomic.getOutputIdx() - const input: SECPTransferInput = new SECPTransferInput(amount) - const xferin: TransferableInput = new TransferableInput( - txid, - outputidx, - assetIDBuf, - input - ) - const from: Buffer[] = output.getAddresses() - const spenders: Buffer[] = output.getSpenders(from) - spenders.forEach((spender: Buffer): void => { - const idx: number = output.getAddressIdx(spender) - if (idx === -1) { - /* istanbul ignore next */ - throw new AddressError( - "Error - UTXOSet.buildImportTx: no such address in output" - ) - } - xferin.getInput().addSignatureIdx(idx, spender) - }) - ins.push(xferin) - - if (map.has(assetID)) { - infeeamount = infeeamount.add(new BN(map.get(assetID))) - } - map.set(assetID, infeeamount.toString()) - }) - - for (let [assetID, amount] of map) { - // Create single EVMOutput for each assetID - const evmOutput: EVMOutput = new EVMOutput( - toAddress, - new BN(amount), - bintools.cb58Decode(assetID) - ) - outs.push(evmOutput) - } - - // lexicographically sort array - ins = ins.sort(TransferableInput.comparator()) - outs = outs.sort(EVMOutput.comparator()) - - const importTx: ImportTx = new ImportTx( - networkID, - blockchainID, - sourceChain, - ins, - outs, - fee - ) - return new UnsignedTx(importTx) - } - - /** - * Creates an unsigned ExportTx transaction. - * - * @param networkID The number representing NetworkID of the node - * @param blockchainID The {@link https://github.com/feross/buffer|Buffer} representing the BlockchainID for the transaction - * @param amount The amount being exported as a {@link https://github.com/indutny/bn.js/|BN} - * @param avaxAssetID {@link https://github.com/feross/buffer|Buffer} of the AssetID for AVAX - * @param toAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who recieves the AVAX - * @param fromAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who owns the AVAX - * @param changeAddresses Optional. The addresses that can spend the change remaining from the spent UTXOs. - * @param destinationChain Optional. A {@link https://github.com/feross/buffer|Buffer} for the chainid where to send the asset. - * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN} - * @param feeAssetID Optional. The assetID of the fees being burned. - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param locktime Optional. The locktime field created in the resulting outputs - * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO - * @returns An unsigned transaction created from the passed in parameters. - * - */ - buildExportTx = ( - networkID: number, - blockchainID: Buffer, - amount: BN, - avaxAssetID: Buffer, - toAddresses: Buffer[], - fromAddresses: Buffer[], - changeAddresses: Buffer[] = undefined, - destinationChain: Buffer = undefined, - fee: BN = undefined, - feeAssetID: Buffer = undefined, - asOf: BN = UnixNow(), - locktime: BN = new BN(0), - threshold: number = 1 - ): UnsignedTx => { - let ins: EVMInput[] = [] - let exportouts: TransferableOutput[] = [] - - if (typeof changeAddresses === "undefined") { - changeAddresses = toAddresses - } - - const zero: BN = new BN(0) - - if (amount.eq(zero)) { - return undefined - } - - if (typeof feeAssetID === "undefined") { - feeAssetID = avaxAssetID - } else if (feeAssetID.toString("hex") !== avaxAssetID.toString("hex")) { - /* istanbul ignore next */ - throw new FeeAssetError( - "Error - UTXOSet.buildExportTx: feeAssetID must match avaxAssetID" - ) - } - - if (typeof destinationChain === "undefined") { - destinationChain = bintools.cb58Decode(PlatformChainID) - } - - const aad: AssetAmountDestination = new AssetAmountDestination( - toAddresses, - fromAddresses, - changeAddresses - ) - if (avaxAssetID.toString("hex") === feeAssetID.toString("hex")) { - aad.addAssetAmount(avaxAssetID, amount, fee) - } else { - aad.addAssetAmount(avaxAssetID, amount, zero) - if (this._feeCheck(fee, feeAssetID)) { - aad.addAssetAmount(feeAssetID, zero, fee) - } - } - const success: Error = this.getMinimumSpendable( - aad, - asOf, - locktime, - threshold - ) - if (typeof success === "undefined") { - exportouts = aad.getOutputs() - } else { - throw success - } - - const exportTx: ExportTx = new ExportTx( - networkID, - blockchainID, - destinationChain, - ins, - exportouts - ) - return new UnsignedTx(exportTx) - } -} diff --git a/src/apis/health/api.ts b/src/apis/health/api.ts deleted file mode 100644 index 03d56e8cf..000000000 --- a/src/apis/health/api.ts +++ /dev/null @@ -1,36 +0,0 @@ -/** - * @packageDocumentation - * @module API-Health - */ -import AvalancheCore from "../../avalanche" -import { JRPCAPI } from "../../common/jrpcapi" -import { RequestResponseData } from "../../common/apibase" -import { HealthResponse } from "./interfaces" - -/** - * Class for interacting with a node API that is using the node's HealthApi. - * - * @category RPCAPIs - * - * @remarks This extends the [[JRPCAPI]] class. This class should not be directly called. Instead, use the [[Avalanche.addAPI]] function to register this interface with Avalanche. - */ -export class HealthAPI extends JRPCAPI { - /** - * - * @returns Promise for a [[HealthResponse]] - */ - health = async (): Promise => { - const response: RequestResponseData = await this.callMethod("health.health") - return response.data.result - } - - /** - * This class should not be instantiated directly. Instead use the [[Avalanche.addAPI]] method. - * - * @param core A reference to the Avalanche class - * @param baseURL Defaults to the string "/ext/health" as the path to rpc's baseURL - */ - constructor(core: AvalancheCore, baseURL: string = "/ext/health") { - super(core, baseURL) - } -} diff --git a/src/apis/health/index.ts b/src/apis/health/index.ts deleted file mode 100644 index e1a716605..000000000 --- a/src/apis/health/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./api" diff --git a/src/apis/health/interfaces.ts b/src/apis/health/interfaces.ts deleted file mode 100644 index 92b5751b7..000000000 --- a/src/apis/health/interfaces.ts +++ /dev/null @@ -1,26 +0,0 @@ -/** - * @packageDocumentation - * @module Health-Interfaces - */ - -export interface Entity { - message?: Object[] - timestamp: string - duration: number - contiguousFailures?: number - timeOfFirstFailure?: string -} - -export interface Checks { - C: Entity - P: Entity - X: Entity - bootstrapped: Entity - network: Entity - router: Entity -} - -export interface HealthResponse { - checks: Checks - healthy: boolean -} diff --git a/src/apis/index/api.ts b/src/apis/index/api.ts deleted file mode 100644 index 7f2a78859..000000000 --- a/src/apis/index/api.ts +++ /dev/null @@ -1,225 +0,0 @@ -/** - * @packageDocumentation - * @module API-Index - */ -import AvalancheCore from "../../avalanche" -import { JRPCAPI } from "../../common/jrpcapi" -import { RequestResponseData } from "../../common/apibase" -import { - GetLastAcceptedParams, - GetLastAcceptedResponse, - GetContainerByIndexParams, - GetContainerByIndexResponse, - GetContainerByIDParams, - GetContainerByIDResponse, - GetContainerRangeParams, - GetContainerRangeResponse, - GetIndexParams, - GetIsAcceptedParams, - IsAcceptedResponse -} from "./interfaces" - -/** - * Class for interacting with a node's IndexAPI. - * - * @category RPCAPIs - * - * @remarks This extends the [[JRPCAPI]] class. This class should not be directly called. Instead, use the [[Avalanche.addAPI]] function to register this interface with Avalanche. - */ -export class IndexAPI extends JRPCAPI { - /** - * Get last accepted tx, vtx or block - * - * @param encoding - * @param baseURL - * - * @returns Returns a Promise GetLastAcceptedResponse. - */ - getLastAccepted = async ( - encoding: string = "hex", - baseURL: string = this.getBaseURL() - ): Promise => { - this.setBaseURL(baseURL) - const params: GetLastAcceptedParams = { - encoding - } - - try { - const response: RequestResponseData = await this.callMethod( - "index.getLastAccepted", - params - ) - return response.data.result - } catch (error) { - console.log(error) - } - } - - /** - * Get container by index - * - * @param index - * @param encoding - * @param baseURL - * - * @returns Returns a Promise GetContainerByIndexResponse. - */ - getContainerByIndex = async ( - index: string = "0", - encoding: string = "hex", - baseURL: string = this.getBaseURL() - ): Promise => { - this.setBaseURL(baseURL) - const params: GetContainerByIndexParams = { - index, - encoding - } - - try { - const response: RequestResponseData = await this.callMethod( - "index.getContainerByIndex", - params - ) - return response.data.result - } catch (error) { - console.log(error) - } - } - - /** - * Get contrainer by ID - * - * @param id - * @param encoding - * @param baseURL - * - * @returns Returns a Promise GetContainerByIDResponse. - */ - getContainerByID = async ( - id: string = "0", - encoding: string = "hex", - baseURL: string = this.getBaseURL() - ): Promise => { - this.setBaseURL(baseURL) - const params: GetContainerByIDParams = { - id, - encoding - } - - try { - const response: RequestResponseData = await this.callMethod( - "index.getContainerByID", - params - ) - return response.data.result - } catch (error) { - console.log(error) - } - } - - /** - * Get container range - * - * @param startIndex - * @param numToFetch - * @param encoding - * @param baseURL - * - * @returns Returns a Promise GetContainerRangeResponse. - */ - getContainerRange = async ( - startIndex: number = 0, - numToFetch: number = 100, - encoding: string = "hex", - baseURL: string = this.getBaseURL() - ): Promise => { - this.setBaseURL(baseURL) - const params: GetContainerRangeParams = { - startIndex, - numToFetch, - encoding - } - - try { - const response: RequestResponseData = await this.callMethod( - "index.getContainerRange", - params - ) - return response.data.result - } catch (error) { - console.log(error) - } - } - - /** - * Get index by containerID - * - * @param id - * @param encoding - * @param baseURL - * - * @returns Returns a Promise GetIndexResponse. - */ - getIndex = async ( - id: string = "", - encoding: string = "hex", - baseURL: string = this.getBaseURL() - ): Promise => { - this.setBaseURL(baseURL) - const params: GetIndexParams = { - id, - encoding - } - - try { - const response: RequestResponseData = await this.callMethod( - "index.getIndex", - params - ) - return response.data.result.index - } catch (error) { - console.log(error) - } - } - - /** - * Check if container is accepted - * - * @param id - * @param encoding - * @param baseURL - * - * @returns Returns a Promise GetIsAcceptedResponse. - */ - isAccepted = async ( - id: string = "", - encoding: string = "hex", - baseURL: string = this.getBaseURL() - ): Promise => { - this.setBaseURL(baseURL) - const params: GetIsAcceptedParams = { - id, - encoding - } - - try { - const response: RequestResponseData = await this.callMethod( - "index.isAccepted", - params - ) - return response.data.result - } catch (error) { - console.log(error) - } - } - - /** - * This class should not be instantiated directly. Instead use the [[Avalanche.addAPI]] method. - * - * @param core A reference to the Avalanche class - * @param baseURL Defaults to the string "/ext/index/X/tx" as the path to rpc's baseURL - */ - constructor(core: AvalancheCore, baseURL: string = "/ext/index/X/tx") { - super(core, baseURL) - } -} diff --git a/src/apis/index/index.ts b/src/apis/index/index.ts deleted file mode 100644 index e1a716605..000000000 --- a/src/apis/index/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./api" diff --git a/src/apis/index/interfaces.ts b/src/apis/index/interfaces.ts deleted file mode 100644 index 851059219..000000000 --- a/src/apis/index/interfaces.ts +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @packageDocumentation - * @module Index-Interfaces - */ - -export interface BaseIndexParams { - encoding: string -} - -export interface BaseIndexResponse { - id: string - bytes: string - timestamp: string - encoding: string - index: string -} - -export interface GetLastAcceptedParams extends BaseIndexParams {} - -export interface GetLastAcceptedResponse extends BaseIndexResponse {} - -export interface GetLastVertexParams extends BaseIndexParams {} - -export interface GetLastVertexResponse extends BaseIndexResponse {} - -export interface GetContainerByIndexParams extends BaseIndexParams { - index: string -} - -export interface GetContainerByIndexResponse extends BaseIndexResponse {} - -export interface GetContainerByIDParams extends BaseIndexParams { - id: string -} - -export interface GetContainerByIDResponse extends BaseIndexResponse {} - -export interface GetContainerRangeParams extends BaseIndexParams { - startIndex: number - numToFetch: number -} - -export interface IsAcceptedResponse { - isAccepted: boolean -} - -export interface GetContainerRangeResponse { - constainer: BaseIndexParams[] -} - -export interface GetIndexParams extends BaseIndexParams { - id: string -} - -export interface GetIsAcceptedParams extends BaseIndexParams { - id: string -} diff --git a/src/apis/info/api.ts b/src/apis/info/api.ts deleted file mode 100644 index 9bb2e047f..000000000 --- a/src/apis/info/api.ts +++ /dev/null @@ -1,173 +0,0 @@ -/** - * @packageDocumentation - * @module API-Info - */ -import AvalancheCore from "../../avalanche" -import { JRPCAPI } from "../../common/jrpcapi" -import { RequestResponseData } from "../../common/apibase" -import BN from "bn.js" -import { - GetBlockchainIDParams, - GetTxFeeResponse, - IsBootstrappedParams, - PeersParams, - PeersResponse, - UptimeResponse -} from "./interfaces" - -/** - * Class for interacting with a node's InfoAPI. - * - * @category RPCAPIs - * - * @remarks This extends the [[JRPCAPI]] class. This class should not be directly called. Instead, use the [[Avalanche.addAPI]] function to register this interface with Avalanche. - */ -export class InfoAPI extends JRPCAPI { - /** - * Fetches the blockchainID from the node for a given alias. - * - * @param alias The blockchain alias to get the blockchainID - * - * @returns Returns a Promise string containing the base 58 string representation of the blockchainID. - */ - getBlockchainID = async (alias: string): Promise => { - const params: GetBlockchainIDParams = { - alias - } - - const response: RequestResponseData = await this.callMethod( - "info.getBlockchainID", - params - ) - return response.data.result.blockchainID - } - - /** - * Fetches the IP address from the node. - * - * @returns Returns a Promise string of the node IP address. - */ - getNodeIP = async (): Promise => { - const response: RequestResponseData = await this.callMethod( - "info.getBlockchainID" - ) - return response.data.result.ip - } - - /** - * Fetches the networkID from the node. - * - * @returns Returns a Promise number of the networkID. - */ - getNetworkID = async (): Promise => { - const response: RequestResponseData = await this.callMethod( - "info.getNetworkID" - ) - return response.data.result.networkID - } - - /** - * Fetches the network name this node is running on - * - * @returns Returns a Promise string containing the network name. - */ - getNetworkName = async (): Promise => { - const response: RequestResponseData = await this.callMethod( - "info.getNetworkName" - ) - return response.data.result.networkName - } - - /** - * Fetches the nodeID from the node. - * - * @returns Returns a Promise string of the nodeID. - */ - getNodeID = async (): Promise => { - const response: RequestResponseData = await this.callMethod( - "info.getNodeID" - ) - return response.data.result.nodeID - } - - /** - * Fetches the version of Gecko this node is running - * - * @returns Returns a Promise string containing the version of Gecko. - */ - getNodeVersion = async (): Promise => { - const response: RequestResponseData = await this.callMethod( - "info.getNodeVersion" - ) - return response.data.result.version - } - - /** - * Fetches the transaction fee from the node. - * - * @returns Returns a Promise object of the transaction fee in nAVAX. - */ - getTxFee = async (): Promise => { - const response: RequestResponseData = await this.callMethod("info.getTxFee") - return { - txFee: new BN(response.data.result.txFee, 10), - creationTxFee: new BN(response.data.result.creationTxFee, 10) - } - } - - /** - * Check whether a given chain is done bootstrapping - * @param chain The ID or alias of a chain. - * - * @returns Returns a Promise boolean of whether the chain has completed bootstrapping. - */ - isBootstrapped = async (chain: string): Promise => { - const params: IsBootstrappedParams = { - chain - } - const response: RequestResponseData = await this.callMethod( - "info.isBootstrapped", - params - ) - return response.data.result.isBootstrapped - } - - /** - * Returns the peers connected to the node. - * @param nodeIDs an optional parameter to specify what nodeID's descriptions should be returned. - * If this parameter is left empty, descriptions for all active connections will be returned. - * If the node is not connected to a specified nodeID, it will be omitted from the response. - * - * @returns Promise for the list of connected peers in PeersResponse format. - */ - peers = async (nodeIDs: string[] = []): Promise => { - const params: PeersParams = { - nodeIDs - } - const response: RequestResponseData = await this.callMethod( - "info.peers", - params - ) - return response.data.result.peers - } - - /** - * Returns the network's observed uptime of this node. - * - * @returns Returns a Promise UptimeResponse which contains rewardingStakePercentage and weightedAveragePercentage. - */ - uptime = async (): Promise => { - const response: RequestResponseData = await this.callMethod("info.uptime") - return response.data.result - } - - /** - * This class should not be instantiated directly. Instead use the [[Avalanche.addAPI]] method. - * - * @param core A reference to the Avalanche class - * @param baseURL Defaults to the string "/ext/info" as the path to rpc's baseURL - */ - constructor(core: AvalancheCore, baseURL: string = "/ext/info") { - super(core, baseURL) - } -} diff --git a/src/apis/info/index.ts b/src/apis/info/index.ts deleted file mode 100644 index e1a716605..000000000 --- a/src/apis/info/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./api" diff --git a/src/apis/info/interfaces.ts b/src/apis/info/interfaces.ts deleted file mode 100644 index 6209c9d2f..000000000 --- a/src/apis/info/interfaces.ts +++ /dev/null @@ -1,37 +0,0 @@ -/** - * @packageDocumentation - * @module Info-Interfaces - */ - -import BN from "bn.js" - -export interface GetBlockchainIDParams { - alias: string -} - -export interface IsBootstrappedParams { - chain: string -} - -export interface PeersParams { - nodeIDs: string[] -} - -export interface PeersResponse { - ip: string - publicIP: string - nodeID: string - version: string - lastSent: string - lastReceived: string -} - -export interface GetTxFeeResponse { - txFee: BN - creationTxFee: BN -} - -export interface UptimeResponse { - rewardingStakePercentage: string - weightedAveragePercentage: string -} diff --git a/src/apis/keystore/api.ts b/src/apis/keystore/api.ts deleted file mode 100644 index 276e7e188..000000000 --- a/src/apis/keystore/api.ts +++ /dev/null @@ -1,136 +0,0 @@ -/** - * @packageDocumentation - * @module API-Keystore - */ -import AvalancheCore from "../../avalanche" -import { JRPCAPI } from "../../common/jrpcapi" -import { RequestResponseData } from "../../common/apibase" -import { ImportUserParams } from "./interfaces" -import { CredsInterface } from "../../common/interfaces" - -/** - * Class for interacting with a node API that is using the node's KeystoreAPI. - * - * **WARNING**: The KeystoreAPI is to be used by the node-owner as the data is stored locally on the node. Do not trust the root user. If you are not the node-owner, do not use this as your wallet. - * - * @category RPCAPIs - * - * @remarks This extends the [[JRPCAPI]] class. This class should not be directly called. Instead, use the [[Avalanche.addAPI]] function to register this interface with Avalanche. - */ -export class KeystoreAPI extends JRPCAPI { - /** - * Creates a user in the node's database. - * - * @param username Name of the user to create - * @param password Password for the user - * - * @returns Promise for a boolean with true on success - */ - createUser = async (username: string, password: string): Promise => { - const params: CredsInterface = { - username, - password - } - const response: RequestResponseData = await this.callMethod( - "keystore.createUser", - params - ) - return response.data.result.success - ? response.data.result.success - : response.data.result - } - - /** - * Exports a user. The user can be imported to another node with keystore.importUser . - * - * @param username The name of the user to export - * @param password The password of the user to export - * - * @returns Promise with a string importable using importUser - */ - exportUser = async (username: string, password: string): Promise => { - const params: CredsInterface = { - username, - password - } - const response: RequestResponseData = await this.callMethod( - "keystore.exportUser", - params - ) - return response.data.result.user - ? response.data.result.user - : response.data.result - } - - /** - * Imports a user file into the node's user database and assigns it to a username. - * - * @param username The name the user file should be imported into - * @param user cb58 serialized string represetning a user"s data - * @param password The user"s password - * - * @returns A promise with a true-value on success. - */ - importUser = async ( - username: string, - user: string, - password: string - ): Promise => { - const params: ImportUserParams = { - username, - user, - password - } - const response: RequestResponseData = await this.callMethod( - "keystore.importUser", - params - ) - return response.data.result.success - ? response.data.result.success - : response.data.result - } - - /** - * Lists the names of all users on the node. - * - * @returns Promise of an array with all user names. - */ - listUsers = async (): Promise => { - const response: RequestResponseData = await this.callMethod( - "keystore.listUsers" - ) - return response.data.result.users - } - - /** - * Deletes a user in the node's database. - * - * @param username Name of the user to delete - * @param password Password for the user - * - * @returns Promise for a boolean with true on success - */ - deleteUser = async (username: string, password: string): Promise => { - const params: CredsInterface = { - username, - password - } - const response: RequestResponseData = await this.callMethod( - "keystore.deleteUser", - params - ) - return response.data.result.success - ? response.data.result.success - : response.data.result - } - - /** - * This class should not be instantiated directly. Instead use the [[Avalanche.addAPI]] method. - * - * @param core A reference to the Avalanche class - * @param baseURL Defaults to the string "/ext/keystore" as the path to rpc's baseURL - */ - constructor(core: AvalancheCore, baseURL: string = "/ext/keystore") { - super(core, baseURL) - } -} diff --git a/src/apis/keystore/index.ts b/src/apis/keystore/index.ts deleted file mode 100644 index e1a716605..000000000 --- a/src/apis/keystore/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./api" diff --git a/src/apis/keystore/interfaces.ts b/src/apis/keystore/interfaces.ts deleted file mode 100644 index 5c50531ea..000000000 --- a/src/apis/keystore/interfaces.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** - * @packageDocumentation - * @module Keystore-Interfaces - */ - -import { CredsInterface } from "../../common" - -export interface ImportUserParams extends CredsInterface { - user: string -} diff --git a/src/apis/metrics/api.ts b/src/apis/metrics/api.ts deleted file mode 100644 index 9ce160fb4..000000000 --- a/src/apis/metrics/api.ts +++ /dev/null @@ -1,43 +0,0 @@ -/** - * @packageDocumentation - * @module API-Metrics - */ -import AvalancheCore from "../../avalanche" -import { RESTAPI } from "../../common/restapi" -import { RequestResponseData } from "../../common/apibase" -import { AxiosRequestConfig } from "axios" - -/** - * Class for interacting with a node API that is using the node's MetricsApi. - * - * @category RPCAPIs - * - * @remarks This extends the [[RESTAPI]] class. This class should not be directly called. Instead, use the [[Avalanche.addAPI]] function to register this interface with Avalanche. - */ -export class MetricsAPI extends RESTAPI { - protected axConf = (): AxiosRequestConfig => { - return { - baseURL: `${this.core.getProtocol()}://${this.core.getHost()}:${this.core.getPort()}`, - responseType: "text" - } - } - - /** - * - * @returns Promise for an object containing the metrics response - */ - getMetrics = async (): Promise => { - const response: RequestResponseData = await this.post("") - return response.data as string - } - - /** - * This class should not be instantiated directly. Instead use the [[Avalanche.addAPI]] method. - * - * @param core A reference to the Avalanche class - * @param baseURL Defaults to the string "/ext/metrics" as the path to rpc's baseurl - */ - constructor(core: AvalancheCore, baseURL: string = "/ext/metrics") { - super(core, baseURL) - } -} diff --git a/src/apis/metrics/index.ts b/src/apis/metrics/index.ts deleted file mode 100644 index e1a716605..000000000 --- a/src/apis/metrics/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./api" diff --git a/src/apis/platformvm/addsubnetvalidatortx.ts b/src/apis/platformvm/addsubnetvalidatortx.ts deleted file mode 100644 index 03e6d87f6..000000000 --- a/src/apis/platformvm/addsubnetvalidatortx.ts +++ /dev/null @@ -1,296 +0,0 @@ -/** - * @packageDocumentation - * @module API-PlatformVM-AddSubnetValidatorTx - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { PlatformVMConstants } from "./constants" -import { TransferableOutput } from "./outputs" -import { TransferableInput } from "./inputs" -import { Credential, SigIdx, Signature } from "../../common/credentials" -import { BaseTx } from "./basetx" -import { DefaultNetworkID } from "../../utils/constants" -import { Serialization, SerializedEncoding } from "../../utils/serialization" -import { SelectCredentialClass, SubnetAuth } from "." -import { KeyChain, KeyPair } from "./keychain" -import BN from "bn.js" -import { bufferToNodeIDString } from "../../utils" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Class representing an unsigned AddSubnetValidatorTx transaction. - */ -export class AddSubnetValidatorTx extends BaseTx { - protected _typeName = "AddSubnetValidatorTx" - protected _typeID = PlatformVMConstants.ADDSUBNETVALIDATORTX - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - subnetID: serialization.encoder(this.subnetID, encoding, "Buffer", "cb58") - // exportOuts: this.exportOuts.map((e) => e.serialize(encoding)) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.subnetID = serialization.decoder( - fields["subnetID"], - encoding, - "cb58", - "Buffer", - 32 - ) - // this.exportOuts = fields["exportOuts"].map((e: object) => { - // let eo: TransferableOutput = new TransferableOutput() - // eo.deserialize(e, encoding) - // return eo - // }) - } - - protected nodeID: Buffer = Buffer.alloc(20) - protected startTime: Buffer = Buffer.alloc(8) - protected endTime: Buffer = Buffer.alloc(8) - protected weight: Buffer = Buffer.alloc(8) - protected subnetID: Buffer = Buffer.alloc(32) - protected subnetAuth: SubnetAuth - protected sigCount: Buffer = Buffer.alloc(4) - protected sigIdxs: SigIdx[] = [] // idxs of subnet auth signers - - /** - * Returns the id of the [[AddSubnetValidatorTx]] - */ - getTxType(): number { - return PlatformVMConstants.ADDSUBNETVALIDATORTX - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} for the stake amount. - */ - getNodeID(): Buffer { - return this.nodeID - } - - /** - * Returns a string for the nodeID amount. - */ - getNodeIDString(): string { - return bufferToNodeIDString(this.nodeID) - } - - /** - * Returns a {@link https://github.com/indutny/bn.js/|BN} for the startTime. - */ - getStartTime(): BN { - return bintools.fromBufferToBN(this.startTime) - } - - /** - * Returns a {@link https://github.com/indutny/bn.js/|BN} for the endTime. - */ - getEndTime(): BN { - return bintools.fromBufferToBN(this.endTime) - } - - /** - * Returns a {@link https://github.com/indutny/bn.js/|BN} for the weight - */ - getWeight(): BN { - return bintools.fromBufferToBN(this.weight) - } - - /** - * Returns the subnetID as a string - */ - getSubnetID(): string { - return bintools.cb58Encode(this.subnetID) - } - /** - * Returns the subnetAuth - */ - getSubnetAuth(): SubnetAuth { - return this.subnetAuth - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[AddSubnetValidatorTx]], parses it, populates the class, and returns the length of the [[CreateChainTx]] in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[AddSubnetValidatorTx]] - * - * @returns The length of the raw [[AddSubnetValidatorTx]] - * - * @remarks assume not-checksummed - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - - this.nodeID = bintools.copyFrom(bytes, offset, offset + 20) - offset += 20 - - this.startTime = bintools.copyFrom(bytes, offset, offset + 8) - offset += 8 - - this.endTime = bintools.copyFrom(bytes, offset, offset + 8) - offset += 8 - - this.weight = bintools.copyFrom(bytes, offset, offset + 8) - offset += 8 - - this.subnetID = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - - const sa: SubnetAuth = new SubnetAuth() - offset += sa.fromBuffer(bintools.copyFrom(bytes, offset)) - this.subnetAuth = sa - - return offset - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[CreateChainTx]]. - */ - toBuffer(): Buffer { - const superbuff: Buffer = super.toBuffer() - - const bsize: number = - superbuff.length + - this.nodeID.length + - this.startTime.length + - this.endTime.length + - this.weight.length + - this.subnetID.length + - this.subnetAuth.toBuffer().length - - const barr: Buffer[] = [ - superbuff, - this.nodeID, - this.startTime, - this.endTime, - this.weight, - this.subnetID, - this.subnetAuth.toBuffer() - ] - return Buffer.concat(barr, bsize) - } - - clone(): this { - const newAddSubnetValidatorTx: AddSubnetValidatorTx = - new AddSubnetValidatorTx() - newAddSubnetValidatorTx.fromBuffer(this.toBuffer()) - return newAddSubnetValidatorTx as this - } - - create(...args: any[]): this { - return new AddSubnetValidatorTx(...args) as this - } - - /** - * Creates and adds a [[SigIdx]] to the [[AddSubnetValidatorTx]]. - * - * @param addressIdx The index of the address to reference in the signatures - * @param address The address of the source of the signature - */ - addSignatureIdx(addressIdx: number, address: Buffer): void { - const addressIndex: Buffer = Buffer.alloc(4) - addressIndex.writeUIntBE(addressIdx, 0, 4) - this.subnetAuth.addAddressIndex(addressIndex) - - const sigidx: SigIdx = new SigIdx() - const b: Buffer = Buffer.alloc(4) - b.writeUInt32BE(addressIdx, 0) - sigidx.fromBuffer(b) - sigidx.setSource(address) - this.sigIdxs.push(sigidx) - this.sigCount.writeUInt32BE(this.sigIdxs.length, 0) - } - - /** - * Returns the array of [[SigIdx]] for this [[Input]] - */ - getSigIdxs(): SigIdx[] { - return this.sigIdxs - } - - getCredentialID(): number { - return PlatformVMConstants.SECPCREDENTIAL - } - - /** - * Takes the bytes of an [[UnsignedTx]] and returns an array of [[Credential]]s - * - * @param msg A Buffer for the [[UnsignedTx]] - * @param kc An [[KeyChain]] used in signing - * - * @returns An array of [[Credential]]s - */ - sign(msg: Buffer, kc: KeyChain): Credential[] { - const creds: Credential[] = super.sign(msg, kc) - const sigidxs: SigIdx[] = this.getSigIdxs() - const cred: Credential = SelectCredentialClass(this.getCredentialID()) - for (let i: number = 0; i < sigidxs.length; i++) { - const keypair: KeyPair = kc.getKey(sigidxs[`${i}`].getSource()) - const signval: Buffer = keypair.sign(msg) - const sig: Signature = new Signature() - sig.fromBuffer(signval) - cred.addSignature(sig) - } - creds.push(cred) - return creds - } - - /** - * Class representing an unsigned AddSubnetValidator transaction. - * - * @param networkID Optional networkID, [[DefaultNetworkID]] - * @param blockchainID Optional blockchainID, default Buffer.alloc(32, 16) - * @param outs Optional array of the [[TransferableOutput]]s - * @param ins Optional array of the [[TransferableInput]]s - * @param memo Optional {@link https://github.com/feross/buffer|Buffer} for the memo field - * @param nodeID Optional. The node ID of the validator being added. - * @param startTime Optional. The Unix time when the validator starts validating the Primary Network. - * @param endTime Optional. The Unix time when the validator stops validating the Primary Network (and staked AVAX is returned). - * @param weight Optional. Weight of this validator used when sampling - * @param subnetID Optional. ID of the subnet this validator is validating - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: Buffer = Buffer.alloc(32, 16), - outs: TransferableOutput[] = undefined, - ins: TransferableInput[] = undefined, - memo: Buffer = undefined, - nodeID: Buffer = undefined, - startTime: BN = undefined, - endTime: BN = undefined, - weight: BN = undefined, - subnetID: string | Buffer = undefined - ) { - super(networkID, blockchainID, outs, ins, memo) - if (typeof subnetID != "undefined") { - if (typeof subnetID === "string") { - this.subnetID = bintools.cb58Decode(subnetID) - } else { - this.subnetID = subnetID - } - } - if (typeof nodeID != "undefined") { - this.nodeID = nodeID - } - if (typeof startTime != "undefined") { - this.startTime = bintools.fromBNToBuffer(startTime, 8) - } - if (typeof endTime != "undefined") { - this.endTime = bintools.fromBNToBuffer(endTime, 8) - } - if (typeof weight != "undefined") { - this.weight = bintools.fromBNToBuffer(weight, 8) - } - - const subnetAuth: SubnetAuth = new SubnetAuth() - this.subnetAuth = subnetAuth - } -} diff --git a/src/apis/platformvm/api.ts b/src/apis/platformvm/api.ts deleted file mode 100644 index 9fcf2d304..000000000 --- a/src/apis/platformvm/api.ts +++ /dev/null @@ -1,2014 +0,0 @@ -/** - * @packageDocumentation - * @module API-PlatformVM - */ -import { Buffer } from "buffer/" -import BN from "bn.js" -import AvalancheCore from "../../avalanche" -import { JRPCAPI } from "../../common/jrpcapi" -import { RequestResponseData } from "../../common/apibase" -import { - ErrorResponseObject, - SubnetOwnerError, - SubnetThresholdError -} from "../../utils/errors" -import BinTools from "../../utils/bintools" -import { KeyChain } from "./keychain" -import { Defaults, PlatformChainID, ONEAVAX } from "../../utils/constants" -import { PlatformVMConstants } from "./constants" -import { UnsignedTx, Tx } from "./tx" -import { PayloadBase } from "../../utils/payload" -import { UnixNow, NodeIDStringToBuffer } from "../../utils/helperfunctions" -import { UTXO, UTXOSet } from "../platformvm/utxos" -import { PersistanceOptions } from "../../utils/persistenceoptions" -import { - AddressError, - TransactionError, - ChainIdError, - GooseEggCheckError, - TimeError, - StakeError, - DelegationFeeError -} from "../../utils/errors" -import { - GetCurrentValidatorsParams, - GetPendingValidatorsParams, - GetRewardUTXOsParams, - GetRewardUTXOsResponse, - GetStakeParams, - GetStakeResponse, - Subnet, - GetValidatorsAtParams, - GetValidatorsAtResponse, - CreateAddressParams, - GetUTXOsParams, - GetBalanceResponse, - GetUTXOsResponse, - ListAddressesParams, - SampleValidatorsParams, - AddValidatorParams, - AddDelegatorParams, - CreateSubnetParams, - ExportAVAXParams, - ExportKeyParams, - ImportKeyParams, - ImportAVAXParams, - CreateBlockchainParams, - Blockchain, - GetTxStatusParams, - GetTxStatusResponse, - GetMinStakeResponse, - GetMaxStakeAmountParams -} from "./interfaces" -import { TransferableOutput } from "./outputs" -import { Serialization, SerializedType } from "../../utils" -import { SubnetAuth } from "." -import { GenesisData } from "../avm" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Class for interacting with a node's PlatformVMAPI - * - * @category RPCAPIs - * - * @remarks This extends the [[JRPCAPI]] class. This class should not be directly called. Instead, use the [[Avalanche.addAPI]] function to register this interface with Avalanche. - */ -export class PlatformVMAPI extends JRPCAPI { - /** - * @ignore - */ - protected keychain: KeyChain = new KeyChain("", "") - - protected blockchainID: string = PlatformChainID - - protected blockchainAlias: string = undefined - - protected AVAXAssetID: Buffer = undefined - - protected txFee: BN = undefined - - protected creationTxFee: BN = undefined - - protected minValidatorStake: BN = undefined - - protected minDelegatorStake: BN = undefined - - /** - * Gets the alias for the blockchainID if it exists, otherwise returns `undefined`. - * - * @returns The alias for the blockchainID - */ - getBlockchainAlias = (): string => { - if (typeof this.blockchainAlias === "undefined") { - const netid: number = this.core.getNetworkID() - if ( - netid in Defaults.network && - this.blockchainID in Defaults.network[`${netid}`] - ) { - this.blockchainAlias = - Defaults.network[`${netid}`][this.blockchainID]["alias"] - return this.blockchainAlias - } else { - /* istanbul ignore next */ - return undefined - } - } - return this.blockchainAlias - } - - /** - * Sets the alias for the blockchainID. - * - * @param alias The alias for the blockchainID. - * - */ - setBlockchainAlias = (alias: string): string => { - this.blockchainAlias = alias - /* istanbul ignore next */ - return undefined - } - - /** - * Gets the blockchainID and returns it. - * - * @returns The blockchainID - */ - getBlockchainID = (): string => this.blockchainID - - /** - * Refresh blockchainID, and if a blockchainID is passed in, use that. - * - * @param Optional. BlockchainID to assign, if none, uses the default based on networkID. - * - * @returns The blockchainID - */ - refreshBlockchainID = (blockchainID: string = undefined): boolean => { - const netid: number = this.core.getNetworkID() - if ( - typeof blockchainID === "undefined" && - typeof Defaults.network[`${netid}`] !== "undefined" - ) { - this.blockchainID = PlatformChainID //default to P-Chain - return true - } - if (typeof blockchainID === "string") { - this.blockchainID = blockchainID - return true - } - return false - } - - /** - * Takes an address string and returns its {@link https://github.com/feross/buffer|Buffer} representation if valid. - * - * @returns A {@link https://github.com/feross/buffer|Buffer} for the address if valid, undefined if not valid. - */ - parseAddress = (addr: string): Buffer => { - const alias: string = this.getBlockchainAlias() - const blockchainID: string = this.getBlockchainID() - return bintools.parseAddress( - addr, - blockchainID, - alias, - PlatformVMConstants.ADDRESSLENGTH - ) - } - - addressFromBuffer = (address: Buffer): string => { - const chainid: string = this.getBlockchainAlias() - ? this.getBlockchainAlias() - : this.getBlockchainID() - const type: SerializedType = "bech32" - return serialization.bufferToType( - address, - type, - this.core.getHRP(), - chainid - ) - } - - /** - * Fetches the AVAX AssetID and returns it in a Promise. - * - * @param refresh This function caches the response. Refresh = true will bust the cache. - * - * @returns The the provided string representing the AVAX AssetID - */ - getAVAXAssetID = async (refresh: boolean = false): Promise => { - if (typeof this.AVAXAssetID === "undefined" || refresh) { - const assetID: string = await this.getStakingAssetID() - this.AVAXAssetID = bintools.cb58Decode(assetID) - } - return this.AVAXAssetID - } - - /** - * Overrides the defaults and sets the cache to a specific AVAX AssetID - * - * @param avaxAssetID A cb58 string or Buffer representing the AVAX AssetID - * - * @returns The the provided string representing the AVAX AssetID - */ - setAVAXAssetID = (avaxAssetID: string | Buffer) => { - if (typeof avaxAssetID === "string") { - avaxAssetID = bintools.cb58Decode(avaxAssetID) - } - this.AVAXAssetID = avaxAssetID - } - - /** - * Gets the default tx fee for this chain. - * - * @returns The default tx fee as a {@link https://github.com/indutny/bn.js/|BN} - */ - getDefaultTxFee = (): BN => { - return this.core.getNetworkID() in Defaults.network - ? new BN(Defaults.network[this.core.getNetworkID()]["P"]["txFee"]) - : new BN(0) - } - - /** - * Gets the tx fee for this chain. - * - * @returns The tx fee as a {@link https://github.com/indutny/bn.js/|BN} - */ - getTxFee = (): BN => { - if (typeof this.txFee === "undefined") { - this.txFee = this.getDefaultTxFee() - } - return this.txFee - } - - /** - * Gets the CreateSubnetTx fee. - * - * @returns The CreateSubnetTx fee as a {@link https://github.com/indutny/bn.js/|BN} - */ - getCreateSubnetTxFee = (): BN => { - return this.core.getNetworkID() in Defaults.network - ? new BN( - Defaults.network[this.core.getNetworkID()]["P"]["createSubnetTx"] - ) - : new BN(0) - } - - /** - * Gets the CreateChainTx fee. - * - * @returns The CreateChainTx fee as a {@link https://github.com/indutny/bn.js/|BN} - */ - getCreateChainTxFee = (): BN => { - return this.core.getNetworkID() in Defaults.network - ? new BN(Defaults.network[this.core.getNetworkID()]["P"]["createChainTx"]) - : new BN(0) - } - - /** - * Sets the tx fee for this chain. - * - * @param fee The tx fee amount to set as {@link https://github.com/indutny/bn.js/|BN} - */ - setTxFee = (fee: BN) => { - this.txFee = fee - } - - /** - * Gets the default creation fee for this chain. - * - * @returns The default creation fee as a {@link https://github.com/indutny/bn.js/|BN} - */ - getDefaultCreationTxFee = (): BN => { - return this.core.getNetworkID() in Defaults.network - ? new BN(Defaults.network[this.core.getNetworkID()]["P"]["creationTxFee"]) - : new BN(0) - } - - /** - * Gets the creation fee for this chain. - * - * @returns The creation fee as a {@link https://github.com/indutny/bn.js/|BN} - */ - getCreationTxFee = (): BN => { - if (typeof this.creationTxFee === "undefined") { - this.creationTxFee = this.getDefaultCreationTxFee() - } - return this.creationTxFee - } - - /** - * Sets the creation fee for this chain. - * - * @param fee The creation fee amount to set as {@link https://github.com/indutny/bn.js/|BN} - */ - setCreationTxFee = (fee: BN) => { - this.creationTxFee = fee - } - - /** - * Gets a reference to the keychain for this class. - * - * @returns The instance of [[]] for this class - */ - keyChain = (): KeyChain => this.keychain - - /** - * @ignore - */ - newKeyChain = (): KeyChain => { - // warning, overwrites the old keychain - const alias = this.getBlockchainAlias() - if (alias) { - this.keychain = new KeyChain(this.core.getHRP(), alias) - } else { - this.keychain = new KeyChain(this.core.getHRP(), this.blockchainID) - } - return this.keychain - } - - /** - * Helper function which determines if a tx is a goose egg transaction. - * - * @param utx An UnsignedTx - * - * @returns boolean true if passes goose egg test and false if fails. - * - * @remarks - * A "Goose Egg Transaction" is when the fee far exceeds a reasonable amount - */ - checkGooseEgg = async ( - utx: UnsignedTx, - outTotal: BN = new BN(0) - ): Promise => { - const avaxAssetID: Buffer = await this.getAVAXAssetID() - let outputTotal: BN = outTotal.gt(new BN(0)) - ? outTotal - : utx.getOutputTotal(avaxAssetID) - const fee: BN = utx.getBurn(avaxAssetID) - if (fee.lte(ONEAVAX.mul(new BN(10))) || fee.lte(outputTotal)) { - return true - } else { - return false - } - } - - /** - * Retrieves an assetID for a subnet"s staking assset. - * - * @returns Returns a Promise string with cb58 encoded value of the assetID. - */ - getStakingAssetID = async (): Promise => { - const response: RequestResponseData = await this.callMethod( - "platform.getStakingAssetID" - ) - return response.data.result.assetID - } - - /** - * Creates a new blockchain. - * - * @param username The username of the Keystore user that controls the new account - * @param password The password of the Keystore user that controls the new account - * @param subnetID Optional. Either a {@link https://github.com/feross/buffer|Buffer} or an cb58 serialized string for the SubnetID or its alias. - * @param vmID The ID of the Virtual Machine the blockchain runs. Can also be an alias of the Virtual Machine. - * @param fxIDs The ids of the FXs the VM is running. - * @param name A human-readable name for the new blockchain - * @param genesis The base 58 (with checksum) representation of the genesis state of the new blockchain. Virtual Machines should have a static API method named buildGenesis that can be used to generate genesisData. - * - * @returns Promise for the unsigned transaction to create this blockchain. Must be signed by a sufficient number of the Subnet’s control keys and by the account paying the transaction fee. - */ - createBlockchain = async ( - username: string, - password: string, - subnetID: Buffer | string = undefined, - vmID: string, - fxIDs: number[], - name: string, - genesis: string - ): Promise => { - const params: CreateBlockchainParams = { - username, - password, - fxIDs, - vmID, - name, - genesisData: genesis - } - if (typeof subnetID === "string") { - params.subnetID = subnetID - } else if (typeof subnetID !== "undefined") { - params.subnetID = bintools.cb58Encode(subnetID) - } - const response: RequestResponseData = await this.callMethod( - "platform.createBlockchain", - params - ) - return response.data.result.txID - } - - /** - * Gets the status of a blockchain. - * - * @param blockchainID The blockchainID requesting a status update - * - * @returns Promise for a string of one of: "Validating", "Created", "Preferred", "Unknown". - */ - getBlockchainStatus = async (blockchainID: string): Promise => { - const params: any = { - blockchainID - } - const response: RequestResponseData = await this.callMethod( - "platform.getBlockchainStatus", - params - ) - return response.data.result.status - } - - /** - * Get the validators and their weights of a subnet or the Primary Network at a given P-Chain height. - * - * @param height The P-Chain height to get the validator set at. - * @param subnetID Optional. A cb58 serialized string for the SubnetID or its alias. - * - * @returns Promise GetValidatorsAtResponse - */ - getValidatorsAt = async ( - height: number, - subnetID?: string - ): Promise => { - const params: GetValidatorsAtParams = { - height - } - if (typeof subnetID !== "undefined") { - params.subnetID = subnetID - } - const response: RequestResponseData = await this.callMethod( - "platform.getValidatorsAt", - params - ) - return response.data.result - } - - /** - * Create an address in the node's keystore. - * - * @param username The username of the Keystore user that controls the new account - * @param password The password of the Keystore user that controls the new account - * - * @returns Promise for a string of the newly created account address. - */ - createAddress = async ( - username: string, - password: string - ): Promise => { - const params: CreateAddressParams = { - username, - password - } - const response: RequestResponseData = await this.callMethod( - "platform.createAddress", - params - ) - return response.data.result.address - } - - /** - * Gets the balance of a particular asset. - * - * @param addresses The addresses to pull the asset balance from - * - * @returns Promise with the balance as a {@link https://github.com/indutny/bn.js/|BN} on the provided address. - */ - getBalance = async (addresses: string[]): Promise => { - addresses.forEach(address => { - if (typeof this.parseAddress(address) === "undefined") { - /* istanbul ignore next */ - throw new AddressError( - "Error - PlatformVMAPI.getBalance: Invalid address format" - ) - } - }) - const params: any = { - addresses - } - const response: RequestResponseData = await this.callMethod( - "platform.getBalance", - params - ) - return response.data.result - } - - /** - * List the addresses controlled by the user. - * - * @param username The username of the Keystore user - * @param password The password of the Keystore user - * - * @returns Promise for an array of addresses. - */ - listAddresses = async ( - username: string, - password: string - ): Promise => { - const params: ListAddressesParams = { - username, - password - } - const response: RequestResponseData = await this.callMethod( - "platform.listAddresses", - params - ) - return response.data.result.addresses - } - - /** - * Lists the set of current validators. - * - * @param subnetID Optional. Either a {@link https://github.com/feross/buffer|Buffer} or an - * cb58 serialized string for the SubnetID or its alias. - * @param nodeIDs Optional. An array of strings - * - * @returns Promise for an array of validators that are currently staking, see: {@link https://docs.avax.network/v1.0/en/api/platform/#platformgetcurrentvalidators|platform.getCurrentValidators documentation}. - * - */ - getCurrentValidators = async ( - subnetID: Buffer | string = undefined, - nodeIDs: string[] = undefined - ): Promise => { - const params: GetCurrentValidatorsParams = {} - if (typeof subnetID === "string") { - params.subnetID = subnetID - } else if (typeof subnetID !== "undefined") { - params.subnetID = bintools.cb58Encode(subnetID) - } - if (typeof nodeIDs != "undefined" && nodeIDs.length > 0) { - params.nodeIDs = nodeIDs - } - const response: RequestResponseData = await this.callMethod( - "platform.getCurrentValidators", - params - ) - return response.data.result - } - - /** - * Lists the set of pending validators. - * - * @param subnetID Optional. Either a {@link https://github.com/feross/buffer|Buffer} - * or a cb58 serialized string for the SubnetID or its alias. - * @param nodeIDs Optional. An array of strings - * - * @returns Promise for an array of validators that are pending staking, see: {@link https://docs.avax.network/v1.0/en/api/platform/#platformgetpendingvalidators|platform.getPendingValidators documentation}. - * - */ - getPendingValidators = async ( - subnetID: Buffer | string = undefined, - nodeIDs: string[] = undefined - ): Promise => { - const params: GetPendingValidatorsParams = {} - if (typeof subnetID === "string") { - params.subnetID = subnetID - } else if (typeof subnetID !== "undefined") { - params.subnetID = bintools.cb58Encode(subnetID) - } - if (typeof nodeIDs != "undefined" && nodeIDs.length > 0) { - params.nodeIDs = nodeIDs - } - - const response: RequestResponseData = await this.callMethod( - "platform.getPendingValidators", - params - ) - return response.data.result - } - - /** - * Samples `Size` validators from the current validator set. - * - * @param sampleSize Of the total universe of validators, select this many at random - * @param subnetID Optional. Either a {@link https://github.com/feross/buffer|Buffer} or an - * cb58 serialized string for the SubnetID or its alias. - * - * @returns Promise for an array of validator"s stakingIDs. - */ - sampleValidators = async ( - sampleSize: number, - subnetID: Buffer | string = undefined - ): Promise => { - const params: SampleValidatorsParams = { - size: sampleSize.toString() - } - if (typeof subnetID === "string") { - params.subnetID = subnetID - } else if (typeof subnetID !== "undefined") { - params.subnetID = bintools.cb58Encode(subnetID) - } - const response: RequestResponseData = await this.callMethod( - "platform.sampleValidators", - params - ) - return response.data.result.validators - } - - /** - * Add a validator to the Primary Network. - * - * @param username The username of the Keystore user - * @param password The password of the Keystore user - * @param nodeID The node ID of the validator - * @param startTime Javascript Date object for the start time to validate - * @param endTime Javascript Date object for the end time to validate - * @param stakeAmount The amount of nAVAX the validator is staking as - * a {@link https://github.com/indutny/bn.js/|BN} - * @param rewardAddress The address the validator reward will go to, if there is one. - * @param delegationFeeRate Optional. A {@link https://github.com/indutny/bn.js/|BN} for the percent fee this validator - * charges when others delegate stake to them. Up to 4 decimal places allowed additional decimal places are ignored. - * Must be between 0 and 100, inclusive. For example, if delegationFeeRate is 1.2345 and someone delegates to this - * validator, then when the delegation period is over, 1.2345% of the reward goes to the validator and the rest goes - * to the delegator. - * - * @returns Promise for a base58 string of the unsigned transaction. - */ - addValidator = async ( - username: string, - password: string, - nodeID: string, - startTime: Date, - endTime: Date, - stakeAmount: BN, - rewardAddress: string, - delegationFeeRate: BN = undefined - ): Promise => { - const params: AddValidatorParams = { - username, - password, - nodeID, - startTime: startTime.getTime() / 1000, - endTime: endTime.getTime() / 1000, - stakeAmount: stakeAmount.toString(10), - rewardAddress - } - if (typeof delegationFeeRate !== "undefined") { - params.delegationFeeRate = delegationFeeRate.toString(10) - } - const response: RequestResponseData = await this.callMethod( - "platform.addValidator", - params - ) - return response.data.result.txID - } - - /** - * Add a validator to a Subnet other than the Primary Network. The validator must validate the Primary Network for the entire duration they validate this Subnet. - * - * @param username The username of the Keystore user - * @param password The password of the Keystore user - * @param nodeID The node ID of the validator - * @param subnetID Either a {@link https://github.com/feross/buffer|Buffer} or a cb58 serialized string for the SubnetID or its alias. - * @param startTime Javascript Date object for the start time to validate - * @param endTime Javascript Date object for the end time to validate - * @param weight The validator’s weight used for sampling - * - * @returns Promise for the unsigned transaction. It must be signed (using sign) by the proper number of the Subnet’s control keys and by the key of the account paying the transaction fee before it can be issued. - */ - addSubnetValidator = async ( - username: string, - password: string, - nodeID: string, - subnetID: Buffer | string, - startTime: Date, - endTime: Date, - weight: number - ): Promise => { - const params: any = { - username, - password, - nodeID, - startTime: startTime.getTime() / 1000, - endTime: endTime.getTime() / 1000, - weight - } - if (typeof subnetID === "string") { - params.subnetID = subnetID - } else if (typeof subnetID !== "undefined") { - params.subnetID = bintools.cb58Encode(subnetID) - } - const response: RequestResponseData = await this.callMethod( - "platform.addSubnetValidator", - params - ) - return response.data.result.txID - } - - /** - * Add a delegator to the Primary Network. - * - * @param username The username of the Keystore user - * @param password The password of the Keystore user - * @param nodeID The node ID of the delegatee - * @param startTime Javascript Date object for when the delegator starts delegating - * @param endTime Javascript Date object for when the delegator starts delegating - * @param stakeAmount The amount of nAVAX the delegator is staking as - * a {@link https://github.com/indutny/bn.js/|BN} - * @param rewardAddress The address of the account the staked AVAX and validation reward - * (if applicable) are sent to at endTime - * - * @returns Promise for an array of validator"s stakingIDs. - */ - addDelegator = async ( - username: string, - password: string, - nodeID: string, - startTime: Date, - endTime: Date, - stakeAmount: BN, - rewardAddress: string - ): Promise => { - const params: AddDelegatorParams = { - username, - password, - nodeID, - startTime: startTime.getTime() / 1000, - endTime: endTime.getTime() / 1000, - stakeAmount: stakeAmount.toString(10), - rewardAddress - } - const response: RequestResponseData = await this.callMethod( - "platform.addDelegator", - params - ) - return response.data.result.txID - } - - /** - * Create an unsigned transaction to create a new Subnet. The unsigned transaction must be - * signed with the key of the account paying the transaction fee. The Subnet’s ID is the ID of the transaction that creates it (ie the response from issueTx when issuing the signed transaction). - * - * @param username The username of the Keystore user - * @param password The password of the Keystore user - * @param controlKeys Array of platform addresses as strings - * @param threshold To add a validator to this Subnet, a transaction must have threshold - * signatures, where each signature is from a key whose address is an element of `controlKeys` - * - * @returns Promise for a string with the unsigned transaction encoded as base58. - */ - createSubnet = async ( - username: string, - password: string, - controlKeys: string[], - threshold: number - ): Promise => { - const params: CreateSubnetParams = { - username, - password, - controlKeys, - threshold - } - const response: RequestResponseData = await this.callMethod( - "platform.createSubnet", - params - ) - return response.data.result.txID - ? response.data.result.txID - : response.data.result - } - - /** - * Get the Subnet that validates a given blockchain. - * - * @param blockchainID Either a {@link https://github.com/feross/buffer|Buffer} or a cb58 - * encoded string for the blockchainID or its alias. - * - * @returns Promise for a string of the subnetID that validates the blockchain. - */ - validatedBy = async (blockchainID: string): Promise => { - const params: any = { - blockchainID - } - const response: RequestResponseData = await this.callMethod( - "platform.validatedBy", - params - ) - return response.data.result.subnetID - } - - /** - * Get the IDs of the blockchains a Subnet validates. - * - * @param subnetID Either a {@link https://github.com/feross/buffer|Buffer} or an AVAX - * serialized string for the SubnetID or its alias. - * - * @returns Promise for an array of blockchainIDs the subnet validates. - */ - validates = async (subnetID: Buffer | string): Promise => { - const params: any = { - subnetID - } - if (typeof subnetID === "string") { - params.subnetID = subnetID - } else if (typeof subnetID !== "undefined") { - params.subnetID = bintools.cb58Encode(subnetID) - } - const response: RequestResponseData = await this.callMethod( - "platform.validates", - params - ) - return response.data.result.blockchainIDs - } - - /** - * Get all the blockchains that exist (excluding the P-Chain). - * - * @returns Promise for an array of objects containing fields "id", "subnetID", and "vmID". - */ - getBlockchains = async (): Promise => { - const response: RequestResponseData = await this.callMethod( - "platform.getBlockchains" - ) - return response.data.result.blockchains - } - - /** - * Send AVAX from an account on the P-Chain to an address on the X-Chain. This transaction - * must be signed with the key of the account that the AVAX is sent from and which pays the - * transaction fee. After issuing this transaction, you must call the X-Chain’s importAVAX - * method to complete the transfer. - * - * @param username The Keystore user that controls the account specified in `to` - * @param password The password of the Keystore user - * @param to The address on the X-Chain to send the AVAX to. Do not include X- in the address - * @param amount Amount of AVAX to export as a {@link https://github.com/indutny/bn.js/|BN} - * - * @returns Promise for an unsigned transaction to be signed by the account the the AVAX is - * sent from and pays the transaction fee. - */ - exportAVAX = async ( - username: string, - password: string, - amount: BN, - to: string - ): Promise => { - const params: ExportAVAXParams = { - username, - password, - to, - amount: amount.toString(10) - } - const response: RequestResponseData = await this.callMethod( - "platform.exportAVAX", - params - ) - return response.data.result.txID - ? response.data.result.txID - : response.data.result - } - - /** - * Send AVAX from an account on the P-Chain to an address on the X-Chain. This transaction - * must be signed with the key of the account that the AVAX is sent from and which pays - * the transaction fee. After issuing this transaction, you must call the X-Chain’s - * importAVAX method to complete the transfer. - * - * @param username The Keystore user that controls the account specified in `to` - * @param password The password of the Keystore user - * @param to The ID of the account the AVAX is sent to. This must be the same as the to - * argument in the corresponding call to the X-Chain’s exportAVAX - * @param sourceChain The chainID where the funds are coming from. - * - * @returns Promise for a string for the transaction, which should be sent to the network - * by calling issueTx. - */ - importAVAX = async ( - username: string, - password: string, - to: string, - sourceChain: string - ): Promise => { - const params: ImportAVAXParams = { - to, - sourceChain, - username, - password - } - const response: RequestResponseData = await this.callMethod( - "platform.importAVAX", - params - ) - return response.data.result.txID - ? response.data.result.txID - : response.data.result - } - - /** - * Calls the node's issueTx method from the API and returns the resulting transaction ID as a string. - * - * @param tx A string, {@link https://github.com/feross/buffer|Buffer}, or [[Tx]] representing a transaction - * - * @returns A Promise string representing the transaction ID of the posted transaction. - */ - issueTx = async (tx: string | Buffer | Tx): Promise => { - let Transaction = "" - if (typeof tx === "string") { - Transaction = tx - } else if (tx instanceof Buffer) { - const txobj: Tx = new Tx() - txobj.fromBuffer(tx) - Transaction = txobj.toStringHex() - } else if (tx instanceof Tx) { - Transaction = tx.toStringHex() - } else { - /* istanbul ignore next */ - throw new TransactionError( - "Error - platform.issueTx: provided tx is not expected type of string, Buffer, or Tx" - ) - } - const params: any = { - tx: Transaction.toString(), - encoding: "hex" - } - const response: RequestResponseData = await this.callMethod( - "platform.issueTx", - params - ) - return response.data.result.txID - } - - /** - * Returns an upper bound on the amount of tokens that exist. Not monotonically increasing because this number can go down if a staker"s reward is denied. - */ - getCurrentSupply = async (): Promise => { - const response: RequestResponseData = await this.callMethod( - "platform.getCurrentSupply" - ) - return new BN(response.data.result.supply, 10) - } - - /** - * Returns the height of the platform chain. - */ - getHeight = async (): Promise => { - const response: RequestResponseData = await this.callMethod( - "platform.getHeight" - ) - return new BN(response.data.result.height, 10) - } - - /** - * Gets the minimum staking amount. - * - * @param refresh A boolean to bypass the local cached value of Minimum Stake Amount, polling the node instead. - */ - getMinStake = async ( - refresh: boolean = false - ): Promise => { - if ( - refresh !== true && - typeof this.minValidatorStake !== "undefined" && - typeof this.minDelegatorStake !== "undefined" - ) { - return { - minValidatorStake: this.minValidatorStake, - minDelegatorStake: this.minDelegatorStake - } - } - const response: RequestResponseData = await this.callMethod( - "platform.getMinStake" - ) - this.minValidatorStake = new BN(response.data.result.minValidatorStake, 10) - this.minDelegatorStake = new BN(response.data.result.minDelegatorStake, 10) - return { - minValidatorStake: this.minValidatorStake, - minDelegatorStake: this.minDelegatorStake - } - } - - /** - * getTotalStake() returns the total amount staked on the Primary Network - * - * @returns A big number representing total staked by validators on the primary network - */ - getTotalStake = async (): Promise => { - const response: RequestResponseData = await this.callMethod( - "platform.getTotalStake" - ) - return new BN(response.data.result.stake, 10) - } - - /** - * getMaxStakeAmount() returns the maximum amount of nAVAX staking to the named node during the time period. - * - * @param subnetID A Buffer or cb58 string representing subnet - * @param nodeID A string representing ID of the node whose stake amount is required during the given duration - * @param startTime A big number denoting start time of the duration during which stake amount of the node is required. - * @param endTime A big number denoting end time of the duration during which stake amount of the node is required. - * @returns A big number representing total staked by validators on the primary network - */ - getMaxStakeAmount = async ( - subnetID: string | Buffer, - nodeID: string, - startTime: BN, - endTime: BN - ): Promise => { - const now: BN = UnixNow() - if (startTime.gt(now) || endTime.lte(startTime)) { - throw new TimeError( - "PlatformVMAPI.getMaxStakeAmount -- startTime must be in the past and endTime must come after startTime" - ) - } - - const params: GetMaxStakeAmountParams = { - nodeID, - startTime, - endTime - } - - if (typeof subnetID === "string") { - params.subnetID = subnetID - } else if (typeof subnetID !== "undefined") { - params.subnetID = bintools.cb58Encode(subnetID) - } - - const response: RequestResponseData = await this.callMethod( - "platform.getMaxStakeAmount", - params - ) - return new BN(response.data.result.amount, 10) - } - - /** - * Sets the minimum stake cached in this class. - * @param minValidatorStake A {@link https://github.com/indutny/bn.js/|BN} to set the minimum stake amount cached in this class. - * @param minDelegatorStake A {@link https://github.com/indutny/bn.js/|BN} to set the minimum delegation amount cached in this class. - */ - setMinStake = ( - minValidatorStake: BN = undefined, - minDelegatorStake: BN = undefined - ): void => { - if (typeof minValidatorStake !== "undefined") { - this.minValidatorStake = minValidatorStake - } - if (typeof minDelegatorStake !== "undefined") { - this.minDelegatorStake = minDelegatorStake - } - } - - /** - * Gets the total amount staked for an array of addresses. - */ - getStake = async ( - addresses: string[], - encoding: string = "hex" - ): Promise => { - const params: GetStakeParams = { - addresses, - encoding - } - const response: RequestResponseData = await this.callMethod( - "platform.getStake", - params - ) - return { - staked: new BN(response.data.result.staked, 10), - stakedOutputs: response.data.result.stakedOutputs.map( - (stakedOutput: string): TransferableOutput => { - const transferableOutput: TransferableOutput = - new TransferableOutput() - let buf: Buffer - if (encoding === "cb58") { - buf = bintools.cb58Decode(stakedOutput) - } else { - buf = Buffer.from(stakedOutput.replace(/0x/g, ""), "hex") - } - transferableOutput.fromBuffer(buf, 2) - return transferableOutput - } - ) - } - } - - /** - * Get all the subnets that exist. - * - * @param ids IDs of the subnets to retrieve information about. If omitted, gets all subnets - * - * @returns Promise for an array of objects containing fields "id", - * "controlKeys", and "threshold". - */ - getSubnets = async (ids: string[] = undefined): Promise => { - const params: any = {} - if (typeof ids !== undefined) { - params.ids = ids - } - const response: RequestResponseData = await this.callMethod( - "platform.getSubnets", - params - ) - return response.data.result.subnets - } - - /** - * Exports the private key for an address. - * - * @param username The name of the user with the private key - * @param password The password used to decrypt the private key - * @param address The address whose private key should be exported - * - * @returns Promise with the decrypted private key as store in the database - */ - exportKey = async ( - username: string, - password: string, - address: string - ): Promise => { - const params: ExportKeyParams = { - username, - password, - address - } - const response: RequestResponseData = await this.callMethod( - "platform.exportKey", - params - ) - return response.data.result.privateKey - ? response.data.result.privateKey - : response.data.result - } - - /** - * Give a user control over an address by providing the private key that controls the address. - * - * @param username The name of the user to store the private key - * @param password The password that unlocks the user - * @param privateKey A string representing the private key in the vm"s format - * - * @returns The address for the imported private key. - */ - importKey = async ( - username: string, - password: string, - privateKey: string - ): Promise => { - const params: ImportKeyParams = { - username, - password, - privateKey - } - const response: RequestResponseData = await this.callMethod( - "platform.importKey", - params - ) - - return response.data.result.address - ? response.data.result.address - : response.data.result - } - - /** - * Returns the treansaction data of a provided transaction ID by calling the node's `getTx` method. - * - * @param txID The string representation of the transaction ID - * @param encoding sets the format of the returned transaction. Can be, "cb58", "hex" or "json". Defaults to "cb58". - * - * @returns Returns a Promise string or object containing the bytes retrieved from the node - */ - getTx = async ( - txID: string, - encoding: string = "hex" - ): Promise => { - const params: any = { - txID, - encoding - } - const response: RequestResponseData = await this.callMethod( - "platform.getTx", - params - ) - return response.data.result.tx - ? response.data.result.tx - : response.data.result - } - - /** - * Returns the status of a provided transaction ID by calling the node's `getTxStatus` method. - * - * @param txid The string representation of the transaction ID - * @param includeReason Return the reason tx was dropped, if applicable. Defaults to true - * - * @returns Returns a Promise string containing the status retrieved from the node and the reason a tx was dropped, if applicable. - */ - getTxStatus = async ( - txid: string, - includeReason: boolean = true - ): Promise => { - const params: GetTxStatusParams = { - txID: txid, - includeReason: includeReason - } - const response: RequestResponseData = await this.callMethod( - "platform.getTxStatus", - params - ) - return response.data.result - } - - /** - * Retrieves the UTXOs related to the addresses provided from the node's `getUTXOs` method. - * - * @param addresses An array of addresses as cb58 strings or addresses as {@link https://github.com/feross/buffer|Buffer}s - * @param sourceChain A string for the chain to look for the UTXO"s. Default is to use this chain, but if exported UTXOs exist from other chains, this can used to pull them instead. - * @param limit Optional. Returns at most [limit] addresses. If [limit] == 0 or > [maxUTXOsToFetch], fetches up to [maxUTXOsToFetch]. - * @param startIndex Optional. [StartIndex] defines where to start fetching UTXOs (for pagination.) - * UTXOs fetched are from addresses equal to or greater than [StartIndex.Address] - * For address [StartIndex.Address], only UTXOs with IDs greater than [StartIndex.Utxo] will be returned. - * @param persistOpts Options available to persist these UTXOs in local storage - * @param encoding Optional. is the encoding format to use for the payload argument. Can be either "cb58" or "hex". Defaults to "hex". - * - * @remarks - * persistOpts is optional and must be of type [[PersistanceOptions]] - * - */ - getUTXOs = async ( - addresses: string[] | string, - sourceChain: string = undefined, - limit: number = 0, - startIndex: { address: string; utxo: string } = undefined, - persistOpts: PersistanceOptions = undefined, - encoding: string = "hex" - ): Promise => { - if (typeof addresses === "string") { - addresses = [addresses] - } - - const params: GetUTXOsParams = { - addresses: addresses, - limit, - encoding - } - if (typeof startIndex !== "undefined" && startIndex) { - params.startIndex = startIndex - } - - if (typeof sourceChain !== "undefined") { - params.sourceChain = sourceChain - } - - const response: RequestResponseData = await this.callMethod( - "platform.getUTXOs", - params - ) - - const utxos: UTXOSet = new UTXOSet() - let data = response.data.result.utxos - if (persistOpts && typeof persistOpts === "object") { - if (this.db.has(persistOpts.getName())) { - const selfArray: string[] = this.db.get(persistOpts.getName()) - if (Array.isArray(selfArray)) { - utxos.addArray(data) - const self: UTXOSet = new UTXOSet() - self.addArray(selfArray) - self.mergeByRule(utxos, persistOpts.getMergeRule()) - data = self.getAllUTXOStrings() - } - } - this.db.set(persistOpts.getName(), data, persistOpts.getOverwrite()) - } - - if (data.length > 0 && data[0].substring(0, 2) === "0x") { - const cb58Strs: string[] = [] - data.forEach((str: string): void => { - cb58Strs.push(bintools.cb58Encode(new Buffer(str.slice(2), "hex"))) - }) - - utxos.addArray(cb58Strs, false) - } else { - utxos.addArray(data, false) - } - response.data.result.utxos = utxos - response.data.result.numFetched = parseInt(response.data.result.numFetched) - return response.data.result - } - - /** - * Helper function which creates an unsigned Import Tx. For more granular control, you may create your own - * [[UnsignedTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s, and [[TransferOperation]]s). - * - * @param utxoset A set of UTXOs that the transaction is built on - * @param ownerAddresses The addresses being used to import - * @param sourceChain The chainid for where the import is coming from. - * @param toAddresses The addresses to send the funds - * @param fromAddresses The addresses being used to send the funds from the UTXOs provided - * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param locktime Optional. The locktime field created in the resulting outputs - * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO - * - * @returns An unsigned transaction ([[UnsignedTx]]) which contains a [[ImportTx]]. - * - * @remarks - * This helper exists because the endpoint API should be the primary point of entry for most functionality. - */ - buildImportTx = async ( - utxoset: UTXOSet, - ownerAddresses: string[], - sourceChain: Buffer | string, - toAddresses: string[], - fromAddresses: string[], - changeAddresses: string[] = undefined, - memo: PayloadBase | Buffer = undefined, - asOf: BN = UnixNow(), - locktime: BN = new BN(0), - threshold: number = 1 - ): Promise => { - const to: Buffer[] = this._cleanAddressArray( - toAddresses, - "buildImportTx" - ).map((a: string): Buffer => bintools.stringToAddress(a)) - const from: Buffer[] = this._cleanAddressArray( - fromAddresses, - "buildImportTx" - ).map((a: string): Buffer => bintools.stringToAddress(a)) - const change: Buffer[] = this._cleanAddressArray( - changeAddresses, - "buildImportTx" - ).map((a: string): Buffer => bintools.stringToAddress(a)) - - let srcChain: string = undefined - - if (typeof sourceChain === "undefined") { - throw new ChainIdError( - "Error - PlatformVMAPI.buildImportTx: Source ChainID is undefined." - ) - } else if (typeof sourceChain === "string") { - srcChain = sourceChain - sourceChain = bintools.cb58Decode(sourceChain) - } else if (!(sourceChain instanceof Buffer)) { - throw new ChainIdError( - "Error - PlatformVMAPI.buildImportTx: Invalid destinationChain type: " + - typeof sourceChain - ) - } - const atomicUTXOs: UTXOSet = await ( - await this.getUTXOs(ownerAddresses, srcChain, 0, undefined) - ).utxos - const avaxAssetID: Buffer = await this.getAVAXAssetID() - - if (memo instanceof PayloadBase) { - memo = memo.getPayload() - } - - const atomics: UTXO[] = atomicUTXOs.getAllUTXOs() - - const builtUnsignedTx: UnsignedTx = utxoset.buildImportTx( - this.core.getNetworkID(), - bintools.cb58Decode(this.blockchainID), - to, - from, - change, - atomics, - sourceChain, - this.getTxFee(), - avaxAssetID, - memo, - asOf, - locktime, - threshold - ) - - if (!(await this.checkGooseEgg(builtUnsignedTx))) { - /* istanbul ignore next */ - throw new GooseEggCheckError("Failed Goose Egg Check") - } - - return builtUnsignedTx - } - - /** - * Helper function which creates an unsigned Export Tx. For more granular control, you may create your own - * [[UnsignedTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s, and [[TransferOperation]]s). - * - * @param utxoset A set of UTXOs that the transaction is built on - * @param amount The amount being exported as a {@link https://github.com/indutny/bn.js/|BN} - * @param destinationChain The chainid for where the assets will be sent. - * @param toAddresses The addresses to send the funds - * @param fromAddresses The addresses being used to send the funds from the UTXOs provided - * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param locktime Optional. The locktime field created in the resulting outputs - * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO - * - * @returns An unsigned transaction ([[UnsignedTx]]) which contains an [[ExportTx]]. - */ - buildExportTx = async ( - utxoset: UTXOSet, - amount: BN, - destinationChain: Buffer | string, - toAddresses: string[], - fromAddresses: string[], - changeAddresses: string[] = undefined, - memo: PayloadBase | Buffer = undefined, - asOf: BN = UnixNow(), - locktime: BN = new BN(0), - threshold: number = 1 - ): Promise => { - let prefixes: object = {} - toAddresses.map((a: string): void => { - prefixes[a.split("-")[0]] = true - }) - if (Object.keys(prefixes).length !== 1) { - throw new AddressError( - "Error - PlatformVMAPI.buildExportTx: To addresses must have the same chainID prefix." - ) - } - - if (typeof destinationChain === "undefined") { - throw new ChainIdError( - "Error - PlatformVMAPI.buildExportTx: Destination ChainID is undefined." - ) - } else if (typeof destinationChain === "string") { - destinationChain = bintools.cb58Decode(destinationChain) // - } else if (!(destinationChain instanceof Buffer)) { - throw new ChainIdError( - "Error - PlatformVMAPI.buildExportTx: Invalid destinationChain type: " + - typeof destinationChain - ) - } - if (destinationChain.length !== 32) { - throw new ChainIdError( - "Error - PlatformVMAPI.buildExportTx: Destination ChainID must be 32 bytes in length." - ) - } - /* - if(bintools.cb58Encode(destinationChain) !== Defaults.network[this.core.getNetworkID()].X["blockchainID"]) { - throw new Error("Error - PlatformVMAPI.buildExportTx: Destination ChainID must The X-Chain ID in the current version of AvalancheJS.") - }*/ - - let to: Buffer[] = [] - toAddresses.map((a: string): void => { - to.push(bintools.stringToAddress(a)) - }) - const from: Buffer[] = this._cleanAddressArray( - fromAddresses, - "buildExportTx" - ).map((a): Buffer => bintools.stringToAddress(a)) - const change: Buffer[] = this._cleanAddressArray( - changeAddresses, - "buildExportTx" - ).map((a): Buffer => bintools.stringToAddress(a)) - - if (memo instanceof PayloadBase) { - memo = memo.getPayload() - } - - const avaxAssetID: Buffer = await this.getAVAXAssetID() - - const builtUnsignedTx: UnsignedTx = utxoset.buildExportTx( - this.core.getNetworkID(), - bintools.cb58Decode(this.blockchainID), - amount, - avaxAssetID, - to, - from, - change, - destinationChain, - this.getTxFee(), - avaxAssetID, - memo, - asOf, - locktime, - threshold - ) - - if (!(await this.checkGooseEgg(builtUnsignedTx))) { - /* istanbul ignore next */ - throw new GooseEggCheckError("Failed Goose Egg Check") - } - - return builtUnsignedTx - } - - /** - * Helper function which creates an unsigned [[AddSubnetValidatorTx]]. For more granular control, you may create your own - * [[UnsignedTx]] manually and import the [[AddSubnetValidatorTx]] class directly. - * - * @param utxoset A set of UTXOs that the transaction is built on. - * @param fromAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who pays the fees in AVAX - * @param changeAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who gets the change leftover from the fee payment - * @param nodeID The node ID of the validator being added. - * @param startTime The Unix time when the validator starts validating the Primary Network. - * @param endTime The Unix time when the validator stops validating the Primary Network (and staked AVAX is returned). - * @param weight The amount of weight for this subnet validator. - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param subnetAuthCredentials Optional. An array of index and address to sign for each SubnetAuth. - * - * @returns An unsigned transaction created from the passed in parameters. - */ - - buildAddSubnetValidatorTx = async ( - utxoset: UTXOSet, - fromAddresses: string[], - changeAddresses: string[], - nodeID: string, - startTime: BN, - endTime: BN, - weight: BN, - subnetID: string, - memo: PayloadBase | Buffer = undefined, - asOf: BN = UnixNow(), - subnetAuthCredentials: [number, Buffer][] = [] - ): Promise => { - const from: Buffer[] = this._cleanAddressArray( - fromAddresses, - "buildAddSubnetValidatorTx" - ).map((a: string): Buffer => bintools.stringToAddress(a)) - const change: Buffer[] = this._cleanAddressArray( - changeAddresses, - "buildAddSubnetValidatorTx" - ).map((a: string): Buffer => bintools.stringToAddress(a)) - - if (memo instanceof PayloadBase) { - memo = memo.getPayload() - } - - const avaxAssetID: Buffer = await this.getAVAXAssetID() - - const now: BN = UnixNow() - if (startTime.lt(now) || endTime.lte(startTime)) { - throw new Error( - "PlatformVMAPI.buildAddSubnetValidatorTx -- startTime must be in the future and endTime must come after startTime" - ) - } - - const builtUnsignedTx: UnsignedTx = utxoset.buildAddSubnetValidatorTx( - this.core.getNetworkID(), - bintools.cb58Decode(this.blockchainID), - from, - change, - NodeIDStringToBuffer(nodeID), - startTime, - endTime, - weight, - subnetID, - this.getDefaultTxFee(), - avaxAssetID, - memo, - asOf, - subnetAuthCredentials - ) - - if (!(await this.checkGooseEgg(builtUnsignedTx))) { - /* istanbul ignore next */ - throw new Error("Failed Goose Egg Check") - } - - return builtUnsignedTx - } - - /** - * Helper function which creates an unsigned [[AddDelegatorTx]]. For more granular control, you may create your own - * [[UnsignedTx]] manually and import the [[AddDelegatorTx]] class directly. - * - * @param utxoset A set of UTXOs that the transaction is built on - * @param toAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who received the staked tokens at the end of the staking period - * @param fromAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who own the staking UTXOs the fees in AVAX - * @param changeAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who gets the change leftover from the fee payment - * @param nodeID The node ID of the validator being added. - * @param startTime The Unix time when the validator starts validating the Primary Network. - * @param endTime The Unix time when the validator stops validating the Primary Network (and staked AVAX is returned). - * @param stakeAmount The amount being delegated as a {@link https://github.com/indutny/bn.js/|BN} - * @param rewardAddresses The addresses which will recieve the rewards from the delegated stake. - * @param rewardLocktime Optional. The locktime field created in the resulting reward outputs - * @param rewardThreshold Opional. The number of signatures required to spend the funds in the resultant reward UTXO. Default 1. - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * - * @returns An unsigned transaction created from the passed in parameters. - */ - buildAddDelegatorTx = async ( - utxoset: UTXOSet, - toAddresses: string[], - fromAddresses: string[], - changeAddresses: string[], - nodeID: string, - startTime: BN, - endTime: BN, - stakeAmount: BN, - rewardAddresses: string[], - rewardLocktime: BN = new BN(0), - rewardThreshold: number = 1, - memo: PayloadBase | Buffer = undefined, - asOf: BN = UnixNow() - ): Promise => { - const to: Buffer[] = this._cleanAddressArray( - toAddresses, - "buildAddDelegatorTx" - ).map((a: string): Buffer => bintools.stringToAddress(a)) - const from: Buffer[] = this._cleanAddressArray( - fromAddresses, - "buildAddDelegatorTx" - ).map((a: string): Buffer => bintools.stringToAddress(a)) - const change: Buffer[] = this._cleanAddressArray( - changeAddresses, - "buildAddDelegatorTx" - ).map((a: string): Buffer => bintools.stringToAddress(a)) - const rewards: Buffer[] = this._cleanAddressArray( - rewardAddresses, - "buildAddDelegatorTx" - ).map((a: string): Buffer => bintools.stringToAddress(a)) - - if (memo instanceof PayloadBase) { - memo = memo.getPayload() - } - - const minStake: BN = (await this.getMinStake())["minDelegatorStake"] - if (stakeAmount.lt(minStake)) { - throw new StakeError( - "PlatformVMAPI.buildAddDelegatorTx -- stake amount must be at least " + - minStake.toString(10) - ) - } - - const avaxAssetID: Buffer = await this.getAVAXAssetID() - - const now: BN = UnixNow() - if (startTime.lt(now) || endTime.lte(startTime)) { - throw new TimeError( - "PlatformVMAPI.buildAddDelegatorTx -- startTime must be in the future and endTime must come after startTime" - ) - } - - const builtUnsignedTx: UnsignedTx = utxoset.buildAddDelegatorTx( - this.core.getNetworkID(), - bintools.cb58Decode(this.blockchainID), - avaxAssetID, - to, - from, - change, - NodeIDStringToBuffer(nodeID), - startTime, - endTime, - stakeAmount, - rewardLocktime, - rewardThreshold, - rewards, - new BN(0), - avaxAssetID, - memo, - asOf - ) - - if (!(await this.checkGooseEgg(builtUnsignedTx))) { - /* istanbul ignore next */ - throw new GooseEggCheckError("Failed Goose Egg Check") - } - - return builtUnsignedTx - } - - /** - * Helper function which creates an unsigned [[AddValidatorTx]]. For more granular control, you may create your own - * [[UnsignedTx]] manually and import the [[AddValidatorTx]] class directly. - * - * @param utxoset A set of UTXOs that the transaction is built on - * @param toAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who received the staked tokens at the end of the staking period - * @param fromAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who own the staking UTXOs the fees in AVAX - * @param changeAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who gets the change leftover from the fee payment - * @param nodeID The node ID of the validator being added. - * @param startTime The Unix time when the validator starts validating the Primary Network. - * @param endTime The Unix time when the validator stops validating the Primary Network (and staked AVAX is returned). - * @param stakeAmount The amount being delegated as a {@link https://github.com/indutny/bn.js/|BN} - * @param rewardAddresses The addresses which will recieve the rewards from the delegated stake. - * @param delegationFee A number for the percentage of reward to be given to the validator when someone delegates to them. Must be between 0 and 100. - * @param rewardLocktime Optional. The locktime field created in the resulting reward outputs - * @param rewardThreshold Opional. The number of signatures required to spend the funds in the resultant reward UTXO. Default 1. - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * - * @returns An unsigned transaction created from the passed in parameters. - */ - buildAddValidatorTx = async ( - utxoset: UTXOSet, - toAddresses: string[], - fromAddresses: string[], - changeAddresses: string[], - nodeID: string, - startTime: BN, - endTime: BN, - stakeAmount: BN, - rewardAddresses: string[], - delegationFee: number, - rewardLocktime: BN = new BN(0), - rewardThreshold: number = 1, - memo: PayloadBase | Buffer = undefined, - asOf: BN = UnixNow() - ): Promise => { - const to: Buffer[] = this._cleanAddressArray( - toAddresses, - "buildAddValidatorTx" - ).map((a: string): Buffer => bintools.stringToAddress(a)) - const from: Buffer[] = this._cleanAddressArray( - fromAddresses, - "buildAddValidatorTx" - ).map((a: string): Buffer => bintools.stringToAddress(a)) - const change: Buffer[] = this._cleanAddressArray( - changeAddresses, - "buildAddValidatorTx" - ).map((a: string): Buffer => bintools.stringToAddress(a)) - const rewards: Buffer[] = this._cleanAddressArray( - rewardAddresses, - "buildAddValidatorTx" - ).map((a: string): Buffer => bintools.stringToAddress(a)) - - if (memo instanceof PayloadBase) { - memo = memo.getPayload() - } - - const minStake: BN = (await this.getMinStake())["minValidatorStake"] - if (stakeAmount.lt(minStake)) { - throw new StakeError( - "PlatformVMAPI.buildAddValidatorTx -- stake amount must be at least " + - minStake.toString(10) - ) - } - - if ( - typeof delegationFee !== "number" || - delegationFee > 100 || - delegationFee < 0 - ) { - throw new DelegationFeeError( - "PlatformVMAPI.buildAddValidatorTx -- delegationFee must be a number between 0 and 100" - ) - } - - const avaxAssetID: Buffer = await this.getAVAXAssetID() - - const now: BN = UnixNow() - if (startTime.lt(now) || endTime.lte(startTime)) { - throw new TimeError( - "PlatformVMAPI.buildAddValidatorTx -- startTime must be in the future and endTime must come after startTime" - ) - } - - const builtUnsignedTx: UnsignedTx = utxoset.buildAddValidatorTx( - this.core.getNetworkID(), - bintools.cb58Decode(this.blockchainID), - avaxAssetID, - to, - from, - change, - NodeIDStringToBuffer(nodeID), - startTime, - endTime, - stakeAmount, - rewardLocktime, - rewardThreshold, - rewards, - delegationFee, - new BN(0), - avaxAssetID, - memo, - asOf - ) - - if (!(await this.checkGooseEgg(builtUnsignedTx))) { - /* istanbul ignore next */ - throw new GooseEggCheckError("Failed Goose Egg Check") - } - - return builtUnsignedTx - } - - /** - * Class representing an unsigned [[CreateSubnetTx]] transaction. - * - * @param utxoset A set of UTXOs that the transaction is built on - * @param fromAddresses The addresses being used to send the funds from the UTXOs {@link https://github.com/feross/buffer|Buffer} - * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs - * @param subnetOwnerAddresses An array of addresses for owners of the new subnet - * @param subnetOwnerThreshold A number indicating the amount of signatures required to add validators to a subnet - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * - * @returns An unsigned transaction created from the passed in parameters. - */ - buildCreateSubnetTx = async ( - utxoset: UTXOSet, - fromAddresses: string[], - changeAddresses: string[], - subnetOwnerAddresses: string[], - subnetOwnerThreshold: number, - memo: PayloadBase | Buffer = undefined, - asOf: BN = UnixNow() - ): Promise => { - const from: Buffer[] = this._cleanAddressArray( - fromAddresses, - "buildCreateSubnetTx" - ).map((a: string): Buffer => bintools.stringToAddress(a)) - const change: Buffer[] = this._cleanAddressArray( - changeAddresses, - "buildCreateSubnetTx" - ).map((a: string): Buffer => bintools.stringToAddress(a)) - const owners: Buffer[] = this._cleanAddressArray( - subnetOwnerAddresses, - "buildCreateSubnetTx" - ).map((a: string): Buffer => bintools.stringToAddress(a)) - - if (memo instanceof PayloadBase) { - memo = memo.getPayload() - } - - const avaxAssetID: Buffer = await this.getAVAXAssetID() - const networkID: number = this.core.getNetworkID() - const blockchainID: Buffer = bintools.cb58Decode(this.blockchainID) - const fee: BN = this.getCreateSubnetTxFee() - const builtUnsignedTx: UnsignedTx = utxoset.buildCreateSubnetTx( - networkID, - blockchainID, - from, - change, - owners, - subnetOwnerThreshold, - fee, - avaxAssetID, - memo, - asOf - ) - - if (!(await this.checkGooseEgg(builtUnsignedTx, this.getCreationTxFee()))) { - /* istanbul ignore next */ - throw new GooseEggCheckError("Failed Goose Egg Check") - } - - return builtUnsignedTx - } - - /** - * Build an unsigned [[CreateChainTx]]. - * - * @param utxoset A set of UTXOs that the transaction is built on - * @param fromAddresses The addresses being used to send the funds from the UTXOs {@link https://github.com/feross/buffer|Buffer} - * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs - * @param subnetID Optional ID of the Subnet that validates this blockchain - * @param chainName Optional A human readable name for the chain; need not be unique - * @param vmID Optional ID of the VM running on the new chain - * @param fxIDs Optional IDs of the feature extensions running on the new chain - * @param genesisData Optional Byte representation of genesis state of the new chain - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param subnetAuthCredentials Optional. An array of index and address to sign for each SubnetAuth. - * - * @returns An unsigned transaction created from the passed in parameters. - */ - buildCreateChainTx = async ( - utxoset: UTXOSet, - fromAddresses: string[], - changeAddresses: string[], - subnetID: string | Buffer = undefined, - chainName: string = undefined, - vmID: string = undefined, - fxIDs: string[] = undefined, - genesisData: string | GenesisData = undefined, - memo: PayloadBase | Buffer = undefined, - asOf: BN = UnixNow(), - subnetAuthCredentials: [number, Buffer][] = [] - ): Promise => { - const from: Buffer[] = this._cleanAddressArray( - fromAddresses, - "buildCreateChainTx" - ).map((a: string): Buffer => bintools.stringToAddress(a)) - const change: Buffer[] = this._cleanAddressArray( - changeAddresses, - "buildCreateChainTx" - ).map((a: string): Buffer => bintools.stringToAddress(a)) - - if (memo instanceof PayloadBase) { - memo = memo.getPayload() - } - - const avaxAssetID: Buffer = await this.getAVAXAssetID() - fxIDs = fxIDs.sort() - - const networkID: number = this.core.getNetworkID() - const blockchainID: Buffer = bintools.cb58Decode(this.blockchainID) - const fee: BN = this.getCreateChainTxFee() - const builtUnsignedTx: UnsignedTx = utxoset.buildCreateChainTx( - networkID, - blockchainID, - from, - change, - subnetID, - chainName, - vmID, - fxIDs, - genesisData, - fee, - avaxAssetID, - memo, - asOf, - subnetAuthCredentials - ) - - if (!(await this.checkGooseEgg(builtUnsignedTx, this.getCreationTxFee()))) { - /* istanbul ignore next */ - throw new GooseEggCheckError("Failed Goose Egg Check") - } - - return builtUnsignedTx - } - - /** - * @ignore - */ - protected _cleanAddressArray( - addresses: string[] | Buffer[], - caller: string - ): string[] { - const addrs: string[] = [] - const chainid: string = this.getBlockchainAlias() - ? this.getBlockchainAlias() - : this.getBlockchainID() - if (addresses && addresses.length > 0) { - for (let i: number = 0; i < addresses.length; i++) { - if (typeof addresses[`${i}`] === "string") { - if ( - typeof this.parseAddress(addresses[`${i}`] as string) === - "undefined" - ) { - /* istanbul ignore next */ - throw new AddressError("Error - Invalid address format") - } - addrs.push(addresses[`${i}`] as string) - } else { - const bech32: SerializedType = "bech32" - addrs.push( - serialization.bufferToType( - addresses[`${i}`] as Buffer, - bech32, - this.core.getHRP(), - chainid - ) - ) - } - } - } - return addrs - } - - /** - * This class should not be instantiated directly. - * Instead use the [[Avalanche.addAPI]] method. - * - * @param core A reference to the Avalanche class - * @param baseURL Defaults to the string "/ext/P" as the path to blockchain's baseURL - */ - constructor(core: AvalancheCore, baseURL: string = "/ext/bc/P") { - super(core, baseURL) - this.blockchainID = PlatformChainID - const netID: number = core.getNetworkID() - if ( - netID in Defaults.network && - this.blockchainID in Defaults.network[`${netID}`] - ) { - const alias: string = - Defaults.network[`${netID}`][this.blockchainID]["alias"] - this.keychain = new KeyChain(this.core.getHRP(), alias) - } else { - this.keychain = new KeyChain(this.core.getHRP(), this.blockchainID) - } - } - - /** - * @returns the current timestamp on chain. - */ - getTimestamp = async (): Promise => { - const response: RequestResponseData = await this.callMethod( - "platform.getTimestamp" - ) - return response.data.result.timestamp - } - - /** - * @returns the UTXOs that were rewarded after the provided transaction"s staking or delegation period ended. - */ - getRewardUTXOs = async ( - txID: string, - encoding?: string - ): Promise => { - const params: GetRewardUTXOsParams = { - txID, - encoding - } - const response: RequestResponseData = await this.callMethod( - "platform.getRewardUTXOs", - params - ) - return response.data.result - } -} diff --git a/src/apis/platformvm/basetx.ts b/src/apis/platformvm/basetx.ts deleted file mode 100644 index d9e4c0e69..000000000 --- a/src/apis/platformvm/basetx.ts +++ /dev/null @@ -1,169 +0,0 @@ -/** - * @packageDocumentation - * @module API-PlatformVM-BaseTx - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { PlatformVMConstants } from "./constants" -import { TransferableOutput } from "./outputs" -import { TransferableInput } from "./inputs" -import { SelectCredentialClass } from "./credentials" -import { KeyChain, KeyPair } from "./keychain" -import { StandardBaseTx } from "../../common/tx" -import { Signature, SigIdx, Credential } from "../../common/credentials" -import { DefaultNetworkID } from "../../utils/constants" -import { SelectTxClass } from "../platformvm/tx" -import { SerializedEncoding } from "../../utils/serialization" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() - -/** - * Class representing a base for all transactions. - */ -export class BaseTx extends StandardBaseTx { - protected _typeName = "BaseTx" - protected _typeID = PlatformVMConstants.CREATESUBNETTX - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.outs = fields["outs"].map((o: TransferableOutput) => { - let newOut: TransferableOutput = new TransferableOutput() - newOut.deserialize(o, encoding) - return newOut - }) - this.ins = fields["ins"].map((i: TransferableInput) => { - let newIn: TransferableInput = new TransferableInput() - newIn.deserialize(i, encoding) - return newIn - }) - this.numouts = Buffer.alloc(4) - this.numouts.writeUInt32BE(this.outs.length, 0) - this.numins = Buffer.alloc(4) - this.numins.writeUInt32BE(this.ins.length, 0) - } - - getOuts(): TransferableOutput[] { - return this.outs as TransferableOutput[] - } - - getIns(): TransferableInput[] { - return this.ins as TransferableInput[] - } - - getTotalOuts(): TransferableOutput[] { - return this.getOuts() as TransferableOutput[] - } - - /** - * Returns the id of the [[BaseTx]] - */ - getTxType(): number { - return PlatformVMConstants.BASETX - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[BaseTx]], parses it, populates the class, and returns the length of the BaseTx in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[BaseTx]] - * - * @returns The length of the raw [[BaseTx]] - * - * @remarks assume not-checksummed - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.networkID = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - this.blockchainID = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - this.numouts = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const outcount: number = this.numouts.readUInt32BE(0) - this.outs = [] - for (let i: number = 0; i < outcount; i++) { - const xferout: TransferableOutput = new TransferableOutput() - offset = xferout.fromBuffer(bytes, offset) - this.outs.push(xferout) - } - - this.numins = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const incount: number = this.numins.readUInt32BE(0) - this.ins = [] - for (let i: number = 0; i < incount; i++) { - const xferin: TransferableInput = new TransferableInput() - offset = xferin.fromBuffer(bytes, offset) - this.ins.push(xferin) - } - let memolen: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.memo = bintools.copyFrom(bytes, offset, offset + memolen) - offset += memolen - return offset - } - - /** - * Takes the bytes of an [[UnsignedTx]] and returns an array of [[Credential]]s - * - * @param msg A Buffer for the [[UnsignedTx]] - * @param kc An [[KeyChain]] used in signing - * - * @returns An array of [[Credential]]s - */ - sign(msg: Buffer, kc: KeyChain): Credential[] { - const creds: Credential[] = [] - for (let i: number = 0; i < this.ins.length; i++) { - const cred: Credential = SelectCredentialClass( - this.ins[`${i}`].getInput().getCredentialID() - ) - const sigidxs: SigIdx[] = this.ins[`${i}`].getInput().getSigIdxs() - for (let j: number = 0; j < sigidxs.length; j++) { - const keypair: KeyPair = kc.getKey(sigidxs[`${j}`].getSource()) - const signval: Buffer = keypair.sign(msg) - const sig: Signature = new Signature() - sig.fromBuffer(signval) - cred.addSignature(sig) - } - creds.push(cred) - } - return creds - } - - clone(): this { - let newbase: BaseTx = new BaseTx() - newbase.fromBuffer(this.toBuffer()) - return newbase as this - } - - create(...args: any[]): this { - return new BaseTx(...args) as this - } - - select(id: number, ...args: any[]): this { - let newbasetx: BaseTx = SelectTxClass(id, ...args) - return newbasetx as this - } - - /** - * Class representing a BaseTx which is the foundation for all transactions. - * - * @param networkID Optional networkID, [[DefaultNetworkID]] - * @param blockchainID Optional blockchainID, default Buffer.alloc(32, 16) - * @param outs Optional array of the [[TransferableOutput]]s - * @param ins Optional array of the [[TransferableInput]]s - * @param memo Optional {@link https://github.com/feross/buffer|Buffer} for the memo field - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: Buffer = Buffer.alloc(32, 16), - outs: TransferableOutput[] = undefined, - ins: TransferableInput[] = undefined, - memo: Buffer = undefined - ) { - super(networkID, blockchainID, outs, ins, memo) - } -} diff --git a/src/apis/platformvm/constants.ts b/src/apis/platformvm/constants.ts deleted file mode 100644 index 34e47babd..000000000 --- a/src/apis/platformvm/constants.ts +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @packageDocumentation - * @module API-PlatformVM-Constants - */ - -export class PlatformVMConstants { - static LATESTCODEC: number = 0 - - static SECPFXID: number = 0 - - static SECPXFEROUTPUTID: number = 7 - - static SUBNETAUTHID: number = 10 - - static SECPOWNEROUTPUTID: number = 11 - - static STAKEABLELOCKOUTID: number = 22 - - static SECPINPUTID: number = 5 - - static STAKEABLELOCKINID: number = 21 - - static LOCKEDSTAKEABLES: number[] = [ - PlatformVMConstants.STAKEABLELOCKINID, - PlatformVMConstants.STAKEABLELOCKOUTID - ] - - static BASETX: number = 0 - - static SUBNETAUTH: number = 10 - - static ADDVALIDATORTX: number = 12 - - static ADDSUBNETVALIDATORTX: number = 13 - - static ADDDELEGATORTX: number = 14 - - static CREATECHAINTX: number = 15 - - static CREATESUBNETTX: number = 16 - - static IMPORTTX: number = 17 - - static EXPORTTX: number = 18 - - static ADVANCETIMETX: number = 19 - - static REWARDVALIDATORTX: number = 20 - - static REMOVESUBNETVALIDATORTX: number = 23 - - static SECPCREDENTIAL: number = 9 - - static ASSETIDLEN: number = 32 - - static BLOCKCHAINIDLEN: number = 32 - - static SYMBOLMAXLEN: number = 4 - - static ASSETNAMELEN: number = 128 - - static ADDRESSLENGTH: number = 20 -} diff --git a/src/apis/platformvm/createchaintx.ts b/src/apis/platformvm/createchaintx.ts deleted file mode 100644 index 8033eb6fb..000000000 --- a/src/apis/platformvm/createchaintx.ts +++ /dev/null @@ -1,342 +0,0 @@ -/** - * @packageDocumentation - * @module API-PlatformVM-CreateChainTx - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { PlatformVMConstants } from "./constants" -import { TransferableOutput } from "./outputs" -import { TransferableInput } from "./inputs" -import { Credential, SigIdx, Signature } from "../../common/credentials" -import { BaseTx } from "./basetx" -import { DefaultNetworkID } from "../../utils/constants" -import { Serialization, SerializedEncoding } from "../../utils/serialization" -import { GenesisData } from "../avm" -import { SelectCredentialClass, SubnetAuth } from "." -import { KeyChain, KeyPair } from "./keychain" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Class representing an unsigned CreateChainTx transaction. - */ -export class CreateChainTx extends BaseTx { - protected _typeName = "CreateChainTx" - protected _typeID = PlatformVMConstants.CREATECHAINTX - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - subnetID: serialization.encoder(this.subnetID, encoding, "Buffer", "cb58") - // exportOuts: this.exportOuts.map((e) => e.serialize(encoding)) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.subnetID = serialization.decoder( - fields["subnetID"], - encoding, - "cb58", - "Buffer", - 32 - ) - // this.exportOuts = fields["exportOuts"].map((e: object) => { - // let eo: TransferableOutput = new TransferableOutput() - // eo.deserialize(e, encoding) - // return eo - // }) - } - - protected subnetID: Buffer = Buffer.alloc(32) - protected chainName: string = "" - protected vmID: Buffer = Buffer.alloc(32) - protected numFXIDs: Buffer = Buffer.alloc(4) - protected fxIDs: Buffer[] = [] - protected genesisData: Buffer = Buffer.alloc(32) - protected subnetAuth: SubnetAuth - protected sigCount: Buffer = Buffer.alloc(4) - protected sigIdxs: SigIdx[] = [] // idxs of subnet auth signers - - /** - * Returns the id of the [[CreateChainTx]] - */ - getTxType(): number { - return PlatformVMConstants.CREATECHAINTX - } - - /** - * Returns the subnetAuth - */ - getSubnetAuth(): SubnetAuth { - return this.subnetAuth - } - - /** - * Returns the subnetID as a string - */ - getSubnetID(): string { - return bintools.cb58Encode(this.subnetID) - } - - /** - * Returns a string of the chainName - */ - getChainName(): string { - return this.chainName - } - - /** - * Returns a Buffer of the vmID - */ - getVMID(): Buffer { - return this.vmID - } - - /** - * Returns an array of fxIDs as Buffers - */ - getFXIDs(): Buffer[] { - return this.fxIDs - } - - /** - * Returns a string of the genesisData - */ - getGenesisData(): string { - return bintools.cb58Encode(this.genesisData) - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[CreateChainTx]], parses it, populates the class, and returns the length of the [[CreateChainTx]] in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[CreateChainTx]] - * - * @returns The length of the raw [[CreateChainTx]] - * - * @remarks assume not-checksummed - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - this.subnetID = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - - const chainNameSize: number = bintools - .copyFrom(bytes, offset, offset + 2) - .readUInt16BE(0) - offset += 2 - - this.chainName = bintools - .copyFrom(bytes, offset, offset + chainNameSize) - .toString("utf8") - offset += chainNameSize - - this.vmID = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - - this.numFXIDs = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - - const nfxids: number = parseInt(this.numFXIDs.toString("hex"), 10) - - for (let i: number = 0; i < nfxids; i++) { - this.fxIDs.push(bintools.copyFrom(bytes, offset, offset + 32)) - offset += 32 - } - - const genesisDataSize: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - - this.genesisData = bintools.copyFrom( - bytes, - offset, - offset + genesisDataSize - ) - offset += genesisDataSize - - const sa: SubnetAuth = new SubnetAuth() - offset += sa.fromBuffer(bintools.copyFrom(bytes, offset)) - - this.subnetAuth = sa - - return offset - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[CreateChainTx]]. - */ - toBuffer(): Buffer { - const superbuff: Buffer = super.toBuffer() - - const chainNameBuff: Buffer = Buffer.alloc(this.chainName.length) - chainNameBuff.write(this.chainName, 0, this.chainName.length, "utf8") - const chainNameSize: Buffer = Buffer.alloc(2) - chainNameSize.writeUIntBE(this.chainName.length, 0, 2) - - let bsize: number = - superbuff.length + - this.subnetID.length + - chainNameSize.length + - chainNameBuff.length + - this.vmID.length + - this.numFXIDs.length - - const barr: Buffer[] = [ - superbuff, - this.subnetID, - chainNameSize, - chainNameBuff, - this.vmID, - this.numFXIDs - ] - - this.fxIDs.forEach((fxID: Buffer): void => { - bsize += fxID.length - barr.push(fxID) - }) - - bsize += 4 - bsize += this.genesisData.length - const gdLength: Buffer = Buffer.alloc(4) - gdLength.writeUIntBE(this.genesisData.length, 0, 4) - barr.push(gdLength) - barr.push(this.genesisData) - - bsize += this.subnetAuth.toBuffer().length - barr.push(this.subnetAuth.toBuffer()) - - return Buffer.concat(barr, bsize) - } - - clone(): this { - const newCreateChainTx: CreateChainTx = new CreateChainTx() - newCreateChainTx.fromBuffer(this.toBuffer()) - return newCreateChainTx as this - } - - create(...args: any[]): this { - return new CreateChainTx(...args) as this - } - - /** - * Creates and adds a [[SigIdx]] to the [[AddSubnetValidatorTx]]. - * - * @param addressIdx The index of the address to reference in the signatures - * @param address The address of the source of the signature - */ - addSignatureIdx(addressIdx: number, address: Buffer): void { - const addressIndex: Buffer = Buffer.alloc(4) - addressIndex.writeUIntBE(addressIdx, 0, 4) - this.subnetAuth.addAddressIndex(addressIndex) - - const sigidx: SigIdx = new SigIdx() - const b: Buffer = Buffer.alloc(4) - b.writeUInt32BE(addressIdx, 0) - sigidx.fromBuffer(b) - sigidx.setSource(address) - this.sigIdxs.push(sigidx) - this.sigCount.writeUInt32BE(this.sigIdxs.length, 0) - } - - /** - * Returns the array of [[SigIdx]] for this [[Input]] - */ - getSigIdxs(): SigIdx[] { - return this.sigIdxs - } - - getCredentialID(): number { - return PlatformVMConstants.SECPCREDENTIAL - } - - /** - * Takes the bytes of an [[UnsignedTx]] and returns an array of [[Credential]]s - * - * @param msg A Buffer for the [[UnsignedTx]] - * @param kc An [[KeyChain]] used in signing - * - * @returns An array of [[Credential]]s - */ - sign(msg: Buffer, kc: KeyChain): Credential[] { - const creds: Credential[] = super.sign(msg, kc) - const sigidxs: SigIdx[] = this.getSigIdxs() - const cred: Credential = SelectCredentialClass(this.getCredentialID()) - for (let i: number = 0; i < sigidxs.length; i++) { - const keypair: KeyPair = kc.getKey(sigidxs[`${i}`].getSource()) - const signval: Buffer = keypair.sign(msg) - const sig: Signature = new Signature() - sig.fromBuffer(signval) - cred.addSignature(sig) - } - creds.push(cred) - return creds - } - - /** - * Class representing an unsigned CreateChain transaction. - * - * @param networkID Optional networkID, [[DefaultNetworkID]] - * @param blockchainID Optional blockchainID, default Buffer.alloc(32, 16) - * @param outs Optional array of the [[TransferableOutput]]s - * @param ins Optional array of the [[TransferableInput]]s - * @param memo Optional {@link https://github.com/feross/buffer|Buffer} for the memo field - * @param subnetID Optional ID of the Subnet that validates this blockchain. - * @param chainName Optional A human readable name for the chain; need not be unique - * @param vmID Optional ID of the VM running on the new chain - * @param fxIDs Optional IDs of the feature extensions running on the new chain - * @param genesisData Optional Byte representation of genesis state of the new chain - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: Buffer = Buffer.alloc(32, 16), - outs: TransferableOutput[] = undefined, - ins: TransferableInput[] = undefined, - memo: Buffer = undefined, - subnetID: string | Buffer = undefined, - chainName: string = undefined, - vmID: string = undefined, - fxIDs: string[] = undefined, - genesisData: string | GenesisData = undefined - ) { - super(networkID, blockchainID, outs, ins, memo) - if (typeof subnetID != "undefined") { - if (typeof subnetID === "string") { - this.subnetID = bintools.cb58Decode(subnetID) - } else { - this.subnetID = subnetID - } - } - if (typeof chainName != "undefined") { - this.chainName = chainName - } - if (typeof vmID != "undefined") { - const buf: Buffer = Buffer.alloc(32) - buf.write(vmID, 0, vmID.length) - this.vmID = buf - } - if (typeof fxIDs != "undefined") { - this.numFXIDs.writeUInt32BE(fxIDs.length, 0) - const fxIDBufs: Buffer[] = [] - fxIDs.forEach((fxID: string): void => { - const buf: Buffer = Buffer.alloc(32) - buf.write(fxID, 0, fxID.length, "utf8") - fxIDBufs.push(buf) - }) - this.fxIDs = fxIDBufs - } - if (typeof genesisData != "undefined" && typeof genesisData != "string") { - this.genesisData = genesisData.toBuffer() - } else if (typeof genesisData == "string") { - this.genesisData = Buffer.from(genesisData) - } - - const subnetAuth: SubnetAuth = new SubnetAuth() - this.subnetAuth = subnetAuth - } -} diff --git a/src/apis/platformvm/createsubnettx.ts b/src/apis/platformvm/createsubnettx.ts deleted file mode 100644 index 973889911..000000000 --- a/src/apis/platformvm/createsubnettx.ts +++ /dev/null @@ -1,108 +0,0 @@ -/** - * @packageDocumentation - * @module API-PlatformVM-CreateSubnetTx - */ -import { Buffer } from "buffer/" -import { BaseTx } from "./basetx" -import { PlatformVMConstants } from "./constants" -import { DefaultNetworkID } from "../../utils/constants" -import { TransferableOutput, SECPOwnerOutput } from "./outputs" -import { TransferableInput } from "./inputs" -import { SerializedEncoding } from "../../utils/serialization" -import { SubnetOwnerError } from "../../utils/errors" - -export class CreateSubnetTx extends BaseTx { - protected _typeName = "CreateSubnetTx" - protected _typeID = PlatformVMConstants.CREATESUBNETTX - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - subnetOwners: this.subnetOwners.serialize(encoding) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.subnetOwners = new SECPOwnerOutput() - this.subnetOwners.deserialize(fields["subnetOwners"], encoding) - } - - protected subnetOwners: SECPOwnerOutput = undefined - - /** - * Returns the id of the [[CreateSubnetTx]] - */ - getTxType(): number { - return this._typeID - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} for the reward address. - */ - getSubnetOwners(): SECPOwnerOutput { - return this.subnetOwners - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[CreateSubnetTx]], parses it, populates the class, and returns the length of the [[CreateSubnetTx]] in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[CreateSubnetTx]] - * @param offset A number for the starting position in the bytes. - * - * @returns The length of the raw [[CreateSubnetTx]] - * - * @remarks assume not-checksummed - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - offset += 4 - this.subnetOwners = new SECPOwnerOutput() - offset = this.subnetOwners.fromBuffer(bytes, offset) - return offset - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[CreateSubnetTx]]. - */ - toBuffer(): Buffer { - if ( - typeof this.subnetOwners === "undefined" || - !(this.subnetOwners instanceof SECPOwnerOutput) - ) { - throw new SubnetOwnerError( - "CreateSubnetTx.toBuffer -- this.subnetOwners is not a SECPOwnerOutput" - ) - } - let typeID: Buffer = Buffer.alloc(4) - typeID.writeUInt32BE(this.subnetOwners.getOutputID(), 0) - let barr: Buffer[] = [ - super.toBuffer(), - typeID, - this.subnetOwners.toBuffer() - ] - return Buffer.concat(barr) - } - - /** - * Class representing an unsigned Create Subnet transaction. - * - * @param networkID Optional networkID, [[DefaultNetworkID]] - * @param blockchainID Optional blockchainID, default Buffer.alloc(32, 16) - * @param outs Optional array of the [[TransferableOutput]]s - * @param ins Optional array of the [[TransferableInput]]s - * @param memo Optional {@link https://github.com/feross/buffer|Buffer} for the memo field - * @param subnetOwners Optional [[SECPOwnerOutput]] class for specifying who owns the subnet. - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: Buffer = Buffer.alloc(32, 16), - outs: TransferableOutput[] = undefined, - ins: TransferableInput[] = undefined, - memo: Buffer = undefined, - subnetOwners: SECPOwnerOutput = undefined - ) { - super(networkID, blockchainID, outs, ins, memo) - this.subnetOwners = subnetOwners - } -} diff --git a/src/apis/platformvm/credentials.ts b/src/apis/platformvm/credentials.ts deleted file mode 100644 index 5b5e3630d..000000000 --- a/src/apis/platformvm/credentials.ts +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @packageDocumentation - * @module API-PlatformVM-Credentials - */ - -import { PlatformVMConstants } from "./constants" -import { Credential } from "../../common/credentials" -import { CredIdError } from "../../utils/errors" - -/** - * Takes a buffer representing the credential and returns the proper [[Credential]] instance. - * - * @param credid A number representing the credential ID parsed prior to the bytes passed in - * - * @returns An instance of an [[Credential]]-extended class. - */ -export const SelectCredentialClass = ( - credid: number, - ...args: any[] -): Credential => { - if (credid === PlatformVMConstants.SECPCREDENTIAL) { - return new SECPCredential(...args) - } - /* istanbul ignore next */ - throw new CredIdError("Error - SelectCredentialClass: unknown credid") -} - -export class SECPCredential extends Credential { - protected _typeName = "SECPCredential" - protected _typeID = PlatformVMConstants.SECPCREDENTIAL - - //serialize and deserialize both are inherited - - getCredentialID(): number { - return this._typeID - } - - clone(): this { - let newbase: SECPCredential = new SECPCredential() - newbase.fromBuffer(this.toBuffer()) - return newbase as this - } - - create(...args: any[]): this { - return new SECPCredential(...args) as this - } - - select(id: number, ...args: any[]): Credential { - let newbasetx: Credential = SelectCredentialClass(id, ...args) - return newbasetx - } -} diff --git a/src/apis/platformvm/exporttx.ts b/src/apis/platformvm/exporttx.ts deleted file mode 100644 index 2660f3135..000000000 --- a/src/apis/platformvm/exporttx.ts +++ /dev/null @@ -1,191 +0,0 @@ -/** - * @packageDocumentation - * @module API-PlatformVM-ExportTx - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { PlatformVMConstants } from "./constants" -import { TransferableOutput } from "./outputs" -import { TransferableInput } from "./inputs" -import { BaseTx } from "./basetx" -import { DefaultNetworkID } from "../../utils/constants" -import BN from "bn.js" -import { AmountOutput } from "../platformvm/outputs" -import { Serialization, SerializedEncoding } from "../../utils/serialization" -import { ChainIdError, TransferableOutputError } from "../../utils/errors" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Class representing an unsigned Export transaction. - */ -export class ExportTx extends BaseTx { - protected _typeName = "ExportTx" - protected _typeID = PlatformVMConstants.EXPORTTX - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - destinationChain: serialization.encoder( - this.destinationChain, - encoding, - "Buffer", - "cb58" - ), - exportOuts: this.exportOuts.map((e) => e.serialize(encoding)) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.destinationChain = serialization.decoder( - fields["destinationChain"], - encoding, - "cb58", - "Buffer", - 32 - ) - this.exportOuts = fields["exportOuts"].map((e: object) => { - let eo: TransferableOutput = new TransferableOutput() - eo.deserialize(e, encoding) - return eo - }) - this.numOuts = Buffer.alloc(4) - this.numOuts.writeUInt32BE(this.exportOuts.length, 0) - } - - protected destinationChain: Buffer = Buffer.alloc(32) - protected numOuts: Buffer = Buffer.alloc(4) - protected exportOuts: TransferableOutput[] = [] - - /** - * Returns the id of the [[ExportTx]] - */ - getTxType(): number { - return PlatformVMConstants.EXPORTTX - } - - /** - * Returns an array of [[TransferableOutput]]s in this transaction. - */ - getExportOutputs(): TransferableOutput[] { - return this.exportOuts - } - - /** - * Returns the total exported amount as a {@link https://github.com/indutny/bn.js/|BN}. - */ - getExportTotal(): BN { - let val: BN = new BN(0) - for (let i: number = 0; i < this.exportOuts.length; i++) { - val = val.add( - (this.exportOuts[`${i}`].getOutput() as AmountOutput).getAmount() - ) - } - return val - } - - getTotalOuts(): TransferableOutput[] { - return [ - ...(this.getOuts() as TransferableOutput[]), - ...this.getExportOutputs() - ] - } - - /** - * Returns the destinationChain as a {@link https://github.com/feross/buffer|Buffer} - */ - getDestinationChain(): Buffer { - return this.destinationChain - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[ExportTx]], parses it, populates the class, and returns the length of the [[ExportTx]] in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[ExportTx]] - * - * @returns The length of the raw [[ExportTx]] - * - * @remarks assume not-checksummed - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - this.destinationChain = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - this.numOuts = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const numOuts: number = this.numOuts.readUInt32BE(0) - for (let i: number = 0; i < numOuts; i++) { - const anOut: TransferableOutput = new TransferableOutput() - offset = anOut.fromBuffer(bytes, offset) - this.exportOuts.push(anOut) - } - return offset - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[ExportTx]]. - */ - toBuffer(): Buffer { - if (typeof this.destinationChain === "undefined") { - throw new ChainIdError( - "ExportTx.toBuffer -- this.destinationChain is undefined" - ) - } - this.numOuts.writeUInt32BE(this.exportOuts.length, 0) - let barr: Buffer[] = [super.toBuffer(), this.destinationChain, this.numOuts] - this.exportOuts = this.exportOuts.sort(TransferableOutput.comparator()) - for (let i: number = 0; i < this.exportOuts.length; i++) { - barr.push(this.exportOuts[`${i}`].toBuffer()) - } - return Buffer.concat(barr) - } - - clone(): this { - let newbase: ExportTx = new ExportTx() - newbase.fromBuffer(this.toBuffer()) - return newbase as this - } - - create(...args: any[]): this { - return new ExportTx(...args) as this - } - - /** - * Class representing an unsigned Export transaction. - * - * @param networkID Optional networkID, [[DefaultNetworkID]] - * @param blockchainID Optional blockchainID, default Buffer.alloc(32, 16) - * @param outs Optional array of the [[TransferableOutput]]s - * @param ins Optional array of the [[TransferableInput]]s - * @param memo Optional {@link https://github.com/feross/buffer|Buffer} for the memo field - * @param destinationChain Optional chainid which identifies where the funds will send to. - * @param exportOuts Array of [[TransferableOutputs]]s used in the transaction - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: Buffer = Buffer.alloc(32, 16), - outs: TransferableOutput[] = undefined, - ins: TransferableInput[] = undefined, - memo: Buffer = undefined, - destinationChain: Buffer = undefined, - exportOuts: TransferableOutput[] = undefined - ) { - super(networkID, blockchainID, outs, ins, memo) - this.destinationChain = destinationChain //do not correct, it should bomb on toBuffer if not provided - if (typeof exportOuts !== "undefined" && Array.isArray(exportOuts)) { - for (let i: number = 0; i < exportOuts.length; i++) { - if (!(exportOuts[`${i}`] instanceof TransferableOutput)) { - throw new TransferableOutputError( - "Error - ExportTx.constructor: invalid TransferableOutput in array parameter 'exportOuts'" - ) - } - } - this.exportOuts = exportOuts - } - } -} diff --git a/src/apis/platformvm/importtx.ts b/src/apis/platformvm/importtx.ts deleted file mode 100644 index b550f62a3..000000000 --- a/src/apis/platformvm/importtx.ts +++ /dev/null @@ -1,198 +0,0 @@ -/** - * @packageDocumentation - * @module API-PlatformVM-ImportTx - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { PlatformVMConstants } from "./constants" -import { TransferableOutput } from "./outputs" -import { TransferableInput } from "./inputs" -import { KeyChain, KeyPair } from "./keychain" -import { SelectCredentialClass } from "./credentials" -import { Signature, SigIdx, Credential } from "../../common/credentials" -import { BaseTx } from "./basetx" -import { DefaultNetworkID } from "../../utils/constants" -import { Serialization, SerializedEncoding } from "../../utils/serialization" -import { ChainIdError, TransferableInputError } from "../../utils/errors" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Class representing an unsigned Import transaction. - */ -export class ImportTx extends BaseTx { - protected _typeName = "ImportTx" - protected _typeID = PlatformVMConstants.IMPORTTX - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - sourceChain: serialization.encoder( - this.sourceChain, - encoding, - "Buffer", - "cb58" - ), - importIns: this.importIns.map((i) => i.serialize(encoding)) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.sourceChain = serialization.decoder( - fields["sourceChain"], - encoding, - "cb58", - "Buffer", - 32 - ) - this.importIns = fields["importIns"].map((i: object) => { - let ii: TransferableInput = new TransferableInput() - ii.deserialize(i, encoding) - return ii - }) - this.numIns = Buffer.alloc(4) - this.numIns.writeUInt32BE(this.importIns.length, 0) - } - - protected sourceChain: Buffer = Buffer.alloc(32) - protected numIns: Buffer = Buffer.alloc(4) - protected importIns: TransferableInput[] = [] - - /** - * Returns the id of the [[ImportTx]] - */ - getTxType(): number { - return this._typeID - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[ImportTx]], parses it, populates the class, and returns the length of the [[ImportTx]] in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[ImportTx]] - * - * @returns The length of the raw [[ImportTx]] - * - * @remarks assume not-checksummed - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - this.sourceChain = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - this.numIns = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const numIns: number = this.numIns.readUInt32BE(0) - for (let i: number = 0; i < numIns; i++) { - const anIn: TransferableInput = new TransferableInput() - offset = anIn.fromBuffer(bytes, offset) - this.importIns.push(anIn) - } - return offset - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[ImportTx]]. - */ - toBuffer(): Buffer { - if (typeof this.sourceChain === "undefined") { - throw new ChainIdError( - "ImportTx.toBuffer -- this.sourceChain is undefined" - ) - } - this.numIns.writeUInt32BE(this.importIns.length, 0) - let barr: Buffer[] = [super.toBuffer(), this.sourceChain, this.numIns] - this.importIns = this.importIns.sort(TransferableInput.comparator()) - for (let i: number = 0; i < this.importIns.length; i++) { - barr.push(this.importIns[`${i}`].toBuffer()) - } - return Buffer.concat(barr) - } - /** - * Returns an array of [[TransferableInput]]s in this transaction. - */ - getImportInputs(): TransferableInput[] { - return this.importIns - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} for the source chainid. - */ - getSourceChain(): Buffer { - return this.sourceChain - } - - /** - * Takes the bytes of an [[UnsignedTx]] and returns an array of [[Credential]]s - * - * @param msg A Buffer for the [[UnsignedTx]] - * @param kc An [[KeyChain]] used in signing - * - * @returns An array of [[Credential]]s - */ - sign(msg: Buffer, kc: KeyChain): Credential[] { - const creds: Credential[] = super.sign(msg, kc) - for (let i: number = 0; i < this.importIns.length; i++) { - const cred: Credential = SelectCredentialClass( - this.importIns[`${i}`].getInput().getCredentialID() - ) - const sigidxs: SigIdx[] = this.importIns[`${i}`].getInput().getSigIdxs() - for (let j: number = 0; j < sigidxs.length; j++) { - const keypair: KeyPair = kc.getKey(sigidxs[`${j}`].getSource()) - const signval: Buffer = keypair.sign(msg) - const sig: Signature = new Signature() - sig.fromBuffer(signval) - cred.addSignature(sig) - } - creds.push(cred) - } - return creds - } - - clone(): this { - let newbase: ImportTx = new ImportTx() - newbase.fromBuffer(this.toBuffer()) - return newbase as this - } - - create(...args: any[]): this { - return new ImportTx(...args) as this - } - - /** - * Class representing an unsigned Import transaction. - * - * @param networkID Optional networkID, [[DefaultNetworkID]] - * @param blockchainID Optional blockchainID, default Buffer.alloc(32, 16) - * @param outs Optional array of the [[TransferableOutput]]s - * @param ins Optional array of the [[TransferableInput]]s - * @param memo Optional {@link https://github.com/feross/buffer|Buffer} for the memo field - * @param sourceChain Optiona chainid for the source inputs to import. Default platform chainid. - * @param importIns Array of [[TransferableInput]]s used in the transaction - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: Buffer = Buffer.alloc(32, 16), - outs: TransferableOutput[] = undefined, - ins: TransferableInput[] = undefined, - memo: Buffer = undefined, - sourceChain: Buffer = undefined, - importIns: TransferableInput[] = undefined - ) { - super(networkID, blockchainID, outs, ins, memo) - this.sourceChain = sourceChain // do no correct, if it's wrong it'll bomb on toBuffer - if (typeof importIns !== "undefined" && Array.isArray(importIns)) { - for (let i: number = 0; i < importIns.length; i++) { - if (!(importIns[`${i}`] instanceof TransferableInput)) { - throw new TransferableInputError( - "Error - ImportTx.constructor: invalid TransferableInput in array parameter 'importIns'" - ) - } - } - this.importIns = importIns - } - } -} diff --git a/src/apis/platformvm/index.ts b/src/apis/platformvm/index.ts deleted file mode 100644 index bfbe00c58..000000000 --- a/src/apis/platformvm/index.ts +++ /dev/null @@ -1,19 +0,0 @@ -export * from "./api" -export * from "./addsubnetvalidatortx" -export * from "./basetx" -export * from "./constants" -export * from "./createchaintx" -export * from "./createsubnettx" -export * from "./credentials" -export * from "./exporttx" -export * from "./importtx" -export * from "./inputs" -export * from "./interfaces" -export * from "./keychain" -export * from "./outputs" -export * from "./proofOfPossession" -export * from "./removesubnetvalidatortx" -export * from "./subnetauth" -export * from "./tx" -export * from "./utxos" -export * from "./validationtx" diff --git a/src/apis/platformvm/inputs.ts b/src/apis/platformvm/inputs.ts deleted file mode 100644 index aebfbe782..000000000 --- a/src/apis/platformvm/inputs.ts +++ /dev/null @@ -1,268 +0,0 @@ -/** - * @packageDocumentation - * @module API-PlatformVM-Inputs - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { PlatformVMConstants } from "./constants" -import { - Input, - StandardTransferableInput, - StandardAmountInput, - StandardParseableInput -} from "../../common/input" -import { Serialization, SerializedEncoding } from "../../utils/serialization" -import BN from "bn.js" -import { InputIdError } from "../../utils/errors" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Takes a buffer representing the output and returns the proper [[Input]] instance. - * - * @param inputid A number representing the inputID parsed prior to the bytes passed in - * - * @returns An instance of an [[Input]]-extended class. - */ -export const SelectInputClass = (inputid: number, ...args: any[]): Input => { - if (inputid === PlatformVMConstants.SECPINPUTID) { - return new SECPTransferInput(...args) - } else if (inputid === PlatformVMConstants.STAKEABLELOCKINID) { - return new StakeableLockIn(...args) - } - /* istanbul ignore next */ - throw new InputIdError("Error - SelectInputClass: unknown inputid") -} - -export class ParseableInput extends StandardParseableInput { - protected _typeName = "ParseableInput" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.input = SelectInputClass(fields["input"]["_typeID"]) - this.input.deserialize(fields["input"], encoding) - } - - fromBuffer(bytes: Buffer, offset: number = 0): number { - const inputid: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.input = SelectInputClass(inputid) - return this.input.fromBuffer(bytes, offset) - } -} - -export class TransferableInput extends StandardTransferableInput { - protected _typeName = "TransferableInput" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.input = SelectInputClass(fields["input"]["_typeID"]) - this.input.deserialize(fields["input"], encoding) - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing a [[TransferableInput]], parses it, populates the class, and returns the length of the [[TransferableInput]] in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[TransferableInput]] - * - * @returns The length of the raw [[TransferableInput]] - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.txid = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - this.outputidx = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - this.assetID = bintools.copyFrom( - bytes, - offset, - offset + PlatformVMConstants.ASSETIDLEN - ) - offset += 32 - const inputid: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.input = SelectInputClass(inputid) - return this.input.fromBuffer(bytes, offset) - } -} - -export abstract class AmountInput extends StandardAmountInput { - protected _typeName = "AmountInput" - protected _typeID = undefined - - //serialize and deserialize both are inherited - - select(id: number, ...args: any[]): Input { - return SelectInputClass(id, ...args) - } -} - -export class SECPTransferInput extends AmountInput { - protected _typeName = "SECPTransferInput" - protected _typeID = PlatformVMConstants.SECPINPUTID - - //serialize and deserialize both are inherited - - /** - * Returns the inputID for this input - */ - getInputID(): number { - return this._typeID - } - - getCredentialID = (): number => PlatformVMConstants.SECPCREDENTIAL - - create(...args: any[]): this { - return new SECPTransferInput(...args) as this - } - - clone(): this { - const newout: SECPTransferInput = this.create() - newout.fromBuffer(this.toBuffer()) - return newout as this - } -} - -/** - * An [[Input]] class which specifies an input that has a locktime which can also enable staking of the value held, preventing transfers but not validation. - */ -export class StakeableLockIn extends AmountInput { - protected _typeName = "StakeableLockIn" - protected _typeID = PlatformVMConstants.STAKEABLELOCKINID - - //serialize and deserialize both are inherited - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - let outobj: object = { - ...fields, - stakeableLocktime: serialization.encoder( - this.stakeableLocktime, - encoding, - "Buffer", - "decimalString", - 8 - ), - transferableInput: this.transferableInput.serialize(encoding) - } - delete outobj["sigIdxs"] - delete outobj["sigCount"] - delete outobj["amount"] - return outobj - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - fields["sigIdxs"] = [] - fields["sigCount"] = "0" - fields["amount"] = "98" - super.deserialize(fields, encoding) - this.stakeableLocktime = serialization.decoder( - fields["stakeableLocktime"], - encoding, - "decimalString", - "Buffer", - 8 - ) - this.transferableInput = new ParseableInput() - this.transferableInput.deserialize(fields["transferableInput"], encoding) - this.synchronize() - } - - protected stakeableLocktime: Buffer - protected transferableInput: ParseableInput - - private synchronize() { - let input: AmountInput = this.transferableInput.getInput() as AmountInput - this.sigIdxs = input.getSigIdxs() - this.sigCount = Buffer.alloc(4) - this.sigCount.writeUInt32BE(this.sigIdxs.length, 0) - this.amount = bintools.fromBNToBuffer(input.getAmount(), 8) - this.amountValue = input.getAmount() - } - - getStakeableLocktime(): BN { - return bintools.fromBufferToBN(this.stakeableLocktime) - } - - getTransferablInput(): ParseableInput { - return this.transferableInput - } - /** - * Returns the inputID for this input - */ - getInputID(): number { - return this._typeID - } - - getCredentialID = (): number => PlatformVMConstants.SECPCREDENTIAL - - /** - * Popuates the instance from a {@link https://github.com/feross/buffer|Buffer} representing the [[StakeableLockIn]] and returns the size of the output. - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.stakeableLocktime = bintools.copyFrom(bytes, offset, offset + 8) - offset += 8 - this.transferableInput = new ParseableInput() - offset = this.transferableInput.fromBuffer(bytes, offset) - this.synchronize() - return offset - } - - /** - * Returns the buffer representing the [[StakeableLockIn]] instance. - */ - toBuffer(): Buffer { - const xferinBuff: Buffer = this.transferableInput.toBuffer() - const bsize: number = this.stakeableLocktime.length + xferinBuff.length - const barr: Buffer[] = [this.stakeableLocktime, xferinBuff] - return Buffer.concat(barr, bsize) - } - - create(...args: any[]): this { - return new StakeableLockIn(...args) as this - } - - clone(): this { - const newout: StakeableLockIn = this.create() - newout.fromBuffer(this.toBuffer()) - return newout as this - } - - select(id: number, ...args: any[]): Input { - return SelectInputClass(id, ...args) - } - - /** - * A [[Output]] class which specifies an [[Input]] that has a locktime which can also enable staking of the value held, preventing transfers but not validation. - * - * @param amount A {@link https://github.com/indutny/bn.js/|BN} representing the amount in the input - * @param stakeableLocktime A {@link https://github.com/indutny/bn.js/|BN} representing the stakeable locktime - * @param transferableInput A [[ParseableInput]] which is embedded into this input. - */ - constructor( - amount: BN = undefined, - stakeableLocktime: BN = undefined, - transferableInput: ParseableInput = undefined - ) { - super(amount) - if (typeof stakeableLocktime !== "undefined") { - this.stakeableLocktime = bintools.fromBNToBuffer(stakeableLocktime, 8) - } - if (typeof transferableInput !== "undefined") { - this.transferableInput = transferableInput - this.synchronize() - } - } -} diff --git a/src/apis/platformvm/interfaces.ts b/src/apis/platformvm/interfaces.ts deleted file mode 100644 index 00a33a192..000000000 --- a/src/apis/platformvm/interfaces.ts +++ /dev/null @@ -1,204 +0,0 @@ -/** - * @packageDocumentation - * @module PlatformVM-Interfaces - */ - -import BN from "bn.js" -import { PersistanceOptions } from "../../utils/persistenceoptions" -import { TransferableOutput } from "." -import { UTXOSet } from "../platformvm/utxos" - -export interface GetStakeParams { - addresses: string[] - encoding: string -} - -export interface GetStakeResponse { - staked: BN - stakedOutputs: TransferableOutput[] -} - -export interface GetRewardUTXOsParams { - txID: string - encoding: string -} - -export interface GetRewardUTXOsResponse { - numFetched: number - utxos: string[] - encoding: string -} - -export interface GetValidatorsAtParams { - height: number - subnetID?: string -} - -export interface GetValidatorsAtResponse { - validators: object -} - -export interface GetCurrentValidatorsParams { - subnetID?: Buffer | string - nodeIDs?: string[] -} - -export interface SampleValidatorsParams { - size: number | string - subnetID?: Buffer | string | undefined -} - -export interface SampleValidatorsParams { - size: number | string - subnetID?: Buffer | string | undefined -} - -export interface AddValidatorParams { - username: string - password: string - nodeID: string - startTime: number - endTime: number - stakeAmount: string - rewardAddress: string - delegationFeeRate?: string | undefined -} - -export interface AddDelegatorParams { - username: string - password: string - nodeID: string - startTime: number - endTime: number - stakeAmount: string - rewardAddress: string -} - -export interface GetPendingValidatorsParams { - subnetID?: Buffer | string - nodeIDs?: string[] -} - -export interface ExportAVAXParams { - username: string - password: string - amount: string - to: string -} - -export interface ImportAVAXParams { - username: string - password: string - sourceChain: string - to: string -} - -export interface ExportKeyParams { - username: string - password: string - address: string -} - -export interface ImportKeyParams { - username: string - password: string - privateKey: string -} - -export interface GetBalanceResponse { - balance: BN | number - unlocked: BN | number - lockedStakeable: BN | number - lockedNotStakeable: BN | number - utxoIDs: { - txID: string - outputIndex: number - }[] -} - -export interface CreateAddressParams { - username: string - password: string -} - -export interface ListAddressesParams { - username: string - password: string -} - -export interface StartIndex { - address: string - utxo: string -} - -export interface GetUTXOsParams { - addresses: string[] | string - sourceChain?: string | undefined - limit: number | 0 - startIndex?: StartIndex | undefined - persistOpts?: PersistanceOptions | undefined - encoding?: string -} - -export interface EndIndex { - address: string - utxo: string -} - -export interface GetUTXOsResponse { - numFetched: number - utxos: UTXOSet - endIndex: EndIndex -} - -export interface CreateSubnetParams { - username: string - password: string - controlKeys: string[] - threshold: number -} - -export interface Subnet { - ids: string - controlKeys: string[] - threshold: number -} - -export interface CreateBlockchainParams { - username: string - password: string - subnetID?: Buffer | string | undefined - vmID: string - fxIDs: number[] - name: string - genesisData: string -} - -export interface Blockchain { - id: string - name: string - subnetID: string - vmID: string -} - -export interface GetTxStatusParams { - txID: string - includeReason?: boolean | true -} - -export interface GetTxStatusResponse { - status: string - reason: string -} - -export interface GetMinStakeResponse { - minValidatorStake: BN - minDelegatorStake: BN -} - -export interface GetMaxStakeAmountParams { - subnetID?: string - nodeID: string - startTime: BN - endTime: BN -} diff --git a/src/apis/platformvm/keychain.ts b/src/apis/platformvm/keychain.ts deleted file mode 100644 index 5f51c7d1e..000000000 --- a/src/apis/platformvm/keychain.ts +++ /dev/null @@ -1,112 +0,0 @@ -/** - * @packageDocumentation - * @module API-PlatformVM-KeyChain - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { SECP256k1KeyChain, SECP256k1KeyPair } from "../../common/secp256k1" -import { Serialization, SerializedType } from "../../utils" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Class for representing a private and public keypair on the Platform Chain. - */ -export class KeyPair extends SECP256k1KeyPair { - clone(): this { - let newkp: KeyPair = new KeyPair(this.hrp, this.chainID) - newkp.importKey(bintools.copyFrom(this.getPrivateKey())) - return newkp as this - } - - create(...args: any[]): this { - if (args.length == 2) { - return new KeyPair(args[0], args[1]) as this - } - return new KeyPair(this.hrp, this.chainID) as this - } -} - -/** - * Class for representing a key chain in Avalanche. - * - * @typeparam KeyPair Class extending [[KeyPair]] which is used as the key in [[KeyChain]] - */ -export class KeyChain extends SECP256k1KeyChain { - hrp: string = "" - chainID: string = "" - - /** - * Makes a new key pair, returns the address. - * - * @returns The new key pair - */ - makeKey = (): KeyPair => { - let keypair: KeyPair = new KeyPair(this.hrp, this.chainID) - this.addKey(keypair) - return keypair - } - - addKey = (newKey: KeyPair) => { - newKey.setChainID(this.chainID) - super.addKey(newKey) - } - - /** - * Given a private key, makes a new key pair, returns the address. - * - * @param privk A {@link https://github.com/feross/buffer|Buffer} or cb58 serialized string representing the private key - * - * @returns The new key pair - */ - importKey = (privk: Buffer | string): KeyPair => { - let keypair: KeyPair = new KeyPair(this.hrp, this.chainID) - let pk: Buffer - if (typeof privk === "string") { - pk = bintools.cb58Decode(privk.split("-")[1]) - } else { - pk = bintools.copyFrom(privk) - } - keypair.importKey(pk) - if (!(keypair.getAddress().toString("hex") in this.keys)) { - this.addKey(keypair) - } - return keypair - } - - create(...args: any[]): this { - if (args.length == 2) { - return new KeyChain(args[0], args[1]) as this - } - return new KeyChain(this.hrp, this.chainID) as this - } - - clone(): this { - const newkc: KeyChain = new KeyChain(this.hrp, this.chainID) - for (let k in this.keys) { - newkc.addKey(this.keys[`${k}`].clone()) - } - return newkc as this - } - - union(kc: this): this { - let newkc: KeyChain = kc.clone() - for (let k in this.keys) { - newkc.addKey(this.keys[`${k}`].clone()) - } - return newkc as this - } - - /** - * Returns instance of KeyChain. - */ - constructor(hrp: string, chainID: string) { - super() - this.hrp = hrp - this.chainID = chainID - } -} diff --git a/src/apis/platformvm/outputs.ts b/src/apis/platformvm/outputs.ts deleted file mode 100644 index 86d933f86..000000000 --- a/src/apis/platformvm/outputs.ts +++ /dev/null @@ -1,328 +0,0 @@ -/** - * @packageDocumentation - * @module API-PlatformVM-Outputs - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { PlatformVMConstants } from "./constants" -import { - Output, - StandardAmountOutput, - StandardTransferableOutput, - StandardParseableOutput, - Address -} from "../../common/output" -import { Serialization, SerializedEncoding } from "../../utils/serialization" -import BN from "bn.js" -import { OutputIdError } from "../../utils/errors" - -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Takes a buffer representing the output and returns the proper Output instance. - * - * @param outputid A number representing the inputID parsed prior to the bytes passed in - * - * @returns An instance of an [[Output]]-extended class. - */ -export const SelectOutputClass = (outputid: number, ...args: any[]): Output => { - if (outputid == PlatformVMConstants.SECPXFEROUTPUTID) { - return new SECPTransferOutput(...args) - } else if (outputid == PlatformVMConstants.SECPOWNEROUTPUTID) { - return new SECPOwnerOutput(...args) - } else if (outputid == PlatformVMConstants.STAKEABLELOCKOUTID) { - return new StakeableLockOut(...args) - } - throw new OutputIdError( - "Error - SelectOutputClass: unknown outputid " + outputid - ) -} - -export class TransferableOutput extends StandardTransferableOutput { - protected _typeName = "TransferableOutput" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.output = SelectOutputClass(fields["output"]["_typeID"]) - this.output.deserialize(fields["output"], encoding) - } - - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.assetID = bintools.copyFrom( - bytes, - offset, - offset + PlatformVMConstants.ASSETIDLEN - ) - offset += PlatformVMConstants.ASSETIDLEN - const outputid: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.output = SelectOutputClass(outputid) - return this.output.fromBuffer(bytes, offset) - } -} - -export class ParseableOutput extends StandardParseableOutput { - protected _typeName = "ParseableOutput" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.output = SelectOutputClass(fields["output"]["_typeID"]) - this.output.deserialize(fields["output"], encoding) - } - - fromBuffer(bytes: Buffer, offset: number = 0): number { - const outputid: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.output = SelectOutputClass(outputid) - return this.output.fromBuffer(bytes, offset) - } -} - -export abstract class AmountOutput extends StandardAmountOutput { - protected _typeName = "AmountOutput" - protected _typeID = undefined - - //serialize and deserialize both are inherited - - /** - * @param assetID An assetID which is wrapped around the Buffer of the Output - */ - makeTransferable(assetID: Buffer): TransferableOutput { - return new TransferableOutput(assetID, this) - } - - select(id: number, ...args: any[]): Output { - return SelectOutputClass(id, ...args) - } -} - -/** - * An [[Output]] class which specifies an Output that carries an ammount for an assetID and uses secp256k1 signature scheme. - */ -export class SECPTransferOutput extends AmountOutput { - protected _typeName = "SECPTransferOutput" - protected _typeID = PlatformVMConstants.SECPXFEROUTPUTID - - //serialize and deserialize both are inherited - - /** - * Returns the outputID for this output - */ - getOutputID(): number { - return this._typeID - } - - create(...args: any[]): this { - return new SECPTransferOutput(...args) as this - } - - clone(): this { - const newout: SECPTransferOutput = this.create() - newout.fromBuffer(this.toBuffer()) - return newout as this - } -} - -/** - * An [[Output]] class which specifies an input that has a locktime which can also enable staking of the value held, preventing transfers but not validation. - */ -export class StakeableLockOut extends AmountOutput { - protected _typeName = "StakeableLockOut" - protected _typeID = PlatformVMConstants.STAKEABLELOCKOUTID - - //serialize and deserialize both are inherited - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - let outobj: object = { - ...fields, //included anywayyyy... not ideal - stakeableLocktime: serialization.encoder( - this.stakeableLocktime, - encoding, - "Buffer", - "decimalString", - 8 - ), - transferableOutput: this.transferableOutput.serialize(encoding) - } - delete outobj["addresses"] - delete outobj["locktime"] - delete outobj["threshold"] - delete outobj["amount"] - return outobj - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - fields["addresses"] = [] - fields["locktime"] = "0" - fields["threshold"] = "1" - fields["amount"] = "99" - super.deserialize(fields, encoding) - this.stakeableLocktime = serialization.decoder( - fields["stakeableLocktime"], - encoding, - "decimalString", - "Buffer", - 8 - ) - this.transferableOutput = new ParseableOutput() - this.transferableOutput.deserialize(fields["transferableOutput"], encoding) - this.synchronize() - } - - protected stakeableLocktime: Buffer - protected transferableOutput: ParseableOutput - - //call this every time you load in data - private synchronize() { - let output: AmountOutput = - this.transferableOutput.getOutput() as AmountOutput - this.addresses = output.getAddresses().map((a) => { - let addr: Address = new Address() - addr.fromBuffer(a) - return addr - }) - this.numaddrs = Buffer.alloc(4) - this.numaddrs.writeUInt32BE(this.addresses.length, 0) - this.locktime = bintools.fromBNToBuffer(output.getLocktime(), 8) - this.threshold = Buffer.alloc(4) - this.threshold.writeUInt32BE(output.getThreshold(), 0) - this.amount = bintools.fromBNToBuffer(output.getAmount(), 8) - this.amountValue = output.getAmount() - } - - getStakeableLocktime(): BN { - return bintools.fromBufferToBN(this.stakeableLocktime) - } - - getTransferableOutput(): ParseableOutput { - return this.transferableOutput - } - - /** - * @param assetID An assetID which is wrapped around the Buffer of the Output - */ - makeTransferable(assetID: Buffer): TransferableOutput { - return new TransferableOutput(assetID, this) - } - - select(id: number, ...args: any[]): Output { - return SelectOutputClass(id, ...args) - } - - /** - * Popuates the instance from a {@link https://github.com/feross/buffer|Buffer} representing the [[StakeableLockOut]] and returns the size of the output. - */ - fromBuffer(outbuff: Buffer, offset: number = 0): number { - this.stakeableLocktime = bintools.copyFrom(outbuff, offset, offset + 8) - offset += 8 - this.transferableOutput = new ParseableOutput() - offset = this.transferableOutput.fromBuffer(outbuff, offset) - this.synchronize() - return offset - } - - /** - * Returns the buffer representing the [[StakeableLockOut]] instance. - */ - toBuffer(): Buffer { - let xferoutBuff: Buffer = this.transferableOutput.toBuffer() - const bsize: number = this.stakeableLocktime.length + xferoutBuff.length - const barr: Buffer[] = [this.stakeableLocktime, xferoutBuff] - return Buffer.concat(barr, bsize) - } - - /** - * Returns the outputID for this output - */ - getOutputID(): number { - return this._typeID - } - - create(...args: any[]): this { - return new StakeableLockOut(...args) as this - } - - clone(): this { - const newout: StakeableLockOut = this.create() - newout.fromBuffer(this.toBuffer()) - return newout as this - } - - /** - * A [[Output]] class which specifies a [[ParseableOutput]] that has a locktime which can also enable staking of the value held, preventing transfers but not validation. - * - * @param amount A {@link https://github.com/indutny/bn.js/|BN} representing the amount in the output - * @param addresses An array of {@link https://github.com/feross/buffer|Buffer}s representing addresses - * @param locktime A {@link https://github.com/indutny/bn.js/|BN} representing the locktime - * @param threshold A number representing the the threshold number of signers required to sign the transaction - * @param stakeableLocktime A {@link https://github.com/indutny/bn.js/|BN} representing the stakeable locktime - * @param transferableOutput A [[ParseableOutput]] which is embedded into this output. - */ - constructor( - amount: BN = undefined, - addresses: Buffer[] = undefined, - locktime: BN = undefined, - threshold: number = undefined, - stakeableLocktime: BN = undefined, - transferableOutput: ParseableOutput = undefined - ) { - super(amount, addresses, locktime, threshold) - if (typeof stakeableLocktime !== "undefined") { - this.stakeableLocktime = bintools.fromBNToBuffer(stakeableLocktime, 8) - } - if (typeof transferableOutput !== "undefined") { - this.transferableOutput = transferableOutput - this.synchronize() - } - } -} - -/** - * An [[Output]] class which only specifies an Output ownership and uses secp256k1 signature scheme. - */ -export class SECPOwnerOutput extends Output { - protected _typeName = "SECPOwnerOutput" - protected _typeID = PlatformVMConstants.SECPOWNEROUTPUTID - - //serialize and deserialize both are inherited - - /** - * Returns the outputID for this output - */ - getOutputID(): number { - return this._typeID - } - - /** - * - * @param assetID An assetID which is wrapped around the Buffer of the Output - */ - makeTransferable(assetID: Buffer): TransferableOutput { - return new TransferableOutput(assetID, this) - } - - create(...args: any[]): this { - return new SECPOwnerOutput(...args) as this - } - - clone(): this { - const newout: SECPOwnerOutput = this.create() - newout.fromBuffer(this.toBuffer()) - return newout as this - } - - select(id: number, ...args: any[]): Output { - return SelectOutputClass(id, ...args) - } -} diff --git a/src/apis/platformvm/proofOfPossession.ts b/src/apis/platformvm/proofOfPossession.ts deleted file mode 100644 index 4b7bc74fc..000000000 --- a/src/apis/platformvm/proofOfPossession.ts +++ /dev/null @@ -1,77 +0,0 @@ -/** - * @packageDocumentation - * @module API-PlatformVM-ProofOfPossession - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() - -// A BLS public key and a proof of possession of the key. -export class ProofOfPossession { - protected _typeName = "ProofOfPossession" - protected _typeID = undefined - protected publicKey: Buffer = Buffer.alloc(48) - protected signature: Buffer = Buffer.alloc(96) - - /** - * Returns the {@link https://github.com/feross/buffer|Buffer} representation of the publicKey - */ - getPublicKey(): Buffer { - return this.publicKey - } - - /** - * Returns the {@link https://github.com/feross/buffer|Buffer} representation of the signature - */ - getSignature(): Buffer { - return this.signature - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[ProofOfPossession]], parses it, populates the class, and returns the length of the [[ProofOfPossession]] in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[ProofOfPossession]] - * - * @returns The length of the raw [[ProofOfPossession]] - * - * @remarks assume not-checksummed - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.publicKey = bintools.copyFrom(bytes, offset, offset + 48) - offset += 48 - - this.signature = bintools.copyFrom(bytes, offset, offset + 96) - offset += 96 - - return offset - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[ProofOfPossession]] - */ - toBuffer(): Buffer { - let bsize: number = this.publicKey.length + this.signature.length - - const barr: Buffer[] = [ - this.publicKey, - this.signature - ] - - return Buffer.concat(barr, bsize) - } - - /** - * Class representing a Proof of Possession - * - * @param publicKey {@link https://github.com/feross/buffer|Buffer} for the public key - * @param signature {@link https://github.com/feross/buffer|Buffer} for the signature - */ - constructor(publicKey: Buffer = undefined, signature: Buffer = undefined) { - this.publicKey = publicKey - this.signature = signature - } -} diff --git a/src/apis/platformvm/removesubnetvalidatortx.ts b/src/apis/platformvm/removesubnetvalidatortx.ts deleted file mode 100644 index e87f7fd6e..000000000 --- a/src/apis/platformvm/removesubnetvalidatortx.ts +++ /dev/null @@ -1,214 +0,0 @@ -/** - * @packageDocumentation - * @module API-PlatformVM-RemoveSubnetValidatorTx - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { PlatformVMConstants } from "./constants" -import { TransferableOutput } from "./outputs" -import { TransferableInput } from "./inputs" -import { Credential, SigIdx, Signature } from "../../common/credentials" -import { BaseTx } from "./basetx" -import { DefaultNetworkID } from "../../utils/constants" -import { SelectCredentialClass, SubnetAuth } from "." -import { KeyChain, KeyPair } from "./keychain" -import { bufferToNodeIDString } from "../../utils" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() - -/** - * Class representing an unsigned RemoveSubnetValidatorTx transaction. - */ -export class RemoveSubnetValidatorTx extends BaseTx { - protected _typeName = "RemoveSubnetValidatorTx" - protected _typeID = PlatformVMConstants.REMOVESUBNETVALIDATORTX - protected nodeID: Buffer = Buffer.alloc(20) - protected subnetID: Buffer = Buffer.alloc(32) - protected subnetAuth: SubnetAuth - protected sigCount: Buffer = Buffer.alloc(4) - protected sigIdxs: SigIdx[] = [] // idxs of subnet auth signers - - /** - * Returns the id of the [[RemoveSubnetValidatorTx]] - */ - getTxType(): number { - return PlatformVMConstants.REMOVESUBNETVALIDATORTX - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} for the nodeID. - */ - getNodeID(): Buffer { - return this.nodeID - } - - /** - * Returns a string for the nodeID. - */ - getNodeIDString(): string { - return bufferToNodeIDString(this.nodeID) - } - - /** - * Returns the subnetID as a string - */ - getSubnetID(): string { - return bintools.cb58Encode(this.subnetID) - } - /** - * Returns the subnetAuth - */ - getSubnetAuth(): SubnetAuth { - return this.subnetAuth - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[RemoveSubnetValidatorTx]], parses it, populates the class, and returns the length of the [[RemoveSubnetValidatorTx]] in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[RemoveSubnetValidatorTx]] - * - * @returns The length of the raw [[RemoveSubnetValidatorTx]] - * - * @remarks assume not-checksummed - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - - this.nodeID = bintools.copyFrom(bytes, offset, offset + 20) - offset += 20 - - this.subnetID = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - - const sa: SubnetAuth = new SubnetAuth() - offset += sa.fromBuffer(bintools.copyFrom(bytes, offset)) - this.subnetAuth = sa - - return offset - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[RemoveSubnetValidatorTx]]. - */ - toBuffer(): Buffer { - const superbuff: Buffer = super.toBuffer() - - const bsize: number = - superbuff.length + - this.nodeID.length + - this.subnetID.length + - this.subnetAuth.toBuffer().length - - const barr: Buffer[] = [ - superbuff, - this.nodeID, - this.subnetID, - this.subnetAuth.toBuffer() - ] - return Buffer.concat(barr, bsize) - } - - clone(): this { - const newRemoveSubnetValidatorTx: RemoveSubnetValidatorTx = - new RemoveSubnetValidatorTx() - newRemoveSubnetValidatorTx.fromBuffer(this.toBuffer()) - return newRemoveSubnetValidatorTx as this - } - - create(...args: any[]): this { - return new RemoveSubnetValidatorTx(...args) as this - } - - /** - * Creates and adds a [[SigIdx]] to the [[RemoveSubnetValidatorTx]]. - * - * @param addressIdx The index of the address to reference in the signatures - * @param address The address of the source of the signature - */ - addSignatureIdx(addressIdx: number, address: Buffer): void { - const addressIndex: Buffer = Buffer.alloc(4) - addressIndex.writeUIntBE(addressIdx, 0, 4) - this.subnetAuth.addAddressIndex(addressIndex) - - const sigidx: SigIdx = new SigIdx() - const b: Buffer = Buffer.alloc(4) - b.writeUInt32BE(addressIdx, 0) - sigidx.fromBuffer(b) - sigidx.setSource(address) - this.sigIdxs.push(sigidx) - this.sigCount.writeUInt32BE(this.sigIdxs.length, 0) - } - - /** - * Returns the array of [[SigIdx]] for this [[Input]] - */ - getSigIdxs(): SigIdx[] { - return this.sigIdxs - } - - getCredentialID(): number { - return PlatformVMConstants.SECPCREDENTIAL - } - - /** - * Takes the bytes of an [[UnsignedTx]] and returns an array of [[Credential]]s - * - * @param msg A Buffer for the [[UnsignedTx]] - * @param kc An [[KeyChain]] used in signing - * - * @returns An array of [[Credential]]s - */ - sign(msg: Buffer, kc: KeyChain): Credential[] { - const creds: Credential[] = super.sign(msg, kc) - const sigidxs: SigIdx[] = this.getSigIdxs() - const cred: Credential = SelectCredentialClass(this.getCredentialID()) - for (let i: number = 0; i < sigidxs.length; i++) { - const keypair: KeyPair = kc.getKey(sigidxs[`${i}`].getSource()) - const signval: Buffer = keypair.sign(msg) - const sig: Signature = new Signature() - sig.fromBuffer(signval) - cred.addSignature(sig) - } - creds.push(cred) - return creds - } - - /** - * Class representing an unsigned RemoveSubnetValidatorTx transaction. - * - * @param networkID Optional networkID, [[DefaultNetworkID]] - * @param blockchainID Optional blockchainID, default Buffer.alloc(32, 16) - * @param outs Optional array of the [[TransferableOutput]]s - * @param ins Optional array of the [[TransferableInput]]s - * @param memo Optional {@link https://github.com/feross/buffer|Buffer} for the memo field - * @param nodeID Optional. The node ID of the validator being added. - * @param subnetID Optional. ID of the subnet this validator is validating - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: Buffer = Buffer.alloc(32, 16), - outs: TransferableOutput[] = undefined, - ins: TransferableInput[] = undefined, - memo: Buffer = undefined, - nodeID: Buffer = undefined, - subnetID: string | Buffer = undefined - ) { - super(networkID, blockchainID, outs, ins, memo) - if (typeof subnetID != "undefined") { - if (typeof subnetID === "string") { - this.subnetID = bintools.cb58Decode(subnetID) - } else { - this.subnetID = subnetID - } - } - if (typeof nodeID != "undefined") { - this.nodeID = nodeID - } - - const subnetAuth: SubnetAuth = new SubnetAuth() - this.subnetAuth = subnetAuth - } -} diff --git a/src/apis/platformvm/subnetauth.ts b/src/apis/platformvm/subnetauth.ts deleted file mode 100644 index eceb615ba..000000000 --- a/src/apis/platformvm/subnetauth.ts +++ /dev/null @@ -1,85 +0,0 @@ -/** - * @packageDocumentation - * @module API-PlatformVM-SubnetAuth - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { Serializable, SerializedEncoding } from "../../utils" -import { PlatformVMConstants } from "." - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() - -export class SubnetAuth extends Serializable { - protected _typeName = "SubnetAuth" - protected _typeID = PlatformVMConstants.SUBNETAUTH - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - } - - /** - * Add an address index for Subnet Auth signing - * - * @param index the Buffer of the address index to add - */ - addAddressIndex(index: Buffer): void { - const numAddrIndices: number = this.getNumAddressIndices() - this.numAddressIndices.writeUIntBE(numAddrIndices + 1, 0, 4) - this.addressIndices.push(index) - } - - /** - * Returns the number of address indices as a number - */ - getNumAddressIndices(): number { - return this.numAddressIndices.readUIntBE(0, 4) - } - - /** - * Returns an array of AddressIndices as Buffers - */ - getAddressIndices(): Buffer[] { - return this.addressIndices - } - - protected addressIndices: Buffer[] = [] - protected numAddressIndices: Buffer = Buffer.alloc(4) - - fromBuffer(bytes: Buffer, offset: number = 0): number { - // increase offset for type id - offset += 4 - this.numAddressIndices = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - for (let i: number = 0; i < this.getNumAddressIndices(); i++) { - this.addressIndices.push(bintools.copyFrom(bytes, offset, offset + 4)) - offset += 4 - } - return offset - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[SubnetAuth]]. - */ - toBuffer(): Buffer { - const typeIDBuf: Buffer = Buffer.alloc(4) - typeIDBuf.writeUIntBE(this._typeID, 0, 4) - const numAddressIndices: Buffer = Buffer.alloc(4) - numAddressIndices.writeIntBE(this.addressIndices.length, 0, 4) - const barr: Buffer[] = [typeIDBuf, numAddressIndices] - let bsize: number = typeIDBuf.length + numAddressIndices.length - this.addressIndices.forEach((addressIndex: Buffer, i: number): void => { - bsize += 4 - barr.push(this.addressIndices[`${i}`]) - }) - return Buffer.concat(barr, bsize) - } -} diff --git a/src/apis/platformvm/tx.ts b/src/apis/platformvm/tx.ts deleted file mode 100644 index 51a2db847..000000000 --- a/src/apis/platformvm/tx.ts +++ /dev/null @@ -1,145 +0,0 @@ -/** - * @packageDocumentation - * @module API-PlatformVM-Transactions - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import { PlatformVMConstants } from "./constants" -import { SelectCredentialClass } from "./credentials" -import { KeyChain, KeyPair } from "./keychain" -import { StandardTx, StandardUnsignedTx } from "../../common/tx" -import { Credential } from "../../common/credentials" -import createHash from "create-hash" -import { BaseTx } from "./basetx" -import { ImportTx } from "./importtx" -import { ExportTx } from "./exporttx" -import { SerializedEncoding } from "../../utils/serialization" -import { AddDelegatorTx, AddValidatorTx } from "./validationtx" -import { CreateSubnetTx } from "./createsubnettx" -import { TransactionError } from "../../utils/errors" -import { AddSubnetValidatorTx } from "./addsubnetvalidatortx" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() - -/** - * Takes a buffer representing the output and returns the proper [[BaseTx]] instance. - * - * @param txtype The id of the transaction type - * - * @returns An instance of an [[BaseTx]]-extended class. - */ -export const SelectTxClass = (txtype: number, ...args: any[]): BaseTx => { - if (txtype === PlatformVMConstants.BASETX) { - return new BaseTx(...args) - } else if (txtype === PlatformVMConstants.IMPORTTX) { - return new ImportTx(...args) - } else if (txtype === PlatformVMConstants.EXPORTTX) { - return new ExportTx(...args) - } else if (txtype === PlatformVMConstants.ADDDELEGATORTX) { - return new AddDelegatorTx(...args) - } else if (txtype === PlatformVMConstants.ADDVALIDATORTX) { - return new AddValidatorTx(...args) - } else if (txtype === PlatformVMConstants.CREATESUBNETTX) { - return new CreateSubnetTx(...args) - } else if (txtype === PlatformVMConstants.ADDSUBNETVALIDATORTX) { - return new AddSubnetValidatorTx(...args) - } - /* istanbul ignore next */ - throw new TransactionError("Error - SelectTxClass: unknown txtype") -} - -export class UnsignedTx extends StandardUnsignedTx { - protected _typeName = "UnsignedTx" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.transaction = SelectTxClass(fields["transaction"]["_typeID"]) - this.transaction.deserialize(fields["transaction"], encoding) - } - - getTransaction(): BaseTx { - return this.transaction as BaseTx - } - - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.codecID = bintools.copyFrom(bytes, offset, offset + 2).readUInt16BE(0) - offset += 2 - const txtype: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.transaction = SelectTxClass(txtype) - return this.transaction.fromBuffer(bytes, offset) - } - - /** - * Signs this [[UnsignedTx]] and returns signed [[StandardTx]] - * - * @param kc An [[KeyChain]] used in signing - * - * @returns A signed [[StandardTx]] - */ - sign(kc: KeyChain): Tx { - const txbuff = this.toBuffer() - const msg: Buffer = Buffer.from( - createHash("sha256").update(txbuff).digest() - ) - const creds: Credential[] = this.transaction.sign(msg, kc) - return new Tx(this, creds) - } -} - -export class Tx extends StandardTx { - protected _typeName = "Tx" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.unsignedTx = new UnsignedTx() - this.unsignedTx.deserialize(fields["unsignedTx"], encoding) - this.credentials = [] - for (let i: number = 0; i < fields["credentials"].length; i++) { - const cred: Credential = SelectCredentialClass( - fields["credentials"][`${i}`]["_typeID"] - ) - cred.deserialize(fields["credentials"][`${i}`], encoding) - this.credentials.push(cred) - } - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[Tx]], parses it, populates the class, and returns the length of the Tx in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[Tx]] - * @param offset A number representing the starting point of the bytes to begin parsing - * - * @returns The length of the raw [[Tx]] - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.unsignedTx = new UnsignedTx() - offset = this.unsignedTx.fromBuffer(bytes, offset) - const numcreds: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.credentials = [] - for (let i: number = 0; i < numcreds; i++) { - const credid: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - const cred: Credential = SelectCredentialClass(credid) - offset = cred.fromBuffer(bytes, offset) - this.credentials.push(cred) - } - return offset - } -} diff --git a/src/apis/platformvm/utxos.ts b/src/apis/platformvm/utxos.ts deleted file mode 100644 index 5c244f537..000000000 --- a/src/apis/platformvm/utxos.ts +++ /dev/null @@ -1,1385 +0,0 @@ -/** - * @packageDocumentation - * @module API-PlatformVM-UTXOs - */ -import { Buffer } from "buffer/" -import BinTools from "../../utils/bintools" -import BN from "bn.js" -import { - AmountOutput, - SelectOutputClass, - TransferableOutput, - SECPOwnerOutput, - ParseableOutput, - StakeableLockOut, - SECPTransferOutput -} from "./outputs" -import { - AmountInput, - SECPTransferInput, - StakeableLockIn, - TransferableInput, - ParseableInput -} from "./inputs" -import { UnixNow } from "../../utils/helperfunctions" -import { StandardUTXO, StandardUTXOSet } from "../../common/utxos" -import { PlatformVMConstants } from "./constants" -import { UnsignedTx } from "./tx" -import { ExportTx } from "../platformvm/exporttx" -import { DefaultNetworkID, Defaults } from "../../utils/constants" -import { ImportTx } from "../platformvm/importtx" -import { BaseTx } from "../platformvm/basetx" -import { - StandardAssetAmountDestination, - AssetAmount -} from "../../common/assetamount" -import { Output } from "../../common/output" -import { AddDelegatorTx, AddValidatorTx } from "./validationtx" -import { CreateSubnetTx } from "./createsubnettx" -import { Serialization, SerializedEncoding } from "../../utils/serialization" -import { - UTXOError, - AddressError, - InsufficientFundsError, - ThresholdError, - FeeAssetError, - TimeError, - UnknownFormatError -} from "../../utils/errors" -import { CreateChainTx } from "." -import { GenesisData } from "../avm" -import { AddSubnetValidatorTx } from "../platformvm/addsubnetvalidatortx" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Class for representing a single UTXO. - */ -export class UTXO extends StandardUTXO { - protected _typeName = "UTXO" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.output = SelectOutputClass(fields["output"]["_typeID"]) - this.output.deserialize(fields["output"], encoding) - } - - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.codecID = bintools.copyFrom(bytes, offset, offset + 2) - offset += 2 - this.txid = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - this.outputidx = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - this.assetID = bintools.copyFrom(bytes, offset, offset + 32) - offset += 32 - const outputid: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.output = SelectOutputClass(outputid) - return this.output.fromBuffer(bytes, offset) - } - - /** - * Takes a base-58 or hex string containing a [[UTXO]], parses it, populates the class, and returns the length of the StandardUTXO in bytes. - * - * @param serialized A base-58 string containing a raw [[UTXO]] - * @param format The format of the encoded [[UTXO]] (cb58 or hex). Defaults to cb58 per existing codebase - * - * @returns The length of the raw [[UTXO]] - * - * @remarks - * Default encoding format is cb58, if providing hex encoded string please specify format as 'hex' - */ - fromString(serialized: string, format: string = 'cb58'): number { - switch (format) { - case "cb58": { - /* istanbul ignore next */ - return this.fromBuffer(bintools.cb58Decode(serialized)); - }; - case "hex": { - let decoded = serialization.decoder(serialized, 'hex', 'hex', 'cb58'); - this.fromString(decoded); - return this.toBuffer().length; - }; - default: { - throw new UnknownFormatError(`Specified format '${format}' is unknown, should be hex or cb58.`); - }; - } - } - - /** - * Returns a base-58 representation of the [[UTXO]]. - * - * @param format The format of the encoded [[UTXO]] (cb58 or hex). Defaults to cb58 per existing codebase - * - * @remarks - * Default encoding format to cb58, if you want a hex encoded output please specify format as 'hex' - */ - toString(format: string = 'cb58'): string { - switch (format) { - case "cb58": { - /* istanbul ignore next */ - return bintools.cb58Encode(this.toBuffer()) - }; - case "hex": { - return serialization.encoder(bintools.cb58Encode(this.toBuffer()), 'hex', 'cb58', 'hex'); - }; - default: { - throw new UnknownFormatError(`Specified format '${format}' is unknown, should be hex or cb58.`); - }; - } - } - - clone(): this { - const utxo: UTXO = new UTXO() - utxo.fromBuffer(this.toBuffer()) - return utxo as this - } - - create( - codecID: number = PlatformVMConstants.LATESTCODEC, - txid: Buffer = undefined, - outputidx: Buffer | number = undefined, - assetID: Buffer = undefined, - output: Output = undefined - ): this { - return new UTXO(codecID, txid, outputidx, assetID, output) as this - } -} - -export class AssetAmountDestination extends StandardAssetAmountDestination< - TransferableOutput, - TransferableInput -> {} - -/** - * Class representing a set of [[UTXO]]s. - */ -export class UTXOSet extends StandardUTXOSet { - protected _typeName = "UTXOSet" - protected _typeID = undefined - - //serialize is inherited - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - let utxos = {} - for (let utxoid in fields["utxos"]) { - let utxoidCleaned: string = serialization.decoder( - utxoid, - encoding, - "base58", - "base58" - ) - utxos[`${utxoidCleaned}`] = new UTXO() - utxos[`${utxoidCleaned}`].deserialize( - fields["utxos"][`${utxoid}`], - encoding - ) - } - let addressUTXOs = {} - for (let address in fields["addressUTXOs"]) { - let addressCleaned: string = serialization.decoder( - address, - encoding, - "cb58", - "hex" - ) - let utxobalance = {} - for (let utxoid in fields["addressUTXOs"][`${address}`]) { - let utxoidCleaned: string = serialization.decoder( - utxoid, - encoding, - "base58", - "base58" - ) - utxobalance[`${utxoidCleaned}`] = serialization.decoder( - fields["addressUTXOs"][`${address}`][`${utxoid}`], - encoding, - "decimalString", - "BN" - ) - } - addressUTXOs[`${addressCleaned}`] = utxobalance - } - this.utxos = utxos - this.addressUTXOs = addressUTXOs - } - - parseUTXO(utxo: UTXO | string): UTXO { - const utxovar: UTXO = new UTXO() - // force a copy - if (typeof utxo === "string") { - utxovar.fromBuffer(bintools.cb58Decode(utxo)) - } else if (utxo instanceof StandardUTXO) { - utxovar.fromBuffer(utxo.toBuffer()) // forces a copy - } else { - /* istanbul ignore next */ - throw new UTXOError( - "Error - UTXO.parseUTXO: utxo parameter is not a UTXO or string" - ) - } - return utxovar - } - - create(...args: any[]): this { - return new UTXOSet() as this - } - - clone(): this { - const newset: UTXOSet = this.create() - const allUTXOs: UTXO[] = this.getAllUTXOs() - newset.addArray(allUTXOs) - return newset as this - } - - _feeCheck(fee: BN, feeAssetID: Buffer): boolean { - return ( - typeof fee !== "undefined" && - typeof feeAssetID !== "undefined" && - fee.gt(new BN(0)) && - feeAssetID instanceof Buffer - ) - } - - getConsumableUXTO = ( - asOf: BN = UnixNow(), - stakeable: boolean = false - ): UTXO[] => { - return this.getAllUTXOs().filter((utxo: UTXO) => { - if (stakeable) { - // stakeable transactions can consume any UTXO. - return true - } - const output: Output = utxo.getOutput() - if (!(output instanceof StakeableLockOut)) { - // non-stakeable transactions can consume any UTXO that isn't locked. - return true - } - const stakeableOutput: StakeableLockOut = output as StakeableLockOut - if (stakeableOutput.getStakeableLocktime().lt(asOf)) { - // If the stakeable outputs locktime has ended, then this UTXO can still - // be consumed by a non-stakeable transaction. - return true - } - // This output is locked and can't be consumed by a non-stakeable - // transaction. - return false - }) - } - - getMinimumSpendable = ( - aad: AssetAmountDestination, - asOf: BN = UnixNow(), - locktime: BN = new BN(0), - threshold: number = 1, - stakeable: boolean = false - ): Error => { - let utxoArray: UTXO[] = this.getConsumableUXTO(asOf, stakeable) - let tmpUTXOArray: UTXO[] = [] - if (stakeable) { - // If this is a stakeable transaction then have StakeableLockOut come before SECPTransferOutput - // so that users first stake locked tokens before staking unlocked tokens - utxoArray.forEach((utxo: UTXO) => { - // StakeableLockOuts - if (utxo.getOutput().getTypeID() === 22) { - tmpUTXOArray.push(utxo) - } - }) - - // Sort the StakeableLockOuts by StakeableLocktime so that the greatest StakeableLocktime are spent first - tmpUTXOArray.sort((a: UTXO, b: UTXO) => { - let stakeableLockOut1 = a.getOutput() as StakeableLockOut - let stakeableLockOut2 = b.getOutput() as StakeableLockOut - return ( - stakeableLockOut2.getStakeableLocktime().toNumber() - - stakeableLockOut1.getStakeableLocktime().toNumber() - ) - }) - - utxoArray.forEach((utxo: UTXO) => { - // SECPTransferOutputs - if (utxo.getOutput().getTypeID() === 7) { - tmpUTXOArray.push(utxo) - } - }) - utxoArray = tmpUTXOArray - } - - // outs is a map from assetID to a tuple of (lockedStakeable, unlocked) - // which are arrays of outputs. - const outs: object = {} - - // We only need to iterate over UTXOs until we have spent sufficient funds - // to met the requested amounts. - utxoArray.forEach((utxo: UTXO, index: number) => { - const assetID: Buffer = utxo.getAssetID() - const assetKey: string = assetID.toString("hex") - const fromAddresses: Buffer[] = aad.getSenders() - const output: Output = utxo.getOutput() - if ( - !(output instanceof AmountOutput) || - !aad.assetExists(assetKey) || - !output.meetsThreshold(fromAddresses, asOf) - ) { - // We should only try to spend fungible assets. - // We should only spend {{ assetKey }}. - // We need to be able to spend the output. - return - } - - const assetAmount: AssetAmount = aad.getAssetAmount(assetKey) - if (assetAmount.isFinished()) { - // We've already spent the needed UTXOs for this assetID. - return - } - - if (!(assetKey in outs)) { - // If this is the first time spending this assetID, we need to - // initialize the outs object correctly. - outs[`${assetKey}`] = { - lockedStakeable: [], - unlocked: [] - } - } - - const amountOutput: AmountOutput = output as AmountOutput - // amount is the amount of funds available from this UTXO. - const amount = amountOutput.getAmount() - - // Set up the SECP input with the same amount as the output. - let input: AmountInput = new SECPTransferInput(amount) - - let locked: boolean = false - if (amountOutput instanceof StakeableLockOut) { - const stakeableOutput: StakeableLockOut = - amountOutput as StakeableLockOut - const stakeableLocktime: BN = stakeableOutput.getStakeableLocktime() - - if (stakeableLocktime.gt(asOf)) { - // Add a new input and mark it as being locked. - input = new StakeableLockIn( - amount, - stakeableLocktime, - new ParseableInput(input) - ) - - // Mark this UTXO as having been re-locked. - locked = true - } - } - - assetAmount.spendAmount(amount, locked) - if (locked) { - // Track the UTXO as locked. - outs[`${assetKey}`].lockedStakeable.push(amountOutput) - } else { - // Track the UTXO as unlocked. - outs[`${assetKey}`].unlocked.push(amountOutput) - } - - // Get the indices of the outputs that should be used to authorize the - // spending of this input. - - // TODO: getSpenders should return an array of indices rather than an - // array of addresses. - const spenders: Buffer[] = amountOutput.getSpenders(fromAddresses, asOf) - spenders.forEach((spender: Buffer) => { - const idx: number = amountOutput.getAddressIdx(spender) - if (idx === -1) { - // This should never happen, which is why the error is thrown rather - // than being returned. If this were to ever happen this would be an - // error in the internal logic rather having called this function with - // invalid arguments. - - /* istanbul ignore next */ - throw new AddressError( - "Error - UTXOSet.getMinimumSpendable: no such " + - `address in output: ${spender}` - ) - } - input.addSignatureIdx(idx, spender) - }) - - const txID: Buffer = utxo.getTxID() - const outputIdx: Buffer = utxo.getOutputIdx() - const transferInput: TransferableInput = new TransferableInput( - txID, - outputIdx, - assetID, - input - ) - aad.addInput(transferInput) - }) - - if (!aad.canComplete()) { - // After running through all the UTXOs, we still weren't able to get all - // the necessary funds, so this transaction can't be made. - return new InsufficientFundsError( - "Error - UTXOSet.getMinimumSpendable: insufficient " + - "funds to create the transaction" - ) - } - - // TODO: We should separate the above functionality into a single function - // that just selects the UTXOs to consume. - - const zero: BN = new BN(0) - - // assetAmounts is an array of asset descriptions and how much is left to - // spend for them. - const assetAmounts: AssetAmount[] = aad.getAmounts() - assetAmounts.forEach((assetAmount: AssetAmount) => { - // change is the amount that should be returned back to the source of the - // funds. - const change: BN = assetAmount.getChange() - // isStakeableLockChange is if the change is locked or not. - const isStakeableLockChange: boolean = - assetAmount.getStakeableLockChange() - // lockedChange is the amount of locked change that should be returned to - // the sender - const lockedChange: BN = isStakeableLockChange ? change : zero.clone() - - const assetID: Buffer = assetAmount.getAssetID() - const assetKey: string = assetAmount.getAssetIDString() - const lockedOutputs: StakeableLockOut[] = - outs[`${assetKey}`].lockedStakeable - lockedOutputs.forEach((lockedOutput: StakeableLockOut, i: number) => { - const stakeableLocktime: BN = lockedOutput.getStakeableLocktime() - const parseableOutput: ParseableOutput = - lockedOutput.getTransferableOutput() - - // We know that parseableOutput contains an AmountOutput because the - // first loop filters for fungible assets. - const output: AmountOutput = parseableOutput.getOutput() as AmountOutput - - let outputAmountRemaining: BN = output.getAmount() - // The only output that could generate change is the last output. - // Otherwise, any further UTXOs wouldn't have needed to be spent. - if (i == lockedOutputs.length - 1 && lockedChange.gt(zero)) { - // update outputAmountRemaining to no longer hold the change that we - // are returning. - outputAmountRemaining = outputAmountRemaining.sub(lockedChange) - // Create the inner output. - const newChangeOutput: AmountOutput = SelectOutputClass( - output.getOutputID(), - lockedChange, - output.getAddresses(), - output.getLocktime(), - output.getThreshold() - ) as AmountOutput - // Wrap the inner output in the StakeableLockOut wrapper. - let newLockedChangeOutput: StakeableLockOut = SelectOutputClass( - lockedOutput.getOutputID(), - lockedChange, - output.getAddresses(), - output.getLocktime(), - output.getThreshold(), - stakeableLocktime, - new ParseableOutput(newChangeOutput) - ) as StakeableLockOut - const transferOutput: TransferableOutput = new TransferableOutput( - assetID, - newLockedChangeOutput - ) - aad.addChange(transferOutput) - } - - // We know that outputAmountRemaining > 0. Otherwise, we would never - // have consumed this UTXO, as it would be only change. - - // Create the inner output. - const newOutput: AmountOutput = SelectOutputClass( - output.getOutputID(), - outputAmountRemaining, - output.getAddresses(), - output.getLocktime(), - output.getThreshold() - ) as AmountOutput - // Wrap the inner output in the StakeableLockOut wrapper. - const newLockedOutput: StakeableLockOut = SelectOutputClass( - lockedOutput.getOutputID(), - outputAmountRemaining, - output.getAddresses(), - output.getLocktime(), - output.getThreshold(), - stakeableLocktime, - new ParseableOutput(newOutput) - ) as StakeableLockOut - const transferOutput: TransferableOutput = new TransferableOutput( - assetID, - newLockedOutput - ) - aad.addOutput(transferOutput) - }) - - // unlockedChange is the amount of unlocked change that should be returned - // to the sender - const unlockedChange: BN = isStakeableLockChange ? zero.clone() : change - if (unlockedChange.gt(zero)) { - const newChangeOutput: AmountOutput = new SECPTransferOutput( - unlockedChange, - aad.getChangeAddresses(), - zero.clone(), // make sure that we don't lock the change output. - threshold - ) as AmountOutput - const transferOutput: TransferableOutput = new TransferableOutput( - assetID, - newChangeOutput - ) - aad.addChange(transferOutput) - } - - // totalAmountSpent is the total amount of tokens consumed. - const totalAmountSpent: BN = assetAmount.getSpent() - // stakeableLockedAmount is the total amount of locked tokens consumed. - const stakeableLockedAmount: BN = assetAmount.getStakeableLockSpent() - // totalUnlockedSpent is the total amount of unlocked tokens consumed. - const totalUnlockedSpent: BN = totalAmountSpent.sub(stakeableLockedAmount) - // amountBurnt is the amount of unlocked tokens that must be burn. - const amountBurnt: BN = assetAmount.getBurn() - // totalUnlockedAvailable is the total amount of unlocked tokens available - // to be produced. - const totalUnlockedAvailable: BN = totalUnlockedSpent.sub(amountBurnt) - // unlockedAmount is the amount of unlocked tokens that should be sent. - const unlockedAmount: BN = totalUnlockedAvailable.sub(unlockedChange) - if (unlockedAmount.gt(zero)) { - const newOutput: AmountOutput = new SECPTransferOutput( - unlockedAmount, - aad.getDestinations(), - locktime, - threshold - ) as AmountOutput - const transferOutput: TransferableOutput = new TransferableOutput( - assetID, - newOutput - ) - aad.addOutput(transferOutput) - } - }) - return undefined - } - - /** - * Creates an [[UnsignedTx]] wrapping a [[BaseTx]]. For more granular control, you may create your own - * [[UnsignedTx]] wrapping a [[BaseTx]] manually (with their corresponding [[TransferableInput]]s and [[TransferableOutput]]s). - * - * @param networkID The number representing NetworkID of the node - * @param blockchainID The {@link https://github.com/feross/buffer|Buffer} representing the BlockchainID for the transaction - * @param amount The amount of the asset to be spent in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN}. - * @param assetID {@link https://github.com/feross/buffer|Buffer} of the asset ID for the UTXO - * @param toAddresses The addresses to send the funds - * @param fromAddresses The addresses being used to send the funds from the UTXOs {@link https://github.com/feross/buffer|Buffer} - * @param changeAddresses Optional. The addresses that can spend the change remaining from the spent UTXOs. Default: toAddresses - * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN} - * @param feeAssetID Optional. The assetID of the fees being burned. Default: assetID - * @param memo Optional. Contains arbitrary data, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param locktime Optional. The locktime field created in the resulting outputs - * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO - * - * @returns An unsigned transaction created from the passed in parameters. - * - */ - buildBaseTx = ( - networkID: number, - blockchainID: Buffer, - amount: BN, - assetID: Buffer, - toAddresses: Buffer[], - fromAddresses: Buffer[], - changeAddresses: Buffer[] = undefined, - fee: BN = undefined, - feeAssetID: Buffer = undefined, - memo: Buffer = undefined, - asOf: BN = UnixNow(), - locktime: BN = new BN(0), - threshold: number = 1 - ): UnsignedTx => { - if (threshold > toAddresses.length) { - /* istanbul ignore next */ - throw new ThresholdError( - "Error - UTXOSet.buildBaseTx: threshold is greater than number of addresses" - ) - } - - if (typeof changeAddresses === "undefined") { - changeAddresses = toAddresses - } - - if (typeof feeAssetID === "undefined") { - feeAssetID = assetID - } - - const zero: BN = new BN(0) - - if (amount.eq(zero)) { - return undefined - } - - const aad: AssetAmountDestination = new AssetAmountDestination( - toAddresses, - fromAddresses, - changeAddresses - ) - if (assetID.toString("hex") === feeAssetID.toString("hex")) { - aad.addAssetAmount(assetID, amount, fee) - } else { - aad.addAssetAmount(assetID, amount, zero) - if (this._feeCheck(fee, feeAssetID)) { - aad.addAssetAmount(feeAssetID, zero, fee) - } - } - - let ins: TransferableInput[] = [] - let outs: TransferableOutput[] = [] - - const minSpendableErr: Error = this.getMinimumSpendable( - aad, - asOf, - locktime, - threshold - ) - if (typeof minSpendableErr === "undefined") { - ins = aad.getInputs() - outs = aad.getAllOutputs() - } else { - throw minSpendableErr - } - - const baseTx: BaseTx = new BaseTx(networkID, blockchainID, outs, ins, memo) - return new UnsignedTx(baseTx) - } - - /** - * Creates an unsigned ImportTx transaction. - * - * @param networkID The number representing NetworkID of the node - * @param blockchainID The {@link https://github.com/feross/buffer|Buffer} representing the BlockchainID for the transaction - * @param toAddresses The addresses to send the funds - * @param fromAddresses The addresses being used to send the funds from the UTXOs {@link https://github.com/feross/buffer|Buffer} - * @param changeAddresses Optional. The addresses that can spend the change remaining from the spent UTXOs. Default: toAddresses - * @param importIns An array of [[TransferableInput]]s being imported - * @param sourceChain A {@link https://github.com/feross/buffer|Buffer} for the chainid where the imports are coming from. - * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN}. Fee will come from the inputs first, if they can. - * @param feeAssetID Optional. The assetID of the fees being burned. - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param locktime Optional. The locktime field created in the resulting outputs - * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO - * @returns An unsigned transaction created from the passed in parameters. - * - */ - buildImportTx = ( - networkID: number, - blockchainID: Buffer, - toAddresses: Buffer[], - fromAddresses: Buffer[], - changeAddresses: Buffer[], - atomics: UTXO[], - sourceChain: Buffer = undefined, - fee: BN = undefined, - feeAssetID: Buffer = undefined, - memo: Buffer = undefined, - asOf: BN = UnixNow(), - locktime: BN = new BN(0), - threshold: number = 1 - ): UnsignedTx => { - const zero: BN = new BN(0) - let ins: TransferableInput[] = [] - let outs: TransferableOutput[] = [] - if (typeof fee === "undefined") { - fee = zero.clone() - } - - const importIns: TransferableInput[] = [] - let feepaid: BN = new BN(0) - let feeAssetStr: string = feeAssetID.toString("hex") - for (let i: number = 0; i < atomics.length; i++) { - const utxo: UTXO = atomics[`${i}`] - const assetID: Buffer = utxo.getAssetID() - const output: AmountOutput = utxo.getOutput() as AmountOutput - let amt: BN = output.getAmount().clone() - - let infeeamount = amt.clone() - let assetStr: string = assetID.toString("hex") - if ( - typeof feeAssetID !== "undefined" && - fee.gt(zero) && - feepaid.lt(fee) && - assetStr === feeAssetStr - ) { - feepaid = feepaid.add(infeeamount) - if (feepaid.gte(fee)) { - infeeamount = feepaid.sub(fee) - feepaid = fee.clone() - } else { - infeeamount = zero.clone() - } - } - - const txid: Buffer = utxo.getTxID() - const outputidx: Buffer = utxo.getOutputIdx() - const input: SECPTransferInput = new SECPTransferInput(amt) - const xferin: TransferableInput = new TransferableInput( - txid, - outputidx, - assetID, - input - ) - const from: Buffer[] = output.getAddresses() - const spenders: Buffer[] = output.getSpenders(from, asOf) - for (let j: number = 0; j < spenders.length; j++) { - const idx: number = output.getAddressIdx(spenders[`${j}`]) - if (idx === -1) { - /* istanbul ignore next */ - throw new AddressError( - "Error - UTXOSet.buildImportTx: no such " + - `address in output: ${spenders[`${j}`]}` - ) - } - xferin.getInput().addSignatureIdx(idx, spenders[`${j}`]) - } - importIns.push(xferin) - //add extra outputs for each amount (calculated from the imported inputs), minus fees - if (infeeamount.gt(zero)) { - const spendout: AmountOutput = SelectOutputClass( - output.getOutputID(), - infeeamount, - toAddresses, - locktime, - threshold - ) as AmountOutput - const xferout: TransferableOutput = new TransferableOutput( - assetID, - spendout - ) - outs.push(xferout) - } - } - - // get remaining fees from the provided addresses - let feeRemaining: BN = fee.sub(feepaid) - if (feeRemaining.gt(zero) && this._feeCheck(feeRemaining, feeAssetID)) { - const aad: AssetAmountDestination = new AssetAmountDestination( - toAddresses, - fromAddresses, - changeAddresses - ) - aad.addAssetAmount(feeAssetID, zero, feeRemaining) - const minSpendableErr: Error = this.getMinimumSpendable( - aad, - asOf, - locktime, - threshold - ) - if (typeof minSpendableErr === "undefined") { - ins = aad.getInputs() - outs = aad.getAllOutputs() - } else { - throw minSpendableErr - } - } - - const importTx: ImportTx = new ImportTx( - networkID, - blockchainID, - outs, - ins, - memo, - sourceChain, - importIns - ) - return new UnsignedTx(importTx) - } - - /** - * Creates an unsigned ExportTx transaction. - * - * @param networkID The number representing NetworkID of the node - * @param blockchainID The {@link https://github.com/feross/buffer|Buffer} representing the BlockchainID for the transaction - * @param amount The amount being exported as a {@link https://github.com/indutny/bn.js/|BN} - * @param avaxAssetID {@link https://github.com/feross/buffer|Buffer} of the asset ID for AVAX - * @param toAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who recieves the AVAX - * @param fromAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who owns the AVAX - * @param changeAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who gets the change leftover of the AVAX - * @param destinationChain Optional. A {@link https://github.com/feross/buffer|Buffer} for the chainid where to send the asset. - * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN} - * @param feeAssetID Optional. The assetID of the fees being burned. - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param locktime Optional. The locktime field created in the resulting outputs - * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO - * - * @returns An unsigned transaction created from the passed in parameters. - * - */ - buildExportTx = ( - networkID: number, - blockchainID: Buffer, - amount: BN, - avaxAssetID: Buffer, // TODO: rename this to amountAssetID - toAddresses: Buffer[], - fromAddresses: Buffer[], - changeAddresses: Buffer[] = undefined, - destinationChain: Buffer = undefined, - fee: BN = undefined, - feeAssetID: Buffer = undefined, - memo: Buffer = undefined, - asOf: BN = UnixNow(), - locktime: BN = new BN(0), - threshold: number = 1 - ): UnsignedTx => { - let ins: TransferableInput[] = [] - let outs: TransferableOutput[] = [] - let exportouts: TransferableOutput[] = [] - - if (typeof changeAddresses === "undefined") { - changeAddresses = toAddresses - } - - const zero: BN = new BN(0) - - if (amount.eq(zero)) { - return undefined - } - - if (typeof feeAssetID === "undefined") { - feeAssetID = avaxAssetID - } else if (feeAssetID.toString("hex") !== avaxAssetID.toString("hex")) { - /* istanbul ignore next */ - throw new FeeAssetError( - "Error - UTXOSet.buildExportTx: " + `feeAssetID must match avaxAssetID` - ) - } - - if (typeof destinationChain === "undefined") { - destinationChain = bintools.cb58Decode( - Defaults.network[`${networkID}`].X["blockchainID"] - ) - } - - const aad: AssetAmountDestination = new AssetAmountDestination( - toAddresses, - fromAddresses, - changeAddresses - ) - if (avaxAssetID.toString("hex") === feeAssetID.toString("hex")) { - aad.addAssetAmount(avaxAssetID, amount, fee) - } else { - aad.addAssetAmount(avaxAssetID, amount, zero) - if (this._feeCheck(fee, feeAssetID)) { - aad.addAssetAmount(feeAssetID, zero, fee) - } - } - - const minSpendableErr: Error = this.getMinimumSpendable( - aad, - asOf, - locktime, - threshold - ) - if (typeof minSpendableErr === "undefined") { - ins = aad.getInputs() - outs = aad.getChangeOutputs() - exportouts = aad.getOutputs() - } else { - throw minSpendableErr - } - - const exportTx: ExportTx = new ExportTx( - networkID, - blockchainID, - outs, - ins, - memo, - destinationChain, - exportouts - ) - - return new UnsignedTx(exportTx) - } - - /** - * Class representing an unsigned [[AddSubnetValidatorTx]] transaction. - * - * @param networkID Networkid, [[DefaultNetworkID]] - * @param blockchainID Blockchainid, default undefined - * @param fromAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who pays the fees in AVAX - * @param changeAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who gets the change leftover from the fee payment - * @param nodeID The node ID of the validator being added. - * @param startTime The Unix time when the validator starts validating the Primary Network. - * @param endTime The Unix time when the validator stops validating the Primary Network (and staked AVAX is returned). - * @param weight The amount of weight for this subnet validator. - * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN} - * @param feeAssetID Optional. The assetID of the fees being burned. - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param subnetAuthCredentials Optional. An array of index and address to sign for each SubnetAuth. - * - * @returns An unsigned transaction created from the passed in parameters. - */ - buildAddSubnetValidatorTx = ( - networkID: number = DefaultNetworkID, - blockchainID: Buffer, - fromAddresses: Buffer[], - changeAddresses: Buffer[], - nodeID: Buffer, - startTime: BN, - endTime: BN, - weight: BN, - subnetID: string, - fee: BN = undefined, - feeAssetID: Buffer = undefined, - memo: Buffer = undefined, - asOf: BN = UnixNow(), - subnetAuthCredentials: [number, Buffer][] = [] - ): UnsignedTx => { - let ins: TransferableInput[] = [] - let outs: TransferableOutput[] = [] - - const zero: BN = new BN(0) - const now: BN = UnixNow() - if (startTime.lt(now) || endTime.lte(startTime)) { - throw new Error( - "UTXOSet.buildAddSubnetValidatorTx -- startTime must be in the future and endTime must come after startTime" - ) - } - - if (this._feeCheck(fee, feeAssetID)) { - const aad: AssetAmountDestination = new AssetAmountDestination( - fromAddresses, - fromAddresses, - changeAddresses - ) - aad.addAssetAmount(feeAssetID, zero, fee) - const success: Error = this.getMinimumSpendable(aad, asOf) - if (typeof success === "undefined") { - ins = aad.getInputs() - outs = aad.getAllOutputs() - } else { - throw success - } - } - - const addSubnetValidatorTx: AddSubnetValidatorTx = new AddSubnetValidatorTx( - networkID, - blockchainID, - outs, - ins, - memo, - nodeID, - startTime, - endTime, - weight, - subnetID - ) - subnetAuthCredentials.forEach( - (subnetAuthCredential: [number, Buffer]): void => { - addSubnetValidatorTx.addSignatureIdx( - subnetAuthCredential[0], - subnetAuthCredential[1] - ) - } - ) - return new UnsignedTx(addSubnetValidatorTx) - } - - /** - * Class representing an unsigned [[AddDelegatorTx]] transaction. - * - * @param networkID Networkid, [[DefaultNetworkID]] - * @param blockchainID Blockchainid, default undefined - * @param avaxAssetID {@link https://github.com/feross/buffer|Buffer} of the asset ID for AVAX - * @param toAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} recieves the stake at the end of the staking period - * @param fromAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who pays the fees and the stake - * @param changeAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who gets the change leftover from the staking payment - * @param nodeID The node ID of the validator being added. - * @param startTime The Unix time when the validator starts validating the Primary Network. - * @param endTime The Unix time when the validator stops validating the Primary Network (and staked AVAX is returned). - * @param stakeAmount A {@link https://github.com/indutny/bn.js/|BN} for the amount of stake to be delegated in nAVAX. - * @param rewardLocktime The locktime field created in the resulting reward outputs - * @param rewardThreshold The number of signatures required to spend the funds in the resultant reward UTXO - * @param rewardAddresses The addresses the validator reward goes. - * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN} - * @param feeAssetID Optional. The assetID of the fees being burned. - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param changeThreshold Optional. The number of signatures required to spend the funds in the change UTXO - * - * @returns An unsigned transaction created from the passed in parameters. - */ - buildAddDelegatorTx = ( - networkID: number = DefaultNetworkID, - blockchainID: Buffer, - avaxAssetID: Buffer, - toAddresses: Buffer[], - fromAddresses: Buffer[], - changeAddresses: Buffer[], - nodeID: Buffer, - startTime: BN, - endTime: BN, - stakeAmount: BN, - rewardLocktime: BN, - rewardThreshold: number, - rewardAddresses: Buffer[], - fee: BN = undefined, - feeAssetID: Buffer = undefined, - memo: Buffer = undefined, - asOf: BN = UnixNow(), - changeThreshold: number = 1 - ): UnsignedTx => { - if (rewardThreshold > rewardAddresses.length) { - /* istanbul ignore next */ - throw new ThresholdError( - "Error - UTXOSet.buildAddDelegatorTx: reward threshold is greater than number of addresses" - ) - } - - if (typeof changeAddresses === "undefined") { - changeAddresses = toAddresses - } - - let ins: TransferableInput[] = [] - let outs: TransferableOutput[] = [] - let stakeOuts: TransferableOutput[] = [] - - const zero: BN = new BN(0) - const now: BN = UnixNow() - if (startTime.lt(now) || endTime.lte(startTime)) { - throw new TimeError( - "UTXOSet.buildAddDelegatorTx -- startTime must be in the future and endTime must come after startTime" - ) - } - - const aad: AssetAmountDestination = new AssetAmountDestination( - toAddresses, - fromAddresses, - changeAddresses - ) - if (avaxAssetID.toString("hex") === feeAssetID.toString("hex")) { - aad.addAssetAmount(avaxAssetID, stakeAmount, fee) - } else { - aad.addAssetAmount(avaxAssetID, stakeAmount, zero) - if (this._feeCheck(fee, feeAssetID)) { - aad.addAssetAmount(feeAssetID, zero, fee) - } - } - - const minSpendableErr: Error = this.getMinimumSpendable( - aad, - asOf, - undefined, - changeThreshold, - true - ) - if (typeof minSpendableErr === "undefined") { - ins = aad.getInputs() - outs = aad.getChangeOutputs() - stakeOuts = aad.getOutputs() - } else { - throw minSpendableErr - } - - const rewardOutputOwners: SECPOwnerOutput = new SECPOwnerOutput( - rewardAddresses, - rewardLocktime, - rewardThreshold - ) - - const UTx: AddDelegatorTx = new AddDelegatorTx( - networkID, - blockchainID, - outs, - ins, - memo, - nodeID, - startTime, - endTime, - stakeAmount, - stakeOuts, - new ParseableOutput(rewardOutputOwners) - ) - return new UnsignedTx(UTx) - } - - /** - * Class representing an unsigned [[AddValidatorTx]] transaction. - * - * @param networkID NetworkID, [[DefaultNetworkID]] - * @param blockchainID BlockchainID, default undefined - * @param avaxAssetID {@link https://github.com/feross/buffer|Buffer} of the asset ID for AVAX - * @param toAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} recieves the stake at the end of the staking period - * @param fromAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who pays the fees and the stake - * @param changeAddresses An array of addresses as {@link https://github.com/feross/buffer|Buffer} who gets the change leftover from the staking payment - * @param nodeID The node ID of the validator being added. - * @param startTime The Unix time when the validator starts validating the Primary Network. - * @param endTime The Unix time when the validator stops validating the Primary Network (and staked AVAX is returned). - * @param stakeAmount A {@link https://github.com/indutny/bn.js/|BN} for the amount of stake to be delegated in nAVAX. - * @param rewardLocktime The locktime field created in the resulting reward outputs - * @param rewardThreshold The number of signatures required to spend the funds in the resultant reward UTXO - * @param rewardAddresses The addresses the validator reward goes. - * @param delegationFee A number for the percentage of reward to be given to the validator when someone delegates to them. Must be between 0 and 100. - * @param minStake A {@link https://github.com/indutny/bn.js/|BN} representing the minimum stake required to validate on this network. - * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN} - * @param feeAssetID Optional. The assetID of the fees being burned. - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * - * @returns An unsigned transaction created from the passed in parameters. - */ - buildAddValidatorTx = ( - networkID: number = DefaultNetworkID, - blockchainID: Buffer, - avaxAssetID: Buffer, - toAddresses: Buffer[], - fromAddresses: Buffer[], - changeAddresses: Buffer[], - nodeID: Buffer, - startTime: BN, - endTime: BN, - stakeAmount: BN, - rewardLocktime: BN, - rewardThreshold: number, - rewardAddresses: Buffer[], - delegationFee: number, - fee: BN = undefined, - feeAssetID: Buffer = undefined, - memo: Buffer = undefined, - asOf: BN = UnixNow() - ): UnsignedTx => { - let ins: TransferableInput[] = [] - let outs: TransferableOutput[] = [] - let stakeOuts: TransferableOutput[] = [] - - const zero: BN = new BN(0) - const now: BN = UnixNow() - if (startTime.lt(now) || endTime.lte(startTime)) { - throw new TimeError( - "UTXOSet.buildAddValidatorTx -- startTime must be in the future and endTime must come after startTime" - ) - } - - if (delegationFee > 100 || delegationFee < 0) { - throw new TimeError( - "UTXOSet.buildAddValidatorTx -- startTime must be in the range of 0 to 100, inclusively" - ) - } - - const aad: AssetAmountDestination = new AssetAmountDestination( - toAddresses, - fromAddresses, - changeAddresses - ) - if (avaxAssetID.toString("hex") === feeAssetID.toString("hex")) { - aad.addAssetAmount(avaxAssetID, stakeAmount, fee) - } else { - aad.addAssetAmount(avaxAssetID, stakeAmount, zero) - if (this._feeCheck(fee, feeAssetID)) { - aad.addAssetAmount(feeAssetID, zero, fee) - } - } - - const minSpendableErr: Error = this.getMinimumSpendable( - aad, - asOf, - undefined, - undefined, - true - ) - if (typeof minSpendableErr === "undefined") { - ins = aad.getInputs() - outs = aad.getChangeOutputs() - stakeOuts = aad.getOutputs() - } else { - throw minSpendableErr - } - - const rewardOutputOwners: SECPOwnerOutput = new SECPOwnerOutput( - rewardAddresses, - rewardLocktime, - rewardThreshold - ) - - const UTx: AddValidatorTx = new AddValidatorTx( - networkID, - blockchainID, - outs, - ins, - memo, - nodeID, - startTime, - endTime, - stakeAmount, - stakeOuts, - new ParseableOutput(rewardOutputOwners), - delegationFee - ) - return new UnsignedTx(UTx) - } - - /** - * Class representing an unsigned [[CreateSubnetTx]] transaction. - * - * @param networkID Networkid, [[DefaultNetworkID]] - * @param blockchainID Blockchainid, default undefined - * @param fromAddresses The addresses being used to send the funds from the UTXOs {@link https://github.com/feross/buffer|Buffer} - * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs. - * @param subnetOwnerAddresses An array of {@link https://github.com/feross/buffer|Buffer} for the addresses to add to a subnet - * @param subnetOwnerThreshold The number of owners's signatures required to add a validator to the network - * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN} - * @param feeAssetID Optional. The assetID of the fees being burned - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * - * @returns An unsigned transaction created from the passed in parameters. - */ - buildCreateSubnetTx = ( - networkID: number = DefaultNetworkID, - blockchainID: Buffer, - fromAddresses: Buffer[], - changeAddresses: Buffer[], - subnetOwnerAddresses: Buffer[], - subnetOwnerThreshold: number, - fee: BN = undefined, - feeAssetID: Buffer = undefined, - memo: Buffer = undefined, - asOf: BN = UnixNow() - ): UnsignedTx => { - const zero: BN = new BN(0) - let ins: TransferableInput[] = [] - let outs: TransferableOutput[] = [] - - if (this._feeCheck(fee, feeAssetID)) { - const aad: AssetAmountDestination = new AssetAmountDestination( - fromAddresses, - fromAddresses, - changeAddresses - ) - aad.addAssetAmount(feeAssetID, zero, fee) - const minSpendableErr: Error = this.getMinimumSpendable( - aad, - asOf, - undefined, - undefined - ) - if (typeof minSpendableErr === "undefined") { - ins = aad.getInputs() - outs = aad.getAllOutputs() - } else { - throw minSpendableErr - } - } - - const locktime: BN = new BN(0) - const subnetOwners: SECPOwnerOutput = new SECPOwnerOutput( - subnetOwnerAddresses, - locktime, - subnetOwnerThreshold - ) - const createSubnetTx: CreateSubnetTx = new CreateSubnetTx( - networkID, - blockchainID, - outs, - ins, - memo, - subnetOwners - ) - - return new UnsignedTx(createSubnetTx) - } - - /** - * Build an unsigned [[CreateChainTx]]. - * - * @param networkID Networkid, [[DefaultNetworkID]] - * @param blockchainID Blockchainid, default undefined - * @param fromAddresses The addresses being used to send the funds from the UTXOs {@link https://github.com/feross/buffer|Buffer} - * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs. - * @param subnetID Optional ID of the Subnet that validates this blockchain - * @param chainName Optional A human readable name for the chain; need not be unique - * @param vmID Optional ID of the VM running on the new chain - * @param fxIDs Optional IDs of the feature extensions running on the new chain - * @param genesisData Optional Byte representation of genesis state of the new chain - * @param fee Optional. The amount of fees to burn in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN} - * @param feeAssetID Optional. The assetID of the fees being burned - * @param memo Optional contains arbitrary bytes, up to 256 bytes - * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * @param subnetAuthCredentials Optional. An array of index and address to sign for each SubnetAuth. - * - * @returns An unsigned CreateChainTx created from the passed in parameters. - */ - buildCreateChainTx = ( - networkID: number = DefaultNetworkID, - blockchainID: Buffer, - fromAddresses: Buffer[], - changeAddresses: Buffer[], - subnetID: string | Buffer = undefined, - chainName: string = undefined, - vmID: string = undefined, - fxIDs: string[] = undefined, - genesisData: string | GenesisData = undefined, - fee: BN = undefined, - feeAssetID: Buffer = undefined, - memo: Buffer = undefined, - asOf: BN = UnixNow(), - subnetAuthCredentials: [number, Buffer][] = [] - ): UnsignedTx => { - const zero: BN = new BN(0) - let ins: TransferableInput[] = [] - let outs: TransferableOutput[] = [] - - if (this._feeCheck(fee, feeAssetID)) { - const aad: AssetAmountDestination = new AssetAmountDestination( - fromAddresses, - fromAddresses, - changeAddresses - ) - aad.addAssetAmount(feeAssetID, zero, fee) - const minSpendableErr: Error = this.getMinimumSpendable( - aad, - asOf, - undefined, - undefined - ) - if (typeof minSpendableErr === "undefined") { - ins = aad.getInputs() - outs = aad.getAllOutputs() - } else { - throw minSpendableErr - } - } - - const createChainTx: CreateChainTx = new CreateChainTx( - networkID, - blockchainID, - outs, - ins, - memo, - subnetID, - chainName, - vmID, - fxIDs, - genesisData - ) - subnetAuthCredentials.forEach( - (subnetAuthCredential: [number, Buffer]): void => { - createChainTx.addSignatureIdx( - subnetAuthCredential[0], - subnetAuthCredential[1] - ) - } - ) - - return new UnsignedTx(createChainTx) - } -} diff --git a/src/apis/platformvm/validationtx.ts b/src/apis/platformvm/validationtx.ts deleted file mode 100644 index 81e29f80b..000000000 --- a/src/apis/platformvm/validationtx.ts +++ /dev/null @@ -1,545 +0,0 @@ -/** - * @packageDocumentation - * @module API-PlatformVM-ValidationTx - */ - -import BN from "bn.js" -import BinTools from "../../utils/bintools" -import { BaseTx } from "./basetx" -import { TransferableOutput } from "../platformvm/outputs" -import { TransferableInput } from "../platformvm/inputs" -import { Buffer } from "buffer/" -import { PlatformVMConstants } from "./constants" -import { DefaultNetworkID } from "../../utils/constants" -import { bufferToNodeIDString } from "../../utils/helperfunctions" -import { AmountOutput, ParseableOutput } from "./outputs" -import { Serialization, SerializedEncoding } from "../../utils/serialization" -import { DelegationFeeError } from "../../utils/errors" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Abstract class representing an transactions with validation information. - */ -export abstract class ValidatorTx extends BaseTx { - protected _typeName = "ValidatorTx" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - nodeID: serialization.encoder(this.nodeID, encoding, "Buffer", "nodeID"), - startTime: serialization.encoder( - this.startTime, - encoding, - "Buffer", - "decimalString" - ), - endTime: serialization.encoder( - this.endTime, - encoding, - "Buffer", - "decimalString" - ) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.nodeID = serialization.decoder( - fields["nodeID"], - encoding, - "nodeID", - "Buffer", - 20 - ) - this.startTime = serialization.decoder( - fields["startTime"], - encoding, - "decimalString", - "Buffer", - 8 - ) - this.endTime = serialization.decoder( - fields["endTime"], - encoding, - "decimalString", - "Buffer", - 8 - ) - } - - protected nodeID: Buffer = Buffer.alloc(20) - protected startTime: Buffer = Buffer.alloc(8) - protected endTime: Buffer = Buffer.alloc(8) - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} for the stake amount. - */ - getNodeID(): Buffer { - return this.nodeID - } - - /** - * Returns a string for the nodeID amount. - */ - getNodeIDString(): string { - return bufferToNodeIDString(this.nodeID) - } - /** - * Returns a {@link https://github.com/indutny/bn.js/|BN} for the stake amount. - */ - getStartTime() { - return bintools.fromBufferToBN(this.startTime) - } - - /** - * Returns a {@link https://github.com/indutny/bn.js/|BN} for the stake amount. - */ - getEndTime() { - return bintools.fromBufferToBN(this.endTime) - } - - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - this.nodeID = bintools.copyFrom(bytes, offset, offset + 20) - offset += 20 - this.startTime = bintools.copyFrom(bytes, offset, offset + 8) - offset += 8 - this.endTime = bintools.copyFrom(bytes, offset, offset + 8) - offset += 8 - return offset - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[ValidatorTx]]. - */ - toBuffer(): Buffer { - const superbuff: Buffer = super.toBuffer() - const bsize: number = - superbuff.length + - this.nodeID.length + - this.startTime.length + - this.endTime.length - return Buffer.concat( - [superbuff, this.nodeID, this.startTime, this.endTime], - bsize - ) - } - - constructor( - networkID: number, - blockchainID: Buffer, - outs: TransferableOutput[], - ins: TransferableInput[], - memo?: Buffer, - nodeID?: Buffer, - startTime?: BN, - endTime?: BN - ) { - super(networkID, blockchainID, outs, ins, memo) - this.nodeID = nodeID - this.startTime = bintools.fromBNToBuffer(startTime, 8) - this.endTime = bintools.fromBNToBuffer(endTime, 8) - } -} - -export abstract class WeightedValidatorTx extends ValidatorTx { - protected _typeName = "WeightedValidatorTx" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - weight: serialization.encoder( - this.weight, - encoding, - "Buffer", - "decimalString" - ) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.weight = serialization.decoder( - fields["weight"], - encoding, - "decimalString", - "Buffer", - 8 - ) - } - - protected weight: Buffer = Buffer.alloc(8) - - /** - * Returns a {@link https://github.com/indutny/bn.js/|BN} for the stake amount. - */ - getWeight(): BN { - return bintools.fromBufferToBN(this.weight) - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} for the stake amount. - */ - getWeightBuffer(): Buffer { - return this.weight - } - - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - this.weight = bintools.copyFrom(bytes, offset, offset + 8) - offset += 8 - return offset - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[AddSubnetValidatorTx]]. - */ - toBuffer(): Buffer { - const superbuff: Buffer = super.toBuffer() - return Buffer.concat([superbuff, this.weight]) - } - - /** - * Class representing an unsigned AddSubnetValidatorTx transaction. - * - * @param networkID Optional. Networkid, [[DefaultNetworkID]] - * @param blockchainID Optional. Blockchainid, default Buffer.alloc(32, 16) - * @param outs Optional. Array of the [[TransferableOutput]]s - * @param ins Optional. Array of the [[TransferableInput]]s - * @param memo Optional. {@link https://github.com/feross/buffer|Buffer} for the memo field - * @param nodeID Optional. The node ID of the validator being added. - * @param startTime Optional. The Unix time when the validator starts validating the Primary Network. - * @param endTime Optional. The Unix time when the validator stops validating the Primary Network (and staked AVAX is returned). - * @param weight Optional. The amount of nAVAX the validator is staking. - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: Buffer = Buffer.alloc(32, 16), - outs: TransferableOutput[] = undefined, - ins: TransferableInput[] = undefined, - memo: Buffer = undefined, - nodeID: Buffer = undefined, - startTime: BN = undefined, - endTime: BN = undefined, - weight: BN = undefined - ) { - super(networkID, blockchainID, outs, ins, memo, nodeID, startTime, endTime) - if (typeof weight !== undefined) { - this.weight = bintools.fromBNToBuffer(weight, 8) - } - } -} - -/** - * Class representing an unsigned AddDelegatorTx transaction. - */ -export class AddDelegatorTx extends WeightedValidatorTx { - protected _typeName = "AddDelegatorTx" - protected _typeID = PlatformVMConstants.ADDDELEGATORTX - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - stakeOuts: this.stakeOuts.map((s) => s.serialize(encoding)), - rewardOwners: this.rewardOwners.serialize(encoding) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.stakeOuts = fields["stakeOuts"].map((s: object) => { - let xferout: TransferableOutput = new TransferableOutput() - xferout.deserialize(s, encoding) - return xferout - }) - this.rewardOwners = new ParseableOutput() - this.rewardOwners.deserialize(fields["rewardOwners"], encoding) - } - - protected stakeOuts: TransferableOutput[] = [] - protected rewardOwners: ParseableOutput = undefined - - /** - * Returns the id of the [[AddDelegatorTx]] - */ - getTxType(): number { - return this._typeID - } - - /** - * Returns a {@link https://github.com/indutny/bn.js/|BN} for the stake amount. - */ - getStakeAmount(): BN { - return this.getWeight() - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} for the stake amount. - */ - getStakeAmountBuffer(): Buffer { - return this.weight - } - - /** - * Returns the array of outputs being staked. - */ - getStakeOuts(): TransferableOutput[] { - return this.stakeOuts - } - - /** - * Should match stakeAmount. Used in sanity checking. - */ - getStakeOutsTotal(): BN { - let val: BN = new BN(0) - for (let i: number = 0; i < this.stakeOuts.length; i++) { - val = val.add( - (this.stakeOuts[`${i}`].getOutput() as AmountOutput).getAmount() - ) - } - return val - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} for the reward address. - */ - getRewardOwners(): ParseableOutput { - return this.rewardOwners - } - - getTotalOuts(): TransferableOutput[] { - return [...(this.getOuts() as TransferableOutput[]), ...this.getStakeOuts()] - } - - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - const numstakeouts = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const outcount: number = numstakeouts.readUInt32BE(0) - this.stakeOuts = [] - for (let i: number = 0; i < outcount; i++) { - const xferout: TransferableOutput = new TransferableOutput() - offset = xferout.fromBuffer(bytes, offset) - this.stakeOuts.push(xferout) - } - this.rewardOwners = new ParseableOutput() - offset = this.rewardOwners.fromBuffer(bytes, offset) - return offset - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[AddDelegatorTx]]. - */ - toBuffer(): Buffer { - const superbuff: Buffer = super.toBuffer() - let bsize: number = superbuff.length - const numouts: Buffer = Buffer.alloc(4) - numouts.writeUInt32BE(this.stakeOuts.length, 0) - let barr: Buffer[] = [super.toBuffer(), numouts] - bsize += numouts.length - this.stakeOuts = this.stakeOuts.sort(TransferableOutput.comparator()) - for (let i: number = 0; i < this.stakeOuts.length; i++) { - let out: Buffer = this.stakeOuts[`${i}`].toBuffer() - barr.push(out) - bsize += out.length - } - let ro: Buffer = this.rewardOwners.toBuffer() - barr.push(ro) - bsize += ro.length - return Buffer.concat(barr, bsize) - } - - clone(): this { - let newbase: AddDelegatorTx = new AddDelegatorTx() - newbase.fromBuffer(this.toBuffer()) - return newbase as this - } - - create(...args: any[]): this { - return new AddDelegatorTx(...args) as this - } - - /** - * Class representing an unsigned AddDelegatorTx transaction. - * - * @param networkID Optional. Networkid, [[DefaultNetworkID]] - * @param blockchainID Optional. Blockchainid, default Buffer.alloc(32, 16) - * @param outs Optional. Array of the [[TransferableOutput]]s - * @param ins Optional. Array of the [[TransferableInput]]s - * @param memo Optional. {@link https://github.com/feross/buffer|Buffer} for the memo field - * @param nodeID Optional. The node ID of the validator being added. - * @param startTime Optional. The Unix time when the validator starts validating the Primary Network. - * @param endTime Optional. The Unix time when the validator stops validating the Primary Network (and staked AVAX is returned). - * @param stakeAmount Optional. The amount of nAVAX the validator is staking. - * @param stakeOuts Optional. The outputs used in paying the stake. - * @param rewardOwners Optional. The [[ParseableOutput]] containing a [[SECPOwnerOutput]] for the rewards. - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: Buffer = Buffer.alloc(32, 16), - outs: TransferableOutput[] = undefined, - ins: TransferableInput[] = undefined, - memo: Buffer = undefined, - nodeID: Buffer = undefined, - startTime: BN = undefined, - endTime: BN = undefined, - stakeAmount: BN = undefined, - stakeOuts: TransferableOutput[] = undefined, - rewardOwners: ParseableOutput = undefined - ) { - super( - networkID, - blockchainID, - outs, - ins, - memo, - nodeID, - startTime, - endTime, - stakeAmount - ) - if (typeof stakeOuts !== undefined) { - this.stakeOuts = stakeOuts - } - this.rewardOwners = rewardOwners - } -} - -export class AddValidatorTx extends AddDelegatorTx { - protected _typeName = "AddValidatorTx" - protected _typeID = PlatformVMConstants.ADDVALIDATORTX - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - delegationFee: serialization.encoder( - this.getDelegationFeeBuffer(), - encoding, - "Buffer", - "decimalString", - 4 - ) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - let dbuff: Buffer = serialization.decoder( - fields["delegationFee"], - encoding, - "decimalString", - "Buffer", - 4 - ) - this.delegationFee = - dbuff.readUInt32BE(0) / AddValidatorTx.delegatorMultiplier - } - - protected delegationFee: number = 0 - private static delegatorMultiplier: number = 10000 - - /** - * Returns the id of the [[AddValidatorTx]] - */ - getTxType(): number { - return this._typeID - } - - /** - * Returns the delegation fee (represents a percentage from 0 to 100); - */ - getDelegationFee(): number { - return this.delegationFee - } - - /** - * Returns the binary representation of the delegation fee as a {@link https://github.com/feross/buffer|Buffer}. - */ - getDelegationFeeBuffer(): Buffer { - let dBuff: Buffer = Buffer.alloc(4) - let buffnum: number = - parseFloat(this.delegationFee.toFixed(4)) * - AddValidatorTx.delegatorMultiplier - dBuff.writeUInt32BE(buffnum, 0) - return dBuff - } - - fromBuffer(bytes: Buffer, offset: number = 0): number { - offset = super.fromBuffer(bytes, offset) - let dbuff: Buffer = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - this.delegationFee = - dbuff.readUInt32BE(0) / AddValidatorTx.delegatorMultiplier - return offset - } - - toBuffer(): Buffer { - let superBuff: Buffer = super.toBuffer() - let feeBuff: Buffer = this.getDelegationFeeBuffer() - return Buffer.concat([superBuff, feeBuff]) - } - - /** - * Class representing an unsigned AddValidatorTx transaction. - * - * @param networkID Optional. Networkid, [[DefaultNetworkID]] - * @param blockchainID Optional. Blockchainid, default Buffer.alloc(32, 16) - * @param outs Optional. Array of the [[TransferableOutput]]s - * @param ins Optional. Array of the [[TransferableInput]]s - * @param memo Optional. {@link https://github.com/feross/buffer|Buffer} for the memo field - * @param nodeID Optional. The node ID of the validator being added. - * @param startTime Optional. The Unix time when the validator starts validating the Primary Network. - * @param endTime Optional. The Unix time when the validator stops validating the Primary Network (and staked AVAX is returned). - * @param stakeAmount Optional. The amount of nAVAX the validator is staking. - * @param stakeOuts Optional. The outputs used in paying the stake. - * @param rewardOwners Optional. The [[ParseableOutput]] containing the [[SECPOwnerOutput]] for the rewards. - * @param delegationFee Optional. The percent fee this validator charges when others delegate stake to them. - * Up to 4 decimal places allowed; additional decimal places are ignored. Must be between 0 and 100, inclusive. - * For example, if delegationFeeRate is 1.2345 and someone delegates to this validator, then when the delegation - * period is over, 1.2345% of the reward goes to the validator and the rest goes to the delegator. - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: Buffer = Buffer.alloc(32, 16), - outs: TransferableOutput[] = undefined, - ins: TransferableInput[] = undefined, - memo: Buffer = undefined, - nodeID: Buffer = undefined, - startTime: BN = undefined, - endTime: BN = undefined, - stakeAmount: BN = undefined, - stakeOuts: TransferableOutput[] = undefined, - rewardOwners: ParseableOutput = undefined, - delegationFee: number = undefined - ) { - super( - networkID, - blockchainID, - outs, - ins, - memo, - nodeID, - startTime, - endTime, - stakeAmount, - stakeOuts, - rewardOwners - ) - if (typeof delegationFee === "number") { - if (delegationFee >= 0 && delegationFee <= 100) { - this.delegationFee = parseFloat(delegationFee.toFixed(4)) - } else { - throw new DelegationFeeError( - "AddValidatorTx.constructor -- delegationFee must be in the range of 0 and 100, inclusively." - ) - } - } - } -} diff --git a/src/apis/socket/index.ts b/src/apis/socket/index.ts deleted file mode 100644 index c39411d31..000000000 --- a/src/apis/socket/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./socket" diff --git a/src/apis/socket/socket.ts b/src/apis/socket/socket.ts deleted file mode 100644 index d86dd6c94..000000000 --- a/src/apis/socket/socket.ts +++ /dev/null @@ -1,50 +0,0 @@ -/** - * @packageDocumentation - * @module API-Socket - */ -import { ClientRequestArgs } from "http" -import WebSocket from "isomorphic-ws" -import { MainnetAPI } from "../../utils" -export class Socket extends WebSocket { - // Fires once the connection has been established between the client and the server - onopen: any - // Fires when the server sends some data - onmessage: any - // Fires after end of the communication between server and the client - onclose: any - // Fires for some mistake, which happens during the communication - onerror: any - - /** - * Send a message to the server - * - * @param data - * @param cb Optional - */ - send(data: any, cb?: any): void { - super.send(data, cb) - } - - /** - * Terminates the connection completely - * - * @param mcode Optional - * @param data Optional - */ - close(mcode?: number, data?: string): void { - super.close(mcode, data) - } - - /** - * Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. - * - * @param url Defaults to [[MainnetAPI]] - * @param options Optional - */ - constructor( - url: string | import("url").URL = `wss://${MainnetAPI}:443/ext/bc/X/events`, - options?: WebSocket.ClientOptions | ClientRequestArgs - ) { - super(url, options) - } -} diff --git a/src/avalanche.ts b/src/avalanche.ts deleted file mode 100644 index d83d7761a..000000000 --- a/src/avalanche.ts +++ /dev/null @@ -1,478 +0,0 @@ -/** - * @packageDocumentation - * @module AvalancheCore - */ -import axios, { - AxiosRequestConfig, - AxiosRequestHeaders, - AxiosResponse, - Method -} from "axios" -import { APIBase, RequestResponseData } from "./common/apibase" -import { ProtocolError } from "./utils/errors" -import { fetchAdapter } from "./utils/fetchadapter" -import { getPreferredHRP } from "./utils/helperfunctions" - -/** - * AvalancheCore is middleware for interacting with Avalanche node RPC APIs. - * - * Example usage: - * ```js - * let avalanche = new AvalancheCore("127.0.0.1", 9650, "https") - * ``` - * - * - */ -export default class AvalancheCore { - protected networkID: number = 0 - protected hrp: string = "" - protected protocol: string - protected ip: string - protected host: string - protected port: number - protected baseEndpoint: string - protected url: string - protected auth: string = undefined - protected headers: { [k: string]: string } = {} - protected requestConfig: AxiosRequestConfig = {} - protected apis: { [k: string]: APIBase } = {} - - /** - * Sets the address and port of the main Avalanche Client. - * - * @param host The hostname to resolve to reach the Avalanche Client RPC APIs. - * @param port The port to resolve to reach the Avalanche Client RPC APIs. - * @param protocol The protocol string to use before a "://" in a request, - * ex: "http", "https", etc. Defaults to http - * @param baseEndpoint the base endpoint to reach the Avalanche Client RPC APIs, - * ex: "/rpc". Defaults to "/" - * The following special characters are removed from host and protocol - * &#,@+()$~%'":*?{} also less than and greater than signs - */ - setAddress = ( - host: string, - port: number, - protocol: string = "http", - baseEndpoint: string = "" - ): void => { - host = host.replace(/[&#,@+()$~%'":*?<>{}]/g, "") - protocol = protocol.replace(/[&#,@+()$~%'":*?<>{}]/g, "") - const protocols: string[] = ["http", "https"] - if (!protocols.includes(protocol)) { - /* istanbul ignore next */ - throw new ProtocolError( - "Error - AvalancheCore.setAddress: Invalid protocol" - ) - } - - this.host = host - this.port = port - this.protocol = protocol - this.baseEndpoint = baseEndpoint - let url: string = `${protocol}://${host}` - if (port != undefined && typeof port === "number" && port >= 0) { - url = `${url}:${port}` - } - if ( - baseEndpoint != undefined && - typeof baseEndpoint == "string" && - baseEndpoint.length > 0 - ) { - if (baseEndpoint[0] != "/") { - baseEndpoint = `/${baseEndpoint}` - } - url = `${url}${baseEndpoint}` - } - this.url = url - } - - /** - * Returns the protocol such as "http", "https", "git", "ws", etc. - */ - getProtocol = (): string => this.protocol - - /** - * Returns the host for the Avalanche node. - */ - getHost = (): string => this.host - - /** - * Returns the IP for the Avalanche node. - */ - getIP = (): string => this.host - - /** - * Returns the port for the Avalanche node. - */ - getPort = (): number => this.port - - /** - * Returns the base endpoint for the Avalanche node. - */ - getBaseEndpoint = (): string => this.baseEndpoint - - /** - * Returns the URL of the Avalanche node (ip + port) - */ - getURL = (): string => this.url - - /** - * Returns the custom headers - */ - getHeaders = (): object => this.headers - - /** - * Returns the custom request config - */ - getRequestConfig = (): AxiosRequestConfig => this.requestConfig - - /** - * Returns the networkID - */ - getNetworkID = (): number => this.networkID - - /** - * Sets the networkID - */ - setNetworkID = (netID: number): void => { - this.networkID = netID - this.hrp = getPreferredHRP(this.networkID) - } - - /** - * Returns the Human-Readable-Part of the network associated with this key. - * - * @returns The [[KeyPair]]'s Human-Readable-Part of the network's Bech32 addressing scheme - */ - getHRP = (): string => this.hrp - - /** - * Sets the the Human-Readable-Part of the network associated with this key. - * - * @param hrp String for the Human-Readable-Part of Bech32 addresses - */ - setHRP = (hrp: string): void => { - this.hrp = hrp - } - - /** - * Adds a new custom header to be included with all requests. - * - * @param key Header name - * @param value Header value - */ - setHeader = (key: string, value: string): void => { - this.headers[`${key}`] = value - } - - /** - * Removes a previously added custom header. - * - * @param key Header name - */ - removeHeader = (key: string): void => { - delete this.headers[`${key}`] - } - - /** - * Removes all headers. - */ - removeAllHeaders = (): void => { - for (const prop in this.headers) { - if (Object.prototype.hasOwnProperty.call(this.headers, prop)) { - delete this.headers[`${prop}`] - } - } - } - - /** - * Adds a new custom config value to be included with all requests. - * - * @param key Config name - * @param value Config value - */ - setRequestConfig = (key: string, value: string | boolean): void => { - this.requestConfig[`${key}`] = value - } - - /** - * Removes a previously added request config. - * - * @param key Header name - */ - removeRequestConfig = (key: string): void => { - delete this.requestConfig[`${key}`] - } - - /** - * Removes all request configs. - */ - removeAllRequestConfigs = (): void => { - for (const prop in this.requestConfig) { - if (Object.prototype.hasOwnProperty.call(this.requestConfig, prop)) { - delete this.requestConfig[`${prop}`] - } - } - } - - /** - * Sets the temporary auth token used for communicating with the node. - * - * @param auth A temporary token provided by the node enabling access to the endpoints on the node. - */ - setAuthToken = (auth: string): void => { - this.auth = auth - } - - protected _setHeaders = (headers: any): AxiosRequestHeaders => { - if (typeof this.headers === "object") { - for (const [key, value] of Object.entries(this.headers)) { - headers[`${key}`] = value - } - } - - if (typeof this.auth === "string") { - headers.Authorization = `Bearer ${this.auth}` - } - return headers - } - - /** - * Adds an API to the middleware. The API resolves to a registered blockchain's RPC. - * - * In TypeScript: - * ```js - * avalanche.addAPI("mychain", MyVMClass, "/ext/bc/mychain") - * ``` - * - * In Javascript: - * ```js - * avalanche.addAPI("mychain", MyVMClass, "/ext/bc/mychain") - * ``` - * - * @typeparam GA Class of the API being added - * @param apiName A label for referencing the API in the future - * @param ConstructorFN A reference to the class which instantiates the API - * @param baseurl Path to resolve to reach the API - * - */ - addAPI = ( - apiName: string, - ConstructorFN: new ( - avax: AvalancheCore, - baseurl?: string, - ...args: any[] - ) => GA, - baseurl: string = undefined, - ...args: any[] - ) => { - if (typeof baseurl === "undefined") { - this.apis[`${apiName}`] = new ConstructorFN(this, undefined, ...args) - } else { - this.apis[`${apiName}`] = new ConstructorFN(this, baseurl, ...args) - } - } - - /** - * Retrieves a reference to an API by its apiName label. - * - * @param apiName Name of the API to return - */ - api = (apiName: string): GA => - this.apis[`${apiName}`] as GA - - /** - * @ignore - */ - protected _request = async ( - xhrmethod: Method, - baseurl: string, - getdata: object, - postdata: string | object | ArrayBuffer | ArrayBufferView, - headers: AxiosRequestHeaders = {}, - axiosConfig: AxiosRequestConfig = undefined - ): Promise => { - let config: AxiosRequestConfig - if (axiosConfig) { - config = { - ...axiosConfig, - ...this.requestConfig - } - } else { - config = { - baseURL: this.url, - responseType: "text", - ...this.requestConfig - } - } - config.url = baseurl - config.method = xhrmethod - config.headers = headers - config.data = postdata - config.params = getdata - // use the fetch adapter if fetch is available e.g. non Node<17 env - if (typeof fetch !== "undefined") { - config.adapter = fetchAdapter - } - const resp: AxiosResponse = await axios.request(config) - // purging all that is axios - const xhrdata: RequestResponseData = new RequestResponseData( - resp.data, - resp.headers, - resp.status, - resp.statusText, - resp.request - ) - return xhrdata - } - - /** - * Makes a GET call to an API. - * - * @param baseurl Path to the api - * @param getdata Object containing the key value pairs sent in GET - * @param headers An array HTTP Request Headers - * @param axiosConfig Configuration for the axios javascript library that will be the - * foundation for the rest of the parameters - * - * @returns A promise for [[RequestResponseData]] - */ - get = ( - baseurl: string, - getdata: object, - headers: object = {}, - axiosConfig: AxiosRequestConfig = undefined - ): Promise => - this._request( - "GET", - baseurl, - getdata, - {}, - this._setHeaders(headers), - axiosConfig - ) - - /** - * Makes a DELETE call to an API. - * - * @param baseurl Path to the API - * @param getdata Object containing the key value pairs sent in DELETE - * @param headers An array HTTP Request Headers - * @param axiosConfig Configuration for the axios javascript library that will be the - * foundation for the rest of the parameters - * - * @returns A promise for [[RequestResponseData]] - */ - delete = ( - baseurl: string, - getdata: object, - headers: object = {}, - axiosConfig: AxiosRequestConfig = undefined - ): Promise => - this._request( - "DELETE", - baseurl, - getdata, - {}, - this._setHeaders(headers), - axiosConfig - ) - - /** - * Makes a POST call to an API. - * - * @param baseurl Path to the API - * @param getdata Object containing the key value pairs sent in POST - * @param postdata Object containing the key value pairs sent in POST - * @param headers An array HTTP Request Headers - * @param axiosConfig Configuration for the axios javascript library that will be the - * foundation for the rest of the parameters - * - * @returns A promise for [[RequestResponseData]] - */ - post = ( - baseurl: string, - getdata: object, - postdata: string | object | ArrayBuffer | ArrayBufferView, - headers: object = {}, - axiosConfig: AxiosRequestConfig = undefined - ): Promise => - this._request( - "POST", - baseurl, - getdata, - postdata, - this._setHeaders(headers), - axiosConfig - ) - - /** - * Makes a PUT call to an API. - * - * @param baseurl Path to the baseurl - * @param getdata Object containing the key value pairs sent in PUT - * @param postdata Object containing the key value pairs sent in PUT - * @param headers An array HTTP Request Headers - * @param axiosConfig Configuration for the axios javascript library that will be the - * foundation for the rest of the parameters - * - * @returns A promise for [[RequestResponseData]] - */ - put = ( - baseurl: string, - getdata: object, - postdata: string | object | ArrayBuffer | ArrayBufferView, - headers: object = {}, - axiosConfig: AxiosRequestConfig = undefined - ): Promise => - this._request( - "PUT", - baseurl, - getdata, - postdata, - this._setHeaders(headers), - axiosConfig - ) - - /** - * Makes a PATCH call to an API. - * - * @param baseurl Path to the baseurl - * @param getdata Object containing the key value pairs sent in PATCH - * @param postdata Object containing the key value pairs sent in PATCH - * @param parameters Object containing the parameters of the API call - * @param headers An array HTTP Request Headers - * @param axiosConfig Configuration for the axios javascript library that will be the - * foundation for the rest of the parameters - * - * @returns A promise for [[RequestResponseData]] - */ - patch = ( - baseurl: string, - getdata: object, - postdata: string | object | ArrayBuffer | ArrayBufferView, - headers: object = {}, - axiosConfig: AxiosRequestConfig = undefined - ): Promise => - this._request( - "PATCH", - baseurl, - getdata, - postdata, - this._setHeaders(headers), - axiosConfig - ) - - /** - * Creates a new Avalanche instance. Sets the address and port of the main Avalanche Client. - * - * @param host The hostname to resolve to reach the Avalanche Client APIs - * @param port The port to resolve to reach the Avalanche Client APIs - * @param protocol The protocol string to use before a "://" in a request, ex: "http", "https", "git", "ws", etc ... - */ - constructor(host?: string, port?: number, protocol: string = "http") { - if (host != undefined) { - this.setAddress(host, port, protocol) - } - } -} diff --git a/src/common/apibase.ts b/src/common/apibase.ts deleted file mode 100644 index 4f38f947b..000000000 --- a/src/common/apibase.ts +++ /dev/null @@ -1,69 +0,0 @@ -/** - * @packageDocumentation - * @module Common-APIBase - */ - -import { StoreAPI } from "store2" -import { ClientRequest } from "http" -import DB from "../utils/db" -import AvalancheCore from "../avalanche" - -/** - * Response data for HTTP requests. - */ -export class RequestResponseData { - constructor( - public data: any, - public headers: any, - public status: number, - public statusText: string, - public request: ClientRequest | XMLHttpRequest - ) {} -} - -/** - * Abstract class defining a generic endpoint that all endpoints must implement (extend). - */ -export abstract class APIBase { - protected core: AvalancheCore - protected baseURL: string - protected db: StoreAPI - - /** - * Sets the path of the APIs baseURL. - * - * @param baseURL Path of the APIs baseURL - ex: "/ext/bc/X" - */ - setBaseURL = (baseURL: string) => { - if (this.db && this.baseURL !== baseURL) { - const backup = this.db.getAll() - this.db.clearAll() - this.baseURL = baseURL - this.db = DB.getNamespace(baseURL) - this.db.setAll(backup, true) - } else { - this.baseURL = baseURL - this.db = DB.getNamespace(baseURL) - } - } - - /** - * Returns the baseURL's path. - */ - getBaseURL = (): string => this.baseURL - - /** - * Returns the baseURL's database. - */ - getDB = (): StoreAPI => this.db - - /** - * - * @param core Reference to the Avalanche instance using this baseURL - * @param baseURL Path to the baseURL - */ - constructor(core: AvalancheCore, baseURL: string) { - this.core = core - this.setBaseURL(baseURL) - } -} diff --git a/src/common/assetamount.ts b/src/common/assetamount.ts deleted file mode 100644 index e205fe0de..000000000 --- a/src/common/assetamount.ts +++ /dev/null @@ -1,201 +0,0 @@ -/** - * @packageDocumentation - * @module Common-AssetAmount - */ - -import { Buffer } from "buffer/" -import BN from "bn.js" -import { StandardTransferableOutput } from "./output" -import { StandardTransferableInput } from "./input" -import { InsufficientFundsError } from "../utils/errors" - -/** - * Class for managing asset amounts in the UTXOSet fee calcuation - */ -export class AssetAmount { - // assetID that is amount is managing. - protected assetID: Buffer = Buffer.alloc(32) - // amount of this asset that should be sent. - protected amount: BN = new BN(0) - // burn is the amount of this asset that should be burned. - protected burn: BN = new BN(0) - - // spent is the total amount of this asset that has been consumed. - protected spent: BN = new BN(0) - // stakeableLockSpent is the amount of this asset that has been consumed that - // was locked. - protected stakeableLockSpent: BN = new BN(0) - - // change is the excess amount of this asset that was consumed over the amount - // requested to be consumed(amount + burn). - protected change: BN = new BN(0) - // stakeableLockChange is a flag to mark if the input that generated the - // change was locked. - protected stakeableLockChange: boolean = false - - // finished is a convenience flag to track "spent >= amount + burn" - protected finished: boolean = false - - getAssetID = (): Buffer => { - return this.assetID - } - - getAssetIDString = (): string => { - return this.assetID.toString("hex") - } - - getAmount = (): BN => { - return this.amount - } - - getSpent = (): BN => { - return this.spent - } - - getBurn = (): BN => { - return this.burn - } - - getChange = (): BN => { - return this.change - } - - getStakeableLockSpent = (): BN => { - return this.stakeableLockSpent - } - - getStakeableLockChange = (): boolean => { - return this.stakeableLockChange - } - - isFinished = (): boolean => { - return this.finished - } - - // spendAmount should only be called if this asset is still awaiting more - // funds to consume. - spendAmount = (amt: BN, stakeableLocked: boolean = false): boolean => { - if (this.finished) { - /* istanbul ignore next */ - throw new InsufficientFundsError( - "Error - AssetAmount.spendAmount: attempted to spend " + "excess funds" - ) - } - this.spent = this.spent.add(amt) - if (stakeableLocked) { - this.stakeableLockSpent = this.stakeableLockSpent.add(amt) - } - - const total: BN = this.amount.add(this.burn) - if (this.spent.gte(total)) { - this.change = this.spent.sub(total) - if (stakeableLocked) { - this.stakeableLockChange = true - } - this.finished = true - } - return this.finished - } - - constructor(assetID: Buffer, amount: BN, burn: BN) { - this.assetID = assetID - this.amount = typeof amount === "undefined" ? new BN(0) : amount - this.burn = typeof burn === "undefined" ? new BN(0) : burn - this.spent = new BN(0) - this.stakeableLockSpent = new BN(0) - this.stakeableLockChange = false - } -} - -export abstract class StandardAssetAmountDestination< - TO extends StandardTransferableOutput, - TI extends StandardTransferableInput -> { - protected amounts: AssetAmount[] = [] - protected destinations: Buffer[] = [] - protected senders: Buffer[] = [] - protected changeAddresses: Buffer[] = [] - protected amountkey: object = {} - protected inputs: TI[] = [] - protected outputs: TO[] = [] - protected change: TO[] = [] - - // TODO: should this function allow for repeated calls with the same - // assetID? - addAssetAmount = (assetID: Buffer, amount: BN, burn: BN) => { - let aa: AssetAmount = new AssetAmount(assetID, amount, burn) - this.amounts.push(aa) - this.amountkey[aa.getAssetIDString()] = aa - } - - addInput = (input: TI) => { - this.inputs.push(input) - } - - addOutput = (output: TO) => { - this.outputs.push(output) - } - - addChange = (output: TO) => { - this.change.push(output) - } - - getAmounts = (): AssetAmount[] => { - return this.amounts - } - - getDestinations = (): Buffer[] => { - return this.destinations - } - - getSenders = (): Buffer[] => { - return this.senders - } - - getChangeAddresses = (): Buffer[] => { - return this.changeAddresses - } - - getAssetAmount = (assetHexStr: string): AssetAmount => { - return this.amountkey[`${assetHexStr}`] - } - - assetExists = (assetHexStr: string): boolean => { - return assetHexStr in this.amountkey - } - - getInputs = (): TI[] => { - return this.inputs - } - - getOutputs = (): TO[] => { - return this.outputs - } - - getChangeOutputs = (): TO[] => { - return this.change - } - - getAllOutputs = (): TO[] => { - return this.outputs.concat(this.change) - } - - canComplete = (): boolean => { - for (let i: number = 0; i < this.amounts.length; i++) { - if (!this.amounts[`${i}`].isFinished()) { - return false - } - } - return true - } - - constructor( - destinations: Buffer[], - senders: Buffer[], - changeAddresses: Buffer[] - ) { - this.destinations = destinations - this.changeAddresses = changeAddresses - this.senders = senders - } -} diff --git a/src/common/credentials.ts b/src/common/credentials.ts deleted file mode 100644 index 7eff46a92..000000000 --- a/src/common/credentials.ts +++ /dev/null @@ -1,184 +0,0 @@ -/** - * @packageDocumentation - * @module Common-Signature - */ -import { NBytes } from "./nbytes" -import { Buffer } from "buffer/" -import BinTools from "../utils/bintools" -import { - Serializable, - Serialization, - SerializedEncoding -} from "../utils/serialization" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Type representing a [[Signature]] index used in [[Input]] - */ -export class SigIdx extends NBytes { - protected _typeName = "SigIdx" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - source: serialization.encoder(this.source, encoding, "Buffer", "hex") - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.source = serialization.decoder( - fields["source"], - encoding, - "hex", - "Buffer" - ) - } - - protected source: Buffer = Buffer.alloc(20) - protected bytes = Buffer.alloc(4) - protected bsize = 4 - - /** - * Sets the source address for the signature - */ - setSource = (address: Buffer) => { - this.source = address - } - - /** - * Retrieves the source address for the signature - */ - getSource = (): Buffer => this.source - - clone(): this { - let newbase: SigIdx = new SigIdx() - newbase.fromBuffer(this.toBuffer()) - return newbase as this - } - - create(...args: any[]): this { - return new SigIdx() as this - } - - /** - * Type representing a [[Signature]] index used in [[Input]] - */ - constructor() { - super() - } -} - -/** - * Signature for a [[Tx]] - */ -export class Signature extends NBytes { - protected _typeName = "Signature" - protected _typeID = undefined - - //serialize and deserialize both are inherited - - protected bytes = Buffer.alloc(65) - protected bsize = 65 - - clone(): this { - let newbase: Signature = new Signature() - newbase.fromBuffer(this.toBuffer()) - return newbase as this - } - - create(...args: any[]): this { - return new Signature() as this - } - - /** - * Signature for a [[Tx]] - */ - constructor() { - super() - } -} - -export abstract class Credential extends Serializable { - protected _typeName = "Credential" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - sigArray: this.sigArray.map((s) => s.serialize(encoding)) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.sigArray = fields["sigArray"].map((s: object) => { - let sig: Signature = new Signature() - sig.deserialize(s, encoding) - return sig - }) - } - - protected sigArray: Signature[] = [] - - abstract getCredentialID(): number - - /** - * Set the codecID - * - * @param codecID The codecID to set - */ - setCodecID(codecID: number): void {} - - /** - * Adds a signature to the credentials and returns the index off the added signature. - */ - addSignature = (sig: Signature): number => { - this.sigArray.push(sig) - return this.sigArray.length - 1 - } - - fromBuffer(bytes: Buffer, offset: number = 0): number { - const siglen: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.sigArray = [] - for (let i: number = 0; i < siglen; i++) { - const sig: Signature = new Signature() - offset = sig.fromBuffer(bytes, offset) - this.sigArray.push(sig) - } - return offset - } - - toBuffer(): Buffer { - const siglen: Buffer = Buffer.alloc(4) - siglen.writeInt32BE(this.sigArray.length, 0) - const barr: Buffer[] = [siglen] - let bsize: number = siglen.length - for (let i: number = 0; i < this.sigArray.length; i++) { - const sigbuff: Buffer = this.sigArray[`${i}`].toBuffer() - bsize += sigbuff.length - barr.push(sigbuff) - } - return Buffer.concat(barr, bsize) - } - - abstract clone(): this - abstract create(...args: any[]): this - abstract select(id: number, ...args: any[]): Credential - constructor(sigarray: Signature[] = undefined) { - super() - if (typeof sigarray !== "undefined") { - /* istanbul ignore next */ - this.sigArray = sigarray - } - } -} diff --git a/src/common/evmtx.ts b/src/common/evmtx.ts deleted file mode 100644 index 8da5dc6af..000000000 --- a/src/common/evmtx.ts +++ /dev/null @@ -1,385 +0,0 @@ -/** - * @packageDocumentation - * @module Common-Transactions - */ - -import { Buffer } from "buffer/" -import BinTools from "../utils/bintools" -import { Credential } from "./credentials" -import BN from "bn.js" -import { StandardKeyChain, StandardKeyPair } from "./keychain" -import { StandardAmountInput, StandardTransferableInput } from "./input" -import { StandardAmountOutput, StandardTransferableOutput } from "./output" -import { DefaultNetworkID } from "../utils/constants" -import { - Serializable, - Serialization, - SerializedEncoding -} from "../utils/serialization" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serializer: Serialization = Serialization.getInstance() - -/** - * Class representing a base for all transactions. - */ -export abstract class EVMStandardBaseTx< - KPClass extends StandardKeyPair, - KCClass extends StandardKeyChain -> extends Serializable { - protected _typeName = "EVMStandardBaseTx" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - networkID: serializer.encoder( - this.networkID, - encoding, - "Buffer", - "decimalString" - ), - blockchainID: serializer.encoder( - this.blockchainID, - encoding, - "Buffer", - "cb58" - ) - } - } - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.networkID = serializer.decoder( - fields["networkID"], - encoding, - "decimalString", - "Buffer", - 4 - ) - this.blockchainID = serializer.decoder( - fields["blockchainID"], - encoding, - "cb58", - "Buffer", - 32 - ) - } - - protected networkID: Buffer = Buffer.alloc(4) - protected blockchainID: Buffer = Buffer.alloc(32) - - /** - * Returns the id of the [[StandardBaseTx]] - */ - abstract getTxType(): number - - /** - * Returns the NetworkID as a number - */ - getNetworkID(): number { - return this.networkID.readUInt32BE(0) - } - - /** - * Returns the Buffer representation of the BlockchainID - */ - getBlockchainID(): Buffer { - return this.blockchainID - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[StandardBaseTx]]. - */ - toBuffer(): Buffer { - let bsize: number = this.networkID.length + this.blockchainID.length - const barr: Buffer[] = [this.networkID, this.blockchainID] - const buff: Buffer = Buffer.concat(barr, bsize) - return buff - } - - /** - * Returns a base-58 representation of the [[StandardBaseTx]]. - */ - toString(): string { - return bintools.bufferToB58(this.toBuffer()) - } - - abstract clone(): this - - abstract create(...args: any[]): this - - abstract select(id: number, ...args: any[]): this - - /** - * Class representing a StandardBaseTx which is the foundation for all transactions. - * - * @param networkID Optional networkID, [[DefaultNetworkID]] - * @param blockchainID Optional blockchainID, default Buffer.alloc(32, 16) - * @param outs Optional array of the [[TransferableOutput]]s - * @param ins Optional array of the [[TransferableInput]]s - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: Buffer = Buffer.alloc(32, 16) - ) { - super() - this.networkID.writeUInt32BE(networkID, 0) - this.blockchainID = blockchainID - } -} - -/** - * Class representing an unsigned transaction. - */ -export abstract class EVMStandardUnsignedTx< - KPClass extends StandardKeyPair, - KCClass extends StandardKeyChain, - SBTx extends EVMStandardBaseTx -> extends Serializable { - protected _typeName = "StandardUnsignedTx" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - codecID: serializer.encoder( - this.codecID, - encoding, - "number", - "decimalString", - 2 - ), - transaction: this.transaction.serialize(encoding) - } - } - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.codecID = serializer.decoder( - fields["codecID"], - encoding, - "decimalString", - "number" - ) - } - - protected codecID: number = 0 - protected transaction: SBTx - - /** - * Returns the CodecID as a number - */ - getCodecID(): number { - return this.codecID - } - - /** - * Returns the {@link https://github.com/feross/buffer|Buffer} representation of the CodecID - */ - getCodecIDBuffer(): Buffer { - let codecBuf: Buffer = Buffer.alloc(2) - codecBuf.writeUInt16BE(this.codecID, 0) - return codecBuf - } - - /** - * Returns the inputTotal as a BN - */ - getInputTotal(assetID: Buffer): BN { - const ins: StandardTransferableInput[] = [] - const aIDHex: string = assetID.toString("hex") - let total: BN = new BN(0) - ins.forEach((input: StandardTransferableInput) => { - // only check StandardAmountInputs - if ( - input.getInput() instanceof StandardAmountInput && - aIDHex === input.getAssetID().toString("hex") - ) { - const i = input.getInput() as StandardAmountInput - total = total.add(i.getAmount()) - } - }) - return total - } - - /** - * Returns the outputTotal as a BN - */ - getOutputTotal(assetID: Buffer): BN { - const outs: StandardTransferableOutput[] = [] - const aIDHex: string = assetID.toString("hex") - let total: BN = new BN(0) - - outs.forEach((out: StandardTransferableOutput) => { - // only check StandardAmountOutput - if ( - out.getOutput() instanceof StandardAmountOutput && - aIDHex === out.getAssetID().toString("hex") - ) { - const output: StandardAmountOutput = - out.getOutput() as StandardAmountOutput - total = total.add(output.getAmount()) - } - }) - return total - } - - /** - * Returns the number of burned tokens as a BN - */ - getBurn(assetID: Buffer): BN { - return this.getInputTotal(assetID).sub(this.getOutputTotal(assetID)) - } - - /** - * Returns the Transaction - */ - abstract getTransaction(): SBTx - - abstract fromBuffer(bytes: Buffer, offset?: number): number - - toBuffer(): Buffer { - const codecID: Buffer = this.getCodecIDBuffer() - const txtype: Buffer = Buffer.alloc(4) - txtype.writeUInt32BE(this.transaction.getTxType(), 0) - const basebuff: Buffer = this.transaction.toBuffer() - return Buffer.concat( - [codecID, txtype, basebuff], - codecID.length + txtype.length + basebuff.length - ) - } - - /** - * Signs this [[UnsignedTx]] and returns signed [[StandardTx]] - * - * @param kc An [[KeyChain]] used in signing - * - * @returns A signed [[StandardTx]] - */ - abstract sign( - kc: KCClass - ): EVMStandardTx< - KPClass, - KCClass, - EVMStandardUnsignedTx - > - - constructor(transaction: SBTx = undefined, codecID: number = 0) { - super() - this.codecID = codecID - this.transaction = transaction - } -} - -/** - * Class representing a signed transaction. - */ -export abstract class EVMStandardTx< - KPClass extends StandardKeyPair, - KCClass extends StandardKeyChain, - SUBTx extends EVMStandardUnsignedTx< - KPClass, - KCClass, - EVMStandardBaseTx - > -> extends Serializable { - protected _typeName = "StandardTx" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - unsignedTx: this.unsignedTx.serialize(encoding), - credentials: this.credentials.map((c) => c.serialize(encoding)) - } - } - - protected unsignedTx: SUBTx = undefined - protected credentials: Credential[] = [] - - /** - * Returns the [[StandardUnsignedTx]] - */ - getUnsignedTx(): SUBTx { - return this.unsignedTx - } - - abstract fromBuffer(bytes: Buffer, offset?: number): number - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[StandardTx]]. - */ - toBuffer(): Buffer { - const txbuff: Buffer = this.unsignedTx.toBuffer() - let bsize: number = txbuff.length - const credlen: Buffer = Buffer.alloc(4) - credlen.writeUInt32BE(this.credentials.length, 0) - const barr: Buffer[] = [txbuff, credlen] - bsize += credlen.length - this.credentials.forEach((credential: Credential) => { - const credid: Buffer = Buffer.alloc(4) - credid.writeUInt32BE(credential.getCredentialID(), 0) - barr.push(credid) - bsize += credid.length - const credbuff: Buffer = credential.toBuffer() - bsize += credbuff.length - barr.push(credbuff) - }) - const buff: Buffer = Buffer.concat(barr, bsize) - return buff - } - - /** - * Takes a base-58 string containing an [[StandardTx]], parses it, populates the class, and returns the length of the Tx in bytes. - * - * @param serialized A base-58 string containing a raw [[StandardTx]] - * - * @returns The length of the raw [[StandardTx]] - * - * @remarks - * unlike most fromStrings, it expects the string to be serialized in cb58 format - */ - fromString(serialized: string): number { - return this.fromBuffer(bintools.cb58Decode(serialized)) - } - - /** - * Returns a cb58 representation of the [[StandardTx]]. - * - * @remarks - * unlike most toStrings, this returns in cb58 serialization format - */ - toString(): string { - return bintools.cb58Encode(this.toBuffer()) - } - - toStringHex(): string { - return `0x${bintools.addChecksum(this.toBuffer()).toString("hex")}` - } - - /** - * Class representing a signed transaction. - * - * @param unsignedTx Optional [[StandardUnsignedTx]] - * @param signatures Optional array of [[Credential]]s - */ - constructor( - unsignedTx: SUBTx = undefined, - credentials: Credential[] = undefined - ) { - super() - if (typeof unsignedTx !== "undefined") { - this.unsignedTx = unsignedTx - if (typeof credentials !== "undefined") { - this.credentials = credentials - } - } - } -} diff --git a/src/common/index.ts b/src/common/index.ts deleted file mode 100644 index 21880c041..000000000 --- a/src/common/index.ts +++ /dev/null @@ -1,14 +0,0 @@ -export * from "./apibase" -export * from "./assetamount" -export * from "./credentials" -export * from "./evmtx" -export * from "./input" -export * from "./interfaces" -export * from "./jrpcapi" -export * from "./keychain" -export * from "./nbytes" -export * from "./output" -export * from "./restapi" -export * from "./secp256k1" -export * from "./tx" -export * from "./utxos" diff --git a/src/common/input.ts b/src/common/input.ts deleted file mode 100644 index 8eb5b6fe5..000000000 --- a/src/common/input.ts +++ /dev/null @@ -1,392 +0,0 @@ -/** - * @packageDocumentation - * @module Common-Inputs - */ -import { Buffer } from "buffer/" -import BinTools from "../utils/bintools" -import BN from "bn.js" -import { SigIdx } from "./credentials" -import { - Serializable, - Serialization, - SerializedEncoding -} from "../utils/serialization" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -export abstract class Input extends Serializable { - protected _typeName = "Input" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - sigIdxs: this.sigIdxs.map((s) => s.serialize(encoding)) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.sigIdxs = fields["sigIdxs"].map((s: object) => { - let sidx: SigIdx = new SigIdx() - sidx.deserialize(s, encoding) - return sidx - }) - this.sigCount.writeUInt32BE(this.sigIdxs.length, 0) - } - - protected sigCount: Buffer = Buffer.alloc(4) - protected sigIdxs: SigIdx[] = [] // idxs of signers from utxo - - static comparator = - (): ((a: Input, b: Input) => 1 | -1 | 0) => - (a: Input, b: Input): 1 | -1 | 0 => { - const aoutid: Buffer = Buffer.alloc(4) - aoutid.writeUInt32BE(a.getInputID(), 0) - const abuff: Buffer = a.toBuffer() - - const boutid: Buffer = Buffer.alloc(4) - boutid.writeUInt32BE(b.getInputID(), 0) - const bbuff: Buffer = b.toBuffer() - - const asort: Buffer = Buffer.concat( - [aoutid, abuff], - aoutid.length + abuff.length - ) - const bsort: Buffer = Buffer.concat( - [boutid, bbuff], - boutid.length + bbuff.length - ) - return Buffer.compare(asort, bsort) as 1 | -1 | 0 - } - - abstract getInputID(): number - - /** - * Returns the array of [[SigIdx]] for this [[Input]] - */ - getSigIdxs = (): SigIdx[] => this.sigIdxs - - abstract getCredentialID(): number - - /** - * Creates and adds a [[SigIdx]] to the [[Input]]. - * - * @param addressIdx The index of the address to reference in the signatures - * @param address The address of the source of the signature - */ - addSignatureIdx = (addressIdx: number, address: Buffer) => { - const sigidx: SigIdx = new SigIdx() - const b: Buffer = Buffer.alloc(4) - b.writeUInt32BE(addressIdx, 0) - sigidx.fromBuffer(b) - sigidx.setSource(address) - this.sigIdxs.push(sigidx) - this.sigCount.writeUInt32BE(this.sigIdxs.length, 0) - } - - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.sigCount = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const sigCount: number = this.sigCount.readUInt32BE(0) - this.sigIdxs = [] - for (let i: number = 0; i < sigCount; i++) { - const sigidx = new SigIdx() - const sigbuff: Buffer = bintools.copyFrom(bytes, offset, offset + 4) - sigidx.fromBuffer(sigbuff) - offset += 4 - this.sigIdxs.push(sigidx) - } - return offset - } - - toBuffer(): Buffer { - this.sigCount.writeUInt32BE(this.sigIdxs.length, 0) - let bsize: number = this.sigCount.length - const barr: Buffer[] = [this.sigCount] - for (let i: number = 0; i < this.sigIdxs.length; i++) { - const b: Buffer = this.sigIdxs[`${i}`].toBuffer() - barr.push(b) - bsize += b.length - } - return Buffer.concat(barr, bsize) - } - - /** - * Returns a base-58 representation of the [[Input]]. - */ - toString(): string { - return bintools.bufferToB58(this.toBuffer()) - } - - abstract clone(): this - - abstract create(...args: any[]): this - - abstract select(id: number, ...args: any[]): Input -} - -export abstract class StandardParseableInput extends Serializable { - protected _typeName = "StandardParseableInput" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - input: this.input.serialize(encoding) - } - } - - protected input: Input - - /** - * Returns a function used to sort an array of [[StandardParseableInput]]s - */ - static comparator = - (): (( - a: StandardParseableInput, - b: StandardParseableInput - ) => 1 | -1 | 0) => - (a: StandardParseableInput, b: StandardParseableInput): 1 | -1 | 0 => { - const sorta = a.toBuffer() - const sortb = b.toBuffer() - return Buffer.compare(sorta, sortb) as 1 | -1 | 0 - } - - getInput = (): Input => this.input - - // must be implemented to select input types for the VM in question - abstract fromBuffer(bytes: Buffer, offset?: number): number - - toBuffer(): Buffer { - const inbuff: Buffer = this.input.toBuffer() - const inid: Buffer = Buffer.alloc(4) - inid.writeUInt32BE(this.input.getInputID(), 0) - const barr: Buffer[] = [inid, inbuff] - return Buffer.concat(barr, inid.length + inbuff.length) - } - - /** - * Class representing an [[StandardParseableInput]] for a transaction. - * - * @param input A number representing the InputID of the [[StandardParseableInput]] - */ - constructor(input: Input = undefined) { - super() - if (input instanceof Input) { - this.input = input - } - } -} - -export abstract class StandardTransferableInput extends StandardParseableInput { - protected _typeName = "StandardTransferableInput" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - txid: serialization.encoder(this.txid, encoding, "Buffer", "cb58"), - outputidx: serialization.encoder( - this.outputidx, - encoding, - "Buffer", - "decimalString" - ), - assetID: serialization.encoder(this.assetID, encoding, "Buffer", "cb58") - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.txid = serialization.decoder( - fields["txid"], - encoding, - "cb58", - "Buffer", - 32 - ) - this.outputidx = serialization.decoder( - fields["outputidx"], - encoding, - "decimalString", - "Buffer", - 4 - ) - this.assetID = serialization.decoder( - fields["assetID"], - encoding, - "cb58", - "Buffer", - 32 - ) - //input deserialization must be implmented in child classes - } - - protected txid: Buffer = Buffer.alloc(32) - protected outputidx: Buffer = Buffer.alloc(4) - protected assetID: Buffer = Buffer.alloc(32) - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} of the TxID. - */ - getTxID = (): /* istanbul ignore next */ Buffer => this.txid - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} of the OutputIdx. - */ - getOutputIdx = (): /* istanbul ignore next */ Buffer => this.outputidx - - /** - * Returns a base-58 string representation of the UTXOID this [[StandardTransferableInput]] references. - */ - getUTXOID = (): string => - bintools.bufferToB58(Buffer.concat([this.txid, this.outputidx])) - - /** - * Returns the input. - */ - getInput = (): Input => this.input - - /** - * Returns the assetID of the input. - */ - getAssetID = (): Buffer => this.assetID - - abstract fromBuffer(bytes: Buffer, offset?: number): number - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[StandardTransferableInput]]. - */ - toBuffer(): Buffer { - const parseableBuff: Buffer = super.toBuffer() - const bsize: number = - this.txid.length + - this.outputidx.length + - this.assetID.length + - parseableBuff.length - const barr: Buffer[] = [ - this.txid, - this.outputidx, - this.assetID, - parseableBuff - ] - const buff: Buffer = Buffer.concat(barr, bsize) - return buff - } - - /** - * Returns a base-58 representation of the [[StandardTransferableInput]]. - */ - toString(): string { - /* istanbul ignore next */ - return bintools.bufferToB58(this.toBuffer()) - } - - /** - * Class representing an [[StandardTransferableInput]] for a transaction. - * - * @param txid A {@link https://github.com/feross/buffer|Buffer} containing the transaction ID of the referenced UTXO - * @param outputidx A {@link https://github.com/feross/buffer|Buffer} containing the index of the output in the transaction consumed in the [[StandardTransferableInput]] - * @param assetID A {@link https://github.com/feross/buffer|Buffer} representing the assetID of the [[Input]] - * @param input An [[Input]] to be made transferable - */ - constructor( - txid: Buffer = undefined, - outputidx: Buffer = undefined, - assetID: Buffer = undefined, - input: Input = undefined - ) { - super() - if ( - typeof txid !== "undefined" && - typeof outputidx !== "undefined" && - typeof assetID !== "undefined" && - input instanceof Input - ) { - this.input = input - this.txid = txid - this.outputidx = outputidx - this.assetID = assetID - } - } -} - -/** - * An [[Input]] class which specifies a token amount . - */ -export abstract class StandardAmountInput extends Input { - protected _typeName = "StandardAmountInput" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - amount: serialization.encoder( - this.amount, - encoding, - "Buffer", - "decimalString", - 8 - ) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.amount = serialization.decoder( - fields["amount"], - encoding, - "decimalString", - "Buffer", - 8 - ) - this.amountValue = bintools.fromBufferToBN(this.amount) - } - - protected amount: Buffer = Buffer.alloc(8) - protected amountValue: BN = new BN(0) - - /** - * Returns the amount as a {@link https://github.com/indutny/bn.js/|BN}. - */ - getAmount = (): BN => this.amountValue.clone() - - /** - * Popuates the instance from a {@link https://github.com/feross/buffer|Buffer} representing the [[AmountInput]] and returns the size of the input. - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.amount = bintools.copyFrom(bytes, offset, offset + 8) - this.amountValue = bintools.fromBufferToBN(this.amount) - offset += 8 - return super.fromBuffer(bytes, offset) - } - - /** - * Returns the buffer representing the [[AmountInput]] instance. - */ - toBuffer(): Buffer { - const superbuff: Buffer = super.toBuffer() - const bsize: number = this.amount.length + superbuff.length - const barr: Buffer[] = [this.amount, superbuff] - return Buffer.concat(barr, bsize) - } - - /** - * An [[AmountInput]] class which issues a payment on an assetID. - * - * @param amount A {@link https://github.com/indutny/bn.js/|BN} representing the amount in the input - */ - constructor(amount: BN = undefined) { - super() - if (amount) { - this.amountValue = amount.clone() - this.amount = bintools.fromBNToBuffer(amount, 8) - } - } -} diff --git a/src/common/interfaces.ts b/src/common/interfaces.ts deleted file mode 100644 index 5758a7863..000000000 --- a/src/common/interfaces.ts +++ /dev/null @@ -1,67 +0,0 @@ -/** - * @packageDocumentation - * @module Common-Interfaces - */ - -import { Buffer } from "buffer/" -import { SerializedEncoding } from "../utils" - -export interface CredsInterface { - username: string - password: string -} - -export interface IssueTxParams { - tx: string - encoding: string -} - -export interface Index { - address: string - utxo: string -} - -export interface UTXOResponse { - numFetched: number - utxos: any - endIndex: Index -} - -export interface Asset { - name: string - symbol: string - assetID: Buffer - denomination: number -} - -export interface StakedOuts { - nodeID: string - stakedUntil: string - stakeOnlyUntil: string - owners: string[] - threshold: string - amount: string -} - -export interface WordLists { - czech: string[] - chinese_simplified: string[] - chinese_traditional: string[] - korean: string[] - french: string[] - italian: string[] - spanish: string[] - japanese: string[] - JA: string[] - portuguese: string[] - english: string[] - EN: string[] -} - -export interface Serialized { - vm: string - encoding: SerializedEncoding - version: number - notes: string - fields: object -} diff --git a/src/common/jrpcapi.ts b/src/common/jrpcapi.ts deleted file mode 100644 index 8ed988294..000000000 --- a/src/common/jrpcapi.ts +++ /dev/null @@ -1,94 +0,0 @@ -/** - * @packageDocumentation - * @module Common-JRPCAPI - */ - -import { AxiosRequestConfig } from "axios" -import { fetchAdapter } from "../utils" -import AvalancheCore from "../avalanche" -import { APIBase, RequestResponseData } from "./apibase" - -export class JRPCAPI extends APIBase { - protected jrpcVersion: string = "2.0" - protected rpcID = 1 - - callMethod = async ( - method: string, - params?: object[] | object, - baseURL?: string, - headers?: object - ): Promise => { - const ep: string = baseURL || this.baseURL - const rpc: any = {} - rpc.id = this.rpcID - rpc.method = method - - // Set parameters if exists - if (params) { - rpc.params = params - } else if (this.jrpcVersion === "1.0") { - rpc.params = [] - } - - if (this.jrpcVersion !== "1.0") { - rpc.jsonrpc = this.jrpcVersion - } - - let headrs: object = { "Content-Type": "application/json;charset=UTF-8" } - if (headers) { - headrs = { ...headrs, ...headers } - } - - baseURL = this.core.getURL() - - const axConf: AxiosRequestConfig = { - baseURL: baseURL, - responseType: "json", - // use the fetch adapter if fetch is available e.g. non Node<17 env - adapter: typeof fetch !== "undefined" ? fetchAdapter : undefined - } - - const resp: RequestResponseData = await this.core.post( - ep, - {}, - JSON.stringify(rpc), - headrs, - axConf - ) - if (resp.status >= 200 && resp.status < 300) { - this.rpcID += 1 - if (typeof resp.data === "string") { - resp.data = JSON.parse(resp.data) - } - if ( - typeof resp.data === "object" && - (resp.data === null || "error" in resp.data) - ) { - throw new Error(resp.data.error.message) - } - } - return resp - } - - /** - * Returns the rpcid, a strictly-increasing number, starting from 1, indicating the next - * request ID that will be sent. - */ - getRPCID = (): number => this.rpcID - - /** - * - * @param core Reference to the Avalanche instance using this endpoint - * @param baseURL Path of the APIs baseURL - ex: "/ext/bc/avm" - * @param jrpcVersion The jrpc version to use, default "2.0". - */ - constructor( - core: AvalancheCore, - baseURL: string, - jrpcVersion: string = "2.0" - ) { - super(core, baseURL) - this.jrpcVersion = jrpcVersion - this.rpcID = 1 - } -} diff --git a/src/common/keychain.ts b/src/common/keychain.ts deleted file mode 100644 index d8ad5cb69..000000000 --- a/src/common/keychain.ts +++ /dev/null @@ -1,212 +0,0 @@ -/** - * @packageDocumentation - * @module Common-KeyChain - */ - -import { Buffer } from "buffer/" - -/** - * Class for representing a private and public keypair in Avalanche. - * All APIs that need key pairs should extend on this class. - */ -export abstract class StandardKeyPair { - protected pubk: Buffer - protected privk: Buffer - - /** - * Generates a new keypair. - * - * @param entropy Optional parameter that may be necessary to produce secure keys - */ - abstract generateKey(entropy?: Buffer): void - - /** - * Imports a private key and generates the appropriate public key. - * - * @param privk A {@link https://github.com/feross/buffer|Buffer} representing the private key - * - * @returns true on success, false on failure - */ - abstract importKey(privk: Buffer): boolean - - /** - * Takes a message, signs it, and returns the signature. - * - * @param msg The message to sign - * - * @returns A {@link https://github.com/feross/buffer|Buffer} containing the signature - */ - abstract sign(msg: Buffer): Buffer - - /** - * Recovers the public key of a message signer from a message and its associated signature. - * - * @param msg The message that's signed - * @param sig The signature that's signed on the message - * - * @returns A {@link https://github.com/feross/buffer|Buffer} containing the public - * key of the signer - */ - abstract recover(msg: Buffer, sig: Buffer): Buffer - - /** - * Verifies that the private key associated with the provided public key produces the - * signature associated with the given message. - * - * @param msg The message associated with the signature - * @param sig The signature of the signed message - * @param pubk The public key associated with the message signature - * - * @returns True on success, false on failure - */ - abstract verify(msg: Buffer, sig: Buffer, pubk: Buffer): boolean - - /** - * Returns a reference to the private key. - * - * @returns A {@link https://github.com/feross/buffer|Buffer} containing the private key - */ - getPrivateKey(): Buffer { - return this.privk - } - - /** - * Returns a reference to the public key. - * - * @returns A {@link https://github.com/feross/buffer|Buffer} containing the public key - */ - getPublicKey(): Buffer { - return this.pubk - } - - /** - * Returns a string representation of the private key. - * - * @returns A string representation of the public key - */ - abstract getPrivateKeyString(): string - - /** - * Returns the public key. - * - * @returns A string representation of the public key - */ - abstract getPublicKeyString(): string - - /** - * Returns the address. - * - * @returns A {@link https://github.com/feross/buffer|Buffer} representation of the address - */ - abstract getAddress(): Buffer - - /** - * Returns the address's string representation. - * - * @returns A string representation of the address - */ - abstract getAddressString(): string - - abstract create(...args: any[]): this - - abstract clone(): this -} - -/** - * Class for representing a key chain in Avalanche. - * All endpoints that need key chains should extend on this class. - * - * @typeparam KPClass extending [[StandardKeyPair]] which is used as the key in [[StandardKeyChain]] - */ -export abstract class StandardKeyChain { - protected keys: { [address: string]: KPClass } = {} - - /** - * Makes a new [[StandardKeyPair]], returns the address. - * - * @returns Address of the new [[StandardKeyPair]] - */ - makeKey: () => KPClass - - /** - * Given a private key, makes a new [[StandardKeyPair]], returns the address. - * - * @param privk A {@link https://github.com/feross/buffer|Buffer} representing the private key - * - * @returns A new [[StandardKeyPair]] - */ - importKey: (privk: Buffer) => KPClass - - /** - * Gets an array of addresses stored in the [[StandardKeyChain]]. - * - * @returns An array of {@link https://github.com/feross/buffer|Buffer} representations - * of the addresses - */ - getAddresses = (): Buffer[] => - Object.values(this.keys).map((kp) => kp.getAddress()) - - /** - * Gets an array of addresses stored in the [[StandardKeyChain]]. - * - * @returns An array of string representations of the addresses - */ - getAddressStrings = (): string[] => - Object.values(this.keys).map((kp) => kp.getAddressString()) - - /** - * Adds the key pair to the list of the keys managed in the [[StandardKeyChain]]. - * - * @param newKey A key pair of the appropriate class to be added to the [[StandardKeyChain]] - */ - addKey(newKey: KPClass) { - this.keys[newKey.getAddress().toString("hex")] = newKey - } - - /** - * Removes the key pair from the list of they keys managed in the [[StandardKeyChain]]. - * - * @param key A {@link https://github.com/feross/buffer|Buffer} for the address or - * KPClass to remove - * - * @returns The boolean true if a key was removed. - */ - removeKey = (key: KPClass | Buffer) => { - let kaddr: string - if (key instanceof Buffer) { - kaddr = key.toString("hex") - } else { - kaddr = key.getAddress().toString("hex") - } - if (kaddr in this.keys) { - delete this.keys[`${kaddr}`] - return true - } - return false - } - - /** - * Checks if there is a key associated with the provided address. - * - * @param address The address to check for existence in the keys database - * - * @returns True on success, false if not found - */ - hasKey = (address: Buffer): boolean => address.toString("hex") in this.keys - - /** - * Returns the [[StandardKeyPair]] listed under the provided address - * - * @param address The {@link https://github.com/feross/buffer|Buffer} of the address to - * retrieve from the keys database - * - * @returns A reference to the [[StandardKeyPair]] in the keys database - */ - getKey = (address: Buffer): KPClass => this.keys[address.toString("hex")] - - abstract create(...args: any[]): this - - abstract clone(): this - - abstract union(kc: this): this -} diff --git a/src/common/nbytes.ts b/src/common/nbytes.ts deleted file mode 100644 index 884c27b53..000000000 --- a/src/common/nbytes.ts +++ /dev/null @@ -1,137 +0,0 @@ -/** - * @packageDocumentation - * @module Common-NBytes - */ - -import { Buffer } from "buffer/" -import BinTools from "../utils/bintools" -import { - Serializable, - Serialization, - SerializedEncoding -} from "../utils/serialization" -import { BufferSizeError } from "../utils/errors" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Abstract class that implements basic functionality for managing a - * {@link https://github.com/feross/buffer|Buffer} of an exact length. - * - * Create a class that extends this one and override bsize to make it validate for exactly - * the correct length. - */ -export abstract class NBytes extends Serializable { - protected _typeName = "NBytes" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - bsize: serialization.encoder( - this.bsize, - encoding, - "number", - "decimalString", - 4 - ), - bytes: serialization.encoder( - this.bytes, - encoding, - "Buffer", - "hex", - this.bsize - ) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.bsize = serialization.decoder( - fields["bsize"], - encoding, - "decimalString", - "number", - 4 - ) - this.bytes = serialization.decoder( - fields["bytes"], - encoding, - "hex", - "Buffer", - this.bsize - ) - } - - protected bytes: Buffer - protected bsize: number - - /** - * Returns the length of the {@link https://github.com/feross/buffer|Buffer}. - * - * @returns The exact length requirement of this class - */ - getSize = () => this.bsize - - /** - * Takes a base-58 encoded string, verifies its length, and stores it. - * - * @returns The size of the {@link https://github.com/feross/buffer|Buffer} - */ - fromString(b58str: string): number { - try { - this.fromBuffer(bintools.b58ToBuffer(b58str)) - } catch (e) { - /* istanbul ignore next */ - const emsg: string = `Error - NBytes.fromString: ${e}` - /* istanbul ignore next */ - throw new Error(emsg) - } - return this.bsize - } - - /** - * Takes a [[Buffer]], verifies its length, and stores it. - * - * @returns The size of the {@link https://github.com/feross/buffer|Buffer} - */ - fromBuffer(buff: Buffer, offset: number = 0): number { - try { - if (buff.length - offset < this.bsize) { - /* istanbul ignore next */ - throw new BufferSizeError( - "Error - NBytes.fromBuffer: not enough space available in buffer." - ) - } - - this.bytes = bintools.copyFrom(buff, offset, offset + this.bsize) - } catch (e) { - /* istanbul ignore next */ - const emsg: string = `Error - NBytes.fromBuffer: ${e}` - /* istanbul ignore next */ - throw new Error(emsg) - } - return offset + this.bsize - } - - /** - * @returns A reference to the stored {@link https://github.com/feross/buffer|Buffer} - */ - toBuffer(): Buffer { - return this.bytes - } - - /** - * @returns A base-58 string of the stored {@link https://github.com/feross/buffer|Buffer} - */ - toString(): string { - return bintools.bufferToB58(this.toBuffer()) - } - - abstract clone(): this - abstract create(...args: any[]): this -} diff --git a/src/common/output.ts b/src/common/output.ts deleted file mode 100644 index 1f923186d..000000000 --- a/src/common/output.ts +++ /dev/null @@ -1,626 +0,0 @@ -/** - * @packageDocumentation - * @module Common-Output - */ - -import { Buffer } from "buffer/" -import BN from "bn.js" -import BinTools from "../utils/bintools" -import { NBytes } from "./nbytes" -import { UnixNow } from "../utils/helperfunctions" -import { - Serializable, - Serialization, - SerializedEncoding -} from "../utils/serialization" -import { ChecksumError, AddressError, AddressIndexError } from "../utils/errors" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Class for representing an address used in [[Output]] types - */ -export class Address extends NBytes { - protected _typeName = "Address" - protected _typeID = undefined - - //serialize and deserialize both are inherited - - protected bytes = Buffer.alloc(20) - protected bsize = 20 - - /** - * Returns a function used to sort an array of [[Address]]es - */ - static comparator = - (): ((a: Address, b: Address) => 1 | -1 | 0) => - (a: Address, b: Address): 1 | -1 | 0 => - Buffer.compare(a.toBuffer(), b.toBuffer()) as 1 | -1 | 0 - - /** - * Returns a base-58 representation of the [[Address]]. - */ - toString(): string { - return bintools.cb58Encode(this.toBuffer()) - } - - /** - * Takes a base-58 string containing an [[Address]], parses it, populates the class, and returns the length of the Address in bytes. - * - * @param bytes A base-58 string containing a raw [[Address]] - * - * @returns The length of the raw [[Address]] - */ - fromString(addr: string): number { - const addrbuff: Buffer = bintools.b58ToBuffer(addr) - if (addrbuff.length === 24 && bintools.validateChecksum(addrbuff)) { - const newbuff: Buffer = bintools.copyFrom( - addrbuff, - 0, - addrbuff.length - 4 - ) - if (newbuff.length === 20) { - this.bytes = newbuff - } - } else if (addrbuff.length === 24) { - throw new ChecksumError( - "Error - Address.fromString: invalid checksum on address" - ) - } else if (addrbuff.length === 20) { - this.bytes = addrbuff - } else { - /* istanbul ignore next */ - throw new AddressError("Error - Address.fromString: invalid address") - } - return this.getSize() - } - - clone(): this { - let newbase: Address = new Address() - newbase.fromBuffer(this.toBuffer()) - return newbase as this - } - - create(...args: any[]): this { - return new Address() as this - } - - /** - * Class for representing an address used in [[Output]] types - */ - constructor() { - super() - } -} - -/** - * Defines the most basic values for output ownership. Mostly inherited from, but can be used in population of NFT Owner data. - */ -export class OutputOwners extends Serializable { - protected _typeName = "OutputOwners" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - locktime: serialization.encoder( - this.locktime, - encoding, - "Buffer", - "decimalString", - 8 - ), - threshold: serialization.encoder( - this.threshold, - encoding, - "Buffer", - "decimalString", - 4 - ), - addresses: this.addresses.map((a: Address): object => - a.serialize(encoding) - ) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.locktime = serialization.decoder( - fields["locktime"], - encoding, - "decimalString", - "Buffer", - 8 - ) - this.threshold = serialization.decoder( - fields["threshold"], - encoding, - "decimalString", - "Buffer", - 4 - ) - this.addresses = fields["addresses"].map((a: object) => { - let addr: Address = new Address() - addr.deserialize(a, encoding) - return addr - }) - this.numaddrs = Buffer.alloc(4) - this.numaddrs.writeUInt32BE(this.addresses.length, 0) - } - - protected locktime: Buffer = Buffer.alloc(8) - protected threshold: Buffer = Buffer.alloc(4) - protected numaddrs: Buffer = Buffer.alloc(4) - protected addresses: Address[] = [] - - /** - * Returns the threshold of signers required to spend this output. - */ - getThreshold = (): number => this.threshold.readUInt32BE(0) - - /** - * Returns the a {@link https://github.com/indutny/bn.js/|BN} repersenting the UNIX Timestamp when the lock is made available. - */ - getLocktime = (): BN => bintools.fromBufferToBN(this.locktime) - - /** - * Returns an array of {@link https://github.com/feross/buffer|Buffer}s for the addresses. - */ - getAddresses = (): Buffer[] => { - const result: Buffer[] = [] - for (let i: number = 0; i < this.addresses.length; i++) { - result.push(this.addresses[`${i}`].toBuffer()) - } - return result - } - - /** - * Returns the index of the address. - * - * @param address A {@link https://github.com/feross/buffer|Buffer} of the address to look up to return its index. - * - * @returns The index of the address. - */ - getAddressIdx = (address: Buffer): number => { - for (let i: number = 0; i < this.addresses.length; i++) { - if ( - this.addresses[`${i}`].toBuffer().toString("hex") === - address.toString("hex") - ) { - return i - } - } - /* istanbul ignore next */ - return -1 - } - - /** - * Returns the address from the index provided. - * - * @param idx The index of the address. - * - * @returns Returns the string representing the address. - */ - getAddress = (idx: number): Buffer => { - if (idx < this.addresses.length) { - return this.addresses[`${idx}`].toBuffer() - } - throw new AddressIndexError("Error - Output.getAddress: idx out of range") - } - - /** - * Given an array of address {@link https://github.com/feross/buffer|Buffer}s and an optional timestamp, returns true if the addresses meet the threshold required to spend the output. - */ - meetsThreshold = (addresses: Buffer[], asOf: BN = undefined): boolean => { - let now: BN - if (typeof asOf === "undefined") { - now = UnixNow() - } else { - now = asOf - } - const qualified: Buffer[] = this.getSpenders(addresses, now) - const threshold: number = this.threshold.readUInt32BE(0) - if (qualified.length >= threshold) { - return true - } - - return false - } - - /** - * Given an array of addresses and an optional timestamp, select an array of address {@link https://github.com/feross/buffer|Buffer}s of qualified spenders for the output. - */ - getSpenders = (addresses: Buffer[], asOf: BN = undefined): Buffer[] => { - const qualified: Buffer[] = [] - let now: BN - if (typeof asOf === "undefined") { - now = UnixNow() - } else { - now = asOf - } - const locktime: BN = bintools.fromBufferToBN(this.locktime) - if (now.lte(locktime)) { - // not unlocked, not spendable - return qualified - } - - const threshold: number = this.threshold.readUInt32BE(0) - for ( - let i: number = 0; - i < this.addresses.length && qualified.length < threshold; - i++ - ) { - for ( - let j: number = 0; - j < addresses.length && qualified.length < threshold; - j++ - ) { - if ( - addresses[`${j}`].toString("hex") === - this.addresses[`${i}`].toBuffer().toString("hex") - ) { - qualified.push(addresses[`${j}`]) - } - } - } - - return qualified - } - - /** - * Returns a base-58 string representing the [[Output]]. - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - this.locktime = bintools.copyFrom(bytes, offset, offset + 8) - offset += 8 - this.threshold = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - this.numaddrs = bintools.copyFrom(bytes, offset, offset + 4) - offset += 4 - const numaddrs: number = this.numaddrs.readUInt32BE(0) - this.addresses = [] - for (let i: number = 0; i < numaddrs; i++) { - const addr: Address = new Address() - offset = addr.fromBuffer(bytes, offset) - this.addresses.push(addr) - } - this.addresses.sort(Address.comparator()) - return offset - } - - /** - * Returns the buffer representing the [[Output]] instance. - */ - toBuffer(): Buffer { - this.addresses.sort(Address.comparator()) - this.numaddrs.writeUInt32BE(this.addresses.length, 0) - let bsize: number = - this.locktime.length + this.threshold.length + this.numaddrs.length - const barr: Buffer[] = [this.locktime, this.threshold, this.numaddrs] - for (let i: number = 0; i < this.addresses.length; i++) { - const b: Buffer = this.addresses[`${i}`].toBuffer() - barr.push(b) - bsize += b.length - } - return Buffer.concat(barr, bsize) - } - - /** - * Returns a base-58 string representing the [[Output]]. - */ - toString(): string { - return bintools.bufferToB58(this.toBuffer()) - } - - static comparator = - (): ((a: Output, b: Output) => 1 | -1 | 0) => - (a: Output, b: Output): 1 | -1 | 0 => { - const aoutid: Buffer = Buffer.alloc(4) - aoutid.writeUInt32BE(a.getOutputID(), 0) - const abuff: Buffer = a.toBuffer() - - const boutid: Buffer = Buffer.alloc(4) - boutid.writeUInt32BE(b.getOutputID(), 0) - const bbuff: Buffer = b.toBuffer() - - const asort: Buffer = Buffer.concat( - [aoutid, abuff], - aoutid.length + abuff.length - ) - const bsort: Buffer = Buffer.concat( - [boutid, bbuff], - boutid.length + bbuff.length - ) - return Buffer.compare(asort, bsort) as 1 | -1 | 0 - } - - /** - * An [[Output]] class which contains addresses, locktimes, and thresholds. - * - * @param addresses An array of {@link https://github.com/feross/buffer|Buffer}s representing output owner's addresses - * @param locktime A {@link https://github.com/indutny/bn.js/|BN} representing the locktime - * @param threshold A number representing the the threshold number of signers required to sign the transaction - */ - constructor( - addresses: Buffer[] = undefined, - locktime: BN = undefined, - threshold: number = undefined - ) { - super() - if (typeof addresses !== "undefined" && addresses.length) { - const addrs: Address[] = [] - for (let i: number = 0; i < addresses.length; i++) { - addrs[`${i}`] = new Address() - addrs[`${i}`].fromBuffer(addresses[`${i}`]) - } - this.addresses = addrs - this.addresses.sort(Address.comparator()) - this.numaddrs.writeUInt32BE(this.addresses.length, 0) - } - if (typeof threshold !== undefined) { - this.threshold.writeUInt32BE(threshold || 1, 0) - } - if (typeof locktime !== "undefined") { - this.locktime = bintools.fromBNToBuffer(locktime, 8) - } - } -} - -export abstract class Output extends OutputOwners { - protected _typeName = "Output" - protected _typeID = undefined - - //serialize and deserialize both are inherited - - /** - * Returns the outputID for the output which tells parsers what type it is - */ - abstract getOutputID(): number - - abstract clone(): this - - abstract create(...args: any[]): this - - abstract select(id: number, ...args: any[]): Output - - /** - * - * @param assetID An assetID which is wrapped around the Buffer of the Output - * - * Must be implemented to use the appropriate TransferableOutput for the VM. - */ - abstract makeTransferable(assetID: Buffer): StandardTransferableOutput -} - -export abstract class StandardParseableOutput extends Serializable { - protected _typeName = "StandardParseableOutput" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - output: this.output.serialize(encoding) - } - } - - protected output: Output - - /** - * Returns a function used to sort an array of [[ParseableOutput]]s - */ - static comparator = - (): (( - a: StandardParseableOutput, - b: StandardParseableOutput - ) => 1 | -1 | 0) => - (a: StandardParseableOutput, b: StandardParseableOutput): 1 | -1 | 0 => { - const sorta = a.toBuffer() - const sortb = b.toBuffer() - return Buffer.compare(sorta, sortb) as 1 | -1 | 0 - } - - getOutput = (): Output => this.output - - // must be implemented to select output types for the VM in question - abstract fromBuffer(bytes: Buffer, offset?: number): number - - toBuffer(): Buffer { - const outbuff: Buffer = this.output.toBuffer() - const outid: Buffer = Buffer.alloc(4) - outid.writeUInt32BE(this.output.getOutputID(), 0) - const barr: Buffer[] = [outid, outbuff] - return Buffer.concat(barr, outid.length + outbuff.length) - } - - /** - * Class representing an [[ParseableOutput]] for a transaction. - * - * @param output A number representing the InputID of the [[ParseableOutput]] - */ - constructor(output: Output = undefined) { - super() - if (output instanceof Output) { - this.output = output - } - } -} - -export abstract class StandardTransferableOutput extends StandardParseableOutput { - protected _typeName = "StandardTransferableOutput" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - assetID: serialization.encoder(this.assetID, encoding, "Buffer", "cb58") - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.assetID = serialization.decoder( - fields["assetID"], - encoding, - "cb58", - "Buffer", - 32 - ) - } - - protected assetID: Buffer = undefined - - getAssetID = (): Buffer => this.assetID - - // must be implemented to select output types for the VM in question - abstract fromBuffer(bytes: Buffer, offset?: number): number - - toBuffer(): Buffer { - const parseableBuff: Buffer = super.toBuffer() - const barr: Buffer[] = [this.assetID, parseableBuff] - return Buffer.concat(barr, this.assetID.length + parseableBuff.length) - } - - /** - * Class representing an [[StandardTransferableOutput]] for a transaction. - * - * @param assetID A {@link https://github.com/feross/buffer|Buffer} representing the assetID of the [[Output]] - * @param output A number representing the InputID of the [[StandardTransferableOutput]] - */ - constructor(assetID: Buffer = undefined, output: Output = undefined) { - super(output) - if (typeof assetID !== "undefined") { - this.assetID = assetID - } - } -} - -/** - * An [[Output]] class which specifies a token amount . - */ -export abstract class StandardAmountOutput extends Output { - protected _typeName = "StandardAmountOutput" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - amount: serialization.encoder( - this.amount, - encoding, - "Buffer", - "decimalString", - 8 - ) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.amount = serialization.decoder( - fields["amount"], - encoding, - "decimalString", - "Buffer", - 8 - ) - this.amountValue = bintools.fromBufferToBN(this.amount) - } - - protected amount: Buffer = Buffer.alloc(8) - protected amountValue: BN = new BN(0) - - /** - * Returns the amount as a {@link https://github.com/indutny/bn.js/|BN}. - */ - getAmount(): BN { - return this.amountValue.clone() - } - - /** - * Popuates the instance from a {@link https://github.com/feross/buffer|Buffer} representing the [[StandardAmountOutput]] and returns the size of the output. - */ - fromBuffer(outbuff: Buffer, offset: number = 0): number { - this.amount = bintools.copyFrom(outbuff, offset, offset + 8) - this.amountValue = bintools.fromBufferToBN(this.amount) - offset += 8 - return super.fromBuffer(outbuff, offset) - } - - /** - * Returns the buffer representing the [[StandardAmountOutput]] instance. - */ - toBuffer(): Buffer { - const superbuff: Buffer = super.toBuffer() - const bsize: number = this.amount.length + superbuff.length - this.numaddrs.writeUInt32BE(this.addresses.length, 0) - const barr: Buffer[] = [this.amount, superbuff] - return Buffer.concat(barr, bsize) - } - - /** - * A [[StandardAmountOutput]] class which issues a payment on an assetID. - * - * @param amount A {@link https://github.com/indutny/bn.js/|BN} representing the amount in the output - * @param addresses An array of {@link https://github.com/feross/buffer|Buffer}s representing addresses - * @param locktime A {@link https://github.com/indutny/bn.js/|BN} representing the locktime - * @param threshold A number representing the the threshold number of signers required to sign the transaction - */ - constructor( - amount: BN = undefined, - addresses: Buffer[] = undefined, - locktime: BN = undefined, - threshold: number = undefined - ) { - super(addresses, locktime, threshold) - if (typeof amount !== "undefined") { - this.amountValue = amount.clone() - this.amount = bintools.fromBNToBuffer(amount, 8) - } - } -} - -/** - * An [[Output]] class which specifies an NFT. - */ -export abstract class BaseNFTOutput extends Output { - protected _typeName = "BaseNFTOutput" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - groupID: serialization.encoder( - this.groupID, - encoding, - "Buffer", - "decimalString", - 4 - ) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.groupID = serialization.decoder( - fields["groupID"], - encoding, - "decimalString", - "Buffer", - 4 - ) - } - - protected groupID: Buffer = Buffer.alloc(4) - - /** - * Returns the groupID as a number. - */ - getGroupID = (): number => { - return this.groupID.readUInt32BE(0) - } -} diff --git a/src/common/restapi.ts b/src/common/restapi.ts deleted file mode 100644 index efe973d6c..000000000 --- a/src/common/restapi.ts +++ /dev/null @@ -1,192 +0,0 @@ -/** - * @packageDocumentation - * @module Common-RESTAPI - */ - -import { AxiosRequestConfig } from "axios" -import AvalancheCore from "../avalanche" -import { APIBase, RequestResponseData } from "./apibase" - -export class RESTAPI extends APIBase { - protected contentType: string - protected acceptType: string - - protected prepHeaders = ( - contentType?: string, - acceptType?: string - ): object => { - const headers: object = {} - if (contentType !== undefined) { - headers["Content-Type"] = contentType - } else { - headers["Content-Type"] = this.contentType - } - - if (acceptType !== undefined) { - headers["Accept"] = acceptType - } else if (this.acceptType !== undefined) { - headers["Accept"] = this.acceptType - } - return headers - } - - protected axConf = (): AxiosRequestConfig => { - return { - baseURL: this.core.getURL(), - responseType: "json" - } - } - - get = async ( - baseURL?: string, - contentType?: string, - acceptType?: string - ): Promise => { - const ep: string = baseURL || this.baseURL - const headers: object = this.prepHeaders(contentType, acceptType) - const resp: RequestResponseData = await this.core.get( - ep, - {}, - headers, - this.axConf() - ) - return resp - } - - post = async ( - method: string, - params?: object[] | object, - baseURL?: string, - contentType?: string, - acceptType?: string - ): Promise => { - const ep: string = baseURL || this.baseURL - const rpc: any = {} - rpc.method = method - - // Set parameters if exists - if (params) { - rpc.params = params - } - - const headers: object = this.prepHeaders(contentType, acceptType) - const resp: RequestResponseData = await this.core.post( - ep, - {}, - JSON.stringify(rpc), - headers, - this.axConf() - ) - return resp - } - - put = async ( - method: string, - params?: object[] | object, - baseURL?: string, - contentType?: string, - acceptType?: string - ): Promise => { - const ep: string = baseURL || this.baseURL - const rpc: any = {} - rpc.method = method - - // Set parameters if exists - if (params) { - rpc.params = params - } - - const headers: object = this.prepHeaders(contentType, acceptType) - const resp: RequestResponseData = await this.core.put( - ep, - {}, - JSON.stringify(rpc), - headers, - this.axConf() - ) - return resp - } - - delete = async ( - method: string, - params?: object[] | object, - baseURL?: string, - contentType?: string, - acceptType?: string - ): Promise => { - const ep: string = baseURL || this.baseURL - const rpc: any = {} - rpc.method = method - - // Set parameters if exists - if (params) { - rpc.params = params - } - - const headers: object = this.prepHeaders(contentType, acceptType) - const resp: RequestResponseData = await this.core.delete( - ep, - {}, - headers, - this.axConf() - ) - return resp - } - - patch = async ( - method: string, - params?: object[] | object, - baseURL?: string, - contentType?: string, - acceptType?: string - ): Promise => { - const ep: string = baseURL || this.baseURL - const rpc: any = {} - rpc.method = method - - // Set parameters if exists - if (params) { - rpc.params = params - } - - const headers: object = this.prepHeaders(contentType, acceptType) - const resp: RequestResponseData = await this.core.patch( - ep, - {}, - JSON.stringify(rpc), - headers, - this.axConf() - ) - return resp - } - - /** - * Returns the type of the entity attached to the incoming request - */ - getContentType = (): string => this.contentType - - /** - * Returns what type of representation is desired at the client side - */ - getAcceptType = (): string => this.acceptType - - /** - * - * @param core Reference to the Avalanche instance using this endpoint - * @param baseURL Path of the APIs baseURL - ex: "/ext/bc/avm" - * @param contentType Optional Determines the type of the entity attached to the - * incoming request - * @param acceptType Optional Determines the type of representation which is - * desired on the client side - */ - constructor( - core: AvalancheCore, - baseURL: string, - contentType: string = "application/json;charset=UTF-8", - acceptType: string = undefined - ) { - super(core, baseURL) - this.contentType = contentType - this.acceptType = acceptType - } -} diff --git a/src/common/secp256k1.ts b/src/common/secp256k1.ts deleted file mode 100644 index 40c8f8069..000000000 --- a/src/common/secp256k1.ts +++ /dev/null @@ -1,290 +0,0 @@ -/** - * @packageDocumentation - * @module Common-SECP256k1KeyChain - */ -import { Buffer } from "buffer/" -import * as elliptic from "elliptic" -import createHash from "create-hash" -import BinTools from "../utils/bintools" -import { StandardKeyPair, StandardKeyChain } from "./keychain" -import { PublicKeyError } from "../utils/errors" -import { BNInput } from "elliptic" -import { Serialization, SerializedType } from "../utils" - -/** - * @ignore - */ -const EC: typeof elliptic.ec = elliptic.ec - -/** - * @ignore - */ -const ec: elliptic.ec = new EC("secp256k1") - -/** - * @ignore - */ -const ecparams: any = ec.curve - -/** - * @ignore - */ -const BN: any = ecparams.n.constructor - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Class for representing a private and public keypair on the Platform Chain. - */ -export abstract class SECP256k1KeyPair extends StandardKeyPair { - protected keypair: elliptic.ec.KeyPair - protected chainID: string = "" - protected hrp: string = "" - - /** - * @ignore - */ - protected _sigFromSigBuffer(sig: Buffer): elliptic.ec.SignatureOptions { - const r: BNInput = new BN(bintools.copyFrom(sig, 0, 32)) - const s: BNInput = new BN(bintools.copyFrom(sig, 32, 64)) - const recoveryParam: number = bintools - .copyFrom(sig, 64, 65) - .readUIntBE(0, 1) - const sigOpt = { - r: r, - s: s, - recoveryParam: recoveryParam - } - return sigOpt - } - - /** - * Generates a new keypair. - */ - generateKey() { - this.keypair = ec.genKeyPair() - - // doing hex translation to get Buffer class - this.privk = Buffer.from( - this.keypair.getPrivate("hex").padStart(64, "0"), - "hex" - ) - this.pubk = Buffer.from( - this.keypair.getPublic(true, "hex").padStart(66, "0"), - "hex" - ) - } - - /** - * Imports a private key and generates the appropriate public key. - * - * @param privk A {@link https://github.com/feross/buffer|Buffer} representing the private key - * - * @returns true on success, false on failure - */ - importKey(privk: Buffer): boolean { - this.keypair = ec.keyFromPrivate(privk.toString("hex"), "hex") - // doing hex translation to get Buffer class - try { - this.privk = Buffer.from( - this.keypair.getPrivate("hex").padStart(64, "0"), - "hex" - ) - this.pubk = Buffer.from( - this.keypair.getPublic(true, "hex").padStart(66, "0"), - "hex" - ) - return true // silly I know, but the interface requires so it returns true on success, so if Buffer fails validation... - } catch (error) { - return false - } - } - - /** - * Returns the address as a {@link https://github.com/feross/buffer|Buffer}. - * - * @returns A {@link https://github.com/feross/buffer|Buffer} representation of the address - */ - getAddress(): Buffer { - return SECP256k1KeyPair.addressFromPublicKey(this.pubk) - } - - /** - * Returns the address's string representation. - * - * @returns A string representation of the address - */ - getAddressString(): string { - const addr: Buffer = SECP256k1KeyPair.addressFromPublicKey(this.pubk) - const type: SerializedType = "bech32" - return serialization.bufferToType(addr, type, this.hrp, this.chainID) - } - - /** - * Returns an address given a public key. - * - * @param pubk A {@link https://github.com/feross/buffer|Buffer} representing the public key - * - * @returns A {@link https://github.com/feross/buffer|Buffer} for the address of the public key. - */ - static addressFromPublicKey(pubk: Buffer): Buffer { - if (pubk.length === 65) { - /* istanbul ignore next */ - pubk = Buffer.from( - ec.keyFromPublic(pubk).getPublic(true, "hex").padStart(66, "0"), - "hex" - ) // make compact, stick back into buffer - } - if (pubk.length === 33) { - const sha256: Buffer = Buffer.from( - createHash("sha256").update(pubk).digest() - ) - const ripesha: Buffer = Buffer.from( - createHash("ripemd160").update(sha256).digest() - ) - return ripesha - } - /* istanbul ignore next */ - throw new PublicKeyError("Unable to make address.") - } - - /** - * Returns a string representation of the private key. - * - * @returns A cb58 serialized string representation of the private key - */ - getPrivateKeyString(): string { - return `PrivateKey-${bintools.cb58Encode(this.privk)}` - } - - /** - * Returns the public key. - * - * @returns A cb58 serialized string representation of the public key - */ - getPublicKeyString(): string { - return bintools.cb58Encode(this.pubk) - } - - /** - * Takes a message, signs it, and returns the signature. - * - * @param msg The message to sign, be sure to hash first if expected - * - * @returns A {@link https://github.com/feross/buffer|Buffer} containing the signature - */ - sign(msg: Buffer): Buffer { - const sigObj: elliptic.ec.Signature = this.keypair.sign(msg, undefined, { - canonical: true - }) - const recovery: Buffer = Buffer.alloc(1) - recovery.writeUInt8(sigObj.recoveryParam, 0) - const r: Buffer = Buffer.from(sigObj.r.toArray("be", 32)) //we have to skip native Buffer class, so this is the way - const s: Buffer = Buffer.from(sigObj.s.toArray("be", 32)) //we have to skip native Buffer class, so this is the way - const result: Buffer = Buffer.concat([r, s, recovery], 65) - return result - } - - /** - * Verifies that the private key associated with the provided public key produces the signature associated with the given message. - * - * @param msg The message associated with the signature - * @param sig The signature of the signed message - * - * @returns True on success, false on failure - */ - verify(msg: Buffer, sig: Buffer): boolean { - const sigObj: elliptic.ec.SignatureOptions = this._sigFromSigBuffer(sig) - return ec.verify(msg, sigObj, this.keypair) - } - - /** - * Recovers the public key of a message signer from a message and its associated signature. - * - * @param msg The message that's signed - * @param sig The signature that's signed on the message - * - * @returns A {@link https://github.com/feross/buffer|Buffer} containing the public key of the signer - */ - recover(msg: Buffer, sig: Buffer): Buffer { - const sigObj: elliptic.ec.SignatureOptions = this._sigFromSigBuffer(sig) - const pubk = ec.recoverPubKey(msg, sigObj, sigObj.recoveryParam) - return Buffer.from(pubk.encodeCompressed()) - } - - /** - * Returns the chainID associated with this key. - * - * @returns The [[KeyPair]]'s chainID - */ - getChainID(): string { - return this.chainID - } - - /** - * Sets the the chainID associated with this key. - * - * @param chainID String for the chainID - */ - setChainID(chainID: string): void { - this.chainID = chainID - } - - /** - * Returns the Human-Readable-Part of the network associated with this key. - * - * @returns The [[KeyPair]]'s Human-Readable-Part of the network's Bech32 addressing scheme - */ - getHRP(): string { - return this.hrp - } - - /** - * Sets the the Human-Readable-Part of the network associated with this key. - * - * @param hrp String for the Human-Readable-Part of Bech32 addresses - */ - setHRP(hrp: string): void { - this.hrp = hrp - } - - constructor(hrp: string, chainID: string) { - super() - this.chainID = chainID - this.hrp = hrp - this.generateKey() - } -} - -/** - * Class for representing a key chain in Avalanche. - * - * @typeparam SECP256k1KeyPair Class extending [[StandardKeyPair]] which is used as the key in [[SECP256k1KeyChain]] - */ -export abstract class SECP256k1KeyChain< - SECPKPClass extends SECP256k1KeyPair -> extends StandardKeyChain { - /** - * Makes a new key pair, returns the address. - * - * @returns Address of the new key pair - */ - makeKey: () => SECPKPClass - - addKey(newKey: SECPKPClass): void { - super.addKey(newKey) - } - - /** - * Given a private key, makes a new key pair, returns the address. - * - * @param privk A {@link https://github.com/feross/buffer|Buffer} or cb58 serialized string representing the private key - * - * @returns Address of the new key pair - */ - importKey: (privk: Buffer | string) => SECPKPClass -} diff --git a/src/common/tx.ts b/src/common/tx.ts deleted file mode 100644 index 1ba8c87c0..000000000 --- a/src/common/tx.ts +++ /dev/null @@ -1,484 +0,0 @@ -/** - * @packageDocumentation - * @module Common-Transactions - */ -import { Buffer } from "buffer/" -import BinTools from "../utils/bintools" -import { Credential } from "./credentials" -import BN from "bn.js" -import { StandardKeyChain, StandardKeyPair } from "./keychain" -import { StandardAmountInput, StandardTransferableInput } from "./input" -import { StandardAmountOutput, StandardTransferableOutput } from "./output" -import { DefaultNetworkID } from "../utils/constants" -import { - Serializable, - Serialization, - SerializedEncoding, - SerializedType -} from "../utils/serialization" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() -const cb58: SerializedType = "cb58" -const hex: SerializedType = "hex" -const decimalString: SerializedType = "decimalString" -const buffer: SerializedType = "Buffer" - -/** - * Class representing a base for all transactions. - */ -export abstract class StandardBaseTx< - KPClass extends StandardKeyPair, - KCClass extends StandardKeyChain -> extends Serializable { - protected _typeName = "StandardBaseTx" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - const fields: object = super.serialize(encoding) - return { - ...fields, - networkID: serialization.encoder( - this.networkID, - encoding, - buffer, - decimalString - ), - blockchainID: serialization.encoder( - this.blockchainID, - encoding, - buffer, - cb58 - ), - outs: this.outs.map((o) => o.serialize(encoding)), - ins: this.ins.map((i) => i.serialize(encoding)), - memo: serialization.encoder(this.memo, encoding, buffer, hex) - } - } - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.networkID = serialization.decoder( - fields["networkID"], - encoding, - decimalString, - buffer, - 4 - ) - this.blockchainID = serialization.decoder( - fields["blockchainID"], - encoding, - cb58, - buffer, - 32 - ) - this.memo = serialization.decoder(fields["memo"], encoding, hex, buffer) - } - - protected networkID: Buffer = Buffer.alloc(4) - protected blockchainID: Buffer = Buffer.alloc(32) - protected numouts: Buffer = Buffer.alloc(4) - protected outs: StandardTransferableOutput[] - protected numins: Buffer = Buffer.alloc(4) - protected ins: StandardTransferableInput[] - protected memo: Buffer = Buffer.alloc(0) - - /** - * Returns the id of the [[StandardBaseTx]] - */ - abstract getTxType(): number - - /** - * Returns the NetworkID as a number - */ - getNetworkID(): number { - return this.networkID.readUInt32BE(0) - } - - /** - * Returns the Buffer representation of the BlockchainID - */ - getBlockchainID(): Buffer { - return this.blockchainID - } - - /** - * Returns the array of [[StandardTransferableInput]]s - */ - abstract getIns(): StandardTransferableInput[] - - /** - * Returns the array of [[StandardTransferableOutput]]s - */ - abstract getOuts(): StandardTransferableOutput[] - - /** - * Returns the array of combined total [[StandardTransferableOutput]]s - */ - abstract getTotalOuts(): StandardTransferableOutput[] - - /** - * Returns the {@link https://github.com/feross/buffer|Buffer} representation of the memo - */ - getMemo(): Buffer { - return this.memo - } - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[StandardBaseTx]]. - */ - toBuffer(): Buffer { - this.outs.sort(StandardTransferableOutput.comparator()) - this.ins.sort(StandardTransferableInput.comparator()) - this.numouts.writeUInt32BE(this.outs.length, 0) - this.numins.writeUInt32BE(this.ins.length, 0) - let bsize: number = - this.networkID.length + this.blockchainID.length + this.numouts.length - const barr: Buffer[] = [this.networkID, this.blockchainID, this.numouts] - for (let i: number = 0; i < this.outs.length; i++) { - const b: Buffer = this.outs[`${i}`].toBuffer() - barr.push(b) - bsize += b.length - } - barr.push(this.numins) - bsize += this.numins.length - for (let i: number = 0; i < this.ins.length; i++) { - const b: Buffer = this.ins[`${i}`].toBuffer() - barr.push(b) - bsize += b.length - } - let memolen: Buffer = Buffer.alloc(4) - memolen.writeUInt32BE(this.memo.length, 0) - barr.push(memolen) - bsize += 4 - barr.push(this.memo) - bsize += this.memo.length - const buff: Buffer = Buffer.concat(barr, bsize) - return buff - } - - /** - * Returns a base-58 representation of the [[StandardBaseTx]]. - */ - toString(): string { - return bintools.bufferToB58(this.toBuffer()) - } - - toStringHex(): string { - return `0x${bintools.addChecksum(this.toBuffer()).toString("hex")}` - } - - /** - * Takes the bytes of an [[UnsignedTx]] and returns an array of [[Credential]]s - * - * @param msg A Buffer for the [[UnsignedTx]] - * @param kc An [[KeyChain]] used in signing - * - * @returns An array of [[Credential]]s - */ - abstract sign(msg: Buffer, kc: StandardKeyChain): Credential[] - - abstract clone(): this - - abstract create(...args: any[]): this - - abstract select(id: number, ...args: any[]): this - - /** - * Class representing a StandardBaseTx which is the foundation for all transactions. - * - * @param networkID Optional networkID, [[DefaultNetworkID]] - * @param blockchainID Optional blockchainID, default Buffer.alloc(32, 16) - * @param outs Optional array of the [[TransferableOutput]]s - * @param ins Optional array of the [[TransferableInput]]s - * @param memo Optional {@link https://github.com/feross/buffer|Buffer} for the memo field - */ - constructor( - networkID: number = DefaultNetworkID, - blockchainID: Buffer = Buffer.alloc(32, 16), - outs: StandardTransferableOutput[] = undefined, - ins: StandardTransferableInput[] = undefined, - memo: Buffer = undefined - ) { - super() - this.networkID.writeUInt32BE(networkID, 0) - this.blockchainID = blockchainID - if (typeof memo != "undefined") { - this.memo = memo - } - - if (typeof ins !== "undefined" && typeof outs !== "undefined") { - this.numouts.writeUInt32BE(outs.length, 0) - this.outs = outs.sort(StandardTransferableOutput.comparator()) - this.numins.writeUInt32BE(ins.length, 0) - this.ins = ins.sort(StandardTransferableInput.comparator()) - } - } -} - -/** - * Class representing an unsigned transaction. - */ -export abstract class StandardUnsignedTx< - KPClass extends StandardKeyPair, - KCClass extends StandardKeyChain, - SBTx extends StandardBaseTx -> extends Serializable { - protected _typeName = "StandardUnsignedTx" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - codecID: serialization.encoder( - this.codecID, - encoding, - "number", - "decimalString", - 2 - ), - transaction: this.transaction.serialize(encoding) - } - } - - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.codecID = serialization.decoder( - fields["codecID"], - encoding, - "decimalString", - "number" - ) - } - - protected codecID: number = 0 - protected transaction: SBTx - - /** - * Returns the CodecID as a number - */ - getCodecID(): number { - return this.codecID - } - - /** - * Returns the {@link https://github.com/feross/buffer|Buffer} representation of the CodecID - */ - getCodecIDBuffer(): Buffer { - let codecBuf: Buffer = Buffer.alloc(2) - codecBuf.writeUInt16BE(this.codecID, 0) - return codecBuf - } - - /** - * Returns the inputTotal as a BN - */ - getInputTotal(assetID: Buffer): BN { - const ins: StandardTransferableInput[] = this.getTransaction().getIns() - const aIDHex: string = assetID.toString("hex") - let total: BN = new BN(0) - - for (let i: number = 0; i < ins.length; i++) { - // only check StandardAmountInputs - if ( - ins[`${i}`].getInput() instanceof StandardAmountInput && - aIDHex === ins[`${i}`].getAssetID().toString("hex") - ) { - const input: StandardAmountInput = ins[ - `${i}` - ].getInput() as StandardAmountInput - total = total.add(input.getAmount()) - } - } - return total - } - - /** - * Returns the outputTotal as a BN - */ - getOutputTotal(assetID: Buffer): BN { - const outs: StandardTransferableOutput[] = - this.getTransaction().getTotalOuts() - const aIDHex: string = assetID.toString("hex") - let total: BN = new BN(0) - - for (let i: number = 0; i < outs.length; i++) { - // only check StandardAmountOutput - if ( - outs[`${i}`].getOutput() instanceof StandardAmountOutput && - aIDHex === outs[`${i}`].getAssetID().toString("hex") - ) { - const output: StandardAmountOutput = outs[ - `${i}` - ].getOutput() as StandardAmountOutput - total = total.add(output.getAmount()) - } - } - return total - } - - /** - * Returns the number of burned tokens as a BN - */ - getBurn(assetID: Buffer): BN { - return this.getInputTotal(assetID).sub(this.getOutputTotal(assetID)) - } - - /** - * Returns the Transaction - */ - abstract getTransaction(): SBTx - - abstract fromBuffer(bytes: Buffer, offset?: number): number - - toBuffer(): Buffer { - const codecBuf: Buffer = Buffer.alloc(2) - codecBuf.writeUInt16BE(this.transaction.getCodecID(), 0) - const txtype: Buffer = Buffer.alloc(4) - txtype.writeUInt32BE(this.transaction.getTxType(), 0) - const basebuff = this.transaction.toBuffer() - return Buffer.concat( - [codecBuf, txtype, basebuff], - codecBuf.length + txtype.length + basebuff.length - ) - } - - /** - * Signs this [[UnsignedTx]] and returns signed [[StandardTx]] - * - * @param kc An [[KeyChain]] used in signing - * - * @returns A signed [[StandardTx]] - */ - abstract sign( - kc: KCClass - ): StandardTx> - - constructor(transaction: SBTx = undefined, codecID: number = 0) { - super() - this.codecID = codecID - this.transaction = transaction - } -} - -/** - * Class representing a signed transaction. - */ -export abstract class StandardTx< - KPClass extends StandardKeyPair, - KCClass extends StandardKeyChain, - SUBTx extends StandardUnsignedTx< - KPClass, - KCClass, - StandardBaseTx - > -> extends Serializable { - protected _typeName = "StandardTx" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - unsignedTx: this.unsignedTx.serialize(encoding), - credentials: this.credentials.map((c) => c.serialize(encoding)) - } - } - - protected unsignedTx: SUBTx = undefined - protected credentials: Credential[] = [] - - /** - * Returns the [[Credential[]]] - */ - getCredentials(): Credential[] { - return this.credentials - } - - /** - * Returns the [[StandardUnsignedTx]] - */ - getUnsignedTx(): SUBTx { - return this.unsignedTx - } - - abstract fromBuffer(bytes: Buffer, offset?: number): number - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[StandardTx]]. - */ - toBuffer(): Buffer { - const tx: StandardBaseTx = - this.unsignedTx.getTransaction() - const codecID: number = tx.getCodecID() - const txbuff: Buffer = this.unsignedTx.toBuffer() - let bsize: number = txbuff.length - const credlen: Buffer = Buffer.alloc(4) - credlen.writeUInt32BE(this.credentials.length, 0) - const barr: Buffer[] = [txbuff, credlen] - bsize += credlen.length - for (let i: number = 0; i < this.credentials.length; i++) { - this.credentials[`${i}`].setCodecID(codecID) - const credID: Buffer = Buffer.alloc(4) - credID.writeUInt32BE(this.credentials[`${i}`].getCredentialID(), 0) - barr.push(credID) - bsize += credID.length - const credbuff: Buffer = this.credentials[`${i}`].toBuffer() - bsize += credbuff.length - barr.push(credbuff) - } - const buff: Buffer = Buffer.concat(barr, bsize) - return buff - } - - /** - * Takes a base-58 string containing an [[StandardTx]], parses it, populates the class, and returns the length of the Tx in bytes. - * - * @param serialized A base-58 string containing a raw [[StandardTx]] - * - * @returns The length of the raw [[StandardTx]] - * - * @remarks - * unlike most fromStrings, it expects the string to be serialized in cb58 format - */ - fromString(serialized: string): number { - return this.fromBuffer(bintools.cb58Decode(serialized)) - } - - /** - * Returns a cb58 representation of the [[StandardTx]]. - * - * @remarks - * unlike most toStrings, this returns in cb58 serialization format - */ - toString(): string { - return bintools.cb58Encode(this.toBuffer()) - } - - toStringHex(): string { - return `0x${bintools.addChecksum(this.toBuffer()).toString("hex")}` - } - - /** - * Class representing a signed transaction. - * - * @param unsignedTx Optional [[StandardUnsignedTx]] - * @param signatures Optional array of [[Credential]]s - */ - constructor( - unsignedTx: SUBTx = undefined, - credentials: Credential[] = undefined - ) { - super() - if (typeof unsignedTx !== "undefined") { - this.unsignedTx = unsignedTx - if (typeof credentials !== "undefined") { - this.credentials = credentials - } - } - } -} diff --git a/src/common/utxos.ts b/src/common/utxos.ts deleted file mode 100644 index 7fdf203f4..000000000 --- a/src/common/utxos.ts +++ /dev/null @@ -1,695 +0,0 @@ -/** - * @packageDocumentation - * @module Common-UTXOs - */ -import { Buffer } from "buffer/" -import BinTools from "../utils/bintools" -import BN from "bn.js" -import { Output, StandardAmountOutput } from "./output" -import { UnixNow } from "../utils/helperfunctions" -import { MergeRule } from "../utils/constants" -import { - Serializable, - Serialization, - SerializedEncoding -} from "../utils/serialization" -import { MergeRuleError } from "../utils/errors" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Class for representing a single StandardUTXO. - */ -export abstract class StandardUTXO extends Serializable { - protected _typeName = "StandardUTXO" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - return { - ...fields, - codecID: serialization.encoder( - this.codecID, - encoding, - "Buffer", - "decimalString" - ), - txid: serialization.encoder(this.txid, encoding, "Buffer", "cb58"), - outputidx: serialization.encoder( - this.outputidx, - encoding, - "Buffer", - "decimalString" - ), - assetID: serialization.encoder(this.assetID, encoding, "Buffer", "cb58"), - output: this.output.serialize(encoding) - } - } - deserialize(fields: object, encoding: SerializedEncoding = "hex") { - super.deserialize(fields, encoding) - this.codecID = serialization.decoder( - fields["codecID"], - encoding, - "decimalString", - "Buffer", - 2 - ) - this.txid = serialization.decoder( - fields["txid"], - encoding, - "cb58", - "Buffer", - 32 - ) - this.outputidx = serialization.decoder( - fields["outputidx"], - encoding, - "decimalString", - "Buffer", - 4 - ) - this.assetID = serialization.decoder( - fields["assetID"], - encoding, - "cb58", - "Buffer", - 32 - ) - } - - protected codecID: Buffer = Buffer.alloc(2) - protected txid: Buffer = Buffer.alloc(32) - protected outputidx: Buffer = Buffer.alloc(4) - protected assetID: Buffer = Buffer.alloc(32) - protected output: Output = undefined - - /** - * Returns the numeric representation of the CodecID. - */ - getCodecID = (): /* istanbul ignore next */ number => - this.codecID.readUInt8(0) - - /** - * Returns the {@link https://github.com/feross/buffer|Buffer} representation of the CodecID - */ - getCodecIDBuffer = (): Buffer => this.codecID - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} of the TxID. - */ - getTxID = (): /* istanbul ignore next */ Buffer => this.txid - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} of the OutputIdx. - */ - getOutputIdx = (): /* istanbul ignore next */ Buffer => this.outputidx - - /** - * Returns the assetID as a {@link https://github.com/feross/buffer|Buffer}. - */ - getAssetID = (): Buffer => this.assetID - - /** - * Returns the UTXOID as a base-58 string (UTXOID is a string ) - */ - getUTXOID = (): /* istanbul ignore next */ string => - bintools.bufferToB58(Buffer.concat([this.getTxID(), this.getOutputIdx()])) - - /** - * Returns a reference to the output - */ - getOutput = (): Output => this.output - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[StandardUTXO]], parses it, populates the class, and returns the length of the StandardUTXO in bytes. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[StandardUTXO]] - */ - abstract fromBuffer(bytes: Buffer, offset?: number): number - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[StandardUTXO]]. - */ - toBuffer(): Buffer { - const outbuff: Buffer = this.output.toBuffer() - const outputidbuffer: Buffer = Buffer.alloc(4) - outputidbuffer.writeUInt32BE(this.output.getOutputID(), 0) - const barr: Buffer[] = [ - this.codecID, - this.txid, - this.outputidx, - this.assetID, - outputidbuffer, - outbuff - ] - return Buffer.concat( - barr, - this.codecID.length + - this.txid.length + - this.outputidx.length + - this.assetID.length + - outputidbuffer.length + - outbuff.length - ) - } - - abstract fromString(serialized: string): number - - abstract toString(): string - - abstract clone(): this - - abstract create( - codecID?: number, - txid?: Buffer, - outputidx?: Buffer | number, - assetID?: Buffer, - output?: Output - ): this - - /** - * Class for representing a single StandardUTXO. - * - * @param codecID Optional number which specifies the codeID of the UTXO. Default 0 - * @param txID Optional {@link https://github.com/feross/buffer|Buffer} of transaction ID for the StandardUTXO - * @param txidx Optional {@link https://github.com/feross/buffer|Buffer} or number for the index of the transaction's [[Output]] - * @param assetID Optional {@link https://github.com/feross/buffer|Buffer} of the asset ID for the StandardUTXO - * @param outputid Optional {@link https://github.com/feross/buffer|Buffer} or number of the output ID for the StandardUTXO - */ - constructor( - codecID: number = 0, - txID: Buffer = undefined, - outputidx: Buffer | number = undefined, - assetID: Buffer = undefined, - output: Output = undefined - ) { - super() - if (typeof codecID !== "undefined") { - this.codecID.writeUInt8(codecID, 0) - } - if (typeof txID !== "undefined") { - this.txid = txID - } - if (typeof outputidx === "number") { - this.outputidx.writeUInt32BE(outputidx, 0) - } else if (outputidx instanceof Buffer) { - this.outputidx = outputidx - } - - if (typeof assetID !== "undefined") { - this.assetID = assetID - } - if (typeof output !== "undefined") { - this.output = output - } - } -} -/** - * Class representing a set of [[StandardUTXO]]s. - */ -export abstract class StandardUTXOSet< - UTXOClass extends StandardUTXO -> extends Serializable { - protected _typeName = "StandardUTXOSet" - protected _typeID = undefined - - serialize(encoding: SerializedEncoding = "hex"): object { - let fields: object = super.serialize(encoding) - let utxos = {} - for (let utxoid in this.utxos) { - let utxoidCleaned: string = serialization.encoder( - utxoid, - encoding, - "base58", - "base58" - ) - utxos[`${utxoidCleaned}`] = this.utxos[`${utxoid}`].serialize(encoding) - } - let addressUTXOs = {} - for (let address in this.addressUTXOs) { - let addressCleaned: string = serialization.encoder( - address, - encoding, - "hex", - "cb58" - ) - let utxobalance = {} - for (let utxoid in this.addressUTXOs[`${address}`]) { - let utxoidCleaned: string = serialization.encoder( - utxoid, - encoding, - "base58", - "base58" - ) - utxobalance[`${utxoidCleaned}`] = serialization.encoder( - this.addressUTXOs[`${address}`][`${utxoid}`], - encoding, - "BN", - "decimalString" - ) - } - addressUTXOs[`${addressCleaned}`] = utxobalance - } - return { - ...fields, - utxos, - addressUTXOs - } - } - - protected utxos: { [utxoid: string]: UTXOClass } = {} - protected addressUTXOs: { [address: string]: { [utxoid: string]: BN } } = {} // maps address to utxoids:locktime - - abstract parseUTXO(utxo: UTXOClass | string): UTXOClass - - /** - * Returns true if the [[StandardUTXO]] is in the StandardUTXOSet. - * - * @param utxo Either a [[StandardUTXO]] a cb58 serialized string representing a StandardUTXO - */ - includes = (utxo: UTXOClass | string): boolean => { - let utxoX: UTXOClass = undefined - let utxoid: string = undefined - try { - utxoX = this.parseUTXO(utxo) - utxoid = utxoX.getUTXOID() - } catch (e) { - if (e instanceof Error) { - console.log(e.message) - } else { - console.log(e) - } - return false - } - return utxoid in this.utxos - } - - /** - * Adds a [[StandardUTXO]] to the StandardUTXOSet. - * - * @param utxo Either a [[StandardUTXO]] an cb58 serialized string representing a StandardUTXO - * @param overwrite If true, if the UTXOID already exists, overwrite it... default false - * - * @returns A [[StandardUTXO]] if one was added and undefined if nothing was added. - */ - add(utxo: UTXOClass | string, overwrite: boolean = false): UTXOClass { - let utxovar: UTXOClass = undefined - try { - utxovar = this.parseUTXO(utxo) - } catch (e) { - if (e instanceof Error) { - console.log(e.message) - } else { - console.log(e) - } - return undefined - } - - const utxoid: string = utxovar.getUTXOID() - if (!(utxoid in this.utxos) || overwrite === true) { - this.utxos[`${utxoid}`] = utxovar - const addresses: Buffer[] = utxovar.getOutput().getAddresses() - const locktime: BN = utxovar.getOutput().getLocktime() - for (let i: number = 0; i < addresses.length; i++) { - const address: string = addresses[`${i}`].toString("hex") - if (!(address in this.addressUTXOs)) { - this.addressUTXOs[`${address}`] = {} - } - this.addressUTXOs[`${address}`][`${utxoid}`] = locktime - } - return utxovar - } - return undefined - } - - /** - * Adds an array of [[StandardUTXO]]s to the [[StandardUTXOSet]]. - * - * @param utxo Either a [[StandardUTXO]] an cb58 serialized string representing a StandardUTXO - * @param overwrite If true, if the UTXOID already exists, overwrite it... default false - * - * @returns An array of StandardUTXOs which were added. - */ - addArray( - utxos: string[] | UTXOClass[], - overwrite: boolean = false - ): StandardUTXO[] { - const added: UTXOClass[] = [] - for (let i: number = 0; i < utxos.length; i++) { - let result: UTXOClass = this.add(utxos[`${i}`], overwrite) - if (typeof result !== "undefined") { - added.push(result) - } - } - return added - } - - /** - * Removes a [[StandardUTXO]] from the [[StandardUTXOSet]] if it exists. - * - * @param utxo Either a [[StandardUTXO]] an cb58 serialized string representing a StandardUTXO - * - * @returns A [[StandardUTXO]] if it was removed and undefined if nothing was removed. - */ - remove = (utxo: UTXOClass | string): UTXOClass => { - let utxovar: UTXOClass = undefined - try { - utxovar = this.parseUTXO(utxo) - } catch (e) { - if (e instanceof Error) { - console.log(e.message) - } else { - console.log(e) - } - return undefined - } - - const utxoid: string = utxovar.getUTXOID() - if (!(utxoid in this.utxos)) { - return undefined - } - delete this.utxos[`${utxoid}`] - const addresses = Object.keys(this.addressUTXOs) - for (let i: number = 0; i < addresses.length; i++) { - if (utxoid in this.addressUTXOs[addresses[`${i}`]]) { - delete this.addressUTXOs[addresses[`${i}`]][`${utxoid}`] - } - } - return utxovar - } - - /** - * Removes an array of [[StandardUTXO]]s to the [[StandardUTXOSet]]. - * - * @param utxo Either a [[StandardUTXO]] an cb58 serialized string representing a StandardUTXO - * @param overwrite If true, if the UTXOID already exists, overwrite it... default false - * - * @returns An array of UTXOs which were removed. - */ - removeArray = (utxos: string[] | UTXOClass[]): UTXOClass[] => { - const removed: UTXOClass[] = [] - for (let i: number = 0; i < utxos.length; i++) { - const result: UTXOClass = this.remove(utxos[`${i}`]) - if (typeof result !== "undefined") { - removed.push(result) - } - } - return removed - } - - /** - * Gets a [[StandardUTXO]] from the [[StandardUTXOSet]] by its UTXOID. - * - * @param utxoid String representing the UTXOID - * - * @returns A [[StandardUTXO]] if it exists in the set. - */ - getUTXO = (utxoid: string): UTXOClass => this.utxos[`${utxoid}`] - - /** - * Gets all the [[StandardUTXO]]s, optionally that match with UTXOIDs in an array - * - * @param utxoids An optional array of UTXOIDs, returns all [[StandardUTXO]]s if not provided - * - * @returns An array of [[StandardUTXO]]s. - */ - getAllUTXOs = (utxoids: string[] = undefined): UTXOClass[] => { - let results: UTXOClass[] = [] - if (typeof utxoids !== "undefined" && Array.isArray(utxoids)) { - results = utxoids - .filter((utxoid) => this.utxos[`${utxoid}`]) - .map((utxoid) => this.utxos[`${utxoid}`]) - } else { - results = Object.values(this.utxos) - } - return results - } - - /** - * Gets all the [[StandardUTXO]]s as strings, optionally that match with UTXOIDs in an array. - * - * @param utxoids An optional array of UTXOIDs, returns all [[StandardUTXO]]s if not provided - * - * @returns An array of [[StandardUTXO]]s as cb58 serialized strings. - */ - getAllUTXOStrings = (utxoids: string[] = undefined): string[] => { - const results: string[] = [] - const utxos = Object.keys(this.utxos) - if (typeof utxoids !== "undefined" && Array.isArray(utxoids)) { - for (let i: number = 0; i < utxoids.length; i++) { - if (utxoids[`${i}`] in this.utxos) { - results.push(this.utxos[utxoids[`${i}`]].toString()) - } - } - } else { - for (const u of utxos) { - results.push(this.utxos[`${u}`].toString()) - } - } - return results - } - - /** - * Given an address or array of addresses, returns all the UTXOIDs for those addresses - * - * @param address An array of address {@link https://github.com/feross/buffer|Buffer}s - * @param spendable If true, only retrieves UTXOIDs whose locktime has passed - * - * @returns An array of addresses. - */ - getUTXOIDs = ( - addresses: Buffer[] = undefined, - spendable: boolean = true - ): string[] => { - if (typeof addresses !== "undefined") { - const results: string[] = [] - const now: BN = UnixNow() - for (let i: number = 0; i < addresses.length; i++) { - if (addresses[`${i}`].toString("hex") in this.addressUTXOs) { - const entries = Object.entries( - this.addressUTXOs[addresses[`${i}`].toString("hex")] - ) - for (const [utxoid, locktime] of entries) { - if ( - (results.indexOf(utxoid) === -1 && - spendable && - locktime.lte(now)) || - !spendable - ) { - results.push(utxoid) - } - } - } - } - return results - } - return Object.keys(this.utxos) - } - - /** - * Gets the addresses in the [[StandardUTXOSet]] and returns an array of {@link https://github.com/feross/buffer|Buffer}. - */ - getAddresses = (): Buffer[] => - Object.keys(this.addressUTXOs).map((k) => Buffer.from(k, "hex")) - - /** - * Returns the balance of a set of addresses in the StandardUTXOSet. - * - * @param addresses An array of addresses - * @param assetID Either a {@link https://github.com/feross/buffer|Buffer} or an cb58 serialized representation of an AssetID - * @param asOf The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} - * - * @returns Returns the total balance as a {@link https://github.com/indutny/bn.js/|BN}. - */ - getBalance = ( - addresses: Buffer[], - assetID: Buffer | string, - asOf: BN = undefined - ): BN => { - const utxoids: string[] = this.getUTXOIDs(addresses) - const utxos: StandardUTXO[] = this.getAllUTXOs(utxoids) - let spend: BN = new BN(0) - let asset: Buffer - if (typeof assetID === "string") { - asset = bintools.cb58Decode(assetID) - } else { - asset = assetID - } - for (let i: number = 0; i < utxos.length; i++) { - if ( - utxos[`${i}`].getOutput() instanceof StandardAmountOutput && - utxos[`${i}`].getAssetID().toString("hex") === asset.toString("hex") && - utxos[`${i}`].getOutput().meetsThreshold(addresses, asOf) - ) { - spend = spend.add( - (utxos[`${i}`].getOutput() as StandardAmountOutput).getAmount() - ) - } - } - return spend - } - - /** - * Gets all the Asset IDs, optionally that match with Asset IDs in an array - * - * @param utxoids An optional array of Addresses as string or Buffer, returns all Asset IDs if not provided - * - * @returns An array of {@link https://github.com/feross/buffer|Buffer} representing the Asset IDs. - */ - getAssetIDs = (addresses: Buffer[] = undefined): Buffer[] => { - const results: Set = new Set() - let utxoids: string[] = [] - if (typeof addresses !== "undefined") { - utxoids = this.getUTXOIDs(addresses) - } else { - utxoids = this.getUTXOIDs() - } - - for (let i: number = 0; i < utxoids.length; i++) { - if (utxoids[`${i}`] in this.utxos && !(utxoids[`${i}`] in results)) { - results.add(this.utxos[utxoids[`${i}`]].getAssetID()) - } - } - - return [...results] - } - - abstract clone(): this - - abstract create(...args: any[]): this - - filter( - args: any[], - lambda: (utxo: UTXOClass, ...largs: any[]) => boolean - ): this { - let newset: this = this.clone() - let utxos: UTXOClass[] = this.getAllUTXOs() - for (let i: number = 0; i < utxos.length; i++) { - if (lambda(utxos[`${i}`], ...args) === false) { - newset.remove(utxos[`${i}`]) - } - } - return newset - } - - /** - * Returns a new set with copy of UTXOs in this and set parameter. - * - * @param utxoset The [[StandardUTXOSet]] to merge with this one - * @param hasUTXOIDs Will subselect a set of [[StandardUTXO]]s which have the UTXOIDs provided in this array, defults to all UTXOs - * - * @returns A new StandardUTXOSet that contains all the filtered elements. - */ - merge = (utxoset: this, hasUTXOIDs: string[] = undefined): this => { - const results: this = this.create() - const utxos1: UTXOClass[] = this.getAllUTXOs(hasUTXOIDs) - const utxos2: UTXOClass[] = utxoset.getAllUTXOs(hasUTXOIDs) - const process = (utxo: UTXOClass) => { - results.add(utxo) - } - utxos1.forEach(process) - utxos2.forEach(process) - return results as this - } - - /** - * Set intersetion between this set and a parameter. - * - * @param utxoset The set to intersect - * - * @returns A new StandardUTXOSet containing the intersection - */ - intersection = (utxoset: this): this => { - const us1: string[] = this.getUTXOIDs() - const us2: string[] = utxoset.getUTXOIDs() - const results: string[] = us1.filter((utxoid) => us2.includes(utxoid)) - return this.merge(utxoset, results) as this - } - - /** - * Set difference between this set and a parameter. - * - * @param utxoset The set to difference - * - * @returns A new StandardUTXOSet containing the difference - */ - difference = (utxoset: this): this => { - const us1: string[] = this.getUTXOIDs() - const us2: string[] = utxoset.getUTXOIDs() - const results: string[] = us1.filter((utxoid) => !us2.includes(utxoid)) - return this.merge(utxoset, results) as this - } - - /** - * Set symmetrical difference between this set and a parameter. - * - * @param utxoset The set to symmetrical difference - * - * @returns A new StandardUTXOSet containing the symmetrical difference - */ - symDifference = (utxoset: this): this => { - const us1: string[] = this.getUTXOIDs() - const us2: string[] = utxoset.getUTXOIDs() - const results: string[] = us1 - .filter((utxoid) => !us2.includes(utxoid)) - .concat(us2.filter((utxoid) => !us1.includes(utxoid))) - return this.merge(utxoset, results) as this - } - - /** - * Set union between this set and a parameter. - * - * @param utxoset The set to union - * - * @returns A new StandardUTXOSet containing the union - */ - union = (utxoset: this): this => this.merge(utxoset) as this - - /** - * Merges a set by the rule provided. - * - * @param utxoset The set to merge by the MergeRule - * @param mergeRule The [[MergeRule]] to apply - * - * @returns A new StandardUTXOSet containing the merged data - * - * @remarks - * The merge rules are as follows: - * * "intersection" - the intersection of the set - * * "differenceSelf" - the difference between the existing data and new set - * * "differenceNew" - the difference between the new data and the existing set - * * "symDifference" - the union of the differences between both sets of data - * * "union" - the unique set of all elements contained in both sets - * * "unionMinusNew" - the unique set of all elements contained in both sets, excluding values only found in the new set - * * "unionMinusSelf" - the unique set of all elements contained in both sets, excluding values only found in the existing set - */ - mergeByRule = (utxoset: this, mergeRule: MergeRule): this => { - let uSet: this - switch (mergeRule) { - case "intersection": - return this.intersection(utxoset) - case "differenceSelf": - return this.difference(utxoset) - case "differenceNew": - return utxoset.difference(this) as this - case "symDifference": - return this.symDifference(utxoset) - case "union": - return this.union(utxoset) - case "unionMinusNew": - uSet = this.union(utxoset) - return uSet.difference(utxoset) as this - case "unionMinusSelf": - uSet = this.union(utxoset) - return uSet.difference(this) as this - default: - throw new MergeRuleError( - "Error - StandardUTXOSet.mergeByRule: bad MergeRule" - ) - } - } -} diff --git a/src/constants/bls.ts b/src/constants/bls.ts new file mode 100644 index 000000000..a06deb2f5 --- /dev/null +++ b/src/constants/bls.ts @@ -0,0 +1,2 @@ +export const BLS_PUBKEY_LENGTH = 48; +export const BLS_SIGNATURE_LENGTH = 96; diff --git a/src/constants/codec.ts b/src/constants/codec.ts new file mode 100644 index 000000000..1e7d3ee0f --- /dev/null +++ b/src/constants/codec.ts @@ -0,0 +1 @@ +export const DEFAULT_CODEC_VERSION = 0; diff --git a/src/constants/conversion.ts b/src/constants/conversion.ts new file mode 100644 index 000000000..69006836f --- /dev/null +++ b/src/constants/conversion.ts @@ -0,0 +1 @@ +export const CorethToEVMRatio = BigInt(1e9); diff --git a/src/constants/endpoints.ts b/src/constants/endpoints.ts new file mode 100644 index 000000000..0127d9a3a --- /dev/null +++ b/src/constants/endpoints.ts @@ -0,0 +1,6 @@ +export const MAINNET_PUBLIC_API_BASE_URL = 'https://api.avax.network'; +export const TESTNET_PUBLIC_API_BASE_URL = 'https://api.avax-test.network'; + +export const C_CHAIN_ENDPOINT = '/ext/bc/C/rpc'; +export const X_CHAIN_ENDPOINT = '/ext/bc/X'; +export const P_CHAIN_ENDPOINT = '/ext/bc/P'; diff --git a/src/constants/networkIDs.ts b/src/constants/networkIDs.ts new file mode 100644 index 000000000..67e03c3e1 --- /dev/null +++ b/src/constants/networkIDs.ts @@ -0,0 +1,50 @@ +import { Id } from '../serializable/fxs/common'; + +export const PrimaryNetworkID = new Id(new Uint8Array(32)); +export const PlatformChainID = new Id(new Uint8Array(32)); + +export const MainnetName = 'mainnet'; +export const CascadeName = 'cascade'; +export const DenaliName = 'denali'; +export const EverestName = 'everest'; +export const FujiName = 'fuji'; +export const TestnetName = 'testnet'; +export const UnitTestName = 'testing'; +export const LocalName = 'local'; + +export const MainnetID = 1; +export const CascadeID = 2; +export const DenaliID = 3; +export const EverestID = 4; +export const FujiID = 5; + +export const TestnetID = FujiID; +export const UnitTestID = 10; +export const LocalID = 12345; + +export const MainnetHRP = 'avax'; +export const CascadeHRP = 'cascade'; +export const DenaliHRP = 'denali'; +export const EverestHRP = 'everest'; +export const FujiHRP = 'fuji'; +export const UnitTestHRP = 'testing'; +export const LocalHRP = 'local'; +export const FallbackHRP = 'custom'; + +export const NetworkIDToHRP = { + [MainnetID]: MainnetHRP, + [CascadeID]: CascadeHRP, + [DenaliID]: DenaliHRP, + [EverestID]: EverestHRP, + [FujiID]: FujiHRP, + [UnitTestID]: UnitTestHRP, + [LocalID]: LocalHRP, +}; + +/** + * Returns the human readbale part for a bech32 string given the network ID. + * @param networkID + */ +export const getHRP = (networkID: number): string => { + return NetworkIDToHRP[networkID] ?? FallbackHRP; +}; diff --git a/src/constants/node.ts b/src/constants/node.ts new file mode 100644 index 000000000..2c2a78280 --- /dev/null +++ b/src/constants/node.ts @@ -0,0 +1 @@ +export const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom'); diff --git a/src/constants/public-urls.ts b/src/constants/public-urls.ts new file mode 100644 index 000000000..82c49b464 --- /dev/null +++ b/src/constants/public-urls.ts @@ -0,0 +1,2 @@ +export const AVAX_PUBLIC_URL = 'https://api.avax.network'; +export const AVAX_PUBLIC_URL_FUJI = 'https://api.avax-test.network'; diff --git a/src/constants/zeroValue.ts b/src/constants/zeroValue.ts new file mode 100644 index 000000000..7de9780cf --- /dev/null +++ b/src/constants/zeroValue.ts @@ -0,0 +1,18 @@ +import { Id } from '../serializable/fxs/common'; +import { OutputOwners } from '../serializable/fxs/secp256k1'; +import { + SepkSignatureLength, + Signature, +} from '../serializable/fxs/secp256k1/signature'; +import { BigIntPr, Int } from '../serializable/primitives'; + +export const zeroOutputOwners = new OutputOwners( + new BigIntPr(0n), + new Int(0), + [], +); + +export const emptyId = new Id(new Uint8Array(32)); +export const emptySignature = new Signature( + new Uint8Array(Array(SepkSignatureLength).fill(0)), +); diff --git a/src/fixtures/avax.ts b/src/fixtures/avax.ts new file mode 100644 index 000000000..390006d09 --- /dev/null +++ b/src/fixtures/avax.ts @@ -0,0 +1,176 @@ +import { + BaseTx as AvaxBaseTx, + TransferableInput, + TransferableOutput, +} from '../serializable/avax'; +import { UTXOID } from '../serializable/avax/utxoId'; +import { TransferableOp } from '../serializable/avax/transferableOp'; +import { Utxo } from '../serializable/avax/utxo'; +import { CreateAssetTx } from '../serializable/avm/createAssetTx'; +import { ExportTx } from '../serializable/avm/exportTx'; +import { ImportTx } from '../serializable/avm/importTx'; +import { BaseTx as AvmBaseTx } from '../serializable/avm/baseTx'; +import { BaseTx as PvmBaseTx } from '../serializable/pvm/baseTx'; +import { InitialState } from '../serializable/avm/initialState'; +import { OperationTx } from '../serializable/avm/operationTx'; +import { SignedTx } from '../serializable/avax/signedTx'; +import { Byte, Int, Short } from '../serializable/primitives'; +import { concatBytes } from '../utils/buffer'; +import { id, idBytes } from './common'; +import { mintOperation, mintOperationBytes } from './nft'; +import { + bytes, + bytesBytes, + int, + intBytes, + stringPr, + stringPrBytes, +} from './primitives'; +import { + credential, + credentialBytes, + mintOutput, + mintOutputBytes, + transferInput, + transferInputBytes, + transferOutput, + transferOutputBytes, +} from './secp256k1'; +import { bytesForInt } from './utils/bytesFor'; +import { makeList, makeListBytes } from './utils/makeList'; + +// https://docs.avax.network/specs/avm-transaction-serialization#transferable-output-example +export const transferableOutputBytes = () => + concatBytes(idBytes(), bytesForInt(7), transferOutputBytes()); + +export const transferableOutput = () => + new TransferableOutput(id(), transferOutput()); + +export const transferableOutputs = makeList(transferableOutput); + +export const transferableOutputsBytes = makeListBytes(transferableOutputBytes); + +// https://docs.avax.network/specs/avm-transaction-serialization#transferable-input-example +export const transferableInputBytes = () => + concatBytes(utxoIdBytes(), idBytes(), bytesForInt(5), transferInputBytes()); + +export const transferableInput = () => + new TransferableInput(utxoId(), id(), transferInput()); + +export const transferableInputsBytes = makeListBytes(transferableInputBytes); +export const transferableInputs = makeList(transferableInput); + +export const transferableOp = () => + new TransferableOp(id(), makeList(utxoId)(), mintOperation()); +export const transferableOpBytes = () => + concatBytes( + idBytes(), + makeListBytes(utxoIdBytes)(), + bytesForInt(12), + mintOperationBytes(), + ); + +export const utxoIdBytes = () => concatBytes(idBytes(), bytesForInt(5)); + +export const utxoId = () => new UTXOID(id(), new Int(5)); + +export const baseTx = () => + new AvaxBaseTx( + int(), + id(), + transferableOutputs(), + transferableInputs(), + bytes(), + ); + +export const baseTxbytes = () => + concatBytes( + intBytes(), + idBytes(), + transferableOutputsBytes(), + transferableInputsBytes(), + bytesBytes(), + ); + +export const initialStateBytes = () => + concatBytes( + intBytes(), + bytesForInt(2), + bytesForInt(5), + transferInputBytes(), + bytesForInt(6), + mintOutputBytes(), + ); + +export const initialState = () => + new InitialState(int(), [transferInput(), mintOutput()]); + +export const createAssetTxBytes = () => + concatBytes( + baseTxbytes(), + stringPrBytes(), + stringPrBytes(), + new Uint8Array([0x0f]), + makeListBytes(initialStateBytes)(), + ); +export const createAssetTx = () => + new CreateAssetTx( + baseTx(), + stringPr(), + stringPr(), + new Byte(new Uint8Array([0x0f])), + makeList(initialState)(), + ); + +export const operationTx = () => + new OperationTx(baseTx(), makeList(transferableOp)()); + +export const operationTxBytes = () => + concatBytes(baseTxbytes(), makeListBytes(transferableOpBytes)()); + +export const importTx = () => + new ImportTx(baseTx(), id(), makeList(transferableInput)()); + +export const importTxBytes = () => + concatBytes( + baseTxbytes(), + idBytes(), + makeListBytes(transferableInputBytes)(), + ); + +export const exportTx = () => + new ExportTx(baseTx(), id(), makeList(transferableOutput)()); + +export const exportTxBytes = () => + concatBytes( + baseTxbytes(), + idBytes(), + makeListBytes(transferableOutputBytes)(), + ); + +export const avmBaseTx = () => new AvmBaseTx(baseTx()); + +export const avmBaseTxBytes = () => baseTxbytes(); + +export const pvmBaseTx = () => new PvmBaseTx(baseTx()); + +export const pvmBaseTxBytes = () => baseTxbytes(); + +export const signedTx = () => + new SignedTx(exportTx(), [credential(), credential()]); + +export const signedTxBytes = () => + concatBytes( + new Short(0).toBytes(), + bytesForInt(4), + exportTxBytes(), + bytesForInt(2), + bytesForInt(9), + credentialBytes(), + bytesForInt(9), + credentialBytes(), + ); + +export const utxo = () => new Utxo(utxoId(), id(), transferOutput()); +export const utxoBytes = () => + concatBytes(utxoIdBytes(), idBytes(), bytesForInt(7), transferOutputBytes()); diff --git a/src/fixtures/codec.ts b/src/fixtures/codec.ts new file mode 100644 index 000000000..f60a39064 --- /dev/null +++ b/src/fixtures/codec.ts @@ -0,0 +1,15 @@ +import { getAVMManager } from '../serializable/avm/codec'; +import { codec as EVMCodec } from '../serializable/evm/codec'; +import { Short } from '../serializable/primitives'; +import { codec } from '../serializable/pvm/codec'; + +// Check for circular imports in the fx type +// registries if tests are throwing errors + +export const testManager = getAVMManager; + +export const testCodec = () => testManager().getCodecForVersion(new Short(0)); + +export const testPVMCodec = () => codec; + +export const testEVMCodec = () => EVMCodec; diff --git a/src/fixtures/common.ts b/src/fixtures/common.ts new file mode 100644 index 000000000..3da6b785d --- /dev/null +++ b/src/fixtures/common.ts @@ -0,0 +1,45 @@ +import { Address } from '../serializable/fxs/common/address'; +import { Id } from '../serializable/fxs/common/id'; +import { NodeId } from '../serializable/fxs/common/nodeId'; +import { bytesForInt } from './utils/bytesFor'; +import { makeList } from './utils/makeList'; + +const TEST_ADDRESS_HEX = '8db97c7cece249c2b98bdc0226cc4c2a57bf52fc'; +const TEST_ID_HEX = + 'dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db'; +const TEST_NODE_ID_HEX = '0xe9094f73698002fd52c90819b457b9fbc866ab80'; + +export const addressBytes = () => + new Uint8Array([ + 0x8d, 0xb9, 0x7c, 0x7c, 0xec, 0xe2, 0x49, 0xc2, 0xb9, 0x8b, 0xdc, 0x02, + 0x26, 0xcc, 0x4c, 0x2a, 0x57, 0xbf, 0x52, 0xfc, + ]); + +export const address = () => Address.fromHex(TEST_ADDRESS_HEX); + +export const idBytes = () => + new Uint8Array([ + 0xdb, 0xcf, 0x89, 0x0f, 0x77, 0xf4, 0x9b, 0x96, 0x85, 0x76, 0x48, 0xb7, + 0x2b, 0x77, 0xf9, 0xf8, 0x29, 0x37, 0xf2, 0x8a, 0x68, 0x70, 0x4a, 0xf0, + 0x5d, 0xa0, 0xdc, 0x12, 0xba, 0x53, 0xf2, 0xdb, + ]); + +export const id = () => Id.fromHex(TEST_ID_HEX); + +export const nodeIdBytes = () => + new Uint8Array([ + 0xe9, 0x09, 0x4f, 0x73, 0x69, 0x80, 0x02, 0xfd, 0x52, 0xc9, 0x08, 0x19, + 0xb4, 0x57, 0xb9, 0xfb, 0xc8, 0x66, 0xab, 0x80, + ]); + +export const nodeId = () => NodeId.fromHex(TEST_NODE_ID_HEX); + +export const addressesBytes = () => + new Uint8Array([ + //length + ...bytesForInt(2), + ...addressBytes(), + ...addressBytes(), + ]); + +export const addresses = () => makeList(address); diff --git a/src/fixtures/context.ts b/src/fixtures/context.ts new file mode 100644 index 000000000..2e6aff484 --- /dev/null +++ b/src/fixtures/context.ts @@ -0,0 +1,19 @@ +import type { Context } from '../vms/context'; + +export const testContext: Context = { + xBlockchainID: '2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM', + pBlockchainID: '11111111111111111111111111111111LpoYY', + cBlockchainID: '2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5', + avaxAssetID: 'FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z', + baseTxFee: 1000000n, + createAssetTxFee: 10000000n, + createSubnetTxFee: 1000000000n, + transformSubnetTxFee: 10000000000n, + createBlockchainTxFee: 1000000000n, + addPrimaryNetworkValidatorFee: 0n, + addPrimaryNetworkDelegatorFee: 0n, + addSubnetValidatorFee: 1000000n, + addSubnetDelegatorFee: 1000000n, + networkID: 1, + hrp: 'avax', +}; diff --git a/src/fixtures/evm.ts b/src/fixtures/evm.ts new file mode 100644 index 000000000..d901cb420 --- /dev/null +++ b/src/fixtures/evm.ts @@ -0,0 +1,58 @@ +import { concatBytes } from '@noble/hashes/utils'; +import { ExportTx } from '../serializable/evm/exportTx'; +import { ImportTx } from '../serializable/evm/importTx'; +import { Input } from '../serializable/evm/input'; +import { Output } from '../serializable/evm/output'; +import { + transferableInput, + transferableInputBytes, + transferableOutput, + transferableOutputBytes, +} from './avax'; +import { address, addressBytes, id, idBytes } from './common'; +import { bigIntPr, bigIntPrBytes, int, intBytes } from './primitives'; +import { makeList, makeListBytes } from './utils/makeList'; + +export const output = () => new Output(address(), bigIntPr(), id()); +export const outputBytes = () => + concatBytes(addressBytes(), bigIntPrBytes(), idBytes()); + +export const importTx = () => + new ImportTx( + int(), + id(), + id(), + makeList(transferableInput)(), + makeList(output)(), + ); + +export const importTxBytes = () => + concatBytes( + intBytes(), + idBytes(), + idBytes(), + makeListBytes(transferableInputBytes)(), + makeListBytes(outputBytes)(), + ); + +export const input = () => new Input(address(), bigIntPr(), id(), bigIntPr()); +export const inputBytes = () => + concatBytes(addressBytes(), bigIntPrBytes(), idBytes(), bigIntPrBytes()); + +export const exportTx = () => + new ExportTx( + int(), + id(), + id(), + makeList(input)(), + makeList(transferableOutput)(), + ); + +export const exportTxBytes = () => + concatBytes( + intBytes(), + idBytes(), + idBytes(), + makeListBytes(inputBytes)(), + makeListBytes(transferableOutputBytes)(), + ); diff --git a/src/fixtures/nft.ts b/src/fixtures/nft.ts new file mode 100644 index 000000000..a27915660 --- /dev/null +++ b/src/fixtures/nft.ts @@ -0,0 +1,40 @@ +import { + MintOperation, + MintOutput, + TransferOutput, +} from '../serializable/fxs/nft'; +import { bytes, bytesBytes, int, intBytes } from './primitives'; +import { TransferOperation } from '../serializable/fxs/nft/transferOperation'; +import { concatBytes } from '../utils/buffer'; +import { + input, + inputBytes, + outputOwner, + outputOwnerBytes, + outputOwnersList, + outputOwnersListBytes, +} from './secp256k1'; + +// https://docs.avax.network/specs/avm-transaction-serialization/#nft-mint-output-example +export const mintOutputBytes = () => + concatBytes(intBytes(), outputOwnerBytes()); + +export const mintOutput = () => new MintOutput(int(), outputOwner()); + +// https://docs.avax.network/specs/avm-transaction-serialization/#nft-transfer-output-example +export const transferOutputBytes = () => + concatBytes(intBytes(), bytesBytes(), outputOwnerBytes()); + +export const transferOutput = () => + new TransferOutput(int(), bytes(), outputOwner()); + +export const mintOperationBytes = () => + concatBytes(inputBytes(), intBytes(), bytesBytes(), outputOwnersListBytes()); +export const mintOperation = () => + new MintOperation(input(), int(), bytes(), outputOwnersList()); + +export const transferOperationBytes = () => + concatBytes(inputBytes(), transferOutputBytes()); + +export const transferOperation = () => + new TransferOperation(input(), transferOutput()); diff --git a/src/fixtures/primitives.ts b/src/fixtures/primitives.ts new file mode 100644 index 000000000..d824f653c --- /dev/null +++ b/src/fixtures/primitives.ts @@ -0,0 +1,62 @@ +import { + BigIntPr, + Byte, + Bytes, + Int, + Short, + Stringpr, +} from '../serializable/primitives'; +import { concatBytes } from '../utils/buffer'; +import { bytesForInt } from './utils/bytesFor'; + +export const intBytes = () => new Uint8Array([0x00, 0x00, 0x00, 0x0d]); + +export const int = () => new Int(13); + +export const intsBytes = () => + concatBytes(bytesForInt(3), bytesForInt(3), bytesForInt(2), bytesForInt(1)); + +export const ints = () => [new Int(3), new Int(2), new Int(1)]; + +export const byteByte = () => new Uint8Array([0x01]); + +export const byte = () => new Byte(new Uint8Array([0x01])); + +export const bytesBytes = () => + concatBytes(bytesForInt(2), new Uint8Array([0x01, 0x02])); + +export const bytes = () => new Bytes(new Uint8Array([0x01, 0x02])); + +export const bigIntPrBytes = () => + new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x84, 0x80]); + +export const bigIntPr = () => new BigIntPr(2000000n); + +export const stringPr = () => new Stringpr('Avax'); + +export const stringPrBytes = () => + new Uint8Array([0x00, 0x04, 0x41, 0x76, 0x61, 0x78]); + +export const shortBytes = () => new Uint8Array([0x00, 0x0d]); + +export const short = () => new Short(13); + +export const blsPublicKeyBytes = () => + new Uint8Array([ + 0x85, 0x02, 0x5b, 0xca, 0x6a, 0x30, 0x2d, 0xc6, 0x13, 0x38, 0xff, 0x49, + 0xc8, 0xba, 0xa5, 0x72, 0xde, 0xd3, 0xe8, 0x6f, 0x37, 0x59, 0x30, 0x4c, + 0x7f, 0x61, 0x8a, 0x2a, 0x25, 0x93, 0xc1, 0x87, 0xe0, 0x80, 0xa3, 0xcf, + 0xde, 0xc9, 0x50, 0x40, 0x30, 0x9a, 0xd1, 0xf1, 0x58, 0x95, 0x30, 0x67, + ]); + +export const blsSignatureBytes = () => + new Uint8Array([ + 0x8b, 0x1d, 0x61, 0x33, 0xd1, 0x7e, 0x34, 0x83, 0x22, 0x0a, 0xd9, 0x60, + 0xb6, 0xfd, 0xe1, 0x1e, 0x4e, 0x12, 0x14, 0xa8, 0xce, 0x21, 0xef, 0x61, + 0x62, 0x27, 0xe5, 0xd5, 0xee, 0xf0, 0x70, 0xd7, 0x50, 0x0e, 0x6f, 0x7d, + 0x44, 0x52, 0xc5, 0xa7, 0x60, 0x62, 0x0c, 0xc0, 0x67, 0x95, 0xcb, 0xe2, + 0x18, 0xe0, 0x72, 0xeb, 0xa7, 0x6d, 0x94, 0x78, 0x8d, 0x9d, 0x01, 0x17, + 0x6c, 0xe4, 0xec, 0xad, 0xfb, 0x96, 0xb4, 0x7f, 0x94, 0x22, 0x81, 0x89, + 0x4d, 0xdf, 0xad, 0xd1, 0xc1, 0x74, 0x3f, 0x7f, 0x54, 0x9f, 0x1d, 0x07, + 0xd5, 0x9d, 0x55, 0x65, 0x59, 0x27, 0xf7, 0x2b, 0xc6, 0xbf, 0x7c, 0x12, + ]); diff --git a/src/fixtures/pvm.ts b/src/fixtures/pvm.ts new file mode 100644 index 000000000..54ce32b31 --- /dev/null +++ b/src/fixtures/pvm.ts @@ -0,0 +1,292 @@ +import { concatBytes } from '@noble/hashes/utils'; +import { + AddDelegatorTx, + AddPermissionlessDelegatorTx, + AddPermissionlessValidatorTx, + AddSubnetValidatorTx, + AddValidatorTx, + AdvanceTimeTx, + CreateChainTx, + CreateSubnetTx, + ExportTx, + ImportTx, + ProofOfPossession, + Signer, + StakeableLockIn, + StakeableLockOut, + SubnetValidator, + Validator, + RemoveSubnetValidatorTx, + TransferSubnetOwnershipTx, + TransformSubnetTx, +} from '../serializable/pvm'; +import { + baseTx, + baseTxbytes, + transferableInput, + transferableInputBytes, + transferableOutput, + transferableOutputBytes, +} from './avax'; +import { id, idBytes, nodeId, nodeIdBytes } from './common'; +import { + bigIntPr, + bigIntPrBytes, + bytes, + bytesBytes, + int, + intBytes, + blsPublicKeyBytes, + blsSignatureBytes, + stringPr, + stringPrBytes, + byte, + byteByte, +} from './primitives'; +import { + input, + inputBytes, + outputOwner, + outputOwnerBytes, + transferInput, + transferInputBytes, + transferOutput, + transferOutputBytes, +} from './secp256k1'; +import { bytesForInt } from './utils/bytesFor'; +import { makeList, makeListBytes } from './utils/makeList'; + +export const validator = () => + new Validator(nodeId(), bigIntPr(), bigIntPr(), bigIntPr()); + +export const validatorBytes = () => + concatBytes(nodeIdBytes(), bigIntPrBytes(), bigIntPrBytes(), bigIntPrBytes()); + +export const addValidatorTx = () => + new AddValidatorTx( + baseTx(), + validator(), + makeList(transferableOutput)(), + outputOwner(), + int(), + ); +export const addValidatorTxBytes = () => + concatBytes( + baseTxbytes(), + validatorBytes(), + makeListBytes(transferableOutputBytes)(), + bytesForInt(11), + outputOwnerBytes(), + intBytes(), + ); + +export const subnetValidator = () => new SubnetValidator(validator(), id()); + +export const subnetValidatorBytes = () => + concatBytes(validatorBytes(), idBytes()); + +export const addSubnetValidatorTx = () => + new AddSubnetValidatorTx(baseTx(), subnetValidator(), input()); + +export const addSubnetValidatorTxBytes = () => + concatBytes( + baseTxbytes(), + subnetValidatorBytes(), + bytesForInt(10), + inputBytes(), + ); + +export const addDelegatorTx = () => + new AddDelegatorTx( + baseTx(), + validator(), + makeList(transferableOutput)(), + outputOwner(), + ); + +export const addDelegatorTxBytes = () => + concatBytes( + baseTxbytes(), + validatorBytes(), + makeListBytes(transferableOutputBytes)(), + bytesForInt(11), + outputOwnerBytes(), + ); + +export const createChainTx = () => + new CreateChainTx( + baseTx(), + id(), + stringPr(), + id(), + makeList(id)(), + bytes(), + input(), + ); + +export const createChainTxBytes = () => + concatBytes( + baseTxbytes(), + idBytes(), + stringPrBytes(), + idBytes(), + makeListBytes(idBytes)(), + bytesBytes(), + bytesForInt(10), + inputBytes(), + ); + +export const createSubnetTx = () => new CreateSubnetTx(baseTx(), outputOwner()); +export const removeValidatorTx = () => + new RemoveSubnetValidatorTx(baseTx(), nodeId(), id(), input()); + +export const createSubnetTxBytes = () => + concatBytes(baseTxbytes(), bytesForInt(11), outputOwnerBytes()); + +export const importTx = () => + new ImportTx(baseTx(), id(), makeList(transferableInput)()); + +export const importTxBytes = () => + concatBytes( + baseTxbytes(), + idBytes(), + makeListBytes(transferableInputBytes)(), + ); + +export const exportTx = () => + new ExportTx(baseTx(), id(), makeList(transferableOutput)()); + +export const exportTxBytes = () => + concatBytes( + baseTxbytes(), + idBytes(), + makeListBytes(transferableOutputBytes)(), + ); + +export const removeSubnetValidatorTxBytes = () => + concatBytes( + baseTxbytes(), + nodeIdBytes(), + idBytes(), + bytesForInt(10), + inputBytes(), + ); + +export const stakeableLockIn = () => + new StakeableLockIn(bigIntPr(), transferInput()); + +export const stakeableLockInBytes = () => + concatBytes(bigIntPrBytes(), bytesForInt(5), transferInputBytes()); + +export const stakeableLockOut = () => + new StakeableLockOut(bigIntPr(), transferOutput()); + +export const stakeableLockOutBytes = () => + concatBytes(bigIntPrBytes(), bytesForInt(7), transferOutputBytes()); + +export const advanceTimeTx = () => new AdvanceTimeTx(bigIntPr()); + +export const advanceTimeBytesTx = () => bigIntPrBytes(); + +export const proofOfPossession = () => + new ProofOfPossession(blsPublicKeyBytes(), blsSignatureBytes()); + +export const signer = () => new Signer(proofOfPossession()); +export const signerBytes = () => + concatBytes(blsPublicKeyBytes(), blsSignatureBytes()); + +export const addPermissionlessValidatorTx = () => + new AddPermissionlessValidatorTx( + baseTx(), + subnetValidator(), + signer(), + makeList(transferableOutput)(), + outputOwner(), + outputOwner(), + int(), + ); + +export const addPermissionlessValidatorTxBytes = () => + concatBytes( + baseTxbytes(), + subnetValidatorBytes(), + bytesForInt(28), + signerBytes(), + makeListBytes(transferableOutputBytes)(), + bytesForInt(11), + outputOwnerBytes(), + bytesForInt(11), + outputOwnerBytes(), + intBytes(), + ); + +export const addPermissionlessDelegatorTx = () => + new AddPermissionlessDelegatorTx( + baseTx(), + subnetValidator(), + makeList(transferableOutput)(), + outputOwner(), + ); + +export const addPermissionlessDelegatorTxBytes = () => + concatBytes( + baseTxbytes(), + subnetValidatorBytes(), + makeListBytes(transferableOutputBytes)(), + bytesForInt(11), + outputOwnerBytes(), + ); + +export const transferSubnetOwnershipTx = () => + new TransferSubnetOwnershipTx(baseTx(), id(), input(), outputOwner()); + +export const transferSubnetOwnershipTxBytes = () => + concatBytes( + baseTxbytes(), + idBytes(), + bytesForInt(10), + inputBytes(), + bytesForInt(11), + outputOwnerBytes(), + ); + +export const transformSubnetTx = () => + new TransformSubnetTx( + baseTx(), + id(), + id(), + bigIntPr(), + bigIntPr(), + bigIntPr(), + bigIntPr(), + bigIntPr(), + bigIntPr(), + int(), + int(), + int(), + int(), + byte(), + int(), + input(), + ); + +export const transformSubnetTxBytes = () => + concatBytes( + baseTxbytes(), + idBytes(), + idBytes(), + bigIntPrBytes(), + bigIntPrBytes(), + bigIntPrBytes(), + bigIntPrBytes(), + bigIntPrBytes(), + bigIntPrBytes(), + intBytes(), + intBytes(), + intBytes(), + intBytes(), + byteByte(), + intBytes(), + bytesForInt(10), + inputBytes(), + ); diff --git a/src/fixtures/secp256k1.ts b/src/fixtures/secp256k1.ts new file mode 100644 index 000000000..3a3d66851 --- /dev/null +++ b/src/fixtures/secp256k1.ts @@ -0,0 +1,107 @@ +import { + Input, + MintOperation, + MintOutput, + OutputOwners, + TransferInput, + TransferOutput, +} from '../serializable/fxs/secp256k1'; +import { Credential } from '../serializable/fxs/secp256k1/credential'; +import { OutputOwnersList } from '../serializable/fxs/secp256k1/outputOwnersList'; +import { Signature } from '../serializable/fxs/secp256k1/signature'; +import { concatBytes, hexToBuffer } from '../utils/buffer'; +import { addresses, addressesBytes } from './common'; +import { + bigIntPr, + bigIntPrBytes, + int, + intBytes, + ints, + intsBytes, +} from './primitives'; +import { bytesForInt } from './utils/bytesFor'; + +// https://docs.avax.network/specs/avm-transaction-serialization#secp256k1-mint-output-example +export const mintOutputBytes = () => outputOwnerBytes(); + +export const mintOutput = () => new MintOutput(outputOwner()); + +// https://docs.avax.network/specs/avm-transaction-serialization#secp256k1-transfer-output +export const transferOutputBytes = () => + concatBytes(bigIntPrBytes(), outputOwnerBytes()); + +export const transferOutput = () => + new TransferOutput(bigIntPr(), outputOwner()); + +export const outputOwnerBytes = () => + concatBytes( + // locktime: + bigIntPrBytes(), + // threshold: + intBytes(), + addressesBytes(), + ); + +export const outputOwner = () => + new OutputOwners(bigIntPr(), int(), addresses()()); + +export const inputBytes = () => intsBytes(); + +export const input = () => new Input(ints()); + +// https://docs.avax.network/specs/avm-transaction-serialization#secp256k1-transfer-input-example +export const transferInputBytes = () => + concatBytes(bigIntPrBytes(), inputBytes()); + +export const transferInput = () => new TransferInput(bigIntPr(), input()); + +// https://docs.avax.network/specs/avm-transaction-serialization#secp256k1-mint-operation-example +export const mintOperationBytes = () => + concatBytes(inputBytes(), mintOutputBytes(), transferOutputBytes()); + +export const mintOperation = () => + new MintOperation(input(), new MintOutput(outputOwner()), transferOutput()); + +export const outputOwnersListBytes = () => + concatBytes(bytesForInt(2), outputOwnerBytes(), outputOwnerBytes()); + +export const outputOwnersList = () => + new OutputOwnersList([outputOwner(), outputOwner()]); + +export const signatureBytes = () => + new Uint8Array([ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, + 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1e, 0x1d, 0x1f, 0x20, 0x21, 0x22, 0x23, + 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2e, 0x2d, 0x2f, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, + 0x3c, 0x3d, 0x3e, 0x3f, 0x00, + ]); + +export const signature2Bytes = () => + new Uint8Array([ + 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, + 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, + 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5e, 0x5d, 0x5f, 0x60, 0x61, 0x62, 0x63, + 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6e, 0x6d, 0x6f, + 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, + 0x7c, 0x7d, 0x7e, 0x7f, 0x00, + ]); + +export const signature = () => + new Signature( + hexToBuffer( + '0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1e1d1f202122232425262728292a2b2c2e2d2f303132333435363738393a3b3c3d3e3f00', + ), + ); + +export const signature2 = () => + new Signature( + hexToBuffer( + '0x404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5e5d5f606162636465666768696a6b6c6e6d6f707172737475767778797a7b7c7d7e7f00', + ), + ); + +export const credentialBytes = () => + concatBytes(bytesForInt(2), signatureBytes(), signature2Bytes()); +export const credential = () => new Credential([signature(), signature2()]); diff --git a/src/fixtures/transactions.ts b/src/fixtures/transactions.ts new file mode 100644 index 000000000..8d755e95f --- /dev/null +++ b/src/fixtures/transactions.ts @@ -0,0 +1,192 @@ +import { Output } from '../serializable/evm'; +import { + BaseTx, + TransferableInput, + TransferableOutput, + UTXOID, +} from '../serializable/avax'; +import { Utxo } from '../serializable/avax/utxo'; +import { Address, Id } from '../serializable/fxs/common'; +import { + OutputOwners, + TransferInput, + TransferOutput, +} from '../serializable/fxs/secp256k1'; +import { BigIntPr, Int, Bytes } from '../serializable/primitives'; +import { StakeableLockIn, StakeableLockOut } from '../serializable/pvm'; +import { hexToBuffer } from '../utils'; +import { testContext } from './context'; +import { stringToBytes } from '@scure/base'; + +export const cAddressForTest = '0xfd4DFC8f567caD8a275989982c5f8f1fC82B7563'; +export const privateKeyForTest = + '4ec512bf0130a604b68b80446238f20ccd94eec8588f56c5e5c499f1d0d7e7cd'; +export const xAddressForTest = 'X-fuji1w5jg0xyw2zq22nhpjar834gyeksc6wuleftqzg'; +export const pAddressForTest = 'P-fuji1w5jg0xyw2zq22nhpjar834gyeksc6wuleftqzg'; +export const cAddressBech32ForTest = + 'C-fuji1w5jg0xyw2zq22nhpjar834gyeksc6wuleftqzg'; + +export const testAvaxAssetID = Id.fromString(testContext.avaxAssetID); +export const testOwnerXAddress = Address.fromString(xAddressForTest); +export const testOwnerCBech32Address = Address.fromString( + cAddressBech32ForTest, +); + +export const testUTXOID1 = Id.fromHex( + '0x009e71412d5b89d0b51e679a93cf59966c3c89346949f1976f930feddbfd765d', +); +export const testUTXOID2 = Id.fromHex( + '0xd1f6526c4233a5af42b0c8311a9824a84f73b3e32ba637aaa7d9dd4994bccbad', +); +export const testUTXOID3 = Id.fromHex( + '0x5199944d5f58272adff87558c5c0857d3de3be01da518431523bff2bbf1117e6', +); +export const testUTXOID4 = Id.fromHex( + '0x5199944d5f58272adff87558c5c0857d3de3be01da518431523bff2bbf1116e6', +); + +export const testSubnetId = + '0x8c86d07cd60218661863e0116552dccd5bd84c564bd29d7181dbddd5ec616104'; + +export const testVMId = + '0x61766d0000000000000000000000000000000000000000000000000000000000'; + +export const testGenesisData = { + test: 'data', +}; + +export const testSubnetAuthData = new Bytes( + stringToBytes('utf8', '0x0000000a0000000100000000'), +); + +export const getLockedUTXO = ( + amt = new BigIntPr(BigInt(30 * 1e9)), + lockTime = BigInt(Math.floor(new Date().getTime() / 1000)) + 100000n, +) => + new Utxo( + new UTXOID(testUTXOID1, new Int(0)), + testAvaxAssetID, + new TransferOutput( + amt, + OutputOwners.fromNative([testOwnerXAddress.toBytes()], lockTime), + ), + ); + +export const getNotTransferOutput = (amt = BigInt(30 * 1e9)) => + new Utxo( + new UTXOID(testUTXOID2, new Int(0)), + testAvaxAssetID, + new StakeableLockIn( + new BigIntPr(2000000000n), + TransferableOutput.fromNative(testAvaxAssetID.toString(), amt, [ + hexToBuffer('0x12345678901234578901234567890123457890'), + ]), + ), + ); + +export const getStakeableLockoutOutput = ( + id: Id, + amt: bigint, + lockTime: bigint = BigInt(Math.floor(new Date().getTime() / 1000)) + 100000n, + assetId = testAvaxAssetID, +) => + new Utxo( + new UTXOID(id, new Int(0)), + assetId, + new StakeableLockOut( + new BigIntPr(lockTime), + new TransferOutput( + new BigIntPr(amt), + OutputOwners.fromNative([testOwnerXAddress.toBytes()]), + ), + ), + ); + +export const getTransferableInputForTest = (amt = 50000000000n) => + TransferableInput.fromNative( + 'cwMuSYz3XjaKNwwC7tDmzyWg2eNgpEtkeKwabZ4QJD9PDsjni', + 0, + testContext.avaxAssetID, + amt, + [0], + ); + +export const getStakeableLockedTransferableInputForTest = ( + amtount: bigint, + lockTime: bigint, +) => + new TransferableInput( + new UTXOID(testUTXOID1, new Int(0)), + Id.fromString(testContext.avaxAssetID), + new StakeableLockIn( + new BigIntPr(lockTime), + TransferInput.fromNative(amtount, [0]), + ), + ); + +export const getValidUtxo = ( + amt = new BigIntPr(BigInt(50 * 1e9)), + assetId = testAvaxAssetID, +) => + new Utxo( + new UTXOID(testUTXOID3, new Int(0)), + assetId, + new TransferOutput( + amt, + OutputOwners.fromNative([testOwnerXAddress.toBytes()]), + ), + ); + +export const fromAddressBytes = [testOwnerXAddress.toBytes()]; + +export const getTransferableOutForTest = ( + amount: bigint, + locktime?: bigint, + threshold?: number, +) => { + return TransferableOutput.fromNative( + testContext.avaxAssetID, + amount, + fromAddressBytes, + locktime, + threshold, + ); +}; + +export const getStakeableLockedTransferableOutForTest = ( + amount: bigint, + lockTime: bigint, +) => { + return new TransferableOutput( + Id.fromString(testContext.avaxAssetID), + new StakeableLockOut( + new BigIntPr(lockTime), + new TransferOutput( + new BigIntPr(amount), + OutputOwners.fromNative([testOwnerXAddress.toBytes()]), + ), + ), + ); +}; + +export const testUtxos = () => [ + getLockedUTXO(), + getNotTransferOutput(), + getValidUtxo(), +]; + +export const getBaseTxForTest = (changeAmount: bigint, blockchainId: string) => + BaseTx.fromNative( + testContext.networkID, + blockchainId, + [getTransferableOutForTest(changeAmount)], + [getTransferableInputForTest()], + new Uint8Array(), + ); + +export const getOutputForTest = () => + new Output( + testOwnerXAddress, + new BigIntPr(BigInt(0.1 * 1e9)), + Id.fromString(testContext.avaxAssetID), + ); diff --git a/src/fixtures/utils/bytesFor.ts b/src/fixtures/utils/bytesFor.ts new file mode 100644 index 000000000..4f390d140 --- /dev/null +++ b/src/fixtures/utils/bytesFor.ts @@ -0,0 +1,3 @@ +import { Int } from '../../serializable/primitives/int'; + +export const bytesForInt = (num: number): Uint8Array => new Int(num).toBytes(); diff --git a/src/fixtures/utils/expectTx.ts b/src/fixtures/utils/expectTx.ts new file mode 100644 index 000000000..c783b7543 --- /dev/null +++ b/src/fixtures/utils/expectTx.ts @@ -0,0 +1,5 @@ +export const expectTxs = (result: any, expected: any) => { + expect(JSON.stringify(result, null, 2)).toEqual( + JSON.stringify(expected, null, 2), + ); +}; diff --git a/src/fixtures/utils/makeList.spec.ts b/src/fixtures/utils/makeList.spec.ts new file mode 100644 index 000000000..cf8b8cc52 --- /dev/null +++ b/src/fixtures/utils/makeList.spec.ts @@ -0,0 +1,16 @@ +import { concatBytes } from '../../utils/buffer'; +import { address, addressBytes } from '../common'; +import { bytesForInt } from './bytesFor'; +import { makeList, makeListBytes } from './makeList'; + +describe('makeList', () => { + it('make lists', () => { + expect(makeList(address)()).toEqual([address(), address()]); + }); + + it('make lists bytes', () => { + expect(makeListBytes(addressBytes)()).toEqual( + concatBytes(bytesForInt(2), addressBytes(), addressBytes()), + ); + }); +}); diff --git a/src/fixtures/utils/makeList.ts b/src/fixtures/utils/makeList.ts new file mode 100644 index 000000000..02b08e45a --- /dev/null +++ b/src/fixtures/utils/makeList.ts @@ -0,0 +1,11 @@ +import { concatBytes } from '../../utils/buffer'; +import type { Serializable } from '../../serializable/common/types'; +import { bytesForInt } from './bytesFor'; + +export const makeList = + (single: () => T) => + (): T[] => + [single(), single()]; + +export const makeListBytes = (single: () => Uint8Array) => () => + concatBytes(bytesForInt(2), single(), single()); diff --git a/src/fixtures/utils/serializable.ts b/src/fixtures/utils/serializable.ts new file mode 100644 index 000000000..0a6115a45 --- /dev/null +++ b/src/fixtures/utils/serializable.ts @@ -0,0 +1,28 @@ +import type { Codec } from '../../serializable/codec'; +import type { + Serializable, + SerializableStatic, +} from '../../serializable/common/types'; +import { testCodec } from '../codec'; + +export const testSerialization = ( + name: string, + entity: SerializableStatic, + entityFixture: () => Serializable, + bytesFixture: () => Uint8Array, + codec: () => Codec = testCodec, +) => { + describe(name, () => { + it('deserializes correctly', () => { + const [output, remainder] = entity.fromBytes(bytesFixture(), codec()); + expect(JSON.stringify(output)).toBe(JSON.stringify(entityFixture())); + expect(remainder).toStrictEqual(new Uint8Array()); + }); + }); + + describe(name, () => { + it('serializes correctly', () => { + expect(entityFixture().toBytes(codec())).toStrictEqual(bytesFixture()); + }); + }); +}; diff --git a/src/fixtures/utils/typeguards.ts b/src/fixtures/utils/typeguards.ts new file mode 100644 index 000000000..8e62a3f47 --- /dev/null +++ b/src/fixtures/utils/typeguards.ts @@ -0,0 +1,13 @@ +export type TypeChecker = (object: any) => boolean; + +export function checkAllGuards(object: any, guards: TypeChecker[]) { + return guards.map((checker) => checker(object)); +} + +export function countGuardPasses(object: any, guards: TypeChecker[]) { + return checkAllGuards(object, guards).filter((val) => val).length; +} + +export function onlyChecksOneGuard(object: any, guards: TypeChecker[]) { + return countGuardPasses(object, guards) === 1; +} diff --git a/src/fixtures/vms.ts b/src/fixtures/vms.ts new file mode 100644 index 000000000..017bdb7dd --- /dev/null +++ b/src/fixtures/vms.ts @@ -0,0 +1,20 @@ +import { + getPublicKey, + hexToBuffer, + publicKeyBytesToAddress, + publicKeyToEthAddress, +} from '../utils'; + +export const testPrivateKey1 = hexToBuffer( + '9c0523e7611e62f5dca291ad335e950db076c5ee31c4107355abde0d357bbd29', +); +export const testPublicKey1 = getPublicKey(testPrivateKey1); +export const testAddress1 = publicKeyBytesToAddress(testPublicKey1); +export const testEthAddress1 = publicKeyToEthAddress(testPublicKey1); + +export const testPrivateKey2 = hexToBuffer( + 'd11e7aa633eb15682bc2456d399c2a9861c82e0a308dbfd4d3a51ffa972f2b62', +); +export const testPublicKey2 = getPublicKey(testPrivateKey2); +export const testAddress2 = publicKeyBytesToAddress(testPublicKey2); +export const testEthAddress2 = publicKeyToEthAddress(testPublicKey2); diff --git a/src/index.ts b/src/index.ts index b48a73843..73523cc69 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,191 +1,8 @@ -/** - * @packageDocumentation - * @module Avalanche - */ -import AvalancheCore from "./avalanche" -import { AdminAPI } from "./apis/admin/api" -import { AuthAPI } from "./apis/auth/api" -import { AVMAPI } from "./apis/avm/api" -import { EVMAPI } from "./apis/evm/api" -import { GenesisAsset } from "./apis/avm/genesisasset" -import { GenesisData } from "./apis/avm/genesisdata" -import { HealthAPI } from "./apis/health/api" -import { IndexAPI } from "./apis/index/api" -import { InfoAPI } from "./apis/info/api" -import { KeystoreAPI } from "./apis/keystore/api" -import { MetricsAPI } from "./apis/metrics/api" -import { PlatformVMAPI } from "./apis/platformvm/api" -import { Socket } from "./apis/socket/socket" -import { DefaultNetworkID, Defaults } from "./utils/constants" -import { getPreferredHRP } from "./utils/helperfunctions" -import BinTools from "./utils/bintools" -import DB from "./utils/db" -import Mnemonic from "./utils/mnemonic" -import PubSub from "./utils/pubsub" -import HDNode from "./utils/hdnode" -import BN from "bn.js" -import { Buffer } from "buffer/" - -/** - * AvalancheJS is middleware for interacting with Avalanche node RPC APIs. - * - * Example usage: - * ```js - * const avalanche: Avalanche = new Avalanche("127.0.0.1", 9650, "https") - * ``` - * - */ -export default class Avalanche extends AvalancheCore { - /** - * Returns a reference to the Admin RPC. - */ - Admin = () => this.apis.admin as AdminAPI - - /** - * Returns a reference to the Auth RPC. - */ - Auth = () => this.apis.auth as AuthAPI - - /** - * Returns a reference to the EVMAPI RPC pointed at the C-Chain. - */ - CChain = () => this.apis.cchain as EVMAPI - - /** - * Returns a reference to the AVM RPC pointed at the X-Chain. - */ - XChain = () => this.apis.xchain as AVMAPI - - /** - * Returns a reference to the Health RPC for a node. - */ - Health = () => this.apis.health as HealthAPI - - /** - * Returns a reference to the Index RPC for a node. - */ - Index = () => this.apis.index as IndexAPI - - /** - * Returns a reference to the Info RPC for a node. - */ - Info = () => this.apis.info as InfoAPI - - /** - * Returns a reference to the Metrics RPC. - */ - Metrics = () => this.apis.metrics as MetricsAPI - - /** - * Returns a reference to the Keystore RPC for a node. We label it "NodeKeys" to reduce - * confusion about what it's accessing. - */ - NodeKeys = () => this.apis.keystore as KeystoreAPI - - /** - * Returns a reference to the PlatformVM RPC pointed at the P-Chain. - */ - PChain = () => this.apis.pchain as PlatformVMAPI - - /** - * Creates a new Avalanche instance. Sets the address and port of the main Avalanche Client. - * - * @param host The hostname to resolve to reach the Avalanche Client RPC APIs - * @param port The port to resolve to reach the Avalanche Client RPC APIs - * @param protocol The protocol string to use before a "://" in a request, - * ex: "http", "https", "git", "ws", etc. Defaults to http - * @param networkID Sets the NetworkID of the class. Default [[DefaultNetworkID]] - * @param XChainID Sets the blockchainID for the AVM. Will try to auto-detect, - * otherwise default "2eNy1mUFdmaxXNj1eQHUe7Np4gju9sJsEtWQ4MX3ToiNKuADed" - * @param CChainID Sets the blockchainID for the EVM. Will try to auto-detect, - * otherwise default "2CA6j5zYzasynPsFeNoqWkmTCt3VScMvXUZHbfDJ8k3oGzAPtU" - * @param hrp The human-readable part of the bech32 addresses - * @param skipinit Skips creating the APIs. Defaults to false - */ - constructor( - host?: string, - port?: number, - protocol: string = "http", - networkID: number = DefaultNetworkID, - XChainID: string = undefined, - CChainID: string = undefined, - hrp: string = undefined, - skipinit: boolean = false - ) { - super(host, port, protocol) - let xchainid: string = XChainID - let cchainid: string = CChainID - - if ( - typeof XChainID === "undefined" || - !XChainID || - XChainID.toLowerCase() === "x" - ) { - if (networkID.toString() in Defaults.network) { - xchainid = Defaults.network[`${networkID}`].X.blockchainID - } else { - xchainid = Defaults.network[12345].X.blockchainID - } - } - if ( - typeof CChainID === "undefined" || - !CChainID || - CChainID.toLowerCase() === "c" - ) { - if (networkID.toString() in Defaults.network) { - cchainid = Defaults.network[`${networkID}`].C.blockchainID - } else { - cchainid = Defaults.network[12345].C.blockchainID - } - } - if (typeof networkID === "number" && networkID >= 0) { - this.networkID = networkID - } else if (typeof networkID === "undefined") { - networkID = DefaultNetworkID - } - if (typeof hrp !== "undefined") { - this.hrp = hrp - } else { - this.hrp = getPreferredHRP(this.networkID) - } - - if (!skipinit) { - this.addAPI("admin", AdminAPI) - this.addAPI("auth", AuthAPI) - this.addAPI("xchain", AVMAPI, "/ext/bc/X", xchainid) - this.addAPI("cchain", EVMAPI, "/ext/bc/C/avax", cchainid) - this.addAPI("health", HealthAPI) - this.addAPI("info", InfoAPI) - this.addAPI("index", IndexAPI) - this.addAPI("keystore", KeystoreAPI) - this.addAPI("metrics", MetricsAPI) - this.addAPI("pchain", PlatformVMAPI) - } - } -} - -export { Avalanche } -export { AvalancheCore } -export { BinTools } -export { BN } -export { Buffer } -export { DB } -export { HDNode } -export { GenesisAsset } -export { GenesisData } -export { Mnemonic } -export { PubSub } -export { Socket } - -export * as admin from "./apis/admin" -export * as auth from "./apis/auth" -export * as avm from "./apis/avm" -export * as common from "./common" -export * as evm from "./apis/evm" -export * as health from "./apis/health" -export * as index from "./apis/index" -export * as info from "./apis/info" -export * as keystore from "./apis/keystore" -export * as metrics from "./apis/metrics" -export * as platformvm from "./apis/platformvm" -export * as utils from "./utils" +export * as networkIDs from './constants/networkIDs'; +export * from './serializable'; +export { Utxo } from './serializable/avax/utxo'; +export * from './signer'; +export * from './utils'; +export * as utils from './utils'; +export * from './vms'; +export { Info } from './info/info'; diff --git a/src/info/info.ts b/src/info/info.ts new file mode 100644 index 000000000..45f3f1580 --- /dev/null +++ b/src/info/info.ts @@ -0,0 +1,78 @@ +import { AVAX_PUBLIC_URL } from '../constants/public-urls'; +import { Api } from '../vms/common/baseApi'; +import type { + GetBlockchainIDResponse, + GetNetworkIdResponse, + GetNetworkNameResponse, + GetNodeIdResponse, + GetNodeIpResponse, + GetNodeVersionReply, + GetPeersResponse, + GetTxFeeResponse, + isBootstrapped, + UptimeResponse, +} from './model'; + +export class Info extends Api { + constructor(private readonly baseURL: string = AVAX_PUBLIC_URL) { + super(baseURL, '/ext/info', 'info'); + } + + getNodeVersion(): Promise { + return this.callRpc('getNodeVersion'); + } + + async getNodeId(): Promise { + return this.callRpc('getNodeID'); + } + + getNodeIp(): Promise { + return this.callRpc('getNodeIP'); + } + + getNetworkId(): Promise { + return this.callRpc('getNetworkID'); + } + + getNetworkName(): Promise { + return this.callRpc('getNetworkName'); + } + + getBlockchainId(alias: string): Promise { + return this.callRpc('getBlockchainID', { alias }); + } + + peers(nodeIDs?: string[]): Promise { + return this.callRpc('peers', { nodeIDs }); + } + + isBootstrapped(chain: string): Promise { + return this.callRpc('peers', { chain }); + } + /** + * @link https://docs.avax.network/apis/avalanchego/apis/info#infogettxfee + */ + async getTxFee(): Promise { + const resp = await this.callRpc('getTxFee'); + + return { + txFee: BigInt(resp.txFee), + createAssetTxFee: BigInt(resp.createAssetTxFee), + createSubnetTxFee: BigInt(resp.createSubnetTxFee), + transformSubnetTxFee: BigInt(resp.transformSubnetTxFee), + createBlockchainTxFee: BigInt(resp.createBlockchainTxFee), + addPrimaryNetworkValidatorFee: BigInt(resp.addPrimaryNetworkValidatorFee), + addPrimaryNetworkDelegatorFee: BigInt(resp.addPrimaryNetworkDelegatorFee), + addSubnetValidatorFee: BigInt(resp.addSubnetValidatorFee), + addSubnetDelegatorFee: BigInt(resp.addSubnetDelegatorFee), + }; + } + + uptime(): Promise { + return this.callRpc('uptime'); + } + + getVMs(): Promise> { + return this.callRpc>('getVMs'); + } +} diff --git a/src/info/model.ts b/src/info/model.ts new file mode 100644 index 000000000..361dbdd41 --- /dev/null +++ b/src/info/model.ts @@ -0,0 +1,71 @@ +export type GetNodeVersionReply = { + version: string; + databaseVersion: string; + gitCommit: string; + vmVersions: Map; +}; + +export type Peer = { + ip: string; + publicIp: string; + nodeID: string; + version: string; + lastSent: string; + lastReceived: string; + observedUptime: number; + benched: string[]; +}; + +export type GetPeersResponse = { + numPeers: number; + peers: Peer[]; +}; + +export type GetTxFeeApiResponse = { + txFee: string; + creationTxFee: string; + createAssetTxFee: string; + createSubnetTxFee: string; + createBlockchainTxFee: string; +}; + +export type GetTxFeeResponse = { + txFee: bigint; + createAssetTxFee: bigint; + createSubnetTxFee: bigint; + transformSubnetTxFee: bigint; + createBlockchainTxFee: bigint; + addPrimaryNetworkValidatorFee: bigint; + addPrimaryNetworkDelegatorFee: bigint; + addSubnetValidatorFee: bigint; + addSubnetDelegatorFee: bigint; +}; + +export type UptimeResponse = { + rewardingStakePercentage: string; + weightedAveragePercentage: string; +}; + +export type GetNodeIdResponse = { + nodeID: string; +}; + +export type GetNodeIpResponse = { + ip: string; +}; + +export type GetNetworkIdResponse = { + networkID: number; +}; + +export type GetNetworkNameResponse = { + networkName: string; +}; + +export type GetBlockchainIDResponse = { + blockchainID: string; +}; + +export type isBootstrapped = { + isBootstrapped: boolean; +}; diff --git a/src/serializable/avax/avaxTx.ts b/src/serializable/avax/avaxTx.ts new file mode 100644 index 000000000..48d24a690 --- /dev/null +++ b/src/serializable/avax/avaxTx.ts @@ -0,0 +1,22 @@ +import { Transaction } from '../../vms/common/transaction'; +import type { BaseTx } from './baseTx'; +import type { TransferableInput } from './transferableInput'; + +export abstract class AvaxTx extends Transaction { + abstract baseTx?: BaseTx; + + getInputs(): TransferableInput[] { + return this.baseTx?.inputs ?? []; + } + getBlockchainId() { + return this.baseTx?.BlockchainId.toString() ?? ''; + } + + getSigIndices(): number[][] { + return this.getInputs() + .map((input) => { + return input.sigIndicies(); + }) + .filter((indicies): indicies is number[] => indicies !== undefined); + } +} diff --git a/src/serializable/avax/baseTx.spec.ts b/src/serializable/avax/baseTx.spec.ts new file mode 100644 index 000000000..d77f08da8 --- /dev/null +++ b/src/serializable/avax/baseTx.spec.ts @@ -0,0 +1,5 @@ +import { baseTx, baseTxbytes } from '../../fixtures/avax'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { BaseTx } from './baseTx'; + +testSerialization('BaseTx', BaseTx, baseTx, baseTxbytes); diff --git a/src/serializable/avax/baseTx.ts b/src/serializable/avax/baseTx.ts new file mode 100644 index 000000000..ceab6d8ea --- /dev/null +++ b/src/serializable/avax/baseTx.ts @@ -0,0 +1,69 @@ +import { concatBytes } from '../../utils/buffer'; +import { packList, toListStruct } from '../../utils/serializeList'; +import { pack, unpack } from '../../utils/struct'; +import type { Codec } from '../codec/codec'; +import { serializable } from '../common/types'; +import { Id } from '../fxs/common/id'; +import { Bytes, Int } from '../primitives'; +import { TransferableInput } from './transferableInput'; +import { TransferableOutput } from './transferableOutput'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://docs.avax.network/specs/avm-transaction-serialization#unsigned-basetx + */ +@serializable() +export class BaseTx { + _type = TypeSymbols.BaseTx; + + constructor( + public readonly NetworkId: Int, + public readonly BlockchainId: Id, + public readonly outputs: TransferableOutput[], + public readonly inputs: TransferableInput[], + public readonly memo: Bytes, + ) {} + + static fromBytes(bytes: Uint8Array, codec: Codec): [BaseTx, Uint8Array] { + const [networkId, blockchainId, outputs, inputs, memo, remaining] = unpack( + bytes, + [ + Int, + Id, + toListStruct(TransferableOutput), + toListStruct(TransferableInput), + Bytes, + ], + codec, + ); + return [ + new BaseTx(networkId, blockchainId, outputs, inputs, memo), + remaining, + ]; + } + + static fromNative( + networkId: number, + blockchainId: string, + outputs: TransferableOutput[], + inputs: TransferableInput[], + memo: Uint8Array, + ) { + return new BaseTx( + new Int(networkId), + Id.fromString(blockchainId), + outputs, + inputs, + new Bytes(memo), + ); + } + + toBytes(codec) { + return concatBytes( + pack([this.NetworkId, this.BlockchainId], codec), + packList(this.outputs, codec), + packList(this.inputs, codec), + this.memo.toBytes(), + ); + } +} diff --git a/src/serializable/avax/index.ts b/src/serializable/avax/index.ts new file mode 100644 index 000000000..60146941e --- /dev/null +++ b/src/serializable/avax/index.ts @@ -0,0 +1,7 @@ +export { AvaxTx } from './avaxTx'; +export { BaseTx } from './baseTx'; +export * from './signedTx'; +export { TransferableInput } from './transferableInput'; +export { TransferableOutput } from './transferableOutput'; +export * from './typeGuards'; +export { UTXOID } from './utxoId'; diff --git a/src/serializable/avax/signedTx.spec.ts b/src/serializable/avax/signedTx.spec.ts new file mode 100644 index 000000000..30ad8a1fd --- /dev/null +++ b/src/serializable/avax/signedTx.spec.ts @@ -0,0 +1,16 @@ +import { signedTx, signedTxBytes } from '../../fixtures/avax'; +import { getAVMManager } from '../avm/codec'; +import { SignedTx } from './signedTx'; + +describe('SignedTx', () => { + it('deserializes correctly', () => { + const output = getAVMManager().unpack(signedTxBytes(), SignedTx); + expect(JSON.stringify(output)).toBe(JSON.stringify(signedTx())); + }); +}); + +describe('SignedTx', () => { + it('serializes correctly', () => { + expect(signedTx().toBytes()).toStrictEqual(signedTxBytes()); + }); +}); diff --git a/src/serializable/avax/signedTx.ts b/src/serializable/avax/signedTx.ts new file mode 100644 index 000000000..231744956 --- /dev/null +++ b/src/serializable/avax/signedTx.ts @@ -0,0 +1,51 @@ +import { concatBytes } from '@noble/hashes/utils'; +import { DEFAULT_CODEC_VERSION } from '../../constants/codec'; +import { getDefaultCodecFromTx } from '../../utils/packTx'; +import { toListStruct } from '../../utils/serializeList'; +import { unpack } from '../../utils/struct'; +import type { Transaction } from '../../vms/common/transaction'; +import { Codec } from '../codec/codec'; +import type { Serializable } from '../common/types'; +import { serializable } from '../common/types'; +import type { Credential } from '../fxs/secp256k1'; +import { Short } from '../primitives'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://docs.avax.network/specs/avm-transaction-serialization#unsigned-Exporttx + */ +@serializable() +export class SignedTx { + _type = TypeSymbols.AvmSignedTx; + + constructor( + public readonly unsignedTx: Transaction, + public readonly credentials: Serializable[], + ) {} + + static fromBytes(bytes: Uint8Array, codec: Codec): [SignedTx, Uint8Array] { + const [unsignedTx, outs, remaining] = unpack( + bytes, + [Codec, toListStruct(Codec)], + codec, + ); + return [new SignedTx(unsignedTx as Transaction, outs), remaining]; + } + + getCredentials(): Credential[] { + return this.credentials as Credential[]; + } + + getAllSignatures() { + return this.getCredentials().flatMap((cred) => cred.getSignatures()); + } + + toBytes() { + const codec = getDefaultCodecFromTx(this.unsignedTx); + return concatBytes( + new Short(DEFAULT_CODEC_VERSION).toBytes(), + codec.PackPrefix(this.unsignedTx), + codec.PackPrefixList(this.credentials), + ); + } +} diff --git a/src/serializable/avax/transferableInput.spec.ts b/src/serializable/avax/transferableInput.spec.ts new file mode 100644 index 000000000..0fe425acb --- /dev/null +++ b/src/serializable/avax/transferableInput.spec.ts @@ -0,0 +1,196 @@ +import { TransferableInput } from '.'; +import { + transferableInput, + transferableInputBytes, + utxoId, +} from '../../fixtures/avax'; +import { id } from '../../fixtures/common'; +import { bigIntPr } from '../../fixtures/primitives'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { Input, TransferInput } from '../fxs/secp256k1'; +import { StakeableLockIn } from '../pvm'; + +testSerialization( + 'TransferableInput', + TransferableInput, + transferableInput, + transferableInputBytes, +); + +describe('TransferableInput sorting', () => { + it('sorts correctly', () => { + const inputs = [ + { + utxoID: { + txID: '2iCGnbjjeZQhqq5jcjqJg4ZxgAbYy92HZtUyPY7abXGwiMvxSg', + outputIdx: 0, + }, + assetId: 'FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z', + input: { + amt: { + bigint: '2000000000', + }, + input: { + sigIndices: [0], + }, + }, + }, + { + utxoID: { + txID: '2MpCHQEVzMS5AhyXLJxmLT5SoiTV1GxVFBhVxkPXbuoHEKva9Z', + outputIdx: 0, + }, + assetId: 'FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z', + input: { + amt: { + bigint: '10000000', + }, + input: { + sigIndices: [0], + }, + }, + }, + { + utxoID: { + txID: '2p2cZ6pnszaQjrCYVisq432aQZFnhXsMdtSn3L5azUUAXw4ZRE', + outputIdx: 0, + }, + assetId: 'FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z', + input: { + amt: { + bigint: '97000000', + }, + input: { + sigIndices: [0], + }, + }, + }, + { + utxoID: { + txID: 'nrZ6vSw6fU8K6WTPeBJBXoTU8rcbViVbPi45ZW4yLtD6v3K6y', + outputIdx: 0, + }, + assetId: 'FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z', + input: { + amt: { + bigint: '1971075188', + }, + input: { + sigIndices: [0], + }, + }, + }, + ]; + const inputTransferableInputs = inputs.map((inp) => + TransferableInput.fromNative( + inp.utxoID.txID, + inp.utxoID.outputIdx, + inp.assetId, + BigInt(inp.input.amt.bigint), + inp.input.input.sigIndices, + ), + ); + + const expected = [ + { + utxoID: { + txID: 'nrZ6vSw6fU8K6WTPeBJBXoTU8rcbViVbPi45ZW4yLtD6v3K6y', + outputIdx: 0, + }, + assetId: 'FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z', + input: { + amt: { + bigint: '1971075188', + }, + input: { + sigIndices: [0], + }, + }, + }, + { + utxoID: { + txID: '2MpCHQEVzMS5AhyXLJxmLT5SoiTV1GxVFBhVxkPXbuoHEKva9Z', + outputIdx: 0, + }, + assetId: 'FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z', + input: { + amt: { + bigint: '10000000', + }, + input: { + sigIndices: [0], + }, + }, + }, + { + utxoID: { + txID: '2iCGnbjjeZQhqq5jcjqJg4ZxgAbYy92HZtUyPY7abXGwiMvxSg', + outputIdx: 0, + }, + assetId: 'FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z', + input: { + amt: { + bigint: '2000000000', + }, + input: { + sigIndices: [0], + }, + }, + }, + { + utxoID: { + txID: '2p2cZ6pnszaQjrCYVisq432aQZFnhXsMdtSn3L5azUUAXw4ZRE', + outputIdx: 0, + }, + assetId: 'FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z', + input: { + amt: { + bigint: '97000000', + }, + input: { + sigIndices: [0], + }, + }, + }, + ]; + + const expectedTransferableInputs = expected.map((inp) => + TransferableInput.fromNative( + inp.utxoID.txID, + inp.utxoID.outputIdx, + inp.assetId, + BigInt(inp.input.amt.bigint), + inp.input.input.sigIndices, + ), + ); + + inputTransferableInputs.sort(TransferableInput.compare); + + expect(inputTransferableInputs).toStrictEqual(expectedTransferableInputs); + }); +}); + +describe('sigindicies', () => { + it('gets sigindicies for transferinput', () => { + const transferableInputWithTransferInput = new TransferableInput( + utxoId(), + id(), + new TransferInput(bigIntPr(), Input.fromNative([0, 1])), + ); + + expect(transferableInputWithTransferInput.sigIndicies()).toEqual([0, 1]); + }); + + it('gets sigindicies for stakeableLockIn', () => { + const transferableInputWithTransferInput = new TransferableInput( + utxoId(), + id(), + new StakeableLockIn( + bigIntPr(), + new TransferInput(bigIntPr(), Input.fromNative([0, 1])), + ), + ); + + expect(transferableInputWithTransferInput.sigIndicies()).toEqual([0, 1]); + }); +}); diff --git a/src/serializable/avax/transferableInput.ts b/src/serializable/avax/transferableInput.ts new file mode 100644 index 000000000..12f8ac198 --- /dev/null +++ b/src/serializable/avax/transferableInput.ts @@ -0,0 +1,108 @@ +import { concatBytes } from '../../utils/buffer'; +import { pack, unpack } from '../../utils/struct'; +import { + isStakeableLockIn, + isTransferInput, + isTransferOut, +} from '../../utils/typeGuards'; +import type { Codec } from '../codec/codec'; +import type { Amounter } from '../common/types'; +import { serializable } from '../common/types'; +import { Id } from '../fxs/common/id'; +import { Input, TransferInput } from '../fxs/secp256k1'; +import { BigIntPr, Int } from '../primitives'; +import type { Utxo } from './utxo'; +import { UTXOID } from './utxoId'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://github.com/ava-labs/avalanchego/blob/master/vms/components/avax/transferables.go + * @see https://docs.avax.network/specs/coreth-atomic-transaction-serialization#transferable-input + * @see https://docs.avax.network/specs/avm-transaction-serialization#transferable-input + * @see https://docs.avax.network/specs/platform-transaction-serialization#transferable-input + */ +@serializable() +export class TransferableInput { + _type = TypeSymbols.TransferableInput; + + constructor( + public readonly utxoID: UTXOID, + public readonly assetId: Id, + public readonly input: Amounter, + ) {} + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [TransferableInput, Uint8Array] { + const [utxoID, assetId, remaining] = unpack(bytes, [UTXOID, Id]); + const [input, rest] = codec.UnpackPrefix(remaining); + + return [new TransferableInput(utxoID, assetId, input), rest]; + } + + static fromNative( + utxoId: string, + outputIdx: number, + assetId: string, + amount: bigint, + sigIndices: number[], + ) { + return new TransferableInput( + UTXOID.fromNative(utxoId, outputIdx), + Id.fromString(assetId), + new TransferInput( + new BigIntPr(amount), + new Input(sigIndices.map((num) => new Int(num))), + ), + ); + } + + static fromUtxoAndSigindicies(utxo: Utxo, sigIndicies: number[]) { + const out = utxo.output; + if (!isTransferOut(out)) { + throw new Error('utxo.output must be Transferout'); + } + + return new TransferableInput( + utxo.utxoId, + utxo.assetId, + TransferInput.fromNative(out.amount(), sigIndicies), + ); + } + + sigIndicies() { + const input = this.input; + + if (isTransferInput(input)) { + return input.sigIndicies(); + } + if (isStakeableLockIn(input)) { + const lockedInput = input.transferableInput; + + if (isTransferInput(lockedInput)) { + return lockedInput.sigIndicies(); + } + } + throw new Error('Input must be TransferInput or StakeableLockIn'); + } + + static compare(input1: TransferableInput, input2: TransferableInput): number { + return UTXOID.compare(input1.utxoID, input2.utxoID); + } + + amount() { + return this.input.amount(); + } + + getAssetId() { + return this.assetId.toString(); + } + + toBytes(codec: Codec) { + return concatBytes( + pack([this.utxoID, this.assetId], codec), + codec.PackPrefix(this.input), + ); + } +} diff --git a/src/serializable/avax/transferableOp.spec.ts b/src/serializable/avax/transferableOp.spec.ts new file mode 100644 index 000000000..9cdfcbd64 --- /dev/null +++ b/src/serializable/avax/transferableOp.spec.ts @@ -0,0 +1,10 @@ +import { transferableOp, transferableOpBytes } from '../../fixtures/avax'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { TransferableOp } from './transferableOp'; + +testSerialization( + 'TransferableOp', + TransferableOp, + transferableOp, + transferableOpBytes, +); diff --git a/src/serializable/avax/transferableOp.ts b/src/serializable/avax/transferableOp.ts new file mode 100644 index 000000000..bf23e4f31 --- /dev/null +++ b/src/serializable/avax/transferableOp.ts @@ -0,0 +1,44 @@ +import { concatBytes } from '../../utils/buffer'; +import { packList, toListStruct } from '../../utils/serializeList'; +import { pack, unpack } from '../../utils/struct'; +import { Codec } from '../codec/codec'; +import type { Serializable } from '../common/types'; +import { serializable } from '../common/types'; +import { Id } from '../fxs/common/id'; +import { UTXOID } from './utxoId'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://docs.avax.network/specs/avm-transaction-serialization#transferable-op + */ +@serializable() +export class TransferableOp { + _type = TypeSymbols.TransferableOp; + + constructor( + private readonly assetId: Id, + private readonly UTXOId: UTXOID[], + private readonly transferOp: Serializable, + ) {} + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [TransferableOp, Uint8Array] { + const [assetId, utxoID, transferOp, remaining] = unpack( + bytes, + [Id, toListStruct(UTXOID), Codec], + codec, + ); + + return [new TransferableOp(assetId, utxoID, transferOp), remaining]; + } + + toBytes(codec: Codec) { + return concatBytes( + pack([this.assetId], codec), + packList(this.UTXOId, codec), + codec.PackPrefix(this.transferOp), + ); + } +} diff --git a/src/serializable/avax/transferableOutput.spec.ts b/src/serializable/avax/transferableOutput.spec.ts new file mode 100644 index 000000000..dbb98c6e2 --- /dev/null +++ b/src/serializable/avax/transferableOutput.spec.ts @@ -0,0 +1,13 @@ +import { + transferableOutput, + transferableOutputBytes, +} from '../../fixtures/avax'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { TransferableOutput } from './transferableOutput'; + +testSerialization( + 'TransferableInput', + TransferableOutput, + transferableOutput, + transferableOutputBytes, +); diff --git a/src/serializable/avax/transferableOutput.ts b/src/serializable/avax/transferableOutput.ts new file mode 100644 index 000000000..191efd959 --- /dev/null +++ b/src/serializable/avax/transferableOutput.ts @@ -0,0 +1,62 @@ +import { concatBytes } from '../../utils/buffer'; +import { pack, unpack } from '../../utils/struct'; +import type { Codec } from '../codec/codec'; +import type { Amounter } from '../common/types'; +import { serializable } from '../common/types'; +import { Id } from '../fxs/common/id'; +import { OutputOwners, TransferOutput } from '../fxs/secp256k1'; +import { BigIntPr } from '../primitives'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://github.com/ava-labs/avalanchego/blob/master/vms/components/avax/transferables.go + * @see https://docs.avax.network/specs/coreth-atomic-transaction-serialization#transferable-output + * @see https://docs.avax.network/specs/avm-transaction-serialization#transferable-output + * @see https://docs.avax.network/specs/platform-transaction-serialization#transferable-output + */ +@serializable() +export class TransferableOutput { + _type = TypeSymbols.TransferableOutput; + + constructor(public readonly assetId: Id, public readonly output: Amounter) {} + + static fromNative( + assetId: string, + amt: bigint, + addresses: Uint8Array[], + locktime?: bigint, + threshold?: number, + ) { + return new TransferableOutput( + Id.fromString(assetId), + new TransferOutput( + new BigIntPr(amt), + OutputOwners.fromNative(addresses, locktime, threshold), + ), + ); + } + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [TransferableOutput, Uint8Array] { + const [assetId, remaining] = unpack(bytes, [Id], codec); + const [output, rest] = codec.UnpackPrefix(remaining); + return [new TransferableOutput(assetId, output), rest]; + } + + getAssetId() { + return this.assetId.toString(); + } + + amount() { + return this.output.amount(); + } + + toBytes(codec: Codec) { + return concatBytes( + pack([this.assetId], codec), + codec.PackPrefix(this.output), + ); + } +} diff --git a/src/serializable/avax/typeGuards.ts b/src/serializable/avax/typeGuards.ts new file mode 100644 index 000000000..d9b3c7796 --- /dev/null +++ b/src/serializable/avax/typeGuards.ts @@ -0,0 +1,21 @@ +import type { BaseTx } from './baseTx'; +import type { Serializable } from '../common/types'; +import type { TransferableOutput } from './transferableOutput'; +import type { TransferableInput } from './transferableInput'; +import { TypeSymbols } from '../constants'; + +export function isBaseTx(tx: Serializable): tx is BaseTx { + return tx._type === TypeSymbols.BaseTx; +} + +export function isTransferableOutput( + out: Serializable, +): out is TransferableOutput { + return out._type === TypeSymbols.TransferableOutput; +} + +export function isTransferableInput( + out: Serializable, +): out is TransferableInput { + return out._type === TypeSymbols.TransferableInput; +} diff --git a/src/serializable/avax/utxo.spec.ts b/src/serializable/avax/utxo.spec.ts new file mode 100644 index 000000000..ba3e1184f --- /dev/null +++ b/src/serializable/avax/utxo.spec.ts @@ -0,0 +1,14 @@ +import { hexToBuffer } from '../../utils/buffer'; +import { getPVMManager } from '../pvm/codec'; +import { Utxo } from './utxo'; + +// testSerialization('Utxo', Utxo, utxo, utxoBytes); + +describe('examples with real data', () => { + it('samlpe 1', () => { + const bytes = + '0x00004cc3cf2e380c03f0227193a6573d1940350a43f028123ca68c14f54e33a11dcf000000093d9bdac0ed1d761330cf680efdeb1a42159eb387d6d2950c96f7d28f61bbe2aa000000160000000063af7b800000000700000002540be40000000000000000000000000100000001e0cfe8cae22827d032805ded484e393ce51cbedb7f24bb9c'; + + getPVMManager().unpack(hexToBuffer(bytes), Utxo); + }); +}); diff --git a/src/serializable/avax/utxo.ts b/src/serializable/avax/utxo.ts new file mode 100644 index 000000000..ec71be13e --- /dev/null +++ b/src/serializable/avax/utxo.ts @@ -0,0 +1,60 @@ +import { concatBytes } from '@noble/hashes/utils'; +import { UTXOID } from '.'; +import { isRewardsOwner, isStakeableLockOut, isTransferOut } from '../../utils'; +import { pack, unpack } from '../../utils/struct'; +import { Codec } from '../codec/codec'; +import type { Serializable } from '../common/types'; +import { serializable } from '../common/types'; +import { Id } from '../fxs/common'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://docs.avax.network/specs/avm-transaction-serialization#unsigned-Exporttx + */ +@serializable() +export class Utxo { + _type = TypeSymbols.UTXO; + + constructor( + public readonly utxoId: UTXOID, + public readonly assetId: Id, + public readonly output: Serializable, + ) {} + + static fromBytes(bytes: Uint8Array, codec: Codec): [Utxo, Uint8Array] { + const [utxoId, assetId, output, remaining] = unpack( + bytes, + [UTXOID, Id, Codec], + codec, + ); + return [new Utxo(utxoId, assetId, output), remaining]; + } + + getOutputOwners() { + if (isTransferOut(this.output)) { + return this.output.outputOwners; + } + if (isStakeableLockOut(this.output)) { + return this.output.getOutputOwners(); + } + if (isRewardsOwner(this.output)) { + return this.output; + } + throw new Error('unable to get output owner'); + } + + toBytes(codec) { + return concatBytes( + pack([this.utxoId, this.assetId], codec), + codec.PackPrefix(this.output), + ); + } + + getAssetId() { + return this.assetId.toString(); + } + + ID() { + return this.utxoId.ID(); + } +} diff --git a/src/serializable/avax/utxoId.spec.ts b/src/serializable/avax/utxoId.spec.ts new file mode 100644 index 000000000..57ad3788d --- /dev/null +++ b/src/serializable/avax/utxoId.spec.ts @@ -0,0 +1,29 @@ +import { UTXOID } from './utxoId'; +import { utxoId, utxoIdBytes } from '../../fixtures/avax'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { Id } from '../fxs/common'; +import { Int } from '../primitives'; + +testSerialization('UTXOID', UTXOID, utxoId, utxoIdBytes); + +describe('UTXOID', () => { + it('generates correct id', () => { + expect( + new UTXOID( + Id.fromHex( + '0400000000000000000000000000000000000000000000000000000000000000', + ), + new Int(0), + ).ID(), + ).toEqual('HBD3fiEVpzFy569fjPgGKa7GZayj1K1tSWcRs2QWE3ZfjNzWv'); + + expect( + new UTXOID( + Id.fromHex( + '0x0500000000000000000000000000000000000000000000000000000000000000', + ), + new Int(4), + ).ID(), + ).toEqual('ZsXUqJ1rFapUSA7mRGJqGMFPjWtx1YHdb4csN6GWL9zZZ7sGs'); + }); +}); diff --git a/src/serializable/avax/utxoId.ts b/src/serializable/avax/utxoId.ts new file mode 100644 index 000000000..50f827805 --- /dev/null +++ b/src/serializable/avax/utxoId.ts @@ -0,0 +1,52 @@ +import { sha256 } from '@noble/hashes/sha256'; +import { base58check } from '../../utils/base58'; +import { concatBytes } from '../../utils/buffer'; +import { pack, unpack } from '../../utils/struct'; +import type { Codec } from '../codec'; +import { serializable } from '../common/types'; +import { Id } from '../fxs/common/id'; +import { BigIntPr, Int } from '../primitives'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://github.com/ava-labs/avalanchego/blob/master/vms/components/avax/utxo_id.go + */ +@serializable() +export class UTXOID { + _type = TypeSymbols.UTXOID; + + constructor(public readonly txID: Id, public readonly outputIdx: Int) {} + + static fromBytes(bytes: Uint8Array, codec: Codec): [UTXOID, Uint8Array] { + const [txID, outputIdx, remaining] = unpack(bytes, [Id, Int], codec); + + return [new UTXOID(txID, outputIdx), remaining]; + } + + static fromNative(txId: string, outputIdx: number) { + return new UTXOID(Id.fromString(txId), new Int(outputIdx)); + } + + static compare(id1: UTXOID, id2: UTXOID) { + const txIDRes = Id.compare(id1.txID, id2.txID); + if (txIDRes !== 0) { + return txIDRes; + } + return id1.outputIdx.value() - id2.outputIdx.value(); + } + + toBytes(codec) { + return pack([this.txID, this.outputIdx], codec); + } + + ID() { + return base58check.encode( + sha256( + concatBytes( + new BigIntPr(BigInt(this.outputIdx.value())).toBytes(), + this.txID.toBytes(), + ), + ), + ); + } +} diff --git a/src/serializable/avm/abstractTx.ts b/src/serializable/avm/abstractTx.ts new file mode 100644 index 000000000..203fb6396 --- /dev/null +++ b/src/serializable/avm/abstractTx.ts @@ -0,0 +1,6 @@ +import { AvaxTx } from '../avax/avaxTx'; +import { AVM } from '../constants'; + +export abstract class AVMTx extends AvaxTx { + vm = AVM; +} diff --git a/src/serializable/avm/baseTx.spec.ts b/src/serializable/avm/baseTx.spec.ts new file mode 100644 index 000000000..7d6c5c1b5 --- /dev/null +++ b/src/serializable/avm/baseTx.spec.ts @@ -0,0 +1,5 @@ +import { avmBaseTx, avmBaseTxBytes } from '../../fixtures/avax'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { BaseTx } from './baseTx'; + +testSerialization('BaseTx', BaseTx, avmBaseTx, avmBaseTxBytes); diff --git a/src/serializable/avm/baseTx.ts b/src/serializable/avm/baseTx.ts new file mode 100644 index 000000000..d12838885 --- /dev/null +++ b/src/serializable/avm/baseTx.ts @@ -0,0 +1,27 @@ +import { unpack } from '../../utils/struct'; +import { BaseTx as AvaxBaseTx } from '../avax/baseTx'; +import type { Codec } from '../codec/codec'; +import { serializable } from '../common/types'; +import { AVMTx } from './abstractTx'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://docs.avax.network/specs/avm-transaction-serialization#unsigned-basetx + */ +@serializable() +export class BaseTx extends AVMTx { + _type = TypeSymbols.AvmBaseTx; + + constructor(public readonly baseTx: AvaxBaseTx) { + super(); + } + + static fromBytes(bytes: Uint8Array, codec: Codec): [BaseTx, Uint8Array] { + const [baseTx, remaining] = unpack(bytes, [AvaxBaseTx], codec); + return [new BaseTx(baseTx), remaining]; + } + + toBytes(codec: Codec) { + return this.baseTx.toBytes(codec); + } +} diff --git a/src/serializable/avm/codec.ts b/src/serializable/avm/codec.ts new file mode 100644 index 000000000..79be785f2 --- /dev/null +++ b/src/serializable/avm/codec.ts @@ -0,0 +1,33 @@ +import { BaseTx } from './baseTx'; +import { Codec } from '../codec/codec'; +import { Manager } from '../codec/manager'; +import * as NftFx from '../fxs/nft'; +import * as Secp256k1Fx from '../fxs/secp256k1'; +import { CreateAssetTx } from './createAssetTx'; +import { ExportTx } from './exportTx'; +import { ImportTx } from './importTx'; +import { OperationTx } from './operationTx'; + +// https://github.com/ava-labs/avalanchego/blob/master/vms/avm/txs/parser.go +// https://github.com/ava-labs/avalanchego/blob/master/wallet/chain/x/constants.go +let manager: Manager; + +export const getAVMManager = () => { + if (manager) return manager; + + manager = new Manager(); + manager.RegisterCodec( + 0, + new Codec([ + BaseTx, + CreateAssetTx, + OperationTx, + ImportTx, + ExportTx, + ...Secp256k1Fx.TypeRegistry, + ...NftFx.TypeRegistry, + // TODO: ...PropertyFx.TypeRegistry, + ]), + ); + return manager; +}; diff --git a/src/serializable/avm/createAssetTx.spec.ts b/src/serializable/avm/createAssetTx.spec.ts new file mode 100644 index 000000000..a5748c78c --- /dev/null +++ b/src/serializable/avm/createAssetTx.spec.ts @@ -0,0 +1,10 @@ +import { createAssetTx, createAssetTxBytes } from '../../fixtures/avax'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { CreateAssetTx } from './createAssetTx'; + +testSerialization( + 'CreateAssetTx', + CreateAssetTx, + createAssetTx, + createAssetTxBytes, +); diff --git a/src/serializable/avm/createAssetTx.ts b/src/serializable/avm/createAssetTx.ts new file mode 100644 index 000000000..42786c8f6 --- /dev/null +++ b/src/serializable/avm/createAssetTx.ts @@ -0,0 +1,47 @@ +import { concatBytes } from '../../utils/buffer'; +import { packList, toListStruct } from '../../utils/serializeList'; +import { pack, unpack } from '../../utils/struct'; +import { BaseTx } from '../avax/baseTx'; +import type { Codec } from '../codec/codec'; +import { serializable } from '../common/types'; +import { Byte, Stringpr } from '../primitives'; +import { InitialState } from './initialState'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://docs.avax.network/specs/avm-transaction-serialization#unsigned-createassettx + */ +@serializable() +export class CreateAssetTx { + _type = TypeSymbols.CreateAssetTx; + + constructor( + private readonly baseTx: BaseTx, + private readonly name: Stringpr, + private readonly symbol: Stringpr, + private readonly denomination: Byte, + private readonly initialStates: InitialState[], + ) {} + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [CreateAssetTx, Uint8Array] { + const [baseTx, name, symbol, domination, initialStates, remaining] = unpack( + bytes, + [BaseTx, Stringpr, Stringpr, Byte, toListStruct(InitialState)], + codec, + ); + return [ + new CreateAssetTx(baseTx, name, symbol, domination, initialStates), + remaining, + ]; + } + + toBytes(codec: Codec) { + return concatBytes( + pack([this.baseTx, this.name, this.symbol, this.denomination], codec), + packList(this.initialStates, codec), + ); + } +} diff --git a/src/serializable/avm/exportTx.spec.ts b/src/serializable/avm/exportTx.spec.ts new file mode 100644 index 000000000..ad3396496 --- /dev/null +++ b/src/serializable/avm/exportTx.spec.ts @@ -0,0 +1,5 @@ +import { exportTx, exportTxBytes } from '../../fixtures/avax'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { ExportTx } from './exportTx'; + +testSerialization('ExportTx', ExportTx, exportTx, exportTxBytes); diff --git a/src/serializable/avm/exportTx.ts b/src/serializable/avm/exportTx.ts new file mode 100644 index 000000000..cf4d0083b --- /dev/null +++ b/src/serializable/avm/exportTx.ts @@ -0,0 +1,41 @@ +import { concatBytes } from '../../utils/buffer'; +import { packList, toListStruct } from '../../utils/serializeList'; +import { pack, unpack } from '../../utils/struct'; +import { BaseTx } from '../avax/baseTx'; +import { TransferableOutput } from '../avax/transferableOutput'; +import type { Codec } from '../codec/codec'; +import { serializable } from '../common/types'; +import { Id } from '../fxs/common'; +import { AVMTx } from './abstractTx'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://docs.avax.network/specs/avm-transaction-serialization#unsigned-Exporttx + */ +@serializable() +export class ExportTx extends AVMTx { + _type = TypeSymbols.AvmExportTx; + constructor( + public readonly baseTx: BaseTx, + public readonly destination: Id, + public readonly outs: TransferableOutput[], + ) { + super(); + } + + static fromBytes(bytes: Uint8Array, codec: Codec): [ExportTx, Uint8Array] { + const [baseTx, sourceChain, outs, remaining] = unpack( + bytes, + [BaseTx, Id, toListStruct(TransferableOutput)], + codec, + ); + return [new ExportTx(baseTx, sourceChain, outs), remaining]; + } + + toBytes(codec: Codec) { + return concatBytes( + pack([this.baseTx, this.destination], codec), + packList(this.outs, codec), + ); + } +} diff --git a/src/serializable/avm/importTx.spec.ts b/src/serializable/avm/importTx.spec.ts new file mode 100644 index 000000000..f19e1da48 --- /dev/null +++ b/src/serializable/avm/importTx.spec.ts @@ -0,0 +1,5 @@ +import { importTx, importTxBytes } from '../../fixtures/avax'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { ImportTx } from './importTx'; + +testSerialization('ImportTx', ImportTx, importTx, importTxBytes); diff --git a/src/serializable/avm/importTx.ts b/src/serializable/avm/importTx.ts new file mode 100644 index 000000000..873eae280 --- /dev/null +++ b/src/serializable/avm/importTx.ts @@ -0,0 +1,48 @@ +import { concatBytes } from '../../utils/buffer'; +import { packList, toListStruct } from '../../utils/serializeList'; +import { pack, unpack } from '../../utils/struct'; +import { BaseTx } from '../avax/baseTx'; +import { TransferableInput } from '../avax/transferableInput'; +import type { Codec } from '../codec/codec'; +import { serializable } from '../common/types'; +import { Id } from '../fxs/common'; +import { AVMTx } from './abstractTx'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://docs.avax.network/specs/avm-transaction-serialization#unsigned-importtx + */ +@serializable() +export class ImportTx extends AVMTx { + _type = TypeSymbols.AvmImportTx; + + constructor( + readonly baseTx: BaseTx, + readonly sourceChain: Id, + readonly ins: TransferableInput[], + ) { + super(); + } + + getSigIndices() { + return this.ins + .map((inp) => inp.sigIndicies()) + .concat(super.getSigIndices()); + } + + static fromBytes(bytes: Uint8Array, codec: Codec): [ImportTx, Uint8Array] { + const [baseTx, sourceChain, ins, remaining] = unpack( + bytes, + [BaseTx, Id, toListStruct(TransferableInput)], + codec, + ); + return [new ImportTx(baseTx, sourceChain, ins), remaining]; + } + + toBytes(codec: Codec) { + return concatBytes( + pack([this.baseTx, this.sourceChain], codec), + packList(this.ins, codec), + ); + } +} diff --git a/src/serializable/avm/index.ts b/src/serializable/avm/index.ts new file mode 100644 index 000000000..0112b01fe --- /dev/null +++ b/src/serializable/avm/index.ts @@ -0,0 +1,9 @@ +import { BaseTx } from './baseTx'; +import { CreateAssetTx } from './createAssetTx'; +import { ExportTx } from './exportTx'; +import { ImportTx } from './importTx'; +import { InitialState } from './initialState'; +import { OperationTx } from './operationTx'; +export { getAVMManager } from './codec'; +export * from './typeGuards'; +export { BaseTx, CreateAssetTx, ExportTx, ImportTx, InitialState, OperationTx }; diff --git a/src/serializable/avm/initialState.spec.ts b/src/serializable/avm/initialState.spec.ts new file mode 100644 index 000000000..2052dd025 --- /dev/null +++ b/src/serializable/avm/initialState.spec.ts @@ -0,0 +1,10 @@ +import { initialState, initialStateBytes } from '../../fixtures/avax'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { InitialState } from './initialState'; + +testSerialization( + 'InitialState', + InitialState, + initialState, + initialStateBytes, +); diff --git a/src/serializable/avm/initialState.ts b/src/serializable/avm/initialState.ts new file mode 100644 index 000000000..fd2aabc00 --- /dev/null +++ b/src/serializable/avm/initialState.ts @@ -0,0 +1,33 @@ +import { concatBytes } from '../../utils/buffer'; +import type { Codec } from '../codec/codec'; +import type { Serializable } from '../common/types'; +import { serializable } from '../common/types'; +import { Int } from '../primitives'; +import { unpackCodecList } from '../../utils/serializeList'; +import { unpack } from '../../utils/struct'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://docs.avax.network/specs/avm-transaction-serialization#initial-state + */ +@serializable() +export class InitialState { + _type = TypeSymbols.InitialState; + + constructor( + private readonly fxId: Int, + private readonly outputs: Serializable[], + ) {} + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [InitialState, Uint8Array] { + const [fxId, outputs, rest] = unpack(bytes, [Int, unpackCodecList], codec); + return [new InitialState(fxId, outputs), rest]; + } + + toBytes(codec: Codec) { + return concatBytes(this.fxId.toBytes(), codec.PackPrefixList(this.outputs)); + } +} diff --git a/src/serializable/avm/operationTx.spec.ts b/src/serializable/avm/operationTx.spec.ts new file mode 100644 index 000000000..174791736 --- /dev/null +++ b/src/serializable/avm/operationTx.spec.ts @@ -0,0 +1,5 @@ +import { operationTx, operationTxBytes } from '../../fixtures/avax'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { OperationTx } from './operationTx'; + +testSerialization('OperationTx', OperationTx, operationTx, operationTxBytes); diff --git a/src/serializable/avm/operationTx.ts b/src/serializable/avm/operationTx.ts new file mode 100644 index 000000000..3252a5fe5 --- /dev/null +++ b/src/serializable/avm/operationTx.ts @@ -0,0 +1,34 @@ +import { concatBytes } from '../../utils/buffer'; +import { packList, toListStruct } from '../../utils/serializeList'; +import { unpack } from '../../utils/struct'; +import { BaseTx } from '../avax/baseTx'; +import { TransferableOp } from '../avax/transferableOp'; +import type { Codec } from '../codec/codec'; +import { serializable } from '../common/types'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://docs.avax.network/specs/avm-transaction-serialization#unsigned-OperationTx + */ +@serializable() +export class OperationTx { + _type = TypeSymbols.OperationTx; + + constructor( + private readonly baseTx: BaseTx, + private readonly ops: TransferableOp[], + ) {} + + static fromBytes(bytes: Uint8Array, codec: Codec): [OperationTx, Uint8Array] { + const [baseTx, ops, remaining] = unpack( + bytes, + [BaseTx, toListStruct(TransferableOp)], + codec, + ); + return [new OperationTx(baseTx, ops), remaining]; + } + + toBytes(codec: Codec) { + return concatBytes(this.baseTx.toBytes(codec), packList(this.ops, codec)); + } +} diff --git a/src/serializable/avm/typeGuards.spec.ts b/src/serializable/avm/typeGuards.spec.ts new file mode 100644 index 000000000..476492781 --- /dev/null +++ b/src/serializable/avm/typeGuards.spec.ts @@ -0,0 +1,63 @@ +import { + isAvmBaseTx, + isExportTx, + isImportTx, + isOperationTx, + isCreateAssetTx, +} from './typeGuards'; +import { TypeSymbols } from '../constants'; +import type { Serializable } from '../common/types'; +import { onlyChecksOneGuard } from '../../fixtures/utils/typeguards'; + +const typeGuards = [ + isAvmBaseTx, + isExportTx, + isImportTx, + isOperationTx, + isCreateAssetTx, +]; + +describe('avm/typeGuards', function () { + it('can check base tx', () => { + const tx = { _type: TypeSymbols.AvmBaseTx } as Serializable; + const check = isAvmBaseTx(tx); + expect(check).toBe(true); + expect(onlyChecksOneGuard(tx, typeGuards)).toBe(true); + }); + + it('can check export tx', () => { + const tx = { + _type: TypeSymbols.AvmExportTx, + } as Serializable; + const check = isExportTx(tx); + expect(check).toBe(true); + expect(onlyChecksOneGuard(tx, typeGuards)).toBe(true); + }); + + it('can check import tx', () => { + const tx = { + _type: TypeSymbols.AvmImportTx, + } as Serializable; + const check = isImportTx(tx); + expect(check).toBe(true); + expect(onlyChecksOneGuard(tx, typeGuards)).toBe(true); + }); + + it('can check operation tx', () => { + const tx = { + _type: TypeSymbols.OperationTx, + } as Serializable; + const check = isOperationTx(tx); + expect(check).toBe(true); + expect(onlyChecksOneGuard(tx, typeGuards)).toBe(true); + }); + + it('can check create asset tx', () => { + const tx = { + _type: TypeSymbols.CreateAssetTx, + } as Serializable; + const check = isCreateAssetTx(tx); + expect(check).toBe(true); + expect(onlyChecksOneGuard(tx, typeGuards)).toBe(true); + }); +}); diff --git a/src/serializable/avm/typeGuards.ts b/src/serializable/avm/typeGuards.ts new file mode 100644 index 000000000..0175da670 --- /dev/null +++ b/src/serializable/avm/typeGuards.ts @@ -0,0 +1,27 @@ +import type { Serializable } from '../common/types'; +import type { BaseTx } from './baseTx'; +import type { CreateAssetTx } from './createAssetTx'; +import type { ExportTx } from './exportTx'; +import type { ImportTx } from './importTx'; +import type { OperationTx } from './operationTx'; +import { TypeSymbols } from '../constants'; + +export function isAvmBaseTx(tx: Serializable): tx is BaseTx { + return tx._type === TypeSymbols.AvmBaseTx; +} + +export function isExportTx(tx: Serializable): tx is ExportTx { + return tx._type === TypeSymbols.AvmExportTx; +} + +export function isImportTx(tx: Serializable): tx is ImportTx { + return tx._type === TypeSymbols.AvmImportTx; +} + +export function isCreateAssetTx(tx: Serializable): tx is CreateAssetTx { + return tx._type === TypeSymbols.CreateAssetTx; +} + +export function isOperationTx(tx: Serializable): tx is OperationTx { + return tx._type === TypeSymbols.OperationTx; +} diff --git a/src/serializable/codec/codec.spec.ts b/src/serializable/codec/codec.spec.ts new file mode 100644 index 000000000..0a1453e19 --- /dev/null +++ b/src/serializable/codec/codec.spec.ts @@ -0,0 +1,67 @@ +import { Codec } from '.'; +import { id, idBytes } from '../../fixtures/common'; +import { + mintOutput, + mintOutputBytes, + outputOwner, + outputOwnerBytes, +} from '../../fixtures/secp256k1'; +import { bytesForInt } from '../../fixtures/utils/bytesFor'; +import { Id } from '../fxs/common'; +import { MintOutput, OutputOwners } from '../fxs/secp256k1'; +import { concatBytes } from '../../utils/buffer'; +import { unpack } from '../../utils/struct'; + +describe('Codec', () => { + let testCodec: Codec; + beforeEach(() => { + testCodec = new Codec([MintOutput, OutputOwners]); + }); + + it('unpacks types correctly', () => { + const bytes = concatBytes(bytesForInt(1), outputOwnerBytes()); + + const [out, remainder] = testCodec.UnpackPrefix(bytes); + + expect(out).toStrictEqual(outputOwner()); + + expect(remainder).toStrictEqual(new Uint8Array()); + }); + + it('packs types correctly', () => { + const owners = outputOwner(); + const bytes = concatBytes(bytesForInt(1), outputOwnerBytes()); + + expect(testCodec.PackPrefix(owners)).toStrictEqual(bytes); + }); + + it('packs list of types correctly', () => { + const input = [outputOwner(), mintOutput()]; + const output = testCodec.PackPrefixList(input); + + expect(output).toEqual( + concatBytes( + bytesForInt(2), + bytesForInt(1), + outputOwnerBytes(), + bytesForInt(0), + mintOutputBytes(), + ), + ); + }); + + it('packs types correctly', () => { + const owners = outputOwner(); + const bytes = concatBytes(bytesForInt(1), outputOwnerBytes()); + + expect(testCodec.PackPrefix(owners)).toStrictEqual(bytes); + }); + + it('works with unpack', () => { + const input = concatBytes(idBytes(), bytesForInt(1), outputOwnerBytes()); + const [idoutput, owner, remaining] = unpack(input, [Id, Codec], testCodec); + expect(idoutput).toEqual(id()); + expect(owner).toEqual(outputOwner()); + expect(remaining).toStrictEqual(new Uint8Array()); + }); +}); diff --git a/src/serializable/codec/codec.ts b/src/serializable/codec/codec.ts new file mode 100644 index 000000000..102982722 --- /dev/null +++ b/src/serializable/codec/codec.ts @@ -0,0 +1,71 @@ +import { bytesForInt } from '../../fixtures/utils/bytesFor'; +import { concatBytes } from '../../utils/buffer'; +import { unpack } from '../../utils/struct'; +import type { Serializable, SerializableStatic } from '../common/types'; +import { serializable } from '../common/types'; +import { Int } from '../primitives'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://github.com/ava-labs/avalanchego/blob/master/codec/linearcodec/codec.go + */ +@serializable() +export class Codec { + _type = TypeSymbols.Codec; + typeToTypeID: Map; + + constructor( + private readonly typeIdToType: (SerializableStatic | undefined)[], + ) { + this.typeToTypeID = typeIdToType.reduce( + (agg, type, index) => (type ? agg.set(new type()._type, index) : agg), + new Map(), + ); + } + + PackPrefix = (type: Serializable) => { + const id = this.typeToTypeID.get(type._type); + if (id === undefined) { + throw new Error( + `can't marshal unregistered type: ${type._type.toString()}`, + ); + } + + return concatBytes(bytesForInt(id), type.toBytes(this)); + }; + + UnpackPrefix = (buf: Uint8Array): [T, Uint8Array] => { + let typeId: Int; + [typeId, buf] = unpack(buf, [Int]); + const type = this.typeIdToType[typeId.value()]; + + if (type === undefined) { + throw new Error( + `couldn't unmarshal interface: unknown type ID ${typeId.value()}`, + ); + } + + const [entity, rest] = type.fromBytes(buf, this); + + return [entity as T, rest]; + }; + + static fromBytes(buf: Uint8Array, codec?: Codec) { + if (!codec) { + throw new Error('codec required'); + } + return codec.UnpackPrefix(buf); + } + + // this is placed here to satisfy serializable and should not be used directly + toBytes(): Uint8Array { + throw new Error('not implemented'); + } + + PackPrefixList(list: Serializable[]): Uint8Array { + return concatBytes( + bytesForInt(list.length), + ...list.map((type) => this.PackPrefix(type)), + ); + } +} diff --git a/src/serializable/codec/index.ts b/src/serializable/codec/index.ts new file mode 100644 index 000000000..bb23adca3 --- /dev/null +++ b/src/serializable/codec/index.ts @@ -0,0 +1,2 @@ +export { Codec } from './codec'; +export { Manager } from './manager'; diff --git a/src/serializable/codec/manager.spec.ts b/src/serializable/codec/manager.spec.ts new file mode 100644 index 000000000..1a365cfc8 --- /dev/null +++ b/src/serializable/codec/manager.spec.ts @@ -0,0 +1,74 @@ +import { Codec, Manager } from '.'; +import { createAssetTx, createAssetTxBytes } from '../../fixtures/avax'; +import { bytesForInt } from '../../fixtures/utils/bytesFor'; +import { concatBytes } from '../../utils/buffer'; +import { CreateAssetTx } from '../avm/createAssetTx'; +import { Bytes, Short, Stringpr } from '../primitives'; +import { jest } from '@jest/globals'; +import type { Mock } from 'jest-mock'; + +describe('Manager', () => { + it('registers multiple codecs', () => { + const m = new Manager(); + m.RegisterCodec(0, new Codec([])); + m.RegisterCodec(1, new Codec([])); + }); + + it('errors when registering a codec version twice', () => { + const m = new Manager(); + m.RegisterCodec(0, new Codec([])); + expect(() => m.RegisterCodec(0, new Codec([]))).toThrow( + 'duplicated codec version', + ); + }); +}); + +describe('using the codecs', () => { + let m: Manager; + let codec1: Codec; + beforeEach(() => { + m = new Manager(); + codec1 = new Codec([Bytes]); + + //filler + m.RegisterCodec(0, new Codec([Stringpr])); + + m.RegisterCodec(1, codec1); + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + it('chooses the right codec', () => { + CreateAssetTx.fromBytes = jest.fn(() => [ + createAssetTx(), + new Uint8Array(), + ]) as Mock<() => [CreateAssetTx, Uint8Array]>; + + const input = concatBytes(new Short(1).toBytes(), createAssetTxBytes()); + + m.unpack(input, CreateAssetTx); + + expect(CreateAssetTx.fromBytes).toBeCalledWith( + createAssetTxBytes(), + codec1, + ); + }); + + it('packs with correct prefix', () => { + const tx = createAssetTx(); + codec1.PackPrefix = jest.fn(() => + concatBytes(bytesForInt(2), createAssetTxBytes()), + ); + const bytes = m.packCodec(tx, 1); + + const output = concatBytes( + new Short(1).toBytes(), + concatBytes(bytesForInt(2), createAssetTxBytes()), + ); + + expect(codec1.PackPrefix).toBeCalledWith(tx); + expect(bytes).toEqual(output); + }); +}); diff --git a/src/serializable/codec/manager.ts b/src/serializable/codec/manager.ts new file mode 100644 index 000000000..582a19205 --- /dev/null +++ b/src/serializable/codec/manager.ts @@ -0,0 +1,66 @@ +import { DEFAULT_CODEC_VERSION } from '../../constants/codec'; +import { concatBytes } from '../../utils/buffer'; +import type { FromBytesReturn } from '../../utils/struct'; +import { unpack } from '../../utils/struct'; +import type { Transaction } from '../../vms/common/transaction'; +import type { Serializable, SerializableStatic } from '../common/types'; +import { Short } from '../primitives'; +import type { Codec } from './codec'; + +/** + * @see https://github.com/ava-labs/avalanchego/blob/master/codec/manager.go + */ +export class Manager { + codecs: Record = {}; + RegisterCodec(version: number, codec: Codec) { + if (version in this.codecs) { + throw new Error('duplicated codec version'); + } + + this.codecs[version] = codec; + } + + unpack = ( + buff: Uint8Array, + unpacker: T, + ): FromBytesReturn => { + const [codec, rest] = this.getCodecFromBuffer(buff); + // TODO: try to do this without casting + return unpacker.fromBytes(rest, codec)[0] as FromBytesReturn; + }; + + unpackTransaction = (buff: Uint8Array): Transaction => { + const [codec, rest] = this.getCodecFromBuffer(buff); + return codec.UnpackPrefix(rest)[0]; + }; + + public getCodecFromBuffer(buff: Uint8Array): [Codec, Uint8Array] { + const [codecId, rest] = unpack(buff, [Short]); + const codec = this.getCodecForVersion(codecId); + return [codec, rest]; + } + + getCodecForVersion(codecId: Short): Codec { + if (!this.codecs[codecId.value()]) { + throw new Error(`codec id(${codecId.value()}) not found`); + } + return this.codecs[codecId.value()]; + } + + getDefaultCodec() { + return this.getCodecForVersion(new Short(DEFAULT_CODEC_VERSION)); + } + + getDefaultCodecId() { + return new Short(DEFAULT_CODEC_VERSION); + } + + packCodec( + serializable: Serializable, + codecVersion = DEFAULT_CODEC_VERSION, + ): Uint8Array { + const codecIdShort = new Short(codecVersion); + const codec = this.getCodecForVersion(codecIdShort); + return concatBytes(codecIdShort.toBytes(), codec.PackPrefix(serializable)); + } +} diff --git a/src/serializable/common/types.ts b/src/serializable/common/types.ts new file mode 100644 index 000000000..72931886b --- /dev/null +++ b/src/serializable/common/types.ts @@ -0,0 +1,28 @@ +import type { Codec } from '../../serializable/codec'; +import type { TypeSymbols } from '../constants'; + +export interface Serializable { + _type: TypeSymbols; + + toBytes(codec: Codec): Uint8Array; +} + +export interface SerializableStatic { + new (...args: any[]): Serializable; + + fromBytes(bytes: Uint8Array, codec: Codec): [Serializable, Uint8Array]; +} + +export function staticImplements() { + return (constructor: U) => { + constructor; + }; +} + +export function serializable() { + return staticImplements(); +} + +export interface Amounter extends Serializable { + amount(): bigint; +} diff --git a/src/serializable/constants.ts b/src/serializable/constants.ts new file mode 100644 index 000000000..3ce44acd8 --- /dev/null +++ b/src/serializable/constants.ts @@ -0,0 +1,88 @@ +export const AVM = 'AVM' as const; +export const EVM = 'EVM' as const; +export const PVM = 'PVM' as const; + +export type VM = typeof AVM | typeof EVM | typeof PVM; +export const ValidVMs = [AVM, EVM, PVM] as const; + +export enum TypeSymbols { + Codec = 'codec', + + // AVAX + BaseTx = 'avax.BaseTx', + TransferableOutput = 'avax.TransferableOutput', + TransferableInput = 'avax.TransferableInput', + TransferableOp = 'avax.TransferableOp', + UTXOID = 'avax.UTXOID', + UTXO = 'avax.Utxo', + + // COMMON + Id = 'common.Id', + Address = 'common.Address', + NodeId = 'common.NodeId', + + // PRIMITIVES + Int = 'primitives.Int', + BigIntPr = 'primitives.BigInt', + StringPr = 'primitives.String', + Byte = 'primitives.Byte', + Bytes = 'primitives.Bytes', + Short = 'primitives.Short', + + // SECP256k1FX + Input = 'secp256k1fx.Input', + TransferInput = 'secp256k1fx.TransferInput', + TransferOutput = 'secp256k1fx.TransferOutput', + OutputOwners = 'secp256k1fx.OutputOwners', + OutputOwnersList = 'secp256k1fx.OutputOwnersList', + Credential = 'secp256k1fx.Credential', + Signature = 'secp256k1fx.Signature', + SecpMintOperation = 'secp256k1fx.MintOperation', + SecpMintOutput = 'secp256k1fx.MintOutput', + + // NFTFX + NftFxMintOperation = 'nftfx.MintOperation', + NftFxMintOutput = 'nftfx.MintOutput', + NftFxTransferOperation = 'nftfx.TransferOperation', + NftFxTransferOutput = 'nftfx.TransferOutput', + NftFxCredential = 'nftfx.Credential', + + // AVM + AvmBaseTx = 'avm.BaseTx', + AvmExportTx = 'avm.ExportTx', + AvmImportTx = 'avm.ImportTx', + CreateAssetTx = 'avm.CreateAssetTx', + OperationTx = 'avm.OperationTx', + InitialState = 'avm.InitialState', + AvmSignedTx = 'avm.SignedTx', + + // PVM + PvmBaseTx = 'pvm.BaseTx', + StakeableLockIn = 'pvm.StakeableLockIn', + StakeableLockOut = 'pvm.StakeableLockOut', + AddDelegatorTx = 'pvm.AddDelegatorTx', + AddValidatorTx = 'pvm.AddValidatorTx', + AddPermissionlessDelegatorTx = 'pvm.AddPermissionlessDelegator', + AddPermissionlessValidatorTx = 'pvm.AddPermissionlessValidator', + Validator = 'pvm.Validator', + SubnetValidator = 'pvm.SubnetValidator', + Signer = 'pvm.signer', + SignerEmpty = 'pvm.signerEmpty', + ProofOfPossession = 'pvm.proofOfPossession', + AddSubnetValidatorTx = 'pvm.AddSubnetValidator', + AdvanceTimeTx = 'pvm.AdvanceTimeTx', + CreateChainTx = 'pvm.CreateChainTx', + CreateSubnetTx = 'pvm.CreateSubnetTx', + PvmExportTx = 'pvm.ExportTx', + PvmImportTx = 'pvm.ImportTx', + RewardValidatorTx = 'pvm.RewardValidatorTx', + RemoveSubnetValidatorTx = 'pvm.RemoveSubnetValidator', + TransformSubnetTx = 'pvm.TransformSubnetTx', + TransferSubnetOwnershipTx = 'pvm.TransferSubnetOwnershipTx', + + // EVM + EvmExportTx = 'evm.ExportTx', + EvmInput = 'evm.Input', + EvmOutput = 'evm.Output', + EvmImportTx = 'evm.ImportTx', +} diff --git a/src/serializable/evm/abstractTx.ts b/src/serializable/evm/abstractTx.ts new file mode 100644 index 000000000..214743a9a --- /dev/null +++ b/src/serializable/evm/abstractTx.ts @@ -0,0 +1,12 @@ +import { Transaction } from '../../vms/common/transaction'; +import { EVM } from '../constants'; +import type { Id } from '../fxs/common'; + +export abstract class EVMTx extends Transaction { + abstract blockchainId: Id; + vm = EVM; + + getBlockchainId = () => { + return this.blockchainId.toString(); + }; +} diff --git a/src/serializable/evm/codec.ts b/src/serializable/evm/codec.ts new file mode 100644 index 000000000..f25cbc307 --- /dev/null +++ b/src/serializable/evm/codec.ts @@ -0,0 +1,24 @@ +import { Codec, Manager } from '../codec'; +import * as Secp256k1Fx from '../fxs/secp256k1'; +import { ExportTx } from './exportTx'; +import { ImportTx } from './importTx'; + +// https://github.com/ava-labs/coreth/blob/master/plugin/evm/codec.go +let manager; +export const codec = new Codec([ + ImportTx, // 0 + ExportTx, // 1 + + ...Array(3).fill(undefined), + + ...Secp256k1Fx.TypeRegistry, + Secp256k1Fx.Input, + Secp256k1Fx.OutputOwners, +]); + +export const getEVMManager = () => { + if (manager) return manager; + manager = new Manager(); + manager.RegisterCodec(0, codec); + return manager; +}; diff --git a/src/serializable/evm/exportTx.spec.ts b/src/serializable/evm/exportTx.spec.ts new file mode 100644 index 000000000..26aa5cf5e --- /dev/null +++ b/src/serializable/evm/exportTx.spec.ts @@ -0,0 +1,6 @@ +import { testEVMCodec } from '../../fixtures/codec'; +import { exportTx, exportTxBytes } from '../../fixtures/evm'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { ExportTx } from './exportTx'; + +testSerialization('ExportTx', ExportTx, exportTx, exportTxBytes, testEVMCodec); diff --git a/src/serializable/evm/exportTx.ts b/src/serializable/evm/exportTx.ts new file mode 100644 index 000000000..b370d494e --- /dev/null +++ b/src/serializable/evm/exportTx.ts @@ -0,0 +1,55 @@ +import { toListStruct } from '../../utils/serializeList'; +import { packSwitched, unpack } from '../../utils/struct'; +import { serializable } from '../../vms/common/types'; +import { TransferableOutput } from '../avax/transferableOutput'; +import type { Codec } from '../codec'; +import { Id } from '../fxs/common'; +import { Int } from '../primitives'; +import { EVMTx } from './abstractTx'; +import { Input } from './input'; +import { TypeSymbols } from '../constants'; + +/** + * @see + */ +@serializable() +export class ExportTx extends EVMTx { + _type = TypeSymbols.EvmExportTx; + + constructor( + public readonly networkId: Int, + public readonly blockchainId: Id, + public readonly destinationChain: Id, + public readonly ins: Input[], + public readonly exportedOutputs: TransferableOutput[], + ) { + super(); + } + getSigIndices() { + return [[0]]; + } + + static fromBytes(bytes: Uint8Array, codec: Codec): [ExportTx, Uint8Array] { + const [networkId, blockchainId, sourceChain, ins, exportedOutputs, rest] = + unpack( + bytes, + [Int, Id, Id, toListStruct(Input), toListStruct(TransferableOutput)], + codec, + ); + return [ + new ExportTx(networkId, blockchainId, sourceChain, ins, exportedOutputs), + rest, + ]; + } + + toBytes(codec: Codec) { + return packSwitched( + codec, + this.networkId, + this.blockchainId, + this.destinationChain, + this.ins, + this.exportedOutputs, + ); + } +} diff --git a/src/serializable/evm/importTx.spec.ts b/src/serializable/evm/importTx.spec.ts new file mode 100644 index 000000000..0bdf64f7d --- /dev/null +++ b/src/serializable/evm/importTx.spec.ts @@ -0,0 +1,6 @@ +import { testEVMCodec } from '../../fixtures/codec'; +import { importTx, importTxBytes } from '../../fixtures/evm'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { ImportTx } from './importTx'; + +testSerialization('ImportTx', ImportTx, importTx, importTxBytes, testEVMCodec); diff --git a/src/serializable/evm/importTx.ts b/src/serializable/evm/importTx.ts new file mode 100644 index 000000000..a95b505d5 --- /dev/null +++ b/src/serializable/evm/importTx.ts @@ -0,0 +1,56 @@ +import { toListStruct } from '../../utils/serializeList'; +import { packSwitched, unpack } from '../../utils/struct'; +import { serializable } from '../../vms/common/types'; +import { TransferableInput } from '../avax/transferableInput'; +import type { Codec } from '../codec'; +import { Id } from '../fxs/common'; +import { Int } from '../primitives'; +import { EVMTx } from './abstractTx'; +import { Output } from './output'; +import { TypeSymbols } from '../constants'; + +/** + * @see + */ +@serializable() +export class ImportTx extends EVMTx { + _type = TypeSymbols.EvmImportTx; + + constructor( + public readonly networkId: Int, + public readonly blockchainId: Id, + public readonly sourceChain: Id, + public readonly importedInputs: TransferableInput[], + public readonly Outs: Output[], + ) { + super(); + } + + getSigIndices() { + return this.importedInputs.map((inp) => inp.sigIndicies()); + } + + static fromBytes(bytes: Uint8Array, codec: Codec): [ImportTx, Uint8Array] { + const [networkId, blockchainId, sourceChain, importedInputs, Outs, rest] = + unpack( + bytes, + [Int, Id, Id, toListStruct(TransferableInput), toListStruct(Output)], + codec, + ); + return [ + new ImportTx(networkId, blockchainId, sourceChain, importedInputs, Outs), + rest, + ]; + } + + toBytes(codec: Codec) { + return packSwitched( + codec, + this.networkId, + this.blockchainId, + this.sourceChain, + this.importedInputs, + this.Outs, + ); + } +} diff --git a/src/serializable/evm/index.ts b/src/serializable/evm/index.ts new file mode 100644 index 000000000..8ef3cba93 --- /dev/null +++ b/src/serializable/evm/index.ts @@ -0,0 +1,6 @@ +export { EVMTx } from './abstractTx'; +export { ExportTx } from './exportTx'; +export { ImportTx } from './importTx'; +export { Input } from './input'; +export { Output } from './output'; +export * from './typeGuards'; diff --git a/src/serializable/evm/input.spec.ts b/src/serializable/evm/input.spec.ts new file mode 100644 index 000000000..282779b73 --- /dev/null +++ b/src/serializable/evm/input.spec.ts @@ -0,0 +1,6 @@ +import { testEVMCodec } from '../../fixtures/codec'; +import { input, inputBytes } from '../../fixtures/secp256k1'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { Input } from '../fxs/secp256k1'; + +testSerialization('Input', Input, input, inputBytes, testEVMCodec); diff --git a/src/serializable/evm/input.ts b/src/serializable/evm/input.ts new file mode 100644 index 000000000..9767e5fd9 --- /dev/null +++ b/src/serializable/evm/input.ts @@ -0,0 +1,47 @@ +import { packSwitched, unpack } from '../../utils/struct'; +import { serializable } from '../../vms/common/types'; +import type { Codec } from '../codec'; +import { Address, Id } from '../fxs/common'; +import { BigIntPr } from '../primitives'; +import { TypeSymbols } from '../constants'; + +/** + * @see + */ +@serializable() +export class Input { + _type = TypeSymbols.EvmInput; + + constructor( + public readonly address: Address, + public readonly amount: BigIntPr, + public readonly assetId: Id, + public readonly nonce: BigIntPr, + ) {} + + static fromBytes(bytes: Uint8Array, codec: Codec): [Input, Uint8Array] { + const [address, amount, assetId, nonce, rest] = unpack( + bytes, + [Address, BigIntPr, Id, BigIntPr], + codec, + ); + return [new Input(address, amount, assetId, nonce), rest]; + } + + static compare = (a: Input, b: Input) => { + if (a.address.value() !== b.address.value()) { + return a.address.value().localeCompare(b.address.value()); + } + return a.assetId.value().localeCompare(b.assetId.value()); + }; + + toBytes(codec: Codec) { + return packSwitched( + codec, + this.address, + this.amount, + this.assetId, + this.nonce, + ); + } +} diff --git a/src/serializable/evm/output.spec.ts b/src/serializable/evm/output.spec.ts new file mode 100644 index 000000000..399c9d32a --- /dev/null +++ b/src/serializable/evm/output.spec.ts @@ -0,0 +1,6 @@ +import { testEVMCodec } from '../../fixtures/codec'; +import { output, outputBytes } from '../../fixtures/evm'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { Output } from './output'; + +testSerialization('Output', Output, output, outputBytes, testEVMCodec); diff --git a/src/serializable/evm/output.ts b/src/serializable/evm/output.ts new file mode 100644 index 000000000..7ee53f176 --- /dev/null +++ b/src/serializable/evm/output.ts @@ -0,0 +1,33 @@ +import { packSwitched, unpack } from '../../utils/struct'; +import { serializable } from '../../vms/common/types'; +import type { Codec } from '../codec'; +import { Address, Id } from '../fxs/common'; +import { BigIntPr } from '../primitives'; +import { TypeSymbols } from '../constants'; + +/** + * @see + */ +@serializable() +export class Output { + _type = TypeSymbols.EvmOutput; + + constructor( + public readonly address: Address, + public readonly amount: BigIntPr, + public readonly assetId: Id, + ) {} + + static fromBytes(bytes: Uint8Array, codec: Codec): [Output, Uint8Array] { + const [address, amount, assetId, rest] = unpack( + bytes, + [Address, BigIntPr, Id], + codec, + ); + return [new Output(address, amount, assetId), rest]; + } + + toBytes(codec: Codec) { + return packSwitched(codec, this.address, this.amount, this.assetId); + } +} diff --git a/src/serializable/evm/typeGuards.spec.ts b/src/serializable/evm/typeGuards.spec.ts new file mode 100644 index 000000000..bbdb320f1 --- /dev/null +++ b/src/serializable/evm/typeGuards.spec.ts @@ -0,0 +1,33 @@ +import { + isImportTx, + isExportTx, + isImportExportTx, + isEvmTx, +} from './typeGuards'; +import { TypeSymbols } from '../constants'; +import type { Transaction } from '../../vms/common'; +import { onlyChecksOneGuard } from '../../fixtures/utils/typeguards'; + +const guards = [isImportTx, isExportTx]; + +describe('evm/typeGuards', function () { + it('isImportTx', () => { + const tx = { + _type: TypeSymbols.EvmImportTx, + } as Transaction; + expect(isImportTx(tx)).toBe(true); + expect(isImportExportTx(tx)).toBe(true); + expect(isEvmTx(tx)).toBe(true); + expect(onlyChecksOneGuard(tx, guards)).toBe(true); + }); + + it('isExportTx', () => { + const tx = { + _type: TypeSymbols.EvmExportTx, + } as Transaction; + expect(isExportTx(tx)).toBe(true); + expect(isImportExportTx(tx)).toBe(true); + expect(isEvmTx(tx)).toBe(true); + expect(onlyChecksOneGuard(tx, guards)).toBe(true); + }); +}); diff --git a/src/serializable/evm/typeGuards.ts b/src/serializable/evm/typeGuards.ts new file mode 100644 index 000000000..ea4912d07 --- /dev/null +++ b/src/serializable/evm/typeGuards.ts @@ -0,0 +1,24 @@ +import type { Transaction } from '../../vms/common/transaction'; +import type { EVMTx } from './abstractTx'; +import type { ExportTx } from './exportTx'; +import type { ImportTx } from './importTx'; +import { TypeSymbols } from '../constants'; + +export function isExportTx(tx: Transaction): tx is ExportTx { + return tx._type == TypeSymbols.EvmExportTx; +} + +export function isImportTx(tx: Transaction): tx is ImportTx { + return tx._type == TypeSymbols.EvmImportTx; +} + +export function isEvmTx(tx: Transaction): tx is EVMTx { + return isImportTx(tx) || isExportTx(tx); +} + +export function isImportExportTx(tx: Transaction): tx is ImportTx | ExportTx { + if (!(isExportTx(tx) || isImportTx(tx))) { + return false; + } + return true; +} diff --git a/src/serializable/fxs/common/address.spec.ts b/src/serializable/fxs/common/address.spec.ts new file mode 100644 index 000000000..71cfd8dea --- /dev/null +++ b/src/serializable/fxs/common/address.spec.ts @@ -0,0 +1,5 @@ +import { address, addressBytes } from '../../../fixtures/common'; +import { testSerialization } from '../../../fixtures/utils/serializable'; +import { Address } from './address'; + +testSerialization('Address', Address, address, addressBytes); diff --git a/src/serializable/fxs/common/address.ts b/src/serializable/fxs/common/address.ts new file mode 100644 index 000000000..7344b2e9e --- /dev/null +++ b/src/serializable/fxs/common/address.ts @@ -0,0 +1,51 @@ +import { customInspectSymbol } from '../../../constants/node'; +import { bech32ToBytes, formatBech32 } from '../../../utils/address'; +import { bufferToHex, hexToBuffer, padLeft } from '../../../utils/buffer'; +import { serializable } from '../../common/types'; +import { Primitives } from '../../primitives/primatives'; +import { TypeSymbols } from '../../constants'; + +@serializable() +export class Address extends Primitives { + _type = TypeSymbols.Address; + constructor(private readonly address: Uint8Array) { + super(); + } + + static fromBytes(buf: Uint8Array): [Address, Uint8Array] { + return [new Address(buf.slice(0, 20)), buf.slice(20)]; + } + + [customInspectSymbol](_, options: any) { + return options.stylize(this.toJSON(), 'string'); + } + + toJSON(hrp = 'avax') { + return this.toString(hrp); + } + + //decodes from bech32 Addresses + static fromString(addr: string): Address { + return new Address(bech32ToBytes(addr)); + } + + static fromHex(hex: string): Address { + return new Address(hexToBuffer(hex)); + } + + toHex(): string { + return bufferToHex(this.address); + } + + toBytes() { + return padLeft(this.address, 20); + } + + toString(hrp = 'avax') { + return formatBech32(hrp, this.address); + } + + value() { + return this.toString(); + } +} diff --git a/src/serializable/fxs/common/id.spec.ts b/src/serializable/fxs/common/id.spec.ts new file mode 100644 index 000000000..5817060f5 --- /dev/null +++ b/src/serializable/fxs/common/id.spec.ts @@ -0,0 +1,26 @@ +import { id, idBytes } from '../../../fixtures/common'; +import { testSerialization } from '../../../fixtures/utils/serializable'; +import { Id } from './id'; + +testSerialization('Id', Id, id, idBytes); + +describe('id', function () { + it('works correctly', () => { + const id = Id.fromHex( + '0x6176617800000000000000000000000000000000000000000000000000000000', + ); + const expectedIDStr = 'jvYiYUgxB6hG1dBobJK2JSoyuLtmFiDoXmUVxmAB7juqfbVtu'; + + const idStr = id.toString(); + + expect(idStr).toEqual(expectedIDStr); + + expect(Id.fromString(expectedIDStr).toBytes()).toEqual( + new Uint8Array([ + 0x61, 0x76, 0x61, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ]), + ); + }); +}); diff --git a/src/serializable/fxs/common/id.ts b/src/serializable/fxs/common/id.ts new file mode 100644 index 000000000..5595ac16a --- /dev/null +++ b/src/serializable/fxs/common/id.ts @@ -0,0 +1,51 @@ +import { customInspectSymbol } from '../../../constants/node'; +import { base58check } from '../../../utils/base58'; +import { hexToBuffer, padLeft } from '../../../utils/buffer'; +import { bytesCompare } from '../../../utils/bytesCompare'; +import { serializable } from '../../common/types'; +import { Primitives } from '../../primitives/primatives'; +import { TypeSymbols } from '../../constants'; + +@serializable() +export class Id extends Primitives { + _type = TypeSymbols.Id; + constructor(private readonly idVal: Uint8Array) { + super(); + } + + static fromBytes(buf: Uint8Array): [Id, Uint8Array] { + return [new Id(buf.slice(0, 32)), buf.slice(32)]; + } + + static compare(id1: Id, id2: Id): number { + return bytesCompare(id1.toBytes(), id2.toBytes()); + } + + [customInspectSymbol](_, options: any) { + return options.stylize(this.toString(), 'string'); + } + + toBytes() { + return padLeft(this.idVal, 32); + } + + toJSON() { + return this.toString(); + } + + toString() { + return base58check.encode(this.toBytes()); + } + + static fromString(str: string) { + return Id.fromBytes(base58check.decode(str))[0]; + } + + static fromHex(hex: string): Id { + return new Id(hexToBuffer(hex)); + } + + value() { + return this.toString(); + } +} diff --git a/src/serializable/fxs/common/index.ts b/src/serializable/fxs/common/index.ts new file mode 100644 index 000000000..a654df3ec --- /dev/null +++ b/src/serializable/fxs/common/index.ts @@ -0,0 +1,5 @@ +import { Address } from './address'; +import { Id } from './id'; +import { NodeId } from './nodeId'; + +export { Address, Id, NodeId }; diff --git a/src/serializable/fxs/common/nodeId.spec.ts b/src/serializable/fxs/common/nodeId.spec.ts new file mode 100644 index 000000000..6a5d89e93 --- /dev/null +++ b/src/serializable/fxs/common/nodeId.spec.ts @@ -0,0 +1,6 @@ +import { testPVMCodec } from '../../../fixtures/codec'; +import { nodeId, nodeIdBytes } from '../../../fixtures/common'; +import { testSerialization } from '../../../fixtures/utils/serializable'; +import { NodeId } from './nodeId'; + +testSerialization('NodeId', NodeId, nodeId, nodeIdBytes, testPVMCodec); diff --git a/src/serializable/fxs/common/nodeId.ts b/src/serializable/fxs/common/nodeId.ts new file mode 100644 index 000000000..62542d86b --- /dev/null +++ b/src/serializable/fxs/common/nodeId.ts @@ -0,0 +1,50 @@ +import { customInspectSymbol } from '../../../constants/node'; +import { base58check } from '../../../utils/base58'; +import { hexToBuffer, padLeft } from '../../../utils/buffer'; +import { serializable } from '../../common/types'; +import { Primitives } from '../../primitives/primatives'; +import { TypeSymbols } from '../../constants'; + +export const NodeIDPrefix = 'NodeID-'; +@serializable() +export class NodeId extends Primitives { + _type = TypeSymbols.NodeId; + constructor(private readonly idVal: Uint8Array) { + super(); + } + + static fromBytes(buf: Uint8Array): [NodeId, Uint8Array] { + return [new NodeId(buf.slice(0, 20)), buf.slice(20)]; + } + + [customInspectSymbol](_, options: any) { + return options.stylize(this.toString(), 'string'); + } + + toBytes() { + return padLeft(this.idVal, 20); + } + + toJSON() { + return this.toString(); + } + + toString() { + return NodeIDPrefix + base58check.encode(this.toBytes()); + } + + static fromString(str: string) { + if (!str.includes(NodeIDPrefix)) { + throw new Error('ID is missing prefix'); + } + return this.fromBytes(base58check.decode(str.replace(NodeIDPrefix, '')))[0]; + } + + static fromHex(hex: string): NodeId { + return new NodeId(hexToBuffer(hex)); + } + + value() { + return this.toString(); + } +} diff --git a/src/serializable/fxs/nft/credential.ts b/src/serializable/fxs/nft/credential.ts new file mode 100644 index 000000000..c30a9df40 --- /dev/null +++ b/src/serializable/fxs/nft/credential.ts @@ -0,0 +1,6 @@ +import { Credential as SepkCredential } from '../secp256k1/credential'; +import { TypeSymbols } from '../../constants'; + +export class Credential extends SepkCredential { + _type = TypeSymbols.NftFxCredential; +} diff --git a/src/serializable/fxs/nft/index.ts b/src/serializable/fxs/nft/index.ts new file mode 100644 index 000000000..ec8679b59 --- /dev/null +++ b/src/serializable/fxs/nft/index.ts @@ -0,0 +1,23 @@ +import { Credential } from './credential'; +import { MintOperation } from './mintOperation'; +import { MintOutput } from './mintOutput'; +import { TransferOperation } from './transferOperation'; +import { TransferOutput } from './transferOutput'; + +// https://github.com/ava-labs/avalanchego/blob/master/vms/nftfx/fx.go +const TypeRegistry = Object.freeze([ + MintOutput, + TransferOutput, + MintOperation, + TransferOperation, + Credential, +]); + +export { + Credential, + MintOutput, + TransferOutput, + MintOperation, + TransferOperation, + TypeRegistry, +}; diff --git a/src/serializable/fxs/nft/mintOperation.spec.ts b/src/serializable/fxs/nft/mintOperation.spec.ts new file mode 100644 index 000000000..48c84a5ab --- /dev/null +++ b/src/serializable/fxs/nft/mintOperation.spec.ts @@ -0,0 +1,10 @@ +import { mintOperation, mintOperationBytes } from '../../../fixtures/nft'; +import { testSerialization } from '../../../fixtures/utils/serializable'; +import { MintOperation } from './mintOperation'; + +testSerialization( + 'MintOperation', + MintOperation, + mintOperation, + mintOperationBytes, +); diff --git a/src/serializable/fxs/nft/mintOperation.ts b/src/serializable/fxs/nft/mintOperation.ts new file mode 100644 index 000000000..8b51b5a9f --- /dev/null +++ b/src/serializable/fxs/nft/mintOperation.ts @@ -0,0 +1,38 @@ +import { serializable } from '../../common/types'; +import { Bytes, Int } from '../../primitives'; +import { pack, unpack } from '../../../utils/struct'; +import { Input, OutputOwnersList } from '../secp256k1'; +import { TypeSymbols } from '../../constants'; + +/** + * @see https://github.com/ava-labs/avalanchego/blob/master/vms/nftfx/mint_operation.go + * @see https://docs.avax.network/specs/avm-transaction-serialization#nft-mint-op + */ +@serializable() +export class MintOperation { + _type = TypeSymbols.NftFxMintOperation; + constructor( + private readonly input: Input, + private readonly groupId: Int, + private readonly payload: Bytes, + private readonly outputOwnerList: OutputOwnersList, + ) {} + + static fromBytes(bytes: Uint8Array): [MintOperation, Uint8Array] { + const [input, groupId, payload, outputOwnerList, remaining] = unpack( + bytes, + [Input, Int, Bytes, OutputOwnersList] as const, + ); + return [ + new MintOperation(input, groupId, payload, outputOwnerList), + remaining, + ]; + } + + toBytes(codec) { + return pack( + [this.input, this.groupId, this.payload, this.outputOwnerList], + codec, + ); + } +} diff --git a/src/serializable/fxs/nft/mintOutput.spec.ts b/src/serializable/fxs/nft/mintOutput.spec.ts new file mode 100644 index 000000000..77a93b1e8 --- /dev/null +++ b/src/serializable/fxs/nft/mintOutput.spec.ts @@ -0,0 +1,5 @@ +import { MintOutput } from '.'; +import { mintOutput, mintOutputBytes } from '../../../fixtures/nft'; +import { testSerialization } from '../../../fixtures/utils/serializable'; + +testSerialization('MintOutput', MintOutput, mintOutput, mintOutputBytes); diff --git a/src/serializable/fxs/nft/mintOutput.ts b/src/serializable/fxs/nft/mintOutput.ts new file mode 100644 index 000000000..2a4c7e218 --- /dev/null +++ b/src/serializable/fxs/nft/mintOutput.ts @@ -0,0 +1,33 @@ +import { serializable } from '../../common/types'; +import { Int } from '../../primitives'; +import { pack, unpack } from '../../../utils/struct'; +import { OutputOwners } from '../secp256k1'; +import { TypeSymbols } from '../../constants'; + +/** + * @see https://github.com/ava-labs/avalanchego/blob/master/vms/nftfx/mint_output.go + * @see https://docs.avax.network/specs/avm-transaction-serialization/#nft-mint-output + */ +@serializable() +export class MintOutput { + _type = TypeSymbols.NftFxMintOutput; + + constructor( + private readonly groupId: Int, + private readonly outputOwners: OutputOwners, + ) {} + + static fromBytes(bytes: Uint8Array, codec): [MintOutput, Uint8Array] { + const [groupId, owners, remaining] = unpack( + bytes, + [Int, OutputOwners] as const, + codec, + ); + + return [new MintOutput(groupId, owners), remaining]; + } + + toBytes(codec) { + return pack([this.groupId, this.outputOwners], codec); + } +} diff --git a/src/serializable/fxs/nft/transferOperation.spec.ts b/src/serializable/fxs/nft/transferOperation.spec.ts new file mode 100644 index 000000000..332ca6b6d --- /dev/null +++ b/src/serializable/fxs/nft/transferOperation.spec.ts @@ -0,0 +1,13 @@ +import { + transferOperation, + transferOperationBytes, +} from '../../../fixtures/nft'; +import { testSerialization } from '../../../fixtures/utils/serializable'; +import { TransferOperation } from './transferOperation'; + +testSerialization( + 'TransferOperation', + TransferOperation, + transferOperation, + transferOperationBytes, +); diff --git a/src/serializable/fxs/nft/transferOperation.ts b/src/serializable/fxs/nft/transferOperation.ts new file mode 100644 index 000000000..61c26de5b --- /dev/null +++ b/src/serializable/fxs/nft/transferOperation.ts @@ -0,0 +1,29 @@ +import { serializable } from '../../common/types'; +import { pack, unpack } from '../../../utils/struct'; +import { Input } from '../secp256k1'; +import { TransferOutput } from './transferOutput'; +import { TypeSymbols } from '../../constants'; + +/** + * https://docs.avax.network/specs/avm-transaction-serialization#nft-transfer-op + * + */ +@serializable() +export class TransferOperation { + _type = TypeSymbols.NftFxTransferOperation; + + constructor( + private readonly input: Input, + private readonly output: TransferOutput, + ) {} + + static fromBytes(bytes: Uint8Array): [TransferOperation, Uint8Array] { + const [input, output, remaining] = unpack(bytes, [Input, TransferOutput]); + + return [new TransferOperation(input, output), remaining]; + } + + toBytes(codec) { + return pack([this.input, this.output], codec); + } +} diff --git a/src/serializable/fxs/nft/transferOutput.spec.ts b/src/serializable/fxs/nft/transferOutput.spec.ts new file mode 100644 index 000000000..2e01da9a4 --- /dev/null +++ b/src/serializable/fxs/nft/transferOutput.spec.ts @@ -0,0 +1,10 @@ +import { TransferOutput } from '.'; +import { transferOutput, transferOutputBytes } from '../../../fixtures/nft'; +import { testSerialization } from '../../../fixtures/utils/serializable'; + +testSerialization( + 'TransferOutput', + TransferOutput, + transferOutput, + transferOutputBytes, +); diff --git a/src/serializable/fxs/nft/transferOutput.ts b/src/serializable/fxs/nft/transferOutput.ts new file mode 100644 index 000000000..a25e4094e --- /dev/null +++ b/src/serializable/fxs/nft/transferOutput.ts @@ -0,0 +1,34 @@ +import { serializable } from '../../common/types'; +import { Bytes, Int } from '../../primitives'; +import { pack, unpack } from '../../../utils/struct'; +import { OutputOwners } from '../secp256k1'; +import { TypeSymbols } from '../../constants'; + +/** + * @see https://github.com/ava-labs/avalanchego/blob/master/vms/nftfx/transfer_output.go + * @see https://docs.avax.network/specs/avm-transaction-serialization/#nft-transfer-output + */ +@serializable() +export class TransferOutput { + _type = TypeSymbols.NftFxTransferOutput; + + constructor( + public readonly groupId: Int, + public readonly payload: Bytes, + public readonly outputOwners: OutputOwners, + ) {} + + static fromBytes(bytes: Uint8Array): [TransferOutput, Uint8Array] { + const [groupId, payload, outputOwners, remaining] = unpack(bytes, [ + Int, + Bytes, + OutputOwners, + ] as const); + + return [new TransferOutput(groupId, payload, outputOwners), remaining]; + } + + toBytes(codec) { + return pack([this.groupId, this.payload, this.outputOwners], codec); + } +} diff --git a/src/serializable/fxs/secp256k1/credential.spec.ts b/src/serializable/fxs/secp256k1/credential.spec.ts new file mode 100644 index 000000000..05cd8d4d2 --- /dev/null +++ b/src/serializable/fxs/secp256k1/credential.spec.ts @@ -0,0 +1,5 @@ +import { credential, credentialBytes } from '../../../fixtures/secp256k1'; +import { testSerialization } from '../../../fixtures/utils/serializable'; +import { Credential } from './credential'; + +testSerialization('Credential', Credential, credential, credentialBytes); diff --git a/src/serializable/fxs/secp256k1/credential.ts b/src/serializable/fxs/secp256k1/credential.ts new file mode 100644 index 000000000..1b64cbfd1 --- /dev/null +++ b/src/serializable/fxs/secp256k1/credential.ts @@ -0,0 +1,45 @@ +import { packList, unpackList } from '../../../utils/serializeList'; +import type { Codec } from '../../codec'; +import { serializable } from '../../common/types'; +import { Signature } from './signature'; +import { TypeSymbols } from '../../constants'; + +/** + * @see https://docs.avax.network/specs/avm-transaction-serialization#secp256k1-credential + */ +@serializable() +export class Credential { + _type = TypeSymbols.Credential; + + constructor(private readonly signatures: Signature[]) {} + + static fromBytes(bytes: Uint8Array, codec: Codec): [Credential, Uint8Array] { + const [sigs, remaining] = unpackList(bytes, Signature, codec); + return [new Credential(sigs), remaining]; + } + + toJSON() { + return this.signatures; + } + + static fromJSON(credentialsStrings: string[]) { + return new Credential( + credentialsStrings.map((str) => Signature.fromJSON(str)), + ); + } + + setSignature(index: number, signature: Uint8Array) { + if (index >= this.signatures.length) { + throw new Error(`index ${index} is out of bounds for credential`); + } + this.signatures[index] = new Signature(signature); + } + + getSignatures() { + return this.signatures.map((sig) => sig.toString()); + } + + toBytes(codec) { + return packList(this.signatures, codec); + } +} diff --git a/src/serializable/fxs/secp256k1/index.ts b/src/serializable/fxs/secp256k1/index.ts new file mode 100644 index 000000000..6d676edcd --- /dev/null +++ b/src/serializable/fxs/secp256k1/index.ts @@ -0,0 +1,31 @@ +import { Credential } from './credential'; +import { Input } from './input'; +import { MintOperation } from './mintOperation'; +import { MintOutput } from './mintOutput'; +import { OutputOwners } from './outputOwners'; +import { OutputOwnersList } from './outputOwnersList'; +import { Signature } from './signature'; +import { TransferInput } from './transferInput'; +import { TransferOutput } from './transferOutput'; + +// https://github.com/ava-labs/avalanchego/blob/master/vms/secp256k1fx/fx.go +const TypeRegistry = Object.freeze([ + TransferInput, + MintOutput, + TransferOutput, + MintOperation, + Credential, +]); + +export { + Input, + MintOperation, + MintOutput, + OutputOwners, + OutputOwnersList, + TransferInput, + TransferOutput, + Credential, + Signature, + TypeRegistry, +}; diff --git a/src/serializable/fxs/secp256k1/input.spec.ts b/src/serializable/fxs/secp256k1/input.spec.ts new file mode 100644 index 000000000..25d3f4550 --- /dev/null +++ b/src/serializable/fxs/secp256k1/input.spec.ts @@ -0,0 +1,5 @@ +import { Input } from '.'; +import { input, inputBytes } from '../../../fixtures/secp256k1'; +import { testSerialization } from '../../../fixtures/utils/serializable'; + +testSerialization('Input', Input, input, inputBytes); diff --git a/src/serializable/fxs/secp256k1/input.ts b/src/serializable/fxs/secp256k1/input.ts new file mode 100644 index 000000000..b31610399 --- /dev/null +++ b/src/serializable/fxs/secp256k1/input.ts @@ -0,0 +1,35 @@ +import { packList, toListStruct } from '../../../utils/serializeList'; +import { unpack } from '../../../utils/struct'; +import { serializable } from '../../common/types'; +import { Int } from '../../primitives'; +import { TypeSymbols } from '../../constants'; + +/** + * @see https://github.com/ava-labs/avalanchego/blob/master/vms/secp256k1fx/input.go + * @see https://docs.avax.network/specs/coreth-atomic-transaction-serialization/#secp256k1-transfer-input + * @see https://docs.avax.network/specs/avm-transaction-serialization/#secp256k1-transfer-input + * @see https://docs.avax.network/specs/platform-transaction-serialization/#secp256k1-transfer-input + */ +@serializable() +export class Input { + _type = TypeSymbols.Input; + + constructor(private readonly sigIndices: Int[]) {} + + static fromNative(sigIndicies: number[]) { + return new Input(sigIndicies.map((i) => new Int(i))); + } + + static fromBytes(bytes: Uint8Array): [Input, Uint8Array] { + const [sigIndices, remaining] = unpack(bytes, [toListStruct(Int)]); + return [new Input(sigIndices), remaining]; + } + + values() { + return this.sigIndices.map((i) => i.value()); + } + + toBytes(codec) { + return packList(this.sigIndices, codec); + } +} diff --git a/src/serializable/fxs/secp256k1/mintOperation.spec.ts b/src/serializable/fxs/secp256k1/mintOperation.spec.ts new file mode 100644 index 000000000..296198308 --- /dev/null +++ b/src/serializable/fxs/secp256k1/mintOperation.spec.ts @@ -0,0 +1,10 @@ +import { MintOperation } from '.'; +import { mintOperation, mintOperationBytes } from '../../../fixtures/secp256k1'; +import { testSerialization } from '../../../fixtures/utils/serializable'; + +testSerialization( + 'MintOperation', + MintOperation, + mintOperation, + mintOperationBytes, +); diff --git a/src/serializable/fxs/secp256k1/mintOperation.ts b/src/serializable/fxs/secp256k1/mintOperation.ts new file mode 100644 index 000000000..b380fe231 --- /dev/null +++ b/src/serializable/fxs/secp256k1/mintOperation.ts @@ -0,0 +1,40 @@ +import { concatBytes } from '../../../utils/buffer'; +import { unpack } from '../../../utils/struct'; +import { serializable } from '../../common/types'; +import { Input } from './input'; +import { MintOutput } from './mintOutput'; +import { TransferOutput } from './transferOutput'; +import { TypeSymbols } from '../../constants'; + +/** + * @see https://github.com/ava-labs/avalanchego/blob/master/vms/secp256k1fx/mint_operation.go + * @see https://docs.avax.network/specs/avm-transaction-serialization#secp256k1-mint-operation + */ +@serializable() +export class MintOperation { + _type = TypeSymbols.SecpMintOperation; + + constructor( + private readonly input: Input, + private readonly mintOutput: MintOutput, + private readonly transferOutput: TransferOutput, + ) {} + + static fromBytes(bytes: Uint8Array): [MintOperation, Uint8Array] { + const [input, mintOutput, transferOutput, remaining] = unpack(bytes, [ + Input, + MintOutput, + TransferOutput, + ] as const); + + return [new MintOperation(input, mintOutput, transferOutput), remaining]; + } + + toBytes(codec) { + return concatBytes( + this.input.toBytes(codec), + this.mintOutput.toBytes(codec), + this.transferOutput.toBytes(codec), + ); + } +} diff --git a/src/serializable/fxs/secp256k1/mintOutput.spec.ts b/src/serializable/fxs/secp256k1/mintOutput.spec.ts new file mode 100644 index 000000000..4720d2449 --- /dev/null +++ b/src/serializable/fxs/secp256k1/mintOutput.spec.ts @@ -0,0 +1,5 @@ +import { MintOutput } from '.'; +import { mintOutput, mintOutputBytes } from '../../../fixtures/secp256k1'; +import { testSerialization } from '../../../fixtures/utils/serializable'; + +testSerialization('MintOutput', MintOutput, mintOutput, mintOutputBytes); diff --git a/src/serializable/fxs/secp256k1/mintOutput.ts b/src/serializable/fxs/secp256k1/mintOutput.ts new file mode 100644 index 000000000..827044a98 --- /dev/null +++ b/src/serializable/fxs/secp256k1/mintOutput.ts @@ -0,0 +1,25 @@ +import { serializable } from '../../common/types'; +import { OutputOwners } from './outputOwners'; +import { TypeSymbols } from '../../constants'; + +/** + * @see https://github.com/ava-labs/avalanchego/blob/master/vms/secp256k1fx/mint_output.go + * @see https://docs.avax.network/specs/avm-transaction-serialization/#secp256k1-mint-output + */ +@serializable() +export class MintOutput { + _type = TypeSymbols.SecpMintOutput; + + constructor(private readonly outputOwners: OutputOwners) {} + + static fromBytes(bytes: Uint8Array, codec): [MintOutput, Uint8Array] { + let owners: OutputOwners; + [owners, bytes] = OutputOwners.fromBytes(bytes, codec); + + return [new MintOutput(owners), bytes]; + } + + toBytes(codec) { + return this.outputOwners.toBytes(codec); + } +} diff --git a/src/serializable/fxs/secp256k1/outputOwners.spec.ts b/src/serializable/fxs/secp256k1/outputOwners.spec.ts new file mode 100644 index 000000000..38de3ddad --- /dev/null +++ b/src/serializable/fxs/secp256k1/outputOwners.spec.ts @@ -0,0 +1,5 @@ +import { OutputOwners } from '.'; +import { outputOwner, outputOwnerBytes } from '../../../fixtures/secp256k1'; +import { testSerialization } from '../../../fixtures/utils/serializable'; + +testSerialization('OutputOwners', OutputOwners, outputOwner, outputOwnerBytes); diff --git a/src/serializable/fxs/secp256k1/outputOwners.ts b/src/serializable/fxs/secp256k1/outputOwners.ts new file mode 100644 index 000000000..560209d27 --- /dev/null +++ b/src/serializable/fxs/secp256k1/outputOwners.ts @@ -0,0 +1,60 @@ +import { concatBytes } from '@noble/hashes/utils'; +import { addressesFromBytes } from '../../../utils/addressesFromBytes'; +import { packList, toListStruct } from '../../../utils/serializeList'; +import { pack, unpack } from '../../../utils/struct'; +import { serializable } from '../../common/types'; +import { BigIntPr, Int } from '../../primitives'; +import { Address } from '../common/address'; +import { TypeSymbols } from '../../constants'; + +/** + * @see https://github.com/ava-labs/avalanchego/blob/master/vms/secp256k1fx/output_owners.go + * @see https://docs.avax.network/specs/platform-transaction-serialization/#secp256k1-output-owners-output + */ +@serializable() +export class OutputOwners { + _type = TypeSymbols.OutputOwners; + + constructor( + public readonly locktime: BigIntPr, + public readonly threshold: Int, + public readonly addrs: Address[], + ) {} + + static fromNative(address: Uint8Array[], locktime = 0n, threshold = 1) { + return new OutputOwners( + new BigIntPr(locktime), + new Int(threshold), + addressesFromBytes(address), + ); + } + + static fromBytes(bytes: Uint8Array, codec): [OutputOwners, Uint8Array] { + const [locktime, threshold, addresses, remaining] = unpack( + bytes, + [BigIntPr, Int, toListStruct(Address)], + codec, + ); + return [new OutputOwners(locktime, threshold, addresses), remaining]; + } + + toBytes(codec) { + return concatBytes( + pack([this.locktime, this.threshold], codec), + packList(this.addrs, codec), + ); + } + + equals(other: OutputOwners) { + return ( + this.locktime.value() === other.locktime.value() && + this.threshold.value() === other.threshold.value() && + this.addrs.length === other.addrs.length && + this.addrs.every((thisAddr, idx) => { + const thisString = thisAddr.value(); + const otherString = other.addrs[idx].value(); + return thisString === otherString; + }) + ); + } +} diff --git a/src/serializable/fxs/secp256k1/outputOwnersList.spec.ts b/src/serializable/fxs/secp256k1/outputOwnersList.spec.ts new file mode 100644 index 000000000..20239bb5c --- /dev/null +++ b/src/serializable/fxs/secp256k1/outputOwnersList.spec.ts @@ -0,0 +1,13 @@ +import { + outputOwnersList, + outputOwnersListBytes, +} from '../../../fixtures/secp256k1'; +import { testSerialization } from '../../../fixtures/utils/serializable'; +import { OutputOwnersList } from './outputOwnersList'; + +testSerialization( + 'OutputOwnersList', + OutputOwnersList, + outputOwnersList, + outputOwnersListBytes, +); diff --git a/src/serializable/fxs/secp256k1/outputOwnersList.ts b/src/serializable/fxs/secp256k1/outputOwnersList.ts new file mode 100644 index 000000000..e2243aa32 --- /dev/null +++ b/src/serializable/fxs/secp256k1/outputOwnersList.ts @@ -0,0 +1,24 @@ +import { serializable } from '../../common/types'; +import { packList, unpackList } from '../../../utils/serializeList'; +import { OutputOwners } from './outputOwners'; +import { TypeSymbols } from '../../constants'; + +/** + * @see https://github.com/ava-labs/avalanchego/blob/master/vms/secp256k1fx/output_owners.go + * @see https://docs.avax.network/specs/platform-transaction-serialization/#secp256k1-output-owners-output + */ +@serializable() +export class OutputOwnersList { + _type = TypeSymbols.OutputOwnersList; + + constructor(private readonly outputOwners: OutputOwners[]) {} + + static fromBytes(bytes: Uint8Array, codec): [OutputOwnersList, Uint8Array] { + const [owners, remaining] = unpackList(bytes, OutputOwners, codec); + return [new OutputOwnersList(owners), remaining]; + } + + toBytes(codec) { + return packList(this.outputOwners, codec); + } +} diff --git a/src/serializable/fxs/secp256k1/signature.spec.ts b/src/serializable/fxs/secp256k1/signature.spec.ts new file mode 100644 index 000000000..5c4265d09 --- /dev/null +++ b/src/serializable/fxs/secp256k1/signature.spec.ts @@ -0,0 +1,5 @@ +import { signature, signatureBytes } from '../../../fixtures/secp256k1'; +import { testSerialization } from '../../../fixtures/utils/serializable'; +import { Signature } from './signature'; + +testSerialization('Signature', Signature, signature, signatureBytes); diff --git a/src/serializable/fxs/secp256k1/signature.ts b/src/serializable/fxs/secp256k1/signature.ts new file mode 100644 index 000000000..a0442f021 --- /dev/null +++ b/src/serializable/fxs/secp256k1/signature.ts @@ -0,0 +1,48 @@ +import { bytesToHex } from '@noble/hashes/utils'; +import { hexToBytes } from 'micro-eth-signer'; +import { customInspectSymbol } from '../../../constants/node'; +import { bufferToHex, padLeft } from '../../../utils/buffer'; +import { serializable } from '../../common/types'; +import { TypeSymbols } from '../../constants'; + +/** + * @see https://docs.avax.network/specs/avm-transaction-serialization#secp256k1-credential + */ +export const SepkSignatureLength = 65; +@serializable() +export class Signature { + _type = TypeSymbols.Signature; + + constructor(private readonly sig: Uint8Array) { + if (sig.length !== SepkSignatureLength) { + throw new Error('incorrect number of bytes for signature'); + } + } + + toJSON() { + return bytesToHex(this.sig); + } + + static fromJSON(jsonStr: string) { + return new Signature(hexToBytes(jsonStr)); + } + + static fromBytes(bytes: Uint8Array): [Signature, Uint8Array] { + return [ + new Signature(bytes.slice(0, SepkSignatureLength)), + bytes.slice(SepkSignatureLength), + ]; + } + + [customInspectSymbol](_, options: any) { + return options.stylize(this.toString(), 'string'); + } + + toString() { + return bufferToHex(this.sig); + } + + toBytes() { + return padLeft(this.sig, SepkSignatureLength); + } +} diff --git a/src/serializable/fxs/secp256k1/transferInput.spec.ts b/src/serializable/fxs/secp256k1/transferInput.spec.ts new file mode 100644 index 000000000..a9cbce099 --- /dev/null +++ b/src/serializable/fxs/secp256k1/transferInput.spec.ts @@ -0,0 +1,10 @@ +import { TransferInput } from '.'; +import { transferInput, transferInputBytes } from '../../../fixtures/secp256k1'; +import { testSerialization } from '../../../fixtures/utils/serializable'; + +testSerialization( + 'TransferInput', + TransferInput, + transferInput, + transferInputBytes, +); diff --git a/src/serializable/fxs/secp256k1/transferInput.ts b/src/serializable/fxs/secp256k1/transferInput.ts new file mode 100644 index 000000000..41a358360 --- /dev/null +++ b/src/serializable/fxs/secp256k1/transferInput.ts @@ -0,0 +1,42 @@ +import { pack, unpack } from '../../../utils/struct'; +import type { Amounter } from '../../common/types'; +import { serializable } from '../../common/types'; +import { BigIntPr } from '../../primitives'; +import { Input } from './input'; +import { TypeSymbols } from '../../constants'; + +/** + * @see https://github.com/ava-labs/avalanchego/blob/master/vms/secp256k1fx/transfer_input.go + * @see https://docs.avax.network/specs/coreth-atomic-transaction-serialization/#secp256k1-transfer-input + * @see https://docs.avax.network/specs/avm-transaction-serialization/#secp256k1-transfer-input + * @see https://docs.avax.network/specs/platform-transaction-serialization/#secp256k1-transfer-input + */ +@serializable() +export class TransferInput implements Amounter { + _type = TypeSymbols.TransferInput; + + constructor(private readonly amt: BigIntPr, private readonly input: Input) {} + + static fromBytes(bytes: Uint8Array): [TransferInput, Uint8Array] { + const [amt, input, remaining] = unpack(bytes, [BigIntPr, Input]); + return [new TransferInput(amt, input), remaining]; + } + + static fromNative(amount: bigint, sigIndicies: number[]) { + return new TransferInput( + new BigIntPr(amount), + Input.fromNative(sigIndicies), + ); + } + + sigIndicies() { + return this.input.values(); + } + + amount() { + return this.amt.value(); + } + toBytes(codec) { + return pack([this.amt, this.input], codec); + } +} diff --git a/src/serializable/fxs/secp256k1/transferOutput.spec.ts b/src/serializable/fxs/secp256k1/transferOutput.spec.ts new file mode 100644 index 000000000..67e15fe34 --- /dev/null +++ b/src/serializable/fxs/secp256k1/transferOutput.spec.ts @@ -0,0 +1,13 @@ +import { TransferOutput } from '.'; +import { + transferOutput, + transferOutputBytes, +} from '../../../fixtures/secp256k1'; +import { testSerialization } from '../../../fixtures/utils/serializable'; + +testSerialization( + 'TransferOutput', + TransferOutput, + transferOutput, + transferOutputBytes, +); diff --git a/src/serializable/fxs/secp256k1/transferOutput.ts b/src/serializable/fxs/secp256k1/transferOutput.ts new file mode 100644 index 000000000..f12f0772a --- /dev/null +++ b/src/serializable/fxs/secp256k1/transferOutput.ts @@ -0,0 +1,48 @@ +import { pack, unpack } from '../../../utils/struct'; +import type { Amounter } from '../../common/types'; +import { serializable } from '../../common/types'; +import { BigIntPr } from '../../primitives'; +import { OutputOwners } from './outputOwners'; +import { TypeSymbols } from '../../constants'; + +/** + * @see https://github.com/ava-labs/avalanchego/blob/master/vms/secp256k1fx/transfer_output.go + * @see https://docs.avax.network/specs/coreth-atomic-transaction-serialization/#secp256k1-transfer-output + * @see https://docs.avax.network/specs/avm-transaction-serialization/#secp256k1-transfer-output + * @see https://docs.avax.network/specs/platform-transaction-serialization/#secp256k1-transfer-output + */ +@serializable() +export class TransferOutput implements Amounter { + readonly _type = TypeSymbols.TransferOutput; + + constructor( + public readonly amt: BigIntPr, + public readonly outputOwners: OutputOwners, + ) {} + + amount() { + return this.amt.value(); + } + + getLocktime() { + return this.outputOwners.locktime.value(); + } + + getOwners() { + return this.outputOwners.addrs.map((addr) => addr.toBytes()); + } + + getThreshold() { + return this.outputOwners.threshold.value(); + } + + static fromBytes(bytes: Uint8Array): [TransferOutput, Uint8Array] { + const [amt, owners, remaining] = unpack(bytes, [BigIntPr, OutputOwners]); + + return [new TransferOutput(amt, owners), remaining]; + } + + toBytes(codec) { + return pack([this.amt, this.outputOwners], codec); + } +} diff --git a/src/serializable/index.ts b/src/serializable/index.ts new file mode 100644 index 000000000..b4b3a1bd3 --- /dev/null +++ b/src/serializable/index.ts @@ -0,0 +1,10 @@ +export * as avaxSerial from './avax'; +export { TransferableOutput } from './avax/transferableOutput'; +export { TransferableInput } from './avax/transferableInput'; +export * as avmSerial from './avm'; +export * as evmSerial from './evm'; +export * from './fxs/secp256k1'; +export * from './fxs/common'; +export * as pvmSerial from './pvm'; +export * from './primitives'; +export * from './constants'; diff --git a/src/serializable/primitives/bigintpr.spec.ts b/src/serializable/primitives/bigintpr.spec.ts new file mode 100644 index 000000000..f10641986 --- /dev/null +++ b/src/serializable/primitives/bigintpr.spec.ts @@ -0,0 +1,5 @@ +import { bigIntPr, bigIntPrBytes } from '../../fixtures/primitives'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { BigIntPr } from './bigintpr'; + +testSerialization('Bigintpr', BigIntPr, bigIntPr, bigIntPrBytes); diff --git a/src/serializable/primitives/bigintpr.ts b/src/serializable/primitives/bigintpr.ts new file mode 100644 index 000000000..5d439e821 --- /dev/null +++ b/src/serializable/primitives/bigintpr.ts @@ -0,0 +1,34 @@ +import { customInspectSymbol } from '../../constants/node'; +import { bufferToBigInt, hexToBuffer, padLeft } from '../../utils/buffer'; +import { serializable } from '../common/types'; +import { Primitives } from './primatives'; +import { TypeSymbols } from '../constants'; + +// typescript doesn't like BigInt as a class name +@serializable() +export class BigIntPr extends Primitives { + _type = TypeSymbols.BigIntPr; + constructor(private readonly bigint: bigint) { + super(); + } + + [customInspectSymbol]() { + return this.bigint; + } + + static fromBytes(buf: Uint8Array): [BigIntPr, Uint8Array] { + return [new BigIntPr(bufferToBigInt(buf.slice(0, 8))), buf.slice(8)]; + } + + toJSON() { + return this.bigint.toString(); + } + + toBytes() { + return padLeft(hexToBuffer(this.bigint.toString(16)), 8); + } + + value(): bigint { + return this.bigint; + } +} diff --git a/src/serializable/primitives/byte.ts b/src/serializable/primitives/byte.ts new file mode 100644 index 000000000..9b98d0f6a --- /dev/null +++ b/src/serializable/primitives/byte.ts @@ -0,0 +1,24 @@ +import { bufferToHex } from '../../utils/buffer'; +import { serializable } from '../common/types'; +import { Primitives } from './primatives'; +import { TypeSymbols } from '../constants'; + +@serializable() +export class Byte extends Primitives { + _type = TypeSymbols.Byte; + constructor(private readonly byte: Uint8Array) { + super(); + } + + static fromBytes(buf: Uint8Array): [Byte, Uint8Array] { + return [new Byte(buf.slice(0, 1)), buf.slice(1)]; + } + + toJSON() { + return bufferToHex(this.byte); + } + + toBytes() { + return this.byte; + } +} diff --git a/src/serializable/primitives/bytes.spec.ts b/src/serializable/primitives/bytes.spec.ts new file mode 100644 index 000000000..93d2f5e4d --- /dev/null +++ b/src/serializable/primitives/bytes.spec.ts @@ -0,0 +1,5 @@ +import { bytes, bytesBytes } from '../../fixtures/primitives'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { Bytes } from './bytes'; + +testSerialization('Bytes', Bytes, bytes, bytesBytes); diff --git a/src/serializable/primitives/bytes.ts b/src/serializable/primitives/bytes.ts new file mode 100644 index 000000000..7f8362f91 --- /dev/null +++ b/src/serializable/primitives/bytes.ts @@ -0,0 +1,36 @@ +import { bytesToString } from '@scure/base'; +import { bytesForInt } from '../../fixtures/utils/bytesFor'; +import { bufferToHex, concatBytes } from '../../utils/buffer'; +import { serializable } from '../common/types'; +import { Int } from './int'; +import { Primitives } from './primatives'; +import { TypeSymbols } from '../constants'; + +@serializable() +export class Bytes extends Primitives { + _type = TypeSymbols.Bytes; + constructor(private readonly bytes: Uint8Array) { + super(); + } + + toString(encoding: 'utf8' | 'hex' = 'utf8') { + return bytesToString(encoding, this.bytes); + } + + toJSON() { + return bufferToHex(this.bytes); + } + + static fromBytes(buf: Uint8Array): [Bytes, Uint8Array] { + const [len, remaining] = Int.fromBytes(buf); + + return [ + new Bytes(remaining.slice(0, len.value())), + remaining.slice(len.value()), + ]; + } + + toBytes() { + return concatBytes(bytesForInt(this.bytes.length), this.bytes); + } +} diff --git a/src/serializable/primitives/index.ts b/src/serializable/primitives/index.ts new file mode 100644 index 000000000..b685df0b2 --- /dev/null +++ b/src/serializable/primitives/index.ts @@ -0,0 +1,8 @@ +import { BigIntPr } from './bigintpr'; +import { Byte } from './byte'; +import { Bytes } from './bytes'; +import { Int } from './int'; +import { Short } from './short'; +import { Stringpr } from './stringpr'; + +export { BigIntPr, Bytes, Int, Byte, Short, Stringpr }; diff --git a/src/serializable/primitives/int.spec.ts b/src/serializable/primitives/int.spec.ts new file mode 100644 index 000000000..4fe2b666a --- /dev/null +++ b/src/serializable/primitives/int.spec.ts @@ -0,0 +1,5 @@ +import { int, intBytes } from '../../fixtures/primitives'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { Int } from './int'; + +testSerialization('Int', Int, int, intBytes); diff --git a/src/serializable/primitives/int.ts b/src/serializable/primitives/int.ts new file mode 100644 index 000000000..775630b40 --- /dev/null +++ b/src/serializable/primitives/int.ts @@ -0,0 +1,33 @@ +import { customInspectSymbol } from '../../constants/node'; +import { bufferToNumber, hexToBuffer, padLeft } from '../../utils/buffer'; +import { serializable } from '../common/types'; +import { Primitives } from './primatives'; +import { TypeSymbols } from '../constants'; + +@serializable() +export class Int extends Primitives { + _type = TypeSymbols.Int; + constructor(private readonly int: number) { + super(); + } + + static fromBytes(buf: Uint8Array): [Int, Uint8Array] { + return [new Int(bufferToNumber(buf.slice(0, 4))), buf.slice(4)]; + } + + [customInspectSymbol]() { + return this.value(); + } + + toJSON() { + return this.int; + } + + toBytes() { + return padLeft(hexToBuffer(this.int.toString(16)), 4); + } + + value() { + return this.int; + } +} diff --git a/src/serializable/primitives/primatives.ts b/src/serializable/primitives/primatives.ts new file mode 100644 index 000000000..ba9b8f152 --- /dev/null +++ b/src/serializable/primitives/primatives.ts @@ -0,0 +1,3 @@ +export abstract class Primitives { + abstract toJSON(): any; +} diff --git a/src/serializable/primitives/short.spec.ts b/src/serializable/primitives/short.spec.ts new file mode 100644 index 000000000..fb2472b72 --- /dev/null +++ b/src/serializable/primitives/short.spec.ts @@ -0,0 +1,5 @@ +import { short, shortBytes } from '../../fixtures/primitives'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { Short } from './short'; + +testSerialization('Short', Short, short, shortBytes); diff --git a/src/serializable/primitives/short.ts b/src/serializable/primitives/short.ts new file mode 100644 index 000000000..6662442e1 --- /dev/null +++ b/src/serializable/primitives/short.ts @@ -0,0 +1,28 @@ +import { bufferToNumber, hexToBuffer, padLeft } from '../../utils/buffer'; +import { serializable } from '../common/types'; +import { Primitives } from './primatives'; +import { TypeSymbols } from '../constants'; + +@serializable() +export class Short extends Primitives { + _type = TypeSymbols.Short; + constructor(private readonly short: number) { + super(); + } + + static fromBytes(buf: Uint8Array): [Short, Uint8Array] { + return [new Short(bufferToNumber(buf.slice(0, 2))), buf.slice(2)]; + } + + toJSON() { + return this.short.toString(); + } + + toBytes() { + return padLeft(hexToBuffer(this.short.toString(16)), 2); + } + + value() { + return this.short; + } +} diff --git a/src/serializable/primitives/stringpr.spec.ts b/src/serializable/primitives/stringpr.spec.ts new file mode 100644 index 000000000..a6e497e15 --- /dev/null +++ b/src/serializable/primitives/stringpr.spec.ts @@ -0,0 +1,5 @@ +import { stringPr, stringPrBytes } from '../../fixtures/primitives'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { Stringpr } from './stringpr'; + +testSerialization('Stringpr', Stringpr, stringPr, stringPrBytes); diff --git a/src/serializable/primitives/stringpr.ts b/src/serializable/primitives/stringpr.ts new file mode 100644 index 000000000..3e8945d52 --- /dev/null +++ b/src/serializable/primitives/stringpr.ts @@ -0,0 +1,38 @@ +import { concatBytes, hexToBuffer, padLeft } from '../../utils/buffer'; +import { serializable } from '../common/types'; +import { Primitives } from './primatives'; +import { Short } from './short'; +import { TypeSymbols } from '../constants'; + +@serializable() +export class Stringpr extends Primitives { + _type = TypeSymbols.StringPr; + constructor(private readonly string: string) { + super(); + } + + static fromBytes(buf: Uint8Array): [Stringpr, Uint8Array] { + const [length, remaining] = Short.fromBytes(buf); + return [ + new Stringpr( + new TextDecoder().decode(remaining.slice(0, length.value())), + ), + remaining.slice(length.value()), + ]; + } + + toJSON() { + return this.string; + } + + toBytes() { + return concatBytes( + padLeft(hexToBuffer(this.string.length.toString(16)), 2), + new TextEncoder().encode(this.string), + ); + } + + value() { + return this.string; + } +} diff --git a/src/serializable/pvm/abstractSubnetTx.ts b/src/serializable/pvm/abstractSubnetTx.ts new file mode 100644 index 000000000..261d922d6 --- /dev/null +++ b/src/serializable/pvm/abstractSubnetTx.ts @@ -0,0 +1,23 @@ +import type { Serializable } from '../common/types'; +import type { Id } from '../fxs/common'; +import type { Input } from '../fxs/secp256k1'; +import { PVMTx } from './abstractTx'; + +export abstract class AbstractSubnetTx extends PVMTx { + abstract subnetAuth: Serializable; + + abstract getSubnetID(): Id; + + getSubnetAuth() { + return this.subnetAuth as Input; + } + + getSigIndices(): number[][] { + return [ + ...this.getInputs().map((input) => { + return input.sigIndicies(); + }), + this.getSubnetAuth().values(), + ].filter((indicies): indicies is number[] => indicies !== undefined); + } +} diff --git a/src/serializable/pvm/abstractTx.ts b/src/serializable/pvm/abstractTx.ts new file mode 100644 index 000000000..25f000a28 --- /dev/null +++ b/src/serializable/pvm/abstractTx.ts @@ -0,0 +1,6 @@ +import { AvaxTx } from '../avax/avaxTx'; +import { PVM } from '../constants'; + +export abstract class PVMTx extends AvaxTx { + vm = PVM; +} diff --git a/src/serializable/pvm/addDelegatorTx.spec.ts b/src/serializable/pvm/addDelegatorTx.spec.ts new file mode 100644 index 000000000..c2e193462 --- /dev/null +++ b/src/serializable/pvm/addDelegatorTx.spec.ts @@ -0,0 +1,12 @@ +import { testPVMCodec } from '../../fixtures/codec'; +import { addDelegatorTx, addDelegatorTxBytes } from '../../fixtures/pvm'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { AddDelegatorTx } from './addDelegatorTx'; + +testSerialization( + 'AddDelegatorTx', + AddDelegatorTx, + addDelegatorTx, + addDelegatorTxBytes, + testPVMCodec, +); diff --git a/src/serializable/pvm/addDelegatorTx.ts b/src/serializable/pvm/addDelegatorTx.ts new file mode 100644 index 000000000..393e5e09d --- /dev/null +++ b/src/serializable/pvm/addDelegatorTx.ts @@ -0,0 +1,54 @@ +import { concatBytes } from '../../utils/buffer'; +import { toListStruct } from '../../utils/serializeList'; +import { pack, unpack } from '../../utils/struct'; +import { BaseTx } from '../avax/baseTx'; +import { TransferableOutput } from '../avax/transferableOutput'; +import { Codec } from '../codec/codec'; +import type { Serializable } from '../common/types'; +import { serializable } from '../common/types'; +import { PVMTx } from './abstractTx'; +import { Validator } from './validator'; +import type { OutputOwners } from '../fxs/secp256k1'; +import { TypeSymbols } from '../constants'; + +/** + * @deprecated since {@link https://github.com/avalanche-foundation/ACPs/blob/main/ACPs/62-disable-addvalidatortx-and-adddelegatortx.md|Durango-upgrade} + * @see https://docs.avax.network/specs/platform-transaction-serialization#unsigned-add-delegator-tx + */ +@serializable() +export class AddDelegatorTx extends PVMTx { + _type = TypeSymbols.AddDelegatorTx; + + constructor( + public readonly baseTx: BaseTx, + public readonly validator: Validator, + public readonly stake: TransferableOutput[], + public readonly rewardsOwner: Serializable, + ) { + super(); + } + + getRewardsOwner() { + return this.rewardsOwner as OutputOwners; + } + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [AddDelegatorTx, Uint8Array] { + const [baseTx, validator, stake, rewardsOwner, rest] = unpack( + bytes, + [BaseTx, Validator, toListStruct(TransferableOutput), Codec], + codec, + ); + + return [new AddDelegatorTx(baseTx, validator, stake, rewardsOwner), rest]; + } + + toBytes(codec: Codec) { + return concatBytes( + pack([this.baseTx, this.validator, this.stake], codec), + codec.PackPrefix(this.rewardsOwner), + ); + } +} diff --git a/src/serializable/pvm/addPermissionlessDelegatorTx.spec.ts b/src/serializable/pvm/addPermissionlessDelegatorTx.spec.ts new file mode 100644 index 000000000..75eb641be --- /dev/null +++ b/src/serializable/pvm/addPermissionlessDelegatorTx.spec.ts @@ -0,0 +1,15 @@ +import { testPVMCodec } from '../../fixtures/codec'; +import { + addPermissionlessDelegatorTx, + addPermissionlessDelegatorTxBytes, +} from '../../fixtures/pvm'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { AddPermissionlessDelegatorTx } from './addPermissionlessDelegatorTx'; + +testSerialization( + 'AddPermissionlessDelegatorTx', + AddPermissionlessDelegatorTx, + addPermissionlessDelegatorTx, + addPermissionlessDelegatorTxBytes, + testPVMCodec, +); diff --git a/src/serializable/pvm/addPermissionlessDelegatorTx.ts b/src/serializable/pvm/addPermissionlessDelegatorTx.ts new file mode 100644 index 000000000..5be3a282f --- /dev/null +++ b/src/serializable/pvm/addPermissionlessDelegatorTx.ts @@ -0,0 +1,63 @@ +import { PVMTx } from './abstractTx'; +import { BaseTx } from '../avax/baseTx'; +import { TransferableOutput } from '../avax/transferableOutput'; +import type { Serializable } from '../common/types'; +import { serializable } from '../common/types'; +import { SubnetValidator } from './subnetValidator'; +import { Codec } from '../codec'; +import { concatBytes } from '../../utils/buffer'; +import { pack, unpack } from '../../utils/struct'; +import { packList, toListStruct } from '../../utils/serializeList'; +import type { OutputOwners } from '../fxs/secp256k1'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://docs.avax.network/specs/platform-transaction-serialization#unsigned-add-permissionless-delegator-tx + */ +@serializable() +export class AddPermissionlessDelegatorTx extends PVMTx { + _type = TypeSymbols.AddPermissionlessDelegatorTx; + + constructor( + public readonly baseTx: BaseTx, + public readonly subnetValidator: SubnetValidator, + public readonly stake: TransferableOutput[], + public readonly delegatorRewardsOwner: Serializable, + ) { + super(); + } + + getDelegatorRewardsOwner() { + return this.delegatorRewardsOwner as OutputOwners; + } + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [AddPermissionlessDelegatorTx, Uint8Array] { + const [baseTx, subnetValidator, stakeOuts, delegatorRewardsOwner, rest] = + unpack( + bytes, + [BaseTx, SubnetValidator, toListStruct(TransferableOutput), Codec], + codec, + ); + + return [ + new AddPermissionlessDelegatorTx( + baseTx, + subnetValidator, + stakeOuts, + delegatorRewardsOwner, + ), + rest, + ]; + } + + toBytes(codec: Codec): Uint8Array { + return concatBytes( + pack([this.baseTx, this.subnetValidator], codec), + packList(this.stake, codec), + codec.PackPrefix(this.delegatorRewardsOwner), + ); + } +} diff --git a/src/serializable/pvm/addPermissionlessValidatorTx.spec.ts b/src/serializable/pvm/addPermissionlessValidatorTx.spec.ts new file mode 100644 index 000000000..06c952221 --- /dev/null +++ b/src/serializable/pvm/addPermissionlessValidatorTx.spec.ts @@ -0,0 +1,15 @@ +import { testPVMCodec } from '../../fixtures/codec'; +import { + addPermissionlessValidatorTx, + addPermissionlessValidatorTxBytes, +} from '../../fixtures/pvm'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { AddPermissionlessValidatorTx } from './addPermissionlessValidatorTx'; + +testSerialization( + 'AddPermissionlessValidatorTx', + AddPermissionlessValidatorTx, + addPermissionlessValidatorTx, + addPermissionlessValidatorTxBytes, + testPVMCodec, +); diff --git a/src/serializable/pvm/addPermissionlessValidatorTx.ts b/src/serializable/pvm/addPermissionlessValidatorTx.ts new file mode 100644 index 000000000..12dfb9155 --- /dev/null +++ b/src/serializable/pvm/addPermissionlessValidatorTx.ts @@ -0,0 +1,94 @@ +import { PVMTx } from './abstractTx'; +import { BaseTx } from '../avax/baseTx'; +import { TransferableOutput } from '../avax/transferableOutput'; +import type { Serializable } from '../common/types'; +import { serializable } from '../common/types'; +import { SubnetValidator } from './subnetValidator'; +import { Codec } from '../codec'; +import { concatBytes } from '../../utils/buffer'; +import { pack, unpack } from '../../utils/struct'; +import { Int } from '../primitives'; +import { packList, toListStruct } from '../../utils/serializeList'; +import type { Signer, SignerEmpty } from './signer'; +import type { OutputOwners } from '../fxs/secp256k1'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://docs.avax.network/specs/platform-transaction-serialization#unsigned-add-permissionless-validator-tx + */ +@serializable() +export class AddPermissionlessValidatorTx extends PVMTx { + _type = TypeSymbols.AddPermissionlessValidatorTx; + + constructor( + public readonly baseTx: BaseTx, + public readonly subnetValidator: SubnetValidator, + public readonly signer: Signer | SignerEmpty, + public readonly stake: TransferableOutput[], + public readonly validatorRewardsOwner: Serializable, + public readonly delegatorRewardsOwner: Serializable, + public readonly shares: Int, + ) { + super(); + } + + getValidatorRewardsOwner() { + return this.validatorRewardsOwner as OutputOwners; + } + + getDelegatorRewardsOwner() { + return this.delegatorRewardsOwner as OutputOwners; + } + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [AddPermissionlessValidatorTx, Uint8Array] { + const [ + baseTx, + subnetValidator, + signer, + stakeOuts, + validatorRewardsOwner, + delegatorRewardsOwner, + delegationShares, + rest, + ] = unpack( + bytes, + [ + BaseTx, + SubnetValidator, + Codec, + toListStruct(TransferableOutput), + Codec, + Codec, + Int, + ], + codec, + ); + + return [ + new AddPermissionlessValidatorTx( + baseTx, + subnetValidator, + signer, + stakeOuts, + validatorRewardsOwner, + delegatorRewardsOwner, + delegationShares, + ), + rest, + ]; + } + + toBytes(codec: Codec): Uint8Array { + return concatBytes( + pack([this.baseTx, this.subnetValidator], codec), + codec.PackPrefix(this.signer), + packList(this.stake, codec), + codec.PackPrefix(this.validatorRewardsOwner), + codec.PackPrefix(this.delegatorRewardsOwner), + this.shares.toBytes(), + ); + } +} diff --git a/src/serializable/pvm/addSubnetValidatorTx.spec.ts b/src/serializable/pvm/addSubnetValidatorTx.spec.ts new file mode 100644 index 000000000..55d5a3210 --- /dev/null +++ b/src/serializable/pvm/addSubnetValidatorTx.spec.ts @@ -0,0 +1,15 @@ +import { testPVMCodec } from '../../fixtures/codec'; +import { + addSubnetValidatorTx, + addSubnetValidatorTxBytes, +} from '../../fixtures/pvm'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { AddSubnetValidatorTx } from './addSubnetValidatorTx'; + +testSerialization( + 'AddSubnetValidatorTx', + AddSubnetValidatorTx, + addSubnetValidatorTx, + addSubnetValidatorTxBytes, + testPVMCodec, +); diff --git a/src/serializable/pvm/addSubnetValidatorTx.ts b/src/serializable/pvm/addSubnetValidatorTx.ts new file mode 100644 index 000000000..5da774170 --- /dev/null +++ b/src/serializable/pvm/addSubnetValidatorTx.ts @@ -0,0 +1,51 @@ +import { concatBytes } from '../../utils/buffer'; +import { pack, unpack } from '../../utils/struct'; +import { BaseTx } from '../avax/baseTx'; +import { Codec } from '../codec/codec'; +import type { Serializable } from '../common/types'; +import { serializable } from '../common/types'; +import { AbstractSubnetTx } from './abstractSubnetTx'; +import { SubnetValidator } from './subnetValidator'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://docs.avax.network/specs/platform-transaction-serialization#unsigned-add-subnet-validator-tx + */ +@serializable() +export class AddSubnetValidatorTx extends AbstractSubnetTx { + _type = TypeSymbols.AddSubnetValidatorTx; + + constructor( + public readonly baseTx: BaseTx, + public readonly subnetValidator: SubnetValidator, + public readonly subnetAuth: Serializable, + ) { + super(); + } + + getSubnetID() { + return this.subnetValidator.subnetId; + } + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [AddSubnetValidatorTx, Uint8Array] { + const [baseTx, subnetValidator, subnetAuth, rest] = unpack( + bytes, + [BaseTx, SubnetValidator, Codec], + codec, + ); + return [ + new AddSubnetValidatorTx(baseTx, subnetValidator, subnetAuth), + rest, + ]; + } + + toBytes(codec: Codec) { + return concatBytes( + pack([this.baseTx, this.subnetValidator], codec), + codec.PackPrefix(this.subnetAuth), + ); + } +} diff --git a/src/serializable/pvm/addValidatorTx.spec.ts b/src/serializable/pvm/addValidatorTx.spec.ts new file mode 100644 index 000000000..7c180f4d5 --- /dev/null +++ b/src/serializable/pvm/addValidatorTx.spec.ts @@ -0,0 +1,12 @@ +import { testPVMCodec } from '../../fixtures/codec'; +import { addValidatorTx, addValidatorTxBytes } from '../../fixtures/pvm'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { AddValidatorTx } from './addValidatorTx'; + +testSerialization( + 'AddValidatorTx', + AddValidatorTx, + addValidatorTx, + addValidatorTxBytes, + testPVMCodec, +); diff --git a/src/serializable/pvm/addValidatorTx.ts b/src/serializable/pvm/addValidatorTx.ts new file mode 100644 index 000000000..ebb7d1a77 --- /dev/null +++ b/src/serializable/pvm/addValidatorTx.ts @@ -0,0 +1,60 @@ +import { concatBytes } from '../../utils/buffer'; +import { packList, toListStruct } from '../../utils/serializeList'; +import { pack, unpack } from '../../utils/struct'; +import { BaseTx } from '../avax/baseTx'; +import { TransferableOutput } from '../avax/transferableOutput'; +import { Codec } from '../codec/codec'; +import type { Serializable } from '../common/types'; +import { serializable } from '../common/types'; +import type { OutputOwners } from '../fxs/secp256k1'; +import { Int } from '../primitives'; +import { PVMTx } from './abstractTx'; +import { Validator } from './validator'; +import { TypeSymbols } from '../constants'; + +/** + * @deprecated since {@link https://github.com/avalanche-foundation/ACPs/blob/main/ACPs/62-disable-addvalidatortx-and-adddelegatortx.md|Durango-upgrade} + * @see https://docs.avax.network/specs/platform-transaction-serialization#unsigned-add-validator-tx + */ +@serializable() +export class AddValidatorTx extends PVMTx { + _type = TypeSymbols.AddValidatorTx; + + constructor( + public readonly baseTx: BaseTx, + public readonly validator: Validator, + public readonly stake: TransferableOutput[], + public readonly rewardsOwner: Serializable, + public readonly shares: Int, + ) { + super(); + } + + getRewardsOwner() { + return this.rewardsOwner as OutputOwners; + } + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [AddValidatorTx, Uint8Array] { + const [baseTx, validator, stake, rewardsOwner, shares, rest] = unpack( + bytes, + [BaseTx, Validator, toListStruct(TransferableOutput), Codec, Int], + codec, + ); + return [ + new AddValidatorTx(baseTx, validator, stake, rewardsOwner, shares), + rest, + ]; + } + + toBytes(codec: Codec) { + return concatBytes( + pack([this.baseTx, this.validator], codec), + packList(this.stake, codec), + codec.PackPrefix(this.rewardsOwner), + this.shares.toBytes(), + ); + } +} diff --git a/src/serializable/pvm/advanceTimeTx.spec.ts b/src/serializable/pvm/advanceTimeTx.spec.ts new file mode 100644 index 000000000..224777b29 --- /dev/null +++ b/src/serializable/pvm/advanceTimeTx.spec.ts @@ -0,0 +1,12 @@ +import { testPVMCodec } from '../../fixtures/codec'; +import { advanceTimeBytesTx, advanceTimeTx } from '../../fixtures/pvm'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { AdvanceTimeTx } from './advanceTimeTx'; + +testSerialization( + 'AdvanceTime', + AdvanceTimeTx, + advanceTimeTx, + advanceTimeBytesTx, + testPVMCodec, +); diff --git a/src/serializable/pvm/advanceTimeTx.ts b/src/serializable/pvm/advanceTimeTx.ts new file mode 100644 index 000000000..820d15d4e --- /dev/null +++ b/src/serializable/pvm/advanceTimeTx.ts @@ -0,0 +1,28 @@ +import { packSwitched, unpack } from '../../utils/struct'; +import type { Codec } from '../codec/codec'; +import { serializable } from '../common/types'; +import { BigIntPr } from '../primitives'; +import { PVMTx } from './abstractTx'; +import { TypeSymbols } from '../constants'; + +@serializable() +export class AdvanceTimeTx extends PVMTx { + _type = TypeSymbols.AdvanceTimeTx; + + constructor(public readonly time: BigIntPr) { + super(); + } + baseTx = undefined; + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [AdvanceTimeTx, Uint8Array] { + const [time, rest] = unpack(bytes, [BigIntPr], codec); + return [new AdvanceTimeTx(time), rest]; + } + + toBytes(codec: Codec) { + return packSwitched(codec, this.time); + } +} diff --git a/src/serializable/pvm/baseTx.spec.ts b/src/serializable/pvm/baseTx.spec.ts new file mode 100644 index 000000000..50d81f8bc --- /dev/null +++ b/src/serializable/pvm/baseTx.spec.ts @@ -0,0 +1,5 @@ +import { pvmBaseTx, pvmBaseTxBytes } from '../../fixtures/avax'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { BaseTx } from './baseTx'; + +testSerialization('BaseTx', BaseTx, pvmBaseTx, pvmBaseTxBytes); diff --git a/src/serializable/pvm/baseTx.ts b/src/serializable/pvm/baseTx.ts new file mode 100644 index 000000000..70865e150 --- /dev/null +++ b/src/serializable/pvm/baseTx.ts @@ -0,0 +1,28 @@ +import { unpack } from '../../utils/struct'; +import { BaseTx as AvaxBaseTx } from '../avax/baseTx'; +import type { Codec } from '../codec/codec'; +import { serializable } from '../common/types'; +import { PVMTx } from './abstractTx'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://github.com/avalanche-foundation/ACPs/blob/main/ACPs/23-p-chain-native-transfers.md + * TODO: add doc reference after D-upgrade + */ +@serializable() +export class BaseTx extends PVMTx { + _type = TypeSymbols.PvmBaseTx; + + constructor(public readonly baseTx: AvaxBaseTx) { + super(); + } + + static fromBytes(bytes: Uint8Array, codec: Codec): [BaseTx, Uint8Array] { + const [baseTx, remaining] = unpack(bytes, [AvaxBaseTx], codec); + return [new BaseTx(baseTx), remaining]; + } + + toBytes(codec: Codec) { + return this.baseTx.toBytes(codec); + } +} diff --git a/src/serializable/pvm/codec.ts b/src/serializable/pvm/codec.ts new file mode 100644 index 000000000..b7f577520 --- /dev/null +++ b/src/serializable/pvm/codec.ts @@ -0,0 +1,68 @@ +import { Codec, Manager } from '../codec'; +import * as Secp256k1Fx from '../fxs/secp256k1'; +import { AddDelegatorTx } from './addDelegatorTx'; +import { AddSubnetValidatorTx } from './addSubnetValidatorTx'; +import { AddValidatorTx } from './addValidatorTx'; +import { AdvanceTimeTx } from './advanceTimeTx'; +import { CreateChainTx } from './createChainTx'; +import { CreateSubnetTx } from './createSubnetTx'; +import { ExportTx } from './exportTx'; +import { ImportTx } from './importTx'; +import { RewardValidatorTx } from './rewardValidatorTx'; +import { StakeableLockIn } from './stakeableLockIn'; +import { StakeableLockOut } from './stakeableLockOut'; +import { AddPermissionlessValidatorTx } from './addPermissionlessValidatorTx'; +import { AddPermissionlessDelegatorTx } from './addPermissionlessDelegatorTx'; +import { Signer, SignerEmpty } from './signer'; +import { RemoveSubnetValidatorTx } from './removeSubnetValidatorTx'; +import { TransferSubnetOwnershipTx } from './transferSubnetOwnershipTx'; +import { TransformSubnetTx } from './transformSubnetTx'; +import { BaseTx } from './baseTx'; + +/** + * @see https://github.com/ava-labs/avalanchego/blob/master/vms/platformvm/txs/codec.go#L35 + */ +export const codec = new Codec([ + ...new Array(5), // 0-4 + + ...Secp256k1Fx.TypeRegistry, // 5-9 + Secp256k1Fx.Input, // 10 + Secp256k1Fx.OutputOwners, //11 + + AddValidatorTx, // 12 + AddSubnetValidatorTx, // 13 + AddDelegatorTx, // 14 + + CreateChainTx, // 15 + CreateSubnetTx, // 16 + + ImportTx, // 17 + ExportTx, // 18 + + AdvanceTimeTx, //19 + RewardValidatorTx, //20 + + StakeableLockIn, // 21 + StakeableLockOut, // 22 + + RemoveSubnetValidatorTx, //23 + TransformSubnetTx, // 24 + AddPermissionlessValidatorTx, // 25 + AddPermissionlessDelegatorTx, // 26 + + SignerEmpty, // 27 + Signer, // 28 + + ...new Array(4), // 29-32 + + TransferSubnetOwnershipTx, // 33 + BaseTx, // 34 +]); + +let manager: Manager; +export const getPVMManager = () => { + if (manager) return manager; + manager = new Manager(); + manager.RegisterCodec(0, codec); + return manager; +}; diff --git a/src/serializable/pvm/createChainTx.spec.ts b/src/serializable/pvm/createChainTx.spec.ts new file mode 100644 index 000000000..a164673fc --- /dev/null +++ b/src/serializable/pvm/createChainTx.spec.ts @@ -0,0 +1,12 @@ +import { testPVMCodec } from '../../fixtures/codec'; +import { createChainTx, createChainTxBytes } from '../../fixtures/pvm'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { CreateChainTx } from './createChainTx'; + +testSerialization( + 'CreateChainTx', + CreateChainTx, + createChainTx, + createChainTxBytes, + testPVMCodec, +); diff --git a/src/serializable/pvm/createChainTx.ts b/src/serializable/pvm/createChainTx.ts new file mode 100644 index 000000000..b331aec5e --- /dev/null +++ b/src/serializable/pvm/createChainTx.ts @@ -0,0 +1,76 @@ +import { concatBytes } from '@noble/hashes/utils'; +import { packList, toListStruct } from '../../utils/serializeList'; +import { pack, unpack } from '../../utils/struct'; +import { BaseTx } from '../avax/baseTx'; +import { Codec } from '../codec/codec'; +import type { Serializable } from '../common/types'; +import { serializable } from '../common/types'; +import { Id } from '../fxs/common'; +import { Bytes, Stringpr } from '../primitives'; +import { AbstractSubnetTx } from './abstractSubnetTx'; +import { TypeSymbols } from '../constants'; + +/** + * @see + */ +@serializable() +export class CreateChainTx extends AbstractSubnetTx { + _type = TypeSymbols.CreateChainTx; + + constructor( + public readonly baseTx: BaseTx, + public readonly subnetID: Id, + public readonly chainName: Stringpr, + public readonly vmID: Id, + public readonly fxIds: Id[], + public readonly genesisData: Bytes, + public readonly subnetAuth: Serializable, + ) { + super(); + } + + getSubnetID() { + return this.subnetID; + } + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [CreateChainTx, Uint8Array] { + const [ + baseTx, + subnetID, + chainName, + vmID, + fxIds, + genesisData, + subnetAuth, + rest, + ] = unpack( + bytes, + [BaseTx, Id, Stringpr, Id, toListStruct(Id), Bytes, Codec], + codec, + ); + return [ + new CreateChainTx( + baseTx, + subnetID, + chainName, + vmID, + fxIds, + genesisData, + subnetAuth, + ), + rest, + ]; + } + + toBytes(codec: Codec) { + return concatBytes( + pack([this.baseTx, this.subnetID, this.chainName, this.vmID], codec), + packList(this.fxIds, codec), + this.genesisData.toBytes(), + codec.PackPrefix(this.subnetAuth), + ); + } +} diff --git a/src/serializable/pvm/createSubnetTx.spec.ts b/src/serializable/pvm/createSubnetTx.spec.ts new file mode 100644 index 000000000..9326d8fac --- /dev/null +++ b/src/serializable/pvm/createSubnetTx.spec.ts @@ -0,0 +1,12 @@ +import { testPVMCodec } from '../../fixtures/codec'; +import { createSubnetTx, createSubnetTxBytes } from '../../fixtures/pvm'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { CreateSubnetTx } from './createSubnetTx'; + +testSerialization( + 'CreateSubnetTx', + CreateSubnetTx, + createSubnetTx, + createSubnetTxBytes, + testPVMCodec, +); diff --git a/src/serializable/pvm/createSubnetTx.ts b/src/serializable/pvm/createSubnetTx.ts new file mode 100644 index 000000000..701118009 --- /dev/null +++ b/src/serializable/pvm/createSubnetTx.ts @@ -0,0 +1,45 @@ +import { concatBytes } from '../../utils/buffer'; +import { pack, unpack } from '../../utils/struct'; +import { BaseTx } from '../avax/baseTx'; +import { Codec } from '../codec/codec'; +import type { Serializable } from '../common/types'; +import { serializable } from '../common/types'; +import type { OutputOwners } from '../fxs/secp256k1'; +import { PVMTx } from './abstractTx'; +import { TypeSymbols } from '../constants'; + +/** + * The docs for this do not match the actual code, there is no rewards owners just Owners + * @see https://docs.avax.network/specs/platform-transaction-serialization#unsigned-create-subnet-tx + * @see https://github.com/ava-labs/avalanchego/blob/535456298046b5c2fbcb95ce36702422b6980c66/vms/platformvm/txs/create_subnet_tx.go + */ +@serializable() +export class CreateSubnetTx extends PVMTx { + _type = TypeSymbols.CreateSubnetTx; + + constructor( + public readonly baseTx: BaseTx, + public readonly subnetOwners: Serializable, + ) { + super(); + } + + getSubnetOwners() { + return this.subnetOwners as OutputOwners; + } + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [CreateSubnetTx, Uint8Array] { + const [baseTx, subnetOwners, rest] = unpack(bytes, [BaseTx, Codec], codec); + return [new CreateSubnetTx(baseTx, subnetOwners), rest]; + } + + toBytes(codec: Codec) { + return concatBytes( + pack([this.baseTx], codec), + codec.PackPrefix(this.subnetOwners), + ); + } +} diff --git a/src/serializable/pvm/exportTx.spec.ts b/src/serializable/pvm/exportTx.spec.ts new file mode 100644 index 000000000..b61bb1660 --- /dev/null +++ b/src/serializable/pvm/exportTx.spec.ts @@ -0,0 +1,6 @@ +import { testPVMCodec } from '../../fixtures/codec'; +import { exportTx, exportTxBytes } from '../../fixtures/pvm'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { ExportTx } from './exportTx'; + +testSerialization('ExportTx', ExportTx, exportTx, exportTxBytes, testPVMCodec); diff --git a/src/serializable/pvm/exportTx.ts b/src/serializable/pvm/exportTx.ts new file mode 100644 index 000000000..b9a713c26 --- /dev/null +++ b/src/serializable/pvm/exportTx.ts @@ -0,0 +1,38 @@ +import { toListStruct } from '../../utils/serializeList'; +import { packSwitched, unpack } from '../../utils/struct'; +import { BaseTx } from '../avax/baseTx'; +import { TransferableOutput } from '../avax/transferableOutput'; +import type { Codec } from '../codec/codec'; +import { serializable } from '../common/types'; +import { Id } from '../fxs/common'; +import { PVMTx } from './abstractTx'; +import { TypeSymbols } from '../constants'; + +/** + * @see + */ +@serializable() +export class ExportTx extends PVMTx { + _type = TypeSymbols.PvmExportTx; + + constructor( + public readonly baseTx: BaseTx, + public readonly destination: Id, + public readonly outs: TransferableOutput[], + ) { + super(); + } + + static fromBytes(bytes: Uint8Array, codec: Codec): [ExportTx, Uint8Array] { + const [baseTx, id, outs, rest] = unpack( + bytes, + [BaseTx, Id, toListStruct(TransferableOutput)], + codec, + ); + return [new ExportTx(baseTx, id, outs), rest]; + } + + toBytes(codec: Codec) { + return packSwitched(codec, this.baseTx, this.destination, this.outs); + } +} diff --git a/src/serializable/pvm/importTx.spec.ts b/src/serializable/pvm/importTx.spec.ts new file mode 100644 index 000000000..49be591a3 --- /dev/null +++ b/src/serializable/pvm/importTx.spec.ts @@ -0,0 +1,6 @@ +import { testPVMCodec } from '../../fixtures/codec'; +import { importTx, importTxBytes } from '../../fixtures/pvm'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { ImportTx } from './importTx'; + +testSerialization('ImportTx', ImportTx, importTx, importTxBytes, testPVMCodec); diff --git a/src/serializable/pvm/importTx.ts b/src/serializable/pvm/importTx.ts new file mode 100644 index 000000000..52163ec12 --- /dev/null +++ b/src/serializable/pvm/importTx.ts @@ -0,0 +1,42 @@ +import { toListStruct } from '../../utils/serializeList'; +import { pack, unpack } from '../../utils/struct'; +import { BaseTx } from '../avax/baseTx'; +import { TransferableInput } from '../avax/transferableInput'; +import type { Codec } from '../codec/codec'; +import { serializable } from '../common/types'; +import { Id } from '../fxs/common'; +import { PVMTx } from './abstractTx'; +import { TypeSymbols } from '../constants'; + +/** + * @see + */ +@serializable() +export class ImportTx extends PVMTx { + _type = TypeSymbols.PvmImportTx; + + constructor( + public readonly baseTx: BaseTx, + public readonly sourceChain: Id, + public readonly ins: TransferableInput[], + ) { + super(); + } + + getSigIndices() { + return this.ins.map((inp) => inp.sigIndicies()); + } + + static fromBytes(bytes: Uint8Array, codec: Codec): [ImportTx, Uint8Array] { + const [baseTx, sourceChain, ins, rest] = unpack( + bytes, + [BaseTx, Id, toListStruct(TransferableInput)], + codec, + ); + return [new ImportTx(baseTx, sourceChain, ins), rest]; + } + + toBytes(codec: Codec) { + return pack([this.baseTx, this.sourceChain, this.ins], codec); + } +} diff --git a/src/serializable/pvm/index.ts b/src/serializable/pvm/index.ts new file mode 100644 index 000000000..9ee4a6280 --- /dev/null +++ b/src/serializable/pvm/index.ts @@ -0,0 +1,47 @@ +import { BaseTx } from './baseTx'; +import { RemoveSubnetValidatorTx } from './removeSubnetValidatorTx'; +import { AddDelegatorTx } from './addDelegatorTx'; +import { AddSubnetValidatorTx } from './addSubnetValidatorTx'; +import { AddValidatorTx } from './addValidatorTx'; +import { AdvanceTimeTx } from './advanceTimeTx'; +import { CreateChainTx } from './createChainTx'; +import { CreateSubnetTx } from './createSubnetTx'; +import { ExportTx } from './exportTx'; +import { ImportTx } from './importTx'; +import { StakeableLockIn } from './stakeableLockIn'; +import { StakeableLockOut } from './stakeableLockOut'; +import { SubnetValidator } from './subnetValidator'; +import { Validator } from './validator'; +import { Signer, SignerEmpty } from './signer'; +import { ProofOfPossession } from './proofOfPossession'; +import { AddPermissionlessValidatorTx } from './addPermissionlessValidatorTx'; +import { AddPermissionlessDelegatorTx } from './addPermissionlessDelegatorTx'; +import { AbstractSubnetTx } from './abstractSubnetTx'; +import { TransferSubnetOwnershipTx } from './transferSubnetOwnershipTx'; +import { TransformSubnetTx } from './transformSubnetTx'; + +export * from './typeGuards'; +export { + BaseTx, + AbstractSubnetTx, + AddDelegatorTx, + AddSubnetValidatorTx, + RemoveSubnetValidatorTx, + AddValidatorTx, + AdvanceTimeTx, + CreateChainTx, + CreateSubnetTx, + ExportTx, + ImportTx, + StakeableLockIn, + StakeableLockOut, + SubnetValidator, + Validator, + Signer, + SignerEmpty, + AddPermissionlessValidatorTx, + AddPermissionlessDelegatorTx, + ProofOfPossession, + TransferSubnetOwnershipTx, + TransformSubnetTx, +}; diff --git a/src/serializable/pvm/proofOfPossession.test.ts b/src/serializable/pvm/proofOfPossession.test.ts new file mode 100644 index 000000000..4ea3981d7 --- /dev/null +++ b/src/serializable/pvm/proofOfPossession.test.ts @@ -0,0 +1,46 @@ +import { ProofOfPossession } from './proofOfPossession'; + +const pubkey = new Uint8Array([ + 0x85, 0x02, 0x5b, 0xca, 0x6a, 0x30, 0x2d, 0xc6, 0x13, 0x38, 0xff, 0x49, 0xc8, + 0xba, 0xa5, 0x72, 0xde, 0xd3, 0xe8, 0x6f, 0x37, 0x59, 0x30, 0x4c, 0x7f, 0x61, + 0x8a, 0x2a, 0x25, 0x93, 0xc1, 0x87, 0xe0, 0x80, 0xa3, 0xcf, 0xde, 0xc9, 0x50, + 0x40, 0x30, 0x9a, 0xd1, 0xf1, 0x58, 0x95, 0x30, 0x67, +]); + +const signature = new Uint8Array([ + 0x8b, 0x1d, 0x61, 0x33, 0xd1, 0x7e, 0x34, 0x83, 0x22, 0x0a, 0xd9, 0x60, 0xb6, + 0xfd, 0xe1, 0x1e, 0x4e, 0x12, 0x14, 0xa8, 0xce, 0x21, 0xef, 0x61, 0x62, 0x27, + 0xe5, 0xd5, 0xee, 0xf0, 0x70, 0xd7, 0x50, 0x0e, 0x6f, 0x7d, 0x44, 0x52, 0xc5, + 0xa7, 0x60, 0x62, 0x0c, 0xc0, 0x67, 0x95, 0xcb, 0xe2, 0x18, 0xe0, 0x72, 0xeb, + 0xa7, 0x6d, 0x94, 0x78, 0x8d, 0x9d, 0x01, 0x17, 0x6c, 0xe4, 0xec, 0xad, 0xfb, + 0x96, 0xb4, 0x7f, 0x94, 0x22, 0x81, 0x89, 0x4d, 0xdf, 0xad, 0xd1, 0xc1, 0x74, + 0x3f, 0x7f, 0x54, 0x9f, 0x1d, 0x07, 0xd5, 0x9d, 0x55, 0x65, 0x59, 0x27, 0xf7, + 0x2b, 0xc6, 0xbf, 0x7c, 0x12, +]); + +describe('proofOfPossession', function () { + it('can init', () => { + const proof = new ProofOfPossession(pubkey, signature); + expect(proof instanceof ProofOfPossession).toBe(true); + }); + + it('throws for invalid pubkey', () => { + expect(() => { + const invalidPub = pubkey.slice(0, pubkey.length - 2); + new ProofOfPossession(invalidPub, signature); + }).toThrow(); + }); + + it('throws for invalid signature', () => { + expect(() => { + const invalidSig = signature.slice(0, signature.length - 2); + new ProofOfPossession(pubkey, invalidSig); + }).toThrow(); + }); + + it('can call toString', () => { + const proof = new ProofOfPossession(pubkey, signature); + const expected = `0x85025bca6a302dc61338ff49c8baa572ded3e86f3759304c7f618a2a2593c187e080a3cfdec95040309ad1f1589530678b1d6133d17e3483220ad960b6fde11e4e1214a8ce21ef616227e5d5eef070d7500e6f7d4452c5a760620cc06795cbe218e072eba76d94788d9d01176ce4ecadfb96b47f942281894ddfadd1c1743f7f549f1d07d59d55655927f72bc6bf7c12`; + expect(proof.toString()).toEqual(expected); + }); +}); diff --git a/src/serializable/pvm/proofOfPossession.ts b/src/serializable/pvm/proofOfPossession.ts new file mode 100644 index 000000000..60e7ba2cc --- /dev/null +++ b/src/serializable/pvm/proofOfPossession.ts @@ -0,0 +1,40 @@ +import { serializable } from '../common/types'; +import { bufferToHex, concatBytes } from '../../utils/buffer'; +import { BLS_PUBKEY_LENGTH, BLS_SIGNATURE_LENGTH } from '../../constants/bls'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://docs.avax.network/specs/platform-transaction-serialization#proof-of-possession-specification-1 + */ +@serializable() +export class ProofOfPossession { + _type = TypeSymbols.ProofOfPossession; + + constructor( + public readonly publicKey: Uint8Array, + public readonly signature: Uint8Array, + ) { + if (publicKey.length !== BLS_PUBKEY_LENGTH) + throw new Error(`public key must be ${BLS_PUBKEY_LENGTH} bytes`); + if (signature.length !== BLS_SIGNATURE_LENGTH) + throw new Error(`signature must be ${BLS_SIGNATURE_LENGTH} bytes`); + } + + static fromBytes(bytes: Uint8Array): [ProofOfPossession, Uint8Array] { + const pubkey = bytes.slice(0, BLS_PUBKEY_LENGTH); + const signature = bytes.slice( + BLS_PUBKEY_LENGTH, + BLS_PUBKEY_LENGTH + BLS_SIGNATURE_LENGTH, + ); + const rest = bytes.slice(BLS_PUBKEY_LENGTH + BLS_SIGNATURE_LENGTH); + return [new ProofOfPossession(pubkey, signature), rest]; + } + + toString() { + return bufferToHex(this.toBytes()); + } + + toBytes() { + return concatBytes(this.publicKey, this.signature); + } +} diff --git a/src/serializable/pvm/removeSubnetValidator.spec.ts b/src/serializable/pvm/removeSubnetValidator.spec.ts new file mode 100644 index 000000000..edc8c15d2 --- /dev/null +++ b/src/serializable/pvm/removeSubnetValidator.spec.ts @@ -0,0 +1,15 @@ +import { RemoveSubnetValidatorTx } from './removeSubnetValidatorTx'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { + removeSubnetValidatorTxBytes, + removeValidatorTx, +} from '../../fixtures/pvm'; +import { testPVMCodec } from '../../fixtures/codec'; + +testSerialization( + 'RemoveSubnetValidator', + RemoveSubnetValidatorTx, + removeValidatorTx, + removeSubnetValidatorTxBytes, + testPVMCodec, +); diff --git a/src/serializable/pvm/removeSubnetValidatorTx.ts b/src/serializable/pvm/removeSubnetValidatorTx.ts new file mode 100644 index 000000000..38d0a86c2 --- /dev/null +++ b/src/serializable/pvm/removeSubnetValidatorTx.ts @@ -0,0 +1,53 @@ +import { BaseTx } from '../avax/baseTx'; +import { Codec } from '../codec/codec'; +import { concatBytes } from '../../utils/buffer'; +import { Id } from '../fxs/common'; +import { NodeId } from '../fxs/common/nodeId'; +import { pack, unpack } from '../../utils/struct'; +import { serializable } from '../common/types'; +import type { Serializable } from '../common/types'; +import { TypeSymbols } from '../constants'; +import { AbstractSubnetTx } from './abstractSubnetTx'; + +/** + * @see https://docs.avax.network/specs/platform-transaction-serialization#unsigned-remove-subnet-validator-tx + */ +@serializable() +export class RemoveSubnetValidatorTx extends AbstractSubnetTx { + _type = TypeSymbols.RemoveSubnetValidatorTx; + + constructor( + public readonly baseTx: BaseTx, + public readonly nodeId: NodeId, + public readonly subnetId: Id, + public readonly subnetAuth: Serializable, + ) { + super(); + } + + getSubnetID() { + return this.subnetId; + } + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [RemoveSubnetValidatorTx, Uint8Array] { + const [baseTx, nodeId, subnetId, subnetAuth, rest] = unpack( + bytes, + [BaseTx, NodeId, Id, Codec], + codec, + ); + return [ + new RemoveSubnetValidatorTx(baseTx, nodeId, subnetId, subnetAuth), + rest, + ]; + } + + toBytes(codec: Codec) { + return concatBytes( + pack([this.baseTx, this.nodeId, this.subnetId], codec), + codec.PackPrefix(this.subnetAuth), + ); + } +} diff --git a/src/serializable/pvm/rewardValidatorTx.ts b/src/serializable/pvm/rewardValidatorTx.ts new file mode 100644 index 000000000..2cd1fa42b --- /dev/null +++ b/src/serializable/pvm/rewardValidatorTx.ts @@ -0,0 +1,32 @@ +import { packSwitched, unpack } from '../../utils/struct'; +import type { Codec } from '../codec/codec'; +import { serializable } from '../common/types'; +import { Id } from '../fxs/common'; +import { PVMTx } from './abstractTx'; +import { TypeSymbols } from '../constants'; + +/** + * @see + */ +@serializable() +export class RewardValidatorTx extends PVMTx { + _type = TypeSymbols.RewardValidatorTx; + + constructor(public readonly txId: Id) { + super(); + } + + baseTx = undefined; + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [RewardValidatorTx, Uint8Array] { + const [txId, rest] = unpack(bytes, [Id], codec); + return [new RewardValidatorTx(txId), rest]; + } + + toBytes(codec: Codec) { + return packSwitched(codec, this.txId); + } +} diff --git a/src/serializable/pvm/signer.ts b/src/serializable/pvm/signer.ts new file mode 100644 index 000000000..5b9c6f84b --- /dev/null +++ b/src/serializable/pvm/signer.ts @@ -0,0 +1,49 @@ +import { serializable } from '../common/types'; +import { ProofOfPossession } from './proofOfPossession'; +import { pack, unpack } from '../../utils/struct'; +import type { Codec } from '../codec'; +import { TypeSymbols } from '../constants'; + +@serializable() +export class Signer { + _type = TypeSymbols.Signer; + + constructor(public readonly proof: ProofOfPossession) {} + + static fromBytes(bytes: Uint8Array, codec: Codec): [Signer, Uint8Array] { + const [proof, rest] = unpack(bytes, [ProofOfPossession], codec); + return [new Signer(proof), rest]; + } + + toBytes(codec: Codec) { + return pack([this.proof], codec); + } +} + +@serializable() +export class SignerEmpty { + _type = TypeSymbols.SignerEmpty; + + static fromBytes(bytes: Uint8Array, codec: Codec): [SignerEmpty, Uint8Array] { + const [rest] = unpack(bytes, [], codec); + return [new SignerEmpty(), rest]; + } + + toBytes(codec: Codec) { + return pack([], codec); + } +} + +export function createSignerOrSignerEmptyFromStrings( + publicKey?: Uint8Array, + signature?: Uint8Array, +) { + return publicKey && signature + ? new Signer( + new ProofOfPossession( + new Uint8Array(publicKey), + new Uint8Array(signature), + ), + ) + : new SignerEmpty(); +} diff --git a/src/serializable/pvm/stakeableLockIn.spec.ts b/src/serializable/pvm/stakeableLockIn.spec.ts new file mode 100644 index 000000000..78f48e17c --- /dev/null +++ b/src/serializable/pvm/stakeableLockIn.spec.ts @@ -0,0 +1,12 @@ +import { testPVMCodec } from '../../fixtures/codec'; +import { stakeableLockIn, stakeableLockInBytes } from '../../fixtures/pvm'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { StakeableLockIn } from './stakeableLockIn'; + +testSerialization( + 'StakeableLockIn', + StakeableLockIn, + stakeableLockIn, + stakeableLockInBytes, + testPVMCodec, +); diff --git a/src/serializable/pvm/stakeableLockIn.ts b/src/serializable/pvm/stakeableLockIn.ts new file mode 100644 index 000000000..23aa81a96 --- /dev/null +++ b/src/serializable/pvm/stakeableLockIn.ts @@ -0,0 +1,41 @@ +import { concatBytes } from '@noble/hashes/utils'; +import { packSwitched, unpack } from '../../utils/struct'; +import type { Codec } from '../codec/codec'; +import type { Amounter } from '../common/types'; +import { serializable } from '../common/types'; +import { BigIntPr } from '../primitives'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://docs.avax.network/specs/platform-transaction-serialization#stakeablelockin + */ +@serializable() +export class StakeableLockIn { + _type = TypeSymbols.StakeableLockIn; + + constructor( + public readonly lockTime: BigIntPr, + public readonly transferableInput: Amounter, + ) {} + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [StakeableLockIn, Uint8Array] { + const [lockTime, rest] = unpack(bytes, [BigIntPr], codec); + + const [transferableInput, remaining] = codec.UnpackPrefix(rest); + + return [new StakeableLockIn(lockTime, transferableInput), remaining]; + } + amount() { + return this.transferableInput.amount(); + } + + toBytes(codec: Codec) { + return concatBytes( + packSwitched(codec, this.lockTime), + codec.PackPrefix(this.transferableInput), + ); + } +} diff --git a/src/serializable/pvm/stakeableLockOut.spec.ts b/src/serializable/pvm/stakeableLockOut.spec.ts new file mode 100644 index 000000000..d20ec8a68 --- /dev/null +++ b/src/serializable/pvm/stakeableLockOut.spec.ts @@ -0,0 +1,12 @@ +import { testPVMCodec } from '../../fixtures/codec'; +import { stakeableLockOut, stakeableLockOutBytes } from '../../fixtures/pvm'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { StakeableLockOut } from './stakeableLockOut'; + +testSerialization( + 'StakeableLockOut', + StakeableLockOut, + stakeableLockOut, + stakeableLockOutBytes, + testPVMCodec, +); diff --git a/src/serializable/pvm/stakeableLockOut.ts b/src/serializable/pvm/stakeableLockOut.ts new file mode 100644 index 000000000..9c9a9b486 --- /dev/null +++ b/src/serializable/pvm/stakeableLockOut.ts @@ -0,0 +1,69 @@ +import { concatBytes } from '@noble/hashes/utils'; +import { packSwitched, unpack } from '../../utils/struct'; +import { isTransferOut } from '../../utils/typeGuards'; +import { Codec } from '../codec/codec'; +import type { Amounter } from '../common/types'; +import { serializable } from '../common/types'; +import { BigIntPr } from '../primitives'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://docs.avax.network/specs/platform-transaction-serialization#stakeablelockin + */ +@serializable() +export class StakeableLockOut implements Amounter { + _type = TypeSymbols.StakeableLockOut; + + constructor( + public readonly lockTime: BigIntPr, + public readonly transferOut: Amounter, + ) {} + + amount() { + return this.transferOut.amount(); + } + + /** + * Get the stakeable locktime of this output. After this date this output can be used like a TransferOut. + */ + getStakeableLocktime() { + return this.lockTime.value(); + } + + getLocktime() { + return this.lockTime.value(); + } + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [StakeableLockOut, Uint8Array] { + const [lockTime, transferOut, rest] = unpack( + bytes, + [BigIntPr, Codec], + codec, + ); + return [new StakeableLockOut(lockTime, transferOut as Amounter), rest]; + } + + getOwners() { + if (isTransferOut(this.transferOut)) { + return this.transferOut.getOwners(); + } + throw new Error('Unable to get owners.'); + } + + getOutputOwners() { + if (isTransferOut(this.transferOut)) { + return this.transferOut.outputOwners; + } + throw new Error('Unable to get output owners.'); + } + + toBytes(codec: Codec) { + return concatBytes( + packSwitched(codec, this.lockTime), + codec.PackPrefix(this.transferOut), + ); + } +} diff --git a/src/serializable/pvm/subnetValidator.spec.ts b/src/serializable/pvm/subnetValidator.spec.ts new file mode 100644 index 000000000..71c71f480 --- /dev/null +++ b/src/serializable/pvm/subnetValidator.spec.ts @@ -0,0 +1,12 @@ +import { testPVMCodec } from '../../fixtures/codec'; +import { subnetValidator, subnetValidatorBytes } from '../../fixtures/pvm'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { SubnetValidator } from './subnetValidator'; + +testSerialization( + 'SubnetValidator', + SubnetValidator, + subnetValidator, + subnetValidatorBytes, + testPVMCodec, +); diff --git a/src/serializable/pvm/subnetValidator.ts b/src/serializable/pvm/subnetValidator.ts new file mode 100644 index 000000000..b8329c179 --- /dev/null +++ b/src/serializable/pvm/subnetValidator.ts @@ -0,0 +1,44 @@ +import type { Codec } from '../codec/codec'; +import { serializable } from '../common/types'; +import { Id } from '../fxs/common'; +import { pack, unpack } from '../../utils/struct'; +import { Validator } from './validator'; +import { TypeSymbols } from '../constants'; + +/** + * @see + */ +@serializable() +export class SubnetValidator { + _type = TypeSymbols.SubnetValidator; + + constructor( + public readonly validator: Validator, + public readonly subnetId: Id, + ) {} + + static fromNative( + nodeId: string, + startTime: bigint, + endTime: bigint, + weight: bigint, + subnetId: Id, + ) { + return new SubnetValidator( + Validator.fromNative(nodeId, startTime, endTime, weight), + subnetId, + ); + } + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [SubnetValidator, Uint8Array] { + const [validator, subnetId, rest] = unpack(bytes, [Validator, Id], codec); + return [new SubnetValidator(validator, subnetId), rest]; + } + + toBytes(codec: Codec) { + return pack([this.validator, this.subnetId], codec); + } +} diff --git a/src/serializable/pvm/transferSubnetOwnershipTx.spec.ts b/src/serializable/pvm/transferSubnetOwnershipTx.spec.ts new file mode 100644 index 000000000..bfe3898e2 --- /dev/null +++ b/src/serializable/pvm/transferSubnetOwnershipTx.spec.ts @@ -0,0 +1,15 @@ +import { testPVMCodec } from '../../fixtures/codec'; +import { + transferSubnetOwnershipTx, + transferSubnetOwnershipTxBytes, +} from '../../fixtures/pvm'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { TransferSubnetOwnershipTx } from './transferSubnetOwnershipTx'; + +testSerialization( + 'TransferSubnetOwnershipTx', + TransferSubnetOwnershipTx, + transferSubnetOwnershipTx, + transferSubnetOwnershipTxBytes, + testPVMCodec, +); diff --git a/src/serializable/pvm/transferSubnetOwnershipTx.ts b/src/serializable/pvm/transferSubnetOwnershipTx.ts new file mode 100644 index 000000000..4c30e0cf3 --- /dev/null +++ b/src/serializable/pvm/transferSubnetOwnershipTx.ts @@ -0,0 +1,59 @@ +import { pack, unpack } from '../../utils/struct'; +import { BaseTx } from '../avax/baseTx'; +import { Codec } from '../codec/codec'; +import type { Serializable } from '../common/types'; +import { serializable } from '../common/types'; +import { TypeSymbols } from '../constants'; +import { Id } from '../fxs/common'; +import { concatBytes } from '../../utils/buffer'; +import { AbstractSubnetTx } from './abstractSubnetTx'; +import type { OutputOwners } from '../../serializable/fxs/secp256k1'; + +/** + * @see https://github.com/avalanche-foundation/ACPs/blob/main/ACPs/31-enable-subnet-ownership-transfer.md + * TODO: add doc reference after D-upgrade + */ +@serializable() +export class TransferSubnetOwnershipTx extends AbstractSubnetTx { + _type = TypeSymbols.TransferSubnetOwnershipTx; + + constructor( + public readonly baseTx: BaseTx, + public readonly subnetID: Id, + public readonly subnetAuth: Serializable, // current owner indices + public readonly subnetOwners: Serializable, // new owners + ) { + super(); + } + + getSubnetID() { + return this.subnetID; + } + + getSubnetOwners() { + return this.subnetOwners as OutputOwners; + } + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [TransferSubnetOwnershipTx, Uint8Array] { + const [baseTx, subnetID, subnetAuth, subnetOwners, rest] = unpack( + bytes, + [BaseTx, Id, Codec, Codec], + codec, + ); + return [ + new TransferSubnetOwnershipTx(baseTx, subnetID, subnetAuth, subnetOwners), + rest, + ]; + } + + toBytes(codec: Codec) { + return concatBytes( + pack([this.baseTx, this.subnetID], codec), + codec.PackPrefix(this.subnetAuth), + codec.PackPrefix(this.subnetOwners), + ); + } +} diff --git a/src/serializable/pvm/transformSubnetTx.spec.ts b/src/serializable/pvm/transformSubnetTx.spec.ts new file mode 100644 index 000000000..78ddbe387 --- /dev/null +++ b/src/serializable/pvm/transformSubnetTx.spec.ts @@ -0,0 +1,12 @@ +import { testPVMCodec } from '../../fixtures/codec'; +import { transformSubnetTx, transformSubnetTxBytes } from '../../fixtures/pvm'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { TransformSubnetTx } from './transformSubnetTx'; + +testSerialization( + 'TransformSubnetTx', + TransformSubnetTx, + transformSubnetTx, + transformSubnetTxBytes, + testPVMCodec, +); diff --git a/src/serializable/pvm/transformSubnetTx.ts b/src/serializable/pvm/transformSubnetTx.ts new file mode 100644 index 000000000..c16f93198 --- /dev/null +++ b/src/serializable/pvm/transformSubnetTx.ts @@ -0,0 +1,138 @@ +import { concatBytes } from '../../utils/buffer'; +import { pack, unpack } from '../../utils/struct'; +import { BaseTx } from '../avax/baseTx'; +import { Codec } from '../codec/codec'; +import type { Serializable } from '../common/types'; +import { serializable } from '../common/types'; +import { Int } from '../primitives'; +import { Byte } from '../primitives'; +import { BigIntPr } from '../primitives'; +import { TypeSymbols } from '../constants'; +import { Id } from '../fxs/common'; +import { AbstractSubnetTx } from './abstractSubnetTx'; + +/** + * @see https://docs.avax.network/reference/avalanchego/p-chain/txn-format#unsigned-transform-subnet-tx + */ +@serializable() +export class TransformSubnetTx extends AbstractSubnetTx { + _type = TypeSymbols.TransformSubnetTx; + + constructor( + public readonly baseTx: BaseTx, + public readonly subnetID: Id, + public readonly assetId: Id, + public readonly initialSupply: BigIntPr, + public readonly maximumSupply: BigIntPr, + public readonly minConsumptionRate: BigIntPr, + public readonly maxConsumptionRate: BigIntPr, + public readonly minValidatorStake: BigIntPr, + public readonly maxValidatorStake: BigIntPr, + public readonly minStakeDuration: Int, + public readonly maxStakeDuration: Int, + public readonly minDelegationFee: Int, + public readonly minDelegatorStake: Int, + public readonly maxValidatorWeightFactor: Byte, + public readonly uptimeRequirement: Int, + public readonly subnetAuth: Serializable, + ) { + super(); + } + + getSubnetID() { + return this.subnetID; + } + + static fromBytes( + bytes: Uint8Array, + codec: Codec, + ): [TransformSubnetTx, Uint8Array] { + const [ + baseTx, + subnetID, + assetId, + initialSupply, + maximumSupply, + minConsumptionRate, + maxConsumptionRate, + minValidatorStake, + maxValidatorStake, + minStakeDuration, + maxStakeDuration, + minDelegationFee, + minDelegatorStake, + maxValidatorWeightFactor, + uptimeRequirement, + subnetAuth, + rest, + ] = unpack( + bytes, + [ + BaseTx, + Id, + Id, + BigIntPr, + BigIntPr, + BigIntPr, + BigIntPr, + BigIntPr, + BigIntPr, + Int, + Int, + Int, + Int, + Byte, + Int, + Codec, + ], + codec, + ); + return [ + new TransformSubnetTx( + baseTx, + subnetID, + assetId, + initialSupply, + maximumSupply, + minConsumptionRate, + maxConsumptionRate, + minValidatorStake, + maxValidatorStake, + minStakeDuration, + maxStakeDuration, + minDelegationFee, + minDelegatorStake, + maxValidatorWeightFactor, + uptimeRequirement, + subnetAuth, + ), + rest, + ]; + } + + toBytes(codec: Codec) { + return concatBytes( + pack( + [ + this.baseTx, + this.subnetID, + this.assetId, + this.initialSupply, + this.maximumSupply, + this.minConsumptionRate, + this.maxConsumptionRate, + this.minValidatorStake, + this.maxValidatorStake, + this.minStakeDuration, + this.maxStakeDuration, + this.minDelegationFee, + this.minDelegatorStake, + this.maxValidatorWeightFactor, + this.uptimeRequirement, + ], + codec, + ), + codec.PackPrefix(this.subnetAuth), + ); + } +} diff --git a/src/serializable/pvm/typeGuards.spec.ts b/src/serializable/pvm/typeGuards.spec.ts new file mode 100644 index 000000000..920f1184e --- /dev/null +++ b/src/serializable/pvm/typeGuards.spec.ts @@ -0,0 +1,53 @@ +import { TypeSymbols } from '../constants'; +import { onlyChecksOneGuard } from '../../fixtures/utils/typeguards'; +import { + isImportTx, + isExportTx, + isAddSubnetValidatorTx, + isAddPermissionlessValidatorTx, + isAddValidatorTx, + isAddDelegatorTx, + isAddPermissionlessDelegatorTx, + isCreateSubnetTx, + isCreateChainTx, + isAdvanceTimeTx, + isEmptySigner, + isSigner, + isRewardValidatorTx, + isRemoveSubnetValidatorTx, + isPvmBaseTx, + isTransferSubnetOwnershipTx, + isTransformSubnetTx, +} from './typeGuards'; + +const cases: [any, TypeSymbols][] = [ + [isPvmBaseTx, TypeSymbols.PvmBaseTx], + [isImportTx, TypeSymbols.PvmImportTx], + [isExportTx, TypeSymbols.PvmExportTx], + [isAddSubnetValidatorTx, TypeSymbols.AddSubnetValidatorTx], + [isAddPermissionlessValidatorTx, TypeSymbols.AddPermissionlessValidatorTx], + [isAddValidatorTx, TypeSymbols.AddValidatorTx], + [isAddDelegatorTx, TypeSymbols.AddDelegatorTx], + [isAddPermissionlessDelegatorTx, TypeSymbols.AddPermissionlessDelegatorTx], + [isCreateSubnetTx, TypeSymbols.CreateSubnetTx], + [isRemoveSubnetValidatorTx, TypeSymbols.RemoveSubnetValidatorTx], + [isCreateChainTx, TypeSymbols.CreateChainTx], + [isAdvanceTimeTx, TypeSymbols.AdvanceTimeTx], + [isEmptySigner, TypeSymbols.SignerEmpty], + [isSigner, TypeSymbols.Signer], + [isRewardValidatorTx, TypeSymbols.RewardValidatorTx], + [isTransferSubnetOwnershipTx, TypeSymbols.TransferSubnetOwnershipTx], + [isTransformSubnetTx, TypeSymbols.TransformSubnetTx], +]; + +const guards = cases.map((caseItem) => caseItem[0]); + +describe('pvm/typeGuards', function () { + test.each(cases)('%p to pass', (guard, type) => { + const object = { + _type: type, + }; + expect(guard(object)).toBe(true); + expect(onlyChecksOneGuard(object, guards)).toBe(true); + }); +}); diff --git a/src/serializable/pvm/typeGuards.ts b/src/serializable/pvm/typeGuards.ts new file mode 100644 index 000000000..7ccfff06c --- /dev/null +++ b/src/serializable/pvm/typeGuards.ts @@ -0,0 +1,98 @@ +import type { Transaction } from '../../vms/common/transaction'; +import type { BaseTx } from './baseTx'; +import type { ImportTx } from './importTx'; +import type { ExportTx } from './exportTx'; +import type { AddValidatorTx } from './addValidatorTx'; +import type { AddDelegatorTx } from './addDelegatorTx'; +import type { AddSubnetValidatorTx } from './addSubnetValidatorTx'; +import type { CreateChainTx } from './createChainTx'; +import type { CreateSubnetTx } from './createSubnetTx'; +import type { RemoveSubnetValidatorTx } from './removeSubnetValidatorTx'; +import type { AddPermissionlessDelegatorTx } from './addPermissionlessDelegatorTx'; +import type { AddPermissionlessValidatorTx } from './addPermissionlessValidatorTx'; +import type { AdvanceTimeTx } from './advanceTimeTx'; +import type { RewardValidatorTx } from './rewardValidatorTx'; +import type { Signer, SignerEmpty } from './signer'; +import type { TransferSubnetOwnershipTx } from './transferSubnetOwnershipTx'; +import { TypeSymbols } from '../constants'; +import type { TransformSubnetTx } from './transformSubnetTx'; + +export function isPvmBaseTx(tx: Transaction): tx is BaseTx { + return tx._type === TypeSymbols.PvmBaseTx; +} + +export function isAddDelegatorTx(tx: Transaction): tx is AddDelegatorTx { + return tx._type === TypeSymbols.AddDelegatorTx; +} + +export function isAddPermissionlessDelegatorTx( + tx: Transaction, +): tx is AddPermissionlessDelegatorTx { + return tx._type === TypeSymbols.AddPermissionlessDelegatorTx; +} + +export function isAddPermissionlessValidatorTx( + tx: Transaction, +): tx is AddPermissionlessValidatorTx { + return tx._type === TypeSymbols.AddPermissionlessValidatorTx; +} + +export function isAddSubnetValidatorTx( + tx: Transaction, +): tx is AddSubnetValidatorTx { + return tx._type === TypeSymbols.AddSubnetValidatorTx; +} + +export function isAddValidatorTx(tx: Transaction): tx is AddValidatorTx { + return tx._type === TypeSymbols.AddValidatorTx; +} + +export function isAdvanceTimeTx(tx: Transaction): tx is AdvanceTimeTx { + return tx._type === TypeSymbols.AdvanceTimeTx; +} + +export function isCreateChainTx(tx: Transaction): tx is CreateChainTx { + return tx._type === TypeSymbols.CreateChainTx; +} + +export function isCreateSubnetTx(tx: Transaction): tx is CreateSubnetTx { + return tx._type === TypeSymbols.CreateSubnetTx; +} + +export function isRemoveSubnetValidatorTx( + tx: Transaction, +): tx is RemoveSubnetValidatorTx { + return tx._type === TypeSymbols.RemoveSubnetValidatorTx; +} + +export function isTransferSubnetOwnershipTx( + tx: Transaction, +): tx is TransferSubnetOwnershipTx { + return tx._type === TypeSymbols.TransferSubnetOwnershipTx; +} + +export function isTransformSubnetTx(tx: Transaction): tx is TransformSubnetTx { + return tx._type === TypeSymbols.TransformSubnetTx; +} + +export function isExportTx(tx: Transaction): tx is ExportTx { + return tx._type === TypeSymbols.PvmExportTx; +} + +export function isImportTx(tx: Transaction): tx is ImportTx { + return tx._type === TypeSymbols.PvmImportTx; +} + +export function isRewardValidatorTx(tx: Transaction): tx is RewardValidatorTx { + return tx._type === TypeSymbols.RewardValidatorTx; +} + +export function isEmptySigner( + signer: Signer | SignerEmpty, +): signer is SignerEmpty { + return signer._type === TypeSymbols.SignerEmpty; +} + +export function isSigner(signer: Signer | SignerEmpty): signer is Signer { + return signer._type === TypeSymbols.Signer; +} diff --git a/src/serializable/pvm/validator.spec.ts b/src/serializable/pvm/validator.spec.ts new file mode 100644 index 000000000..b138e1866 --- /dev/null +++ b/src/serializable/pvm/validator.spec.ts @@ -0,0 +1,5 @@ +import { validator, validatorBytes } from '../../fixtures/pvm'; +import { testSerialization } from '../../fixtures/utils/serializable'; +import { Validator } from './validator'; + +testSerialization('Validator', Validator, validator, validatorBytes); diff --git a/src/serializable/pvm/validator.ts b/src/serializable/pvm/validator.ts new file mode 100644 index 000000000..64aae79a0 --- /dev/null +++ b/src/serializable/pvm/validator.ts @@ -0,0 +1,52 @@ +import { pack, unpack } from '../../utils/struct'; +import type { Codec } from '../codec/codec'; +import { serializable } from '../common/types'; +import { NodeId } from '../fxs/common/nodeId'; +import { BigIntPr } from '../primitives'; +import { TypeSymbols } from '../constants'; + +/** + * @see https://docs.avax.network/specs/platform-transaction-serialization#unsigned-add-validator-tx + */ +@serializable() +export class Validator { + _type = TypeSymbols.Validator; + + constructor( + public readonly nodeId: NodeId, + public readonly startTime: BigIntPr, + public readonly endTime: BigIntPr, + public readonly weight: BigIntPr, + ) {} + + static fromNative( + nodeId: string, + startTime: bigint, + endTime: bigint, + weight: bigint, + ) { + return new Validator( + NodeId.fromString(nodeId), + new BigIntPr(startTime), + new BigIntPr(endTime), + new BigIntPr(weight), + ); + } + + static fromBytes(bytes: Uint8Array, codec: Codec): [Validator, Uint8Array] { + const [nodeId, startTime, endTime, weight, rest] = unpack( + bytes, + [NodeId, BigIntPr, BigIntPr, BigIntPr], + codec, + ); + + return [new Validator(nodeId, startTime, endTime, weight), rest]; + } + + toBytes(codec: Codec) { + return pack( + [this.nodeId, this.startTime, this.endTime, this.weight], + codec, + ); + } +} diff --git a/src/signer/addTxSignatures.spec.ts b/src/signer/addTxSignatures.spec.ts new file mode 100644 index 000000000..08afd4419 --- /dev/null +++ b/src/signer/addTxSignatures.spec.ts @@ -0,0 +1,92 @@ +import { jest } from '@jest/globals'; + +import { UnsignedTx } from '../vms'; +import { BaseTx as AvaxBaseTx, TransferableInput } from '../serializable/avax'; +import { bigIntPr, bytes, int } from '../fixtures/primitives'; +import { id } from '../fixtures/common'; +import { BaseTx } from '../serializable/avm'; +import { transferableOutput, utxoId } from '../fixtures/avax'; +import { Input, TransferInput } from '../serializable/fxs/secp256k1'; +import { AddressMaps, AddressMap, getPublicKey, hexToBuffer } from '../utils'; +import { Address } from '../serializable/fxs/common'; +import { + testAddress1, + testAddress2, + testPrivateKey1, + testPrivateKey2, + testPublicKey1, + testPublicKey2, +} from '../fixtures/vms'; +import { addTxSignatures } from './addTxSignatures'; + +describe('addTxSignatures', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('adds the signatures correctly', async () => { + const hasPubkeySpy = jest.spyOn(UnsignedTx.prototype, 'hasPubkey'); + const addSignatureSpy = jest.spyOn(UnsignedTx.prototype, 'addSignature'); + const unknownPrivateKey = hexToBuffer( + '1d4ff8f6582d995354f5c03a28a043d22aa1bb6aa15879a632134aaf1f225cf4', + ); + const unknownPublicKey = getPublicKey(unknownPrivateKey); + + const unsignedTx = new UnsignedTx( + new BaseTx( + new AvaxBaseTx( + int(), + id(), + [transferableOutput()], + [ + new TransferableInput( + utxoId(), + id(), + new TransferInput(bigIntPr(), Input.fromNative([0])), + ), + new TransferableInput( + utxoId(), + id(), + new TransferInput(bigIntPr(), Input.fromNative([0, 1])), + ), + ], + bytes(), + ), + ), + [], + new AddressMaps([ + new AddressMap([[new Address(testAddress1), 0]]), + new AddressMap([ + [new Address(testAddress2), 0], + [new Address(testAddress1), 1], + ]), + ]), + ); + + await addTxSignatures({ + unsignedTx, + privateKeys: [testPrivateKey1, testPrivateKey2, unknownPrivateKey], + }); + + expect(hasPubkeySpy).toHaveBeenCalledTimes(3); + expect(hasPubkeySpy).toHaveBeenNthCalledWith(1, testPublicKey1); + expect(hasPubkeySpy).toHaveBeenNthCalledWith(2, testPublicKey2); + expect(hasPubkeySpy).toHaveBeenNthCalledWith(3, unknownPublicKey); + + expect(addSignatureSpy).toHaveBeenCalledTimes(2); + expect(addSignatureSpy).toHaveBeenNthCalledWith( + 1, + hexToBuffer( + '0x7b3da43d8e4103d1078061872075cbcbb5de0108f3d897752c894757cf0e9c4113949ca2a5568483763e1fa0e74b4f4dd9b2a6e40909d0729f87c7dddfc1e70601', + ), + ); + expect(addSignatureSpy).toHaveBeenNthCalledWith( + 2, + hexToBuffer( + '0x04e2072e34fd5d7cc729afb8bfe7c5865754c3c448b9b3247b16cabbf06378393edf405274048bef74c02862ae032c0b86dda7c28bebf63f4d1de4f517bd710500', + ), + ); + + expect(unsignedTx.hasAllSignatures()).toBe(true); + }); +}); diff --git a/src/signer/addTxSignatures.ts b/src/signer/addTxSignatures.ts new file mode 100644 index 000000000..319473495 --- /dev/null +++ b/src/signer/addTxSignatures.ts @@ -0,0 +1,23 @@ +import type { UnsignedTx } from '../vms/common/unsignedTx'; +import { getPublicKey, sign } from '../utils'; + +export const addTxSignatures = async ({ + unsignedTx, + privateKeys, +}: { + unsignedTx: UnsignedTx; + privateKeys: Uint8Array[]; +}) => { + const unsignedBytes = unsignedTx.toBytes(); + + await Promise.all( + privateKeys.map(async (privateKey) => { + const publicKey = getPublicKey(privateKey); + + if (unsignedTx.hasPubkey(publicKey)) { + const signature = await sign(unsignedBytes, privateKey); + unsignedTx.addSignature(signature); + } + }), + ); +}; diff --git a/src/signer/index.ts b/src/signer/index.ts new file mode 100644 index 000000000..769691b6d --- /dev/null +++ b/src/signer/index.ts @@ -0,0 +1 @@ +export * from './addTxSignatures'; diff --git a/src/utils/UTXOSet/UTXOSet.ts b/src/utils/UTXOSet/UTXOSet.ts new file mode 100644 index 000000000..e511514a6 --- /dev/null +++ b/src/utils/UTXOSet/UTXOSet.ts @@ -0,0 +1,75 @@ +import type { AssetDict } from './models'; +import type { Utxo } from '../../serializable/avax/utxo'; +import { isTransferOut } from '../typeGuards'; +import { filterDuplicateUTXOs } from '../removeDuplicateUTXOs'; + +export class UtxoSet { + constructor(private utxos: Utxo[]) { + this.utxos = filterDuplicateUTXOs(utxos); + } + + getUTXOs() { + return [...this.utxos]; + } + + /** + * Organize the UTXOs as a dictionary with assetID as the key. + */ + getAssetDict() { + const dict = {}; + this.utxos.forEach((utxo) => { + const assetId = utxo.assetId.toString(); + const valNow = dict[assetId] || []; + dict[assetId] = [...valNow, utxo]; + }); + + const finalDict: AssetDict = {}; + for (const assetID in dict) { + finalDict[assetID] = new UtxoSet(dict[assetID]); + } + return finalDict; + } + + /** + * Return asset IDs that exist in this set. + */ + getAssetIDs() { + const ids = this.utxos.map((utxo) => utxo.assetId.toString()); + // Filter duplicates + return ids.filter((id, index) => ids.indexOf(id) === index); + } + + /** + * Add a UTXO to the set, and return a new set. + * @param utxo + */ + push(utxo: Utxo) { + return new UtxoSet([...this.getUTXOs(), utxo]); + } + + /** + * Return the UTXO ids in this set. + */ + getUTXOIDs() { + return this.utxos.map((utxo) => utxo.ID()); + } + + /** + * Merge 2 UtxoSets and return a new set. + * @param set + */ + merge(set: UtxoSet) { + const newUTXOs = [...this.getUTXOs(), ...set.getUTXOs()]; + return new UtxoSet(newUTXOs); + } + + /** + * Return UTXOs that have TransferOut outputs + */ + getTransferOuts() { + const utxos = this.utxos.filter((utxo) => { + return isTransferOut(utxo.output); + }); + return new UtxoSet(utxos); + } +} diff --git a/src/utils/UTXOSet/index.ts b/src/utils/UTXOSet/index.ts new file mode 100644 index 000000000..e972b21be --- /dev/null +++ b/src/utils/UTXOSet/index.ts @@ -0,0 +1,2 @@ +export * from './models'; +export * from './UTXOSet'; diff --git a/src/utils/UTXOSet/models.ts b/src/utils/UTXOSet/models.ts new file mode 100644 index 000000000..8649b03e5 --- /dev/null +++ b/src/utils/UTXOSet/models.ts @@ -0,0 +1,5 @@ +import type { UtxoSet } from './UTXOSet'; + +export interface AssetDict { + [assetID: string]: UtxoSet; +} diff --git a/src/utils/addChecksum.ts b/src/utils/addChecksum.ts new file mode 100644 index 000000000..b70b3642a --- /dev/null +++ b/src/utils/addChecksum.ts @@ -0,0 +1,6 @@ +import { sha256 } from '@noble/hashes/sha256'; +import { concatBytes } from './buffer'; + +export function addChecksum(data: Uint8Array) { + return concatBytes(data, sha256(data).subarray(-4)); +} diff --git a/src/utils/address.spec.ts b/src/utils/address.spec.ts new file mode 100644 index 000000000..fad589cc6 --- /dev/null +++ b/src/utils/address.spec.ts @@ -0,0 +1,18 @@ +import { base58check } from './base58'; +import * as secp from './secp256k1'; +import * as address from './address'; + +describe('address', () => { + it('parses and formats correctly', async () => { + const key = '24jUJ9vZexUM6expyMcT48LBx27k1m7xpraoV62oSQAHdziao5'; + const privKey = base58check.decode(key); + const pubKey = secp.getPublicKey(privKey); + + const addrBytes = secp.publicKeyBytesToAddress(pubKey); + + const addr = address.format('X', 'avax', addrBytes); + expect(addr).toEqual('X-avax1lnk637g0edwnqc2tn8tel39652fswa3xmgyghf'); + + expect(address.parse(addr)).toEqual(['X', 'avax', addrBytes]); + }); +}); diff --git a/src/utils/address.ts b/src/utils/address.ts new file mode 100644 index 000000000..ae0fa8cbf --- /dev/null +++ b/src/utils/address.ts @@ -0,0 +1,43 @@ +import { bech32 } from '@scure/base'; + +const addressSep = '-'; + +// parse takes in an address string and returns an array of +// [chain ID alias, bech32 HRP, address bytes]. +export function parse(addrStr: string): [string, string, Uint8Array] { + const parts = addrStr.split(addressSep); + if (parts.length < 2) { + throw new Error(`Invalid address: ${addrStr}`); + } + + const chainID = parts[0]; + const rawAddr = parts[1]; + + const [hrp, addr] = parseBech32(rawAddr); + + return [chainID, hrp, addr]; +} + +export function bech32ToBytes(addrStr: string): Uint8Array { + return parse(addrStr)[2]; +} + +// format takes in a chain ID alias, bech32 HRP, and byte slice to produce a +// string for an address. +export function format(chainIDAlias: string, hrp: string, addr: Uint8Array) { + const addrStr = formatBech32(hrp, addr); + return `${chainIDAlias}${addressSep}${addrStr}`; +} + +// parseBech32 takes a bech32 address as input and returns the HRP and data +// section of a bech32 address. +export function parseBech32(addrStr: string): [string, Uint8Array] { + const { prefix, words } = bech32.decode(addrStr); + return [prefix, bech32.fromWords(words)]; +} + +// formatBech32 takes an address's bytes as input and returns a bech32 address. +export function formatBech32(hrp: string, payload: Uint8Array) { + const words = bech32.toWords(payload); + return bech32.encode(hrp, words); +} diff --git a/src/utils/addressMap.spec.ts b/src/utils/addressMap.spec.ts new file mode 100644 index 000000000..2f8b69c45 --- /dev/null +++ b/src/utils/addressMap.spec.ts @@ -0,0 +1,242 @@ +import { jest } from '@jest/globals'; +import { address } from '../fixtures/common'; +import { Address } from '../serializable/fxs/common'; +import { AddressMap, AddressMaps } from './addressMap'; + +describe('AddressMap', () => { + const testAddress1 = address(); + const testAddress2 = Address.fromHex( + '8db97c7cece249c2b98bdc0222cc4c2a57bf52f3', + ); + let testMap: AddressMap; + + beforeEach(() => { + jest.resetAllMocks(); + testMap = new AddressMap(); + }); + + it('sets correctly', () => { + testMap.set(testAddress1, 3); + testMap.set(testAddress2, 1); + expect(testMap.get(testAddress1)).toBe(3); + expect(testMap.get(testAddress2)).toBe(1); + expect(testMap.get(Address.fromHex('333'))).toBeUndefined(); + expect(testMap.has(Address.fromHex('333'))).toBeFalsy(); + expect(testMap.size()).toBe(2); + + const keys: [number, Address][] = []; + testMap.forEach((val, key) => { + keys.push([val, key]); + }); + expect(keys.length).toBe(2); + expect(keys[0][0]).toBe(3); + expect(keys[0][1].toHex()).toBe(testAddress1.toHex()); + expect(keys[1][0]).toBe(1); + expect(keys[1][1].toHex()).toBe(testAddress2.toHex()); + }); + + describe('forEachHex', () => { + it('iterates over the storage correctly', () => { + const callbackMock = jest.fn(); + testMap.set(testAddress1, 3); + testMap.set(testAddress2, 1); + + testMap.forEachHex(callbackMock); + + expect(callbackMock).toBeCalledTimes(2); + expect(callbackMock).toHaveBeenNthCalledWith( + 1, + 3, + testAddress1.toHex(), + testMap.storage, + ); + expect(callbackMock).toHaveBeenNthCalledWith( + 2, + 1, + testAddress2.toHex(), + testMap.storage, + ); + }); + + it('reorders and iterates over the storage correctly', () => { + const callbackMock = jest.fn(); + testMap.set(testAddress1, 3); + testMap.set(testAddress2, 1); + + const expectedSortedMap = new AddressMap([ + [testAddress2, 0], + [testAddress1, 1], + ]); + + testMap.forEachHex(callbackMock, true); + + expect(callbackMock).toBeCalledTimes(2); + expect(callbackMock).toHaveBeenNthCalledWith( + 1, + 0, + testAddress2.toHex(), + expectedSortedMap.storage, + ); + expect(callbackMock).toHaveBeenNthCalledWith( + 2, + 1, + testAddress1.toHex(), + expectedSortedMap.storage, + ); + }); + }); +}); + +describe('AddressMaps', () => { + const testAddress1 = address(); + const testAddress2 = Address.fromHex( + '8db97c7cece249c2b98bdc0222cc4c2a57bf52f3', + ); + const testAddress3 = Address.fromHex( + '8db97c7cece219c2b98bdc0222cc4c2a57bf52f3', + ); + + const testMap1 = new AddressMap(); + testMap1.set(testAddress1, 3); + testMap1.set(testAddress2, 1); + const testMap2 = new AddressMap(); + testMap2.set(testAddress3, 2); + testMap2.set(testAddress2, 6); + + const testAddressMaps = new AddressMaps(); + testAddressMaps.push(testMap1); + testAddressMaps.push(testMap2); + + beforeEach(() => { + jest.resetAllMocks(); + }); + + describe('forEach', () => { + it('iterates over the indices correctly', () => { + const callbackMock = jest.fn(); + testAddressMaps.forEach(callbackMock); + + expect(callbackMock).toBeCalledTimes(3); + expect(callbackMock).toHaveBeenNthCalledWith( + 1, + [[0, 3]], + testAddress1.toHex(), + ); + expect(callbackMock).toHaveBeenNthCalledWith( + 2, + [ + [0, 1], + [1, 6], + ], + testAddress2.toHex(), + ); + expect(callbackMock).toHaveBeenNthCalledWith( + 3, + [[1, 2]], + testAddress3.toHex(), + ); + }); + + it('iterates over the ordered indices correctly', () => { + const callbackMock = jest.fn(); + testAddressMaps.forEach(callbackMock, true); + + expect(callbackMock).toBeCalledTimes(3); + expect(callbackMock).toHaveBeenNthCalledWith( + 1, + [ + [0, 0], + [1, 1], + ], + testAddress2.toHex(), + ); + expect(callbackMock).toHaveBeenNthCalledWith( + 2, + [[0, 1]], + testAddress1.toHex(), + ); + expect(callbackMock).toHaveBeenNthCalledWith( + 3, + [[1, 0]], + testAddress3.toHex(), + ); + }); + }); + + it('pushes and getAddresses correctly', () => { + expect(testAddressMaps.getSigIndicesForAddress(testAddress1)).toStrictEqual( + [[0, 3]], + ); + expect(testAddressMaps.getSigIndicesForAddress(testAddress2)).toStrictEqual( + [ + [0, 1], + [1, 6], + ], + ); + expect(testAddressMaps.getSigIndicesForAddress(testAddress3)).toStrictEqual( + [[1, 2]], + ); + + // ordered + expect( + testAddressMaps.getSigIndicesForAddress(testAddress1, true), + ).toStrictEqual([[0, 1]]); + expect( + testAddressMaps.getSigIndicesForAddress(testAddress2, true), + ).toStrictEqual([ + [0, 0], + [1, 1], + ]); + expect( + testAddressMaps.getSigIndicesForAddress(testAddress3, true), + ).toStrictEqual([[1, 0]]); + + const testAddressMaps2 = new AddressMaps(); + testAddressMaps.push(testMap1); + testAddressMaps.push(testMap2); + + testAddressMaps2.merge(testAddressMaps); + expect( + testAddressMaps2.getSigIndicesForAddress(testAddress1), + ).toStrictEqual([ + [0, 3], + [2, 3], + ]); + expect( + testAddressMaps2.getSigIndicesForAddress(testAddress2), + ).toStrictEqual([ + [0, 1], + [1, 6], + [2, 1], + [3, 6], + ]); + expect( + testAddressMaps2.getSigIndicesForAddress(testAddress3), + ).toStrictEqual([ + [1, 2], + [3, 2], + ]); + + // ordered + expect( + testAddressMaps2.getSigIndicesForAddress(testAddress1, true), + ).toStrictEqual([ + [0, 1], + [2, 1], + ]); + expect( + testAddressMaps2.getSigIndicesForAddress(testAddress2, true), + ).toStrictEqual([ + [0, 0], + [1, 1], + [2, 0], + [3, 1], + ]); + expect( + testAddressMaps2.getSigIndicesForAddress(testAddress3, true), + ).toStrictEqual([ + [1, 0], + [3, 0], + ]); + }); +}); diff --git a/src/utils/addressMap.ts b/src/utils/addressMap.ts new file mode 100644 index 000000000..0a6c52e06 --- /dev/null +++ b/src/utils/addressMap.ts @@ -0,0 +1,183 @@ +import type { TransferableInput } from '../serializable'; +import type { Utxo } from '../serializable/avax/utxo'; +import { Address } from '../serializable/fxs/common'; +import { addressesFromBytes } from './addressesFromBytes'; +import { hexToBuffer } from './buffer'; +import { matchOwners } from './matchOwners'; + +export class AddressMap { + constructor(initialData: [Address, number][] = []) { + initialData.forEach(([address, num]) => { + this.set(address, num); + }); + } + + storage = new Map(); + + set(add: Address, item: number) { + this.storage.set(add.toHex(), item); + return this; + } + + toJSON() { + return Array.from(this.storage.entries()); + } + + static fromJSON(maps: [string, number][]) { + return new AddressMap( + maps.map(([addressHex, idx]) => [Address.fromHex(addressHex), idx]), + ); + } + + get(add: Address): number | undefined { + return this.storage.get(add.toHex()); + } + + has(add: Address): boolean { + return this.storage.has(add.toHex()); + } + + size() { + return this.storage.size; + } + + forEach(cb: (value: number, key: Address) => void) { + return this.storage.forEach((val, key) => cb(val, Address.fromHex(key))); + } + + forEachHex( + cb: (value: number, key: string) => void, + shouldReorderWithoutGaps = false, + ) { + // reorder the sigindices, so they start from index 0, without gaps + if (shouldReorderWithoutGaps) { + return AddressMap.fromJSON( + [...this.storage.entries()] + .sort((a, b) => a[1] - b[1]) + .map(([addressHex], index) => [addressHex, index]), + ).storage.forEach(cb); + } + + return this.storage.forEach(cb); + } + + values() { + return this.storage.values(); + } +} + +export class AddressMaps { + constructor(addressMaps: AddressMap[] = []) { + if (addressMaps.length) { + this.push(...addressMaps); + } + } + + private storage: AddressMap[] = []; + private index: Record = {}; + private orderedIndex: Record = {}; + + push(...addressMaps: AddressMap[]) { + addressMaps.forEach((addressMap) => { + addressMap.forEachHex((index, addressHex) => { + this.index[addressHex] = this.index[addressHex] ?? []; + this.index[addressHex].push([this.storage.length, index]); + }); + + addressMap.forEachHex((index, addressHex) => { + this.orderedIndex[addressHex] = this.orderedIndex[addressHex] ?? []; + this.orderedIndex[addressHex].push([this.storage.length, index]); + }, true); + + this.storage.push(addressMap); + }); + } + + // this is a stopgap to quickly fix AddressMap not deriving the order post sorting TransferableInputs. Can probably + // be simplified a lot by just deriving the sigIndicies right before returning the unsingedTx + static fromTransferableInputs( + inputs: TransferableInput[], + inputUtxos: Utxo[], + minIssuanceTime: bigint, + fromAddressesBytes?: Uint8Array[], + ) { + const utxoMap = inputUtxos.reduce((agg, utxo) => { + return agg.set(utxo.utxoId.ID(), utxo); + }, new Map()); + + const addressMaps = inputs.map((input, i) => { + const utxo = utxoMap.get(input.utxoID.ID()); + if (!utxo) throw new Error('input utxo not found'); + + if (fromAddressesBytes) { + const fromAddresses = addressesFromBytes(fromAddressesBytes); + + const sigData = matchOwners( + utxo.getOutputOwners(), + fromAddresses, + minIssuanceTime, + input.sigIndicies(), // we care about signers only + ); + + if (!sigData) { + throw new Error(`input ${i} has no valid owners`); + } + return sigData.addressMap; + } + + // in case fromAddressesBytes were not provided, + // get the them from the provided UTXOs using the inputs' signature indices + const addressMapData = input.sigIndicies().map((sigIndex) => { + const address = utxo.getOutputOwners().addrs[sigIndex]; + return [address, sigIndex] as [Address, number]; + }); + + return new AddressMap(addressMapData); + }); + + return new AddressMaps(addressMaps); + } + + toJSON() { + return this.storage; + } + + static fromJSON(addressMaps: [string, number][][]) { + return new AddressMaps(addressMaps.map((map) => AddressMap.fromJSON(map))); + } + + getAddresses(): Uint8Array[] { + return Object.keys(this.index).map((hex) => hexToBuffer(hex)); + } + + forEach( + cb: (coordinates: [number, number][], address: string) => void, + useReorderedIndices = false, + ) { + Object.entries( + useReorderedIndices ? this.orderedIndex : this.index, + ).forEach(([address, coordinates]) => { + cb(coordinates, address); + }); + } + + has(address: Address): boolean { + return address.toHex() in this.index; + } + + toArray() { + return this.storage; + } + + merge(newMap: AddressMaps) { + newMap.toArray().forEach((map) => this.push(map)); + } + + getSigIndicesForAddress(address: Address, useReorderedIndices = false) { + if (useReorderedIndices) { + return this.orderedIndex[address.toHex()]; + } + + return this.index[address.toHex()]; + } +} diff --git a/src/utils/addressesFromBytes.ts b/src/utils/addressesFromBytes.ts new file mode 100644 index 000000000..ffa53525e --- /dev/null +++ b/src/utils/addressesFromBytes.ts @@ -0,0 +1,5 @@ +import { Address } from '../serializable/fxs/common'; + +export function addressesFromBytes(bytes: Uint8Array[]): Address[] { + return bytes.map((b) => new Address(b)); +} diff --git a/src/utils/avaxToNAvax.ts b/src/utils/avaxToNAvax.ts new file mode 100644 index 000000000..06ce3208e --- /dev/null +++ b/src/utils/avaxToNAvax.ts @@ -0,0 +1 @@ +export const AvaxToNAvax = (num: number) => BigInt(num * 1e9); diff --git a/src/utils/base58.spec.ts b/src/utils/base58.spec.ts new file mode 100644 index 000000000..bfedbca84 --- /dev/null +++ b/src/utils/base58.spec.ts @@ -0,0 +1,51 @@ +import { base58, base58check } from './base58'; + +describe('base58', () => { + it('encodes and decodes correctly', async () => { + const tests = [ + { + buffer: new Uint8Array([ + 0x00, 0xfe, 0x7b, 0xd0, 0xe0, 0x03, 0x2b, 0x8d, 0x2c, 0x11, 0x56, + 0x84, 0x1f, 0xa0, 0x60, 0x14, 0x56, 0xaa, 0xac, 0x8f, 0x3c, 0x0e, + 0xf1, 0x6d, 0x8c, + ]), + string: '1QCaxc8hutpdZ62iKZsn1TCG3nh7uPZojq', + checksum: '13cp39pSRSMbaxjaXZfFLXuiiK4FHDBQRBm35ab2', + }, + { + buffer: new Uint8Array([ + 0x00, 0x8b, 0x46, 0xd2, 0x54, 0xa0, 0x83, 0xd1, 0x0c, 0xe3, 0xf1, + 0x2f, 0x5e, 0x95, 0x43, 0xba, 0x73, 0x1f, 0x21, 0xf2, 0xa9, 0x6f, + 0xeb, 0x2a, 0x60, + ]), + string: '1DhRmSGnhPjUaVPAj48zgPV9e2oRhAQFUb', + checksum: '12S5vHShaePQQAXjmjLC87s1Kxi9uM6YEkS2K5Hh', + }, + { + buffer: new Uint8Array([ + 0x00, 0x45, 0x7a, 0x36, 0xbb, 0x6b, 0xee, 0xe4, 0xea, 0xd3, 0x60, + 0x95, 0x37, 0xda, 0x65, 0x8c, 0x02, 0x62, 0x3e, 0xbe, 0x88, 0x08, + 0x6d, 0x18, 0xc7, + ]), + string: '17LN2oPYRYsXS9TdYdXCCDvF2FegshLDU2', + checksum: '1iSthZt2SDsWS3ELSjFkRsikVNtWDT1GmYzvPQQ', + }, + { + buffer: new Uint8Array([ + 0x00, 0x28, 0x7a, 0x57, 0xcd, 0xbe, 0x7b, 0x5c, 0xf8, 0x0f, 0x76, + 0x30, 0x9b, 0x29, 0x75, 0x6d, 0x25, 0x86, 0x60, 0x07, 0x2b, 0x30, + 0xda, 0x67, 0x7b, + ]), + string: '14h2bDLZSuvRFhUL45VjPHJcW667mmRAAn', + checksum: '1R9XA3AmWSAkSF6krDfnDmLjMQbtuz7ED7jDMbt', + }, + ]; + + for (const { buffer, string, checksum } of tests) { + expect(base58.encode(buffer)).toEqual(string); + expect(base58.decode(string)).toEqual(buffer); + expect(base58check.encode(buffer)).toEqual(checksum); + expect(base58check.decode(checksum)).toEqual(buffer); + } + }); +}); diff --git a/src/utils/base58.ts b/src/utils/base58.ts index 007783d82..dcbb53d99 100644 --- a/src/utils/base58.ts +++ b/src/utils/base58.ts @@ -1,133 +1,15 @@ -/** - * @packageDocumentation - * @module Utils-Base58 - */ -import BN from "bn.js" -import { Buffer } from "buffer/" -import { Base58Error } from "../utils/errors" - -/** - * A Base58 class that uses the cross-platform Buffer module. Built so that Typescript - * will accept the code. - * - * ```js - * let b58:Base58 = new Base58(); - * let str:string = b58.encode(somebuffer); - * let buff:Buffer = b58.decode(somestring); - * ``` - */ -export class Base58 { - private static instance: Base58 - - private constructor() {} - - /** - * Retrieves the Base58 singleton. - */ - static getInstance(): Base58 { - if (!Base58.instance) { - Base58.instance = new Base58() - } - return Base58.instance - } - - protected b58alphabet: string = - "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" - - protected alphabetIdx0 = "1" - - protected b58 = [ - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 255, 255, 255, 255, 255, 255, - 255, 9, 10, 11, 12, 13, 14, 15, 16, 255, 17, 18, 19, 20, 21, 255, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, 32, 255, 255, 255, 255, 255, 255, 33, 34, - 35, 36, 37, 38, 39, 40, 41, 42, 43, 255, 44, 45, 46, 47, 48, 49, 50, 51, 52, - 53, 54, 55, 56, 57, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255 - ] - - protected big58Radix: BN = new BN(58) - - protected bigZero: BN = new BN(0) - - /** - * Encodes a {@link https://github.com/feross/buffer|Buffer} as a base-58 string - * - * @param buff A {@link https://github.com/feross/buffer|Buffer} to encode - * - * @returns A base-58 string. - */ - encode = (buff: Buffer): string => { - let x: BN = new BN(buff.toString("hex"), "hex", "be") - let answer: string = "" // = Buffer.alloc(buff.length*136/100, 0); - while (x.cmp(this.bigZero) > 0) { - const mod: BN = x.mod(this.big58Radix) - x = x.div(this.big58Radix) - answer += this.b58alphabet[mod.toNumber()] - } - - for (let i: number = 0; i < buff.length; i++) { - if (buff.readUInt8(i) !== 0) { - break - } - answer += this.alphabetIdx0 - } - return answer.split("").reverse().join("") - } - - /** - * Decodes a base-58 into a {@link https://github.com/feross/buffer|Buffer} - * - * @param b A base-58 string to decode - * - * @returns A {@link https://github.com/feross/buffer|Buffer} from the decoded string. - */ - decode = (b: string): Buffer => { - const answer: BN = new BN(0) - const j: BN = new BN(1) - - for (let i: number = b.length - 1; i >= 0; i--) { - const tmp: number = this.b58[b.charCodeAt(i)] - if (tmp === 255) { - throw new Base58Error( - "Error - Base58.decode: not a valid base58 string" - ) - } - const scratch: BN = new BN(tmp) - scratch.imul(j) - answer.iadd(scratch) - j.imul(this.big58Radix) - } - - /* we need to make sure the prefaced 0's are put back to be even in this string */ - let anshex = answer.toString("hex") - anshex = anshex.length % 2 ? `0${anshex}` : anshex - - /** - * We need to replace all zeros that were removed during our conversation process. - * This ensures the buffer returns is the appropriate length. - */ - const tmpval: Buffer = Buffer.from(anshex, "hex") - let numZeros: number - for (numZeros = 0; numZeros < b.length; numZeros++) { - if (b[`${numZeros}`] !== this.alphabetIdx0) { - break - } - } - const xlen: number = numZeros + tmpval.length - const result: Buffer = Buffer.alloc(xlen, 0) - tmpval.copy(result, numZeros) - - return result - } -} +import { base58 } from '@scure/base'; +import type { BytesCoder } from '@scure/base'; +import { sha256 } from '@noble/hashes/sha256'; +import { concatBytes } from './buffer'; + +export const base58check: BytesCoder = { + encode(data) { + return base58.encode(concatBytes(data, sha256(data).subarray(-4))); + }, + decode(string) { + return base58.decode(string).subarray(0, -4); + }, +}; + +export { base58 } from '@scure/base'; diff --git a/src/utils/bigintMath.ts b/src/utils/bigintMath.ts new file mode 100644 index 000000000..ccf497569 --- /dev/null +++ b/src/utils/bigintMath.ts @@ -0,0 +1,2 @@ +export const bigIntMin = (...args: bigint[]): bigint => + args.reduce((m, e) => (e < m ? e : m)); diff --git a/src/utils/bintools.ts b/src/utils/bintools.ts deleted file mode 100644 index aacda2af3..000000000 --- a/src/utils/bintools.ts +++ /dev/null @@ -1,411 +0,0 @@ -/** - * @packageDocumentation - * @module Utils-BinTools - */ -import BN from "bn.js" -import { Buffer } from "buffer/" -import createHash from "create-hash" -import * as bech32 from "bech32" -import { Base58 } from "./base58" -import { Bech32Error, ChecksumError, HexError } from "../utils/errors" -import { isAddress } from "ethers" - -/** - * A class containing tools useful in interacting with binary data cross-platform using - * nodejs & javascript. - * - * This class should never be instantiated directly. Instead, - * invoke the "BinTools.getInstance()" static * function to grab the singleton - * instance of the tools. - * - * Everything in this library uses - * the {@link https://github.com/feross/buffer|feross's Buffer class}. - * - * ```js - * const bintools: BinTools = BinTools.getInstance(); - * const b58str: = bintools.bufferToB58(Buffer.from("Wubalubadubdub!")); - * ``` - */ -export default class BinTools { - private static instance: BinTools - - private constructor() { - this.b58 = Base58.getInstance() - } - - private b58: Base58 - - /** - * Retrieves the BinTools singleton. - */ - static getInstance(): BinTools { - if (!BinTools.instance) { - BinTools.instance = new BinTools() - } - return BinTools.instance - } - - /** - * Returns true if base64, otherwise false - * @param str the string to verify is Base64 - */ - isBase64(str: string) { - if (str === "" || str.trim() === "") { - return false - } - try { - let b64: Buffer = Buffer.from(str, "base64") - return b64.toString("base64") === str - } catch (err) { - return false - } - } - - /** - * Returns true if cb58, otherwise false - * @param cb58 the string to verify is cb58 - */ - isCB58(cb58: string): boolean { - return this.isBase58(cb58) - } - - /** - * Returns true if base58, otherwise false - * @param base58 the string to verify is base58 - */ - isBase58(base58: string): boolean { - if (base58 === "" || base58.trim() === "") { - return false - } - try { - return this.b58.encode(this.b58.decode(base58)) === base58 - } catch (err) { - return false - } - } - - /** - * Returns true if hexidecimal, otherwise false - * @param hex the string to verify is hexidecimal - */ - isHex(hex: string): boolean { - if (hex === "" || hex.trim() === "") { - return false - } - const startsWith0x = hex.startsWith("0x") - const matchResult = startsWith0x - ? hex.slice(2).match(/[0-9A-Fa-f]/g) - : hex.match(/[0-9A-Fa-f]/g) - if ( - (startsWith0x && hex.length - 2 == matchResult.length) || - hex.length == matchResult.length - ) { - return true - } else { - return false - } - } - - /** - * Returns true if decimal, otherwise false - * @param str the string to verify is hexidecimal - */ - isDecimal(str: string) { - if (str === "" || str.trim() === "") { - return false - } - try { - return new BN(str, 10).toString(10) === str.trim() - } catch (err) { - return false - } - } - - /** - * Returns true if meets requirements to parse as an address as Bech32 on X-Chain or P-Chain, otherwise false - * @param address the string to verify is address - */ - isPrimaryBechAddress = (address: string): boolean => { - const parts: string[] = address.trim().split("-") - if (parts.length !== 2) { - return false - } - try { - bech32.bech32.fromWords(bech32.bech32.decode(parts[1]).words) - } catch (err) { - return false - } - return true - } - - /** - * Produces a string from a {@link https://github.com/feross/buffer|Buffer} - * representing a string. ONLY USED IN TRANSACTION FORMATTING, ASSUMED LENGTH IS PREPENDED. - * - * @param buff The {@link https://github.com/feross/buffer|Buffer} to convert to a string - */ - bufferToString = (buff: Buffer): string => - this.copyFrom(buff, 2).toString("utf8") - - /** - * Produces a {@link https://github.com/feross/buffer|Buffer} from a string. ONLY USED IN TRANSACTION FORMATTING, LENGTH IS PREPENDED. - * - * @param str The string to convert to a {@link https://github.com/feross/buffer|Buffer} - */ - stringToBuffer = (str: string): Buffer => { - const buff: Buffer = Buffer.alloc(2 + str.length) - buff.writeUInt16BE(str.length, 0) - buff.write(str, 2, str.length, "utf8") - return buff - } - - /** - * Makes a copy (no reference) of a {@link https://github.com/feross/buffer|Buffer} - * over provided indecies. - * - * @param buff The {@link https://github.com/feross/buffer|Buffer} to copy - * @param start The index to start the copy - * @param end The index to end the copy - */ - copyFrom = ( - buff: Buffer, - start: number = 0, - end: number = undefined - ): Buffer => { - if (end === undefined) { - end = buff.length - } - return Buffer.from(Uint8Array.prototype.slice.call(buff.slice(start, end))) - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} and returns a base-58 string of - * the {@link https://github.com/feross/buffer|Buffer}. - * - * @param buff The {@link https://github.com/feross/buffer|Buffer} to convert to base-58 - */ - bufferToB58 = (buff: Buffer): string => this.b58.encode(buff) - - /** - * Takes a base-58 string and returns a {@link https://github.com/feross/buffer|Buffer}. - * - * @param b58str The base-58 string to convert - * to a {@link https://github.com/feross/buffer|Buffer} - */ - b58ToBuffer = (b58str: string): Buffer => this.b58.decode(b58str) - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} and returns an ArrayBuffer. - * - * @param buff The {@link https://github.com/feross/buffer|Buffer} to - * convert to an ArrayBuffer - */ - fromBufferToArrayBuffer = (buff: Buffer): ArrayBuffer => { - const ab = new ArrayBuffer(buff.length) - const view = new Uint8Array(ab) - for (let i: number = 0; i < buff.length; ++i) { - view[`${i}`] = buff[`${i}`] - } - return view - } - - /** - * Takes an ArrayBuffer and converts it to a {@link https://github.com/feross/buffer|Buffer}. - * - * @param ab The ArrayBuffer to convert to a {@link https://github.com/feross/buffer|Buffer} - */ - fromArrayBufferToBuffer = (ab: ArrayBuffer): Buffer => { - const buf = Buffer.alloc(ab.byteLength) - for (let i: number = 0; i < ab.byteLength; ++i) { - buf[`${i}`] = ab[`${i}`] - } - return buf - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} and converts it - * to a {@link https://github.com/indutny/bn.js/|BN}. - * - * @param buff The {@link https://github.com/feross/buffer|Buffer} to convert - * to a {@link https://github.com/indutny/bn.js/|BN} - */ - fromBufferToBN = (buff: Buffer): BN => { - if (typeof buff === "undefined") { - return undefined - } - return new BN(buff.toString("hex"), 16, "be") - } - /** - * Takes a {@link https://github.com/indutny/bn.js/|BN} and converts it - * to a {@link https://github.com/feross/buffer|Buffer}. - * - * @param bn The {@link https://github.com/indutny/bn.js/|BN} to convert - * to a {@link https://github.com/feross/buffer|Buffer} - * @param length The zero-padded length of the {@link https://github.com/feross/buffer|Buffer} - */ - fromBNToBuffer = (bn: BN, length?: number): Buffer => { - if (typeof bn === "undefined") { - return undefined - } - const newarr = bn.toArray("be") - /** - * CKC: Still unsure why bn.toArray with a "be" and a length do not work right. Bug? - */ - if (length) { - // bn toArray with the length parameter doesn't work correctly, need this. - const x = length - newarr.length - for (let i: number = 0; i < x; i++) { - newarr.unshift(0) - } - } - return Buffer.from(newarr) - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} and adds a checksum, returning - * a {@link https://github.com/feross/buffer|Buffer} with the 4-byte checksum appended. - * - * @param buff The {@link https://github.com/feross/buffer|Buffer} to append a checksum - */ - addChecksum = (buff: Buffer): Buffer => { - const hashslice: Buffer = Buffer.from( - createHash("sha256").update(buff).digest().slice(28) - ) - return Buffer.concat([buff, hashslice]) - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} with an appended 4-byte checksum - * and returns true if the checksum is valid, otherwise false. - * - * @param b The {@link https://github.com/feross/buffer|Buffer} to validate the checksum - */ - validateChecksum = (buff: Buffer): boolean => { - const checkslice: Buffer = buff.slice(buff.length - 4) - const hashslice: Buffer = Buffer.from( - createHash("sha256") - .update(buff.slice(0, buff.length - 4)) - .digest() - .slice(28) - ) - return checkslice.toString("hex") === hashslice.toString("hex") - } - - /** - * Takes a {@link https://github.com/feross/buffer|Buffer} and returns a base-58 string with - * checksum as per the cb58 standard. - * - * @param bytes A {@link https://github.com/feross/buffer|Buffer} to serialize - * - * @returns A serialized base-58 string of the Buffer. - */ - cb58Encode = (bytes: Buffer): string => { - const x: Buffer = this.addChecksum(bytes) - return this.bufferToB58(x) - } - - /** - * Takes a cb58 serialized {@link https://github.com/feross/buffer|Buffer} or base-58 string - * and returns a {@link https://github.com/feross/buffer|Buffer} of the original data. Throws on error. - * - * @param bytes A cb58 serialized {@link https://github.com/feross/buffer|Buffer} or base-58 string - */ - cb58Decode = (bytes: Buffer | string): Buffer => { - if (typeof bytes === "string") { - bytes = this.b58ToBuffer(bytes) - } - if (this.validateChecksum(bytes)) { - return this.copyFrom(bytes, 0, bytes.length - 4) - } - throw new ChecksumError("Error - BinTools.cb58Decode: invalid checksum") - } - - cb58DecodeWithChecksum = (bytes: Buffer | string): string => { - if (typeof bytes === "string") { - bytes = this.b58ToBuffer(bytes) - } - if (this.validateChecksum(bytes)) { - return `0x${this.copyFrom(bytes, 0, bytes.length).toString("hex")}` - } - throw new ChecksumError("Error - BinTools.cb58Decode: invalid checksum") - } - - addressToString = (hrp: string, chainid: string, bytes: Buffer): string => - `${chainid}-${bech32.bech32.encode(hrp, bech32.bech32.toWords(bytes))}` - - stringToAddress = (address: string, hrp?: string): Buffer => { - if (address.substring(0, 2) === "0x") { - // ETH-style address - if (isAddress(address)) { - return Buffer.from(address.substring(2), "hex") - } else { - throw new HexError("Error - Invalid address") - } - } - // Bech32 addresses - const parts: string[] = address.trim().split("-") - - if (parts.length < 2) { - throw new Bech32Error("Error - Valid address should include -") - } - - if (parts[0].length < 1) { - throw new Bech32Error("Error - Valid address must have prefix before -") - } - - const split: number = parts[1].lastIndexOf("1") - if (split < 0) { - throw new Bech32Error("Error - Valid address must include separator (1)") - } - - const humanReadablePart: string = parts[1].slice(0, split) - if (humanReadablePart.length < 1) { - throw new Bech32Error("Error - HRP should be at least 1 character") - } - - if ( - humanReadablePart !== "avax" && - humanReadablePart !== "fuji" && - humanReadablePart != "local" && - humanReadablePart != "custom" && - humanReadablePart != hrp - ) { - throw new Bech32Error("Error - Invalid HRP") - } - - return Buffer.from( - bech32.bech32.fromWords(bech32.bech32.decode(parts[1]).words) - ) - } - - /** - * Takes an address and returns its {@link https://github.com/feross/buffer|Buffer} - * representation if valid. A more strict version of stringToAddress. - * - * @param addr A string representation of the address - * @param blockchainID A cb58 encoded string representation of the blockchainID - * @param alias A chainID alias, if any, that the address can also parse from. - * @param addrlen VMs can use any addressing scheme that they like, so this is the appropriate number of address bytes. Default 20. - * - * @returns A {@link https://github.com/feross/buffer|Buffer} for the address if valid, - * undefined if not valid. - */ - parseAddress = ( - addr: string, - blockchainID: string, - alias: string = undefined, - addrlen: number = 20 - ): Buffer => { - const abc: string[] = addr.split("-") - if ( - abc.length === 2 && - ((alias && abc[0] === alias) || (blockchainID && abc[0] === blockchainID)) - ) { - const addrbuff = this.stringToAddress(addr) - if ((addrlen && addrbuff.length === addrlen) || !addrlen) { - return addrbuff - } - } - return undefined - } -} diff --git a/src/utils/buffer.spec.ts b/src/utils/buffer.spec.ts new file mode 100644 index 000000000..2e87b80b2 --- /dev/null +++ b/src/utils/buffer.spec.ts @@ -0,0 +1,80 @@ +import { bufferToBigInt, bufferToNumber, padLeft } from './buffer'; + +describe('bufferToBigInt', () => { + it('converts Uint8Arrays correctly', async () => { + const tests = [ + { + buffer: new Uint8Array([0x00, 0x00]), + number: 0n, + }, + { + buffer: new Uint8Array([0x00, 0x00, 0x00, 0x07]), + number: 7n, + }, + { + buffer: new Uint8Array([ + 0x00, 0x00, 0x00, 0x00, 0x77, 0x35, 0x94, 0x00, + ]), + number: 2_000_000_000n, + }, + ]; + + for (const { buffer, number } of tests) { + expect(bufferToBigInt(buffer)).toEqual(number); + } + }); +}); + +describe('bufferToNumber', () => { + it('converts Uint8Arrays correctly', async () => { + const tests = [ + { + buffer: new Uint8Array([0x00, 0x00]), + number: 0, + }, + { + buffer: new Uint8Array([0x00, 0x00, 0x00, 0x07]), + number: 7, + }, + { + buffer: new Uint8Array([ + 0x00, 0x00, 0x00, 0x00, 0x77, 0x35, 0x94, 0x00, + ]), + number: 2_000_000_000, + }, + ]; + + for (const { buffer, number } of tests) { + expect(bufferToNumber(buffer)).toEqual(number); + } + }); +}); + +describe('padLeft', () => { + it('pads to 2 bytes', () => { + const res = padLeft(new Uint8Array([0x72]), 2); + expect(res).toStrictEqual(new Uint8Array([0x00, 0x72])); + }); + + it('pads to 4 bytes', () => { + const res = padLeft(new Uint8Array([0x72]), 4); + expect(res).toStrictEqual(new Uint8Array([0x00, 0x00, 0x00, 0x72])); + }); + + it('pads to 8 bytes', () => { + const res = padLeft(new Uint8Array([0x72]), 8); + expect(res).toStrictEqual( + new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x72]), + ); + }); + + it('pads if empty array', () => { + const res = padLeft(new Uint8Array([]), 2); + expect(res).toStrictEqual(new Uint8Array([0x00, 0x00])); + }); + + it('no-ops if already at size', () => { + const res = padLeft(new Uint8Array([0xaf, 0x72, 0x72]), 2); + expect(res).toStrictEqual(new Uint8Array([0xaf, 0x72, 0x72])); + }); +}); diff --git a/src/utils/buffer.ts b/src/utils/buffer.ts new file mode 100644 index 000000000..fcaaf1201 --- /dev/null +++ b/src/utils/buffer.ts @@ -0,0 +1,36 @@ +import { bytesToHex, concatBytes, hexToBytes } from '@noble/hashes/utils'; +import { add0x, strip0x } from 'micro-eth-signer'; + +export function bufferToBigInt(buf: Uint8Array) { + return BigInt(bufferToHex(buf)); +} + +export function bufferToNumber(buf: Uint8Array) { + return Number.parseInt(bytesToHex(buf), 16); +} + +export function bufferToHex(buf: Uint8Array) { + return add0x(bytesToHex(buf)); +} + +export function hexToBuffer(hex: string) { + hex = strip0x(hex); + if (hex.length & 1) { + hex = '0' + hex; + } + return hexToBytes(hex); +} + +export function padLeft(bytes: Uint8Array, length: number) { + const offset = length - bytes.length; + + if (offset <= 0) { + return bytes; + } + + const out = new Uint8Array(length); + out.set(bytes, offset); + return out; +} + +export { concatBytes, strip0x, add0x }; diff --git a/src/utils/builderUtils.ts b/src/utils/builderUtils.ts new file mode 100644 index 000000000..79a345322 --- /dev/null +++ b/src/utils/builderUtils.ts @@ -0,0 +1,46 @@ +import { TransferableInput } from '../serializable/avax'; +import type { Utxo } from '../serializable/avax/utxo'; +import { addressesFromBytes } from './addressesFromBytes'; +import { matchOwners } from './matchOwners'; +import { isTransferOut } from './typeGuards'; + +type GetImportedInputsFromUtxosOutput = { + importedInputs: TransferableInput[]; + inputUTXOs: Utxo[]; + importedAmounts: Record; +}; + +export const getImportedInputsFromUtxos = ( + utxos: Utxo[], + fromAddressesBytes: Uint8Array[], + minIssuanceTime: bigint, +): GetImportedInputsFromUtxosOutput => { + const fromAddresses = addressesFromBytes(fromAddressesBytes); + const outputs: GetImportedInputsFromUtxosOutput = { + importedInputs: [], + inputUTXOs: [], + importedAmounts: {}, + }; + + return utxos.reduce((agg, utxo): GetImportedInputsFromUtxosOutput => { + const { importedInputs, inputUTXOs, importedAmounts } = agg; + const out = utxo.output; + if (!isTransferOut(out)) return agg; + + const sigData = matchOwners( + out.outputOwners, + fromAddresses, + minIssuanceTime, + ); + + if (!sigData) return agg; + + importedInputs.push( + TransferableInput.fromUtxoAndSigindicies(utxo, sigData.sigIndicies), + ); + inputUTXOs.push(utxo); + importedAmounts[utxo.getAssetId()] = + (importedAmounts[utxo.getAssetId()] ?? 0n) + out.amount(); + return agg; + }, outputs); +}; diff --git a/src/utils/bytesCompare.spec.ts b/src/utils/bytesCompare.spec.ts new file mode 100644 index 000000000..550b046e0 --- /dev/null +++ b/src/utils/bytesCompare.spec.ts @@ -0,0 +1,58 @@ +import { bytesCompare, bytesEqual } from './bytesCompare'; + +describe('bytesCompare', () => { + it('compares bytes', () => { + const specs = [ + { + bytes1: new Uint8Array([0, 0, 0, 0, 0, 1]), + bytes2: new Uint8Array([0, 0, 0, 0, 0, 0]), + expected: 1, + }, + { + bytes1: new Uint8Array([0, 0, 0, 0, 0, 0]), + bytes2: new Uint8Array([0, 0, 0, 0, 0, 1]), + expected: -1, + }, + { + bytes1: new Uint8Array([0, 0, 0, 0, 0, 1]), + bytes2: new Uint8Array([1, 0, 0, 0, 0, 0]), + expected: -1, + }, + { + bytes1: new Uint8Array([0, 0, 0, 0, 0, 0]), + bytes2: new Uint8Array([0, 0, 0, 0, 0, 0]), + expected: 0, + }, + ]; + + specs.forEach(({ bytes1, bytes2, expected }) => { + expect(bytesCompare(bytes1, bytes2)).toBe(expected); + }); + }); +}); + +describe('bytesEqual', () => { + it('equal bytes', () => { + const specs = [ + { + bytes1: new Uint8Array([0, 0, 0, 0, 0, 0]), + bytes2: new Uint8Array([0, 0, 0, 0, 0, 0]), + expected: true, + }, + { + bytes1: new Uint8Array([0, 0, 0, 0, 0, 0]), + bytes2: new Uint8Array([0, 0, 0, 0, 0, 1]), + expected: false, + }, + { + bytes1: new Uint8Array([0, 0, 0, 0, 0]), + bytes2: new Uint8Array([0, 0, 0, 0, 0, 1]), + expected: false, + }, + ]; + + specs.forEach(({ bytes1, bytes2, expected }) => { + expect(bytesEqual(bytes1, bytes2)).toBe(expected); + }); + }); +}); diff --git a/src/utils/bytesCompare.ts b/src/utils/bytesCompare.ts new file mode 100644 index 000000000..b6363827e --- /dev/null +++ b/src/utils/bytesCompare.ts @@ -0,0 +1,22 @@ +export const bytesCompare = (a: Uint8Array, b: Uint8Array) => { + let i; + for (i = 0; i < a.length && i < b.length; i++) { + const aByte = a[i]; + const bByte = b[i]; + if (aByte !== bByte) { + return aByte - bByte; + } + } + if (i === a.length && i === b.length) { + // throw error? + return 0; + } + return i === a.length ? -1 : 1; +}; + +export const bytesEqual = (bytes1: Uint8Array, bytes2: Uint8Array): boolean => { + if (bytes1.length !== bytes2.length) { + return false; + } + return bytesCompare(bytes1, bytes2) === 0; +}; diff --git a/src/utils/consolidate.spec.ts b/src/utils/consolidate.spec.ts new file mode 100644 index 000000000..d838e539f --- /dev/null +++ b/src/utils/consolidate.spec.ts @@ -0,0 +1,55 @@ +import { consolidate } from './consolidate'; + +describe('consolidate', () => { + it('combines elements', () => { + const arr = [true, false, true, false]; + const canCombine = (a: boolean, b: boolean) => a === b; + const combine = (a: boolean) => a; + + const consolidated = consolidate(arr, canCombine, combine); + + expect(consolidated.length).toEqual(2); + expect(consolidated[0]).toEqual(true); + expect(consolidated[1]).toEqual(false); + }); + + it('preserves combining order', () => { + const arr = [1, 2, 3, 4, 5, 6]; + const canCombine = (a: number, b: number) => a % 2 === 0 && b % 2 === 0; + const combine = (a: number, b: number) => a + b; + + const consolidated = consolidate(arr, canCombine, combine); + + expect(consolidated.length).toEqual(4); + expect(consolidated[0]).toEqual(1); + expect(consolidated[1]).toEqual(12); + expect(consolidated[2]).toEqual(3); + expect(consolidated[3]).toEqual(5); + }); + + it('returns identical array if cannot combine anything', () => { + const arr = [1, 2, 3, 4, 5, 6]; + const canCombine = () => false; + const combine = (a: number, b: number) => a + b; + + const consolidated = consolidate(arr, canCombine, combine); + + expect(consolidated.length).toEqual(arr.length); + expect(consolidated[0]).toEqual(1); + expect(consolidated[1]).toEqual(2); + expect(consolidated[2]).toEqual(3); + expect(consolidated[3]).toEqual(4); + expect(consolidated[4]).toEqual(5); + expect(consolidated[5]).toEqual(6); + }); + + it('handles empty lists gracefully', () => { + const arr: number[] = []; + const canCombine = () => true; + const combine = (a: number, b: number) => a + b; + + const consolidated = consolidate(arr, canCombine, combine); + + expect(consolidated.length).toEqual(arr.length); + }); +}); diff --git a/src/utils/consolidate.ts b/src/utils/consolidate.ts new file mode 100644 index 000000000..23f732843 --- /dev/null +++ b/src/utils/consolidate.ts @@ -0,0 +1,32 @@ +/** + * This implementation of `consolidate` `combine`s all elements of `arr` + * for which `canCombine` returns `true`. It is assumed that all combinations + * can be determined with an initial scan of `arr`, and that `canCombine` is transitive, + * meaning if `canCombine(A, B)` and `canCombine(B, C)` then `canCombine(combine(A, B), C)` + * @param arr - an array of elements + * @param canCombine - a function which determines if 2 elements can combine + * @param combine - a function which combines 2 elements + * @returns an array combined elements + */ +export const consolidate = ( + arr: T[], + canCombine: (a: T, b: T) => boolean, + combine: (a: T, b: T) => T, +): T[] => { + const consolidated: T[] = []; + for (const el of arr) { + let combined = false; + for (let i = 0; i < consolidated.length; i++) { + const existing = consolidated[i]; + if (canCombine(existing, el)) { + consolidated[i] = combine(existing, el); + combined = true; + break; + } + } + if (!combined) { + consolidated.push(el); + } + } + return consolidated; +}; diff --git a/src/utils/constants.ts b/src/utils/constants.ts deleted file mode 100644 index a059890e4..000000000 --- a/src/utils/constants.ts +++ /dev/null @@ -1,528 +0,0 @@ -/** - * @packageDocumentation - * @module Utils-Constants - */ - -import BN from "bn.js" - -export const PrivateKeyPrefix: string = "PrivateKey-" -export const NodeIDPrefix: string = "NodeID-" -export const PrimaryAssetAlias: string = "AVAX" -export const MainnetAPI: string = "api.avax.network" -export const FujiAPI: string = "api.avax-test.network" - -export interface C { - blockchainID: string - alias: string - vm: string - fee?: BN - gasPrice: BN | number - chainID?: number - minGasPrice?: BN - maxGasPrice?: BN - txBytesGas?: number - costPerSignature?: number - txFee?: BN - avaxAssetID?: string -} -export interface X { - blockchainID: string - alias: string - vm: string - creationTxFee: BN | number - mintTxFee: BN - avaxAssetID?: string - txFee?: BN | number - fee?: BN -} -export interface P { - blockchainID: string - alias: string - vm: string - creationTxFee: BN | number - createSubnetTx: BN | number - createChainTx: BN | number - minConsumption: number - maxConsumption: number - maxStakingDuration: BN - maxSupply: BN - minStake: BN - minStakeDuration: number - maxStakeDuration: number - minDelegationStake: BN - minDelegationFee: BN - avaxAssetID?: string - txFee?: BN | number - fee?: BN -} -export interface Network { - C: C - hrp: string - X: X - P: P - [key: string]: C | X | P | string -} -export interface Networks { - [key: number]: Network -} - -export const NetworkIDToHRP: object = { - 0: "custom", - 1: "avax", - 2: "cascade", - 3: "denali", - 4: "everest", - 5: "fuji", - 1337: "custom", - 12345: "local" -} - -export const HRPToNetworkID: object = { - manhattan: 0, - avax: 1, - cascade: 2, - denali: 3, - everest: 4, - fuji: 5, - custom: 1337, - local: 12345 -} - -export const NetworkIDToNetworkNames: object = { - 0: ["Manhattan"], - 1: ["Avalanche", "Mainnet"], - 2: ["Cascade"], - 3: ["Denali"], - 4: ["Everest"], - 5: ["Fuji", "Testnet"], - 1337: ["Custom Network"], - 12345: ["Local Network"] -} - -export const NetworkNameToNetworkID: object = { - Manhattan: 0, - Avalanche: 1, - Mainnet: 1, - Cascade: 2, - Denali: 3, - Everest: 4, - Fuji: 5, - Testnet: 5, - Custom: 1337, - "Custom Network": 1337, - Local: 12345, - "Local Network": 12345 -} - -export const FallbackHRP: string = "custom" -export const FallbackNetworkName: string = "Custom Network" -export const FallbackEVMChainID: number = 43112 - -export const DefaultNetworkID: number = 1 - -export const PlatformChainID: string = "11111111111111111111111111111111LpoYY" -export const PrimaryNetworkID: string = "11111111111111111111111111111111LpoYY" -export const XChainAlias: string = "X" -export const CChainAlias: string = "C" -export const PChainAlias: string = "P" -export const XChainVMName: string = "avm" -export const CChainVMName: string = "evm" -export const PChainVMName: string = "platformvm" - -// DO NOT use the following private keys and/or mnemonic on Fuji or Testnet -// This address/account is for testing on the local avash network -export const DefaultLocalGenesisPrivateKey: string = - "ewoqjP7PxY4yr3iLTpLisriqt94hdyDFNgchSxGGztUrTXtNN" -export const DefaultEVMLocalGenesisPrivateKey: string = - "0x56289e99c94b6912bfc12adc093c9b51124f0dc54ac7a766b2bc5ccf558d8027" -export const DefaultEVMLocalGenesisAddress: string = - "0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC" -export const mnemonic: string = - "output tooth keep tooth bracket fox city sustain blood raise install pond stem reject long scene clap gloom purpose mean music piece unknown light" - -export const ONEAVAX: BN = new BN(1000000000) - -export const DECIAVAX: BN = ONEAVAX.div(new BN(10)) - -export const CENTIAVAX: BN = ONEAVAX.div(new BN(100)) - -export const MILLIAVAX: BN = ONEAVAX.div(new BN(1000)) - -export const MICROAVAX: BN = ONEAVAX.div(new BN(1000000)) - -export const NANOAVAX: BN = ONEAVAX.div(new BN(1000000000)) - -export const WEI: BN = new BN(1) - -export const GWEI: BN = WEI.mul(new BN(1000000000)) - -export const AVAXGWEI: BN = NANOAVAX.clone() - -export const AVAXSTAKECAP: BN = ONEAVAX.mul(new BN(3000000)) - -// Start Manhattan -const n0X: X = { - blockchainID: "2vrXWHgGxh5n3YsLHMV16YVVJTpT4z45Fmb4y3bL6si8kLCyg9", - alias: XChainAlias, - vm: XChainVMName, - fee: MILLIAVAX, - creationTxFee: CENTIAVAX, - mintTxFee: MILLIAVAX -} - -const n0P: P = { - blockchainID: PlatformChainID, - alias: PChainAlias, - vm: PChainVMName, - fee: MILLIAVAX, - creationTxFee: CENTIAVAX, - createSubnetTx: ONEAVAX, - createChainTx: ONEAVAX, - minConsumption: 0.1, - maxConsumption: 0.12, - maxStakingDuration: new BN(31536000), - maxSupply: new BN(720000000).mul(ONEAVAX), - minStake: ONEAVAX.mul(new BN(2000)), - minStakeDuration: 2 * 7 * 24 * 60 * 60, //two weeks - maxStakeDuration: 365 * 24 * 60 * 60, // one year - minDelegationStake: ONEAVAX.mul(new BN(25)), - minDelegationFee: new BN(2) -} - -const n0C: C = { - blockchainID: "2fFZQibQXcd6LTE4rpBPBAkLVXFE91Kit8pgxaBG1mRnh5xqbb", - alias: CChainAlias, - vm: CChainVMName, - fee: MILLIAVAX, - gasPrice: GWEI.mul(new BN(470)), //equivalent to gas price - chainID: 43111 -} -// End Manhattan - -// Start mainnet -let avaxAssetID: string = "FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z" -const n1X: X = { - blockchainID: "2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM", - avaxAssetID: avaxAssetID, - alias: XChainAlias, - vm: XChainVMName, - txFee: MILLIAVAX, - creationTxFee: CENTIAVAX, - mintTxFee: MILLIAVAX -} - -const n1P: P = { - blockchainID: PlatformChainID, - avaxAssetID: avaxAssetID, - alias: PChainAlias, - vm: PChainVMName, - txFee: MILLIAVAX, - createSubnetTx: ONEAVAX, - createChainTx: ONEAVAX, - creationTxFee: CENTIAVAX, - minConsumption: 0.1, - maxConsumption: 0.12, - maxStakingDuration: new BN(31536000), - maxSupply: new BN(720000000).mul(ONEAVAX), - minStake: ONEAVAX.mul(new BN(2000)), - minStakeDuration: 2 * 7 * 24 * 60 * 60, //two weeks - maxStakeDuration: 365 * 24 * 60 * 60, // one year - minDelegationStake: ONEAVAX.mul(new BN(25)), - minDelegationFee: new BN(2) -} - -const n1C: C = { - blockchainID: "2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5", - alias: CChainAlias, - vm: CChainVMName, - txBytesGas: 1, - costPerSignature: 1000, - // DEPRECATED - txFee - // WILL BE REMOVED IN NEXT MAJOR VERSION BUMP - txFee: MILLIAVAX, - // DEPRECATED - gasPrice - // WILL BE REMOVED IN NEXT MAJOR VERSION BUMP - gasPrice: GWEI.mul(new BN(225)), - minGasPrice: GWEI.mul(new BN(25)), - maxGasPrice: GWEI.mul(new BN(1000)), - chainID: 43114 -} -// End Mainnet - -// Start Cascade -const n2X: X = { - blockchainID: "4ktRjsAKxgMr2aEzv9SWmrU7Xk5FniHUrVCX4P1TZSfTLZWFM", - alias: XChainAlias, - vm: XChainVMName, - txFee: 0, - creationTxFee: 0, - mintTxFee: new BN(0) -} - -const n2P: P = { - blockchainID: PlatformChainID, - alias: PChainAlias, - vm: PChainVMName, - txFee: 0, - creationTxFee: 0, - createSubnetTx: ONEAVAX, - createChainTx: ONEAVAX, - minConsumption: 0.1, - maxConsumption: 0.12, - maxStakingDuration: new BN(31536000), - maxSupply: new BN(720000000).mul(ONEAVAX), - minStake: ONEAVAX.mul(new BN(2000)), - minStakeDuration: 2 * 7 * 24 * 60 * 60, //two weeks - maxStakeDuration: 365 * 24 * 60 * 60, // one year - minDelegationStake: ONEAVAX.mul(new BN(25)), - minDelegationFee: new BN(2) -} - -const n2C: C = { - blockchainID: "2mUYSXfLrDtigwbzj1LxKVsHwELghc5sisoXrzJwLqAAQHF4i", - alias: CChainAlias, - vm: CChainVMName, - gasPrice: 0 -} -// End Cascade - -// Start Denali -const n3X: X = { - blockchainID: "rrEWX7gc7D9mwcdrdBxBTdqh1a7WDVsMuadhTZgyXfFcRz45L", - alias: XChainAlias, - vm: XChainVMName, - txFee: 0, - creationTxFee: 0, - mintTxFee: new BN(0) -} - -const n3P: P = { - blockchainID: "", - alias: PChainAlias, - vm: PChainVMName, - txFee: 0, - creationTxFee: 0, - createSubnetTx: ONEAVAX, - createChainTx: ONEAVAX, - minConsumption: 0.1, - maxConsumption: 0.12, - maxStakingDuration: new BN(31536000), - maxSupply: new BN(720000000).mul(ONEAVAX), - minStake: ONEAVAX.mul(new BN(2000)), - minStakeDuration: 2 * 7 * 24 * 60 * 60, //two weeks - maxStakeDuration: 365 * 24 * 60 * 60, // one year - minDelegationStake: ONEAVAX.mul(new BN(25)), - minDelegationFee: new BN(2) -} - -const n3C: C = { - blockchainID: "zJytnh96Pc8rM337bBrtMvJDbEdDNjcXG3WkTNCiLp18ergm9", - alias: CChainAlias, - vm: CChainVMName, - gasPrice: 0 -} -// End Denali - -// Start Everest -const n4X: X = { - blockchainID: "jnUjZSRt16TcRnZzmh5aMhavwVHz3zBrSN8GfFMTQkzUnoBxC", - alias: XChainAlias, - vm: XChainVMName, - txFee: MILLIAVAX, - creationTxFee: CENTIAVAX, - mintTxFee: MILLIAVAX -} - -const n4P: P = { - blockchainID: PlatformChainID, - alias: PChainAlias, - vm: PChainVMName, - txFee: MILLIAVAX, - creationTxFee: CENTIAVAX, - createSubnetTx: ONEAVAX, - createChainTx: ONEAVAX, - minConsumption: 0.1, - maxConsumption: 0.12, - maxStakingDuration: new BN(31536000), - maxSupply: new BN(720000000).mul(ONEAVAX), - minStake: ONEAVAX.mul(new BN(2000)), - minStakeDuration: 2 * 7 * 24 * 60 * 60, //two weeks - maxStakeDuration: 365 * 24 * 60 * 60, // one year - minDelegationStake: ONEAVAX.mul(new BN(25)), - minDelegationFee: new BN(2) -} - -const n4C: C = { - blockchainID: "saMG5YgNsFxzjz4NMkEkt3bAH6hVxWdZkWcEnGB3Z15pcAmsK", - alias: CChainAlias, - vm: CChainVMName, - gasPrice: GWEI.mul(new BN(470)), - chainID: 43110 -} -// End Everest - -// Start Fuji -avaxAssetID = "U8iRqJoiJm8xZHAacmvYyZVwqQx6uDNtQeP3CQ6fcgQk3JqnK" -const n5X: X = { - blockchainID: "2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm", - avaxAssetID: avaxAssetID, - alias: XChainAlias, - vm: XChainVMName, - txFee: MILLIAVAX, - creationTxFee: CENTIAVAX, - mintTxFee: MILLIAVAX -} - -const n5P: P = { - blockchainID: PlatformChainID, - avaxAssetID: avaxAssetID, - alias: PChainAlias, - vm: PChainVMName, - txFee: MILLIAVAX, - creationTxFee: CENTIAVAX, - createSubnetTx: ONEAVAX, - createChainTx: ONEAVAX, - minConsumption: 0.1, - maxConsumption: 0.12, - maxStakingDuration: new BN(31536000), - maxSupply: new BN(720000000).mul(ONEAVAX), - minStake: ONEAVAX, - minStakeDuration: 24 * 60 * 60, //one day - maxStakeDuration: 365 * 24 * 60 * 60, // one year - minDelegationStake: ONEAVAX, - minDelegationFee: new BN(2) -} - -const n5C: C = { - blockchainID: "yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp", - alias: CChainAlias, - vm: CChainVMName, - txBytesGas: 1, - costPerSignature: 1000, - // DEPRECATED - txFee - // WILL BE REMOVED IN NEXT MAJOR VERSION BUMP - txFee: MILLIAVAX, - // DEPRECATED - gasPrice - // WILL BE REMOVED IN NEXT MAJOR VERSION BUMP - gasPrice: GWEI.mul(new BN(225)), - minGasPrice: GWEI.mul(new BN(25)), - maxGasPrice: GWEI.mul(new BN(1000)), - chainID: 43113 -} -// End Fuji - -// Start custom network -avaxAssetID = "BUuypiq2wyuLMvyhzFXcPyxPMCgSp7eeDohhQRqTChoBjKziC" -const n1337X: X = { ...n5X } -n1337X.blockchainID = "qzfF3A11KzpcHkkqznEyQgupQrCNS6WV6fTUTwZpEKqhj1QE7" -n1337X.avaxAssetID = avaxAssetID -const n1337P: P = { ...n5P } -n1337P.blockchainID = PlatformChainID -const n1337C: C = { ...n5C } -n1337C.blockchainID = "BR28ypgLATNS6PbtHMiJ7NQ61vfpT27Hj8tAcZ1AHsfU5cz88" -n1337C.avaxAssetID = avaxAssetID -n1337C.chainID = 43112 -// End custom network - -// Start local network -avaxAssetID = "2fombhL7aGPwj3KH4bfrmJwW6PVnMobf9Y2fn9GwxiAAJyFDbe" -const n12345X: X = { ...n5X } -n12345X.blockchainID = "2eNy1mUFdmaxXNj1eQHUe7Np4gju9sJsEtWQ4MX3ToiNKuADed" -n12345X.avaxAssetID = avaxAssetID -const n12345P: P = { ...n5P } -n12345P.blockchainID = PlatformChainID -const n12345C: C = { ...n5C } -n12345C.blockchainID = "2CA6j5zYzasynPsFeNoqWkmTCt3VScMvXUZHbfDJ8k3oGzAPtU" -n12345C.avaxAssetID = avaxAssetID -n12345C.chainID = 43112 -// End local network - -export class Defaults { - static network: Networks = { - 0: { - hrp: NetworkIDToHRP[0], - X: n0X, - "2vrXWHgGxh5n3YsLHMV16YVVJTpT4z45Fmb4y3bL6si8kLCyg9": n0X, - P: n0P, - "11111111111111111111111111111111LpoYY": n0P, - C: n0C, - "2fFZQibQXcd6LTE4rpBPBAkLVXFE91Kit8pgxaBG1mRnh5xqbb": n0C - }, - 1: { - hrp: NetworkIDToHRP[1], - X: n1X, - "2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM": n1X, - P: n1P, - "11111111111111111111111111111111LpoYY": n1P, - C: n1C, - "2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5": n1C - }, - 2: { - hrp: NetworkIDToHRP[2], - X: n2X, - "4ktRjsAKxgMr2aEzv9SWmrU7Xk5FniHUrVCX4P1TZSfTLZWFM": n2X, - P: n2P, - "11111111111111111111111111111111LpoYY": n2P, - C: n2C, - "2mUYSXfLrDtigwbzj1LxKVsHwELghc5sisoXrzJwLqAAQHF4i": n2C - }, - 3: { - hrp: NetworkIDToHRP[3], - X: n3X, - rrEWX7gc7D9mwcdrdBxBTdqh1a7WDVsMuadhTZgyXfFcRz45L: n3X, - P: n3P, - "11111111111111111111111111111111LpoYY": n3P, - C: n3C, - zJytnh96Pc8rM337bBrtMvJDbEdDNjcXG3WkTNCiLp18ergm9: n3C - }, - 4: { - hrp: NetworkIDToHRP[4], - X: n4X, - jnUjZSRt16TcRnZzmh5aMhavwVHz3zBrSN8GfFMTQkzUnoBxC: n4X, - P: n4P, - "11111111111111111111111111111111LpoYY": n4P, - C: n4C, - saMG5YgNsFxzjz4NMkEkt3bAH6hVxWdZkWcEnGB3Z15pcAmsK: n4C - }, - 5: { - hrp: NetworkIDToHRP[5], - X: n5X, - "2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm": n5X, - P: n5P, - "11111111111111111111111111111111LpoYY": n5P, - C: n5C, - yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp: n5C - }, - 1337: { - hrp: NetworkIDToHRP[1337], - X: n1337X, - qzfF3A11KzpcHkkqznEyQgupQrCNS6WV6fTUTwZpEKqhj1QE7: n1337X, - P: n1337P, - "11111111111111111111111111111111LpoYY": n1337P, - C: n1337C, - BR28ypgLATNS6PbtHMiJ7NQ61vfpT27Hj8tAcZ1AHsfU5cz88: n1337C - }, - 12345: { - hrp: NetworkIDToHRP[12345], - X: n12345X, - "2eNy1mUFdmaxXNj1eQHUe7Np4gju9sJsEtWQ4MX3ToiNKuADed": n12345X, - P: n12345P, - "11111111111111111111111111111111LpoYY": n12345P, - C: n12345C, - "2CA6j5zYzasynPsFeNoqWkmTCt3VScMvXUZHbfDJ8k3oGzAPtU": n12345C - } - } -} - -/** - * Rules used when merging sets - */ -export type MergeRule = - | "intersection" // Self INTERSECT New - | "differenceSelf" // Self MINUS New - | "differenceNew" // New MINUS Self - | "symDifference" // differenceSelf UNION differenceNew - | "union" // Self UNION New - | "unionMinusNew" // union MINUS differenceNew - | "unionMinusSelf" // union MINUS differenceSelf - | "ERROR" // generate error for testing diff --git a/src/utils/costs.ts b/src/utils/costs.ts new file mode 100644 index 000000000..870b48b90 --- /dev/null +++ b/src/utils/costs.ts @@ -0,0 +1,18 @@ +import type { UnsignedTx } from '../vms/common/unsignedTx'; + +export const CTxBytesGas = 1n; +export const CCostPerSignature = 1000n; +export const CFixedFee = 10000; + +export function costCorethTx(tx: UnsignedTx): bigint { + const bytesCost = calcBytesCost(tx.toBytes().length); + + const sigCost = + BigInt(tx.getSigIndices().flatMap((a) => a).length) * CCostPerSignature; + const fixedFee = 10000n; + return bytesCost + sigCost + fixedFee; +} + +export function calcBytesCost(len: number): bigint { + return BigInt(len) * CTxBytesGas; +} diff --git a/src/utils/db.ts b/src/utils/db.ts deleted file mode 100644 index e340c7de7..000000000 --- a/src/utils/db.ts +++ /dev/null @@ -1,43 +0,0 @@ -/** - * @packageDocumentation - * @module Utils-DB - */ -import store, { StoreAPI } from "store2" - -/** - * A class for interacting with the {@link https://github.com/nbubna/store| store2 module} - * - * This class should never be instantiated directly. Instead, invoke the "DB.getInstance()" static - * function to grab the singleton instance of the database. - * - * ```js - * const db = DB.getInstance(); - * const blockchaindb = db.getNamespace("mychain"); - * ``` - */ -export default class DB { - private static instance: DB - - private static store = store - - private constructor() {} - - /** - * Retrieves the database singleton. - */ - static getInstance(): DB { - if (!DB.instance) { - DB.instance = new DB() - } - return DB.instance - } - - /** - * Gets a namespace from the database singleton. - * - * @param ns Namespace to retrieve. - */ - static getNamespace(ns: string): StoreAPI { - return this.store.namespace(ns) - } -} diff --git a/src/utils/devutils.ts b/src/utils/devutils.ts new file mode 100644 index 000000000..a2c58beba --- /dev/null +++ b/src/utils/devutils.ts @@ -0,0 +1,16 @@ +import util from 'util'; +import { bufferToHex } from './buffer'; + +// useful for printing transactions +export const printJSON = (obj: any) => { + console.log(JSON.stringify(obj, null, 2)); +}; + +// useful for printing nested objects +export const printDeep = (obj: any) => { + console.log(util.inspect(obj, { depth: null, colors: true })); +}; + +export const printHex = (bytes: Uint8Array, name = '') => { + console.log(`name = ${name}`, bufferToHex(bytes)); +}; diff --git a/src/utils/errors.ts b/src/utils/errors.ts deleted file mode 100644 index f8d4f12ff..000000000 --- a/src/utils/errors.ts +++ /dev/null @@ -1,387 +0,0 @@ -const ADDRESS_ERROR_CODE: string = "1000" -const GOOSE_EGG_CHECK_ERROR_CODE: string = "1001" -const CHAIN_ID_ERROR_CODE: string = "1002" -const NO_ATOMIX_UTXOS_ERROR_CODE: string = "1003" -const SYMBOL_ERROR_CODE: string = "1004" -const NAME_ERROR_CODE: string = "1005" -const TRANSACTION_ERROR_CODE: string = "1006" -const CODEC_ID_ERROR_CODE: string = "1007" -const CRED_ID_ERROR_CODE: string = "1008" -const TRANSFERABLE_OUTPUT_ERROR_CODE: string = "1009" -const TRANSFERABLE_INPUT_ERROR_CODE: string = "1010" -const INPUT_ID_ERROR_CODE: string = "1011" -const OPERATION_ERROR_CODE: string = "1012" -const INVALID_OPERATION_ID_CODE: string = "1013" -const CHECKSUM_ERROR_CODE: string = "1014" -const OUTPUT_ID_ERROR_CODE: string = "1015" -const UTXO_ERROR_CODE: string = "1016" -const INSUFFICIENT_FUNDS_ERROR_CODE: string = "1017" -const THRESHOLD_ERROR_CODE: string = "1018" -const SECP_MINT_OUTPUT_ERROR_CODE: string = "1019" -const EVM_INPUT_ERROR_CODE: string = "1020" -const EVM_OUTPUT_ERROR_CODE: string = "1021" -const FEE_ASSET_ERROR_CODE: string = "1022" -const STAKE_ERROR_CODE: string = "1023" -const TIME_ERROR_CODE: string = "1024" -const DELEGATION_FEE_ERROR_CODE: string = "1025" -const SUBNET_OWNER_ERROR_CODE: string = "1026" -const BUFFER_SIZE_ERROR_CODE: string = "1027" -const ADDRESS_INDEX_ERROR_CODE: string = "1028" -const PUBLIC_KEY_ERROR_CODE: string = "1029" -const MERGE_RULE_ERROR_CODE: string = "1030" -const BASE58_ERROR_CODE: string = "1031" -const PRIVATE_KEY_ERROR_CODE: string = "1032" -const NODE_ID_ERROR_CODE: string = "1033" -const HEX_ERROR_CODE: string = "1034" -const TYPE_ID_ERROR_CODE: string = "1035" -const UNKNOWN_TYPE_ERROR_CODE: string = "1036" -const BECH32_ERROR_CODE: string = "1037" -const EVM_FEE_ERROR_CODE: string = "1038" -const INVALID_ENTROPY: string = "1039" -const PROTOCOL_ERROR_CODE: string = "1040" -const SUBNET_ID_ERROR_CODE: string = "1041" -const TYPE_NAME_ERROR_CODE: string = "1042" -const SUBNET_THRESHOLD_ERROR_CODE: string = "1043" -const SUBNET_ADDRESS_ERROR_CODE: string = "1044" -const UNKNOWN_FORMAT_ERROR_CODE: string = "1045" - -export class AvalancheError extends Error { - errorCode: string - constructor(m: string, code: string) { - super(m) - Object.setPrototypeOf(this, AvalancheError.prototype) - this.errorCode = code - } - - getCode() { - return this.errorCode - } -} - -export class AddressError extends AvalancheError { - constructor(m: string) { - super(m, ADDRESS_ERROR_CODE) - Object.setPrototypeOf(this, AddressError.prototype) - } -} - -export class GooseEggCheckError extends AvalancheError { - constructor(m: string) { - super(m, GOOSE_EGG_CHECK_ERROR_CODE) - Object.setPrototypeOf(this, GooseEggCheckError.prototype) - } -} - -export class ChainIdError extends AvalancheError { - constructor(m: string) { - super(m, CHAIN_ID_ERROR_CODE) - Object.setPrototypeOf(this, ChainIdError.prototype) - } -} - -export class NoAtomicUTXOsError extends AvalancheError { - constructor(m: string) { - super(m, NO_ATOMIX_UTXOS_ERROR_CODE) - Object.setPrototypeOf(this, NoAtomicUTXOsError.prototype) - } -} - -export class SymbolError extends AvalancheError { - constructor(m: string) { - super(m, SYMBOL_ERROR_CODE) - Object.setPrototypeOf(this, SymbolError.prototype) - } -} - -export class NameError extends AvalancheError { - constructor(m: string) { - super(m, NAME_ERROR_CODE) - Object.setPrototypeOf(this, NameError.prototype) - } -} - -export class TransactionError extends AvalancheError { - constructor(m: string) { - super(m, TRANSACTION_ERROR_CODE) - Object.setPrototypeOf(this, TransactionError.prototype) - } -} - -export class CodecIdError extends AvalancheError { - constructor(m: string) { - super(m, CODEC_ID_ERROR_CODE) - Object.setPrototypeOf(this, CodecIdError.prototype) - } -} - -export class CredIdError extends AvalancheError { - constructor(m: string) { - super(m, CRED_ID_ERROR_CODE) - Object.setPrototypeOf(this, CredIdError.prototype) - } -} - -export class TransferableOutputError extends AvalancheError { - constructor(m: string) { - super(m, TRANSFERABLE_OUTPUT_ERROR_CODE) - Object.setPrototypeOf(this, TransferableOutputError.prototype) - } -} - -export class TransferableInputError extends AvalancheError { - constructor(m: string) { - super(m, TRANSFERABLE_INPUT_ERROR_CODE) - Object.setPrototypeOf(this, TransferableInputError.prototype) - } -} - -export class InputIdError extends AvalancheError { - constructor(m: string) { - super(m, INPUT_ID_ERROR_CODE) - Object.setPrototypeOf(this, InputIdError.prototype) - } -} - -export class OperationError extends AvalancheError { - constructor(m: string) { - super(m, OPERATION_ERROR_CODE) - Object.setPrototypeOf(this, OperationError.prototype) - } -} - -export class InvalidOperationIdError extends AvalancheError { - constructor(m: string) { - super(m, INVALID_OPERATION_ID_CODE) - Object.setPrototypeOf(this, InvalidOperationIdError.prototype) - } -} - -export class ChecksumError extends AvalancheError { - constructor(m: string) { - super(m, CHECKSUM_ERROR_CODE) - Object.setPrototypeOf(this, ChecksumError.prototype) - } -} - -export class OutputIdError extends AvalancheError { - constructor(m: string) { - super(m, OUTPUT_ID_ERROR_CODE) - Object.setPrototypeOf(this, OutputIdError.prototype) - } -} - -export class UTXOError extends AvalancheError { - constructor(m: string) { - super(m, UTXO_ERROR_CODE) - Object.setPrototypeOf(this, UTXOError.prototype) - } -} - -export class InsufficientFundsError extends AvalancheError { - constructor(m: string) { - super(m, INSUFFICIENT_FUNDS_ERROR_CODE) - Object.setPrototypeOf(this, InsufficientFundsError.prototype) - } -} - -export class ThresholdError extends AvalancheError { - constructor(m: string) { - super(m, THRESHOLD_ERROR_CODE) - Object.setPrototypeOf(this, ThresholdError.prototype) - } -} - -export class SECPMintOutputError extends AvalancheError { - constructor(m: string) { - super(m, SECP_MINT_OUTPUT_ERROR_CODE) - Object.setPrototypeOf(this, SECPMintOutputError.prototype) - } -} - -export class EVMInputError extends AvalancheError { - constructor(m: string) { - super(m, EVM_INPUT_ERROR_CODE) - Object.setPrototypeOf(this, EVMInputError.prototype) - } -} - -export class EVMOutputError extends AvalancheError { - constructor(m: string) { - super(m, EVM_OUTPUT_ERROR_CODE) - Object.setPrototypeOf(this, EVMOutputError.prototype) - } -} - -export class FeeAssetError extends AvalancheError { - constructor(m: string) { - super(m, FEE_ASSET_ERROR_CODE) - Object.setPrototypeOf(this, FeeAssetError.prototype) - } -} - -export class StakeError extends AvalancheError { - constructor(m: string) { - super(m, STAKE_ERROR_CODE) - Object.setPrototypeOf(this, StakeError.prototype) - } -} - -export class TimeError extends AvalancheError { - constructor(m: string) { - super(m, TIME_ERROR_CODE) - Object.setPrototypeOf(this, TimeError.prototype) - } -} - -export class DelegationFeeError extends AvalancheError { - constructor(m: string) { - super(m, DELEGATION_FEE_ERROR_CODE) - Object.setPrototypeOf(this, DelegationFeeError.prototype) - } -} - -export class SubnetOwnerError extends AvalancheError { - constructor(m: string) { - super(m, SUBNET_OWNER_ERROR_CODE) - Object.setPrototypeOf(this, SubnetOwnerError.prototype) - } -} - -export class BufferSizeError extends AvalancheError { - constructor(m: string) { - super(m, BUFFER_SIZE_ERROR_CODE) - Object.setPrototypeOf(this, BufferSizeError.prototype) - } -} - -export class AddressIndexError extends AvalancheError { - constructor(m: string) { - super(m, ADDRESS_INDEX_ERROR_CODE) - Object.setPrototypeOf(this, AddressIndexError.prototype) - } -} - -export class PublicKeyError extends AvalancheError { - constructor(m: string) { - super(m, PUBLIC_KEY_ERROR_CODE) - Object.setPrototypeOf(this, PublicKeyError.prototype) - } -} - -export class MergeRuleError extends AvalancheError { - constructor(m: string) { - super(m, MERGE_RULE_ERROR_CODE) - Object.setPrototypeOf(this, MergeRuleError.prototype) - } -} - -export class Base58Error extends AvalancheError { - constructor(m: string) { - super(m, BASE58_ERROR_CODE) - Object.setPrototypeOf(this, Base58Error.prototype) - } -} - -export class PrivateKeyError extends AvalancheError { - constructor(m: string) { - super(m, PRIVATE_KEY_ERROR_CODE) - Object.setPrototypeOf(this, PrivateKeyError.prototype) - } -} - -export class NodeIdError extends AvalancheError { - constructor(m: string) { - super(m, NODE_ID_ERROR_CODE) - Object.setPrototypeOf(this, NodeIdError.prototype) - } -} - -export class HexError extends AvalancheError { - constructor(m: string) { - super(m, HEX_ERROR_CODE) - Object.setPrototypeOf(this, HexError.prototype) - } -} - -export class TypeIdError extends AvalancheError { - constructor(m: string) { - super(m, TYPE_ID_ERROR_CODE) - Object.setPrototypeOf(this, TypeIdError.prototype) - } -} - -export class TypeNameError extends AvalancheError { - constructor(m: string) { - super(m, TYPE_NAME_ERROR_CODE) - Object.setPrototypeOf(this, TypeNameError.prototype) - } -} - -export class UnknownTypeError extends AvalancheError { - constructor(m: string) { - super(m, UNKNOWN_TYPE_ERROR_CODE) - Object.setPrototypeOf(this, UnknownTypeError.prototype) - } -} - -export class Bech32Error extends AvalancheError { - constructor(m: string) { - super(m, BECH32_ERROR_CODE) - Object.setPrototypeOf(this, Bech32Error.prototype) - } -} - -export class EVMFeeError extends AvalancheError { - constructor(m: string) { - super(m, EVM_FEE_ERROR_CODE) - Object.setPrototypeOf(this, EVMFeeError.prototype) - } -} - -export class InvalidEntropy extends AvalancheError { - constructor(m: string) { - super(m, INVALID_ENTROPY) - Object.setPrototypeOf(this, InvalidEntropy.prototype) - } -} - -export class ProtocolError extends AvalancheError { - constructor(m: string) { - super(m, PROTOCOL_ERROR_CODE) - Object.setPrototypeOf(this, ProtocolError.prototype) - } -} - -export class SubnetIdError extends AvalancheError { - constructor(m: string) { - super(m, SUBNET_ID_ERROR_CODE) - Object.setPrototypeOf(this, SubnetIdError.prototype) - } -} - -export class SubnetThresholdError extends AvalancheError { - constructor(m: string) { - super(m, SUBNET_THRESHOLD_ERROR_CODE) - Object.setPrototypeOf(this, SubnetThresholdError.prototype) - } -} - -export class SubnetAddressError extends AvalancheError { - constructor(m: string) { - super(m, SUBNET_ADDRESS_ERROR_CODE) - Object.setPrototypeOf(this, SubnetAddressError.prototype) - } -} - -export class UnknownFormatError extends AvalancheError { - constructor(m: string) { - super(m, UNKNOWN_FORMAT_ERROR_CODE) - Object.setPrototypeOf(this, UnknownFormatError.prototype) - } -} - -export interface ErrorResponseObject { - code: number - message: string - data?: null -} \ No newline at end of file diff --git a/src/utils/fetchadapter.ts b/src/utils/fetchadapter.ts deleted file mode 100644 index edc227094..000000000 --- a/src/utils/fetchadapter.ts +++ /dev/null @@ -1,137 +0,0 @@ -import { AxiosRequestConfig, AxiosResponse, AxiosError } from "axios" - -function createRequest(config: AxiosRequestConfig): Request { - const headers = new Headers(config.headers as Record) - - if (config.auth) { - const username = config.auth.username || "" - const password = config.auth.password - ? encodeURIComponent(config.auth.password) - : "" - headers.set( - "Authorization", - `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}` - ) - } - - const method = config.method.toUpperCase() - const options: RequestInit = { - headers: headers, - method - } - if (method !== "GET" && method !== "HEAD") { - options.body = config.data - } - - if (!!config.withCredentials) { - options.credentials = config.withCredentials ? "include" : "omit" - } - - const fullPath = new URL(config.url, config.baseURL) - const params = new URLSearchParams(config.params) - - const url = `${fullPath}${params}` - - return new Request(url, options) -} - -async function getResponse(request, config): Promise { - let stageOne - try { - stageOne = await fetch(request) - } catch (e) { - const error: AxiosError = { - ...new Error("Network Error"), - config, - request, - isAxiosError: true, - toJSON: () => error - } - return Promise.reject(error) - } - - const response: AxiosResponse = { - status: stageOne.status, - statusText: stageOne.statusText, - headers: { ...stageOne.headers }, // make a copy of the headers - config: config, - request, - data: undefined // we set it below - } - - if (stageOne.status >= 200 && stageOne.status !== 204) { - switch (config.responseType) { - case "arraybuffer": - response.data = await stageOne.arrayBuffer() - break - case "blob": - response.data = await stageOne.blob() - break - case "json": - response.data = await stageOne.json() - break - case "formData": - response.data = await stageOne.formData() - break - default: - response.data = await stageOne.text() - break - } - } - - return Promise.resolve(response) -} - -export async function fetchAdapter( - config: AxiosRequestConfig -): Promise { - const request = createRequest(config) - - const promiseChain = [getResponse(request, config)] - - if (config.timeout && config.timeout > 0) { - promiseChain.push( - new Promise((res, reject) => { - setTimeout(() => { - const message = config.timeoutErrorMessage - ? config.timeoutErrorMessage - : "timeout of " + config.timeout + "ms exceeded" - const error: AxiosError = { - ...new Error(message), - config, - request, - code: "ECONNABORTED", - isAxiosError: true, - toJSON: () => error - } - reject(error) - }, config.timeout) - }) - ) - } - - const response = await Promise.race(promiseChain) - return new Promise((resolve, reject) => { - if (response instanceof Error) { - reject(response) - } else { - if ( - !response.status || - !response.config.validateStatus || - response.config.validateStatus(response.status) - ) { - resolve(response) - } else { - const error: AxiosError = { - ...new Error("Request failed with status code " + response.status), - config, - request, - code: response.status >= 500 ? "ERR_BAD_RESPONSE" : "ERR_BAD_REQUEST", - isAxiosError: true, - toJSON: () => error - } - reject(error) - } - } - }) -} diff --git a/src/utils/getBurnedAmountByTx.test.ts b/src/utils/getBurnedAmountByTx.test.ts new file mode 100644 index 000000000..3a4ae98b5 --- /dev/null +++ b/src/utils/getBurnedAmountByTx.test.ts @@ -0,0 +1,646 @@ +import type { AvaxTx } from '../serializable/avax'; +import { UTXOID } from '../serializable/avax'; +import { TransferableOutput } from '../serializable/avax'; +import { newExportTxFromBaseFee, newImportTxFromBaseFee } from '../vms/evm'; +import { getBurnedAmountByTx } from './getBurnedAmountByTx'; +import { testContext } from '../fixtures/context'; +import { testEthAddress1, testAddress1, testAddress2 } from '../fixtures/vms'; +import { nodeId } from '../fixtures/common'; +import { Utxo } from '../serializable/avax/utxo'; +import { OutputOwners, TransferOutput } from '../serializable/fxs/secp256k1'; +import { Address, Id } from '../serializable/fxs/common'; +import { BigIntPr, Int } from '../serializable/primitives'; +import { + newBaseTx, + newExportTx as avmExportTx, + newImportTx as avmImportTx, +} from '../vms/avm'; +import { + newExportTx as pvmExportTx, + newImportTx as pvmImportTx, + newAddValidatorTx, + newAddDelegatorTx, + newCreateSubnetTx, + newCreateBlockchainTx, + newAddSubnetValidatorTx, +} from '../vms/pvm'; +import type { EVMTx } from '../serializable/evm/abstractTx'; +import { testUTXOID1, testUTXOID2 } from '../fixtures/transactions'; +import { costCorethTx } from './costs'; +import { StakeableLockOut } from '../serializable/pvm'; + +const getUtxoMock = ( + utxoId: Id, + amount = 100000000n, + assetId: string = testContext.avaxAssetID, +) => + new Utxo( + new UTXOID(utxoId, new Int(0)), + Id.fromString(assetId), + new TransferOutput( + new BigIntPr(amount), + new OutputOwners(new BigIntPr(0n), new Int(1), [ + Address.fromBytes(testAddress1)[0], + ]), + ), + ); + +const getStakeableLockoutUtxoMock = ( + utxoId: Id, + lockTime: bigint, + amount = 100000000n, + assetId: string = testContext.avaxAssetID, +) => + new Utxo( + new UTXOID(utxoId, new Int(0)), + Id.fromString(assetId), + new StakeableLockOut( + new BigIntPr(lockTime), + new TransferOutput( + new BigIntPr(amount), + new OutputOwners(new BigIntPr(0n), new Int(1), [ + Address.fromBytes(testAddress1)[0], + ]), + ), + ), + ); + +const getOutputMock = ( + amount = 100000000n, + assetId: string = testContext.avaxAssetID, +) => + new TransferableOutput( + Id.fromString(assetId), + new TransferOutput( + new BigIntPr(amount), + new OutputOwners(new BigIntPr(0n), new Int(1), [ + Address.fromBytes(testAddress2)[0], + ]), + ), + ); + +describe('getBurnedAmountByTx', () => { + describe('C chain atomic transactions', () => { + it('calculates the burned amount of export tx correctly', () => { + const baseFee = 25n; + const tx = newExportTxFromBaseFee( + testContext, + baseFee, + 1000000000n, + 'X', + testEthAddress1, + [testAddress1], + 1n, + ); + + const amounts = getBurnedAmountByTx(tx.getTx() as EVMTx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + baseFee * costCorethTx(tx), + ); + }); + + it('calculates the burned amount of import tx correctly', () => { + const baseFee = 25n; + const utxo1 = getUtxoMock(testUTXOID1, 50000000n); + const utxo2 = getUtxoMock(testUTXOID2, 50000000n); + + const tx = newImportTxFromBaseFee( + testContext, + testEthAddress1, + [testAddress1], + [utxo1, utxo2], + 'X', + baseFee, + ); + + const amounts = getBurnedAmountByTx(tx.getTx() as EVMTx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + baseFee * costCorethTx(tx), + ); + }); + }); + + describe('X chain transactions', () => { + describe('base tx', () => { + it('calculates the burned amount of base tx correctly (multiple inputs)', () => { + // 110000000n total input -> 100000000n ouput + 1000000n fee -> 9000000n change + const utxo1 = getUtxoMock(testUTXOID1, 50000000n); + const utxo2 = getUtxoMock(testUTXOID2, 60000000n); + const output = getOutputMock(100000000n); + + const tx = newBaseTx( + testContext, + [testAddress1], + [utxo1, utxo2], + [output], + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.baseTxFee, + ); + + for (const out of tx.baseTx?.outputs ?? []) { + expect([100000000n, 9000000n]).toContain(out.amount()); + } + }); + + it('calculates the burned amount of base tx correctly (multiple outputs)', () => { + // 150000000n total input -> 140000000n ouput + 1000000n fee -> 9000000n change + const utxo = getUtxoMock(testUTXOID1, 150000000n); + const output1 = getOutputMock(100000000n); + const output2 = getOutputMock(30000000n); + const output3 = getOutputMock(10000000n); + + const tx = newBaseTx( + testContext, + [testAddress1], + [utxo], + [output1, output2, output3], + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.baseTxFee, + ); + + for (const out of tx.baseTx?.outputs ?? []) { + expect([100000000n, 30000000n, 10000000n, 9000000n]).toContain( + out.amount(), + ); + } + }); + + it('calculates the burned amount of base tx correctly (multiple inputs and outputs)', () => { + // 150000000n total input -> 140000000n ouput + 1000000n fee -> 9000000n change + const utxo1 = getUtxoMock(testUTXOID1, 70000000n); + const utxo2 = getUtxoMock(testUTXOID1, 80000000n); + const output1 = getOutputMock(100000000n); + const output2 = getOutputMock(30000000n); + const output3 = getOutputMock(10000000n); + + const tx = newBaseTx( + testContext, + [testAddress1], + [utxo1, utxo2], + [output1, output2, output3], + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.baseTxFee, + ); + + for (const out of tx.baseTx?.outputs ?? []) { + expect([100000000n, 30000000n, 10000000n, 9000000n]).toContain( + out.amount(), + ); + } + }); + }); + + describe('export tx', () => { + it('calculates the burned amount of export tx correctly (multiple inputs)', () => { + // 110000000n total input -> 100000000n ouput + 1000000n fee -> 9000000n change + const utxo1 = getUtxoMock(testUTXOID1, 50000000n); + const utxo2 = getUtxoMock(testUTXOID2, 60000000n); + const output = getOutputMock(100000000n); + + const tx = avmExportTx( + testContext, + 'P', + [testAddress1], + [utxo1, utxo2], + [output], + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.baseTxFee, + ); + }); + + it('calculates the burned amount of export tx correctly (multiple outputs)', () => { + // 150000000n total input -> 140000000n ouput + 1000000n fee -> 9000000n change + const utxo = getUtxoMock(testUTXOID1, 150000000n); + const output1 = getOutputMock(100000000n); + const output2 = getOutputMock(30000000n); + const output3 = getOutputMock(10000000n); + + const tx = avmExportTx( + testContext, + 'P', + [testAddress1], + [utxo], + [output1, output2, output3], + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.baseTxFee, + ); + }); + + it('calculates the burned amount of export tx correctly (multiple inputs and outputs)', () => { + // 150000000n total input -> 140000000n ouput + 1000000n fee -> 9000000n change + const utxo1 = getUtxoMock(testUTXOID1, 70000000n); + const utxo2 = getUtxoMock(testUTXOID1, 80000000n); + const output1 = getOutputMock(100000000n); + const output2 = getOutputMock(30000000n); + const output3 = getOutputMock(10000000n); + + const tx = avmExportTx( + testContext, + 'P', + [testAddress1], + [utxo1, utxo2], + [output1, output2, output3], + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.baseTxFee, + ); + }); + }); + + describe('import tx', () => { + it('calculates the burned amount of import tx correctly', () => { + // 110000000n total input -> 1000000n fee -> 109000000n change + const utxo1 = getUtxoMock(testUTXOID1, 50000000n); + const utxo2 = getUtxoMock(testUTXOID2, 60000000n); + + const tx = avmImportTx( + testContext, + 'P', + [utxo1, utxo2], + [testAddress2], + [testAddress1], + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.baseTxFee, + ); + }); + }); + }); + + describe('P chain transactions', () => { + describe('export tx', () => { + it('calculates the burned amount of export tx correctly (multiple inputs)', () => { + // 110000000n total input -> 100000000n ouput + 1000000n fee -> 9000000n change + const utxo1 = getUtxoMock(testUTXOID1, 50000000n); + const utxo2 = getUtxoMock(testUTXOID2, 60000000n); + const output = getOutputMock(100000000n); + + const tx = pvmExportTx( + testContext, + 'C', + [testAddress1], + [utxo1, utxo2], + [output], + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.baseTxFee, + ); + }); + + it('calculates the burned amount of export tx correctly (multiple outputs)', () => { + // 150000000n total input -> 140000000n ouput + 1000000n fee -> 9000000n change + const utxo = getUtxoMock(testUTXOID1, 150000000n); + const output1 = getOutputMock(100000000n); + const output2 = getOutputMock(30000000n); + const output3 = getOutputMock(10000000n); + + const tx = pvmExportTx( + testContext, + 'C', + [testAddress1], + [utxo], + [output1, output2, output3], + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.baseTxFee, + ); + }); + + it('calculates the burned amount of export tx correctly (multiple inputs and outputs)', () => { + // 150000000n total input -> 140000000n ouput + 1000000n fee -> 9000000n change + const utxo1 = getUtxoMock(testUTXOID1, 70000000n); + const utxo2 = getUtxoMock(testUTXOID1, 80000000n); + const output1 = getOutputMock(100000000n); + const output2 = getOutputMock(30000000n); + const output3 = getOutputMock(10000000n); + + const tx = pvmExportTx( + testContext, + 'C', + [testAddress1], + [utxo1, utxo2], + [output1, output2, output3], + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.baseTxFee, + ); + }); + }); + + describe('import tx', () => { + it('calculates the burned amount of import tx correctly', () => { + // 110000000n total input -> 1000000n fee -> 9000000n change + const utxo1 = getUtxoMock(testUTXOID1, 50000000n); + const utxo2 = getUtxoMock(testUTXOID2, 60000000n); + + const tx = pvmImportTx( + testContext, + 'C', + [utxo1, utxo2], + [testAddress2], + [testAddress1], + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.baseTxFee, + ); + }); + }); + + describe('add validator tx', () => { + it('calculates the burned amount of add validator tx correctly', () => { + // 110000000n total input -> 100000000n stake + 0 fee -> 10000000n change + const weight = 100000000n; + const utxo1 = getUtxoMock(testUTXOID1, 50000000n); + const utxo2 = getUtxoMock(testUTXOID2, 60000000n); + + const tx = newAddValidatorTx( + testContext, + [utxo1, utxo2], + [testAddress1], + nodeId().toString(), + 0n, + 1n, + weight, + [testAddress1], + 3, + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.addPrimaryNetworkValidatorFee, + ); + }); + + it('calculates the burned amount of add validator tx correctly (stakeable lock out)', () => { + // 110000000n total input -> 100000000n stake + 0 fee -> 10000000n change + const weight = 100000000n; + const lockTime = + BigInt(Math.floor(new Date().getTime() / 1000)) + 10000n; + const utxo1 = getStakeableLockoutUtxoMock( + testUTXOID1, + lockTime, + 50000000n, + ); + const utxo2 = getStakeableLockoutUtxoMock( + testUTXOID2, + lockTime, + 60000000n, + ); + + const tx = newAddValidatorTx( + testContext, + [utxo1, utxo2], + [testAddress1], + nodeId().toString(), + 0n, + 1n, + weight, + [testAddress1], + 3, + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.addPrimaryNetworkValidatorFee, + ); + }); + + it('calculates the burned amount of add validator tx correctly (hybrid)', () => { + // 110000000n total input -> 100000000n stake + 0 fee -> 10000000n change + const weight = 100000000n; + const lockTime = + BigInt(Math.floor(new Date().getTime() / 1000)) + 10000n; + const utxo1 = getStakeableLockoutUtxoMock( + testUTXOID1, + lockTime, + 50000000n, + ); + const utxo2 = getUtxoMock(testUTXOID2, 60000000n); + + const tx = newAddValidatorTx( + testContext, + [utxo1, utxo2], + [testAddress1], + nodeId().toString(), + 0n, + 1n, + weight, + [testAddress1], + 3, + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.addPrimaryNetworkValidatorFee, + ); + }); + }); + + describe('add delegator tx', () => { + it('calculates the burned amount of add delegator tx correctly', () => { + // 110000000n total input -> 100000000n stake + 0 fee -> 10000000n change + const weight = 100000000n; + const utxo1 = getUtxoMock(testUTXOID1, 50000000n); + const utxo2 = getUtxoMock(testUTXOID2, 60000000n); + + const tx = newAddDelegatorTx( + testContext, + [utxo1, utxo2], + [testAddress1], + nodeId().toString(), + 0n, + 1n, + weight, + [testAddress1], + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.addPrimaryNetworkDelegatorFee, + ); + }); + + it('calculates the burned amount of add delegator tx correctly (stakeable lock out)', () => { + // 110000000n total input -> 100000000n stake + 0 fee -> 10000000n change + const weight = 100000000n; + const lockTime = + BigInt(Math.floor(new Date().getTime() / 1000)) + 10000n; + const utxo1 = getStakeableLockoutUtxoMock( + testUTXOID1, + lockTime, + 50000000n, + ); + const utxo2 = getStakeableLockoutUtxoMock( + testUTXOID2, + lockTime, + 60000000n, + ); + + const tx = newAddDelegatorTx( + testContext, + [utxo1, utxo2], + [testAddress1], + nodeId().toString(), + 0n, + 1n, + weight, + [testAddress1], + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.addPrimaryNetworkDelegatorFee, + ); + }); + + it('calculates the burned amount of add delegator tx correctly (hybrid)', () => { + // 110000000n total input -> 100000000n stake + 0 fee -> 10000000n change + const weight = 100000000n; + const lockTime = + BigInt(Math.floor(new Date().getTime() / 1000)) + 10000n; + const utxo1 = getStakeableLockoutUtxoMock( + testUTXOID1, + lockTime, + 50000000n, + ); + const utxo2 = getUtxoMock(testUTXOID2, 60000000n); + + const tx = newAddDelegatorTx( + testContext, + [utxo1, utxo2], + [testAddress1], + nodeId().toString(), + 0n, + 1n, + weight, + [testAddress1], + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.addPrimaryNetworkDelegatorFee, + ); + }); + }); + + describe('create subnet tx', () => { + it('calculates the burned amount of create subnet tx correctly', () => { + // 1100000000n total input -> 1000000000n fee -> 100000000n change + const utxo1 = getUtxoMock(testUTXOID1, 500000000n); + const utxo2 = getUtxoMock(testUTXOID2, 600000000n); + + const tx = newCreateSubnetTx( + testContext, + [utxo1, utxo2], + [testAddress1], + [testAddress1], + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.createSubnetTxFee, + ); + }); + }); + + describe('create blockchain', () => { + it('calculates the burned amount of create blockchain tx correctly', () => { + // 1100000000n total input -> 1000000000n fee -> 100000000n change + const utxo1 = getUtxoMock(testUTXOID1, 500000000n); + const utxo2 = getUtxoMock(testUTXOID2, 600000000n); + + const tx = newCreateBlockchainTx( + testContext, + [utxo1, utxo2], + [testAddress1], + 'subnet', + 'chain', + 'vm', + ['fx1', 'fx2'], + {}, + [0], + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.createBlockchainTxFee, + ); + }); + }); + + describe('add subnet validor tx', () => { + it('calculates the burned amount of add subnet validor tx correctly', () => { + // 1100000n total input -> 0 stake + 1000000n fee -> 100000n change + const weight = 10000000n; + const utxo1 = getUtxoMock(testUTXOID1, 500000n); + const utxo2 = getUtxoMock(testUTXOID2, 600000n); + + const tx = newAddSubnetValidatorTx( + testContext, + [utxo1, utxo2], + [testAddress1], + nodeId().toString(), + 0n, + 1n, + weight, + 'subnet', + [0], + ).getTx() as AvaxTx; + + const amounts = getBurnedAmountByTx(tx); + expect(amounts.size).toEqual(1); + expect(amounts.get(testContext.avaxAssetID)).toEqual( + testContext.addSubnetValidatorFee, + ); + }); + }); + }); +}); diff --git a/src/utils/getBurnedAmountByTx.ts b/src/utils/getBurnedAmountByTx.ts new file mode 100644 index 000000000..221181bf2 --- /dev/null +++ b/src/utils/getBurnedAmountByTx.ts @@ -0,0 +1,70 @@ +import type { AvaxTx, TransferableInput } from '../serializable/avax'; +import { isTransferableInput } from '../serializable/avax'; +import type { Input, Output } from '../serializable/evm'; +import { + isExportTx as isEvmExportTx, + isImportTx as isEvmImportTx, +} from '../serializable/evm'; +import type { TransferableOutput } from '../serializable/avax'; +import { isTransferableOutput } from '../serializable/avax'; +import { getTransferableInputsByTx } from './getTransferableInputsByTx'; +import { getTransferableOutputsByTx } from './getTransferableOutputsByTx'; +import type { EVMTx } from '../serializable/evm/abstractTx'; + +const _reducer = ( + assetAmountMap: Map, + item: Input | TransferableInput | Output | TransferableOutput, +) => { + const previousAmount = assetAmountMap.get(item.assetId.toString()) ?? 0n; + const amount = + isTransferableInput(item) || isTransferableOutput(item) + ? item.amount() + : item.amount.value(); + + assetAmountMap.set(item.assetId.toString(), previousAmount + amount); + + return assetAmountMap; +}; + +export const getInputAmounts = (tx: AvaxTx | EVMTx) => { + /** + * `getTransferableInputsByTx` only returns `TransferableInputs` + * so we have to collect the EVM Inputs in an extra step + * */ + if (isEvmExportTx(tx)) { + return tx.ins.reduce(_reducer, new Map()); + } + const inputs = getTransferableInputsByTx(tx); + return inputs.reduce(_reducer, new Map()); +}; + +export const getOutputAmounts = (tx: AvaxTx | EVMTx) => { + /** + * `getTransferableOutputsByTx` only returns `TransferableOutputs` + * so we have to collect the EVM Outs in an extra step + * */ + if (isEvmImportTx(tx)) { + return tx.Outs.reduce(_reducer, new Map()); + } + const outputs = getTransferableOutputsByTx(tx); + return outputs.reduce((assetAmountMap, output) => { + if (isTransferableOutput(output)) { + return _reducer(assetAmountMap, output); + } + + return assetAmountMap; + }, new Map()); +}; + +export const getBurnedAmountByTx = (tx: AvaxTx | EVMTx) => { + const inputAmounts = getInputAmounts(tx); + const outputAmounts = getOutputAmounts(tx); + const burnedAmounts = new Map(); + + for (const [id, inputAmount] of inputAmounts.entries()) { + const outputAmount = outputAmounts.get(id) ?? 0n; + burnedAmounts.set(id, inputAmount - outputAmount); + } + + return burnedAmounts; +}; diff --git a/src/utils/getTransferableInputsByTx.test.ts b/src/utils/getTransferableInputsByTx.test.ts new file mode 100644 index 000000000..e815221a8 --- /dev/null +++ b/src/utils/getTransferableInputsByTx.test.ts @@ -0,0 +1,43 @@ +import { + avmBaseTx, + importTx as avmImportTx, + transferableInputs, +} from '../fixtures/avax'; +import { importTx as pvmImportTx } from '../fixtures/pvm'; +import { + importTx as evmImportTx, + exportTx as evmExportTx, +} from '../fixtures/evm'; +import { getTransferableInputsByTx } from './getTransferableInputsByTx'; + +describe('getTransferableInputsByTx', () => { + it('returns the inputs of a PVM import tx correctly', () => { + expect(getTransferableInputsByTx(pvmImportTx())).toStrictEqual([ + ...transferableInputs(), + ...transferableInputs(), + ]); + }); + + it('returns the inputs of an AVM import tx correctly', () => { + expect(getTransferableInputsByTx(avmImportTx())).toStrictEqual([ + ...transferableInputs(), + ...transferableInputs(), + ]); + }); + + it('returns the inputs of an EVM import tx correctly', () => { + expect(getTransferableInputsByTx(evmImportTx())).toStrictEqual( + transferableInputs(), + ); + }); + + it('returns the inputs of an EVM export tx correctly', () => { + expect(getTransferableInputsByTx(evmExportTx())).toStrictEqual([]); + }); + + it('returns the inputs of a non-import tx correctly', () => { + expect(getTransferableInputsByTx(avmBaseTx())).toStrictEqual( + transferableInputs(), + ); + }); +}); diff --git a/src/utils/getTransferableInputsByTx.ts b/src/utils/getTransferableInputsByTx.ts new file mode 100644 index 000000000..86897b4a0 --- /dev/null +++ b/src/utils/getTransferableInputsByTx.ts @@ -0,0 +1,29 @@ +import { isImportTx as isAvmImportTx } from '../serializable/avm'; +import { isImportTx as isPvmImportTx } from '../serializable/pvm'; +import { + isExportTx as isEvmExportTx, + isImportExportTx, + isEvmTx, +} from '../serializable/evm'; +import type { AvaxTx } from '../serializable/avax'; +import type { EVMTx } from '../serializable/evm/abstractTx'; + +export const getTransferableInputsByEvmTx = (tx: EVMTx) => { + if (isImportExportTx(tx)) { + return isEvmExportTx(tx) ? [] : tx.importedInputs; + } + + // Unreachable + return []; +}; + +export const getTransferableInputsByTx = (tx: AvaxTx | EVMTx) => { + if (isEvmTx(tx)) { + return getTransferableInputsByEvmTx(tx); + } + if (isAvmImportTx(tx) || isPvmImportTx(tx)) { + return [...(tx.baseTx.inputs ?? []), ...(tx.ins ?? [])]; + } + + return tx.getInputs(); +}; diff --git a/src/utils/getTransferableOutputsByTx.test.ts b/src/utils/getTransferableOutputsByTx.test.ts new file mode 100644 index 000000000..f2449f14b --- /dev/null +++ b/src/utils/getTransferableOutputsByTx.test.ts @@ -0,0 +1,113 @@ +import { + exportTx as evmExportTx, + importTx as evmImportTx, +} from '../fixtures/evm'; +import { getTransferableOutputsByTx } from './getTransferableOutputsByTx'; +import { + avmBaseTx, + exportTx as avmExportTx, + importTx as avmImportTx, + pvmBaseTx, + transferableOutputs, +} from '../fixtures/avax'; +import { + addDelegatorTx, + addPermissionlessDelegatorTx, + addPermissionlessValidatorTx, + addValidatorTx, + importTx as pvmImportTx, + exportTx as pvmExportTx, + createSubnetTx, + addSubnetValidatorTx, + removeValidatorTx, + transferSubnetOwnershipTx, + transformSubnetTx, +} from '../fixtures/pvm'; +import { outputOwner } from '../fixtures/secp256k1'; + +describe('getTransferableOutputsByTx', () => { + const testData = [ + // EVM + { tx: evmImportTx(), outs: [] }, + { tx: evmExportTx(), outs: transferableOutputs() }, + // AVM + { + tx: avmBaseTx(), + outs: transferableOutputs(), + }, + { + tx: avmImportTx(), + outs: transferableOutputs(), + }, + { + tx: avmExportTx(), + outs: [...transferableOutputs(), ...transferableOutputs()], + }, + // PVM + { + tx: pvmBaseTx(), + outs: transferableOutputs(), + }, + { + tx: pvmImportTx(), + outs: transferableOutputs(), + }, + { + tx: pvmExportTx(), + outs: [...transferableOutputs(), ...transferableOutputs()], + }, + { + tx: addValidatorTx(), + outs: [ + ...transferableOutputs(), + ...transferableOutputs(), + outputOwner(), + outputOwner(), + ], + }, + { + tx: addDelegatorTx(), + outs: [...transferableOutputs(), ...transferableOutputs(), outputOwner()], + }, + { + tx: addPermissionlessValidatorTx(), + outs: [ + ...transferableOutputs(), + ...transferableOutputs(), + outputOwner(), + outputOwner(), + ], + }, + { + tx: addPermissionlessDelegatorTx(), + outs: [...transferableOutputs(), ...transferableOutputs(), outputOwner()], + }, + { + tx: createSubnetTx(), + outs: [...transferableOutputs(), outputOwner()], + }, + { + tx: addSubnetValidatorTx(), + outs: transferableOutputs(), + }, + { + tx: removeValidatorTx(), + outs: transferableOutputs(), + }, + { + tx: transferSubnetOwnershipTx(), + outs: transferableOutputs(), + }, + { + tx: transformSubnetTx(), + outs: transferableOutputs(), + }, + ]; + + it.each(testData)( + 'returns all the transferable outputs of a $tx._type correctly', + ({ tx, outs }) => { + expect(getTransferableOutputsByTx(tx)).toStrictEqual(outs); + }, + ); +}); diff --git a/src/utils/getTransferableOutputsByTx.ts b/src/utils/getTransferableOutputsByTx.ts new file mode 100644 index 000000000..18e0dadb4 --- /dev/null +++ b/src/utils/getTransferableOutputsByTx.ts @@ -0,0 +1,63 @@ +import { + isExportTx as isEvmExportTx, + isEvmTx, + isImportExportTx, +} from '../serializable/evm'; +import { isExportTx as isAvmExportTx } from '../serializable/avm'; +import { + isAddDelegatorTx, + isAddPermissionlessDelegatorTx, + isAddPermissionlessValidatorTx, + isAddValidatorTx, + isCreateSubnetTx, + isExportTx as isPvmExportTx, +} from '../serializable/pvm'; +import type { AvaxTx } from '../serializable/avax'; +import type { EVMTx } from '../serializable/evm/abstractTx'; +import type { TransferableOutput } from '../serializable/avax'; +import type { OutputOwners } from '../serializable'; + +export const getTransferableOutputsByEvmTx = (tx: EVMTx) => { + if (isImportExportTx(tx)) { + return isEvmExportTx(tx) ? tx.exportedOutputs : []; + } + // Unreachable + return []; +}; + +export const getTransferableOutputsByTx = (tx: AvaxTx | EVMTx) => { + if (isEvmTx(tx)) { + return getTransferableOutputsByEvmTx(tx); + } + if (isAvmExportTx(tx) || isPvmExportTx(tx)) { + return [...(tx.baseTx?.outputs ?? []), ...(tx.outs ?? [])]; + } else if ( + isAddValidatorTx(tx) || + isAddDelegatorTx(tx) || + isAddPermissionlessValidatorTx(tx) || + isAddPermissionlessDelegatorTx(tx) + ) { + const outs: (TransferableOutput | OutputOwners)[] = [ + ...(tx.baseTx?.outputs ?? []), + ...(tx.stake ?? []), + ]; + + if (isAddValidatorTx(tx)) { + // validation reward + delegation reward after cortina upgrade + outs.push(tx.getRewardsOwner(), tx.getRewardsOwner()); + } else if (isAddDelegatorTx(tx)) { + outs.push(tx.getRewardsOwner()); + } else if (isAddPermissionlessValidatorTx(tx)) { + outs.push(tx.getValidatorRewardsOwner(), tx.getDelegatorRewardsOwner()); + } else { + outs.push(tx.getDelegatorRewardsOwner()); + } + + return outs; + } else if (isCreateSubnetTx(tx)) { + return [...tx.baseTx.outputs, tx.getSubnetOwners()]; + } else { + // This covers base tx, import, other subnet related transactions + return tx?.baseTx?.outputs ?? []; + } +}; diff --git a/src/utils/hdnode.ts b/src/utils/hdnode.ts deleted file mode 100644 index 4132b128d..000000000 --- a/src/utils/hdnode.ts +++ /dev/null @@ -1,97 +0,0 @@ -/** - * @packageDocumentation - * @module Utils-HDNode - */ - -import { Buffer } from "buffer/" -import hdnode from "hdkey" -import BinTools from "./bintools" -const bintools: BinTools = BinTools.getInstance() - -/** - * BIP32 hierarchical deterministic keys. - */ - -export default class HDNode { - private hdkey: any - publicKey: Buffer - privateKey: Buffer - privateKeyCB58: string - chainCode: Buffer - privateExtendedKey: string - publicExtendedKey: string - - /** - * Derives the HDNode at path from the current HDNode. - * @param path - * @returns derived child HDNode - */ - derive(path: string): HDNode { - const hdKey = this.hdkey.derive(path) - let hdNode: HDNode - if (hdKey.privateExtendedKey != null) { - hdNode = new HDNode(hdKey.privateExtendedKey) - } else { - hdNode = new HDNode(hdKey.publicExtendedKey) - } - return hdNode - } - - /** - * Signs the buffer hash with the private key using secp256k1 and returns the signature as a buffer. - * @param hash - * @returns signature as a Buffer - */ - sign(hash: Buffer): Buffer { - const sig: Buffer = this.hdkey.sign(hash) - return Buffer.from(sig) - } - - /** - * Verifies that the signature is valid for hash and the HDNode's public key using secp256k1. - * @param hash - * @param signature - * @returns true for valid, false for invalid. - * @throws if the hash or signature is the wrong length. - */ - verify(hash: Buffer, signature: Buffer): boolean { - return this.hdkey.verify(hash, signature) - } - - /** - * Wipes all record of the private key from the HDNode instance. - * After calling this method, the instance will behave as if it was created via an xpub. - */ - wipePrivateData() { - this.privateKey = null - this.privateExtendedKey = null - this.privateKeyCB58 = null - this.hdkey.wipePrivateData() - } - - /** - * Creates an HDNode from a master seed or an extended public/private key - * @param from seed or key to create HDNode from - */ - constructor(from: string | Buffer) { - if (typeof from === "string" && from.substring(0, 2) === "xp") { - this.hdkey = hdnode.fromExtendedKey(from) - } else if (Buffer.isBuffer(from)) { - this.hdkey = hdnode.fromMasterSeed(from as unknown as globalThis.Buffer) - } else { - this.hdkey = hdnode.fromMasterSeed( - Buffer.from(from) as unknown as globalThis.Buffer - ) - } - this.publicKey = this.hdkey.publicKey - this.privateKey = this.hdkey.privateKey - if (this.privateKey) { - this.privateKeyCB58 = `PrivateKey-${bintools.cb58Encode(this.privateKey)}` - } else { - this.privateExtendedKey = null - } - this.chainCode = this.hdkey.chainCode - this.privateExtendedKey = this.hdkey.privateExtendedKey - this.publicExtendedKey = this.hdkey.publicExtendedKey - } -} diff --git a/src/utils/helperfunctions.ts b/src/utils/helperfunctions.ts deleted file mode 100644 index 52e2aac19..000000000 --- a/src/utils/helperfunctions.ts +++ /dev/null @@ -1,113 +0,0 @@ -/** - * @packageDocumentation - * @module Utils-HelperFunctions - */ - -import { - NetworkIDToHRP, - DefaultNetworkID, - FallbackHRP, - Defaults -} from "./constants" -import BN from "bn.js" -import { Buffer } from "buffer/" -import BinTools from "../utils/bintools" -import { PrivateKeyError, NodeIdError } from "../utils/errors" -import { ExportTx, ImportTx, TransferableInput, UnsignedTx } from "../apis/evm" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() - -export function getPreferredHRP(networkID: number = undefined): string { - if (networkID in NetworkIDToHRP) { - return NetworkIDToHRP[`${networkID}`] - } else if (typeof networkID === "undefined") { - return NetworkIDToHRP[`${DefaultNetworkID}`] - } - return FallbackHRP -} - -export function MaxWeightFormula(staked: BN, cap: BN): BN { - return BN.min(staked.mul(new BN(5)), cap) -} - -/** - * Function providing the current UNIX time using a {@link https://github.com/indutny/bn.js/|BN}. - */ -export function UnixNow(): BN { - return new BN(Math.round(new Date().getTime() / 1000)) -} - -/** - * Takes a private key buffer and produces a private key string with prefix. - * - * @param pk A {@link https://github.com/feross/buffer|Buffer} for the private key. - */ -export function bufferToPrivateKeyString(pk: Buffer): string { - return `PrivateKey-${bintools.cb58Encode(pk)}` -} - -/** - * Takes a private key string and produces a private key {@link https://github.com/feross/buffer|Buffer}. - * - * @param pk A string for the private key. - */ -export function privateKeyStringToBuffer(pk: string): Buffer { - if (!pk.startsWith("PrivateKey-")) { - throw new PrivateKeyError( - "Error - privateKeyStringToBuffer: private keys must start with 'PrivateKey-'" - ) - } - const pksplit: string[] = pk.split("-") - return bintools.cb58Decode(pksplit[pksplit.length - 1]) -} - -/** - * Takes a nodeID buffer and produces a nodeID string with prefix. - * - * @param pk A {@link https://github.com/feross/buffer|Buffer} for the nodeID. - */ -export function bufferToNodeIDString(pk: Buffer): string { - return `NodeID-${bintools.cb58Encode(pk)}` -} - -/** - * Takes a nodeID string and produces a nodeID {@link https://github.com/feross/buffer|Buffer}. - * - * @param pk A string for the nodeID. - */ -export function NodeIDStringToBuffer(pk: string): Buffer { - if (!pk.startsWith("NodeID-")) { - throw new NodeIdError( - "Error - privateNodeIDToBuffer: nodeID must start with 'NodeID-'" - ) - } - const pksplit: string[] = pk.split("-") - return bintools.cb58Decode(pksplit[pksplit.length - 1]) -} - -export function costImportTx(tx: UnsignedTx): number { - let bytesCost: number = calcBytesCost(tx.toBuffer().byteLength) - const importTx = tx.getTransaction() as ImportTx - importTx.getImportInputs().forEach((input: TransferableInput): void => { - const inCost: number = input.getCost() - bytesCost += inCost - }) - const fixedFee: number = 10000 - return bytesCost + fixedFee -} - -export function calcBytesCost(len: number): number { - return len * Defaults.network[1].C.txBytesGas -} - -export function costExportTx(tx: UnsignedTx): number { - const bytesCost: number = calcBytesCost(tx.toBuffer().byteLength) - const exportTx = tx.getTransaction() as ExportTx - const numSigs: number = exportTx.getInputs().length - const sigCost: number = numSigs * Defaults.network[1].C.costPerSignature - const fixedFee: number = 10000 - return bytesCost + sigCost + fixedFee -} diff --git a/src/utils/index.ts b/src/utils/index.ts index e81689d93..8531cfd08 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -1,13 +1,17 @@ -export * from "./base58" -export * from "./bintools" -export * from "./mnemonic" -export * from "./constants" -export * from "./db" -export * from "./errors" -export * from "./fetchadapter" -export * from "./hdnode" -export * from "./helperfunctions" -export * from "./payload" -export * from "./persistenceoptions" -export * from "./pubsub" -export * from "./serialization" +export * from './address'; +export * from './addressesFromBytes'; +export * from './base58'; +export * from './buffer'; +export * from './bytesCompare'; +export * from './costs'; +export * from './devutils'; +export * from './secp256k1'; +export * from './typeGuards'; +export * from './UTXOSet'; +export * from './addChecksum'; +export * from './addressMap'; +export * from './getTransferableInputsByTx'; +export * from './getTransferableOutputsByTx'; +export * from './getBurnedAmountByTx'; +export * from './validateBurnedAmount'; +export { unpackWithManager, getManagerForVM, packTx } from './packTx'; diff --git a/src/utils/matchOwners.spec.ts b/src/utils/matchOwners.spec.ts new file mode 100644 index 000000000..63f77ec64 --- /dev/null +++ b/src/utils/matchOwners.spec.ts @@ -0,0 +1,73 @@ +import { Address } from '../serializable/fxs/common'; +import { address } from '../fixtures/common'; +import { OutputOwners } from '../serializable/fxs/secp256k1'; +import { addressesFromBytes } from './addressesFromBytes'; +import { AddressMap } from './addressMap'; +import { hexToBuffer } from './buffer'; +import { matchOwners } from './matchOwners'; + +describe('matchOwners', () => { + it('matches owners', () => { + const owner1 = address(); + const owner2 = Address.fromHex('7db97c7cece249c2b98bdc0226cc4c2a57bf52fc'); + const ownerAddresses: Uint8Array[] = [owner1.toBytes(), owner2.toBytes()]; + const goodOwner = OutputOwners.fromNative(ownerAddresses, 0n, 1); + const threasholdTooHigh = OutputOwners.fromNative(ownerAddresses, 0n, 5); + const wrongOwner = OutputOwners.fromNative( + [hexToBuffer('0x12345123451234512345')], + 0n, + 5, + ); + const locked = OutputOwners.fromNative( + ownerAddresses, + 9999999999999999999999999999999999n, + 5, + ); + + const specs = [ + { + testCase: goodOwner, + expectedSigIndices: [0], + expectedAddressMap: new AddressMap([[owner1, 0]]), + }, + { + testCase: threasholdTooHigh, + expectedSigIndices: undefined, + expectedAddressMap: undefined, + }, + { + testCase: locked, + expectedSigIndices: undefined, + expectedAddressMap: undefined, + }, + { + testCase: wrongOwner, + expectedSigIndices: undefined, + expectedAddressMap: undefined, + }, + { + testCase: goodOwner, + sigindices: [1], + expectedSigIndices: [1], + expectedAddressMap: new AddressMap([[owner2, 1]]), + }, + { + testCase: goodOwner, + sigindices: [2], + expectedSigIndices: undefined, + expectedAddressMap: undefined, + }, + ]; + + specs.forEach((spec) => { + const result = matchOwners( + spec.testCase, + addressesFromBytes(ownerAddresses), + 50n, + spec.sigindices, + ); + expect(result?.sigIndicies).toEqual(spec.expectedSigIndices); + expect(result?.addressMap).toEqual(spec.expectedAddressMap); + }); + }); +}); diff --git a/src/utils/matchOwners.ts b/src/utils/matchOwners.ts new file mode 100644 index 000000000..2a4bd55c6 --- /dev/null +++ b/src/utils/matchOwners.ts @@ -0,0 +1,43 @@ +import type { Address } from '../serializable/fxs/common'; +import type { OutputOwners } from '../serializable/fxs/secp256k1'; +import { AddressMap } from './addressMap'; + +export type MatchOwnerResult = { + sigIndicies: number[]; + addressMap: AddressMap; +}; +export const matchOwners = ( + owners: OutputOwners, + inputAddrs: Address[], + minIssuanceTime: bigint, + sigindices?: number[], +): MatchOwnerResult | undefined => { + if (owners.locktime.value() > minIssuanceTime) { + return undefined; + } + + const inputAddrSet = new Set(inputAddrs.map((a) => a.toString())); + const addressMap = owners.addrs.reduce((agg, addr, i) => { + if ( + agg.size() < owners.threshold.value() && + inputAddrSet.has(addr.value()) + ) { + // only add actual signer addresses if sigindices are known + if (sigindices?.length && !sigindices.includes(i)) { + return agg; + } + + return agg.set(addr, i); + } + return agg; + }, new AddressMap()); + + if (addressMap.size() < owners.threshold.value()) { + return undefined; + } + + return { + sigIndicies: Array.from(addressMap.values()), + addressMap: addressMap, + }; +}; diff --git a/src/utils/mnemonic.ts b/src/utils/mnemonic.ts deleted file mode 100644 index b38341cdb..000000000 --- a/src/utils/mnemonic.ts +++ /dev/null @@ -1,150 +0,0 @@ -/** - * @packageDocumentation - * @module Utils-Mnemonic - */ - -import { Buffer } from "buffer/" -import { Wordlist } from "ethers" -import { InvalidEntropy } from "./errors" -const bip39: any = require("bip39") -const randomBytes: any = require("randombytes") - -/** - * BIP39 Mnemonic code for generating deterministic keys. - * - */ -export default class Mnemonic { - private static instance: Mnemonic - private constructor() {} - protected wordlists: string[] = bip39.wordlists - - /** - * Retrieves the Mnemonic singleton. - */ - static getInstance(): Mnemonic { - if (!Mnemonic.instance) { - Mnemonic.instance = new Mnemonic() - } - return Mnemonic.instance - } - - /** - * Return wordlists - * - * @param language a string specifying the language - * - * @returns A [[Wordlist]] object or array of strings - */ - getWordlists(language?: string): string[] | Wordlist { - if (language !== undefined) { - return this.wordlists[`${language}`] - } else { - return this.wordlists - } - } - - /** - * Synchronously takes mnemonic and password and returns {@link https://github.com/feross/buffer|Buffer} - * - * @param mnemonic the mnemonic as a string - * @param password the password as a string - * - * @returns A {@link https://github.com/feross/buffer|Buffer} - */ - mnemonicToSeedSync(mnemonic: string, password: string = ""): Buffer { - const seed: Buffer = bip39.mnemonicToSeedSync(mnemonic, password) - return Buffer.from(seed) - } - - /** - * Asynchronously takes mnemonic and password and returns Promise {@link https://github.com/feross/buffer|Buffer} - * - * @param mnemonic the mnemonic as a string - * @param password the password as a string - * - * @returns A {@link https://github.com/feross/buffer|Buffer} - */ - async mnemonicToSeed( - mnemonic: string, - password: string = "" - ): Promise { - const seed: Buffer = await bip39.mnemonicToSeed(mnemonic, password) - return Buffer.from(seed) - } - - /** - * Takes mnemonic and wordlist and returns buffer - * - * @param mnemonic the mnemonic as a string - * @param wordlist Optional the wordlist as an array of strings - * - * @returns A string - */ - mnemonicToEntropy(mnemonic: string, wordlist?: string[]): string { - return bip39.mnemonicToEntropy(mnemonic, wordlist) - } - - /** - * Takes mnemonic and wordlist and returns buffer - * - * @param entropy the entropy as a {@link https://github.com/feross/buffer|Buffer} or as a string - * @param wordlist Optional, the wordlist as an array of strings - * - * @returns A string - */ - entropyToMnemonic(entropy: Buffer | string, wordlist?: string[]): string { - return bip39.entropyToMnemonic(entropy, wordlist) - } - - /** - * Validates a mnemonic - 11* - * @param mnemonic the mnemonic as a string - * @param wordlist Optional the wordlist as an array of strings - * - * @returns A string - */ - validateMnemonic(mnemonic: string, wordlist?: string[]): string { - return bip39.validateMnemonic(mnemonic, wordlist) - } - - /** - * Sets the default word list - * - * @param language the language as a string - * - */ - setDefaultWordlist(language: string): void { - bip39.setDefaultWordlist(language) - } - - /** - * Returns the language of the default word list - * - * @returns A string - */ - getDefaultWordlist(): string { - return bip39.getDefaultWordlist() - } - - /** - * Generate a random mnemonic (uses crypto.randomBytes under the hood), defaults to 256-bits of entropy - * - * @param strength Optional the strength as a number - * @param rng Optional the random number generator. Defaults to crypto.randomBytes - * @param wordlist Optional - * - */ - generateMnemonic( - strength?: number, - rng?: (size: number) => Buffer, - wordlist?: string[] - ): string { - strength = strength || 256 - if (strength % 32 !== 0) { - throw new InvalidEntropy("Error - Invalid entropy") - } - rng = rng || randomBytes - return bip39.generateMnemonic(strength, rng, wordlist) - } -} diff --git a/src/utils/models.ts b/src/utils/models.ts new file mode 100644 index 000000000..60ca1e682 --- /dev/null +++ b/src/utils/models.ts @@ -0,0 +1,7 @@ +export type UnpackReturn = + | Uint8Array + | number + | bigint + | string + | string[] + | number[]; diff --git a/src/utils/packTx.ts b/src/utils/packTx.ts new file mode 100644 index 000000000..47934178b --- /dev/null +++ b/src/utils/packTx.ts @@ -0,0 +1,39 @@ +import { DEFAULT_CODEC_VERSION } from '../constants/codec'; +import { getAVMManager } from '../serializable/avm/codec'; +import type { Manager } from '../serializable/codec'; +import type { Serializable } from '../serializable/common/types'; +import type { VM } from '../serializable/constants'; +import { getEVMManager } from '../serializable/evm/codec'; +import { Short } from '../serializable/primitives'; +import { getPVMManager } from '../serializable/pvm/codec'; + +export interface GenericTransaction extends Serializable { + vm: VM; +} + +export function getManagerForVM(vm: VM): Manager { + switch (vm) { + case 'AVM': + return getAVMManager(); + case 'EVM': + return getEVMManager(); + case 'PVM': + return getPVMManager(); + default: + throw new Error('unknown VM'); + } +} + +export function unpackWithManager(vm: VM, txBytes: Uint8Array) { + return getManagerForVM(vm).unpackTransaction(txBytes); +} + +export function packTx(tx: GenericTransaction) { + return getManagerForVM(tx.vm).packCodec(tx); +} + +export function getDefaultCodecFromTx(tx: GenericTransaction) { + return getManagerForVM(tx.vm).getCodecForVersion( + new Short(DEFAULT_CODEC_VERSION), + ); +} diff --git a/src/utils/payload.ts b/src/utils/payload.ts deleted file mode 100644 index 6d1c39a08..000000000 --- a/src/utils/payload.ts +++ /dev/null @@ -1,683 +0,0 @@ -/** - * @packageDocumentation - * @module Utils-Payload - */ - -import { Buffer } from "buffer/" -import BinTools from "./bintools" -import BN from "bn.js" -import { TypeIdError, HexError } from "../utils/errors" -import { Serialization, SerializedType } from "../utils/serialization" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() - -/** - * Class for determining payload types and managing the lookup table. - */ -export class PayloadTypes { - private static instance: PayloadTypes - protected types: string[] = [] - - /** - * Given an encoded payload buffer returns the payload content (minus typeID). - */ - getContent(payload: Buffer): Buffer { - const pl: Buffer = bintools.copyFrom(payload, 5) - return pl - } - - /** - * Given an encoded payload buffer returns the payload (with typeID). - */ - getPayload(payload: Buffer): Buffer { - const pl: Buffer = bintools.copyFrom(payload, 4) - return pl - } - - /** - * Given a payload buffer returns the proper TypeID. - */ - getTypeID(payload: Buffer): number { - const offset: number = 4 - const typeID: number = bintools - .copyFrom(payload, offset, offset + 1) - .readUInt8(0) - return typeID - } - - /** - * Given a type string returns the proper TypeID. - */ - lookupID(typestr: string): number { - return this.types.indexOf(typestr) - } - - /** - * Given a TypeID returns a string describing the payload type. - */ - lookupType(value: number): string { - return this.types[`${value}`] - } - - /** - * Given a TypeID returns the proper [[PayloadBase]]. - */ - select(typeID: number, ...args: any[]): PayloadBase { - switch (typeID) { - case 0: - return new BINPayload(...args) - case 1: - return new UTF8Payload(...args) - case 2: - return new HEXSTRPayload(...args) - case 3: - return new B58STRPayload(...args) - case 4: - return new B64STRPayload(...args) - case 5: - return new BIGNUMPayload(...args) - case 6: - return new XCHAINADDRPayload(...args) - case 7: - return new PCHAINADDRPayload(...args) - case 8: - return new CCHAINADDRPayload(...args) - case 9: - return new TXIDPayload(...args) - case 10: - return new ASSETIDPayload(...args) - case 11: - return new UTXOIDPayload(...args) - case 12: - return new NFTIDPayload(...args) - case 13: - return new SUBNETIDPayload(...args) - case 14: - return new CHAINIDPayload(...args) - case 15: - return new NODEIDPayload(...args) - case 16: - return new SECPSIGPayload(...args) - case 17: - return new SECPENCPayload(...args) - case 18: - return new JPEGPayload(...args) - case 19: - return new PNGPayload(...args) - case 20: - return new BMPPayload(...args) - case 21: - return new ICOPayload(...args) - case 22: - return new SVGPayload(...args) - case 23: - return new CSVPayload(...args) - case 24: - return new JSONPayload(...args) - case 25: - return new YAMLPayload(...args) - case 26: - return new EMAILPayload(...args) - case 27: - return new URLPayload(...args) - case 28: - return new IPFSPayload(...args) - case 29: - return new ONIONPayload(...args) - case 30: - return new MAGNETPayload(...args) - } - throw new TypeIdError( - `Error - PayloadTypes.select: unknown typeid ${typeID}` - ) - } - - /** - * Given a [[PayloadBase]] which may not be cast properly, returns a properly cast [[PayloadBase]]. - */ - recast(unknowPayload: PayloadBase): PayloadBase { - return this.select(unknowPayload.typeID(), unknowPayload.returnType()) - } - - /** - * Returns the [[PayloadTypes]] singleton. - */ - static getInstance(): PayloadTypes { - if (!PayloadTypes.instance) { - PayloadTypes.instance = new PayloadTypes() - } - - return PayloadTypes.instance - } - - private constructor() { - this.types = [ - "BIN", - "UTF8", - "HEXSTR", - "B58STR", - "B64STR", - "BIGNUM", - "XCHAINADDR", - "PCHAINADDR", - "CCHAINADDR", - "TXID", - "ASSETID", - "UTXOID", - "NFTID", - "SUBNETID", - "CHAINID", - "NODEID", - "SECPSIG", - "SECPENC", - "JPEG", - "PNG", - "BMP", - "ICO", - "SVG", - "CSV", - "JSON", - "YAML", - "EMAIL", - "URL", - "IPFS", - "ONION", - "MAGNET" - ] - } -} - -/** - * Base class for payloads. - */ -export abstract class PayloadBase { - protected payload: Buffer = Buffer.alloc(0) - protected typeid: number = undefined - - /** - * Returns the TypeID for the payload. - */ - typeID(): number { - return this.typeid - } - - /** - * Returns the string name for the payload's type. - */ - typeName(): string { - return PayloadTypes.getInstance().lookupType(this.typeid) - } - - /** - * Returns the payload content (minus typeID). - */ - getContent(): Buffer { - const pl: Buffer = bintools.copyFrom(this.payload) - return pl - } - - /** - * Returns the payload (with typeID). - */ - getPayload(): Buffer { - const typeID: Buffer = Buffer.alloc(1) - typeID.writeUInt8(this.typeid, 0) - const pl: Buffer = Buffer.concat([typeID, bintools.copyFrom(this.payload)]) - return pl - } - - /** - * Decodes the payload as a {@link https://github.com/feross/buffer|Buffer} including 4 bytes for the length and TypeID. - */ - fromBuffer(bytes: Buffer, offset: number = 0): number { - const size: number = bintools - .copyFrom(bytes, offset, offset + 4) - .readUInt32BE(0) - offset += 4 - this.typeid = bintools.copyFrom(bytes, offset, offset + 1).readUInt8(0) - offset += 1 - this.payload = bintools.copyFrom(bytes, offset, offset + size - 1) - offset += size - 1 - return offset - } - - /** - * Encodes the payload as a {@link https://github.com/feross/buffer|Buffer} including 4 bytes for the length and TypeID. - */ - toBuffer(): Buffer { - const sizebuff: Buffer = Buffer.alloc(4) - sizebuff.writeUInt32BE(this.payload.length + 1, 0) - const typebuff: Buffer = Buffer.alloc(1) - typebuff.writeUInt8(this.typeid, 0) - return Buffer.concat([sizebuff, typebuff, this.payload]) - } - - /** - * Returns the expected type for the payload. - */ - abstract returnType(...args: any): any - - constructor() {} -} - -/** - * Class for payloads representing simple binary blobs. - */ -export class BINPayload extends PayloadBase { - protected typeid = 0 - - /** - * Returns a {@link https://github.com/feross/buffer|Buffer} for the payload. - */ - returnType(): Buffer { - return this.payload - } - /** - * @param payload Buffer only - */ - constructor(payload: any = undefined) { - super() - if (payload instanceof Buffer) { - this.payload = payload - } else if (typeof payload === "string") { - this.payload = bintools.b58ToBuffer(payload) - } - } -} - -/** - * Class for payloads representing UTF8 encoding. - */ -export class UTF8Payload extends PayloadBase { - protected typeid = 1 - - /** - * Returns a string for the payload. - */ - returnType(): string { - return this.payload.toString("utf8") - } - /** - * @param payload Buffer utf8 string - */ - constructor(payload: any = undefined) { - super() - if (payload instanceof Buffer) { - this.payload = payload - } else if (typeof payload === "string") { - this.payload = Buffer.from(payload, "utf8") - } - } -} - -/** - * Class for payloads representing Hexadecimal encoding. - */ -export class HEXSTRPayload extends PayloadBase { - protected typeid = 2 - - /** - * Returns a hex string for the payload. - */ - returnType(): string { - return this.payload.toString("hex") - } - /** - * @param payload Buffer or hex string - */ - constructor(payload: any = undefined) { - super() - if (payload instanceof Buffer) { - this.payload = payload - } else if (typeof payload === "string") { - if (payload.startsWith("0x") || !payload.match(/^[0-9A-Fa-f]+$/)) { - throw new HexError( - "HEXSTRPayload.constructor -- hex string may not start with 0x and must be in /^[0-9A-Fa-f]+$/: " + - payload - ) - } - this.payload = Buffer.from(payload, "hex") - } - } -} - -/** - * Class for payloads representing Base58 encoding. - */ -export class B58STRPayload extends PayloadBase { - protected typeid = 3 - - /** - * Returns a base58 string for the payload. - */ - returnType(): string { - return bintools.bufferToB58(this.payload) - } - /** - * @param payload Buffer or cb58 encoded string - */ - constructor(payload: any = undefined) { - super() - if (payload instanceof Buffer) { - this.payload = payload - } else if (typeof payload === "string") { - this.payload = bintools.b58ToBuffer(payload) - } - } -} - -/** - * Class for payloads representing Base64 encoding. - */ -export class B64STRPayload extends PayloadBase { - protected typeid = 4 - - /** - * Returns a base64 string for the payload. - */ - returnType(): string { - return this.payload.toString("base64") - } - /** - * @param payload Buffer of base64 string - */ - constructor(payload: any = undefined) { - super() - if (payload instanceof Buffer) { - this.payload = payload - } else if (typeof payload === "string") { - this.payload = Buffer.from(payload, "base64") - } - } -} - -/** - * Class for payloads representing Big Numbers. - * - * @param payload Accepts a Buffer, BN, or base64 string - */ -export class BIGNUMPayload extends PayloadBase { - protected typeid = 5 - - /** - * Returns a {@link https://github.com/indutny/bn.js/|BN} for the payload. - */ - returnType(): BN { - return bintools.fromBufferToBN(this.payload) - } - /** - * @param payload Buffer, BN, or base64 string - */ - constructor(payload: any = undefined) { - super() - if (payload instanceof Buffer) { - this.payload = payload - } else if (payload instanceof BN) { - this.payload = bintools.fromBNToBuffer(payload) - } else if (typeof payload === "string") { - this.payload = Buffer.from(payload, "hex") - } - } -} - -/** - * Class for payloads representing chain addresses. - * - */ -export abstract class ChainAddressPayload extends PayloadBase { - protected typeid = 6 - protected chainid: string = "" - - /** - * Returns the chainid. - */ - returnChainID(): string { - return this.chainid - } - - /** - * Returns an address string for the payload. - */ - returnType(hrp: string): string { - const type: SerializedType = "bech32" - return serialization.bufferToType(this.payload, type, hrp, this.chainid) - } - /** - * @param payload Buffer or address string - */ - constructor(payload: any = undefined, hrp?: string) { - super() - if (payload instanceof Buffer) { - this.payload = payload - } else if (typeof payload === "string") { - if (hrp != undefined) { - this.payload = bintools.stringToAddress(payload, hrp) - } else { - this.payload = bintools.stringToAddress(payload) - } - } - } -} - -/** - * Class for payloads representing X-Chin addresses. - */ -export class XCHAINADDRPayload extends ChainAddressPayload { - protected typeid = 6 - protected chainid = "X" -} - -/** - * Class for payloads representing P-Chain addresses. - */ -export class PCHAINADDRPayload extends ChainAddressPayload { - protected typeid = 7 - protected chainid = "P" -} - -/** - * Class for payloads representing C-Chain addresses. - */ -export class CCHAINADDRPayload extends ChainAddressPayload { - protected typeid = 8 - protected chainid = "C" -} - -/** - * Class for payloads representing data serialized by bintools.cb58Encode(). - */ -export abstract class cb58EncodedPayload extends PayloadBase { - /** - * Returns a bintools.cb58Encoded string for the payload. - */ - returnType(): string { - return bintools.cb58Encode(this.payload) - } - /** - * @param payload Buffer or cb58 encoded string - */ - constructor(payload: any = undefined) { - super() - if (payload instanceof Buffer) { - this.payload = payload - } else if (typeof payload === "string") { - this.payload = bintools.cb58Decode(payload) - } - } -} - -/** - * Class for payloads representing TxIDs. - */ -export class TXIDPayload extends cb58EncodedPayload { - protected typeid = 9 -} - -/** - * Class for payloads representing AssetIDs. - */ -export class ASSETIDPayload extends cb58EncodedPayload { - protected typeid = 10 -} - -/** - * Class for payloads representing NODEIDs. - */ -export class UTXOIDPayload extends cb58EncodedPayload { - protected typeid = 11 -} - -/** - * Class for payloads representing NFTIDs (UTXOIDs in an NFT context). - */ -export class NFTIDPayload extends UTXOIDPayload { - protected typeid = 12 -} - -/** - * Class for payloads representing SubnetIDs. - */ -export class SUBNETIDPayload extends cb58EncodedPayload { - protected typeid = 13 -} - -/** - * Class for payloads representing ChainIDs. - */ -export class CHAINIDPayload extends cb58EncodedPayload { - protected typeid = 14 -} - -/** - * Class for payloads representing NodeIDs. - */ -export class NODEIDPayload extends cb58EncodedPayload { - protected typeid = 15 -} - -/** - * Class for payloads representing secp256k1 signatures. - * convention: secp256k1 signature (130 bytes) - */ -export class SECPSIGPayload extends B58STRPayload { - protected typeid = 16 -} - -/** - * Class for payloads representing secp256k1 encrypted messages. - * convention: public key (65 bytes) + secp256k1 encrypted message for that public key - */ -export class SECPENCPayload extends B58STRPayload { - protected typeid = 17 -} - -/** - * Class for payloads representing JPEG images. - */ -export class JPEGPayload extends BINPayload { - protected typeid = 18 -} - -export class PNGPayload extends BINPayload { - protected typeid = 19 -} - -/** - * Class for payloads representing BMP images. - */ -export class BMPPayload extends BINPayload { - protected typeid = 20 -} - -/** - * Class for payloads representing ICO images. - */ -export class ICOPayload extends BINPayload { - protected typeid = 21 -} - -/** - * Class for payloads representing SVG images. - */ -export class SVGPayload extends UTF8Payload { - protected typeid = 22 -} - -/** - * Class for payloads representing CSV files. - */ -export class CSVPayload extends UTF8Payload { - protected typeid = 23 -} - -/** - * Class for payloads representing JSON strings. - */ -export class JSONPayload extends PayloadBase { - protected typeid = 24 - - /** - * Returns a JSON-decoded object for the payload. - */ - returnType(): any { - return JSON.parse(this.payload.toString("utf8")) - } - - constructor(payload: any = undefined) { - super() - if (payload instanceof Buffer) { - this.payload = payload - } else if (typeof payload === "string") { - this.payload = Buffer.from(payload, "utf8") - } else if (payload) { - let jsonstr: string = JSON.stringify(payload) - this.payload = Buffer.from(jsonstr, "utf8") - } - } -} - -/** - * Class for payloads representing YAML definitions. - */ -export class YAMLPayload extends UTF8Payload { - protected typeid = 25 -} - -/** - * Class for payloads representing email addresses. - */ -export class EMAILPayload extends UTF8Payload { - protected typeid = 26 -} - -/** - * Class for payloads representing URL strings. - */ -export class URLPayload extends UTF8Payload { - protected typeid = 27 -} - -/** - * Class for payloads representing IPFS addresses. - */ -export class IPFSPayload extends B58STRPayload { - protected typeid = 28 -} - -/** - * Class for payloads representing onion URLs. - */ -export class ONIONPayload extends UTF8Payload { - protected typeid = 29 -} - -/** - * Class for payloads representing torrent magnet links. - */ -export class MAGNETPayload extends UTF8Payload { - protected typeid = 30 -} diff --git a/src/utils/persistenceoptions.ts b/src/utils/persistenceoptions.ts deleted file mode 100644 index 846667f7c..000000000 --- a/src/utils/persistenceoptions.ts +++ /dev/null @@ -1,54 +0,0 @@ -/** - * @packageDocumentation - * @module Utils-PersistanceOptions - */ - -import { MergeRule } from "./constants" -/** - * A class for defining the persistance behavior of this an API call. - * - */ -export class PersistanceOptions { - protected name: string = undefined - - protected overwrite: boolean = false - - protected mergeRule: MergeRule = "union" - - /** - * Returns the namespace of the instance - */ - getName = (): string => this.name - - /** - * Returns the overwrite rule of the instance - */ - getOverwrite = (): boolean => this.overwrite - - /** - * Returns the [[MergeRule]] of the instance - */ - getMergeRule = (): MergeRule => this.mergeRule - - /** - * - * @param name The namespace of the database the data - * @param overwrite True if the data should be completey overwritten - * @param MergeRule The type of process used to merge with existing data: "intersection", "differenceSelf", "differenceNew", "symDifference", "union", "unionMinusNew", "unionMinusSelf" - * - * @remarks - * The merge rules are as follows: - * * "intersection" - the intersection of the set - * * "differenceSelf" - the difference between the existing data and new set - * * "differenceNew" - the difference between the new data and the existing set - * * "symDifference" - the union of the differences between both sets of data - * * "union" - the unique set of all elements contained in both sets - * * "unionMinusNew" - the unique set of all elements contained in both sets, excluding values only found in the new set - * * "unionMinusSelf" - the unique set of all elements contained in both sets, excluding values only found in the existing set - */ - constructor(name: string, overwrite: boolean = false, mergeRule: MergeRule) { - this.name = name - this.overwrite = overwrite - this.mergeRule = mergeRule - } -} diff --git a/src/utils/pubsub.ts b/src/utils/pubsub.ts deleted file mode 100644 index 68dd504cf..000000000 --- a/src/utils/pubsub.ts +++ /dev/null @@ -1,20 +0,0 @@ -export default class PubSub { - newSet() { - return JSON.stringify({ newSet: {} }) - } - newBloom(maxElements: number = 1000, collisionProb: number = 0.01) { - return JSON.stringify({ - newBloom: { - maxElements: maxElements, - collisionProb: collisionProb - } - }) - } - addAddresses(addresses: string[]) { - return JSON.stringify({ - addAddresses: { - addresses: addresses - } - }) - } -} diff --git a/src/utils/removeDuplicateUTXOs.ts b/src/utils/removeDuplicateUTXOs.ts new file mode 100644 index 000000000..ba16bd318 --- /dev/null +++ b/src/utils/removeDuplicateUTXOs.ts @@ -0,0 +1,12 @@ +import type { Utxo } from '../serializable/avax/utxo'; + +/** + * Returns a new array of unique UTXOs. + * @param utxos + */ +export function filterDuplicateUTXOs(utxos: Utxo[]) { + const ids = utxos.map((utxo) => utxo.ID()); + return utxos.filter((utxo, index) => { + return ids.indexOf(utxo.ID()) == index; + }); +} diff --git a/src/utils/secp256k1.spec.ts b/src/utils/secp256k1.spec.ts new file mode 100644 index 000000000..e0dd87847 --- /dev/null +++ b/src/utils/secp256k1.spec.ts @@ -0,0 +1,72 @@ +import { sha256 } from '@noble/hashes/sha256'; +import { base58check } from './base58'; +import { bufferToHex, hexToBuffer } from './buffer'; +import * as secp from './secp256k1'; + +describe('secp256k1', function () { + it('works correctly', async () => { + const key = '24jUJ9vZexUM6expyMcT48LBx27k1m7xpraoV62oSQAHdziao5'; + const privKey = base58check.decode(key); + const pubKey = secp.getPublicKey(privKey); + + expect(base58check.encode(secp.publicKeyBytesToAddress(pubKey))).toEqual( + 'Q4MzFZZDPHRPAHFeDs3NiyyaZDvxHKivf', + ); + + const tests = [ + { + msg: 'hello world', + sig: new Uint8Array([ + 0x17, 0x8c, 0xb6, 0x09, 0x6b, 0x3c, 0xa5, 0x82, 0x0a, 0x4c, 0x6e, + 0xce, 0xdf, 0x15, 0xb6, 0x8b, 0x6f, 0x50, 0xe2, 0x52, 0xc2, 0xb6, + 0x4f, 0x37, 0x74, 0x88, 0x86, 0x02, 0xcc, 0x9f, 0xa0, 0x8c, 0x5d, + 0x01, 0x9d, 0x82, 0xfd, 0xde, 0x95, 0xfd, 0xf2, 0x34, 0xaa, 0x2d, + 0x12, 0xad, 0x79, 0xb5, 0xab, 0xb3, 0x45, 0xfe, 0x95, 0x3a, 0x9f, + 0x72, 0xf7, 0x09, 0x14, 0xfd, 0x31, 0x39, 0x06, 0x3b, 0x00, + ]), + }, + { + msg: 'scooby doo', + sig: new Uint8Array([ + 0xc2, 0x57, 0x3f, 0x29, 0xb0, 0xd1, 0x7a, 0xe7, 0x00, 0x9a, 0x9f, + 0x17, 0xa4, 0x55, 0x8d, 0x32, 0x46, 0x2e, 0x5b, 0x8d, 0x05, 0x9e, + 0x38, 0x32, 0xec, 0xb0, 0x32, 0x54, 0x1a, 0xbc, 0x7d, 0xaf, 0x57, + 0x51, 0xf9, 0x6b, 0x85, 0x71, 0xbc, 0xb7, 0x18, 0xd2, 0x6b, 0xe8, + 0xed, 0x8d, 0x59, 0xb0, 0xd6, 0x03, 0x69, 0xab, 0x57, 0xac, 0xc0, + 0xf7, 0x13, 0x3b, 0x21, 0x94, 0x56, 0x03, 0x8e, 0xc7, 0x01, + ]), + }, + { + msg: 'a really long string', + sig: new Uint8Array([ + 0x1b, 0xf5, 0x61, 0xc3, 0x60, 0x07, 0xd2, 0xa6, 0x12, 0x68, 0xe9, + 0xe1, 0x3a, 0x90, 0x2a, 0x9c, 0x2b, 0xa4, 0x3e, 0x28, 0xf8, 0xd4, + 0x75, 0x54, 0x21, 0x57, 0x11, 0xdc, 0xdc, 0xc6, 0xd3, 0x5e, 0x78, + 0x43, 0x18, 0xf6, 0x22, 0x91, 0x37, 0x3c, 0x95, 0x77, 0x9f, 0x67, + 0x94, 0x91, 0x0a, 0x44, 0x16, 0xbf, 0xa3, 0xae, 0x9f, 0x25, 0xfa, + 0x34, 0xa0, 0x14, 0xea, 0x9c, 0x6f, 0xe0, 0x20, 0x37, 0x00, + ]), + }, + ]; + + for (const test of tests) { + const hash = sha256(test.msg); + + await expect(secp.sign(test.msg, privKey)).resolves.toEqual(test.sig); + await expect(secp.signHash(hash, privKey)).resolves.toEqual(test.sig); + expect(secp.recoverPublicKey(hash, test.sig)).toEqual(pubKey); + expect(secp.verify(test.sig, hash, pubKey)).toEqual(true); + } + }); + + it('works with EVM', () => { + const publicKey = hexToBuffer( + '04e68acfc0253a10620dff706b0a1b1f1f5833ea3beb3bde2250d5f271f3563606672ebc45e0b7ea2e816ecb70ca03137b1c9476eec63d4632e990020b7b6fba39', + ); + + const ethAddrKey = bufferToHex(secp.publicKeyToEthAddress(publicKey)); + expect(ethAddrKey).toBe( + '0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1'.toLocaleLowerCase(), + ); + }); +}); diff --git a/src/utils/secp256k1.ts b/src/utils/secp256k1.ts new file mode 100644 index 000000000..8c5b5a324 --- /dev/null +++ b/src/utils/secp256k1.ts @@ -0,0 +1,53 @@ +import { ripemd160 } from '@noble/hashes/ripemd160'; +import { sha256 } from '@noble/hashes/sha256'; +import * as secp from '@noble/secp256k1'; +import { Address } from 'micro-eth-signer'; +import { concatBytes, hexToBuffer } from './buffer'; + +export function randomPrivateKey() { + return secp.utils.randomPrivateKey(); +} + +export function sign(msg: Uint8Array | string, privKey: Uint8Array) { + return signHash(sha256(msg), privKey); +} + +export async function signHash(hash: Uint8Array, privKey: Uint8Array) { + const sig = await secp.signAsync(hash, privKey); + + if (sig.recovery !== undefined) { + return concatBytes(sig.toCompactRawBytes(), new Uint8Array([sig.recovery])); + } else { + throw new Error(`Recovery bit is missing.`); + } +} + +export function recoverPublicKey(hash: Uint8Array | string, sig: Uint8Array) { + const recoveryBit = sig.slice(-1); + const secpSig = secp.Signature.fromCompact(sig.slice(0, -1)).addRecoveryBit( + recoveryBit[0], + ); + const point = secpSig.recoverPublicKey(hash); + + return point.toRawBytes(true); +} + +export function getPublicKey(privKey: Uint8Array) { + return secp.getPublicKey(privKey, true); +} + +export function verify( + sig: Uint8Array, + hash: Uint8Array | string, + publicKey: Uint8Array, +) { + return secp.verify(sig.slice(0, -1), hash, publicKey); +} + +export function publicKeyBytesToAddress(publicKey: Uint8Array) { + return ripemd160(sha256(publicKey)); +} + +export function publicKeyToEthAddress(key: Uint8Array) { + return hexToBuffer(Address.fromPublicKey(key)); +} diff --git a/src/utils/serialization.ts b/src/utils/serialization.ts deleted file mode 100644 index 93a70e659..000000000 --- a/src/utils/serialization.ts +++ /dev/null @@ -1,348 +0,0 @@ -/** - * @packageDocumentation - * @module Utils-Serialization - */ -import BinTools from "../utils/bintools" -import BN from "bn.js" -import { Buffer } from "buffer/" -import xss from "xss" -import { - NodeIDStringToBuffer, - privateKeyStringToBuffer, - bufferToNodeIDString, - bufferToPrivateKeyString -} from "./helperfunctions" -import { - CodecIdError, - TypeIdError, - TypeNameError, - UnknownTypeError -} from "../utils/errors" -import { Serialized } from "../common" - -export const SERIALIZATIONVERSION: number = 0 -export type SerializedType = - | "hex" - | "BN" - | "Buffer" - | "bech32" - | "nodeID" - | "privateKey" - | "cb58" - | "base58" - | "base64" - | "decimalString" - | "number" - | "utf8" - -export type SerializedEncoding = - | "hex" - | "cb58" - | "base58" - | "base64" - | "decimalString" - | "number" - | "utf8" - | "display" - -export abstract class Serializable { - protected _typeName: string = undefined - protected _typeID: number = undefined - protected _codecID: number = undefined - - /** - * Used in serialization. TypeName is a string name for the type of object being output. - */ - getTypeName(): string { - return this._typeName - } - - /** - * Used in serialization. Optional. TypeID is a number for the typeID of object being output. - */ - getTypeID(): number { - return this._typeID - } - - /** - * Used in serialization. Optional. TypeID is a number for the typeID of object being output. - */ - getCodecID(): number { - return this._codecID - } - - /** - * Sanitize to prevent cross scripting attacks. - */ - sanitizeObject(obj: object): object { - for (const k in obj) { - if (typeof obj[`${k}`] === "object" && obj[`${k}`] !== null) { - this.sanitizeObject(obj[`${k}`]) - } else if (typeof obj[`${k}`] === "string") { - obj[`${k}`] = xss(obj[`${k}`]) - } - } - return obj - } - - //sometimes the parent class manages the fields - //these are so you can say super.serialize(encoding) - serialize(encoding?: SerializedEncoding): object { - return { - _typeName: xss(this._typeName), - _typeID: typeof this._typeID === "undefined" ? null : this._typeID, - _codecID: typeof this._codecID === "undefined" ? null : this._codecID - } - } - deserialize(fields: object, encoding?: SerializedEncoding): void { - fields = this.sanitizeObject(fields) - if (typeof fields["_typeName"] !== "string") { - throw new TypeNameError( - "Error - Serializable.deserialize: _typeName must be a string, found: " + - typeof fields["_typeName"] - ) - } - if (fields["_typeName"] !== this._typeName) { - throw new TypeNameError( - "Error - Serializable.deserialize: _typeName mismatch -- expected: " + - this._typeName + - " -- received: " + - fields["_typeName"] - ) - } - if ( - typeof fields["_typeID"] !== "undefined" && - fields["_typeID"] !== null - ) { - if (typeof fields["_typeID"] !== "number") { - throw new TypeIdError( - "Error - Serializable.deserialize: _typeID must be a number, found: " + - typeof fields["_typeID"] - ) - } - if (fields["_typeID"] !== this._typeID) { - throw new TypeIdError( - "Error - Serializable.deserialize: _typeID mismatch -- expected: " + - this._typeID + - " -- received: " + - fields["_typeID"] - ) - } - } - if ( - typeof fields["_codecID"] !== "undefined" && - fields["_codecID"] !== null - ) { - if (typeof fields["_codecID"] !== "number") { - throw new CodecIdError( - "Error - Serializable.deserialize: _codecID must be a number, found: " + - typeof fields["_codecID"] - ) - } - if (fields["_codecID"] !== this._codecID) { - throw new CodecIdError( - "Error - Serializable.deserialize: _codecID mismatch -- expected: " + - this._codecID + - " -- received: " + - fields["_codecID"] - ) - } - } - } -} - -export class Serialization { - private static instance: Serialization - - private constructor() { - this.bintools = BinTools.getInstance() - } - private bintools: BinTools - - /** - * Retrieves the Serialization singleton. - */ - static getInstance(): Serialization { - if (!Serialization.instance) { - Serialization.instance = new Serialization() - } - return Serialization.instance - } - - /** - * Convert {@link https://github.com/feross/buffer|Buffer} to [[SerializedType]] - * - * @param vb {@link https://github.com/feross/buffer|Buffer} - * @param type [[SerializedType]] - * @param ...args remaining arguments - * @returns type of [[SerializedType]] - */ - bufferToType(vb: Buffer, type: SerializedType, ...args: any[]): any { - if (type === "BN") { - return new BN(vb.toString("hex"), "hex") - } else if (type === "Buffer") { - if (args.length == 1 && typeof args[0] === "number") { - vb = Buffer.from(vb.toString("hex").padStart(args[0] * 2, "0"), "hex") - } - return vb - } else if (type === "bech32") { - return this.bintools.addressToString(args[0], args[1], vb) - } else if (type === "nodeID") { - return bufferToNodeIDString(vb) - } else if (type === "privateKey") { - return bufferToPrivateKeyString(vb) - } else if (type === "cb58") { - return this.bintools.cb58Encode(vb) - } else if (type === "base58") { - return this.bintools.bufferToB58(vb) - } else if (type === "base64") { - return vb.toString("base64") - } else if (type === "hex") { - return vb.toString("hex") - } else if (type === "decimalString") { - return new BN(vb.toString("hex"), "hex").toString(10) - } else if (type === "number") { - return new BN(vb.toString("hex"), "hex").toNumber() - } else if (type === "utf8") { - return vb.toString("utf8") - } - return undefined - } - - /** - * Convert [[SerializedType]] to {@link https://github.com/feross/buffer|Buffer} - * - * @param v type of [[SerializedType]] - * @param type [[SerializedType]] - * @param ...args remaining arguments - * @returns {@link https://github.com/feross/buffer|Buffer} - */ - typeToBuffer(v: any, type: SerializedType, ...args: any[]): Buffer { - if (type === "BN") { - let str: string = (v as BN).toString("hex") - if (args.length == 1 && typeof args[0] === "number") { - return Buffer.from(str.padStart(args[0] * 2, "0"), "hex") - } - return Buffer.from(str, "hex") - } else if (type === "Buffer") { - return v - } else if (type === "bech32") { - return this.bintools.stringToAddress(v, ...args) - } else if (type === "nodeID") { - return NodeIDStringToBuffer(v) - } else if (type === "privateKey") { - return privateKeyStringToBuffer(v) - } else if (type === "cb58") { - return this.bintools.cb58Decode(v) - } else if (type === "base58") { - return this.bintools.b58ToBuffer(v) - } else if (type === "base64") { - return Buffer.from(v as string, "base64") - } else if (type === "hex") { - if ((v as string).startsWith("0x")) { - v = (v as string).slice(2) - } - return Buffer.from(v as string, "hex") - } else if (type === "decimalString") { - let str: string = new BN(v as string, 10).toString("hex") - if (args.length == 1 && typeof args[0] === "number") { - return Buffer.from(str.padStart(args[0] * 2, "0"), "hex") - } - return Buffer.from(str, "hex") - } else if (type === "number") { - let str: string = new BN(v, 10).toString("hex") - if (args.length == 1 && typeof args[0] === "number") { - return Buffer.from(str.padStart(args[0] * 2, "0"), "hex") - } - return Buffer.from(str, "hex") - } else if (type === "utf8") { - if (args.length == 1 && typeof args[0] === "number") { - let b: Buffer = Buffer.alloc(args[0]) - b.write(v) - return b - } - return Buffer.from(v, "utf8") - } - return undefined - } - - /** - * Convert value to type of [[SerializedType]] or [[SerializedEncoding]] - * - * @param value - * @param encoding [[SerializedEncoding]] - * @param intype [[SerializedType]] - * @param outtype [[SerializedType]] - * @param ...args remaining arguments - * @returns type of [[SerializedType]] or [[SerializedEncoding]] - */ - encoder( - value: any, - encoding: SerializedEncoding, - intype: SerializedType, - outtype: SerializedType, - ...args: any[] - ): any { - if (typeof value === "undefined") { - throw new UnknownTypeError( - "Error - Serializable.encoder: value passed is undefined" - ) - } - if (encoding !== "display") { - outtype = encoding - } - const vb: Buffer = this.typeToBuffer(value, intype, ...args) - return this.bufferToType(vb, outtype, ...args) - } - - /** - * Convert value to type of [[SerializedType]] or [[SerializedEncoding]] - * - * @param value - * @param encoding [[SerializedEncoding]] - * @param intype [[SerializedType]] - * @param outtype [[SerializedType]] - * @param ...args remaining arguments - * @returns type of [[SerializedType]] or [[SerializedEncoding]] - */ - decoder( - value: string, - encoding: SerializedEncoding, - intype: SerializedType, - outtype: SerializedType, - ...args: any[] - ): any { - if (typeof value === "undefined") { - throw new UnknownTypeError( - "Error - Serializable.decoder: value passed is undefined" - ) - } - if (encoding !== "display") { - intype = encoding - } - const vb: Buffer = this.typeToBuffer(value, intype, ...args) - return this.bufferToType(vb, outtype, ...args) - } - - serialize( - serialize: Serializable, - vm: string, - encoding: SerializedEncoding = "display", - notes: string = undefined - ): Serialized { - if (typeof notes === "undefined") { - notes = serialize.getTypeName() - } - return { - vm, - encoding, - version: SERIALIZATIONVERSION, - notes, - fields: serialize.serialize(encoding) - } - } - - deserialize(input: Serialized, output: Serializable) { - output.deserialize(input.fields, input.encoding) - } -} diff --git a/src/utils/serializeList.spec.ts b/src/utils/serializeList.spec.ts new file mode 100644 index 000000000..de782b655 --- /dev/null +++ b/src/utils/serializeList.spec.ts @@ -0,0 +1,34 @@ +import { TransferableInput } from '../serializable/avax'; +import { transferableInputs, transferableInputsBytes } from '../fixtures/avax'; +import { testCodec } from '../fixtures/codec'; +import { address, addressesBytes } from '../fixtures/common'; +import { Address } from '../serializable/fxs/common'; +import { packList, toListStruct, unpackList } from './serializeList'; +import { unpack } from './struct'; + +describe('SerializeList', () => { + it('unpacks list', () => { + const adds = addressesBytes(); + expect(unpackList(adds, Address, testCodec())).toEqual([ + [address(), address()], + new Uint8Array([]), + ]); + }); + + it('unpacks list', () => { + expect(packList([address(), address()], testCodec())).toEqual( + addressesBytes(), + ); + }); + + it('unpack for list type', () => { + const transferableInputsType = toListStruct(TransferableInput); + const [result, remaining] = unpack( + transferableInputsBytes(), + [transferableInputsType], + testCodec(), + ); + expect(result).toEqual(transferableInputs()); + expect(remaining).toHaveLength(0); + }); +}); diff --git a/src/utils/serializeList.ts b/src/utils/serializeList.ts new file mode 100644 index 000000000..e62ef200f --- /dev/null +++ b/src/utils/serializeList.ts @@ -0,0 +1,64 @@ +import { bytesForInt } from '../fixtures/utils/bytesFor'; +import type { Codec } from '../serializable/codec'; +import type { + Serializable, + SerializableStatic, +} from '../serializable/common/types'; +import { Int } from '../serializable/primitives/int'; +import { concatBytes } from './buffer'; + +type unpackFunc = (buf: Uint8Array, codec: Codec) => [any, Uint8Array]; + +export const unpackList = ( + buf: Uint8Array, + serializable: T, + codec: Codec, +): [ReturnType[0][], Uint8Array] => { + return unpackListForEach(buf, serializable.fromBytes, codec); +}; + +export const unpackListForEach = ( + buf: Uint8Array, + callback: T, + codec: Codec, +): [ReturnType[0][], Uint8Array] => { + let len; + [len, buf] = Int.fromBytes(buf); + const result: ReturnType[0][] = []; + for (let i = 0; i < len.value(); i++) { + if (buf.length === 0) { + throw new Error('not enough bytes'); + } + let res: any; + [res, buf] = callback(buf, codec); + result.push(res); + } + return [result, buf]; +}; + +export const toListStruct = ( + serializable: T, +) => ({ + fromBytes: (buff: Uint8Array, codec: Codec) => + unpackList(buff, serializable, codec), +}); + +export const unpackCodecList = { + fromBytes: ( + buff: Uint8Array, + codec?: Codec, + ): [Serializable[], Uint8Array] => { + if (!codec) throw new Error('codec required when using unpackCodecList'); + return unpackListForEach(buff, codec.UnpackPrefix, codec); + }, +}; + +export const packList = ( + serializables: Serializable[], + codec: Codec, +): Uint8Array => { + return concatBytes( + bytesForInt(serializables.length), + ...serializables.map((ser) => ser.toBytes(codec)), + ); +}; diff --git a/src/utils/sort.spec.ts b/src/utils/sort.spec.ts new file mode 100644 index 000000000..a5469ee4b --- /dev/null +++ b/src/utils/sort.spec.ts @@ -0,0 +1,83 @@ +import { jest } from '@jest/globals'; +import { testCodec, testPVMCodec } from '../fixtures/codec'; +import { + getStakeableLockedTransferableOutForTest, + getTransferableOutForTest, +} from '../fixtures/transactions'; + +// eslint-disable-next-line @typescript-eslint/ban-ts-comment +// @ts-ignore +jest.unstable_mockModule('./bytesCompare', () => ({ + bytesCompare: jest.fn(), +})); + +const { bytesCompare } = await import('./bytesCompare'); +const { compareTransferableOutputs } = await import('./sort'); + +describe('compareTransferableOutputs', () => { + const avmCodec = testCodec(); + const pvmCodec = testPVMCodec(); + + beforeEach(() => { + jest.restoreAllMocks(); + (bytesCompare as jest.Mock).mockReturnValueOnce(-1); + }); + + it('sorts transferable outputs correctly', () => { + const transferableOutput1 = getTransferableOutForTest(1n); + const transferableOutput2 = getTransferableOutForTest(2n); + + const result = compareTransferableOutputs( + transferableOutput1, + transferableOutput2, + ); + + expect(result).toEqual(-1); + expect(bytesCompare).toBeCalledTimes(1); + expect(bytesCompare).toBeCalledWith( + transferableOutput1.toBytes(avmCodec), + transferableOutput2.toBytes(avmCodec), + ); + }); + + it('sorts stakeable locked outs correctly', () => { + const transferableOutput1 = getStakeableLockedTransferableOutForTest( + 1n, + 100n, + ); + const transferableOutput2 = getStakeableLockedTransferableOutForTest( + 2n, + 200n, + ); + + const result = compareTransferableOutputs( + transferableOutput1, + transferableOutput2, + ); + + expect(result).toEqual(-1); + expect(bytesCompare).toBeCalledWith( + transferableOutput1.toBytes(pvmCodec), + transferableOutput2.toBytes(pvmCodec), + ); + }); + + it('sorts transferable outputs and stakeable locked outs correctly', () => { + const transferableOutput1 = getTransferableOutForTest(1n); + const transferableOutput2 = getStakeableLockedTransferableOutForTest( + 1n, + 100n, + ); + + const result = compareTransferableOutputs( + transferableOutput1, + transferableOutput2, + ); + + expect(result).toEqual(-1); + expect(bytesCompare).toBeCalledWith( + transferableOutput1.toBytes(avmCodec), + transferableOutput2.toBytes(pvmCodec), + ); + }); +}); diff --git a/src/utils/sort.ts b/src/utils/sort.ts new file mode 100644 index 000000000..585c8d89a --- /dev/null +++ b/src/utils/sort.ts @@ -0,0 +1,37 @@ +import { getPVMManager } from '../serializable/pvm/codec'; +import type { TransferableOutput } from '../serializable/avax'; +import { getAVMManager } from '../serializable/avm/codec'; +import type { Output } from '../serializable/evm'; +import { Id } from '../serializable/fxs/common'; +import { bytesCompare } from './bytesCompare'; +import { isStakeableLockOut } from './typeGuards'; + +export const compareTransferableOutputs = ( + output1: TransferableOutput, + output2: TransferableOutput, +): number => { + const assetIdRes = Id.compare(output1.assetId, output2.assetId); + if (assetIdRes !== 0) { + return assetIdRes; + } + + const pvmOutputTypes = [isStakeableLockOut]; + const avmCodec = getAVMManager().getDefaultCodec(); + const pvmCodec = getPVMManager().getDefaultCodec(); + + const codec1 = pvmOutputTypes.some((checker) => checker(output1.output)) + ? pvmCodec + : avmCodec; + const codec2 = pvmOutputTypes.some((checker) => checker(output2.output)) + ? pvmCodec + : avmCodec; + + return bytesCompare(output1.toBytes(codec1), output2.toBytes(codec2)); +}; + +export const compareEVMOutputs = (a: Output, b: Output) => { + if (a.address.value() === b.address.value()) { + return bytesCompare(a.assetId.toBytes(), b.assetId.toBytes()); + } + return a.address.value().localeCompare(b.address.value()); +}; diff --git a/src/utils/struct.spec.ts b/src/utils/struct.spec.ts new file mode 100644 index 000000000..c1773ee7c --- /dev/null +++ b/src/utils/struct.spec.ts @@ -0,0 +1,44 @@ +import { TransferableOutput } from '../serializable/avax'; +import { transferableOutput, transferableOutputBytes } from '../fixtures/avax'; +import { testCodec } from '../fixtures/codec'; +import { + mintOutput, + mintOutputBytes, + transferOutput, + transferOutputBytes, +} from '../fixtures/secp256k1'; +import { MintOutput, TransferOutput } from '../serializable/fxs/secp256k1'; +import { concatBytes } from './buffer'; +import { unpack } from './struct'; + +describe('structSimple', () => { + it('unpackSimple', () => { + const input: Uint8Array = concatBytes( + transferOutputBytes(), + mintOutputBytes(), + ); + + const outputArray = [TransferOutput, MintOutput] as const; + const [tsOutput, mntOutput, remaining] = unpack(input, outputArray); + expect(tsOutput).toEqual(transferOutput()); + expect(mntOutput).toEqual(mintOutput()); + expect(remaining).toEqual(new Uint8Array()); + }); + + it('unpackSimple with codec', () => { + const input: Uint8Array = concatBytes( + transferableOutputBytes(), + mintOutputBytes(), + ); + + const outputArray = [TransferableOutput, MintOutput] as const; + const [tsOutput, mntOutput, remaining] = unpack( + input, + outputArray, + testCodec(), + ); + expect(tsOutput).toEqual(transferableOutput()); + expect(mntOutput).toEqual(mintOutput()); + expect(remaining).toEqual(new Uint8Array()); + }); +}); diff --git a/src/utils/struct.ts b/src/utils/struct.ts new file mode 100644 index 000000000..fd78338ba --- /dev/null +++ b/src/utils/struct.ts @@ -0,0 +1,59 @@ +import type { Codec } from '../serializable/codec'; +import type { Serializable } from '../serializable/common/types'; +import { concatBytes } from './buffer'; +import { packList } from './serializeList'; + +export type FromBytesReturn = T extends { + fromBytes: (buff: Uint8Array, codec?: Codec) => [infer rType, Uint8Array]; +} + ? rType + : T extends { + fromBytes: (buff: Uint8Array, codec: Codec) => [infer rType, Uint8Array]; + } + ? rType + : never; + +export type ReturnTypes = { + [i in keyof T]: FromBytesReturn; +}; + +export function unpack( + buffer: Uint8Array, + sers: O, + codec?: Codec, +): [...ReturnTypes, Uint8Array] { + const unpacked = sers.map((ser) => { + let res: ReturnType[0]; + + if (!buffer.length) { + throw new Error('not enough bytes'); + } + + [res, buffer] = ser.fromBytes(buffer, codec); + + return res; + }); + + return [...unpacked, buffer] as unknown as [...ReturnTypes, Uint8Array]; +} + +export function pack( + serializables: (Serializable | Serializable[])[], + codec: Codec, +) { + return concatBytes( + ...serializables.map((ser) => { + if (Array.isArray(ser)) { + return packList(ser, codec); + } + return ser.toBytes(codec); + }), + ); +} + +export function packSwitched( + codec: Codec, + ...serializables: (Serializable | Serializable[])[] +) { + return pack(serializables, codec); +} diff --git a/src/utils/transferableAmounts.ts b/src/utils/transferableAmounts.ts new file mode 100644 index 000000000..d3d6a007c --- /dev/null +++ b/src/utils/transferableAmounts.ts @@ -0,0 +1,13 @@ +import type { Amounter } from '../serializable/common/types'; + +export interface TransferableSummable extends Amounter { + getAssetId(): string; +} + +export const transferableAmounts = (transferables: TransferableSummable[]) => { + return transferables.reduce((agg, transferable) => { + agg[transferable.getAssetId()] = agg[transferable.getAssetId()] ?? 0n; + agg[transferable.getAssetId()] += transferable.amount(); + return agg; + }, {} as Record); +}; diff --git a/src/utils/typeGuards.ts b/src/utils/typeGuards.ts new file mode 100644 index 000000000..357186a56 --- /dev/null +++ b/src/utils/typeGuards.ts @@ -0,0 +1,27 @@ +import type { Serializable } from '../serializable/common/types'; +import type { TransferInput } from '../serializable/fxs/secp256k1'; +import type { OutputOwners } from '../serializable/fxs/secp256k1/outputOwners'; +import type { TransferOutput } from '../serializable/fxs/secp256k1/transferOutput'; +import type { StakeableLockIn } from '../serializable/pvm/stakeableLockIn'; +import type { StakeableLockOut } from '../serializable/pvm/stakeableLockOut'; +import { TypeSymbols } from '../serializable/constants'; + +export function isTransferOut(out: Serializable): out is TransferOutput { + return out._type === TypeSymbols.TransferOutput; +} + +export function isStakeableLockOut(out: Serializable): out is StakeableLockOut { + return out._type === TypeSymbols.StakeableLockOut; +} + +export function isRewardsOwner(out: Serializable): out is OutputOwners { + return out._type === TypeSymbols.OutputOwners; +} + +export function isStakeableLockIn(out: Serializable): out is StakeableLockIn { + return out._type === TypeSymbols.StakeableLockIn; +} + +export function isTransferInput(inp: Serializable): inp is TransferInput { + return inp._type === TypeSymbols.TransferInput; +} diff --git a/src/utils/validateBurnedAmount.test.ts b/src/utils/validateBurnedAmount.test.ts new file mode 100644 index 000000000..21b68eb75 --- /dev/null +++ b/src/utils/validateBurnedAmount.test.ts @@ -0,0 +1,542 @@ +import { testAddress1, testAddress2, testEthAddress1 } from '../fixtures/vms'; +import { testContext } from '../fixtures/context'; +import { newExportTxFromBaseFee, newImportTxFromBaseFee } from '../vms/evm'; +import { Utxo } from '../serializable/avax/utxo'; +import { utxoId } from '../fixtures/avax'; +import { Address, Id } from '../serializable/fxs/common'; +import { OutputOwners, TransferOutput } from '../serializable/fxs/secp256k1'; +import { BigIntPr, Int } from '../serializable/primitives'; +import { + newBaseTx as avmBaseTx, + newExportTx as avmExportTx, + newImportTx as avmImportTx, +} from '../vms/avm'; +import { + newBaseTx as pvmBaseTx, + newExportTx as pvmExportTx, + newImportTx as pvmImportTx, + newAddValidatorTx, + newAddDelegatorTx, + newCreateSubnetTx, + newCreateBlockchainTx, + newAddSubnetValidatorTx, + newTransformSubnetTx, + newAddPermissionlessValidatorTx, + newAddPermissionlessDelegatorTx, + newRemoveSubnetValidatorTx, + newTransferSubnetOwnershipTx, +} from '../vms/pvm'; +import { TransferableOutput } from '../serializable'; +import { nodeId } from '../fixtures/common'; +import { validateBurnedAmount } from './validateBurnedAmount'; +import { testSubnetId } from '../fixtures/transactions'; +import { PrimaryNetworkID } from '../constants/networkIDs'; +import { blsPublicKeyBytes, blsSignatureBytes } from '../fixtures/primitives'; + +const utxoMock = new Utxo( + utxoId(), + Id.fromString(testContext.avaxAssetID), + new TransferOutput( + new BigIntPr(1000000000000n), + new OutputOwners(new BigIntPr(0n), new Int(1), [ + Address.fromBytes(testAddress1)[0], + ]), + ), +); + +const outputMock = new TransferableOutput( + Id.fromString(testContext.avaxAssetID), + new TransferOutput( + new BigIntPr(100000000n), + new OutputOwners(new BigIntPr(0n), new Int(1), [ + Address.fromBytes(testAddress2)[0], + ]), + ), +); + +describe('validateBurnedAmount', () => { + describe('missing burned amount', () => { + it('calculates the burned amount', () => { + const unsignedTx = avmBaseTx( + testContext, + [testAddress1], + [utxoMock], + [outputMock], + ); + + const result = validateBurnedAmount({ + unsignedTx, + context: testContext, + }); + + expect(result).toStrictEqual({ + isValid: true, + txFee: testContext.baseTxFee, + }); + }); + }); + + describe('export from C', () => { + const unsignedTx = newExportTxFromBaseFee( + testContext, + 25n, + 1000000000n, + 'X', + testEthAddress1, + [testAddress1], + 1n, + ); + + it('throws if fee data is missing', () => { + expect(() => + validateBurnedAmount({ + unsignedTx, + context: testContext, + burnedAmount: (280750n * 75n) / 100n, // 25% lower + }), + ).toThrowError('missing evm fee data'); + + expect(() => + validateBurnedAmount({ + unsignedTx, + context: testContext, + burnedAmount: (280750n * 75n) / 100n, // 25% lower + evmBaseFee: 25n, + }), + ).toThrowError('missing evm fee data'); + }); + + it('throws if evmFeeTolerance is incorrect', () => { + expect(() => + validateBurnedAmount({ + unsignedTx, + context: testContext, + burnedAmount: (280750n * 75n) / 100n, // 25% lower, + evmBaseFee: 25n, + evmFeeTolerance: 0.5, + }), + ).toThrowError('evmFeeTolerance must be [1,100]'); + + expect(() => + validateBurnedAmount({ + unsignedTx, + context: testContext, + burnedAmount: (280750n * 75n) / 100n, // 25% lower, + evmBaseFee: 25n, + evmFeeTolerance: 101, + }), + ).toThrowError('evmFeeTolerance must be [1,100]'); + }); + + it('returns true if burned amount is in the tolerance range', () => { + const resultLower = validateBurnedAmount({ + unsignedTx, + context: testContext, + burnedAmount: (280750n * 75n) / 100n, // 25% lower + evmBaseFee: 25n, + evmFeeTolerance: 50.9, + }); + + const resultHigher = validateBurnedAmount({ + unsignedTx, + context: testContext, + burnedAmount: (280750n * 125n) / 100n, // 25% higher + evmBaseFee: 25n, + evmFeeTolerance: 50.9, + }); + + expect(resultLower).toStrictEqual({ + isValid: true, + txFee: (280750n * 75n) / 100n, + }); + expect(resultHigher).toStrictEqual({ + isValid: true, + txFee: (280750n * 125n) / 100n, + }); + }); + + it('returns false if burned amount is not in the tolerance range', () => { + const resultLower = validateBurnedAmount({ + unsignedTx, + context: testContext, + burnedAmount: (280750n * 49n) / 100n, // 51% lower + evmBaseFee: 25n, + evmFeeTolerance: 50.9, + }); + + const resultHigher = validateBurnedAmount({ + unsignedTx, + context: testContext, + burnedAmount: (280750n * 151n) / 100n, // 51% higher + evmBaseFee: 25n, + evmFeeTolerance: 50.9, + }); + + expect(resultLower).toStrictEqual({ + isValid: false, + txFee: (280750n * 49n) / 100n, + }); + expect(resultHigher).toStrictEqual({ + isValid: false, + txFee: (280750n * 151n) / 100n, + }); + }); + }); + + describe('import to C', () => { + const unsignedTx = newImportTxFromBaseFee( + testContext, + testEthAddress1, + [testAddress1], + [utxoMock], + 'X', + 25n, + ); + + it('returns true if burned amount is in the tolerance range', () => { + const resultLower = validateBurnedAmount({ + unsignedTx, + context: testContext, + burnedAmount: (280750n * 75n) / 100n, // 25% lower + evmBaseFee: 25n, + evmFeeTolerance: 50.9, + }); + + const resultHigher = validateBurnedAmount({ + unsignedTx, + context: testContext, + burnedAmount: (280750n * 125n) / 100n, // 25% higher + evmBaseFee: 25n, + evmFeeTolerance: 50.9, + }); + + expect(resultLower).toStrictEqual({ + isValid: true, + txFee: (280750n * 75n) / 100n, + }); + expect(resultHigher).toStrictEqual({ + isValid: true, + txFee: (280750n * 125n) / 100n, + }); + }); + + it('returns false if burned amount is not in the tolerance range', () => { + const resultLower = validateBurnedAmount({ + unsignedTx, + context: testContext, + burnedAmount: (280750n * 49n) / 100n, // 51% lower + evmBaseFee: 25n, + evmFeeTolerance: 50.9, + }); + + const resultHigher = validateBurnedAmount({ + unsignedTx, + context: testContext, + burnedAmount: (280750n * 151n) / 100n, // 51% higher + evmBaseFee: 25n, + evmFeeTolerance: 50.9, + }); + + expect(resultLower).toStrictEqual({ + isValid: false, + txFee: (280750n * 49n) / 100n, + }); + expect(resultHigher).toStrictEqual({ + isValid: false, + txFee: (280750n * 151n) / 100n, + }); + }); + }); + + const testData = [ + { + name: 'base tx on X', + unsignedTx: avmBaseTx( + testContext, + [testAddress1], + [utxoMock], + [outputMock], + ), + correctBurnedAmount: testContext.baseTxFee, + }, + { + name: 'export from X', + unsignedTx: avmExportTx( + testContext, + 'P', + [testAddress1], + [utxoMock], + [outputMock], + ), + correctBurnedAmount: testContext.baseTxFee, + }, + { + name: 'import from X', + unsignedTx: avmImportTx( + testContext, + 'P', + [utxoMock], + [testAddress2], + [testAddress1], + ), + correctBurnedAmount: testContext.baseTxFee, + }, + { + name: 'base tx on P', + unsignedTx: pvmBaseTx( + testContext, + [testAddress1], + [utxoMock], + [outputMock], + ), + correctBurnedAmount: testContext.baseTxFee, + }, + { + name: 'export from P', + unsignedTx: pvmExportTx( + testContext, + 'C', + [testAddress1], + [utxoMock], + [outputMock], + ), + correctBurnedAmount: testContext.baseTxFee, + }, + { + name: 'import to P', + unsignedTx: pvmImportTx( + testContext, + 'C', + [utxoMock], + [testAddress2], + [testAddress1], + ), + correctBurnedAmount: testContext.baseTxFee, + }, + { + name: 'add validator', + unsignedTx: newAddValidatorTx( + testContext, + [utxoMock], + [testAddress1], + nodeId().toString(), + 0n, + 1n, + 2n, + [testAddress1], + 3, + ), + correctBurnedAmount: testContext.addPrimaryNetworkValidatorFee, + }, + { + name: 'add delegator', + unsignedTx: newAddDelegatorTx( + testContext, + [utxoMock], + [testAddress1], + nodeId().toString(), + 0n, + 1n, + 2n, + [testAddress1], + ), + correctBurnedAmount: testContext.addPrimaryNetworkDelegatorFee, + }, + { + name: 'create subnet', + unsignedTx: newCreateSubnetTx( + testContext, + [utxoMock], + [testAddress1], + [testAddress1], + ), + correctBurnedAmount: testContext.createSubnetTxFee, + }, + { + name: 'create blockchain', + unsignedTx: newCreateBlockchainTx( + testContext, + [utxoMock], + [testAddress1], + 'subnet', + 'chain', + 'vm', + ['fx1', 'fx2'], + {}, + [0], + ), + correctBurnedAmount: testContext.createBlockchainTxFee, + }, + { + name: 'add subnet validator', + unsignedTx: newAddSubnetValidatorTx( + testContext, + [utxoMock], + [testAddress1], + nodeId().toString(), + 0n, + 1n, + 2n, + 'subnet', + [0], + ), + correctBurnedAmount: testContext.addSubnetValidatorFee, + }, + { + name: 'remove subnet validator', + unsignedTx: newRemoveSubnetValidatorTx( + testContext, + [utxoMock], + [testAddress1], + nodeId().toString(), + Id.fromHex(testSubnetId).toString(), + [0], + ), + correctBurnedAmount: testContext.baseTxFee, + }, + { + name: 'transform subnet', + unsignedTx: newTransformSubnetTx( + testContext, + [utxoMock], + [testAddress1], + Id.fromHex(testSubnetId).toString(), + '123456789ABC', + 1n, + 2n, + 3n, + 4n, + 5n, + 6n, + 1, + 2, + 3, + 4, + 5, + 6, + [0, 2], + ), + correctBurnedAmount: testContext.transformSubnetTxFee, + }, + { + name: 'add permissionless validator (primary network)', + unsignedTx: newAddPermissionlessValidatorTx( + testContext, + [utxoMock], + [testAddress1], + nodeId().toString(), + PrimaryNetworkID.toString(), + 0n, + 120n, + 1800000n, + [], + [], + 1, + {}, + 1, + 0n, + blsPublicKeyBytes(), + blsSignatureBytes(), + ), + correctBurnedAmount: testContext.addPrimaryNetworkValidatorFee, + }, + { + name: 'add permissionless validator (subnet)', + unsignedTx: newAddPermissionlessValidatorTx( + testContext, + [utxoMock], + [testAddress1], + nodeId().toString(), + Id.fromHex(testSubnetId).toString(), + 0n, + 120n, + 1800000n, + [], + [], + 1, + {}, + 1, + 0n, + blsPublicKeyBytes(), + blsSignatureBytes(), + ), + correctBurnedAmount: testContext.addSubnetValidatorFee, + }, + { + name: 'add permissionless delegator (primary network)', + unsignedTx: newAddPermissionlessDelegatorTx( + testContext, + [utxoMock], + [testAddress1], + nodeId().toString(), + PrimaryNetworkID.toString(), + 0n, + 120n, + 1800000n, + [], + {}, + 1, + 0n, + ), + correctBurnedAmount: testContext.addPrimaryNetworkDelegatorFee, + }, + { + name: 'add permissionless delegator (subnet)', + unsignedTx: newAddPermissionlessDelegatorTx( + testContext, + [utxoMock], + [testAddress1], + nodeId().toString(), + Id.fromHex(testSubnetId).toString(), + 0n, + 120n, + 1800000n, + [], + {}, + 1, + 0n, + ), + correctBurnedAmount: testContext.addSubnetDelegatorFee, + }, + { + name: 'transfer subnet ownership', + unsignedTx: newTransferSubnetOwnershipTx( + testContext, + [utxoMock], + [testAddress1], + Id.fromHex(testSubnetId).toString(), + [0, 2], + [testAddress2], + ), + correctBurnedAmount: testContext.baseTxFee, + }, + ]; + + describe.each(testData)('$name', ({ unsignedTx, correctBurnedAmount }) => { + it('returns true if burned amount is correct', () => { + const result = validateBurnedAmount({ + unsignedTx, + context: testContext, + burnedAmount: correctBurnedAmount, + }); + + expect(result).toStrictEqual({ + isValid: true, + txFee: correctBurnedAmount, + }); + }); + + it('returns false if burned amount is not correct', () => { + const result = validateBurnedAmount({ + unsignedTx, + context: testContext, + burnedAmount: correctBurnedAmount - 1n, + }); + + expect(result).toStrictEqual({ + isValid: false, + txFee: correctBurnedAmount, + }); + }); + }); +}); diff --git a/src/utils/validateBurnedAmount.ts b/src/utils/validateBurnedAmount.ts new file mode 100644 index 000000000..f162e6e55 --- /dev/null +++ b/src/utils/validateBurnedAmount.ts @@ -0,0 +1,136 @@ +import type { Context } from '../vms/context/model'; +import { + isAddDelegatorTx, + isAddPermissionlessDelegatorTx, + isAddPermissionlessValidatorTx, + isAddSubnetValidatorTx, + isAddValidatorTx, + isCreateChainTx, + isCreateSubnetTx, + isPvmBaseTx, + isExportTx as isPvmExportTx, + isImportTx as isPvmImportTx, + isRemoveSubnetValidatorTx, + isTransferSubnetOwnershipTx, + isTransformSubnetTx, +} from '../serializable/pvm'; +import type { Transaction, UnsignedTx } from '../vms/common'; +import type { EVMTx } from '../serializable/evm'; +import { isImportExportTx as isEvmImportExportTx } from '../serializable/evm'; +import { costCorethTx } from './costs'; +import { + isAvmBaseTx, + isExportTx as isAvmExportTx, + isImportTx as isAvmImportTx, +} from '../serializable/avm'; +import { getBurnedAmountByTx } from './getBurnedAmountByTx'; +import type { AvaxTx } from '../serializable/avax'; +import { PrimaryNetworkID } from '../constants/networkIDs'; + +const _getBurnedAmount = (tx: Transaction, context: Context) => { + const burnedAmounts = getBurnedAmountByTx(tx as AvaxTx | EVMTx); + return burnedAmounts.get(context.avaxAssetID) ?? 0n; +}; + +export const validateBurnedAmount = ({ + unsignedTx, + context, + burnedAmount, + evmBaseFee, + evmFeeTolerance, +}: { + unsignedTx: UnsignedTx; + context: Context; + burnedAmount?: bigint; + evmBaseFee?: bigint; // fetched from the network and converted into nAvax (https://docs.avax.network/quickstart/transaction-fees#c-chain-fees) + evmFeeTolerance?: number; // tolerance percentage range where the burned amount is considered valid. e.g.: with evmFeeTolerance = 20% -> (evmBaseFee * 0.8 <= burnedAmount <= evmBaseFee * 1.2) +}): { isValid: boolean; txFee: bigint } => { + const tx = unsignedTx.getTx(); + const burned = burnedAmount ?? _getBurnedAmount(tx, context); + + const validate = (expectedAmount: bigint) => ({ + isValid: burned === expectedAmount, + txFee: expectedAmount, + }); + + if (isEvmImportExportTx(tx)) { + if (!evmBaseFee || !evmFeeTolerance) { + throw new Error('missing evm fee data'); + } + + const feeToleranceInt = Math.floor(evmFeeTolerance); + + if (feeToleranceInt < 1 || feeToleranceInt > 100) { + throw new Error('evmFeeTolerance must be [1,100]'); + } + + const feeAmount = evmBaseFee * costCorethTx(unsignedTx); + const min = (feeAmount * (100n - BigInt(feeToleranceInt))) / 100n; + const max = (feeAmount * (100n + BigInt(feeToleranceInt))) / 100n; + + return { + isValid: burned >= min && burned <= max, + txFee: burned, + }; + } + + if (isAddValidatorTx(tx)) { + return validate(context.addPrimaryNetworkValidatorFee); + } + + if (isAddDelegatorTx(tx)) { + return validate(context.addPrimaryNetworkDelegatorFee); + } + + if (isCreateSubnetTx(tx)) { + return validate(context.createSubnetTxFee); + } + + if (isCreateChainTx(tx)) { + return validate(context.createBlockchainTxFee); + } + + if (isAddSubnetValidatorTx(tx)) { + return validate(context.addSubnetValidatorFee); + } + + if (isTransformSubnetTx(tx)) { + return validate(context.transformSubnetTxFee); + } + + if (isAddPermissionlessValidatorTx(tx)) { + const isPrimarySubnet = + tx.subnetValidator.subnetId.toString() === PrimaryNetworkID.toString(); + + return validate( + isPrimarySubnet + ? context.addPrimaryNetworkValidatorFee + : context.addSubnetValidatorFee, + ); + } + + if (isAddPermissionlessDelegatorTx(tx)) { + const isPrimarySubnet = + tx.subnetValidator.subnetId.toString() === PrimaryNetworkID.toString(); + return validate( + isPrimarySubnet + ? context.addPrimaryNetworkDelegatorFee + : context.addSubnetDelegatorFee, + ); + } + + if ( + isAvmBaseTx(tx) || + isPvmBaseTx(tx) || + isAvmExportTx(tx) || + isAvmImportTx(tx) || + isPvmExportTx(tx) || + isPvmImportTx(tx) || + isRemoveSubnetValidatorTx(tx) || + isTransferSubnetOwnershipTx(tx) + ) { + return validate(context.baseTxFee); + } + + throw new Error(`tx type is not supported`); +}; diff --git a/src/vms/avm/api.ts b/src/vms/avm/api.ts new file mode 100644 index 000000000..dab7d1c2d --- /dev/null +++ b/src/vms/avm/api.ts @@ -0,0 +1,36 @@ +import { getAVMManager } from '../../serializable/avm/codec'; +import { AvaxApi } from '../common/avaxApi'; +import type { + BuildGenesisParams, + BuildGenesisResponse, + GetAllBalancesParams, + GetAllBalancesResponse, +} from './models'; + +export class AVMApi extends AvaxApi { + constructor(baseURL?: string) { + super(baseURL, '/ext/bc/X', 'avm', getAVMManager()); + } + + /** + * Given a JSON representation of this Virtual Machine’s genesis state, create the byte representation of that state. + * + * @param genesisData The blockchain's genesis data object + * + * @returns Promise of a string of bytes + */ + buildGenesis = async ( + params: BuildGenesisParams, + ): Promise => { + return await this.callRpc('buildGenesis', params); + }; + + getAllBalances( + getAllBalancesParams: GetAllBalancesParams, + ): Promise { + return this.callRpc( + 'getAllBalances', + getAllBalancesParams, + ); + } +} diff --git a/src/vms/avm/builder.spec.ts b/src/vms/avm/builder.spec.ts new file mode 100644 index 000000000..bd34f527c --- /dev/null +++ b/src/vms/avm/builder.spec.ts @@ -0,0 +1,189 @@ +import { testContext } from '../../fixtures/context'; +import { + testAvaxAssetID, + testOwnerXAddress, + testUtxos, +} from '../../fixtures/transactions'; +import { + TransferableInput, + TransferableOutput, + UTXOID, +} from '../../serializable/avax'; +import { Utxo } from '../../serializable/avax/utxo'; +import type { BaseTx, ExportTx, ImportTx } from '../../serializable/avm'; +import { Id } from '../../serializable/fxs/common'; +import { + Input, + OutputOwners, + TransferInput, + TransferOutput, +} from '../../serializable/fxs/secp256k1'; +import { BigIntPr, Int } from '../../serializable/primitives'; +import { hexToBuffer } from '../../utils'; +import { newExportTx, newImportTx } from '../pvm'; +import { newBaseTx } from './builder'; + +describe('AVMBuilder', () => { + let utxos: Utxo[]; + beforeEach(() => { + utxos = testUtxos(); + }); + it('importTx', async () => { + const toAddress = hexToBuffer('0x5432112345123451234512'); + const tx = newImportTx( + testContext, + testContext.cBlockchainID, + utxos, + [toAddress], + [testOwnerXAddress.toBytes()], + ); + + const importTx = tx.getTx() as ImportTx; + + expect(importTx.ins).toHaveLength(1); + expect(importTx.ins[0].assetId).toEqual(testAvaxAssetID); + expect(Number(importTx.ins[0].amount())).toEqual(50 * 1e9); + expect(importTx.ins[0].utxoID.ID()).toEqual(utxos[2].ID()); + }); + + it('importTx Low amt', async () => { + const toAddress = hexToBuffer('0x5432112345123451234512'); + utxos[2] = new Utxo( + new UTXOID(Id.fromHex('0x1234512345123451234516'), new Int(0)), + testAvaxAssetID, + new TransferOutput( + new BigIntPr(BigInt(50 * 1e5)), + OutputOwners.fromNative([testOwnerXAddress.toBytes()]), + ), + ); + + const tx = newImportTx( + testContext, + testContext.cBlockchainID, + utxos, + [toAddress], + [testOwnerXAddress.toBytes()], + ); + + const importTx = tx.getTx() as ImportTx; + + expect(importTx.ins).toHaveLength(1); + expect(importTx.ins[0].assetId).toEqual(testAvaxAssetID); + expect(Number(importTx.ins[0].amount())).toEqual(50 * 1e5); + expect((importTx.baseTx.outputs as TransferableOutput[])[0].amount()).toBe( + BigInt(40 * 1e5), + ); + expect(importTx.ins[0].utxoID.ID()).toEqual(utxos[2].ID()); + }); + + it('importTx no utxos available', async () => { + const toAddress = hexToBuffer('0x5432112345123451234512'); + utxos.pop(); + + expect(() => + newImportTx( + testContext, + testContext.cBlockchainID, + utxos, + [toAddress], + [testOwnerXAddress.toBytes()], + ), + ).toThrow(); + }); + + it('exportTx', () => { + const toAddress = hexToBuffer('0x5432112345123451234512'); + const tnsOut = TransferableOutput.fromNative( + testAvaxAssetID.toString(), + BigInt(5 * 1e9), + [toAddress], + ); + const tx = newExportTx( + testContext, + testContext.cBlockchainID, + [testOwnerXAddress.toBytes()], + utxos, + [tnsOut], + ); + const exportTx = tx.getTx() as ExportTx; + expect(exportTx.outs as TransferableOutput[]).toEqual([tnsOut]); + expect(exportTx.baseTx.inputs as TransferableInput[]).toEqual([ + new TransferableInput( + utxos[2].utxoId, + testAvaxAssetID, + new TransferInput( + new BigIntPr(BigInt(50 * 1e9)), + Input.fromNative([0]), + ), + ), + ]); + + expect(exportTx.baseTx.outputs as TransferableOutput[]).toEqual([ + new TransferableOutput( + testAvaxAssetID, + new TransferOutput( + new BigIntPr(44999000000n), + OutputOwners.fromNative([testOwnerXAddress.toBytes()]), + ), + ), + ]); + }); + + it('exportTx', () => { + const toAddress = hexToBuffer('0x5432112345123451234512'); + const tnsOut = TransferableOutput.fromNative( + testAvaxAssetID.toString(), + BigInt(5 * 1e9), + [toAddress], + ); + utxos.pop(); + expect(() => + newExportTx( + testContext, + testContext.cBlockchainID, + [testOwnerXAddress.toBytes()], + utxos, + [tnsOut], + ), + ).toThrow(); + }); + + it('baseTx', () => { + const toAddress = hexToBuffer('0x5432112345123451234512'); + const tnsOut = TransferableOutput.fromNative( + testAvaxAssetID.toString(), + BigInt(1 * 1e9), + [toAddress], + ); + const tx = newBaseTx(testContext, [testOwnerXAddress.toBytes()], utxos, [ + tnsOut, + ]); + const { + baseTx: { inputs, outputs }, + } = tx.getTx() as BaseTx; + + expect(outputs.length).toEqual(2); + expect(outputs as TransferableOutput[]).toEqual([ + tnsOut, + new TransferableOutput( + testAvaxAssetID, + new TransferOutput( + new BigIntPr(48999000000n), // input - amount sent - fee + OutputOwners.fromNative([testOwnerXAddress.toBytes()]), + ), + ), + ]); + + expect(inputs.length).toEqual(1); + expect(inputs as TransferableInput[]).toEqual([ + new TransferableInput( + utxos[2].utxoId, + testAvaxAssetID, + new TransferInput( + new BigIntPr(BigInt(50 * 1e9)), + Input.fromNative([0]), + ), + ), + ]); + }); +}); diff --git a/src/vms/avm/builder.ts b/src/vms/avm/builder.ts new file mode 100644 index 000000000..be2872fb1 --- /dev/null +++ b/src/vms/avm/builder.ts @@ -0,0 +1,269 @@ +import { + BaseTx as AvaxBaseTx, + TransferableInput, + TransferableOutput, +} from '../../serializable/avax'; +import type { Utxo } from '../../serializable/avax/utxo'; +import { ExportTx, ImportTx } from '../../serializable/avm'; +import { Id } from '../../serializable/fxs/common'; +import { addressesFromBytes } from '../../utils'; +import { AddressMaps } from '../../utils/addressMap'; +import { getImportedInputsFromUtxos } from '../../utils/builderUtils'; +import { compareTransferableOutputs } from '../../utils/sort'; +import { transferableAmounts } from '../../utils/transferableAmounts'; +import { defaultSpendOptions } from '../common/defaultSpendOptions'; +import type { SpendOptions } from '../common/models'; +import { UnsignedTx } from '../common/unsignedTx'; +import type { Context } from '../context/model'; +import { BaseTx } from '../../serializable/avm/baseTx'; +import type { UTXOCalculationResult } from '../utils/calculateSpend'; +import { calculateUTXOSpend } from '../utils/calculateSpend'; +import { useAvmAndCorethUTXOs } from './utxoCalculationFns'; +import { baseTxUnsafe } from '../common'; + +/** + * + * @param sourceChainId id of the chain to import from + * @param utxos list of utxos + * @param toAddresses addresses to import the tx + * @param fromAddressesBytes used to filter UTXOs + * @param options used to filter UTXOs + * @param threshold number of signers to put on the resulting utxo + * @param locktime time the resulting utxo unlocks + * @returns + */ +export function newImportTx( + context: Context, + sourceChainId: string, + utxos: Utxo[], + toAddresses: Uint8Array[], + fromAddressesBytes: Uint8Array[], + options?: SpendOptions, + threshold = 1, + locktime = 0n, +) { + const fromAddresses = addressesFromBytes(fromAddressesBytes); + const defaultedOptions = defaultSpendOptions(fromAddressesBytes, options); + const { importedAmounts, importedInputs, inputUTXOs } = + getImportedInputsFromUtxos( + utxos, + fromAddressesBytes, + defaultedOptions.minIssuanceTime, + ); + + if (!importedInputs.length) { + throw new Error('no UTXOs available to import'); + } + + importedInputs.sort(TransferableInput.compare); + const addressMaps = AddressMaps.fromTransferableInputs( + importedInputs, + utxos, + defaultedOptions.minIssuanceTime, + fromAddressesBytes, + ); + const importedAvax = importedAmounts[context.avaxAssetID] ?? 0n; + + let inputOutputs: UTXOCalculationResult = { + inputs: [], + inputUTXOs: [], + stakeOutputs: [], + changeOutputs: [], + addressMaps: new AddressMaps(), + }; + + const txFee = context.baseTxFee; + const avaxAssetID = context.avaxAssetID; + + if (importedAvax > txFee) { + importedAmounts[avaxAssetID] -= txFee; + } else { + if (importedAvax < txFee) { + const toBurn = new Map([ + [avaxAssetID, txFee - importedAvax], + ]); + + inputOutputs = calculateUTXOSpend( + toBurn, + undefined, + utxos, + fromAddresses, + defaultedOptions, + [useAvmAndCorethUTXOs], + ); + } + delete importedAmounts[avaxAssetID]; + } + + inputUTXOs.push(...(inputOutputs.inputUTXOs || [])); + addressMaps.merge(inputOutputs.addressMaps || new AddressMaps()); + + Object.entries(importedAmounts).forEach(([assetID, amount]) => { + inputOutputs.changeOutputs.push( + TransferableOutput.fromNative( + assetID, + amount, + toAddresses, + locktime, + threshold, + ), + ); + }); + + return new UnsignedTx( + new ImportTx( + AvaxBaseTx.fromNative( + context.networkID, + context.xBlockchainID, + inputOutputs.changeOutputs || [], + inputOutputs.inputs || [], + defaultedOptions.memo, + ), + Id.fromString(sourceChainId), + importedInputs, + ), + inputUTXOs, + addressMaps, + ); +} + +/** + * Format export Tx given a set of utxos. The priority is determined by the order of the utxo + * array. Fee is automatically added + * @param destinationChain - id of the destination chain + * @param fromAddresses - used for selecting which utxos are signable + * @param utxoSet - list of utxos to spend from + * @param outputs - the final desired output + * @param options - see SpendingOptions + */ +export function newExportTx( + context: Context, + destinationChain: string, + fromAddressesBytes: Uint8Array[], + utxoSet: Utxo[], + outputs: TransferableOutput[], + options?: SpendOptions, +) { + const fromAddresses = addressesFromBytes(fromAddressesBytes); + const defaultedOptions = defaultSpendOptions(fromAddressesBytes, options); + const toBurn = new Map([ + [context.avaxAssetID, context.baseTxFee], + ]); + + outputs.forEach((out) => { + const assetId = out.assetId.value(); + toBurn.set(assetId, (toBurn.get(assetId) || 0n) + out.output.amount()); + }); + + const { inputs, changeOutputs, inputUTXOs, addressMaps } = calculateUTXOSpend( + toBurn, + undefined, + utxoSet, + fromAddresses, + defaultedOptions, + [useAvmAndCorethUTXOs], + ); + outputs.sort(compareTransferableOutputs); + return exportTxUnsafe( + context, + outputs, + changeOutputs, + inputs, + destinationChain, + defaultedOptions.memo, + inputUTXOs, + addressMaps, + ); +} + +/** + * Format base Tx given a set of utxos. The priority is determined by the order of the utxo + * array. Fee is automatically added + * @param fromAddresses - used for selecting which utxos are signable + * @param utxoSet - list of utxos to spend from + * @param outputs - the desired output (change outputs will be added to them automatically) + * @param options - see SpendingOptions + */ +export function newBaseTx( + context: Context, + fromAddressesBytes: Uint8Array[], + utxoSet: Utxo[], + outputs: TransferableOutput[], + options?: SpendOptions, +) { + const fromAddresses = addressesFromBytes(fromAddressesBytes); + const defaultedOptions = defaultSpendOptions(fromAddressesBytes, options); + const toBurn = new Map([ + [context.avaxAssetID, context.baseTxFee], + ]); + + outputs.forEach((out) => { + const assetId = out.assetId.value(); + toBurn.set(assetId, (toBurn.get(assetId) || 0n) + out.output.amount()); + }); + + const { inputs, inputUTXOs, changeOutputs, addressMaps } = calculateUTXOSpend( + toBurn, + undefined, + utxoSet, + fromAddresses, + defaultedOptions, + [useAvmAndCorethUTXOs], + ); + + const allOutputs = [...outputs, ...changeOutputs]; + allOutputs.sort(compareTransferableOutputs); + + return new UnsignedTx( + new BaseTx( + baseTxUnsafe(context, allOutputs, inputs, defaultedOptions.memo), + ), + inputUTXOs, + addressMaps, + ); +} + +/** + * Format export Tx based on inputs directly. extra inputs amounts are burned + * @param outputs - the total output for the tx + * @param changeOutputs - the output representing the remaining amounts from each input + * @param inputs - the inputs of the tx + * @param destinationChain - id of the destination chain + * @param memo - optional memo + */ +const exportTxUnsafe = ( + context: Context, + outputs: TransferableOutput[], + changeOutputs: TransferableOutput[], + inputs: TransferableInput[], + destinationChain: string, + memo: Uint8Array, + inputUtxos: Utxo[], + sigMappings: AddressMaps, +) => { + outputs.sort(compareTransferableOutputs); + + const outputAmts = transferableAmounts([...outputs, ...changeOutputs]); + + const inputAmts = transferableAmounts(inputs); + + // check outputs and change outputs are all covered by inputs given + // extra inputs are burned and is allowed + const allOutputsCovered = Object.entries(outputAmts).every( + ([assetID, amount]) => inputAmts[assetID] && inputAmts[assetID] >= amount, + ); + + if (!allOutputsCovered) { + throw new Error('Not enough inputs to cover the outputs'); + } + + return new UnsignedTx( + new ExportTx( + baseTxUnsafe(context, changeOutputs, inputs, memo), + Id.fromString(destinationChain), + outputs, + ), + inputUtxos, + sigMappings, + ); +}; diff --git a/src/vms/avm/index.ts b/src/vms/avm/index.ts new file mode 100644 index 000000000..7bf38105f --- /dev/null +++ b/src/vms/avm/index.ts @@ -0,0 +1,3 @@ +export * from './api'; +export * from './builder'; +export * from './models'; diff --git a/src/vms/avm/models.ts b/src/vms/avm/models.ts new file mode 100644 index 000000000..888397c24 --- /dev/null +++ b/src/vms/avm/models.ts @@ -0,0 +1,37 @@ +export interface BuildGenesisParams { + genesisData: object; +} + +export interface BuildGenesisResponse { + bytes: string; + encoding: string; +} + +export interface GetAllBalancesParams { + address: string; +} + +export interface GetAllBalancesResponse { + balances: { asset: string; balance: number }[]; +} + +export interface GetBalanceParams { + address: string; + assetID: string; +} + +export interface GetBalanceResponse { + balance: number; +} + +export interface GetAddressTxsParams { + address: string; + cursor?: bigint; + assetID: string; + pageSize?: bigint; +} + +export interface GetAddressTxsResponse { + txIDs: string[]; + cursor: bigint; +} diff --git a/src/vms/avm/utxoCalculationFns/index.ts b/src/vms/avm/utxoCalculationFns/index.ts new file mode 100644 index 000000000..c272bb8de --- /dev/null +++ b/src/vms/avm/utxoCalculationFns/index.ts @@ -0,0 +1 @@ +export * from './useAvmAndCorethUTXOs'; diff --git a/src/vms/avm/utxoCalculationFns/useAvmAndCorethUTXOs.ts b/src/vms/avm/utxoCalculationFns/useAvmAndCorethUTXOs.ts new file mode 100644 index 000000000..f43b4cb46 --- /dev/null +++ b/src/vms/avm/utxoCalculationFns/useAvmAndCorethUTXOs.ts @@ -0,0 +1,85 @@ +import type { UTXOCalculationState } from '../../utils/calculateSpend'; +import { + TransferableInput, + TransferableOutput, +} from '../../../serializable/avax'; +import { + OutputOwners, + TransferOutput, +} from '../../../serializable/fxs/secp256k1'; +import { BigIntPr, Int } from '../../../serializable/primitives'; +import { addressesFromBytes, isTransferOut } from '../../../utils'; +import { bigIntMin } from '../../../utils/bigintMath'; +import { verifySignaturesMatch } from '../../../vms/utils/calculateSpend/utils'; + +// UTXO Spend for coreth/AVM UTXOs +export const useAvmAndCorethUTXOs = ({ + amountsToBurn, + utxos, + options, + changeOutputs, + inputUTXOs, + fromAddresses, + inputs, + ...state +}: UTXOCalculationState): UTXOCalculationState => { + const changeOwner = new OutputOwners( + new BigIntPr(0n), + new Int(options.threshold), + addressesFromBytes(options.changeAddresses), + ); + verifySignaturesMatch( + utxos + .filter((utxo) => !!amountsToBurn.get(utxo.assetId.toString())) + // We only support burning [secp256k1fx.TransferOutput]s. + .filter((utxo) => !!isTransferOut(utxo.output as TransferOutput)), + (utxo) => utxo.output as TransferOutput, + fromAddresses, + options, + ).forEach(({ sigData, data: utxo }) => { + const utxoTransferout = utxo.output as TransferOutput; + + const remainingAmountToBurn = + amountsToBurn.get(utxo.assetId.toString()) ?? 0n; + + const amountToBurn = bigIntMin( + remainingAmountToBurn, + utxoTransferout.amt.value(), + ); + // if nothing left to burn then lets skip the rest + if (!amountToBurn) return; + + amountsToBurn.set( + utxo.assetId.toString(), + remainingAmountToBurn - amountToBurn, + ); + + inputs.push( + TransferableInput.fromUtxoAndSigindicies(utxo, sigData.sigIndicies), + ); + + inputUTXOs.push(utxo); + + const remainingAmount = utxoTransferout.amt.value() - amountToBurn; + + if (remainingAmount > 0) { + changeOutputs.push( + new TransferableOutput( + utxo.assetId, + new TransferOutput(new BigIntPr(remainingAmount), changeOwner), + ), + ); + } + }); + + return { + utxos, + fromAddresses, + options, + ...state, + amountsToBurn, + inputs, + changeOutputs, + inputUTXOs, + }; +}; diff --git a/src/vms/common/apiModels.ts b/src/vms/common/apiModels.ts new file mode 100644 index 000000000..9de8f4016 --- /dev/null +++ b/src/vms/common/apiModels.ts @@ -0,0 +1,64 @@ +import type { Utxo } from '../../serializable/avax/utxo'; + +export type GetUTXOsInput = { + addresses: string[]; + limit?: number; + startIndex?: { + address: string; + utxo: string; + }; + sourceChain?: string; +}; + +export type GetUTXOsApiResp = { + numFetched: number; + utxos: string[]; + endIndex: { + address: string; + utxo: string; + }; + sourceChain?: string; + encoding: string; +}; + +export type GetUTXOResponse = Omit & { + utxos: Utxo[]; +}; + +export type GetAssetDescriptionResponse = { + assetID: string; + name: string; + symbol: string; + denomination: number; +}; + +export type AVMContext = { + readonly networkID: number; + readonly hrp: string; + readonly blockchainID: string; + readonly avaxAssetID: string; + readonly baseTxFee: bigint; + readonly createAssetTxFee: bigint; +}; + +export interface IssueTxParams { + tx: string; +} + +export interface IssueTxResponse { + txID: string; +} + +export interface GetTxParams { + txID: string; +} + +export interface GetTxStatusParams { + txID: string; + includeReason?: boolean | true; +} + +export interface GetTxStatusResponse { + status: string; + reason: string; +} diff --git a/src/vms/common/avaxApi.ts b/src/vms/common/avaxApi.ts new file mode 100644 index 000000000..6c3fdc153 --- /dev/null +++ b/src/vms/common/avaxApi.ts @@ -0,0 +1,59 @@ +/* + this class is for shared methods between avm/pvm api's +*/ + +import { SignedTx } from '../../serializable/avax'; +import { hexToBuffer } from '../../utils'; +import type { GetAddressTxsParams, GetAddressTxsResponse } from '../avm/models'; +import type { GetBalanceParams, GetBalanceResponse } from '../pvm'; +import type { GetTxServerResponse } from '../pvm/privateModels'; +import type { + GetAssetDescriptionResponse, + GetTxParams, + GetTxStatusParams, + GetTxStatusResponse, +} from './apiModels'; +import { ChainApi } from './chainAPI'; + +export class AvaxApi extends ChainApi { + getAssetDescription(assetID: string): Promise { + return this.callRpc('getAssetDescription', { + assetID, + }); + } + + getTx = async (getTxParams: GetTxParams) => { + const resp = await this.callRpc('getTx', { + ...getTxParams, + encoding: 'hex', + }); + return this.manager.unpack(hexToBuffer(resp.tx), SignedTx); + }; + + getTxJson = (getTxParams: GetTxParams) => { + return this.callRpc('getTx', { + ...getTxParams, + encoding: 'json', + }); + }; + + getTxStatus(getTxStatus: GetTxStatusParams): Promise { + return this.callRpc('getTxStatus', { + includeReason: true, + ...getTxStatus, + }); + } + + getBalance(getBalanceParams: GetBalanceParams): Promise { + return this.callRpc('getBalance', getBalanceParams); + } + + getAddressTxs( + GetAddressTxsParams: GetAddressTxsParams, + ): Promise { + return this.callRpc( + 'GetAddressTxs', + GetAddressTxsParams, + ); + } +} diff --git a/src/vms/common/baseApi.ts b/src/vms/common/baseApi.ts new file mode 100644 index 000000000..4f88b132a --- /dev/null +++ b/src/vms/common/baseApi.ts @@ -0,0 +1,40 @@ +/* + this class has methods that pertain to all api sections +*/ + +import { AVAX_PUBLIC_URL } from '../../constants/public-urls'; +import { JrpcProvider } from './rpc'; + +export abstract class Api { + protected rpcProvider: JrpcProvider; + + constructor( + baseURL: string = AVAX_PUBLIC_URL, + protected path: string, + protected base?: string, + protected fetchOptions?: RequestInit, + ) { + this.rpcProvider = new JrpcProvider(baseURL + path); + } + + setFetchOptions(options: RequestInit | undefined) { + this.fetchOptions = options; + } + + protected getMethodName = (methodName: string) => { + if (!this.base) { + return methodName; + } + return `${this.base}.${methodName}`; + }; + + protected callRpc = ( + methodName: string, + params?: Array> | Record, + ): Promise => + this.rpcProvider.callMethod( + this.getMethodName(methodName), + params, + this.fetchOptions, + ); +} diff --git a/src/vms/common/builder.ts b/src/vms/common/builder.ts new file mode 100644 index 000000000..94f9c62b7 --- /dev/null +++ b/src/vms/common/builder.ts @@ -0,0 +1,24 @@ +import type { TransferableInput, TransferableOutput } from '../../serializable'; +import type { Context } from '../context/model'; +import { BaseTx as AvaxBaseTx } from '../../serializable/avax'; + +/** + * format a BaseTx directly from inputs with no validation + * @param changeOutputs - the output representing the remaining amounts from each input + * @param inputs - the inputs of the tx + * @param memo - optional memo + */ +export const baseTxUnsafe = ( + context: Context, + changeOutputs: TransferableOutput[], + inputs: TransferableInput[], + memo: Uint8Array, +) => { + return AvaxBaseTx.fromNative( + context.networkID, + context.xBlockchainID, + changeOutputs, + inputs, + memo, + ); +}; diff --git a/src/vms/common/chainAPI.ts b/src/vms/common/chainAPI.ts new file mode 100644 index 000000000..fbea84e12 --- /dev/null +++ b/src/vms/common/chainAPI.ts @@ -0,0 +1,53 @@ +/* + this class includes methods that are shared between all three chains/vms +*/ + +import { AVAX_PUBLIC_URL } from '../../constants/public-urls'; +import type { SignedTx } from '../../serializable/avax'; +import { Utxo } from '../../serializable/avax/utxo'; +import type { Manager } from '../../serializable/codec'; +import { addChecksum } from '../../utils'; +import { bufferToHex, hexToBuffer } from '../../utils/buffer'; +import type { + GetUTXOsApiResp, + GetUTXOsInput, + IssueTxParams, + IssueTxResponse, +} from './apiModels'; +import { Api } from './baseApi'; + +export abstract class ChainApi extends Api { + constructor( + baseURL: string = AVAX_PUBLIC_URL, + protected path: string, + protected base: string, + protected manager: Manager, + ) { + super(baseURL, path, base); + } + + async getUTXOs(input: GetUTXOsInput) { + const resp = await this.callRpc('getUTXOs', { + ...input, + encoding: 'hex', + }); + const utxos = resp.utxos.map((utxoHex) => + this.manager.unpack(hexToBuffer(utxoHex), Utxo), + ); + + return { + ...resp, + utxos, + }; + } + + issueTx(issueTxParams: IssueTxParams): Promise { + return this.callRpc('issueTx', issueTxParams); + } + + issueSignedTx(tx: SignedTx): Promise { + return this.issueTx({ + tx: bufferToHex(addChecksum(tx.toBytes())), + }); + } +} diff --git a/src/vms/common/defaultSpendOptions.ts b/src/vms/common/defaultSpendOptions.ts new file mode 100644 index 000000000..e9e0a4fbd --- /dev/null +++ b/src/vms/common/defaultSpendOptions.ts @@ -0,0 +1,15 @@ +import type { SpendOptions, SpendOptionsRequired } from './models'; + +export const defaultSpendOptions = ( + fromAddress: Uint8Array[], + options?: SpendOptions, +): SpendOptionsRequired => { + return { + minIssuanceTime: BigInt(Math.floor(new Date().getTime() / 1000)), + changeAddresses: fromAddress, + threshold: 1, + memo: new Uint8Array(), + locktime: 0n, + ...options, + }; +}; diff --git a/src/vms/common/evmUnsignedTx.test.ts b/src/vms/common/evmUnsignedTx.test.ts new file mode 100644 index 000000000..59042bc39 --- /dev/null +++ b/src/vms/common/evmUnsignedTx.test.ts @@ -0,0 +1,47 @@ +import { signature } from '../../fixtures/secp256k1'; +import { exportTx } from '../../fixtures/evm'; +import { testEthAddress1, testPrivateKey1 } from '../../fixtures/vms'; +import { Address } from '../../serializable/fxs/common'; +import { sign } from '../../utils'; +import { AddressMap, AddressMaps } from '../../utils/addressMap'; +import { EVMUnsignedTx } from './evmUnsignedTx'; + +describe('EVMUnsignedTx', () => { + let addressMaps: AddressMaps; + + beforeEach(() => { + addressMaps = new AddressMaps([ + new AddressMap([[new Address(testEthAddress1), 0]]), + ]); + }); + + it('hasAllSignatures', async () => { + const tx = exportTx(); + const unsignedTx = new EVMUnsignedTx(tx, [], addressMaps); + const unsignedBytes = unsignedTx.toBytes(); + + expect(unsignedTx.hasAllSignatures()).toBeFalsy(); + + const sig = await sign(unsignedBytes, testPrivateKey1); + unsignedTx.addSignature(sig); + + expect(unsignedTx.hasAllSignatures()).toBeTruthy(); + }); + + it('serializes', () => { + const tx = exportTx(); + const unsignedTx = new EVMUnsignedTx(tx, [], addressMaps); + + unsignedTx.addSignatureAt(signature().toBytes(), 0, 0); + + const unsignedTxJson = JSON.stringify(unsignedTx); + const serializedTx = EVMUnsignedTx.fromJSON(unsignedTxJson); + + // workaround until this jest bug (https://github.com/facebook/jest/issues/12377) gets fixed + // jest fails to parse bigints in the tx.ins, so we check the tx properties' byte representation instead + expect(unsignedTx.toBytes()).toStrictEqual(serializedTx.toBytes()); + expect(unsignedTx.utxos).toStrictEqual(serializedTx.utxos); + expect(unsignedTx.addressMaps).toStrictEqual(serializedTx.addressMaps); + expect(unsignedTx.credentials).toStrictEqual(serializedTx.credentials); + }); +}); diff --git a/src/vms/common/evmUnsignedTx.ts b/src/vms/common/evmUnsignedTx.ts new file mode 100644 index 000000000..ea42e0bc3 --- /dev/null +++ b/src/vms/common/evmUnsignedTx.ts @@ -0,0 +1,17 @@ +import { publicKeyToEthAddress } from '../../utils'; +import { UnsignedTx } from './unsignedTx'; +import { Address } from '../../serializable/fxs/common'; + +export class EVMUnsignedTx extends UnsignedTx { + hasPubkey(pubKey: Uint8Array): boolean { + const addrAvax = new Address(this.publicKeyBytesToAddress(pubKey)); + const addrEVM = new Address(publicKeyToEthAddress(pubKey)); + + return this.hasAddress(addrAvax) || this.hasAddress(addrEVM); + } + + static fromJSON(jsonStr: string) { + const tx = UnsignedTx.fromJSON(jsonStr); + return new EVMUnsignedTx(tx.tx, tx.utxos, tx.addressMaps, tx.credentials); + } +} diff --git a/src/vms/common/index.ts b/src/vms/common/index.ts new file mode 100644 index 000000000..1242a8fbf --- /dev/null +++ b/src/vms/common/index.ts @@ -0,0 +1,6 @@ +export * from './apiModels'; +export * from './builder'; +export * from './models'; +export { AvaxApi } from './avaxApi'; +export { UnsignedTx } from './unsignedTx'; +export { Transaction } from './transaction'; diff --git a/src/vms/common/models.ts b/src/vms/common/models.ts new file mode 100644 index 000000000..f7b043c30 --- /dev/null +++ b/src/vms/common/models.ts @@ -0,0 +1,13 @@ +export type SpendOptions = { + minIssuanceTime?: bigint; + changeAddresses?: Uint8Array[]; + threshold?: number; + memo?: Uint8Array; + locktime?: bigint; +}; + +export type SpendOptionsRequired = Required; + +//the strign is address in hex +export type SigMapping = Map; +export type SigMappings = SigMapping[]; diff --git a/src/vms/common/rpc.ts b/src/vms/common/rpc.ts new file mode 100644 index 000000000..6b8bec901 --- /dev/null +++ b/src/vms/common/rpc.ts @@ -0,0 +1,61 @@ +export type RpcCallOptions = { + headers?: Record; +}; + +type JsonRpcSuccessResp = { + jsonrpc: string; + result: T; + id: number; + error?: undefined; +}; + +interface JsonRpcError { + code: number; + message: string; + data?: any; +} + +type JsonRpcErrorResp = { + jsonrpc: string; + id: number; + result?: undefined; + error: JsonRpcError; +}; + +export class JrpcProvider { + private reqId = 0; + + constructor(private readonly url: string) {} + + async callMethod( + method: string, + parameters?: Array> | Record, + fetchOptions?: RequestInit, + ): Promise { + const body = { + jsonrpc: '2.0', + id: this.reqId++, + method, + params: parameters, + }; + const resp = await fetch(this.url, { + ...fetchOptions, + method: 'POST', + body: JSON.stringify(body), + headers: { + 'Content-Type': 'application/json', + ...fetchOptions?.headers, + }, + }) + .then(async (r) => { + return r.json(); + }) + .then((data) => data as JsonRpcSuccessResp | JsonRpcErrorResp); + + if (resp.error) throw new Error(resp.error.message); + + return resp.result; + } + + // TODO: Batch RPC call +} diff --git a/src/vms/common/transaction.ts b/src/vms/common/transaction.ts new file mode 100644 index 000000000..8b05e6790 --- /dev/null +++ b/src/vms/common/transaction.ts @@ -0,0 +1,15 @@ +import type { Codec } from '../../serializable/codec'; +import type { VM, TypeSymbols } from '../../serializable/constants'; + +export abstract class Transaction { + abstract _type: TypeSymbols; + abstract toBytes(codec: Codec): Uint8Array; + abstract vm: VM; + abstract getBlockchainId(): string; + + abstract getSigIndices(): number[][]; + + getVM() { + return this.vm; + } +} diff --git a/src/vms/common/types.ts b/src/vms/common/types.ts new file mode 100644 index 000000000..ef27c4ca8 --- /dev/null +++ b/src/vms/common/types.ts @@ -0,0 +1,28 @@ +import type { Codec } from '../../serializable/codec'; +import type { TypeSymbols } from '../../serializable/constants'; + +export interface Serializable { + _type: TypeSymbols; + + toBytes(codec: Codec): Uint8Array; +} + +export interface SerializableStatic { + new (...args: any[]): Serializable; + + fromBytes(bytes: Uint8Array, codec: Codec): [Serializable, Uint8Array]; +} + +export function staticImplements() { + return (constructor: U) => { + constructor; + }; +} + +export function serializable() { + return staticImplements(); +} + +export interface Amounter extends Serializable { + amount(): bigint; +} diff --git a/src/vms/common/unsignedTx.spec.ts b/src/vms/common/unsignedTx.spec.ts new file mode 100644 index 000000000..18be1e9c3 --- /dev/null +++ b/src/vms/common/unsignedTx.spec.ts @@ -0,0 +1,192 @@ +import { + transferableOutput, + transferableOutputs, + utxoId, +} from '../../fixtures/avax'; +import { id } from '../../fixtures/common'; +import { bigIntPr, bytes, int } from '../../fixtures/primitives'; +import { signature, transferOutput } from '../../fixtures/secp256k1'; +import { + testAddress1, + testAddress2, + testPublicKey1, + testPrivateKey1, + testPrivateKey2, + testPublicKey2, +} from '../../fixtures/vms'; +import { BaseTx, TransferableInput } from '../../serializable/avax'; +import { Utxo } from '../../serializable/avax/utxo'; +import { ExportTx } from '../../serializable/avm'; +import { Address } from '../../serializable/fxs/common'; +import { Input, TransferInput } from '../../serializable/fxs/secp256k1'; +import { sign } from '../../utils'; +import { AddressMap, AddressMaps } from '../../utils/addressMap'; +import { UnsignedTx } from './unsignedTx'; + +describe('UnsignedTx', () => { + let addressMaps: AddressMaps; + beforeEach(() => { + addressMaps = new AddressMaps([ + new AddressMap([[new Address(testAddress1), 0]]), + new AddressMap([ + [new Address(testAddress2), 0], + [new Address(testAddress1), 1], + ]), + ]); + }); + + it('hasAllSignatures', async () => { + const tx = new ExportTx( + new BaseTx( + int(), + id(), + [transferableOutput()], + [ + new TransferableInput( + utxoId(), + id(), + new TransferInput(bigIntPr(), Input.fromNative([0])), + ), + new TransferableInput( + utxoId(), + id(), + new TransferInput(bigIntPr(), Input.fromNative([0, 1])), + ), + ], + bytes(), + ), + id(), + transferableOutputs(), + ); + + const unsignedTx = new UnsignedTx(tx, [], addressMaps); + const unsignedBytes = unsignedTx.toBytes(); + + expect(unsignedTx.hasAllSignatures()).toBeFalsy(); + + const sig = await sign(unsignedBytes, testPrivateKey1); + unsignedTx.addSignature(sig); + expect(unsignedTx.hasAllSignatures()).toBeFalsy(); + + const sig2 = await sign(unsignedBytes, testPrivateKey2); + unsignedTx.addSignature(sig2); + + expect(unsignedTx.hasAllSignatures()).toBeTruthy(); + }); + + it('serializes', () => { + const tx = new ExportTx( + new BaseTx( + int(), + id(), + [transferableOutput()], + [ + new TransferableInput( + utxoId(), + id(), + new TransferInput(bigIntPr(), Input.fromNative([0])), + ), + new TransferableInput( + utxoId(), + id(), + new TransferInput(bigIntPr(), Input.fromNative([0, 1])), + ), + ], + bytes(), + ), + id(), + transferableOutputs(), + ); + + const unsignedTx = new UnsignedTx( + tx, + [new Utxo(utxoId(), id(), transferOutput())], + addressMaps, + ); + unsignedTx.addSignatureAt(signature().toBytes(), 0, 0); + const unsignedTxJson = JSON.stringify(unsignedTx); + + expect(UnsignedTx.fromJSON(unsignedTxJson)).toEqual(unsignedTx); + }); + + describe('getSigIndicesForAddress', () => { + it('returns the correct indices when all signature slots are present', () => { + const tx = new ExportTx( + new BaseTx( + int(), + id(), + [transferableOutput()], + [ + new TransferableInput( + utxoId(), + id(), + new TransferInput(bigIntPr(), Input.fromNative([0])), + ), + new TransferableInput( + utxoId(), + id(), + new TransferInput(bigIntPr(), Input.fromNative([0, 1])), + ), + ], + bytes(), + ), + id(), + transferableOutputs(), + ); + + const unsignedTx = new UnsignedTx(tx, [], addressMaps); + const addr1SigIndices = unsignedTx.getSigIndicesForPubKey(testPublicKey1); + const addr2SigIndices = unsignedTx.getSigIndicesForPubKey(testPublicKey2); + + expect(unsignedTx.credentials[0].toJSON()).toHaveLength(1); + expect(unsignedTx.credentials[1].toJSON()).toHaveLength(2); + expect(addr1SigIndices).toStrictEqual([ + [0, 0], + [1, 1], + ]); + expect(addr2SigIndices).toStrictEqual([[1, 0]]); + }); + + it('returns the correct indices when signature slots are missing', () => { + const tx = new ExportTx( + new BaseTx( + int(), + id(), + [transferableOutput()], + [ + new TransferableInput( + utxoId(), + id(), + new TransferInput(bigIntPr(), Input.fromNative([0])), + ), + new TransferableInput( + utxoId(), + id(), + new TransferInput(bigIntPr(), Input.fromNative([1])), + ), + ], + bytes(), + ), + id(), + transferableOutputs(), + ); + + const unsignedTx = new UnsignedTx( + tx, + [], + new AddressMaps([ + new AddressMap([[new Address(testAddress1), 0]]), + new AddressMap([[new Address(testAddress1), 1]]), // missing signature slot at index 0 + ]), + ); + const addr1SigIndices = unsignedTx.getSigIndicesForPubKey(testPublicKey1); + + expect(unsignedTx.credentials[0].toJSON()).toHaveLength(1); + expect(unsignedTx.credentials[1].toJSON()).toHaveLength(1); + expect(addr1SigIndices).toStrictEqual([ + [0, 0], + [1, 0], // using re-ordered index 0 instead of 1 + ]); + }); + }); +}); diff --git a/src/vms/common/unsignedTx.ts b/src/vms/common/unsignedTx.ts new file mode 100644 index 000000000..0d6e52f47 --- /dev/null +++ b/src/vms/common/unsignedTx.ts @@ -0,0 +1,225 @@ +import { sha256 } from '@noble/hashes/sha256'; +import { emptySignature } from '../../constants/zeroValue'; +import { SignedTx } from '../../serializable/avax'; +import { Utxo } from '../../serializable/avax/utxo'; +import type { VM } from '../../serializable/constants'; +import { ValidVMs } from '../../serializable/constants'; +import { Address } from '../../serializable/fxs/common'; +import { Credential } from '../../serializable/fxs/secp256k1'; +import { + bufferToHex, + hexToBuffer, + publicKeyBytesToAddress, + publicKeyToEthAddress, + recoverPublicKey, +} from '../../utils'; +import { AddressMaps } from '../../utils/addressMap'; +import { getManagerForVM, packTx } from '../../utils/packTx'; +import type { Transaction } from './transaction'; + +type UnsingedTxSerialize = { + txBytes: string; + utxos: string[]; + addressMaps: [string, number][][]; + vm: string; + codecId: string; + credentials: string[][]; +}; +export class UnsignedTx { + credentials: Credential[]; + constructor( + readonly tx: Transaction, + readonly utxos: Utxo[], + readonly addressMaps: AddressMaps, + credentials?: Credential[], + ) { + if (credentials) { + this.credentials = credentials; + return; + } + this.credentials = this.tx + .getSigIndices() + .map((indicies) => new Credential(indicies.map(() => emptySignature))); + } + + toJSON() { + const codec = getManagerForVM(this.tx.vm).getDefaultCodec(); + const codecId = getManagerForVM(this.tx.vm).getDefaultCodecId(); + return { + codecId: codecId, + vm: this.tx.vm, + txBytes: bufferToHex(this.toBytes()), + utxos: this.utxos.map((utxo) => bufferToHex(utxo.toBytes(codec))), + addressMaps: this.addressMaps, + credentials: this.credentials, + }; + } + + static fromJSON(jsonString: string) { + const res = JSON.parse(jsonString) as UnsingedTxSerialize; + + const fields = [ + 'txBytes', + 'utxos', + 'addressMaps', + 'vm', + 'codecId', + 'credentials', + ]; + + fields.forEach((field) => { + if (!res[field]) { + throw new Error( + `invalid structure. must have ${fields.join(', ')}, missing ${field}`, + ); + } + }); + + const vm = res.vm as VM; + if (!ValidVMs.includes(vm)) { + throw new Error('invalid VM'); + } + + const manager = getManagerForVM(vm); + const [codec, rest] = manager.getCodecFromBuffer(hexToBuffer(res.txBytes)); + const tx = codec.UnpackPrefix(rest)[0]; + + const utxos = res.utxos.map( + (utxo) => Utxo.fromBytes(hexToBuffer(utxo), codec)[0], + ); + + const addressMaps = AddressMaps.fromJSON(res.addressMaps); + + const credentials = res.credentials.map((credStr) => + Credential.fromJSON(credStr), + ); + return new UnsignedTx(tx, utxos, addressMaps, credentials); + } + + getSigIndices() { + return this.tx.getSigIndices(); + } + + hasAddress(address: Address) { + return this.addressMaps.has(address); + } + + hasPubkey(pubKey: Uint8Array) { + return this.hasAddress(new Address(this.publicKeyBytesToAddress(pubKey))); + } + + getAddresses() { + return this.addressMaps.getAddresses(); + } + + getSigIndicesForAddress(address: Address) { + const useReorderedIndices = this.getSigIndices().some( + (sigIndices, credIndex) => { + const signaturesLength = this.credentials[credIndex].toJSON().length; + const maxSigIndex = Math.max(...sigIndices); + + return maxSigIndex > signaturesLength - 1; + }, + ); + + return this.addressMaps.getSigIndicesForAddress( + address, + useReorderedIndices, + ); + } + + getSigIndicesForPubKey(pubkey: Uint8Array) { + const addrAvax = this.publicKeyBytesToAddress(pubkey); + const addrEvm = publicKeyToEthAddress(pubkey); + + // Check against both addresses + const coordinatesAvax = this.getSigIndicesForAddress(new Address(addrAvax)); + const coordinatesEvm = this.getSigIndicesForAddress(new Address(addrEvm)); + + return coordinatesAvax || coordinatesEvm; + } + + getInputUtxos() { + return this.utxos; + } + + toBytes(): Uint8Array { + return packTx(this.tx); + } + + getBlockchainId() { + return this.tx.getBlockchainId(); + } + + getTx() { + return this.tx; + } + + getSignedTx() { + return new SignedTx(this.tx, this.credentials); + } + + getCredentials(): Credential[] { + return this.credentials as Credential[]; + } + + addSignatureAt(sig: Uint8Array, index: number, subIndex: number) { + if (index >= this.getCredentials().length) { + throw new Error('index out of bounds'); + } + this.getCredentials()[index].setSignature(subIndex, sig); + } + + addSignature(sig: Uint8Array) { + const unsignedHash = sha256(this.toBytes()); + const publicKey = recoverPublicKey(unsignedHash, sig); + this.addSignatureForPubKey(sig, publicKey); + } + + private addSignatureForPubKey(sig: Uint8Array, publicKey: Uint8Array) { + const coordinates = this.getSigIndicesForPubKey(publicKey); + if (coordinates) { + coordinates.forEach(([index, subIndex]) => { + this.addSignatureAt(sig, index, subIndex); + }); + } + } + + protected publicKeyBytesToAddress(pubKey: Uint8Array) { + return publicKeyBytesToAddress(pubKey); + } + + hasAllSignatures() { + const allSigsHex = this.credentials.map((cred) => cred.getSignatures()); + const emptySignatureHex = emptySignature.toString(); + const unsignedHash = sha256(this.toBytes()); + + const hasNoPlaceholders = allSigsHex.every((cred) => { + return cred.every((sig) => { + return sig !== emptySignatureHex; + }); + }); + + if (!hasNoPlaceholders) return false; + let valid = true; + + this.addressMaps.forEach((coordinates) => { + coordinates.forEach(([index, subIndex]) => { + const sig = allSigsHex[index]?.[subIndex]; + if (!sig) { + throw new Error('error: incorrect structure for credentials'); + } + const sigBytes = hexToBuffer(sig); + const publicKey = recoverPublicKey(unsignedHash, sigBytes); + if (!this.hasPubkey(publicKey)) { + valid = false; + } + }); + }, true); + return valid; + } + + getVM() { + return this.tx.getVM(); + } +} diff --git a/src/vms/context/context.ts b/src/vms/context/context.ts new file mode 100644 index 000000000..b11dff3cc --- /dev/null +++ b/src/vms/context/context.ts @@ -0,0 +1,52 @@ +import { getHRP } from '../../constants/networkIDs'; +import { Info } from '../../info/info'; +import { AVMApi } from '../avm/api'; +import type { Context } from './model'; + +/* +grabs some basic info about an avm chain +*/ +export const getContextFromURI = async ( + baseURL?: string, + assetDescription = 'AVAX', +): Promise => { + const xChainApi = new AVMApi(baseURL); + const { assetID: avaxAssetID } = await xChainApi.getAssetDescription( + assetDescription, + ); + const info = new Info(baseURL); + const { + txFee: baseTxFee, + createAssetTxFee, + createSubnetTxFee, + transformSubnetTxFee, + createBlockchainTxFee, + addPrimaryNetworkValidatorFee, + addPrimaryNetworkDelegatorFee, + addSubnetValidatorFee, + addSubnetDelegatorFee, + } = await info.getTxFee(); + const { blockchainID: xBlockchainID } = await info.getBlockchainId('X'); + const { blockchainID: pBlockchainID } = await info.getBlockchainId('P'); + const { blockchainID: cBlockchainID } = await info.getBlockchainId('C'); + + const { networkID } = await info.getNetworkId(); + + return Object.freeze({ + xBlockchainID, + pBlockchainID, + cBlockchainID, + avaxAssetID, + baseTxFee, + createAssetTxFee, + createSubnetTxFee, + transformSubnetTxFee, + createBlockchainTxFee, + addPrimaryNetworkValidatorFee, + addPrimaryNetworkDelegatorFee, + addSubnetValidatorFee, + addSubnetDelegatorFee, + networkID, + hrp: getHRP(networkID), + }); +}; diff --git a/src/vms/context/index.ts b/src/vms/context/index.ts new file mode 100644 index 000000000..0c6dd31dd --- /dev/null +++ b/src/vms/context/index.ts @@ -0,0 +1,2 @@ +export * from './context'; +export * from './model'; diff --git a/src/vms/context/model.ts b/src/vms/context/model.ts new file mode 100644 index 000000000..1280a8a65 --- /dev/null +++ b/src/vms/context/model.ts @@ -0,0 +1,17 @@ +export type Context = { + readonly networkID: number; + readonly hrp: string; + readonly xBlockchainID: string; + readonly pBlockchainID: string; + readonly cBlockchainID: string; + readonly avaxAssetID: string; + readonly baseTxFee: bigint; + readonly createAssetTxFee: bigint; + readonly createSubnetTxFee: bigint; + readonly transformSubnetTxFee: bigint; + readonly createBlockchainTxFee: bigint; + readonly addPrimaryNetworkValidatorFee: bigint; + readonly addPrimaryNetworkDelegatorFee: bigint; + readonly addSubnetValidatorFee: bigint; + readonly addSubnetDelegatorFee: bigint; +}; diff --git a/src/vms/evm/api.ts b/src/vms/evm/api.ts new file mode 100644 index 000000000..605b3a835 --- /dev/null +++ b/src/vms/evm/api.ts @@ -0,0 +1,62 @@ +import { SignedTx } from '../../serializable/avax'; +import { getEVMManager } from '../../serializable/evm/codec'; +import { hexToBuffer } from '../../utils'; +import { Api } from '../common/baseApi'; +import { ChainApi } from '../common/chainAPI'; +import type { GetAtomicTxParams, GetAtomicTxStatusResponse } from './model'; +import type { GetAtomicTxServerResponse } from './privateModels'; + +export class EVMApi extends ChainApi { + ethAPI: EthereumAPI; + constructor(baseURL?: string) { + super(baseURL, '/ext/bc/C/avax', 'avax', getEVMManager()); + this.ethAPI = new EthereumAPI(baseURL); + } + + /** + * Returns the transaction data of a provided transaction ID by calling the node's `getAtomicTx` method. + * + * @param txID The string representation of the transaction ID + * + * @returns Returns a Promise with the signedTX unmarshalled from the bytes + */ + + getAtomicTx = async (getTxParams: GetAtomicTxParams) => { + const resp = await this.callRpc('getAtomicTx', { + ...getTxParams, + encoding: 'hex', + }); + return this.manager.unpack(hexToBuffer(resp.tx), SignedTx); + }; + + /** + * @returns a Promise string containing the base fee for the next block. + */ + getBaseFee() { + return this.ethAPI.getBaseFee(); + } + + /** + * Returns the status of a provided atomic transaction ID by calling the node's `getAtomicTxStatus` method. + * + * @param txID The string representation of the transaction ID + * + * @returns Returns a Promise {status: string, blockHeight: string} containing the status retrieved from the node + */ + + getAtomicTxStatus(txID: string): Promise { + return this.callRpc('getAtomicTxStatus', { + txID, + }); + } +} + +class EthereumAPI extends Api { + constructor(baseURL?: string) { + super(baseURL, '/ext/bc/C/rpc'); + } + + async getBaseFee() { + return BigInt(await this.callRpc('eth_baseFee')); + } +} diff --git a/src/vms/evm/builder.spec.ts b/src/vms/evm/builder.spec.ts new file mode 100644 index 000000000..f57f14cfa --- /dev/null +++ b/src/vms/evm/builder.spec.ts @@ -0,0 +1,80 @@ +import { testContext } from '../../fixtures/context'; +import { + getTransferableInputForTest, + testAvaxAssetID, + testOwnerXAddress, + testUtxos, +} from '../../fixtures/transactions'; +import { expectTxs } from '../../fixtures/utils/expectTx'; +import { TransferableOutput } from '../../serializable/avax'; +import { ExportTx, ImportTx, Input, Output } from '../../serializable/evm'; +import { Address, Id } from '../../serializable/fxs/common'; +import { BigIntPr, Int } from '../../serializable/primitives'; +import { hexToBuffer, isTransferOut } from '../../utils'; +import { AvaxToNAvax } from '../../utils/avaxToNAvax'; +import { newExportTxFromBaseFee, newImportTxFromBaseFee } from './builder'; + +describe('CorethBuilder', () => { + const baseFee = 25n; + const fromAddress = testOwnerXAddress.toBytes(); + const toAddress = hexToBuffer('0x5432112345123451234512'); + + it('exportTx', () => { + const tx = newExportTxFromBaseFee( + testContext, + baseFee, + AvaxToNAvax(1), + testContext.xBlockchainID, + fromAddress, + [toAddress], + 3n, + ); + + const expectedTx = new ExportTx( + new Int(testContext.networkID), + Id.fromString(testContext.cBlockchainID), + Id.fromString(testContext.xBlockchainID), + [ + new Input( + testOwnerXAddress, + new BigIntPr(1000280750n), + testAvaxAssetID, + new BigIntPr(3n), + ), + ], + [ + TransferableOutput.fromNative(testContext.avaxAssetID, 1000000000n, [ + toAddress, + ]), + ], + ); + expectTxs(tx.getTx(), expectedTx); + }); + + it('importTx', () => { + const tx = newImportTxFromBaseFee( + testContext, + toAddress, + [fromAddress], + testUtxos().filter((utxo) => isTransferOut(utxo.output)), + testContext.xBlockchainID, + baseFee, + ); + + const expectedTx = new ImportTx( + new Int(testContext.networkID), + Id.fromString(testContext.cBlockchainID), + Id.fromString(testContext.xBlockchainID), + [getTransferableInputForTest()], + [ + new Output( + Address.fromString('C-avax12sepzg69zg69zg69zgmpqwf3'), + new BigIntPr(50000000000n), + testAvaxAssetID, + ), + ], + ); + + expectTxs(tx.getTx(), expectedTx); + }); +}); diff --git a/src/vms/evm/builder.ts b/src/vms/evm/builder.ts new file mode 100644 index 000000000..10629beb8 --- /dev/null +++ b/src/vms/evm/builder.ts @@ -0,0 +1,381 @@ +import { TransferableInput, TransferableOutput } from '../../serializable/avax'; +import type { Utxo } from '../../serializable/avax/utxo'; +import { ExportTx, ImportTx, Input, Output } from '../../serializable/evm'; +import { Address, Id } from '../../serializable/fxs/common'; +import { + OutputOwners, + TransferInput, + TransferOutput, +} from '../../serializable/fxs/secp256k1'; +import { BigIntPr, Int } from '../../serializable/primitives'; +import { addressesFromBytes } from '../../utils'; +import { AddressMap, AddressMaps } from '../../utils/addressMap'; +import { costCorethTx } from '../../utils/costs'; +import { matchOwners } from '../../utils/matchOwners'; +import { compareEVMOutputs } from '../../utils/sort'; +import { EVMUnsignedTx } from '../common/evmUnsignedTx'; +import type { UnsignedTx } from '../common/unsignedTx'; +import type { Context } from '../context'; + +export type EVMExportOptions = { + locktime: bigint; + threshold: number; +}; + +const defaultEVMExportOptions = ( + options?: Partial, +): EVMExportOptions => { + return { + locktime: 0n, + threshold: 1, + ...options, + }; +}; + +/** + * similar to new exportTX, except it estimates the price from base fee automatically + * @param baseFee dynamic fee fetched from evmapi + * @param amount amount to export + * @param destinationChain chainID of the destination chain + * @param fromAddress address that can sign this tx + * @param toAddresses address on the destination chain + * @param nonce the number of tx's on the sender's evm address. need to get from EVM directly using a lib like ethers. + * @param assetId the assetId to export + * @param options for additional properties of the resulting utxo + * @returns EVMUnsignedTx + */ +export function newExportTxFromBaseFee( + context: Context, + baseFee: bigint, + amount: bigint, + destinationChain: string, + fromAddress: Uint8Array, + toAddresses: Uint8Array[], + nonce: bigint, + assetId?: string, + options?: Partial, +) { + const fee = estimateExportCost( + context, + baseFee, + amount, + destinationChain, + fromAddress, + toAddresses, + nonce, + assetId, + options, + ); + + return newExportTx( + context, + amount, + destinationChain, + fromAddress, + toAddresses, + fee, + nonce, + assetId, + options, + ); +} + +/** + * + * estimate the export cost by forming a dummy tx and returning the fee based on the length of the tx + * @param baseFee dynamic fee fetched from EVMAPI + * @param amount amount to export in nAVAX + * @param destinationChain chainID of the destination chain + * @param fromAddress address that can sign this tx + * @param toAddresses address on the destination chain + * @param nonce the number of tx's on the sender's evm address. need to get from EVM directly using a lib like ethers. + * @param assetId the assetId to export + * @param options for additional properties of the resulting utxo + * @returns BigInt + */ + +export function estimateExportCost( + context: Context, + baseFee: bigint, + amount: bigint, + destinationChain: string, + fromAddress: Uint8Array, + toAddresses: Uint8Array[], + nonce: bigint, + assetId?: string, + options?: Partial, +) { + const dummyTx = newExportTx( + context, + amount, + destinationChain, + fromAddress, + toAddresses, + baseFee, + nonce, + assetId, + options, + ); + + const importCost = costCorethTx(dummyTx); + return baseFee * importCost; +} + +/** + * returns an export tx + * @param amount amount to export + * @param destinationChain chainID of the destination chain + * @param fromAddress address that can sign this tx + * @param toAddresses address on the destination chain + * @param fee dynamic fee fetched from evmapi + * @param nonce the number of tx's on the sender's evm address. need to get from EVM directly using a lib like ethers. + * @param assetId the assetId to export + * @param options for additional properties of the resulting utxo + * @returns EVMUnsignedTx + */ + +export function newExportTx( + context: Context, + amount: bigint, + destinationChain: string, + fromAddress: Uint8Array, + toAddresses: Uint8Array[], + fee: bigint, + nonce: bigint, + assetId?: string, + options?: Partial, +) { + assetId = assetId ?? context.avaxAssetID; + const { threshold, locktime } = defaultEVMExportOptions(options); + const avaxAssetID = context.avaxAssetID; + const evmInputConfigs: { + amount: bigint; + assetId: string; + }[] = []; + + const assetIsAvax = avaxAssetID === assetId; + + if (assetIsAvax) { + evmInputConfigs.push({ + assetId: context.avaxAssetID, + amount: amount + fee, + }); + } else { + // if asset id isn't AVAX asset id then create 2 inputs + // first input will be AVAX and will be for the amount of the fee + // second input will be the ANT + evmInputConfigs.push({ + amount: fee, + assetId: context.avaxAssetID, + }); + evmInputConfigs.push({ + amount, + assetId, + }); + } + + const evmInputs = evmInputConfigs.map( + ({ assetId, amount }) => + new Input( + new Address(fromAddress), + new BigIntPr(amount), + Id.fromString(assetId), + new BigIntPr(nonce), + ), + ); + + const transferableOutputs = [ + new TransferableOutput( + Id.fromString(assetId), + new TransferOutput( + new BigIntPr(amount), + new OutputOwners( + new BigIntPr(locktime), + new Int(threshold), + addressesFromBytes(toAddresses), + ), + ), + ), + ]; + evmInputs.sort(Input.compare); + return new EVMUnsignedTx( + new ExportTx( + new Int(context.networkID), + Id.fromString(context.cBlockchainID), + Id.fromString(destinationChain), + evmInputs, + transferableOutputs, + ), + [], + new AddressMaps([new AddressMap([[new Address(fromAddress), 0]])]), + ); +} + +/** + this method will handle making a dummy tx to calculate fees, and then using that to return the + correct tx + * @param toAddresses address on C-chain + * @param fromAddress address that can sign this tx + * @param sourceChain chainID of the source chain + * @param baseFee dynamic fee fetched from evmapi + * @param feeAssetId the assetId that the fee is measured in. defaults to AVAX + * @returns UnsignedTx + + + basefee is in nAvax + */ +export function newImportTxFromBaseFee( + context: Context, + toAddress: Uint8Array, + fromAddressesBytes: Uint8Array[], + atomics: Utxo[], + sourceChain: string, + baseFee = 0n, + feeAssetId?: string, +) { + const fee = estimateImportCost( + context, + toAddress, + fromAddressesBytes, + atomics, + sourceChain, + baseFee, + feeAssetId, + ); + + return newImportTx( + context, + toAddress, + fromAddressesBytes, + atomics, + sourceChain, + fee, + feeAssetId, + ); +} + +/** + * calculates the fee by forming a dummy tx and calculating based on the length of the tx + * @param toAddress address to import the utxos + * @param fromAddressesBytes addresses that are able to sign utxos + * @param atomics list of available utxos + * @param sourceChain base58 id of the chain to import from + * @param baseFee baseFee from EVMAPI.getBaseFee + * @param feeAssetId base58 ID of the asset to use for fee + * @returns BigInt + */ + +function estimateImportCost( + context: Context, + toAddress: Uint8Array, + fromAddressesBytes: Uint8Array[], + atomics: Utxo[], + sourceChain: string, + baseFee = 0n, + feeAssetId?: string, +) { + const dummyImportTx = newImportTx( + context, + toAddress, + fromAddressesBytes, + atomics, + sourceChain, + baseFee, + feeAssetId, + ); + + const importCost = costCorethTx(dummyImportTx); + return baseFee * importCost; +} + +/** + * + * @param toAddress address to import the utxos + * @param fromAddressesBytes addresses that are able to sign utxos + * @param atomics list of available utxos + * @param sourceChain base58 id of the chain to import from + * @param fee fee to subtract. If unsure, use newImportTxFromBaseFee + * @param feeAssetId base58 ID of the asset to use for fee + * @returns UnsignedTx + */ +export function newImportTx( + context: Context, + toAddress: Uint8Array, + fromAddressesBytes: Uint8Array[], + atomics: Utxo[], + sourceChain: string, + fee = 0n, + feeAssetId = context.avaxAssetID, +): UnsignedTx { + const fromAddresses = addressesFromBytes(fromAddressesBytes); + + const map: Map = new Map(); + let ins: TransferableInput[] = []; + let outs: Output[] = []; + let feepaid = 0n; + const inputUtxos: Utxo[] = []; + + // build a set of inputs which covers the fee + atomics.forEach((atomic) => { + const assetID: string = atomic.getAssetId(); + const output = atomic.output as TransferOutput; + const amount = output.amount(); + let infeeamount = amount; + if (feeAssetId && fee && feepaid < fee && feeAssetId === assetID) { + feepaid += infeeamount; + if (feepaid > fee) { + infeeamount = feepaid - fee; + feepaid = fee; + } else { + infeeamount = 0n; + } + } + + const sigData = matchOwners(output.outputOwners, fromAddresses, 0n); + + if (!sigData) return; + + const xferin: TransferableInput = new TransferableInput( + atomic.utxoId, + atomic.assetId, + TransferInput.fromNative(amount, sigData.sigIndicies), + ); + ins.push(xferin); + inputUtxos.push(atomic); + const assetFeeAmount = map.get(assetID); + if (assetFeeAmount) { + infeeamount += assetFeeAmount; + } + map.set(assetID, infeeamount); + }); + + for (const [assetID, amount] of map.entries()) { + // Create single EVMOutput for each assetID + outs.push( + new Output( + new Address(toAddress), + new BigIntPr(amount), + Id.fromString(assetID), + ), + ); + } + + // lexicographically sort array + ins = ins.sort(TransferableInput.compare); + const addressMaps = AddressMaps.fromTransferableInputs( + ins, + atomics, + 0n, + fromAddressesBytes, + ); + outs = outs.sort(compareEVMOutputs); + + const importTx = new ImportTx( + new Int(context.networkID), + Id.fromString(context.cBlockchainID), + Id.fromString(sourceChain), + ins, + outs, + ); + return new EVMUnsignedTx(importTx, inputUtxos, addressMaps); +} diff --git a/src/vms/evm/index.ts b/src/vms/evm/index.ts new file mode 100644 index 000000000..9d43eb885 --- /dev/null +++ b/src/vms/evm/index.ts @@ -0,0 +1,3 @@ +export * from './api'; +export * from './builder'; +export * from './model'; diff --git a/src/vms/evm/model.ts b/src/vms/evm/model.ts new file mode 100644 index 000000000..16a1aa129 --- /dev/null +++ b/src/vms/evm/model.ts @@ -0,0 +1,8 @@ +export interface GetAtomicTxParams { + txID: string; +} + +export interface GetAtomicTxStatusResponse { + status: string; + blockHeight: string; +} diff --git a/src/vms/evm/privateModels.ts b/src/vms/evm/privateModels.ts new file mode 100644 index 000000000..0011e1793 --- /dev/null +++ b/src/vms/evm/privateModels.ts @@ -0,0 +1,5 @@ +export interface GetAtomicTxServerResponse { + tx: string; + encoding: string; + blockHeight: string; +} diff --git a/src/vms/index.ts b/src/vms/index.ts new file mode 100644 index 000000000..9eaec9a72 --- /dev/null +++ b/src/vms/index.ts @@ -0,0 +1,7 @@ +export * as avm from './avm'; +export * as Common from './common'; +export { EVMUnsignedTx } from './common/evmUnsignedTx'; +export { UnsignedTx } from './common/unsignedTx'; +export * as Context from './context'; +export * as evm from './evm'; +export * as pvm from './pvm'; diff --git a/src/vms/pvm/api.ts b/src/vms/pvm/api.ts new file mode 100644 index 000000000..e3ce6d9e0 --- /dev/null +++ b/src/vms/pvm/api.ts @@ -0,0 +1,218 @@ +import { TransferableOutput } from '../../serializable/avax'; +import { Utxo } from '../../serializable/avax/utxo'; +import { getPVMManager } from '../../serializable/pvm/codec'; +import { hexToBuffer } from '../../utils'; +import type { GetAssetDescriptionResponse } from '../common/apiModels'; +import { AvaxApi } from '../common/avaxApi'; +import type { + GetBalanceParams, + GetBalanceResponse, + GetBlockchainsResponse, + GetBlockchainStatusResponse, + GetCurrentSupplyResponse, + GetCurrentValidatorsParams, + GetCurrentValidatorsResponse, + GetHeightResponse, + GetMaxStakeAmountParams, + GetMinStakeResponse, + GetPendingValidatorsParams, + GetPendingValidatorsResponse, + GetRewardUTXOsParams, + GetRewardUTXOsResponse, + GetStakeParams, + GetStakeResponse, + GetStakingAssetIDParams, + GetStakingAssetIDResponse, + GetSubnetsParams, + GetSubnetsResponse, + GetTimestampResponse, + GetTotalStakeResponse, + GetTxStatusParams, + GetTxStatusResponse, + GetValidatorsAtParams, + GetValidatorsAtResponse, + SampleValidatorsParams, + SampleValidatorsResponse, + ValidatedByParams, + ValidatedByResponse, + ValidatesParams, + ValidatesResponse, +} from './models'; +import type { + GetRewardUTXOsServerResponse, + GetStakeServerResponse, +} from './privateModels'; + +export class PVMApi extends AvaxApi { + constructor(baseURL?: string) { + super(baseURL, '/ext/bc/P', 'platform', getPVMManager()); + } + + getAssetDescription(assetID: string): Promise { + return this.callRpc('getAssetDescription', { + assetID, + }); + } + + getCurrentValidators( + getCurrentValidatorsParams?: GetCurrentValidatorsParams, + ): Promise { + return this.callRpc( + 'getCurrentValidators', + getCurrentValidatorsParams, + ); + } + getPendingValidators( + getPendingValidatorsParams?: GetPendingValidatorsParams, + ): Promise { + return this.callRpc( + 'getPendingValidators', + getPendingValidatorsParams, + ); + } + + async getRewardUTXOs( + getRewardUTXOsParams: GetRewardUTXOsParams, + ): Promise { + const resp = await this.callRpc( + 'getRewardUTXOs', + getRewardUTXOsParams, + ); + return { + ...resp, + utxos: resp.utxos.map((bytes) => + getPVMManager().unpack(hexToBuffer(bytes), Utxo), + ), + }; + } + + async getStake(getStakeParams: GetStakeParams): Promise { + const resp = await this.callRpc( + 'getStake', + getStakeParams, + ); + return { + ...resp, + stakedOutputs: resp.stakedOutputs.map((bytes) => + getPVMManager().unpack(hexToBuffer(bytes), TransferableOutput), + ), + }; + } + + getValidatorsAt( + getValidatorsAtParams: GetValidatorsAtParams, + ): Promise { + return this.callRpc( + 'getValidatorsAt', + getValidatorsAtParams, + ); + } + + getCurrentSupply(): Promise { + return this.callRpc('getCurrentSupply'); + } + + getMaxStakeAmount( + getMaxStakeAmountParams: GetMaxStakeAmountParams, + ): Promise { + return this.callRpc( + 'getMaxStakeAmount', + getMaxStakeAmountParams, + ); + } + + /** + * @link https://docs.avax.network/apis/avalanchego/apis/p-chain#platformgetbalance + * + * @param GetBalanceParams + * @returns GetBalanceResponse + */ + async getBalance( + GetBalanceParams: GetBalanceParams, + ): Promise { + const resp = await this.callRpc<{ + balance: string; + unlocked: string; + lockedStakeable: string; + lockedNotStakeable: string; + utxoIDs: { + txID: string; + outputIndex: number; + }[]; + }>('getBalance', GetBalanceParams); + + return { + balance: BigInt(resp.balance), + unlocked: BigInt(resp.unlocked), + lockedStakeable: BigInt(resp.lockedStakeable), + lockedNotStakeable: BigInt(resp.lockedNotStakeable), + utxoIDs: resp.utxoIDs, + }; + } + + getBlockchains(): Promise { + return this.callRpc('getBlockchains'); + } + + getBlockchainStatus( + blockchainID: string, + ): Promise { + return this.callRpc('getBlockchainStatus', { + blockchainID, + }); + } + + getHeight(): Promise { + return this.callRpc('getHeight'); + } + + getMinStake(): Promise { + return this.callRpc('getMinStake'); + } + + getStakingAssetID( + getStakingAssetIDParams: GetStakingAssetIDParams, + ): Promise { + return this.callRpc( + 'getStakingAssetID', + getStakingAssetIDParams, + ); + } + + getSubnets(getSubnetsParams: GetSubnetsParams): Promise { + return this.callRpc('getSubnets', getSubnetsParams); + } + + getTimestamp(): Promise { + return this.callRpc('getTimestamp'); + } + + getTotalStake(subnetID: string): Promise { + return this.callRpc('getTotalStake', { subnetID }); + } + + getTxStatus( + getTxStatusParams: GetTxStatusParams, + ): Promise { + return this.callRpc('getTxStatus', getTxStatusParams); + } + + sampleValidators( + sampleValidatorsParams: SampleValidatorsParams, + ): Promise { + return this.callRpc( + 'sampleValidators', + sampleValidatorsParams, + ); + } + + validatedBy( + validatedByParams: ValidatedByParams, + ): Promise { + return this.callRpc('validatedBy', validatedByParams); + } + + validates(validatesParams: ValidatesParams): Promise { + return this.callRpc('validates', validatesParams); + } +} diff --git a/src/vms/pvm/builder.spec.ts b/src/vms/pvm/builder.spec.ts new file mode 100644 index 000000000..1700b9b77 --- /dev/null +++ b/src/vms/pvm/builder.spec.ts @@ -0,0 +1,827 @@ +import { testContext } from '../../fixtures/context'; +import { + fromAddressBytes, + getBaseTxForTest, + getStakeableLockedTransferableInputForTest, + getStakeableLockedTransferableOutForTest, + getTransferableInputForTest, + getTransferableOutForTest, + getValidUtxo, + testAvaxAssetID, + testGenesisData, + testOwnerXAddress, + testSubnetId, + testUTXOID1, + testUtxos, + testVMId, +} from '../../fixtures/transactions'; +import { expectTxs } from '../../fixtures/utils/expectTx'; +import { testAddress1 } from '../../fixtures/vms'; +import { + BaseTx as AvaxBaseTx, + TransferableInput, + TransferableOutput, + UTXOID, +} from '../../serializable/avax'; +import { Utxo } from '../../serializable/avax/utxo'; +import { Id } from '../../serializable/fxs/common'; +import { + Input, + OutputOwners, + TransferInput, + TransferOutput, +} from '../../serializable/fxs/secp256k1'; +import { + BigIntPr, + Byte, + Bytes, + Int, + Stringpr, +} from '../../serializable/primitives'; +import type { BaseTx } from '../../serializable/pvm'; +import { + AddDelegatorTx, + AddPermissionlessDelegatorTx, + AddPermissionlessValidatorTx, + AddSubnetValidatorTx, + AddValidatorTx, + CreateChainTx, + CreateSubnetTx, + ExportTx, + ImportTx, + Signer, + StakeableLockOut, + SubnetValidator, + TransferSubnetOwnershipTx, + TransformSubnetTx, + Validator, +} from '../../serializable/pvm'; +import { hexToBuffer } from '../../utils'; +import { + newAddDelegatorTx, + newAddPermissionlessValidatorTx, + newAddSubnetValidatorTx, + newAddValidatorTx, + newCreateBlockchainTx, + newCreateSubnetTx, + newExportTx, + newImportTx, + newRemoveSubnetValidatorTx, + newAddPermissionlessDelegatorTx, + newBaseTx, + newTransferSubnetOwnershipTx, + newTransformSubnetTx, +} from './builder'; +import { RemoveSubnetValidatorTx } from '../../serializable/pvm/removeSubnetValidatorTx'; +import { NodeId } from '../../serializable/fxs/common/nodeId'; +import { proofOfPossession } from '../../fixtures/pvm'; +import { + blsPublicKeyBytes, + blsSignatureBytes, +} from '../../fixtures/primitives'; +import { AvaxToNAvax } from '../../utils/avaxToNAvax'; +import { PrimaryNetworkID } from '../../constants/networkIDs'; + +describe('pvmBuilder', () => { + const nodeID = 'NodeID-2m38qc95mhHXtrhjyGbe7r2NhniqHHJRB'; + const toAddress = hexToBuffer('0x5432112345123451234512'); + + const getRewardsOwners = () => OutputOwners.fromNative([toAddress]); + + it('baseTx', () => { + const utxos = testUtxos(); + const toAddress = hexToBuffer('0x5432112345123451234512'); + const tnsOut = TransferableOutput.fromNative( + testAvaxAssetID.toString(), + BigInt(1 * 1e9), + [toAddress], + ); + const tx = newBaseTx(testContext, [testOwnerXAddress.toBytes()], utxos, [ + tnsOut, + ]); + const { + baseTx: { inputs, outputs }, + } = tx.getTx() as BaseTx; + + expect(outputs.length).toEqual(2); + expect(outputs as TransferableOutput[]).toEqual([ + tnsOut, + new TransferableOutput( + testAvaxAssetID, + new TransferOutput( + new BigIntPr(48999000000n), // input - amount sent - fee + OutputOwners.fromNative([testOwnerXAddress.toBytes()]), + ), + ), + ]); + + expect(inputs.length).toEqual(1); + expect(inputs as TransferableInput[]).toEqual([ + new TransferableInput( + utxos[2].utxoId, + testAvaxAssetID, + new TransferInput( + new BigIntPr(BigInt(50 * 1e9)), + Input.fromNative([0]), + ), + ), + ]); + }); + + it('importTx', () => { + const utxos = testUtxos(); + const tx = newImportTx( + testContext, + testContext.cBlockchainID, + utxos, + [testAddress1], + fromAddressBytes, + ); + const importTx = tx.getTx() as ImportTx; + + const expectedTx = new ImportTx( + AvaxBaseTx.fromNative( + testContext.networkID, + testContext.pBlockchainID, + [ + TransferableOutput.fromNative(testContext.avaxAssetID, 49999000000n, [ + testAddress1, + ]), + ], + [], + new Uint8Array([]), + ), + Id.fromString(testContext.cBlockchainID), + [TransferableInput.fromUtxoAndSigindicies(utxos[2], [0])], + ); + + expect(JSON.stringify(importTx, null, 2)).toEqual( + JSON.stringify(expectedTx, null, 2), + ); + }); + + it('exportTx', () => { + const tnsOut = TransferableOutput.fromNative( + testContext.avaxAssetID, + BigInt(5 * 1e9), + [toAddress], + ); + const unsignedTx = newExportTx( + testContext, + testContext.cBlockchainID, + fromAddressBytes, + testUtxos(), + [tnsOut], + ); + + const expectedTx = new ExportTx( + AvaxBaseTx.fromNative( + testContext.networkID, + testContext.pBlockchainID, + [ + TransferableOutput.fromNative( + testContext.avaxAssetID, + 44999000000n, + fromAddressBytes, + ), + ], + [getTransferableInputForTest()], + new Uint8Array(), + ), + Id.fromString(testContext.cBlockchainID), + [tnsOut], + ); + + expectTxs(unsignedTx.getTx(), expectedTx); + }); + + it('AddValidatorTx', () => { + const unsignedTx = newAddValidatorTx( + testContext, + testUtxos(), + fromAddressBytes, + nodeID, + 100n, + 200n, + BigInt(1e9), + [toAddress], + 30 * 10000, + ); + + const expectedTx = new AddValidatorTx( + getBaseTxForTest(49000000000n, testContext.pBlockchainID), + Validator.fromNative(nodeID, 100n, 200n, BigInt(1e9)), + [getTransferableOutForTest(1000000000n)], + getRewardsOwners(), + new Int(30 * 10000), + ); + + expectTxs(unsignedTx.getTx(), expectedTx); + }); + + it('AddValidatorTx - stakeable locked', () => { + const utxos = testUtxos(); + const lockTime = BigInt(Math.floor(new Date().getTime() / 1000)) + 10000n; + const lockedUtxo = new Utxo( + new UTXOID(testUTXOID1, new Int(0)), + testAvaxAssetID, + new StakeableLockOut( + new BigIntPr(lockTime), + new TransferOutput( + new BigIntPr(BigInt(50 * 1e9)), + OutputOwners.fromNative([testOwnerXAddress.toBytes()]), + ), + ), + ); + + utxos.push(lockedUtxo); + const unsignedTx = newAddValidatorTx( + testContext, + utxos, + fromAddressBytes, + nodeID, + 100n, + 200n, + BigInt(1e9), + [toAddress], + 30 * 10000, + ); + + const expectedTx = new AddValidatorTx( + AvaxBaseTx.fromNative( + testContext.networkID, + testContext.pBlockchainID, + [getStakeableLockedTransferableOutForTest(49000000000n, lockTime)], + [getStakeableLockedTransferableInputForTest(50000000000n, lockTime)], + new Uint8Array(), + ), + Validator.fromNative(nodeID, 100n, 200n, BigInt(1e9)), + [getStakeableLockedTransferableOutForTest(1000000000n, lockTime)], + getRewardsOwners(), + new Int(30 * 10000), + ); + + expectTxs(unsignedTx.getTx(), expectedTx); + }); + + it('AddDelegatorTx', () => { + const utxos = testUtxos(); + const lockTime = BigInt(Math.floor(new Date().getTime() / 1000)) + 10000n; + const lockedUtxo = new Utxo( + new UTXOID(testUTXOID1, new Int(0)), + testAvaxAssetID, + new StakeableLockOut( + new BigIntPr(lockTime), + new TransferOutput( + new BigIntPr(BigInt(50 * 1e9)), + OutputOwners.fromNative([testOwnerXAddress.toBytes()]), + ), + ), + ); + + utxos.push(lockedUtxo); + + const unsignedTx = newAddDelegatorTx( + testContext, + utxos, + fromAddressBytes, + nodeID, + 100n, + 200n, + BigInt(1e9), + [toAddress], + ); + + const expectedTx = new AddDelegatorTx( + AvaxBaseTx.fromNative( + testContext.networkID, + testContext.pBlockchainID, + [getStakeableLockedTransferableOutForTest(49000000000n, lockTime)], + [getStakeableLockedTransferableInputForTest(50000000000n, lockTime)], + new Uint8Array(), + ), + Validator.fromNative(nodeID, 100n, 200n, BigInt(1e9)), + [getStakeableLockedTransferableOutForTest(1000000000n, lockTime)], + getRewardsOwners(), + ); + + expectTxs(unsignedTx.getTx(), expectedTx); + }); + + it('AddDelegatorTx - stakeable locked', () => { + const unsignedTx = newAddDelegatorTx( + testContext, + testUtxos(), + fromAddressBytes, + nodeID, + 100n, + 200n, + BigInt(1e9), + [toAddress], + ); + + const expectedTx = new AddDelegatorTx( + getBaseTxForTest(49000000000n, testContext.pBlockchainID), + Validator.fromNative(nodeID, 100n, 200n, BigInt(1e9)), + [getTransferableOutForTest(1000000000n)], + getRewardsOwners(), + ); + + expectTxs(unsignedTx.getTx(), expectedTx); + }); + + it('newCreateSubnetTx', () => { + const utxoInputAmt = BigInt(2 * 1e9); + const unsignedTx = newCreateSubnetTx( + testContext, + [getValidUtxo(new BigIntPr(utxoInputAmt))], + fromAddressBytes, + [toAddress], + ); + + const expectedTx = new CreateSubnetTx( + AvaxBaseTx.fromNative( + testContext.networkID, + testContext.pBlockchainID, + [ + getTransferableOutForTest( + utxoInputAmt - testContext.createSubnetTxFee, + ), + ], + [getTransferableInputForTest(utxoInputAmt)], + new Uint8Array(), + ), + getRewardsOwners(), + ); + + expectTxs(unsignedTx.getTx(), expectedTx); + }); + + it('newCreateBlockchainTx', () => { + const utxoInputAmt = BigInt(2 * 1e9); + const unsignedTx = newCreateBlockchainTx( + testContext, + [getValidUtxo(new BigIntPr(utxoInputAmt))], + fromAddressBytes, + Id.fromHex(testSubnetId).toString(), + 'Random Chain Name', + Id.fromHex(testVMId).toString(), + [], + testGenesisData, + [0], + ); + + const expectedTx = new CreateChainTx( + AvaxBaseTx.fromNative( + testContext.networkID, + testContext.pBlockchainID, + [ + getTransferableOutForTest( + utxoInputAmt - testContext.createBlockchainTxFee, + ), + ], + [getTransferableInputForTest(utxoInputAmt)], + new Uint8Array(), + ), + Id.fromHex(testSubnetId), + new Stringpr('Random Chain Name'), + Id.fromHex(testVMId), + [], + new Bytes(new TextEncoder().encode(JSON.stringify(testGenesisData))), + Input.fromNative([0]), + ); + + expectTxs(unsignedTx.getTx(), expectedTx); + }); + + it('newCreateSubnetValidatorTx', () => { + const utxoInputAmt = BigInt(2 * 1e9); + const unsignedTx = newAddSubnetValidatorTx( + testContext, + [getValidUtxo(new BigIntPr(utxoInputAmt))], + fromAddressBytes, + nodeID, + 100n, + 190000000n, + 1800000n, + Id.fromHex(testSubnetId).toString(), + [0], + ); + + const expectedTx = new AddSubnetValidatorTx( + AvaxBaseTx.fromNative( + testContext.networkID, + testContext.pBlockchainID, + [getTransferableOutForTest(utxoInputAmt - testContext.baseTxFee)], + [getTransferableInputForTest(utxoInputAmt)], + new Uint8Array(), + ), + SubnetValidator.fromNative( + nodeID, + 100n, + 190000000n, + 1800000n, + Id.fromHex(testSubnetId), + ), + Input.fromNative([0]), + ); + + expectTxs(unsignedTx.getTx(), expectedTx); + }); + + it('newRemoveSubnetValidatorTx', () => { + const utxoInputAmt = BigInt(2 * 1e9); + const unsignedTx = newRemoveSubnetValidatorTx( + testContext, + [getValidUtxo(new BigIntPr(utxoInputAmt))], + fromAddressBytes, + nodeID, + Id.fromHex(testSubnetId).toString(), + [0], + ); + + const expectedTx = new RemoveSubnetValidatorTx( + AvaxBaseTx.fromNative( + testContext.networkID, + testContext.pBlockchainID, + [getTransferableOutForTest(utxoInputAmt - testContext.baseTxFee)], + [getTransferableInputForTest(utxoInputAmt)], + new Uint8Array(), + ), + NodeId.fromString(nodeID), + Id.fromHex(testSubnetId), + Input.fromNative([0]), + ); + + expectTxs(unsignedTx.getTx(), expectedTx); + }); + + it('newAddPermissionlessValidatorTx - primary network', () => { + const utxoInputAmt = AvaxToNAvax(2); + + const unsignedTx = newAddPermissionlessValidatorTx( + testContext, + [getValidUtxo(new BigIntPr(utxoInputAmt))], + fromAddressBytes, + nodeID, + PrimaryNetworkID.toString(), + 0n, // startTime + 120n, //end time + 1800000n, // weight + [], // rewards owners + [], // delegatorRewardsOwner + 1, + {}, + 1, + 0n, + blsPublicKeyBytes(), + blsSignatureBytes(), + ); + + const expectedTx = new AddPermissionlessValidatorTx( + AvaxBaseTx.fromNative( + testContext.networkID, + testContext.pBlockchainID, + [ + getTransferableOutForTest( + utxoInputAmt - 1800000n - testContext.addPrimaryNetworkValidatorFee, + ), + ], + [getTransferableInputForTest(utxoInputAmt)], + new Uint8Array(), + ), + SubnetValidator.fromNative( + NodeId.fromString(nodeID).toString(), + 0n, + 120n, + 1800000n, + PrimaryNetworkID, + ), + new Signer(proofOfPossession()), + [getTransferableOutForTest(1800000n)], //stake + OutputOwners.fromNative([], 0n, 1), + OutputOwners.fromNative([], 0n, 1), + new Int(1), + ); + + expectTxs(unsignedTx.getTx(), expectedTx); + }); + + it('newAddPermissionlessValidatorTx - subnet', () => { + const utxoInputAmt = AvaxToNAvax(2); + + const unsignedTx = newAddPermissionlessValidatorTx( + testContext, + [getValidUtxo(new BigIntPr(utxoInputAmt))], + fromAddressBytes, + nodeID, + Id.fromHex(testSubnetId).toString(), + 0n, // startTime + 120n, //end time + 1800000n, // weight + [], // rewards owners + [], // delegatorRewardsOwner + 1, + {}, + 1, + 0n, + blsPublicKeyBytes(), + blsSignatureBytes(), + ); + + const expectedTx = new AddPermissionlessValidatorTx( + AvaxBaseTx.fromNative( + testContext.networkID, + testContext.pBlockchainID, + [ + getTransferableOutForTest( + utxoInputAmt - 1800000n - testContext.addSubnetValidatorFee, + ), + ], + [getTransferableInputForTest(utxoInputAmt)], + new Uint8Array(), + ), + SubnetValidator.fromNative( + NodeId.fromString(nodeID).toString(), + 0n, + 120n, + 1800000n, + Id.fromHex(testSubnetId), + ), + new Signer(proofOfPossession()), + [getTransferableOutForTest(1800000n)], //stake + OutputOwners.fromNative([], 0n, 1), + OutputOwners.fromNative([], 0n, 1), + new Int(1), + ); + + expectTxs(unsignedTx.getTx(), expectedTx); + }); + + it('newAddPermissionlessValidatorTx - subnet with non avax staking token', () => { + const utxoInputAmt = AvaxToNAvax(2); + const stakingAssetId = Id.fromHex('0102'); + const stakeAmount = 1_000_000n; + + const unsignedTx = newAddPermissionlessValidatorTx( + testContext, + [ + getValidUtxo(new BigIntPr(utxoInputAmt)), + getValidUtxo(new BigIntPr(2n * stakeAmount), stakingAssetId), + ], + fromAddressBytes, + nodeID, + Id.fromHex(testSubnetId).toString(), + 0n, // startTime + 120n, //end time + stakeAmount, // weight + [], // rewards owners + [], // delegatorRewardsOwner + 1, + {}, + 1, + 0n, + blsPublicKeyBytes(), + blsSignatureBytes(), + stakingAssetId.toString(), + ); + + const baseOuts = (unsignedTx.getTx() as AddPermissionlessValidatorTx).baseTx + .outputs; + const stakeUtxos = (unsignedTx.getTx() as AddPermissionlessValidatorTx) + .stake; + expect(stakeUtxos.length).toEqual(1); + // Expect correct stake out + expect(stakeUtxos[0].assetId.toString()).toEqual(stakingAssetId.toString()); + expect(stakeUtxos[0].amount()).toEqual(stakeAmount); + // Expect correct change utxos + expect(baseOuts.length).toEqual(2); + // Stake token change + expect(baseOuts[0].assetId.toString()).toEqual(stakingAssetId.toString()); + expect(baseOuts[0].amount()).toEqual(stakeAmount); + // AVAX Change + expect(baseOuts[1].assetId.toString()).toEqual(testContext.avaxAssetID); + expect(baseOuts[1].amount().toString()).toEqual( + (utxoInputAmt - testContext.addSubnetValidatorFee).toString(), + ); + }); + + it('newAddPermissionlessDelegatorTx - primary network', () => { + const utxoInputAmt = AvaxToNAvax(2); + + const unsignedTx = newAddPermissionlessDelegatorTx( + testContext, + [getValidUtxo(new BigIntPr(utxoInputAmt))], + fromAddressBytes, + nodeID, + PrimaryNetworkID.toString(), + 0n, // startTime + 120n, //end time + 1800000n, // weight + [], // rewards owners + {}, + 1, + 0n, + ); + + const expectedTx = new AddPermissionlessDelegatorTx( + AvaxBaseTx.fromNative( + testContext.networkID, + testContext.pBlockchainID, + [ + getTransferableOutForTest( + utxoInputAmt - 1800000n - testContext.addPrimaryNetworkDelegatorFee, + ), + ], + [getTransferableInputForTest(utxoInputAmt)], + new Uint8Array(), + ), + SubnetValidator.fromNative( + NodeId.fromString(nodeID).toString(), + 0n, + 120n, + 1800000n, + PrimaryNetworkID, + ), + [getTransferableOutForTest(1800000n)], //stake + OutputOwners.fromNative([], 0n, 1), + ); + + expectTxs(unsignedTx.getTx(), expectedTx); + }); + + it('newAddPermissionlessDelegatorTx - subnet', () => { + const utxoInputAmt = AvaxToNAvax(2); + + const unsignedTx = newAddPermissionlessDelegatorTx( + testContext, + [getValidUtxo(new BigIntPr(utxoInputAmt))], + fromAddressBytes, + nodeID, + Id.fromHex(testSubnetId).toString(), + 0n, // startTime + 120n, //end time + 1800000n, // weight + [], // rewards owners + {}, + 1, + 0n, + ); + + const expectedTx = new AddPermissionlessDelegatorTx( + AvaxBaseTx.fromNative( + testContext.networkID, + testContext.pBlockchainID, + [ + getTransferableOutForTest( + utxoInputAmt - 1800000n - testContext.addSubnetDelegatorFee, + ), + ], + [getTransferableInputForTest(utxoInputAmt)], + new Uint8Array(), + ), + SubnetValidator.fromNative( + NodeId.fromString(nodeID).toString(), + 0n, + 120n, + 1800000n, + Id.fromHex(testSubnetId), + ), + [getTransferableOutForTest(1800000n)], //stake + OutputOwners.fromNative([], 0n, 1), + ); + + expectTxs(unsignedTx.getTx(), expectedTx); + }); + + it('newAddPermissionlessDelegatorTx - subnet with non avax staking token', () => { + const utxoInputAmt = AvaxToNAvax(2); + const stakingAssetId = Id.fromHex('0102'); + const stakeAmount = 1_000_000n; + + const unsignedTx = newAddPermissionlessDelegatorTx( + testContext, + [ + getValidUtxo(new BigIntPr(utxoInputAmt)), + getValidUtxo(new BigIntPr(2n * stakeAmount), stakingAssetId), + ], + fromAddressBytes, + nodeID, + Id.fromHex(testSubnetId).toString(), + 0n, // startTime + 120n, //end time + stakeAmount, // weight + [], // rewards owners + {}, + 1, + 0n, + stakingAssetId.toString(), + ); + + const baseOuts = (unsignedTx.getTx() as AddPermissionlessDelegatorTx).baseTx + .outputs; + const stakeUtxos = (unsignedTx.getTx() as AddPermissionlessDelegatorTx) + .stake; + + expect(stakeUtxos.length).toEqual(1); + // Expect correct stake out + expect(stakeUtxos[0].assetId.toString()).toEqual(stakingAssetId.toString()); + expect(stakeUtxos[0].amount()).toEqual(stakeAmount); + // Expect correct change utxos + expect(baseOuts.length).toEqual(2); + // Stake token change + expect(baseOuts[0].assetId.toString()).toEqual(stakingAssetId.toString()); + expect(baseOuts[0].amount()).toEqual(stakeAmount); + // AVAX Change + expect(baseOuts[1].assetId.toString()).toEqual(testContext.avaxAssetID); + expect(baseOuts[1].amount().toString()).toEqual( + (utxoInputAmt - testContext.addSubnetDelegatorFee).toString(), + ); + }); + + it('newTransferSubnetOwnershipTx', () => { + const utxoInputAmt = BigInt(2 * 1e9); + const subnetAuth = [0, 1]; + const unsignedTx = newTransferSubnetOwnershipTx( + testContext, + [getValidUtxo(new BigIntPr(utxoInputAmt))], + fromAddressBytes, + Id.fromHex(testSubnetId).toString(), + subnetAuth, + [toAddress], + ); + + const expectedTx = new TransferSubnetOwnershipTx( + AvaxBaseTx.fromNative( + testContext.networkID, + testContext.pBlockchainID, + [getTransferableOutForTest(utxoInputAmt - testContext.baseTxFee)], + [getTransferableInputForTest(utxoInputAmt)], + new Uint8Array(), + ), + Id.fromHex(testSubnetId), + Input.fromNative(subnetAuth), + getRewardsOwners(), + ); + + expectTxs(unsignedTx.getTx(), expectedTx); + }); + + it('newTransformSubnetTx', () => { + const utxoInputAmt = BigInt(2 * 1e12); + const stakingAssetId = Id.fromHex('0102'); + const subnetAuth = [0, 1]; + + const unsignedTx = newTransformSubnetTx( + testContext, + [getValidUtxo(new BigIntPr(utxoInputAmt))], + fromAddressBytes, + Id.fromHex(testSubnetId).toString(), + stakingAssetId.toString(), + 1n, + 2n, + 3n, + 4n, + 5n, + 6n, + 1, + 2, + 3, + 4, + 5, + 6, + subnetAuth, + ); + + const expectedTx = new TransformSubnetTx( + AvaxBaseTx.fromNative( + testContext.networkID, + testContext.pBlockchainID, + [ + getTransferableOutForTest( + utxoInputAmt - testContext.transformSubnetTxFee, + ), + ], + [getTransferableInputForTest(utxoInputAmt)], + new Uint8Array(), + ), + Id.fromHex(testSubnetId), + stakingAssetId, + new BigIntPr(1n), + new BigIntPr(2n), + new BigIntPr(3n), + new BigIntPr(4n), + new BigIntPr(5n), + new BigIntPr(6n), + new Int(1), + new Int(2), + new Int(3), + new Int(4), + new Byte(hexToBuffer('0x5')), + new Int(6), + Input.fromNative(subnetAuth), + ); + + expectTxs(unsignedTx.getTx(), expectedTx); + }); +}); diff --git a/src/vms/pvm/builder.ts b/src/vms/pvm/builder.ts new file mode 100644 index 000000000..40763f6b0 --- /dev/null +++ b/src/vms/pvm/builder.ts @@ -0,0 +1,868 @@ +import { PlatformChainID, PrimaryNetworkID } from '../../constants/networkIDs'; +import { + BaseTx as AvaxBaseTx, + TransferableInput, + TransferableOutput, +} from '../../serializable/avax'; +import type { Utxo } from '../../serializable/avax/utxo'; +import { Id } from '../../serializable/fxs/common'; +import { Input, OutputOwners } from '../../serializable/fxs/secp256k1'; +import { BigIntPr, Byte, Stringpr } from '../../serializable/primitives'; +import { Bytes, Int } from '../../serializable/primitives'; +import { + AddDelegatorTx, + AddValidatorTx, + BaseTx, + CreateChainTx, + CreateSubnetTx, + ExportTx, + ImportTx, + Validator, + AddSubnetValidatorTx, + SubnetValidator, + AddPermissionlessValidatorTx, + AddPermissionlessDelegatorTx, + RemoveSubnetValidatorTx, + TransferSubnetOwnershipTx, + TransformSubnetTx, +} from '../../serializable/pvm'; +import { addressesFromBytes, hexToBuffer } from '../../utils'; +import { AddressMaps } from '../../utils/addressMap'; +import { getImportedInputsFromUtxos } from '../../utils/builderUtils'; +import { compareTransferableOutputs } from '../../utils/sort'; +import { defaultSpendOptions } from '../common/defaultSpendOptions'; +import type { SpendOptions } from '../common/models'; +import { UnsignedTx } from '../common/unsignedTx'; +import type { Context } from '../context'; +import { calculateUTXOSpend } from '../utils/calculateSpend'; +import { + useConsolidateOutputs, + useSpendableLockedUTXOs, + useUnlockedUTXOs, +} from './utxoCalculationFns'; +import { NodeId } from '../../serializable/fxs/common/nodeId'; +import { createSignerOrSignerEmptyFromStrings } from '../../serializable/pvm/signer'; +import { baseTxUnsafe } from '../common'; + +/* + Builder is useful for building transactions that are specific to a chain. + */ + +/** + * @param fromAddresses - used for selecting which utxos are signable + * @param utxoSet - list of utxos to spend from + * @param outputs - the desired output (change outputs will be added to them automatically) + * @param options - see SpendingOptions + * + * @returns UnsignedTx containing a BaseTx + */ +export function newBaseTx( + context: Context, + fromAddressesBytes: Uint8Array[], + utxoSet: Utxo[], + outputs: TransferableOutput[], + options?: SpendOptions, +) { + const fromAddresses = addressesFromBytes(fromAddressesBytes); + const defaultedOptions = defaultSpendOptions(fromAddressesBytes, options); + const toBurn = new Map([ + [context.avaxAssetID, context.baseTxFee], + ]); + + outputs.forEach((out) => { + const assetId = out.assetId.value(); + toBurn.set(assetId, (toBurn.get(assetId) || 0n) + out.output.amount()); + }); + + const { inputs, inputUTXOs, changeOutputs, addressMaps } = calculateUTXOSpend( + toBurn, + undefined, + utxoSet, + fromAddresses, + defaultedOptions, + [useUnlockedUTXOs, useConsolidateOutputs], + ); + + const allOutputs = [...outputs, ...changeOutputs]; + allOutputs.sort(compareTransferableOutputs); + + return new UnsignedTx( + new BaseTx( + baseTxUnsafe(context, allOutputs, inputs, defaultedOptions.memo), + ), + inputUTXOs, + addressMaps, + ); +} + +/** + @param sourceChainID - base58 of the sourceChain. can pass in from context + @param utxos - list of utxos + @param toAddress - list of addresses to import into + @param fromAddressesBytes - used for utxo selection. provide all addresses that can sign Tx + @param options - see SpendOptions + @param threshold - the threshold to write on the utxo + @param locktime - the locktime to write onto the utxo + + @returns a unsignedTx +*/ +export function newImportTx( + context: Context, + sourceChainId: string, + utxos: Utxo[], + toAddresses: Uint8Array[], + fromAddressesBytes: Uint8Array[], + options?: SpendOptions, + threshold = 1, + locktime = 0n, +) { + const fromAddresses = addressesFromBytes(fromAddressesBytes); + const defaultedOptions = defaultSpendOptions(fromAddressesBytes, options); + + utxos = utxos.filter( + // Currently - only AVAX is allowed to be imported to the P-chain + (utxo) => utxo.assetId.toString() === context.avaxAssetID, + ); + + const { importedAmounts, importedInputs, inputUTXOs } = + getImportedInputsFromUtxos( + utxos, + fromAddressesBytes, + defaultedOptions.minIssuanceTime, + ); + + const importedAvax = importedAmounts[context.avaxAssetID] ?? 0n; + + importedInputs.sort(TransferableInput.compare); + const addressMaps = AddressMaps.fromTransferableInputs( + importedInputs, + utxos, + defaultedOptions.minIssuanceTime, + fromAddressesBytes, + ); + if (!importedInputs.length) { + throw new Error('no UTXOs available to import'); + } + let inputs: TransferableInput[] = []; + let changeOutputs: TransferableOutput[] = []; + + if (importedAvax < context.baseTxFee) { + const toBurn = new Map([ + [context.avaxAssetID, context.baseTxFee - importedAvax], + ]); + + const spendRes = calculateUTXOSpend( + toBurn, + undefined, + utxos, + fromAddresses, + defaultedOptions, + [useUnlockedUTXOs], + ); + inputs = spendRes.inputs; + changeOutputs = spendRes.changeOutputs; + } else if (importedAvax > context.baseTxFee) { + changeOutputs.push( + TransferableOutput.fromNative( + context.avaxAssetID, + importedAvax - context.baseTxFee, + toAddresses, + locktime, + threshold, + ), + ); + } + + return new UnsignedTx( + new ImportTx( + new AvaxBaseTx( + new Int(context.networkID), + PlatformChainID, + changeOutputs, + inputs, + new Bytes(defaultedOptions.memo), + ), + Id.fromString(sourceChainId), + importedInputs, + ), + inputUTXOs, + addressMaps, + ); +} + +const getToBurn = ( + context: Context, + outputs: TransferableOutput[], + baseFee: bigint, +) => { + const toBurn = new Map([[context.avaxAssetID, baseFee]]); + + outputs.forEach((output) => { + const assetId = output.assetId.value(); + toBurn.set(assetId, (toBurn.get(assetId) || 0n) + output.output.amount()); + }); + return toBurn; +}; + +/** + * Helper function which creates an unsigned [[AddValidatorTx]]. For more granular control, you may create your own + * [[UnsignedTx]] manually and import the [[AddValidatorTx]] class directly. + * + * @deprecated since {@link https://github.com/avalanche-foundation/ACPs/blob/main/ACPs/62-disable-addvalidatortx-and-adddelegatortx.md|Durango-upgrade} + * + * @param utxos A list of UTXOs that the transaction is built on + * @param fromAddresses An array of addresses as uint8Array who own the staking UTXOs the fees in AVAX + * @param nodeID The node ID of the validator being added. + * @param start The Unix time based on p-chain timestamp when the validator starts validating the Primary Network. + * @param end The Unix time based on p-chain timestamp when the validator stops validating the Primary Network (and staked AVAX is returned). + * @param weight The amount being delegated in nAVAX + * @param rewardAddresses The addresses which will recieve the rewards from the delegated stake. + * @param shares A number for the percentage times 10,000 of reward to be given to the validator when someone delegates to them. + * @param threshold Opional. The number of signatures required to spend the funds in the resultant reward UTXO. Default 1. + * @param locktime Optional. The locktime field created in the resulting reward outputs + * + * @returns An unsigned transaction created from the passed in parameters. + */ +export function newAddValidatorTx( + context: Context, + utxos: Utxo[], + fromAddressesBytes: Uint8Array[], + nodeID: string, + start: bigint, + end: bigint, + weight: bigint, + rewardAddresses: Uint8Array[], + shares: number, + options?: SpendOptions, + threshold = 1, + locktime = 0n, +) { + const toBurn = new Map([ + [context.avaxAssetID, context.addPrimaryNetworkValidatorFee], + ]); + const toStake = new Map([[context.avaxAssetID, weight]]); + + const defaultedOptions = defaultSpendOptions(fromAddressesBytes, options); + const { addressMaps, changeOutputs, inputUTXOs, inputs, stakeOutputs } = + calculateUTXOSpend( + toBurn, + toStake, + utxos, + addressesFromBytes(fromAddressesBytes), + defaultedOptions, + [useSpendableLockedUTXOs, useUnlockedUTXOs, useConsolidateOutputs], + ); + + const validatorTx = new AddValidatorTx( + AvaxBaseTx.fromNative( + context.networkID, + context.pBlockchainID, + changeOutputs, + inputs, + defaultedOptions.memo, + ), + Validator.fromNative(nodeID, start, end, weight), + stakeOutputs, + OutputOwners.fromNative(rewardAddresses, locktime, threshold), + new Int(shares), + ); + return new UnsignedTx(validatorTx, inputUTXOs, addressMaps); +} + +/** + * + * @param destinationChainID chain to send the UTXOs to + * @param fromAddressesBytes used for filtering utxos. + * @param utxos list of utxos to choose from + * @param outputs list of outputs to create. + * @param options used for filtering UTXO's + * @returns unsingedTx containing an exportTx + */ + +export function newExportTx( + context: Context, + destinationChainID: string, + fromAddressesBytes: Uint8Array[], + utxos: Utxo[], + outputs: TransferableOutput[], + options?: SpendOptions, +) { + const fromAddresses = addressesFromBytes(fromAddressesBytes); + + const defaultedOptions = defaultSpendOptions(fromAddressesBytes, options); + const toBurn = getToBurn(context, outputs, context.baseTxFee); + + const { inputs, changeOutputs, addressMaps, inputUTXOs } = calculateUTXOSpend( + toBurn, + undefined, + utxos, + fromAddresses, + defaultedOptions, + [useUnlockedUTXOs], + ); + + outputs.sort(compareTransferableOutputs); + return new UnsignedTx( + new ExportTx( + new AvaxBaseTx( + new Int(context.networkID), + PlatformChainID, + changeOutputs, + inputs, + new Bytes(defaultedOptions.memo), + ), + Id.fromString(destinationChainID), + outputs, + ), + inputUTXOs, + addressMaps, + ); +} + +/** + * @deprecated since {@link https://github.com/avalanche-foundation/ACPs/blob/main/ACPs/62-disable-addvalidatortx-and-adddelegatortx.md|Durango-upgrade} + * + * @param utxos list of utxos to choose from + * @param fromAddressesBytes used for filtering utxos + * @param nodeID id of the node to delegate. starts with "NodeID-" + * @param start The Unix time based on p-chain timestamp when the validator starts validating the Primary Network. + * @param end The Unix time based on p-chain timestamp when the validator stops validating the Primary Network (and staked AVAX is returned). + * @param weight The amount being delegated in nAVAX + * @param rewardAddresses The addresses which will recieve the rewards from the delegated stake. + * @param options - used for filtering utxos + * @param threshold Opional. The number of signatures required to spend the funds in the resultant reward UTXO. Default 1. + * @param locktime Optional. The locktime field created in the resulting reward outputs + * @returns UnsingedTx + */ + +export function newAddDelegatorTx( + context: Context, + utxos: Utxo[], + fromAddressesBytes: Uint8Array[], + nodeID: string, + start: bigint, + end: bigint, + weight: bigint, + rewardAddresses: Uint8Array[], + options?: SpendOptions, + threshold = 1, + locktime = 0n, +) { + const toBurn = new Map([ + [context.avaxAssetID, context.addPrimaryNetworkDelegatorFee], + ]); + const toStake = new Map([[context.avaxAssetID, weight]]); + + const defaultedOptions = defaultSpendOptions(fromAddressesBytes, options); + const { inputs, addressMaps, changeOutputs, inputUTXOs, stakeOutputs } = + calculateUTXOSpend( + toBurn, + toStake, + utxos, + addressesFromBytes(fromAddressesBytes), + defaultedOptions, + [useSpendableLockedUTXOs, useUnlockedUTXOs, useConsolidateOutputs], + ); + + const addDelegatorTx = new AddDelegatorTx( + AvaxBaseTx.fromNative( + context.networkID, + context.pBlockchainID, + changeOutputs, + inputs, + defaultedOptions.memo, + ), + Validator.fromNative(nodeID, start, end, weight), + stakeOutputs, + OutputOwners.fromNative(rewardAddresses, locktime, threshold), + ); + return new UnsignedTx(addDelegatorTx, inputUTXOs, addressMaps); +} + +/** + * @see https://docs.avax.network/specs/platform-transaction-serialization#unsigned-create-subnet-tx + * + * @param context + * @param utxos list of utxos to choose from + * @param fromAddressesBytes used for filtering utxos + * @param rewardAddresses The addresses which will recieve the rewards from the delegated stake. + * @param options used for filtering utxos + * @param threshold Opional. The number of signatures required to spend the funds in the resultant reward UTXO. Default 1. + * @param locktime Optional. The locktime field created in the resulting reward outputs + * @returns UnsingedTx + */ +export function newCreateSubnetTx( + context: Context, + utxos: Utxo[], + fromAddressesBytes: Uint8Array[], + subnetOwners: Uint8Array[], + options?: SpendOptions, + threshold = 1, + locktime = 0n, +) { + const defaultedOptions = defaultSpendOptions(fromAddressesBytes, options); + + const { inputs, addressMaps, changeOutputs, inputUTXOs } = calculateUTXOSpend( + new Map([[context.avaxAssetID, context.createSubnetTxFee]]), + undefined, + utxos, + addressesFromBytes(fromAddressesBytes), + defaultedOptions, + [useUnlockedUTXOs], + ); + + const createSubnetTx = new CreateSubnetTx( + AvaxBaseTx.fromNative( + context.networkID, + context.pBlockchainID, + changeOutputs, + inputs, + defaultedOptions.memo, + ), + OutputOwners.fromNative(subnetOwners, locktime, threshold), + ); + + return new UnsignedTx(createSubnetTx, inputUTXOs, addressMaps); +} + +/** + * @see https://docs.avax.network/specs/platform-transaction-serialization#unsigned-create-chain-tx + * + * @param context + * @param utxos list of utxos to choose from + * @param fromAddressesBytes used for filtering utxos + * @param subnetID ID of the Subnet that validates this blockchain + * @param chainName A human readable name for the chain; need not be unique + * @param vmID ID of the VM running on the new chain + * @param fxIds IDs of the feature extensions running on the new chain + * @param genesisData json config for the genesis data + * @param subnetAuth specifies indices of subnet owners + * @param options used for filtering utxos + * @returns UnsignedTx + */ +export function newCreateBlockchainTx( + context: Context, + utxos: Utxo[], + fromAddressesBytes: Uint8Array[], + subnetID: string, + chainName: string, + vmID: string, + fxIds: string[], + genesisData: Record, + subnetAuth: number[], + options?: SpendOptions, +) { + const defaultedOptions = defaultSpendOptions(fromAddressesBytes, options); + + const { inputs, addressMaps, changeOutputs, inputUTXOs } = calculateUTXOSpend( + new Map([[context.avaxAssetID, context.createBlockchainTxFee]]), + undefined, + utxos, + addressesFromBytes(fromAddressesBytes), + defaultedOptions, + [useUnlockedUTXOs], + ); + + const createChainTx = new CreateChainTx( + AvaxBaseTx.fromNative( + context.networkID, + context.pBlockchainID, + changeOutputs, + inputs, + defaultedOptions.memo, + ), + Id.fromString(subnetID), + new Stringpr(chainName), + Id.fromString(vmID), + fxIds.map(Id.fromString.bind(Id)), + new Bytes(new TextEncoder().encode(JSON.stringify(genesisData))), + Input.fromNative(subnetAuth), + ); + + return new UnsignedTx(createChainTx, inputUTXOs, addressMaps); +} + +export function newAddSubnetValidatorTx( + context: Context, + utxos: Utxo[], + fromAddressesBytes: Uint8Array[], + nodeId: string, + start: bigint, + end: bigint, + weight: bigint, + subnetID: string, + subnetAuth: number[], + options?: SpendOptions, +) { + const defaultedOptions = defaultSpendOptions(fromAddressesBytes, options); + + const { inputs, addressMaps, changeOutputs, inputUTXOs } = calculateUTXOSpend( + new Map([[context.avaxAssetID, context.addSubnetValidatorFee]]), + undefined, + utxos, + addressesFromBytes(fromAddressesBytes), + defaultedOptions, + [useUnlockedUTXOs], + ); + + const addSubnetValidatorTx = new AddSubnetValidatorTx( + AvaxBaseTx.fromNative( + context.networkID, + context.pBlockchainID, + changeOutputs, + inputs, + defaultedOptions.memo, + ), + SubnetValidator.fromNative( + nodeId, + start, + end, + weight, + Id.fromString(subnetID), + ), + Input.fromNative(subnetAuth), + ); + + return new UnsignedTx(addSubnetValidatorTx, inputUTXOs, addressMaps); +} +export function newRemoveSubnetValidatorTx( + context: Context, + utxos: Utxo[], + fromAddressesBytes: Uint8Array[], + nodeId: string, + subnetID: string, + subnetAuth: number[], + options?: SpendOptions, +) { + const defaultedOptions = defaultSpendOptions(fromAddressesBytes, options); + + const { inputs, addressMaps, changeOutputs, inputUTXOs } = calculateUTXOSpend( + new Map([[context.avaxAssetID, context.baseTxFee]]), + undefined, + utxos, + addressesFromBytes(fromAddressesBytes), + defaultedOptions, + [useUnlockedUTXOs], + ); + + const removeSubnetValidatorTx = new RemoveSubnetValidatorTx( + AvaxBaseTx.fromNative( + context.networkID, + context.pBlockchainID, + changeOutputs, + inputs, + defaultedOptions.memo, + ), + NodeId.fromString(nodeId), + Id.fromString(subnetID), + Input.fromNative(subnetAuth), + ); + + return new UnsignedTx(removeSubnetValidatorTx, inputUTXOs, addressMaps); +} + +/** + * Helper function which creates an unsigned [[newAddPermissionlessValidatorTx]]. For more granular control, you may create your own + * [[UnsignedTx]] manually and import the [[newAddPermissionlessValidatorTx]] class directly. + * + * @param utxos A list of UTXOs that the transaction is built on + * @param fromAddresses An array of addresses as uint8Array who own the staking UTXOs the fees in AVAX + * @param nodeID The node ID of the validator being added. + * @param subnetID ID of the subnet this validator is validating + * @param start The Unix time based on p-chain timestamp when the validator starts validating the Primary Network. + * @param end The Unix time based on p-chain timestamp when the validator stops validating the Primary Network (and staked AVAX is returned). + * @param weight The amount being locked for validation in nAVAX + * @param rewardAddresses The addresses which will receive the rewards from the delegated stake. Given addresses will share the reward UTXO. + * @param shares A number for the percentage times 10,000 of reward to be given to the validator when someone delegates to them. + * @param threshold Opional. The number of signatures required to spend the funds in the resultant reward UTXO. Default 1. + * @param locktime Optional. The locktime field created in the resulting reward outputs + * @param publicKey the BLS public key, If the subnet is the primary network + * @param signature the BLS signature, If the subnet is the primary network + * @param stakingAssetId Which asset to stake. Defaults to AVAX. + * + * @returns An unsigned transaction created from the passed in parameters. + */ +export function newAddPermissionlessValidatorTx( + context: Context, + utxos: Utxo[], + fromAddressesBytes: Uint8Array[], + nodeID: string, + subnetID: string, + start: bigint, + end: bigint, + weight: bigint, + rewardAddresses: Uint8Array[], + delegatorRewardsOwner: Uint8Array[], + shares: number, + options?: SpendOptions, + threshold = 1, + locktime = 0n, + publicKey?: Uint8Array, + signature?: Uint8Array, + stakingAssetId?: string, +) { + const isPrimaryNetwork = subnetID === PrimaryNetworkID.toString(); + const fee = isPrimaryNetwork + ? context.addPrimaryNetworkValidatorFee + : context.addSubnetValidatorFee; + const toBurn = new Map([[context.avaxAssetID, fee]]); + + const assetId = stakingAssetId ?? context.avaxAssetID; + + // Check if we use correct asset if on primary network + if (isPrimaryNetwork && assetId !== context.avaxAssetID) + throw new Error('Staking asset ID must be AVAX for the primary network.'); + + const toStake = new Map([[assetId, weight]]); + + const defaultedOptions = defaultSpendOptions(fromAddressesBytes, options); + const { addressMaps, changeOutputs, inputUTXOs, inputs, stakeOutputs } = + calculateUTXOSpend( + toBurn, + toStake, + utxos, + addressesFromBytes(fromAddressesBytes), + defaultedOptions, + [useSpendableLockedUTXOs, useUnlockedUTXOs, useConsolidateOutputs], + ); + + const validatorTx = new AddPermissionlessValidatorTx( + AvaxBaseTx.fromNative( + context.networkID, + context.pBlockchainID, + changeOutputs, + inputs, + defaultedOptions.memo, + ), + SubnetValidator.fromNative( + nodeID, + start, + end, + weight, + Id.fromString(subnetID), + ), + createSignerOrSignerEmptyFromStrings(publicKey, signature), + stakeOutputs, + OutputOwners.fromNative(rewardAddresses, locktime, threshold), + OutputOwners.fromNative(delegatorRewardsOwner, 0n), + new Int(shares), + ); + return new UnsignedTx(validatorTx, inputUTXOs, addressMaps); +} + +/** + * Helper function which creates an unsigned [[newAddPermissionlessDelegatorTx]]. For more granular control, you may create your own + * [[UnsignedTx]] manually and import the [[newAddPermissionlessDelegatorTx]] class directly. + * + * @param context The context for the network + * @param utxos A list of UTXOs that the transaction is built on + * @param fromAddressesBytes An array of addresses as uint8Array who own the staking UTXOs the fees in AVAX + * @param nodeID The node ID of the validator being delegated to. + * @param subnetID ID of the subnet being delegated to + * @param start The Unix time based on p-chain timestamp when the delegation starts. + * @param end The Unix time based on p-chain timestamp when the delegation stops (and staked AVAX is returned). + * @param weight The amount being delegated in nAVAX + * @param rewardAddresses The addresses which will receive the rewards from the delegated stake. Given addresses will share the reward UTXO. + * @param threshold Opional. The number of signatures required to spend the funds in the resultant reward UTXO. Default 1. + * @param locktime Optional. The locktime field created in the resulting reward outputs + * @param options Optional. Config for the transaction such as change address, threshold and locktime. + * @param stakingAssetId Optional. Which asset to stake. Defaults to AVAX. + * + * @returns An unsigned transaction created from the passed in parameters. + */ +export function newAddPermissionlessDelegatorTx( + context: Context, + utxos: Utxo[], + fromAddressesBytes: Uint8Array[], + nodeID: string, + subnetID: string, + start: bigint, + end: bigint, + weight: bigint, + rewardAddresses: Uint8Array[], + options?: SpendOptions, + threshold = 1, + locktime = 0n, + stakingAssetId?: string, +) { + const isPrimaryNetwork = subnetID === PrimaryNetworkID.toString(); + const fee = isPrimaryNetwork + ? context.addPrimaryNetworkDelegatorFee + : context.addSubnetDelegatorFee; + + const assetId = stakingAssetId ?? context.avaxAssetID; + + // Check if we use correct asset if on primary network + if (isPrimaryNetwork && assetId !== context.avaxAssetID) + throw new Error('Staking asset ID must be AVAX for the primary network.'); + + const toBurn = new Map([[context.avaxAssetID, fee]]); + const toStake = new Map([[assetId, weight]]); + + const defaultedOptions = defaultSpendOptions(fromAddressesBytes, options); + const { addressMaps, changeOutputs, inputUTXOs, inputs, stakeOutputs } = + calculateUTXOSpend( + toBurn, + toStake, + utxos, + addressesFromBytes(fromAddressesBytes), + defaultedOptions, + [useSpendableLockedUTXOs, useUnlockedUTXOs, useConsolidateOutputs], + ); + + const delegatorTx = new AddPermissionlessDelegatorTx( + AvaxBaseTx.fromNative( + context.networkID, + context.pBlockchainID, + changeOutputs, + inputs, + defaultedOptions.memo, + ), + SubnetValidator.fromNative( + nodeID, + start, + end, + weight, + Id.fromString(subnetID), + ), + stakeOutputs, + OutputOwners.fromNative(rewardAddresses, locktime, threshold), + ); + return new UnsignedTx(delegatorTx, inputUTXOs, addressMaps); +} + +/** + * @param context + * @param utxos list of utxos to choose from + * @param fromAddressesBytes used for filtering utxos + * @param subnetID ID of the subnet + * @param assetID ID of the subnet's staking asset + * @param initialSupply the amount to initially specify as the current supply + * @param maximumSupply the amount to specify as the maximum token supply + * @param minConsumptionRate the rate to allocate funds if the validator's stake duration is 0 + * @param maxConsumptionRate the rate to allocate funds if the validator's stake duration is equal to the minting period + * @param minValidatorStake the minimum amount of funds required to become a validator + * @param maxValidatorStake the maximum amount of funds a single validator can be allocated, including delegated funds + * @param minStakeDuration the minimum number of seconds a staker can stake for + * @param maxStakeDuration the maximum number of seconds a staker can stake for + * @param minDelegationFee the minimum percentage a validator must charge a delegator for delegating + * @param minDelegatorStake the minimum amount of funds required to become a delegator + * @param maxValidatorWeightFactor the factor which calculates the maximum amount of delegation a validator can receive + * @param uptimeRequirement the minimum percentage a validator must be online and responsive to receive a reward + * @param subnetAuth specifies indices of existing subnet owners + * @param options used for filtering utxos + * @returns UnsingedTx containing a TransformSubnetTx + */ +export function newTransformSubnetTx( + context: Context, + utxos: Utxo[], + fromAddressesBytes: Uint8Array[], + subnetID: string, + assetID: string, + initialSupply: bigint, + maximumSupply: bigint, + minConsumptionRate: bigint, + maxConsumptionRate: bigint, + minValidatorStake: bigint, + maxValidatorStake: bigint, + minStakeDuration: number, + maxStakeDuration: number, + minDelegationFee: number, + minDelegatorStake: number, + maxValidatorWeightFactor: number, + uptimeRequirement: number, + subnetAuth: number[], + options?: SpendOptions, +) { + const defaultedOptions = defaultSpendOptions(fromAddressesBytes, options); + + const { inputs, addressMaps, changeOutputs, inputUTXOs } = calculateUTXOSpend( + new Map([[context.avaxAssetID, context.transformSubnetTxFee]]), + undefined, + utxos, + addressesFromBytes(fromAddressesBytes), + defaultedOptions, + [useUnlockedUTXOs], + ); + + return new UnsignedTx( + new TransformSubnetTx( + AvaxBaseTx.fromNative( + context.networkID, + context.pBlockchainID, + changeOutputs, + inputs, + defaultedOptions.memo, + ), + Id.fromString(subnetID), + Id.fromString(assetID), + new BigIntPr(initialSupply), + new BigIntPr(maximumSupply), + new BigIntPr(minConsumptionRate), + new BigIntPr(maxConsumptionRate), + new BigIntPr(minValidatorStake), + new BigIntPr(maxValidatorStake), + new Int(minStakeDuration), + new Int(maxStakeDuration), + new Int(minDelegationFee), + new Int(minDelegatorStake), + new Byte(hexToBuffer(maxValidatorWeightFactor.toString(16))), + new Int(uptimeRequirement), + Input.fromNative(subnetAuth), + ), + inputUTXOs, + addressMaps, + ); +} + +/** + * @param context + * @param utxos list of utxos to choose from + * @param fromAddressesBytes used for filtering utxos + * @param subnetID ID of the subnet + * @param subnetAuth specifies indices of existing subnet owners + * @param subnetOwners The new owner addresses + * @param options used for filtering utxos + * @param threshold Opional. The number of signatures required to spend the funds in the resultant reward UTXO. Default 1. + * @param locktime Optional. The locktime field created in the resulting reward outputs + * @returns UnsingedTx containing a TransferSubnetOwnershipTx + */ +export function newTransferSubnetOwnershipTx( + context: Context, + utxos: Utxo[], + fromAddressesBytes: Uint8Array[], + subnetID: string, + subnetAuth: number[], + subnetOwners: Uint8Array[], + options?: SpendOptions, + threshold = 1, + locktime = 0n, +) { + const defaultedOptions = defaultSpendOptions(fromAddressesBytes, options); + + const { inputs, addressMaps, changeOutputs, inputUTXOs } = calculateUTXOSpend( + new Map([[context.avaxAssetID, context.baseTxFee]]), + undefined, + utxos, + addressesFromBytes(fromAddressesBytes), + defaultedOptions, + [useUnlockedUTXOs], + ); + + return new UnsignedTx( + new TransferSubnetOwnershipTx( + AvaxBaseTx.fromNative( + context.networkID, + context.pBlockchainID, + changeOutputs, + inputs, + defaultedOptions.memo, + ), + Id.fromString(subnetID), + Input.fromNative(subnetAuth), + OutputOwners.fromNative(subnetOwners, locktime, threshold), + ), + inputUTXOs, + addressMaps, + ); +} diff --git a/src/vms/pvm/index.ts b/src/vms/pvm/index.ts new file mode 100644 index 000000000..b83ba1f78 --- /dev/null +++ b/src/vms/pvm/index.ts @@ -0,0 +1,3 @@ +export * from './builder'; +export * from './models'; +export * from './api'; diff --git a/src/vms/pvm/models.ts b/src/vms/pvm/models.ts new file mode 100644 index 000000000..c872972b5 --- /dev/null +++ b/src/vms/pvm/models.ts @@ -0,0 +1,251 @@ +import type { TransferableOutput } from '../../serializable/avax'; +import type { Utxo } from '../../serializable/avax/utxo'; + +export type GetAssetDescriptionResponse = { + assetId: string; + name: string; + symbol: string; + denomination: number; +}; + +export type GetCurrentValidatorsResponse = { + validators: { + accruedDelegateeReward: string; + txID: string; + startTime: string; + endTime: string; + stakeAmount: string; + nodeID: string; + weight: string; + validationRewardOwner: { + locktime: string; + threshold: string; + addresses: string[]; + }; + delegatorCount: string; + delegatorWeight: string; + potentialReward: string; + delegationFee: string; + uptime: string; + connected: boolean; + delegators: { + txID: string; + startTime: string; + endTime: string; + stakeAmount: string; + nodeID: string; + delegationRewardOwner: { + locktime: string; + threshold: string; + addresses: string[]; + }; + potentialReward: string; + }[]; + }[]; +}; + +export type GetPendingValidatorsParams = { + subnetID?: string; + nodeIDs?: string[]; +}; + +export type GetPendingValidatorsResponse = { + validators: { + txID: string; + startTime: string; + endTime: string; + stakeAmount: string; + nodeID: string; + delegationFee: string; + connected: boolean; + weight: string; + }[]; + delegators: { + txID: string; + startTime: string; + endTime: string; + stakeAmount: string; + nodeID: string; + }[]; +}; + +export interface GetRewardUTXOsParams { + txID: string; +} + +export interface GetRewardUTXOsResponse { + numFetched: number; + utxos: Utxo[]; +} + +export interface GetStakeParams { + addresses: string[]; +} + +export interface GetStakeResponse { + staked: bigint; + stakedOutputs: TransferableOutput[]; +} + +export interface GetRewardUTXOsParams { + txID: string; +} + +export interface GetRewardUTXOsResponse { + numFetched: number; + utxos: Utxo[]; +} + +export interface GetValidatorsAtParams { + height: number; + subnetID?: string; +} + +export interface GetValidatorsAtResponse { + validators: object; +} + +export interface GetCurrentValidatorsParams { + subnetID?: Buffer | string; + nodeIDs?: string[]; +} + +export interface SampleValidatorsParams { + size: number; + subnetID?: string; +} + +export interface SampleValidatorsResponse { + validators: string[]; +} + +export interface GetBalanceParams { + addresses: string[]; +} + +export interface GetBalanceResponse { + balance: bigint; + unlocked: bigint; + lockedStakeable: bigint; + lockedNotStakeable: bigint; + utxoIDs: { + txID: string; + outputIndex: number; + }[]; +} + +export interface StartIndex { + address: string; + utxo: string; +} + +export interface Subnet { + ids: string; + controlKeys: string[]; + threshold: number; +} + +export interface Blockchain { + id: string; + name: string; + subnetID: string; + vmID: string; +} + +export interface GetMinStakeResponse { + minValidatorStake: bigint; + minDelegatorStake: bigint; +} + +export interface GetMaxStakeAmountParams { + subnetID?: string; + nodeID: string; + startTime: bigint; + endTime: bigint; +} + +export interface GetTxStatusParams { + txID: string; + includeReason?: boolean; +} + +export interface GetTxStatusResponse { + status: string; + reason: string; +} + +export interface GetCurrentSupplyResponse { + supply: bigint; +} + +export interface GetBalanceResponse { + balance: bigint; + unlocked: bigint; + lockedStakeable: bigint; + lockedNotStakeable: bigint; + utxoIDs: { + txID: string; + outputIndex: number; + }[]; +} + +export interface GetBlockchainsResponse { + blockchains: { + id: string; + name: string; + subnetID: string; + vmID: string; + }[]; +} + +export interface GetBlockchainStatusResponse { + status: string; +} + +export interface GetHeightResponse { + height: number; +} + +export interface GetStakingAssetIDParams { + subnetID: string; +} + +export interface GetStakingAssetIDResponse { + assetID: string; +} + +export interface GetSubnetsParams { + ids: string[]; +} + +export interface GetSubnetsResponse { + subnets: { + id: string; + controlKeys: string[]; + threshold: string; + }[]; +} + +export interface GetTimestampResponse { + timestamp: string; +} + +export interface GetTotalStakeResponse { + weight: string; +} + +export interface ValidatedByParams { + blockchainID: string; +} + +export interface ValidatedByResponse { + subnetID: string; +} + +export interface ValidatesParams { + subnetID: string; +} + +export interface ValidatesResponse { + blockchainIDs: string[]; +} diff --git a/src/vms/pvm/privateModels.ts b/src/vms/pvm/privateModels.ts new file mode 100644 index 000000000..c9b559d04 --- /dev/null +++ b/src/vms/pvm/privateModels.ts @@ -0,0 +1,17 @@ +/* + models in this file are intermediate and not meant to be exported externally +*/ + +export interface GetRewardUTXOsServerResponse { + numFetched: number; + utxos: string[]; +} + +export interface GetStakeServerResponse { + staked: bigint; + stakedOutputs: string[]; +} + +export interface GetTxServerResponse { + tx: any; +} diff --git a/src/vms/pvm/utxoCalculationFns/index.ts b/src/vms/pvm/utxoCalculationFns/index.ts new file mode 100644 index 000000000..8e9e9ca84 --- /dev/null +++ b/src/vms/pvm/utxoCalculationFns/index.ts @@ -0,0 +1,3 @@ +export * from './useSpendableLockedUTXOs'; +export * from './useUnlockedUTXOs'; +export * from './useConsolidateOutputs'; diff --git a/src/vms/pvm/utxoCalculationFns/useConsolidateOutputs.ts b/src/vms/pvm/utxoCalculationFns/useConsolidateOutputs.ts new file mode 100644 index 000000000..6f9867992 --- /dev/null +++ b/src/vms/pvm/utxoCalculationFns/useConsolidateOutputs.ts @@ -0,0 +1,17 @@ +import { consolidateOutputs } from '../../utils/consolidateOutputs'; +import type { UTXOCalculationState } from '../../utils/calculateSpend'; + +export function useConsolidateOutputs({ + changeOutputs, + stakeOutputs, + ...state +}: UTXOCalculationState): UTXOCalculationState { + const consolidatedChangeOutputs = consolidateOutputs(changeOutputs); + const consolidatedStakeOutputs = consolidateOutputs(stakeOutputs); + + return { + ...state, + changeOutputs: consolidatedChangeOutputs, + stakeOutputs: consolidatedStakeOutputs, + }; +} diff --git a/src/vms/pvm/utxoCalculationFns/useSpendableLockedUTXOs.spec.ts b/src/vms/pvm/utxoCalculationFns/useSpendableLockedUTXOs.spec.ts new file mode 100644 index 000000000..9380d69d4 --- /dev/null +++ b/src/vms/pvm/utxoCalculationFns/useSpendableLockedUTXOs.spec.ts @@ -0,0 +1,139 @@ +import { Id } from '../../../serializable/fxs/common'; +import { testContext } from '../../../fixtures/context'; +import { + fromAddressBytes, + testUTXOID1, + getStakeableLockoutOutput, + testUTXOID2, +} from '../../../fixtures/transactions'; +import { addressesFromBytes } from '../../../utils'; +import { useSpendableLockedUTXOs } from './useSpendableLockedUTXOs'; +import { defaultSpendResult } from '../../utils/calculateSpend'; +import type { StakeableLockOut } from '../../../serializable/pvm'; + +describe('src/vms/pvm/spend/useSpendableLockedUTXOs.spec.ts', () => { + it('Should do nothing if stakeable output is not locked anymore', () => { + const stakeableUtxoAmt1 = 600000000n; + const stakeableUtxoAmt2 = 700000000n; + const amountRemainingToStake = 500000000n; + const lockTime = 1n; + + const { amountsToStake, changeOutputs, inputs } = useSpendableLockedUTXOs({ + amountsToBurn: new Map(), + ...defaultSpendResult(), + utxos: [ + getStakeableLockoutOutput(testUTXOID1, stakeableUtxoAmt1, lockTime), + getStakeableLockoutOutput(testUTXOID2, stakeableUtxoAmt2, lockTime), + ], + fromAddresses: addressesFromBytes(fromAddressBytes), + amountsToStake: new Map([ + [testContext.avaxAssetID, amountRemainingToStake], + ]), // amount remaining to stake + options: { minIssuanceTime: lockTime * 2n } as any, + }); + + expect(changeOutputs.length).toEqual(0); + expect(inputs.length).toEqual(0); + expect(amountsToStake.get(testContext.avaxAssetID)).toEqual( + amountRemainingToStake, + ); + }); + + it('Should have a remaining stakeable amount and has no change', () => { + const stakeableUtxoAmt1 = 200000000n; + const stakeableUtxoAmt2 = 100000000n; + const amountRemainingToStake = 500000000n; + + const { amountsToStake, changeOutputs } = useSpendableLockedUTXOs({ + amountsToBurn: new Map(), + ...defaultSpendResult(), + utxos: [ + getStakeableLockoutOutput(testUTXOID1, stakeableUtxoAmt1), + getStakeableLockoutOutput(testUTXOID2, stakeableUtxoAmt2), + ], + fromAddresses: addressesFromBytes(fromAddressBytes), + amountsToStake: new Map([ + [testContext.avaxAssetID, amountRemainingToStake], + ]), // amount remaining to stake + options: { minIssuanceTime: 0n } as any, + }); + + expect(changeOutputs.length).toEqual(0); + expect(amountsToStake.get(testContext.avaxAssetID)).toEqual( + amountRemainingToStake - stakeableUtxoAmt1 - stakeableUtxoAmt2, + ); + }); + + it('Should have no remaining stakeable amount and change', () => { + const stakeableUtxoAmt1 = 200000000n; + const stakeableUtxoAmt2 = 400000000n; + const amountRemainingToStake = 500000000n; + + const { amountsToStake, changeOutputs, inputs, inputUTXOs } = + useSpendableLockedUTXOs({ + amountsToBurn: new Map(), + ...defaultSpendResult(), + utxos: [ + getStakeableLockoutOutput(testUTXOID1, stakeableUtxoAmt1), + getStakeableLockoutOutput(testUTXOID2, stakeableUtxoAmt2), + ], + fromAddresses: addressesFromBytes(fromAddressBytes), + amountsToStake: new Map([ + [testContext.avaxAssetID, amountRemainingToStake], + ]), // amount remaining to stake + options: { minIssuanceTime: 0 } as any, + }); + + expect(changeOutputs.length).toEqual(1); + expect(changeOutputs[0].amount()).toEqual( + stakeableUtxoAmt1 + stakeableUtxoAmt2 - amountRemainingToStake, + ); + expect(amountsToStake.get(testContext.avaxAssetID)).toEqual(0n); + + expect(inputs).toHaveLength(2); + expect(inputs[0].utxoID.txID).toEqual(testUTXOID1); + expect(inputs[0].amount()).toEqual(stakeableUtxoAmt1); + expect(inputs[1].utxoID.txID).toEqual(testUTXOID2); + expect(inputs[1].amount()).toEqual(stakeableUtxoAmt2); + + expect(inputUTXOs).toHaveLength(2); + expect(inputUTXOs[0].utxoId.txID).toEqual(testUTXOID1); + expect( + (inputUTXOs[0].output as StakeableLockOut).transferOut.amount(), + ).toEqual(stakeableUtxoAmt1); + expect(inputUTXOs[1].utxoId.txID).toEqual(testUTXOID2); + expect( + (inputUTXOs[1].output as StakeableLockOut).transferOut.amount(), + ).toEqual(stakeableUtxoAmt2); + }); + + it('Should not be affected by assets with different asset id', () => { + const stakeableUtxoAmt1 = 200000000n; + const stakeableUtxoAmt2 = 400000000n; + const amountRemainingToStake = 500000000n; + + const { amountsToStake, changeOutputs } = useSpendableLockedUTXOs({ + amountsToBurn: new Map(), + ...defaultSpendResult(), + utxos: [ + getStakeableLockoutOutput(testUTXOID1, stakeableUtxoAmt1), + getStakeableLockoutOutput( + testUTXOID1, + stakeableUtxoAmt2, + undefined, + Id.fromString('1'), + ), + ], + fromAddresses: addressesFromBytes(fromAddressBytes), + amountsToStake: new Map([ + [testContext.avaxAssetID, amountRemainingToStake], + ]), // amount remaining to stake + options: { minIssuanceTime: 0 } as any, + }); + + expect(changeOutputs.length).toEqual(0); + expect(amountsToStake.get(testContext.avaxAssetID)).toEqual( + amountRemainingToStake - stakeableUtxoAmt1, + ); + }); +}); diff --git a/src/vms/pvm/utxoCalculationFns/useSpendableLockedUTXOs.ts b/src/vms/pvm/utxoCalculationFns/useSpendableLockedUTXOs.ts new file mode 100644 index 000000000..7924de498 --- /dev/null +++ b/src/vms/pvm/utxoCalculationFns/useSpendableLockedUTXOs.ts @@ -0,0 +1,119 @@ +import { verifySignaturesMatch } from '../../../vms/utils/calculateSpend/utils'; +import { + TransferableOutput, + TransferOutput, + TransferableInput, + TransferInput, +} from '../../../serializable'; +import { BigIntPr } from '../../../serializable/primitives'; +import { StakeableLockOut, StakeableLockIn } from '../../../serializable/pvm'; +import { isStakeableLockOut } from '../../../utils'; +import { bigIntMin } from '../../../utils/bigintMath'; +import type { UTXOCalculationState } from '../../utils/calculateSpend'; + +function createTransferableInput(utxo, lockedOutput, out, sigData) { + return new TransferableInput( + utxo.utxoId, + utxo.assetId, + new StakeableLockIn( + lockedOutput.lockTime, + TransferInput.fromNative(out.amount(), sigData.sigIndicies), + ), + ); +} + +function createTransferableOutput(utxo, lockedOutput, out, amt) { + return new TransferableOutput( + utxo.assetId, + new StakeableLockOut( + lockedOutput.lockTime, + new TransferOutput(new BigIntPr(amt), out.outputOwners), + ), + ); +} + +export function useSpendableLockedUTXOs({ + amountsToBurn, + utxos, + fromAddresses, + amountsToStake, + options, + changeOutputs, + inputUTXOs, + inputs, + stakeOutputs, + ...state +}: UTXOCalculationState): UTXOCalculationState { + const usableUTXOs = utxos + .filter((utxo) => { + const out = utxo.output; + if (!isStakeableLockOut(out)) { + return false; + } + return options.minIssuanceTime < out.getLocktime(); + }) + .map((utxo) => { + const assetId = utxo.assetId.value(); + // If this is 0n then either we are not staking any of this asset or the amount left to stak is zero + const remainingAmountToStake = amountsToStake.get(assetId) ?? 0n; + const lockedOutput = utxo.output as StakeableLockOut; + return { utxo, assetId, remainingAmountToStake, lockedOutput }; + }) + .filter(({ remainingAmountToStake }) => { + return !!remainingAmountToStake; + }) + .filter(({ lockedOutput }) => { + if (!(lockedOutput.transferOut instanceof TransferOutput)) { + throw new Error('unknown output type'); + } + + return options.minIssuanceTime < lockedOutput.lockTime.value(); + }); + verifySignaturesMatch( + usableUTXOs, + ({ lockedOutput }) => { + return lockedOutput.transferOut as TransferOutput; + }, + fromAddresses, + options, + ).forEach(({ sigData, data: { utxo, assetId, lockedOutput } }) => { + const out = lockedOutput.transferOut as TransferOutput; + const remainingAmountToStake = amountsToStake.get(assetId) ?? 0n; + + // if we have already reached the stake amount then there is nothing left to run beyond here + if (!remainingAmountToStake) return; + + inputs.push(createTransferableInput(utxo, lockedOutput, out, sigData)); + + inputUTXOs.push(utxo); + + // check if this UTXO value is greater than the amount left to stake + const amountToStake = bigIntMin(remainingAmountToStake, out.amt.value()); + + stakeOutputs.push( + createTransferableOutput(utxo, lockedOutput, out, amountToStake), + ); + // update the remaining stake amount minus this UTXOs value + amountsToStake.set(assetId, remainingAmountToStake - amountToStake); + const remainingAmount = out.amount() - amountToStake; + + if (remainingAmount > 0n) { + changeOutputs.push( + createTransferableOutput(utxo, lockedOutput, out, remainingAmount), + ); + } + }); + + return { + ...state, + amountsToBurn, + utxos, + fromAddresses, + amountsToStake, + options, + changeOutputs, + inputUTXOs, + inputs, + stakeOutputs, + }; +} diff --git a/src/vms/pvm/utxoCalculationFns/useUnlockedUTXOs.spec.ts b/src/vms/pvm/utxoCalculationFns/useUnlockedUTXOs.spec.ts new file mode 100644 index 000000000..e3e122204 --- /dev/null +++ b/src/vms/pvm/utxoCalculationFns/useUnlockedUTXOs.spec.ts @@ -0,0 +1,26 @@ +import { fromAddressBytes, getValidUtxo } from '../../../fixtures/transactions'; +import { addressesFromBytes } from '../../../utils'; +import { testContext } from '../../../fixtures/context'; +import { useUnlockedUTXOs } from './useUnlockedUTXOs'; +import { BigIntPr } from '../../../serializable/primitives'; +import { defaultSpendResult } from '../../utils/calculateSpend'; + +describe('src/vms/pvm/spend/useUnlockedUTXOs.spec.ts', () => { + it('Should pay gas and stake amount plus have some change', () => { + const { changeOutputs, stakeOutputs, amountsToBurn } = useUnlockedUTXOs({ + ...defaultSpendResult(), + amountsToBurn: new Map([[testContext.avaxAssetID, 4900n]]), + utxos: [getValidUtxo(new BigIntPr(10000n))], + fromAddresses: addressesFromBytes(fromAddressBytes), + amountsToStake: new Map([[testContext.avaxAssetID, 4900n]]), + options: { changeAddresses: fromAddressBytes } as any, + }); + expect(changeOutputs.length).toEqual(1); + expect(BigInt(changeOutputs[0].output.amount())).toEqual(BigInt(200n)); + + expect(stakeOutputs.length).toEqual(1); + expect(BigInt(stakeOutputs[0].output.amount())).toEqual(BigInt(4900n)); + + expect(amountsToBurn.get(testContext.avaxAssetID)).toEqual(0n); + }); +}); diff --git a/src/vms/pvm/utxoCalculationFns/useUnlockedUTXOs.ts b/src/vms/pvm/utxoCalculationFns/useUnlockedUTXOs.ts new file mode 100644 index 000000000..58144ac48 --- /dev/null +++ b/src/vms/pvm/utxoCalculationFns/useUnlockedUTXOs.ts @@ -0,0 +1,138 @@ +import { verifySignaturesMatch } from '../../../vms/utils/calculateSpend/utils'; +import { + TransferableOutput, + TransferOutput, + TransferableInput, + TransferInput, + OutputOwners, +} from '../../../serializable'; +import { BigIntPr, Int } from '../../../serializable/primitives'; +import type { StakeableLockOut } from '../../../serializable/pvm'; +import { + isTransferOut, + isStakeableLockOut, + addressesFromBytes, +} from '../../../utils'; +import { bigIntMin } from '../../../utils/bigintMath'; +import type { UTXOCalculationState } from '../../utils/calculateSpend'; + +export function useUnlockedUTXOs({ + amountsToBurn, + utxos, + fromAddresses, + amountsToStake, + options, + changeOutputs, + inputUTXOs, + inputs, + stakeOutputs, + ...state +}: UTXOCalculationState): UTXOCalculationState { + const changeOwner = new OutputOwners( + new BigIntPr(0n), + new Int(1), + addressesFromBytes(options.changeAddresses), + ); + const usableUTXOs = utxos.filter((utxo) => { + if (isTransferOut(utxo.output)) { + return true; + } + const out = utxo.output; + if (!isStakeableLockOut(out) || !isTransferOut(out.transferOut)) { + return false; + } + return out.getLocktime() < options.minIssuanceTime; + }); + + verifySignaturesMatch( + usableUTXOs, + (utxo) => { + return ( + isTransferOut(utxo.output) + ? utxo.output + : (utxo.output as StakeableLockOut).transferOut + ) as TransferOutput; + }, + fromAddresses, + options, + ).forEach(({ sigData, data: utxo }) => { + const remainingAmountToBurn = amountsToBurn.get(utxo.assetId.value()) ?? 0n; + + const remainingAmountToStake = + amountsToStake.get(utxo.assetId.value()) ?? 0n; + + if (!remainingAmountToBurn && !remainingAmountToStake) { + return; + } + + const utxoTransferout = ( + isTransferOut(utxo.output) + ? utxo.output + : (utxo.output as StakeableLockOut).transferOut + ) as TransferOutput; + + inputs.push( + new TransferableInput( + utxo.utxoId, + utxo.assetId, + TransferInput.fromNative(utxoTransferout.amount(), sigData.sigIndicies), + ), + ); + + inputUTXOs.push(utxo); + + const amountToBurn = bigIntMin( + remainingAmountToBurn, + utxoTransferout.amt.value(), + ); + + amountsToBurn.set( + utxo.assetId.value(), + remainingAmountToBurn - amountToBurn, + ); + + const amountAvailableToStake = utxoTransferout.amount() - amountToBurn; + + const amountToStake = bigIntMin( + remainingAmountToStake, + amountAvailableToStake, + ); + + amountsToStake.set( + utxo.assetId.value(), + (amountsToStake.get(utxo.assetId.value()) ?? 0n) - amountToStake, + ); + + if (amountToStake > 0n) { + stakeOutputs.push( + new TransferableOutput( + utxo.assetId, + new TransferOutput(new BigIntPr(amountToStake), changeOwner), + ), + ); + } + + const remainingAmount = amountAvailableToStake - amountToStake; + if (remainingAmount > 0) { + changeOutputs.push( + new TransferableOutput( + utxo.assetId, + new TransferOutput(new BigIntPr(remainingAmount), changeOwner), + ), + ); + } + }); + + return { + ...state, + amountsToBurn, + utxos, + fromAddresses, + amountsToStake, + options, + changeOutputs, + inputUTXOs, + inputs, + stakeOutputs, + }; +} diff --git a/src/vms/utils/calculateSpend/calculateSpend.spec.ts b/src/vms/utils/calculateSpend/calculateSpend.spec.ts new file mode 100644 index 000000000..9f6517c0c --- /dev/null +++ b/src/vms/utils/calculateSpend/calculateSpend.spec.ts @@ -0,0 +1,205 @@ +import { BigIntPr, Int } from '../../../serializable/primitives'; +import { testContext } from '../../../fixtures/context'; +import { + fromAddressBytes, + getLockedUTXO, + getStakeableLockoutOutput, + getValidUtxo, + testAvaxAssetID, + testUTXOID1, + testUTXOID2, + testUTXOID3, + testUtxos, +} from '../../../fixtures/transactions'; +import { addressesFromBytes } from '../../../utils'; +import { calculateUTXOSpend } from './calculateSpend'; +import { + useSpendableLockedUTXOs, + useUnlockedUTXOs, +} from '../../pvm/utxoCalculationFns'; +import { compareTransferableOutputs } from '../../../utils/sort'; +import { + OutputOwners, + TransferableOutput, + TransferInput, + TransferOutput, +} from '../../../serializable'; +import { TransferableInput } from '../../../serializable'; +import { Address, Id } from '../../../serializable/fxs/common'; +import { NoSigMatchError } from './utils'; +import { useAvmAndCorethUTXOs } from '../../../vms/avm/utxoCalculationFns'; +import type { StakeableLockOut } from '../../../serializable/pvm'; +import { StakeableLockIn } from '../../../serializable/pvm'; +import { UTXOID } from '../../../serializable/avax'; + +describe('src/vms/pvm/spend/calculateSpend.spec.ts', () => { + it('should pay down burn and stake from utxos', () => { + const burnAmount = 100n; + const unlockedUTXOAmount = 200n; + const stakeAmount = 1000000n; + + const stakeAmount1 = 500000n; + const stakeAmount2 = 600000n; + const lockTime1 = BigInt(Math.floor(new Date().getTime() / 1000)) + 100000n; + const lockTime2 = BigInt(Math.floor(new Date().getTime() / 1000)) + 200000n; + + const { stakeOutputs, changeOutputs, inputs } = calculateUTXOSpend( + new Map([[testContext.avaxAssetID, burnAmount]]), + new Map([[testContext.avaxAssetID, stakeAmount]]), + [ + getValidUtxo(new BigIntPr(unlockedUTXOAmount)), + getStakeableLockoutOutput(testUTXOID1, stakeAmount1, lockTime1), + getStakeableLockoutOutput(testUTXOID2, stakeAmount2, lockTime2), + ], + addressesFromBytes(fromAddressBytes), + { changeAddresses: fromAddressBytes, minIssuanceTime: 0n } as any, + [useSpendableLockedUTXOs, useUnlockedUTXOs], + ); + + const getExpectedStakeOut = (lockTime: bigint, amount: bigint) => + new TransferableOutput( + testAvaxAssetID, + getStakeableLockoutOutput( + Id.fromHex(''), // does not matter, we only need the output of the UTXO + amount, + lockTime, + ).output as StakeableLockOut, + ); + + const getExpectedStakeInput = ( + utxoID: UTXOID, + amount: bigint, + lockTime: bigint, + ) => + new TransferableInput( + utxoID, + testAvaxAssetID, + new StakeableLockIn( + new BigIntPr(lockTime), + TransferInput.fromNative(amount, [0]), + ), + ); + + // sorted stake outputs + expect(stakeOutputs.length).toEqual(2); + + expect(stakeOutputs[0]).toStrictEqual( + getExpectedStakeOut(lockTime1, 500000n), + ); + expect(stakeOutputs[1]).toStrictEqual( + getExpectedStakeOut(lockTime2, 500000n), + ); + + // sorted inputs + expect(inputs.length).toEqual(3); + + expect(inputs[0]).toStrictEqual( + getExpectedStakeInput( + new UTXOID(testUTXOID1, new Int(0)), + stakeAmount1, + lockTime1, + ), + ); + expect(inputs[1]).toStrictEqual( + new TransferableInput( + new UTXOID(testUTXOID3, new Int(0)), + testAvaxAssetID, + TransferInput.fromNative(unlockedUTXOAmount, [0]), + ), + ); + expect(inputs[2]).toStrictEqual( + getExpectedStakeInput( + new UTXOID(testUTXOID2, new Int(0)), + stakeAmount2, + lockTime2, + ), + ); + + // sorted change outputs + expect(changeOutputs.length).toEqual(2); + + expect(changeOutputs[0]).toStrictEqual( + new TransferableOutput( + testAvaxAssetID, + new TransferOutput( + new BigIntPr(unlockedUTXOAmount - burnAmount), + new OutputOwners( + new BigIntPr(0n), + new Int(1), + addressesFromBytes(fromAddressBytes), + ), + ), + ), + ); + expect(changeOutputs[1]).toStrictEqual( + getExpectedStakeOut(lockTime2, stakeAmount1 + stakeAmount2 - stakeAmount), + ); + }); + it('Should verify if the changeOutputs, inputs and stakeOutputs have been sorted', () => { + const burnAmount = 100n; + const unlockedUTXOAmount = 200n; + const lockedUTXOAmount = 1000000n; + const stakeUTXOAmount = 1000000n; + + const { stakeOutputs, changeOutputs, inputs } = calculateUTXOSpend( + new Map([[testContext.avaxAssetID, burnAmount]]), + new Map([[testContext.avaxAssetID, stakeUTXOAmount]]), + [ + getValidUtxo(new BigIntPr(unlockedUTXOAmount)), + getLockedUTXO(new BigIntPr(lockedUTXOAmount)), + ], + addressesFromBytes(fromAddressBytes), + { changeAddresses: fromAddressBytes } as any, + [useSpendableLockedUTXOs, useUnlockedUTXOs], + ); + + expect(stakeOutputs).toEqual( + [...stakeOutputs].sort(compareTransferableOutputs), + ); + expect(changeOutputs).toEqual( + [...changeOutputs].sort(compareTransferableOutputs), + ); + expect(inputs).toEqual([...inputs].sort(TransferableInput.compare)); + }); + + it('Should throw an error when the UTXO owner "fromAddress" doesnt match any UTXOs', () => { + const tryUseFunctionAndThrowMismatchError = (useFn: (() => any)[]) => { + return calculateUTXOSpend( + new Map([[testContext.avaxAssetID, 100n]]), + new Map([[testContext.avaxAssetID, 10000n]]), + [ + getValidUtxo(new BigIntPr(10000n)), + getLockedUTXO(new BigIntPr(10000n)), + getStakeableLockoutOutput(testUTXOID1, 300n), + getStakeableLockoutOutput(testUTXOID2, 10000n), + ...testUtxos(), + ], + // use random address that doesnt belong to any utxos we have in the test + addressesFromBytes([ + Address.fromString( + 'X-fuji1xwdz5ca4pl443ghm6ez63m7yr64wu6u7qhksa2', + ).toBytes(), + ]), + { + changeAddresses: fromAddressBytes, + minIssuanceTime: 1000000000000n, + } as any, + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + [...useFn], + ); + }; + + function catchAndEqualNoSigMatch(useFns) { + try { + tryUseFunctionAndThrowMismatchError(useFns); + } catch (err) { + expect(err).toEqual(NoSigMatchError); + } + } + + catchAndEqualNoSigMatch([useUnlockedUTXOs]); + catchAndEqualNoSigMatch([useSpendableLockedUTXOs, useUnlockedUTXOs]); + catchAndEqualNoSigMatch([useAvmAndCorethUTXOs]); + }); +}); diff --git a/src/vms/utils/calculateSpend/calculateSpend.ts b/src/vms/utils/calculateSpend/calculateSpend.ts new file mode 100644 index 000000000..9bbaf0736 --- /dev/null +++ b/src/vms/utils/calculateSpend/calculateSpend.ts @@ -0,0 +1,131 @@ +import { TransferableInput } from '../../../serializable'; +import type { Utxo } from '../../../serializable/avax/utxo'; +import type { Address } from '../../../serializable/fxs/common'; +import { AddressMaps } from '../../../utils/addressMap'; +import { compareTransferableOutputs } from '../../../utils/sort'; +import type { SpendOptionsRequired } from '../../common'; +import type { UTXOCalculationFn, UTXOCalculationResult } from './models'; + +export const defaultSpendResult = (): UTXOCalculationResult => ({ + inputs: [], + inputUTXOs: [], + stakeOutputs: [], + changeOutputs: [], + addressMaps: new AddressMaps(), +}); + +/** + * Make sure that the next state recieves a deep copy so that it cant mutate state. This is great if we need to + * diagnose where something was changed. We can view state by state by putting logs between state cycles. + * + * @param state the state from previous action function + * @returns UTXOCalculationResult + */ +function deepCopyState(state) { + return { + ...state, + amountsToBurn: new Map([...state.amountsToBurn]), + amountsToStake: new Map([...state.amountsToStake]), + inputs: [...state.inputs], + inputUTXOs: [...state.inputUTXOs], + stakeOutputs: [...state.stakeOutputs], + changeOutputs: [...state.changeOutputs], + }; +} +/** + * The idea here is a iterator style UTXO operator function system. Pass in the UTXOs and all of its operating functions. Each + * function takes into account the state and performs its state changes. The next function is given a copy of the previous + * and makes it updates. This way there is no mutations between functions but we can see from function to function what changes + * were made if needed. + * + * In the very near future we can break the operator functions into much smaller chunks and have very precise operators instead of one + * operator that deals with unlocked tokens for burn and stake and inputs all in one + * + * @param amountsToBurn + * @param utxos + * @param amountsToStake + * @param fromAddresses + * @param options + * @param utxoParsers + * @returns + */ +export function calculateUTXOSpend( + amountsToBurn = new Map(), + amountsToStake = new Map(), + utxos: Utxo[], + fromAddresses: Address[], + options: SpendOptionsRequired, + utxoCalculationFns: [UTXOCalculationFn, ...UTXOCalculationFn[]], +): UTXOCalculationResult { + const startState = { + amountsToBurn, + utxos, + amountsToStake, + fromAddresses, + options, + ...defaultSpendResult(), + }; + const result = ( + [ + ...utxoCalculationFns, + function verifyAmountToBurnIsFulfilled({ amountsToBurn, ...state }) { + amountsToBurn.forEach((amount, assetId) => { + if (amount !== 0n) { + throw new Error( + `insufficient funds (Burn Amount): need ${amount} more units of ${assetId} to burn`, + ); + } + }); + + return { amountsToBurn, ...state }; + }, + function verifyAmountToStateIsFulfilled({ amountsToStake, ...state }) { + amountsToStake.forEach((amount, assetId) => { + if (amount !== 0n) { + throw new Error( + `insufficient funds (Stake Amount): need ${amount} more units of ${assetId} to stake`, + ); + } + }); + + return { amountsToStake, ...state }; + }, + function sortTransferableInputs({ inputs, ...state }) { + inputs.sort(TransferableInput.compare); + return { inputs, ...state }; + }, + function sortChangeOutputs({ changeOutputs, ...state }) { + changeOutputs.sort(compareTransferableOutputs); + return { changeOutputs, ...state }; + }, + function sortStakeOutputs({ stakeOutputs, ...state }) { + stakeOutputs.sort(compareTransferableOutputs); + return { stakeOutputs, ...state }; + }, + function getAdressMaps({ inputs, inputUTXOs, ...state }) { + const addressMaps = AddressMaps.fromTransferableInputs( + inputs, + inputUTXOs, + options.minIssuanceTime, + fromAddresses.map((add) => add.toBytes()), + ); + return { inputs, inputUTXOs, ...state, addressMaps }; + }, + ] as UTXOCalculationFn[] + ).reduce((state, next) => { + // to prevent mutation we deep copy the arrays and maps before passing off to + // the next operator + return next(deepCopyState(state)); + }, startState); + const { + /* eslint-disable @typescript-eslint/no-unused-vars */ + amountsToBurn: _amountsToBurn, + amountsToStake: _amountsToStake, + fromAddresses: _fromAddresses, + options: _options, + utxos: _utxos, + /* eslint-enable @typescript-eslint/no-unused-vars */ + ...calculationResults + } = result; + return calculationResults; +} diff --git a/src/vms/utils/calculateSpend/index.ts b/src/vms/utils/calculateSpend/index.ts new file mode 100644 index 000000000..c3241a2fc --- /dev/null +++ b/src/vms/utils/calculateSpend/index.ts @@ -0,0 +1,2 @@ +export * from './calculateSpend'; +export * from './models'; diff --git a/src/vms/utils/calculateSpend/models.ts b/src/vms/utils/calculateSpend/models.ts new file mode 100644 index 000000000..510494a6f --- /dev/null +++ b/src/vms/utils/calculateSpend/models.ts @@ -0,0 +1,28 @@ +import type { Utxo } from '../../../serializable/avax/utxo'; +import type { + TransferableOutput, + TransferableInput, +} from '../../../serializable'; +import type { Address } from '../../../serializable/fxs/common'; +import type { SpendOptionsRequired } from '../../common'; +import type { AddressMaps } from '../../../utils/addressMap'; + +export interface UTXOCalculationResult { + inputs: TransferableInput[]; + inputUTXOs: Utxo[]; + stakeOutputs: TransferableOutput[]; + changeOutputs: TransferableOutput[]; + addressMaps: AddressMaps; +} + +export interface UTXOCalculationState extends UTXOCalculationResult { + amountsToBurn: Map; + utxos: Utxo[]; + fromAddresses: Address[]; + amountsToStake: Map; + options: SpendOptionsRequired; +} + +export type UTXOCalculationFn = ( + values: UTXOCalculationState, +) => UTXOCalculationState; diff --git a/src/vms/utils/calculateSpend/utils/index.ts b/src/vms/utils/calculateSpend/utils/index.ts new file mode 100644 index 000000000..b0e65c2d4 --- /dev/null +++ b/src/vms/utils/calculateSpend/utils/index.ts @@ -0,0 +1 @@ +export * from './verifySignaturesMatch'; diff --git a/src/vms/utils/calculateSpend/utils/verifySignaturesMatch.ts b/src/vms/utils/calculateSpend/utils/verifySignaturesMatch.ts new file mode 100644 index 000000000..31159cb8a --- /dev/null +++ b/src/vms/utils/calculateSpend/utils/verifySignaturesMatch.ts @@ -0,0 +1,44 @@ +import type { MatchOwnerResult } from '../../../../utils/matchOwners'; +import { matchOwners } from '../../../../utils/matchOwners'; +import type { TransferOutput } from '../../../../serializable'; + +export type verifySigMatchItem = Required<{ + sigData: MatchOwnerResult; + data: T; +}>; + +export const NoSigMatchError = new Error('No addresses match UTXO owners'); + +/** + * The idea here is to verify that a given set of utxos contains any utxos that share addresses + * with the fromAddresses array. If not we should be throwing an error as the tx is being formulated + * incoreectly + * + * @param set the utxo or data set, this can change depening on the calcFn + * @param getTransferOutput a callback that takes a utxo and gets the output + * @param fromAddresses the addresses the utxos should belong to + * @param options + * @returns T[] + */ +export function verifySignaturesMatch( + set: T[], + getTransferOutput: (utxo: T) => TransferOutput, + fromAddresses, + options, +): verifySigMatchItem[] { + const outs = set.reduce((acc, data) => { + const out = getTransferOutput(data); + + const sigData = matchOwners( + out.outputOwners, + fromAddresses, + options.minIssuanceTime, + ); + + return sigData ? [...acc, { sigData, data }] : acc; + }, [] as verifySigMatchItem[]); + + if (set.length && !outs.length) throw NoSigMatchError; + + return outs; +} diff --git a/src/vms/utils/consolidateOutputs.spec.ts b/src/vms/utils/consolidateOutputs.spec.ts new file mode 100644 index 000000000..0654ec179 --- /dev/null +++ b/src/vms/utils/consolidateOutputs.spec.ts @@ -0,0 +1,175 @@ +import { isStakeableLockOut, isTransferOut } from '../../utils'; +import { + getStakeableLockedTransferableOutForTest, + getTransferableOutForTest, +} from '../../fixtures/transactions'; + +import { consolidateOutputs } from './consolidateOutputs'; + +describe('consolidateOutputs', () => { + it('consolidate eligible TransferOuts', () => { + // GIVEN + const a = getTransferableOutForTest(BigInt(100)); + const b = getTransferableOutForTest(BigInt(50)); + const c = getTransferableOutForTest(BigInt(50)); + + // WHEN + const consolidated = consolidateOutputs([a, b, c]); + + // THEN + expect(consolidated.length).toEqual(1); + const conslidatedOutput = consolidated[0]; + expect(conslidatedOutput.amount()).toEqual(BigInt(200)); + expect(conslidatedOutput.getAssetId()).toEqual(a.getAssetId()); + if (isTransferOut(conslidatedOutput.output) && isTransferOut(a.output)) { + expect( + conslidatedOutput.output.outputOwners.equals(a.output.outputOwners), + ).toBeTruthy(); + } else { + fail( + 'The consolidated output and first test output should both be transferOuts.', + ); + } + }); + it('consolidates eligible StakeableLockouts', () => { + // GIVEN + const a = getStakeableLockedTransferableOutForTest(BigInt(100), BigInt(0)); + const b = getStakeableLockedTransferableOutForTest(BigInt(200), BigInt(0)); + const c = getStakeableLockedTransferableOutForTest(BigInt(200), BigInt(0)); + + // WHEN + const consolidated = consolidateOutputs([a, b, c]); + + // THEN + expect(consolidated.length).toEqual(1); + const conslidatedOutput = consolidated[0]; + expect(conslidatedOutput.amount()).toEqual(BigInt(500)); + expect(conslidatedOutput.getAssetId()).toEqual(a.getAssetId()); + if ( + isStakeableLockOut(conslidatedOutput.output) && + isStakeableLockOut(a.output) + ) { + expect(conslidatedOutput.output.getLocktime()).toEqual( + a.output.getLocktime(), + ); + expect( + conslidatedOutput.output + .getOutputOwners() + .equals(a.output.getOutputOwners()), + ).toBeTruthy(); + } else { + fail( + 'The consolidated output and first test output should both be stakeableLockouts.', + ); + } + }); + it('consolidates heterogenous inputs', () => { + // GIVEN + const tOutA = getTransferableOutForTest(BigInt(50)); + const tOutB = getTransferableOutForTest(BigInt(100)); + const stlOutA = getStakeableLockedTransferableOutForTest( + BigInt(100), + BigInt(0), + ); + const stlOutB = getStakeableLockedTransferableOutForTest( + BigInt(200), + BigInt(0), + ); + + // WHEN + const consolidated = consolidateOutputs([tOutA, tOutB, stlOutA, stlOutB]); + + // THEN + expect(consolidated.length).toEqual(2); + // THEN - TransferOut + expect(consolidated[0].amount()).toEqual(BigInt(150)); + expect(consolidated[0].getAssetId()).toEqual(tOutA.getAssetId()); + if (isTransferOut(consolidated[0].output) && isTransferOut(tOutA.output)) { + expect( + consolidated[0].output.outputOwners.equals(tOutA.output.outputOwners), + ).toBeTruthy(); + } else { + fail( + 'The consolidated output and first test output should both be transferOuts.', + ); + } + // THEN - StakeableLockouts + expect(consolidated[1].amount()).toEqual(BigInt(300)); + if ( + isStakeableLockOut(consolidated[1].output) && + isStakeableLockOut(stlOutA.output) + ) { + expect(consolidated[1].output.getLocktime()).toEqual( + stlOutA.output.getLocktime(), + ); + expect( + consolidated[1].output + .getOutputOwners() + .equals(stlOutA.output.getOutputOwners()), + ).toBeTruthy(); + } else { + fail( + 'The consolidated output and third test output should both be stakeableLockouts.', + ); + } + }); + it('does not consolidate ineligible TransferOuts - locktime', () => { + // GIVEN + const a = getTransferableOutForTest(BigInt(50)); + const b = getTransferableOutForTest(BigInt(50), BigInt(100)); + + // WHEN + const consolidated = consolidateOutputs([a, b]); + + // THEN + expect(consolidated.length).toEqual(2); + expect(consolidated[0]).toBe(a); + expect(consolidated[1]).toBe(b); + }); + it('does not consolidate ineligible TransferOuts - threshold', () => { + // GIVEN + const a = getTransferableOutForTest(BigInt(50), BigInt(100), 2); + const b = getTransferableOutForTest(BigInt(50), BigInt(100), 1); + + // WHEN + const consolidated = consolidateOutputs([a, b]); + + // THEN + expect(consolidated.length).toEqual(2); + expect(consolidated[0]).toBe(a); + expect(consolidated[1]).toBe(b); + }); + it('does not consolidate ineligible StakeableLockouts - locktime', () => { + // GIVEN + const a = getStakeableLockedTransferableOutForTest(BigInt(100), BigInt(0)); + const b = getStakeableLockedTransferableOutForTest( + BigInt(200), + BigInt(100), + ); + + // WHEN + const consolidated = consolidateOutputs([a, b]); + + // THEN + expect(consolidated.length).toEqual(2); + expect(consolidated[0]).toBe(a); + expect(consolidated[1]).toBe(b); + }); + it('handles empty arrays gracefully', () => { + // WHEN + const consolidated = consolidateOutputs([]); + // THEN + expect(consolidated.length).toEqual(0); + }); + it('handles single output gracefully', () => { + // GIVEN + const a = getStakeableLockedTransferableOutForTest(BigInt(100), BigInt(0)); + + // WHEN + const consolidated = consolidateOutputs([a]); + + // THEN + expect(consolidated.length).toEqual(1); + expect(consolidated[0]).toBe(a); + }); +}); diff --git a/src/vms/utils/consolidateOutputs.ts b/src/vms/utils/consolidateOutputs.ts new file mode 100644 index 000000000..4f7d6f714 --- /dev/null +++ b/src/vms/utils/consolidateOutputs.ts @@ -0,0 +1,52 @@ +import { isStakeableLockOut, isTransferOut } from '../../utils'; +import { + TransferableOutput, + TransferOutput, + BigIntPr, + pvmSerial, +} from '../../serializable'; +import { consolidate } from '../../utils/consolidate'; + +const canCombine = (a: TransferableOutput, b: TransferableOutput) => { + return ( + a.getAssetId() === b.getAssetId() && + ((isStakeableLockOut(a.output) && + isStakeableLockOut(b.output) && + a.output.getStakeableLocktime() === b.output.getStakeableLocktime() && + a.output.getOutputOwners().equals(b.output.getOutputOwners())) || + (isTransferOut(a.output) && + isTransferOut(b.output) && + a.output.outputOwners.equals(b.output.outputOwners))) + ); +}; + +const combine = (a: TransferableOutput, b: TransferableOutput) => { + if (isStakeableLockOut(a.output) && isStakeableLockOut(b.output)) { + return new TransferableOutput( + a.assetId, + new pvmSerial.StakeableLockOut( + a.output.lockTime, + new TransferOutput( + new BigIntPr(a.amount() + b.amount()), + a.output.getOutputOwners(), + ), + ), + ); + } else if (isTransferOut(a.output) && isTransferOut(b.output)) { + return new TransferableOutput( + a.assetId, + new TransferOutput( + new BigIntPr(a.amount() + b.amount()), + a.output.outputOwners, + ), + ); + } else { + throw new Error('Calling combine on incompatible TransferableOutputs'); + } +}; + +export const consolidateOutputs = ( + outputs: TransferableOutput[], +): TransferableOutput[] => { + return consolidate(outputs, canCombine, combine); +}; diff --git a/tests/apis/admin/api.test.ts b/tests/apis/admin/api.test.ts deleted file mode 100644 index 0cee1f1e5..000000000 --- a/tests/apis/admin/api.test.ts +++ /dev/null @@ -1,248 +0,0 @@ -import mockAxios from "jest-mock-axios" -import { HttpResponse } from "jest-mock-axios/dist/lib/mock-axios-types" -import { Avalanche } from "src" -import { - GetLoggerLevelResponse, - LoadVMsResponse, - SetLoggerLevelResponse -} from "src/apis/admin/interfaces" -import { AdminAPI } from "../../../src/apis/admin/api" - -describe("Admin", (): void => { - const ip: string = "127.0.0.1" - const port: number = 9650 - const protocol: string = "https" - const avalanche: Avalanche = new Avalanche( - ip, - port, - protocol, - 12345, - "What is my purpose? You pass butter. Oh my god.", - undefined, - undefined, - false - ) - let admin: AdminAPI - - beforeAll((): void => { - admin = avalanche.Admin() - }) - - afterEach((): void => { - mockAxios.reset() - }) - - test("alias", async (): Promise => { - const ep: string = "/ext/something" - const al: string = "/ext/anotherthing" - const result: Promise = admin.alias(ep, al) - const payload: object = { - result: { - success: true - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: boolean = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(true) - }) - - test("aliasChain", async (): Promise => { - const ch: string = "abcd" - const al: string = "myChain" - const result: Promise = admin.aliasChain(ch, al) - const payload: object = { - result: { - success: true - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: boolean = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(true) - }) - - test("badAliasChain", async (): Promise => { - const ch: any = 2 - const al: string = "myChasdfasdfasain" - const result: Promise = admin.aliasChain(ch, al) - const payload: object = { - result: { - success: false - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: boolean = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response["success"]).toBe(false) - }) - - test("getChainAliases", async (): Promise => { - const ch: string = "chain" - const result: Promise = admin.getChainAliases(ch) - const payload: object = { - result: { - aliases: ["alias1", "alias2"] - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string[] = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - // @ts-ignore - expect(response).toBe(payload.result.aliases) - }) - - test("getLoggerLevel", async (): Promise => { - const result: Promise = admin.getLoggerLevel() - const payload: object = { - result: { - loggerLevels: { C: { logLevel: "DEBUG", displayLevel: "ERROR" } } - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: GetLoggerLevelResponse = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - // @ts-ignore - expect(response).toBe(payload.result) - }) - - test("loadVMs", async (): Promise => { - const result: Promise = admin.loadVMs() - const payload: object = { - result: { newVMs: {} } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: LoadVMsResponse = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - // @ts-ignore - expect(response).toBe(payload.result) - }) - - test("lockProfile", async () => { - const result: Promise = admin.lockProfile() - const payload: object = { - result: { - success: true - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: boolean = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(true) - }) - - test("memoryProfile", async (): Promise => { - const result: Promise = admin.memoryProfile() - const payload: object = { - result: { - success: true - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: boolean = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(true) - }) - - test("setLoggerLevel", async (): Promise => { - const loggerName: string = "C" - const logLevel: string = "DEBUG" - const displayLevel: string = "INFO" - const result: Promise = admin.setLoggerLevel( - loggerName, - logLevel, - displayLevel - ) - const payload: object = { - result: { - success: true - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: SetLoggerLevelResponse = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - // @ts-ignore - expect(response).toBe(payload.result) - }) - - test("startCPUProfiler", async (): Promise => { - const result: Promise = admin.startCPUProfiler() - const payload: object = { - result: { - success: true - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: boolean = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(true) - }) - - test("stopCPUProfiler", async (): Promise => { - const result: Promise = admin.stopCPUProfiler() - const payload: object = { - result: { - success: true - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: boolean = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(true) - }) -}) diff --git a/tests/apis/auth/api.test.ts b/tests/apis/auth/api.test.ts deleted file mode 100644 index 8b037bf89..000000000 --- a/tests/apis/auth/api.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import mockAxios from "jest-mock-axios" -import { HttpResponse } from "jest-mock-axios/dist/lib/mock-axios-types" -import { Avalanche } from "src" -import { AuthAPI } from "../../../src/apis/auth/api" -import { ErrorResponseObject } from "../../../src/utils/errors" - -describe("Auth", (): void => { - const ip: string = "127.0.0.1" - const port: number = 9650 - const protocol: string = "https" - const avalanche: Avalanche = new Avalanche( - ip, - port, - protocol, - 12345, - "What is my purpose? You pass butter. Oh my god.", - undefined, - undefined, - false - ) - let auth: AuthAPI - - // We think we're a Rick, but we're totally a Jerry. - let password: string = - "Weddings are basically funerals with a cake. -- Rich Sanchez" - let newPassword: string = - "Sometimes science is more art than science, Morty. -- Rich Sanchez" - let testToken: string = - "To live is to risk it all otherwise you're just an inert chunk of randomly assembled molecules drifting wherever the universe blows you. -- Rick Sanchez" - let testEndpoints: string[] = ["/ext/opt/bin/bash/foo", "/dev/null", "/tmp"] - - beforeAll((): void => { - auth = avalanche.Auth() - }) - - afterEach((): void => { - mockAxios.reset() - }) - - test("newToken", async (): Promise => { - const result: Promise = auth.newToken( - password, - testEndpoints - ) - const payload: object = { - result: { - token: testToken - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string | ErrorResponseObject = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(testToken) - }) - - test("revokeToken", async (): Promise => { - const result: Promise = auth.revokeToken(password, testToken) - const payload: object = { - result: { - success: true - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: boolean = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(true) - }) - - test("changePassword", async (): Promise => { - const result: Promise = auth.changePassword(password, newPassword) - const payload: object = { - result: { - success: false - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: boolean = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(false) - }) -}) diff --git a/tests/apis/avm/api.test.ts b/tests/apis/avm/api.test.ts deleted file mode 100644 index 7ac09a0da..000000000 --- a/tests/apis/avm/api.test.ts +++ /dev/null @@ -1,2130 +0,0 @@ -import mockAxios from "jest-mock-axios" -import { Avalanche } from "src" -import { AVMAPI } from "../../../src/apis/avm/api" -import { KeyPair, KeyChain } from "../../../src/apis/avm/keychain" -import { Buffer } from "buffer/" -import BN from "bn.js" -import BinTools from "../../../src/utils/bintools" -import { UTXOSet, UTXO } from "../../../src/apis/avm/utxos" -import { - TransferableInput, - SECPTransferInput -} from "../../../src/apis/avm/inputs" -import createHash from "create-hash" -import { UnsignedTx, Tx } from "../../../src/apis/avm/tx" -import { AVMConstants } from "../../../src/apis/avm/constants" -import { - TransferableOutput, - SECPTransferOutput, - NFTMintOutput, - NFTTransferOutput, - SECPMintOutput -} from "../../../src/apis/avm/outputs" -import { - NFTTransferOperation, - TransferableOperation, - SECPMintOperation -} from "../../../src/apis/avm/ops" -import * as bech32 from "bech32" -import { UTF8Payload } from "../../../src/utils/payload" -import { InitialStates } from "../../../src/apis/avm/initialstates" -import { Defaults } from "../../../src/utils/constants" -import { UnixNow } from "../../../src/utils/helperfunctions" -import { OutputOwners } from "../../../src/common/output" -import { MinterSet } from "../../../src/apis/avm/minterset" -import { PlatformChainID } from "../../../src/utils/constants" -import { PersistanceOptions } from "../../../src/utils/persistenceoptions" -import { ONEAVAX } from "../../../src/utils/constants" -import { - Serializable, - Serialization, - SerializedEncoding, - SerializedType -} from "../../../src/utils/serialization" -import { HttpResponse } from "jest-mock-axios/dist/lib/mock-axios-types" -import { - GetBalanceResponse, - SendMultipleResponse, - SendResponse -} from "src/apis/avm/interfaces" -import { CENTIAVAX } from "src/utils" -import { MILLIAVAX } from "src/utils" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serialization: Serialization = Serialization.getInstance() -const dumpSerailization: boolean = false -const display: SerializedEncoding = "display" - -const serialzeit = (aThing: Serializable, name: string): void => { - if (dumpSerailization) { - console.log( - JSON.stringify( - serialization.serialize(aThing, "avm", "hex", name + " -- Hex Encoded") - ) - ) - console.log( - JSON.stringify( - serialization.serialize( - aThing, - "avm", - "display", - name + " -- Human-Readable" - ) - ) - ) - } -} - -describe("AVMAPI", (): void => { - const networkID: number = 1337 - const blockchainID: string = Defaults.network[networkID].X.blockchainID - const ip: string = "127.0.0.1" - const port: number = 9650 - const protocol: string = "https" - - const username: string = "AvaLabs" - const password: string = "password" - - const avalanche: Avalanche = new Avalanche( - ip, - port, - protocol, - networkID, - undefined, - undefined, - undefined, - true - ) - let api: AVMAPI - let alias: string - - const addrA: string = `X-${bech32.bech32.encode( - avalanche.getHRP(), - bech32.bech32.toWords( - bintools.cb58Decode("B6D4v1VtPYLbiUvYXtW4Px8oE9imC2vGW") - ) - )}` - const addrB: string = `X-${bech32.bech32.encode( - avalanche.getHRP(), - bech32.bech32.toWords( - bintools.cb58Decode("P5wdRuZeaDt28eHMP5S3w9ZdoBfo7wuzF") - ) - )}` - const addrC: string = `X-${bech32.bech32.encode( - avalanche.getHRP(), - bech32.bech32.toWords( - bintools.cb58Decode("6Y3kysjF9jnHnYkdS9yGAuoHyae2eNmeV") - ) - )}` - - beforeAll((): void => { - api = new AVMAPI(avalanche, "/ext/bc/X", blockchainID) - alias = api.getBlockchainAlias() - }) - - afterEach((): void => { - mockAxios.reset() - }) - - test("fails to send with incorrect username", async (): Promise => { - const memo: string = "hello world" - const incorrectUserName: string = "asdfasdfsa" - const message: string = `problem retrieving user: incorrect password for user "${incorrectUserName}"` - const result: Promise = api.send( - incorrectUserName, - password, - "assetId", - 10, - addrA, - [addrB], - addrA, - memo - ) - - const payload: object = { - result: { - code: -32000, - message, - data: null - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: object = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response["code"]).toBe(-32000) - expect(response["message"]).toBe(message) - }) - - test("fails to send with incorrect Password", async (): Promise => { - const memo: string = "hello world" - const incorrectPassword: string = "asdfasdfsa" - const message: string = `problem retrieving user: incorrect password for user "${incorrectPassword}"` - const result: Promise = api.send( - username, - incorrectPassword, - "assetId", - 10, - addrA, - [addrB], - addrA, - memo - ) - - const payload: object = { - result: { - code: -32000, - message, - data: null - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: object = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response["code"]).toBe(-32000) - expect(response["message"]).toBe(message) - }) - - test("can Send 1", async (): Promise => { - const txId: string = "asdfhvl234" - const memo: string = "hello world" - const changeAddr: string = "X-local1" - const result: Promise = api.send( - username, - password, - "assetId", - 10, - addrA, - [addrB], - addrA, - memo - ) - const payload: object = { - result: { - txID: txId, - changeAddr: changeAddr - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: object = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response["txID"]).toBe(txId) - expect(response["changeAddr"]).toBe(changeAddr) - }) - - test("can Send 2", async (): Promise => { - const txId: string = "asdfhvl234" - const memo: Buffer = Buffer.from("hello world") - const changeAddr: string = "X-local1" - const result: Promise = api.send( - username, - password, - bintools.b58ToBuffer("6h2s5de1VC65meajE1L2PjvZ1MXvHc3F6eqPCGKuDt4MxiweF"), - new BN(10), - addrA, - [addrB], - addrA, - memo - ) - const payload: object = { - result: { - txID: txId, - changeAddr: changeAddr - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: object = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response["txID"]).toBe(txId) - expect(response["changeAddr"]).toBe(changeAddr) - }) - - test("can Send Multiple", async (): Promise => { - const txId: string = "asdfhvl234" - const memo: string = "hello world" - const changeAddr: string = "X-local1" - const result: Promise = api.sendMultiple( - username, - password, - [{ assetID: "assetId", amount: 10, to: addrA }], - [addrB], - addrA, - memo - ) - const payload: object = { - result: { - txID: txId, - changeAddr: changeAddr - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: SendMultipleResponse = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response["txID"]).toBe(txId) - expect(response["changeAddr"]).toBe(changeAddr) - }) - - test("refreshBlockchainID", async (): Promise => { - const n3bcID: string = Defaults.network[3].X["blockchainID"] - const n1337bcID: string = Defaults.network[1337].X["blockchainID"] - const testAPI: AVMAPI = new AVMAPI(avalanche, "/ext/bc/avm", n3bcID) - const bc1: string = testAPI.getBlockchainID() - expect(bc1).toBe(n3bcID) - - testAPI.refreshBlockchainID() - const bc2: string = testAPI.getBlockchainID() - expect(bc2).toBe(n1337bcID) - - testAPI.refreshBlockchainID(n3bcID) - const bc3: string = testAPI.getBlockchainID() - expect(bc3).toBe(n3bcID) - }) - - test("listAddresses", async (): Promise => { - const addresses = [addrA, addrB] - const result: Promise = api.listAddresses(username, password) - const payload: object = { - result: { - addresses - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string[] = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(addresses) - }) - - test("importKey", async (): Promise => { - const address = addrC - const result: Promise = api.importKey(username, password, "key") - const payload: object = { - result: { - address - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(address) - }) - - test("getBalance", async (): Promise => { - const balance: BN = new BN("100", 10) - const respobj: GetBalanceResponse = { - balance, - utxoIDs: [ - { - txID: "LUriB3W919F84LwPMMw4sm2fZ4Y76Wgb6msaauEY7i1tFNmtv", - outputIndex: 0 - } - ] - } - - const result: Promise = api.getBalance(addrA, "ATH") - const payload: object = { - result: respobj - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: object = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(JSON.stringify(response)).toBe(JSON.stringify(respobj)) - }) - - test("getBalance includePartial", async (): Promise => { - const balance: BN = new BN("100", 10) - const respobj = { - balance, - utxoIDs: [ - { - txID: "LUriB3W919F84LwPMMw4sm2fZ4Y76Wgb6msaauEY7i1tFNmtv", - outputIndex: 0 - } - ] - } - - const result: Promise = api.getBalance( - addrA, - "ATH", - true - ) - const payload: object = { - result: respobj - } - const responseObj: HttpResponse = { - data: payload - } - - const expectedRequestPayload = { - id: 1, - method: "avm.getBalance", - params: { - address: addrA, - assetID: "ATH", - includePartial: true - }, - jsonrpc: "2.0" - } - - mockAxios.mockResponse(responseObj) - const response: object = await result - const calledWith: object = { - baseURL: "https://127.0.0.1:9650", - data: '{"id":9,"method":"avm.getBalance","params":{"address":"X-custom1d6kkj0qh4wcmus3tk59npwt3rluc6en755a58g","assetID":"ATH","includePartial":true},"jsonrpc":"2.0"}', - headers: { - "Content-Type": "application/json;charset=UTF-8" - }, - method: "POST", - params: {}, - responseType: "json", - url: "/ext/bc/X" - } - - expect(mockAxios.request).toBeCalledWith(calledWith) - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(JSON.stringify(response)).toBe(JSON.stringify(respobj)) - }) - - test("exportKey", async (): Promise => { - const key: string = "sdfglvlj2h3v45" - - const result: Promise = api.exportKey(username, password, addrA) - const payload: object = { - result: { - privateKey: key - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(key) - }) - - test("export", async (): Promise => { - const amount: BN = new BN(100) - const to: string = "abcdef" - const assetID: string = "AVAX" - const username: string = "Robert" - const password: string = "Paulson" - const txID: string = "valid" - const result: Promise = api.export( - username, - password, - to, - amount, - assetID - ) - const payload: object = { - result: { - txID: txID - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(txID) - }) - - test("import", async (): Promise => { - const to: string = "abcdef" - const username: string = "Robert" - const password: string = "Paulson" - const txID: string = "valid" - const result: Promise = api.import( - username, - password, - to, - blockchainID - ) - const payload: object = { - result: { - txID: txID - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(txID) - }) - - test("createAddress", async (): Promise => { - const alias: string = "randomalias" - - const result: Promise = api.createAddress(username, password) - const payload: object = { - result: { - address: alias - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(alias) - }) - - test("createFixedCapAsset", async (): Promise => { - const kp: KeyPair = new KeyPair(avalanche.getHRP(), alias) - kp.importKey( - Buffer.from( - "ef9bf2d4436491c153967c9709dd8e82795bdb9b5ad44ee22c2903005d1cf676", - "hex" - ) - ) - - const denomination: number = 0 - const assetID: string = - "8a5d2d32e68bc50036e4d086044617fe4a0a0296b274999ba568ea92da46d533" - const initialHolders: object[] = [ - { - address: "7sik3Pr6r1FeLrvK1oWwECBS8iJ5VPuSh", - amount: "10000" - }, - { - address: "7sik3Pr6r1FeLrvK1oWwECBS8iJ5VPuSh", - amount: "50000" - } - ] - - const result: Promise = api.createFixedCapAsset( - username, - password, - "Some Coin", - "SCC", - denomination, - initialHolders - ) - const payload: object = { - result: { - assetID: assetID - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(assetID) - }) - - test("createVariableCapAsset", async () => { - const kp: KeyPair = new KeyPair(avalanche.getHRP(), alias) - kp.importKey( - Buffer.from( - "ef9bf2d4436491c153967c9709dd8e82795bdb9b5ad44ee22c2903005d1cf676", - "hex" - ) - ) - - const denomination: number = 0 - const assetID: string = - "8a5d2d32e68bc50036e4d086044617fe4a0a0296b274999ba568ea92da46d533" - const minterSets: object[] = [ - { - minters: ["4peJsFvhdn7XjhNF4HWAQy6YaJts27s9q"], - threshold: 1 - }, - { - minters: [ - "dcJ6z9duLfyQTgbjq2wBCowkvcPZHVDF", - "2fE6iibqfERz5wenXE6qyvinsxDvFhHZk", - "7ieAJbfrGQbpNZRAQEpZCC1Gs1z5gz4HU" - ], - threshold: 2 - } - ] - - const result: Promise = api.createVariableCapAsset( - username, - password, - "Some Coin", - "SCC", - denomination, - minterSets - ) - const payload: object = { - result: { - assetID: assetID - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(assetID) - }) - - test("mint 1", async (): Promise => { - const username: string = "Collin" - const password: string = "Cusce" - const amount: number = 2 - const assetID: string = - "f966750f438867c3c9828ddcdbe660e21ccdbb36a9276958f011ba472f75d4e7" - const to: string = "dcJ6z9duLfyQTgbjq2wBCowkvcPZHVDF" - const minters: string[] = [ - "dcJ6z9duLfyQTgbjq2wBCowkvcPZHVDF", - "2fE6iibqfERz5wenXE6qyvinsxDvFhHZk", - "7ieAJbfrGQbpNZRAQEpZCC1Gs1z5gz4HU" - ] - const result: Promise = api.mint( - username, - password, - amount, - assetID, - to, - minters - ) - const payload: object = { - result: { - txID: "sometx" - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe("sometx") - }) - - test("mint 2", async (): Promise => { - const username: string = "Collin" - const password: string = "Cusce" - const amount: BN = new BN(1) - const assetID: Buffer = Buffer.from( - "f966750f438867c3c9828ddcdbe660e21ccdbb36a9276958f011ba472f75d4e7", - "hex" - ) - const to: string = "dcJ6z9duLfyQTgbjq2wBCowkvcPZHVDF" - const minters: string[] = [ - "dcJ6z9duLfyQTgbjq2wBCowkvcPZHVDF", - "2fE6iibqfERz5wenXE6qyvinsxDvFhHZk", - "7ieAJbfrGQbpNZRAQEpZCC1Gs1z5gz4HU" - ] - const result: Promise = api.mint( - username, - password, - amount, - assetID, - to, - minters - ) - const payload: object = { - result: { - txID: "sometx" - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe("sometx") - }) - - test("getTx", async (): Promise => { - const txid: string = - "f966750f438867c3c9828ddcdbe660e21ccdbb36a9276958f011ba472f75d4e7" - - const result: Promise = api.getTx(txid) - const payload: object = { - result: { - tx: "sometx" - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string | object = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe("sometx") - }) - - test("getTxStatus", async (): Promise => { - const txid: string = - "f966750f438867c3c9828ddcdbe660e21ccdbb36a9276958f011ba472f75d4e7" - - const result: Promise = api.getTxStatus(txid) - const payload: object = { - result: { - status: "accepted" - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe("accepted") - }) - - test("getAssetDescription as string", async () => { - const assetID: Buffer = Buffer.from( - "8a5d2d32e68bc50036e4d086044617fe4a0a0296b274999ba568ea92da46d533", - "hex" - ) - const assetidstr: string = bintools.cb58Encode(assetID) - - const result: Promise = api.getAssetDescription(assetidstr) - const payload: object = { - result: { - name: "Collin Coin", - symbol: "CKC", - assetID: assetidstr, - denomination: "10" - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: any = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response.name).toBe("Collin Coin") - expect(response.symbol).toBe("CKC") - expect(response.assetID.toString("hex")).toBe(assetID.toString("hex")) - expect(response.denomination).toBe(10) - }) - - test("getAssetDescription as Buffer", async (): Promise => { - const assetID: Buffer = Buffer.from( - "8a5d2d32e68bc50036e4d086044617fe4a0a0296b274999ba568ea92da46d533", - "hex" - ) - const assetidstr: string = bintools.cb58Encode( - Buffer.from( - "8a5d2d32e68bc50036e4d086044617fe4a0a0296b274999ba568ea92da46d533", - "hex" - ) - ) - - const result: Promise = api.getAssetDescription(assetID) - const payload: object = { - result: { - name: "Collin Coin", - symbol: "CKC", - assetID: assetidstr, - denomination: "11" - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: any = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response.name).toBe("Collin Coin") - expect(response.symbol).toBe("CKC") - expect(response.assetID.toString("hex")).toBe(assetID.toString("hex")) - expect(response.denomination).toBe(11) - }) - - test("getUTXOs", async (): Promise => { - // Payment - const OPUTXOstr1: string = bintools.cb58Encode( - Buffer.from( - "000038d1b9f1138672da6fb6c35125539276a9acc2a668d63bea6ba3c795e2edb0f5000000013e07e38e2f23121be8756412c18db7246a16d26ee9936f3cba28be149cfd3558000000070000000000004dd500000000000000000000000100000001a36fd0c2dbcab311731dde7ef1514bd26fcdc74d", - "hex" - ) - ) - const OPUTXOstr2: string = bintools.cb58Encode( - Buffer.from( - "0000c3e4823571587fe2bdfc502689f5a8238b9d0ea7f3277124d16af9de0d2d9911000000003e07e38e2f23121be8756412c18db7246a16d26ee9936f3cba28be149cfd355800000007000000000000001900000000000000000000000100000001e1b6b6a4bad94d2e3f20730379b9bcd6f176318e", - "hex" - ) - ) - const OPUTXOstr3: string = bintools.cb58Encode( - Buffer.from( - "0000f29dba61fda8d57a911e7f8810f935bde810d3f8d495404685bdb8d9d8545e86000000003e07e38e2f23121be8756412c18db7246a16d26ee9936f3cba28be149cfd355800000007000000000000001900000000000000000000000100000001e1b6b6a4bad94d2e3f20730379b9bcd6f176318e", - "hex" - ) - ) - - const set: UTXOSet = new UTXOSet() - set.add(OPUTXOstr1) - set.addArray([OPUTXOstr2, OPUTXOstr3]) - - const persistOpts: PersistanceOptions = new PersistanceOptions( - "test", - true, - "union" - ) - expect(persistOpts.getMergeRule()).toBe("union") - let addresses: string[] = set - .getAddresses() - .map((a) => api.addressFromBuffer(a)) - let result: Promise<{ - numFetched: number - utxos: UTXOSet - endIndex: { address: string; utxo: string } - }> = api.getUTXOs( - addresses, - api.getBlockchainID(), - 0, - undefined, - persistOpts - ) - const payload: object = { - result: { - numFetched: 3, - utxos: [OPUTXOstr1, OPUTXOstr2, OPUTXOstr3], - stopIndex: { address: "a", utxo: "b" } - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - let response: UTXOSet = (await result).utxos - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(JSON.stringify(response.getAllUTXOStrings().sort())).toBe( - JSON.stringify(set.getAllUTXOStrings().sort()) - ) - - addresses = set.getAddresses().map((a) => api.addressFromBuffer(a)) - result = api.getUTXOs( - addresses, - api.getBlockchainID(), - 0, - undefined, - persistOpts - ) - - mockAxios.mockResponse(responseObj) - response = (await result).utxos - - expect(mockAxios.request).toHaveBeenCalledTimes(2) - expect(JSON.stringify(response.getAllUTXOStrings().sort())).toBe( - JSON.stringify(set.getAllUTXOStrings().sort()) - ) - }) - - describe("Transactions", (): void => { - let set: UTXOSet - let keymgr2: KeyChain - let keymgr3: KeyChain - let addrs1: string[] - let addrs2: string[] - let addrs3: string[] - let addressbuffs: Buffer[] = [] - let addresses: string[] = [] - let utxos: UTXO[] - let inputs: TransferableInput[] - let outputs: TransferableOutput[] - let ops: TransferableOperation[] - let amnt: number = 10000 - const assetID: Buffer = Buffer.from( - createHash("sha256").update("mary had a little lamb").digest() - ) - const NFTassetID: Buffer = Buffer.from( - createHash("sha256") - .update( - "I can't stand it, I know you planned it, I'mma set straight this Watergate." - ) - .digest() - ) - let secpbase1: SECPTransferOutput - let secpbase2: SECPTransferOutput - let secpbase3: SECPTransferOutput - let initialState: InitialStates - let nftpbase1: NFTMintOutput - let nftpbase2: NFTMintOutput - let nftpbase3: NFTMintOutput - let nftInitialState: InitialStates - let nftutxoids: string[] = [] - let fungutxoids: string[] = [] - let avm: AVMAPI - const fee: number = 10 - const name: string = "Mortycoin is the dumb as a sack of hammers." - const symbol: string = "morT" - const denomination: number = 8 - - let secpMintOut1: SECPMintOutput - let secpMintOut2: SECPMintOutput - let secpMintTXID: Buffer - let secpMintUTXO: UTXO - let secpMintXferOut1: SECPTransferOutput - let secpMintXferOut2: SECPTransferOutput - let secpMintOp: SECPMintOperation - - let xfersecpmintop: TransferableOperation - - beforeEach(async (): Promise => { - avm = new AVMAPI(avalanche, "/ext/bc/X", blockchainID) - - const result: Promise = avm.getAVAXAssetID(true) - const payload: object = { - result: { - name, - symbol, - assetID: bintools.cb58Encode(assetID), - denomination: denomination - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - await result - set = new UTXOSet() - avm.newKeyChain() - keymgr2 = new KeyChain(avalanche.getHRP(), alias) - keymgr3 = new KeyChain(avalanche.getHRP(), alias) - addrs1 = [] - addrs2 = [] - addrs3 = [] - utxos = [] - inputs = [] - outputs = [] - ops = [] - nftutxoids = [] - fungutxoids = [] - const pload: Buffer = Buffer.alloc(1024) - pload.write( - "All you Trekkies and TV addicts, Don't mean to diss don't mean to bring static.", - 0, - 1024, - "utf8" - ) - - for (let i: number = 0; i < 3; i++) { - addrs1.push( - avm.addressFromBuffer(avm.keyChain().makeKey().getAddress()) - ) - addrs2.push(avm.addressFromBuffer(keymgr2.makeKey().getAddress())) - addrs3.push(avm.addressFromBuffer(keymgr3.makeKey().getAddress())) - } - const amount: BN = ONEAVAX.mul(new BN(amnt)) - addressbuffs = avm.keyChain().getAddresses() - addresses = addressbuffs.map((a) => avm.addressFromBuffer(a)) - const locktime: BN = new BN(54321) - const threshold: number = 3 - for (let i: number = 0; i < 5; i++) { - let txid: Buffer = Buffer.from( - createHash("sha256") - .update(bintools.fromBNToBuffer(new BN(i), 32)) - .digest() - ) - let txidx: Buffer = Buffer.alloc(4) - txidx.writeUInt32BE(i, 0) - - const out: SECPTransferOutput = new SECPTransferOutput( - amount, - addressbuffs, - locktime, - threshold - ) - const xferout: TransferableOutput = new TransferableOutput(assetID, out) - outputs.push(xferout) - - const u: UTXO = new UTXO() - u.fromBuffer( - Buffer.concat([u.getCodecIDBuffer(), txid, txidx, xferout.toBuffer()]) - ) - fungutxoids.push(u.getUTXOID()) - utxos.push(u) - - txid = u.getTxID() - txidx = u.getOutputIdx() - const asset = u.getAssetID() - - const input: SECPTransferInput = new SECPTransferInput(amount) - const xferinput: TransferableInput = new TransferableInput( - txid, - txidx, - asset, - input - ) - inputs.push(xferinput) - - const nout: NFTTransferOutput = new NFTTransferOutput( - 1000 + i, - pload, - addressbuffs, - locktime, - threshold - ) - const op: NFTTransferOperation = new NFTTransferOperation(nout) - const nfttxid: Buffer = Buffer.from( - createHash("sha256") - .update(bintools.fromBNToBuffer(new BN(1000 + i), 32)) - .digest() - ) - const nftutxo: UTXO = new UTXO( - AVMConstants.LATESTCODEC, - nfttxid, - 1000 + i, - NFTassetID, - nout - ) - nftutxoids.push(nftutxo.getUTXOID()) - const xferop: TransferableOperation = new TransferableOperation( - NFTassetID, - [nftutxo.getUTXOID()], - op - ) - ops.push(xferop) - utxos.push(nftutxo) - } - set.addArray(utxos) - - secpbase1 = new SECPTransferOutput( - new BN(777), - addrs3.map((a) => avm.parseAddress(a)), - UnixNow(), - 1 - ) - secpbase2 = new SECPTransferOutput( - new BN(888), - addrs2.map((a) => avm.parseAddress(a)), - UnixNow(), - 1 - ) - secpbase3 = new SECPTransferOutput( - new BN(999), - addrs2.map((a) => avm.parseAddress(a)), - UnixNow(), - 1 - ) - initialState = new InitialStates() - initialState.addOutput(secpbase1, AVMConstants.SECPFXID) - initialState.addOutput(secpbase2, AVMConstants.SECPFXID) - initialState.addOutput(secpbase3, AVMConstants.SECPFXID) - - nftpbase1 = new NFTMintOutput( - 0, - addrs1.map((a) => api.parseAddress(a)), - locktime, - 1 - ) - nftpbase2 = new NFTMintOutput( - 1, - addrs2.map((a) => api.parseAddress(a)), - locktime, - 1 - ) - nftpbase3 = new NFTMintOutput( - 2, - addrs3.map((a) => api.parseAddress(a)), - locktime, - 1 - ) - nftInitialState = new InitialStates() - nftInitialState.addOutput(nftpbase1, AVMConstants.NFTFXID) - nftInitialState.addOutput(nftpbase2, AVMConstants.NFTFXID) - nftInitialState.addOutput(nftpbase3, AVMConstants.NFTFXID) - - secpMintOut1 = new SECPMintOutput(addressbuffs, new BN(0), 1) - secpMintOut2 = new SECPMintOutput(addressbuffs, new BN(0), 1) - secpMintTXID = Buffer.from( - createHash("sha256") - .update(bintools.fromBNToBuffer(new BN(1337), 32)) - .digest() - ) - secpMintUTXO = new UTXO( - AVMConstants.LATESTCODEC, - secpMintTXID, - 0, - assetID, - secpMintOut1 - ) - secpMintXferOut1 = new SECPTransferOutput( - new BN(123), - addrs3.map((a) => avm.parseAddress(a)), - UnixNow(), - 2 - ) - secpMintXferOut2 = new SECPTransferOutput( - new BN(456), - [avm.parseAddress(addrs2[0])], - UnixNow(), - 1 - ) - secpMintOp = new SECPMintOperation(secpMintOut1, secpMintXferOut1) - - set.add(secpMintUTXO) - - xfersecpmintop = new TransferableOperation( - assetID, - [secpMintUTXO.getUTXOID()], - secpMintOp - ) - }) - - test("getDefaultMintTxFee", (): void => { - expect(avm.getDefaultMintTxFee().toString()).toBe("1000000") - }) - - test("signTx", async (): Promise => { - const txu1: UnsignedTx = await avm.buildBaseTx( - set, - new BN(amnt), - bintools.cb58Encode(assetID), - addrs3, - addrs1, - addrs1 - ) - const txu2: UnsignedTx = set.buildBaseTx( - networkID, - bintools.cb58Decode(blockchainID), - new BN(amnt), - assetID, - addrs3.map((a) => avm.parseAddress(a)), - addrs1.map((a) => avm.parseAddress(a)), - addrs1.map((a) => avm.parseAddress(a)), - avm.getTxFee(), - assetID, - undefined, - UnixNow(), - new BN(0), - 1 - ) - - const tx1: Tx = avm.signTx(txu1) - const tx2: Tx = avm.signTx(txu2) - - expect(tx2.toBuffer().toString("hex")).toBe( - tx1.toBuffer().toString("hex") - ) - expect(tx2.toString()).toBe(tx1.toString()) - }) - - test("buildBaseTx1", async (): Promise => { - const txu1: UnsignedTx = await avm.buildBaseTx( - set, - new BN(amnt), - bintools.cb58Encode(assetID), - addrs3, - addrs1, - addrs1, - new UTF8Payload("hello world").getContent() - ) - const memobuf: Buffer = Buffer.from("hello world") - const txu2: UnsignedTx = set.buildBaseTx( - networkID, - bintools.cb58Decode(blockchainID), - new BN(amnt), - assetID, - addrs3.map((a) => avm.parseAddress(a)), - addrs1.map((a) => avm.parseAddress(a)), - addrs1.map((a) => avm.parseAddress(a)), - avm.getTxFee(), - assetID, - memobuf, - UnixNow(), - new BN(0), - 1 - ) - expect(txu2.toBuffer().toString("hex")).toBe( - txu1.toBuffer().toString("hex") - ) - expect(txu2.toString()).toBe(txu1.toString()) - - const tx1: Tx = txu1.sign(avm.keyChain()) - const checkTx: string = tx1.toBuffer().toString("hex") - const tx1obj: object = tx1.serialize("hex") - const tx1str: string = JSON.stringify(tx1obj) - const tx2newobj: object = JSON.parse(tx1str) - const tx2: Tx = new Tx() - tx2.deserialize(tx2newobj, "hex") - - const tx2obj: object = tx2.serialize("hex") - const tx2str: string = JSON.stringify(tx2obj) - expect(tx1obj).toStrictEqual(tx2obj) - expect(tx1str).toStrictEqual(tx2str) - expect(tx2.toBuffer().toString("hex")).toBe(checkTx) - - const tx3: Tx = txu1.sign(avm.keyChain()) - const tx3obj: object = tx3.serialize(display) - const tx3str: string = JSON.stringify(tx3obj) - const tx4newobj: object = JSON.parse(tx3str) - const tx4: Tx = new Tx() - tx4.deserialize(tx4newobj, display) - - const tx4obj: object = tx4.serialize(display) - const tx4str: string = JSON.stringify(tx4obj) - expect(tx3obj).toStrictEqual(tx4obj) - expect(tx3str).toStrictEqual(tx4str) - expect(tx4.toBuffer().toString("hex")).toBe(checkTx) - }) - - test("xssPreventionObject", async (): Promise => { - const txu1: UnsignedTx = await avm.buildBaseTx( - set, - new BN(amnt), - bintools.cb58Encode(assetID), - addrs3, - addrs1, - addrs1 - ) - - const tx1: Tx = avm.signTx(txu1) - const tx1obj: object = tx1.serialize("hex") - const sanitized: object = tx1.sanitizeObject(tx1obj) - expect(tx1obj).toStrictEqual(sanitized) - }) - - test("xssPreventionHTML", async (): Promise => { - const dirtyDom: string = "" - const sanitizedString: string = `` - - const txu1: UnsignedTx = await avm.buildBaseTx( - set, - new BN(amnt), - bintools.cb58Encode(assetID), - addrs3, - addrs1, - addrs1 - ) - - const tx1: Tx = avm.signTx(txu1) - const tx1obj: object = tx1.serialize("hex") - const dirtyObj: object = { - ...tx1obj, - dirtyDom: dirtyDom - } - const sanitizedObj: any = tx1.sanitizeObject(dirtyObj) - expect(sanitizedObj.dirtyDom).toBe(sanitizedString) - }) - - test("buildBaseTx2", async (): Promise => { - const txu1: UnsignedTx = await avm.buildBaseTx( - set, - new BN(amnt).sub(new BN(100)), - bintools.cb58Encode(assetID), - addrs3, - addrs1, - addrs2, - new UTF8Payload("hello world") - ) - const txu2: UnsignedTx = set.buildBaseTx( - networkID, - bintools.cb58Decode(blockchainID), - new BN(amnt).sub(new BN(100)), - assetID, - addrs3.map((a): Buffer => avm.parseAddress(a)), - addrs1.map((a): Buffer => avm.parseAddress(a)), - addrs2.map((a): Buffer => avm.parseAddress(a)), - avm.getTxFee(), - assetID, - new UTF8Payload("hello world").getPayload(), - UnixNow(), - new BN(0), - 1 - ) - - expect(txu2.toBuffer().toString("hex")).toBe( - txu1.toBuffer().toString("hex") - ) - expect(txu2.toString()).toBe(txu1.toString()) - - const outies = txu1 - .getTransaction() - .getOuts() - .sort(TransferableOutput.comparator()) as TransferableOutput[] - - expect(outies.length).toBe(2) - const outaddr0 = outies[0] - .getOutput() - .getAddresses() - .map((a) => avm.addressFromBuffer(a)) - const outaddr1 = outies[1] - .getOutput() - .getAddresses() - .map((a) => avm.addressFromBuffer(a)) - - const testaddr2 = JSON.stringify(addrs2.sort()) - const testaddr3 = JSON.stringify(addrs3.sort()) - - const testout0 = JSON.stringify(outaddr0.sort()) - const testout1 = JSON.stringify(outaddr1.sort()) - expect( - (testaddr2 == testout0 && testaddr3 == testout1) || - (testaddr3 == testout0 && testaddr2 == testout1) - ).toBe(true) - - const tx1: Tx = txu1.sign(avm.keyChain()) - const checkTx: string = tx1.toBuffer().toString("hex") - const tx1obj: object = tx1.serialize("hex") - const tx1str: string = JSON.stringify(tx1obj) - const tx2newobj: object = JSON.parse(tx1str) - const tx2: Tx = new Tx() - tx2.deserialize(tx2newobj, "hex") - - const tx2obj: object = tx2.serialize("hex") - const tx2str: string = JSON.stringify(tx2obj) - expect(tx1obj).toStrictEqual(tx2obj) - expect(tx1str).toStrictEqual(tx2str) - expect(tx2.toBuffer().toString("hex")).toBe(checkTx) - - const tx3: Tx = txu1.sign(avm.keyChain()) - const tx3obj: object = tx3.serialize(display) - const tx3str: string = JSON.stringify(tx3obj) - const tx4newobj: object = JSON.parse(tx3str) - const tx4: Tx = new Tx() - tx4.deserialize(tx4newobj, display) - - const tx4obj: object = tx4.serialize(display) - const tx4str: string = JSON.stringify(tx4obj) - expect(tx3obj).toStrictEqual(tx4obj) - expect(tx3str).toStrictEqual(tx4str) - expect(tx4.toBuffer().toString("hex")).toBe(checkTx) - - serialzeit(tx1, "BaseTx") - }) - - test("issueTx Serialized", async (): Promise => { - const txu: UnsignedTx = await avm.buildBaseTx( - set, - new BN(amnt), - bintools.cb58Encode(assetID), - addrs3, - addrs1, - addrs1 - ) - const tx = avm.signTx(txu) - const txid: string = - "f966750f438867c3c9828ddcdbe660e21ccdbb36a9276958f011ba472f75d4e7" - - const result: Promise = avm.issueTx(tx.toString()) - const payload: object = { - result: { - txID: txid - } - } - const responseObj: HttpResponse = { - data: payload - } - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(response).toBe(txid) - }) - - test("issueTx Buffer", async (): Promise => { - const txu: UnsignedTx = await avm.buildBaseTx( - set, - new BN(amnt), - bintools.cb58Encode(assetID), - addrs3, - addrs1, - addrs1 - ) - const tx = avm.signTx(txu) - - const txid: string = - "f966750f438867c3c9828ddcdbe660e21ccdbb36a9276958f011ba472f75d4e7" - const result: Promise = avm.issueTx(tx.toBuffer()) - const payload: object = { - result: { - txID: txid - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(response).toBe(txid) - }) - test("issueTx Class Tx", async (): Promise => { - const txu: UnsignedTx = await avm.buildBaseTx( - set, - new BN(amnt), - bintools.cb58Encode(assetID), - addrs3, - addrs1, - addrs1 - ) - const tx = avm.signTx(txu) - - const txid: string = - "f966750f438867c3c9828ddcdbe660e21ccdbb36a9276958f011ba472f75d4e7" - - const result: Promise = avm.issueTx(tx) - const payload: object = { - result: { - txID: txid - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - expect(response).toBe(txid) - }) - - test("buildCreateAssetTx - Fixed Cap", async (): Promise => { - avm.setCreationTxFee(new BN(fee)) - const txu1: UnsignedTx = await avm.buildCreateAssetTx( - set, - addrs1, - addrs2, - initialState, - name, - symbol, - denomination - ) - - const txu2: UnsignedTx = set.buildCreateAssetTx( - avalanche.getNetworkID(), - bintools.cb58Decode(avm.getBlockchainID()), - addrs1.map((a) => avm.parseAddress(a)), - addrs2.map((a) => avm.parseAddress(a)), - initialState, - name, - symbol, - denomination, - undefined, - CENTIAVAX, - assetID - ) - - expect(txu2.toBuffer().toString("hex")).toBe( - txu1.toBuffer().toString("hex") - ) - expect(txu2.toString()).toBe(txu1.toString()) - - const tx1: Tx = txu1.sign(avm.keyChain()) - const checkTx: string = tx1.toBuffer().toString("hex") - const tx1obj: object = tx1.serialize("hex") - const tx1str: string = JSON.stringify(tx1obj) - const tx2newobj: object = JSON.parse(tx1str) - const tx2: Tx = new Tx() - tx2.deserialize(tx2newobj, "hex") - - const tx2obj: object = tx2.serialize("hex") - const tx2str: string = JSON.stringify(tx2obj) - expect(tx1obj).toStrictEqual(tx2obj) - expect(tx1str).toStrictEqual(tx2str) - expect(tx2.toBuffer().toString("hex")).toBe(checkTx) - - const tx3: Tx = txu1.sign(avm.keyChain()) - const tx3obj: object = tx3.serialize(display) - const tx3str: string = JSON.stringify(tx3obj) - const tx4newobj: object = JSON.parse(tx3str) - const tx4: Tx = new Tx() - tx4.deserialize(tx4newobj, display) - - const tx4obj: object = tx4.serialize(display) - const tx4str: string = JSON.stringify(tx4obj) - expect(tx3obj).toStrictEqual(tx4obj) - expect(tx3str).toStrictEqual(tx4str) - expect(tx4.toBuffer().toString("hex")).toBe(checkTx) - serialzeit(tx1, "CreateAssetTx") - }) - - test("buildCreateAssetTx - Variable Cap", async (): Promise => { - avm.setCreationTxFee(new BN(Defaults.network[12345].P["creationTxFee"])) - const mintOutputs: SECPMintOutput[] = [secpMintOut1, secpMintOut2] - const txu1: UnsignedTx = await avm.buildCreateAssetTx( - set, - addrs1, - addrs2, - initialState, - name, - symbol, - denomination, - mintOutputs - ) - - const txu2: UnsignedTx = set.buildCreateAssetTx( - avalanche.getNetworkID(), - bintools.cb58Decode(avm.getBlockchainID()), - addrs1.map((a) => avm.parseAddress(a)), - addrs2.map((a) => avm.parseAddress(a)), - initialState, - name, - symbol, - denomination, - mintOutputs, - avm.getCreationTxFee(), - assetID - ) - - expect(txu2.toBuffer().toString("hex")).toBe( - txu1.toBuffer().toString("hex") - ) - expect(txu2.toString()).toBe(txu1.toString()) - - const tx1: Tx = txu1.sign(avm.keyChain()) - const checkTx: string = tx1.toBuffer().toString("hex") - const tx1obj: object = tx1.serialize("hex") - const tx1str: string = JSON.stringify(tx1obj) - const tx2newobj: object = JSON.parse(tx1str) - const tx2: Tx = new Tx() - tx2.deserialize(tx2newobj, "hex") - - const tx2obj: object = tx2.serialize("hex") - const tx2str: string = JSON.stringify(tx2obj) - expect(tx1obj).toStrictEqual(tx2obj) - expect(tx1str).toStrictEqual(tx2str) - expect(tx2.toBuffer().toString("hex")).toBe(checkTx) - - const tx3: Tx = txu1.sign(avm.keyChain()) - const tx3obj: object = tx3.serialize(display) - const tx3str: string = JSON.stringify(tx3obj) - const tx4newobj: object = JSON.parse(tx3str) - const tx4: Tx = new Tx() - tx4.deserialize(tx4newobj, display) - - const tx4obj: object = tx4.serialize(display) - const tx4str: string = JSON.stringify(tx4obj) - expect(tx3obj).toStrictEqual(tx4obj) - expect(tx3str).toStrictEqual(tx4str) - expect(tx4.toBuffer().toString("hex")).toBe(checkTx) - }) - - test("buildSECPMintTx", async (): Promise => { - avm.setTxFee(new BN(fee)) - const newMinter: SECPMintOutput = new SECPMintOutput( - addrs3.map((a) => avm.parseAddress(a)), - new BN(0), - 1 - ) - const txu1: UnsignedTx = await avm.buildSECPMintTx( - set, - newMinter, - secpMintXferOut1, - addrs1, - addrs2, - secpMintUTXO.getUTXOID() - ) - - const txu2: UnsignedTx = set.buildSECPMintTx( - avalanche.getNetworkID(), - bintools.cb58Decode(avm.getBlockchainID()), - newMinter, - secpMintXferOut1, - addrs1.map((a) => avm.parseAddress(a)), - addrs2.map((a) => avm.parseAddress(a)), - secpMintUTXO.getUTXOID(), - MILLIAVAX, - assetID - ) - - expect(txu2.toBuffer().toString("hex")).toBe( - txu1.toBuffer().toString("hex") - ) - expect(txu2.toString()).toBe(txu1.toString()) - - const tx1: Tx = txu1.sign(avm.keyChain()) - const checkTx: string = tx1.toBuffer().toString("hex") - const tx1obj: object = tx1.serialize("hex") - const tx1str: string = JSON.stringify(tx1obj) - const tx2newobj: object = JSON.parse(tx1str) - const tx2: Tx = new Tx() - tx2.deserialize(tx2newobj, "hex") - - const tx2obj: object = tx2.serialize("hex") - const tx2str: string = JSON.stringify(tx2obj) - expect(tx1obj).toStrictEqual(tx2obj) - expect(tx1str).toStrictEqual(tx2str) - expect(tx2.toBuffer().toString("hex")).toBe(checkTx) - - const tx3: Tx = txu1.sign(avm.keyChain()) - const tx3obj: object = tx3.serialize(display) - const tx3str: string = JSON.stringify(tx3obj) - const tx4newobj: object = JSON.parse(tx3str) - const tx4: Tx = new Tx() - tx4.deserialize(tx4newobj, display) - - const tx4obj: object = tx4.serialize(display) - const tx4str: string = JSON.stringify(tx4obj) - expect(tx3obj).toStrictEqual(tx4obj) - expect(tx3str).toStrictEqual(tx4str) - expect(tx4.toBuffer().toString("hex")).toBe(checkTx) - serialzeit(tx1, "SECPMintTx") - }) - - test("buildCreateNFTAssetTx", async (): Promise => { - avm.setCreationTxFee(new BN(Defaults.network[12345].P["creationTxFee"])) - const minterSets: MinterSet[] = [new MinterSet(1, addrs1)] - const locktime: BN = new BN(0) - - const txu1: UnsignedTx = await avm.buildCreateNFTAssetTx( - set, - addrs1, - addrs2, - minterSets, - name, - symbol, - new UTF8Payload("hello world"), - UnixNow(), - locktime - ) - - const txu2: UnsignedTx = set.buildCreateNFTAssetTx( - avalanche.getNetworkID(), - bintools.cb58Decode(avm.getBlockchainID()), - addrs1.map((a: string): Buffer => avm.parseAddress(a)), - addrs2.map((a: string): Buffer => avm.parseAddress(a)), - minterSets, - name, - symbol, - avm.getCreationTxFee(), - assetID, - new UTF8Payload("hello world").getPayload(), - UnixNow(), - locktime - ) - - expect(txu2.toBuffer().toString("hex")).toBe( - txu1.toBuffer().toString("hex") - ) - expect(txu2.toString()).toBe(txu1.toString()) - - const tx1: Tx = txu1.sign(avm.keyChain()) - const checkTx: string = tx1.toBuffer().toString("hex") - const tx1obj: object = tx1.serialize("hex") - const tx1str: string = JSON.stringify(tx1obj) - const tx2newobj: object = JSON.parse(tx1str) - const tx2: Tx = new Tx() - tx2.deserialize(tx2newobj, "hex") - - const tx2obj: object = tx2.serialize("hex") - const tx2str: string = JSON.stringify(tx2obj) - expect(tx1obj).toStrictEqual(tx2obj) - expect(tx1str).toStrictEqual(tx2str) - expect(tx2.toBuffer().toString("hex")).toBe(checkTx) - - const tx3: Tx = txu1.sign(avm.keyChain()) - const tx3obj: object = tx3.serialize(display) - const tx3str: string = JSON.stringify(tx3obj) - const tx4newobj: object = JSON.parse(tx3str) - const tx4: Tx = new Tx() - tx4.deserialize(tx4newobj, display) - - const tx4obj: object = tx4.serialize(display) - const tx4str: string = JSON.stringify(tx4obj) - expect(tx3obj).toStrictEqual(tx4obj) - expect(tx3str).toStrictEqual(tx4str) - expect(tx4.toBuffer().toString("hex")).toBe(checkTx) - serialzeit(tx1, "CreateNFTAssetTx") - }) - - test("buildCreateNFTMintTx", async (): Promise => { - avm.setTxFee(new BN(fee)) - const groupID: number = 0 - const locktime: BN = new BN(0) - const threshold: number = 1 - const payload: Buffer = Buffer.from("Avalanche") - const addrbuff1: Buffer[] = addrs1.map( - (a: string): Buffer => avm.parseAddress(a) - ) - const addrbuff2: Buffer[] = addrs2.map( - (a: string): Buffer => avm.parseAddress(a) - ) - const addrbuff3: Buffer[] = addrs3.map( - (a: string): Buffer => avm.parseAddress(a) - ) - const outputOwners: OutputOwners[] = [] - const oo: OutputOwners = new OutputOwners(addrbuff3, locktime, threshold) - outputOwners.push() - - const txu1: UnsignedTx = await avm.buildCreateNFTMintTx( - set, - oo, - addrs1, - addrs2, - nftutxoids, - groupID, - payload, - undefined, - UnixNow() - ) - - const txu2: UnsignedTx = set.buildCreateNFTMintTx( - avalanche.getNetworkID(), - bintools.cb58Decode(avm.getBlockchainID()), - [oo], - addrbuff1, - addrbuff2, - nftutxoids, - groupID, - payload, - avm.getTxFee(), - assetID, - undefined, - UnixNow() - ) - - expect(txu2.toBuffer().toString("hex")).toBe( - txu1.toBuffer().toString("hex") - ) - expect(txu2.toString()).toBe(txu1.toString()) - - outputOwners.push(oo) - outputOwners.push(new OutputOwners(addrbuff3, locktime, threshold + 1)) - - const txu3: UnsignedTx = await avm.buildCreateNFTMintTx( - set, - outputOwners, - addrs1, - addrs2, - nftutxoids, - groupID, - payload, - undefined, - UnixNow() - ) - - const txu4: UnsignedTx = set.buildCreateNFTMintTx( - avalanche.getNetworkID(), - bintools.cb58Decode(avm.getBlockchainID()), - outputOwners, - addrbuff1, - addrbuff2, - nftutxoids, - groupID, - payload, - avm.getTxFee(), - assetID, - undefined, - UnixNow() - ) - - expect(txu4.toBuffer().toString("hex")).toBe( - txu3.toBuffer().toString("hex") - ) - expect(txu4.toString()).toBe(txu3.toString()) - - const tx1: Tx = txu1.sign(avm.keyChain()) - const checkTx: string = tx1.toBuffer().toString("hex") - const tx1obj: object = tx1.serialize("hex") - const tx1str: string = JSON.stringify(tx1obj) - const tx2newobj: object = JSON.parse(tx1str) - const tx2: Tx = new Tx() - tx2.deserialize(tx2newobj, "hex") - - const tx2obj: object = tx2.serialize("hex") - const tx2str: string = JSON.stringify(tx2obj) - expect(tx1obj).toStrictEqual(tx2obj) - expect(tx1str).toStrictEqual(tx2str) - expect(tx2.toBuffer().toString("hex")).toBe(checkTx) - - const tx3: Tx = txu1.sign(avm.keyChain()) - const tx3obj: object = tx3.serialize(display) - const tx3str: string = JSON.stringify(tx3obj) - const tx4newobj: object = JSON.parse(tx3str) - const tx4: Tx = new Tx() - tx4.deserialize(tx4newobj, display) - - const tx4obj: object = tx4.serialize(display) - const tx4str: string = JSON.stringify(tx4obj) - expect(tx3obj).toStrictEqual(tx4obj) - expect(tx3str).toStrictEqual(tx4str) - expect(tx4.toBuffer().toString("hex")).toBe(checkTx) - serialzeit(tx1, "CreateNFTMintTx") - }) - - test("buildNFTTransferTx", async (): Promise => { - avm.setTxFee(new BN(fee)) - const pload: Buffer = Buffer.alloc(1024) - pload.write( - "All you Trekkies and TV addicts, Don't mean to diss don't mean to bring static.", - 0, - 1024, - "utf8" - ) - const addrbuff1 = addrs1.map((a: string): Buffer => avm.parseAddress(a)) - const addrbuff2 = addrs2.map((a: string): Buffer => avm.parseAddress(a)) - const addrbuff3 = addrs3.map((a: string): Buffer => avm.parseAddress(a)) - const txu1: UnsignedTx = await avm.buildNFTTransferTx( - set, - addrs3, - addrs1, - addrs2, - nftutxoids[1], - new UTF8Payload("hello world"), - UnixNow(), - new BN(0), - 1 - ) - - const txu2: UnsignedTx = set.buildNFTTransferTx( - networkID, - bintools.cb58Decode(blockchainID), - addrbuff3, - addrbuff1, - addrbuff2, - [nftutxoids[1]], - avm.getTxFee(), - assetID, - new UTF8Payload("hello world").getPayload(), - UnixNow(), - new BN(0), - 1 - ) - - expect(txu2.toBuffer().toString("hex")).toBe( - txu1.toBuffer().toString("hex") - ) - expect(txu2.toString()).toBe(txu1.toString()) - - const tx1: Tx = txu1.sign(avm.keyChain()) - const checkTx: string = tx1.toBuffer().toString("hex") - const tx1obj: object = tx1.serialize("hex") - const tx1str: string = JSON.stringify(tx1obj) - const tx2newobj: object = JSON.parse(tx1str) - const tx2: Tx = new Tx() - tx2.deserialize(tx2newobj, "hex") - - const tx2obj: object = tx2.serialize("hex") - const tx2str: string = JSON.stringify(tx2obj) - expect(tx1obj).toStrictEqual(tx2obj) - expect(tx1str).toStrictEqual(tx2str) - expect(tx2.toBuffer().toString("hex")).toBe(checkTx) - - const tx3: Tx = txu1.sign(avm.keyChain()) - const tx3obj: object = tx3.serialize(display) - const tx3str: string = JSON.stringify(tx3obj) - const tx4newobj: object = JSON.parse(tx3str) - const tx4: Tx = new Tx() - tx4.deserialize(tx4newobj, display) - - const tx4obj: object = tx4.serialize(display) - const tx4str: string = JSON.stringify(tx4obj) - expect(tx3obj).toStrictEqual(tx4obj) - expect(tx3str).toStrictEqual(tx4str) - expect(tx4.toBuffer().toString("hex")).toBe(checkTx) - serialzeit(tx1, "NFTTransferTx") - }) - - test("buildImportTx", async (): Promise => { - const locktime: BN = new BN(0) - const threshold: number = 1 - avm.setTxFee(new BN(fee)) - const addrbuff1 = addrs1.map((a) => avm.parseAddress(a)) - const addrbuff2 = addrs2.map((a) => avm.parseAddress(a)) - const addrbuff3 = addrs3.map((a) => avm.parseAddress(a)) - const fungutxo: UTXO = set.getUTXO(fungutxoids[1]) - const fungutxostr: string = fungutxo.toString() - - const result: Promise = avm.buildImportTx( - set, - addrs1, - PlatformChainID, - addrs3, - addrs1, - addrs2, - new UTF8Payload("hello world"), - UnixNow(), - locktime, - threshold - ) - const payload: object = { - result: { - utxos: [fungutxostr] - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const txu1: UnsignedTx = await result - - const txu2: UnsignedTx = set.buildImportTx( - networkID, - bintools.cb58Decode(blockchainID), - addrbuff3, - addrbuff1, - addrbuff2, - [fungutxo], - bintools.cb58Decode(PlatformChainID), - avm.getTxFee(), - await avm.getAVAXAssetID(), - new UTF8Payload("hello world").getPayload(), - UnixNow(), - locktime, - threshold - ) - - expect(txu2.toBuffer().toString("hex")).toBe( - txu1.toBuffer().toString("hex") - ) - expect(txu2.toString()).toBe(txu1.toString()) - - const tx1: Tx = txu1.sign(avm.keyChain()) - const checkTx: string = tx1.toBuffer().toString("hex") - const tx1obj: object = tx1.serialize("hex") - const tx1str: string = JSON.stringify(tx1obj) - const tx2newobj: object = JSON.parse(tx1str) - const tx2: Tx = new Tx() - tx2.deserialize(tx2newobj, "hex") - - const tx2obj: object = tx2.serialize("hex") - const tx2str: string = JSON.stringify(tx2obj) - expect(tx1obj).toStrictEqual(tx2obj) - expect(tx1str).toStrictEqual(tx2str) - expect(tx2.toBuffer().toString("hex")).toBe(checkTx) - - const tx3: Tx = txu1.sign(avm.keyChain()) - const tx3obj: object = tx3.serialize(display) - const tx3str: string = JSON.stringify(tx3obj) - const tx4newobj: object = JSON.parse(tx3str) - const tx4: Tx = new Tx() - tx4.deserialize(tx4newobj, display) - - const tx4obj: object = tx4.serialize(display) - const tx4str: string = JSON.stringify(tx4obj) - expect(tx3obj).toStrictEqual(tx4obj) - expect(tx3str).toStrictEqual(tx4str) - expect(tx4.toBuffer().toString("hex")).toBe(checkTx) - serialzeit(tx1, "ImportTx") - }) - - test("buildExportTx", async (): Promise => { - avm.setTxFee(new BN(fee)) - const addrbuff1: Buffer[] = addrs1.map( - (a: string): Buffer => avm.parseAddress(a) - ) - const addrbuff2: Buffer[] = addrs2.map( - (a: string): Buffer => avm.parseAddress(a) - ) - const addrbuff3: Buffer[] = addrs3.map( - (a: string): Buffer => avm.parseAddress(a) - ) - const amount: BN = new BN(90) - const type: SerializedType = "bech32" - const txu1: UnsignedTx = await avm.buildExportTx( - set, - amount, - bintools.cb58Decode(PlatformChainID), - addrbuff3.map((a: Buffer): any => - serialization.bufferToType(a, type, avalanche.getHRP(), "P") - ), - addrs1, - addrs2, - new UTF8Payload("hello world"), - UnixNow() - ) - - const txu2: UnsignedTx = set.buildExportTx( - networkID, - bintools.cb58Decode(blockchainID), - amount, - assetID, - addrbuff3, - addrbuff1, - addrbuff2, - bintools.cb58Decode(PlatformChainID), - avm.getTxFee(), - assetID, - new UTF8Payload("hello world").getPayload(), - UnixNow() - ) - - expect(txu2.toBuffer().toString("hex")).toBe( - txu1.toBuffer().toString("hex") - ) - expect(txu2.toString()).toBe(txu1.toString()) - - const txu3: UnsignedTx = await avm.buildExportTx( - set, - amount, - PlatformChainID, - addrs3, - addrs1, - addrs2, - new UTF8Payload("hello world"), - UnixNow() - ) - - const txu4: UnsignedTx = set.buildExportTx( - networkID, - bintools.cb58Decode(blockchainID), - amount, - assetID, - addrbuff3, - addrbuff1, - addrbuff2, - undefined, - avm.getTxFee(), - assetID, - new UTF8Payload("hello world").getPayload(), - UnixNow() - ) - - expect(txu4.toBuffer().toString("hex")).toBe( - txu3.toBuffer().toString("hex") - ) - expect(txu4.toString()).toBe(txu3.toString()) - - const tx1: Tx = txu1.sign(avm.keyChain()) - const checkTx: string = tx1.toBuffer().toString("hex") - const tx1obj: object = tx1.serialize("hex") - const tx1str: string = JSON.stringify(tx1obj) - const tx2newobj: object = JSON.parse(tx1str) - const tx2: Tx = new Tx() - tx2.deserialize(tx2newobj, "hex") - - const tx2obj: object = tx2.serialize("hex") - const tx2str: string = JSON.stringify(tx2obj) - expect(tx1obj).toStrictEqual(tx2obj) - expect(tx1str).toStrictEqual(tx2str) - expect(tx2.toBuffer().toString("hex")).toBe(checkTx) - - const tx3: Tx = txu1.sign(avm.keyChain()) - const tx3obj: object = tx3.serialize(display) - const tx3str: string = JSON.stringify(tx3obj) - const tx4newobj: object = JSON.parse(tx3str) - const tx4: Tx = new Tx() - tx4.deserialize(tx4newobj, display) - - const tx4obj: object = tx4.serialize(display) - const tx4str: string = JSON.stringify(tx4obj) - expect(tx3obj).toStrictEqual(tx4obj) - expect(tx3str).toStrictEqual(tx4str) - expect(tx4.toBuffer().toString("hex")).toBe(checkTx) - serialzeit(tx1, "ExportTx") - }) - - test("buildGenesis", async (): Promise => { - const genesisData: object = { - genesisData: { - assetAlias1: { - name: "human readable name", - symbol: "AVAL", - initialState: { - fixedCap: [ - { - amount: 1000, - address: "A" - }, - { - amount: 5000, - address: "B" - } - ] - } - }, - assetAliasCanBeAnythingUnique: { - name: "human readable name", - symbol: "AVAL", - initialState: { - variableCap: [ - { - minters: ["A", "B"], - threshold: 1 - }, - { - minters: ["A", "B", "C"], - threshold: 2 - } - ] - } - } - } - } - const bytes: string = - "111TNWzUtHKoSvxohjyfEwE2X228ZDGBngZ4mdMUVMnVnjtnawW1b1zbAhzyAM1v6d7ECNj6DXsT7qDmhSEf3DWgXRj7ECwBX36ZXFc9tWVB2qHURoUfdDvFsBeSRqatCmj76eZQMGZDgBFRNijRhPNKUap7bCeKpHDtuCZc4YpPkd4mR84dLL2AL1b4K46eirWKMaFVjA5btYS4DnyUx5cLpAq3d35kEdNdU5zH3rTU18S4TxYV8voMPcLCTZ3h4zRsM5jW1cUzjWVvKg7uYS2oR9qXRFcgy1gwNTFZGstySuvSF7MZeZF4zSdNgC4rbY9H94RVhqe8rW7MXqMSZB6vBTB2BpgF6tNFehmYxEXwjaKRrimX91utvZe9YjgGbDr8XHsXCnXXg4ZDCjapCy4HmmRUtUoAduGNBdGVMiwE9WvVbpMFFcNfgDXGz9NiatgSnkxQALTHvGXXm8bn4CoLFzKnAtq3KwiWqHmV3GjFYeUm3m8Zee9VDfZAvDsha51acxfto1htstxYu66DWpT36YT18WSbxibZcKXa7gZrrsCwyzid8CCWw79DbaLCUiq9u47VqofG1kgxwuuyHb8NVnTgRTkQASSbj232fyG7YeX4mAvZY7a7K7yfSyzJaXdUdR7aLeCdLP6mbFDqUMrN6YEkU2X8d4Ck3T" - const result: Promise = api.buildGenesis(genesisData) - const payload: object = { - result: { - bytes: bytes - } - } - const responseObj: { - data: object - } = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - expect(response).toBe(bytes) - }) - }) -}) diff --git a/tests/apis/avm/genesisasset.test.ts b/tests/apis/avm/genesisasset.test.ts deleted file mode 100644 index 88238cb96..000000000 --- a/tests/apis/avm/genesisasset.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import BN from "bn.js" -import { Buffer } from "buffer/" -import { - SECPTransferOutput, - TransferableOutput -} from "../../../src/apis/avm/outputs" -import { InitialStates } from "../../../src/apis/avm/initialstates" -import { GenesisAsset, TransferableInput } from "../../../src/apis/avm" -import { - DefaultNetworkID, - Serialization, - SerializedEncoding, - SerializedType -} from "../../../src/utils" - -/** - * @ignore - */ -const serialization: Serialization = Serialization.getInstance() -describe("AVM", (): void => { - test("GenesisAsset", (): void => { - const m: string = "2Zc54v4ek37TEwu4LiV3j41PUMRd6acDDU3ZCVSxE7X" - const mHex: string = - "66726f6d20736e6f77666c616b6520746f206176616c616e636865" - const blockchainIDHex: string = - "0000000000000000000000000000000000000000000000000000000000000000" - const hex: SerializedEncoding = "hex" - const cb58: SerializedType = "cb58" - const bech32: SerializedType = "bech32" - const memo: Buffer = serialization.typeToBuffer(m, cb58) - const amount: BN = new BN(0) - const address: string = "X-local18jma8ppw3nhx5r4ap8clazz0dps7rv5u00z96u" - const addressBuf: Buffer = serialization.typeToBuffer(address, bech32) - const threshold: number = 1 - const locktime: BN = new BN(0) - const assetAlias: string = "asset1" - const name: string = "asset1" - const symbol: string = "MFCA" - const denomination: number = 1 - const outs: TransferableOutput[] = [] - const ins: TransferableInput[] = [] - const vcapSecpOutput = new SECPTransferOutput( - amount, - [addressBuf], - locktime, - threshold - ) - const initialStates: InitialStates = new InitialStates() - initialStates.addOutput(vcapSecpOutput) - const genesisAsset: GenesisAsset = new GenesisAsset( - assetAlias, - name, - symbol, - denomination, - initialStates, - memo - ) - const genesisAsset2: GenesisAsset = new GenesisAsset() - genesisAsset2.fromBuffer(genesisAsset.toBuffer()) - expect(genesisAsset.toBuffer().toString("hex")).toBe( - genesisAsset2.toBuffer().toString("hex") - ) - expect(genesisAsset.getTypeName()).toBe("GenesisAsset") - expect(genesisAsset.getTypeID()).toBeUndefined() - expect(genesisAsset.getCodecID()).toBeUndefined() - expect(genesisAsset.getNetworkID()).toBe(DefaultNetworkID) - expect(genesisAsset.getName()).toBe(name) - expect(genesisAsset.getAssetAlias()).toBe(assetAlias) - expect(genesisAsset.getSymbol()).toBe(symbol) - expect(genesisAsset.getDenomination()).toBe(denomination) - expect(genesisAsset.getBlockchainID().toString(hex)).toBe(blockchainIDHex) - expect(genesisAsset.getIns()).toEqual(outs) - expect(genesisAsset.getOuts()).toEqual(ins) - expect(genesisAsset.getInitialStates()).toStrictEqual(initialStates) - expect(genesisAsset.getMemo().toString(hex)).toBe(mHex) - }) -}) diff --git a/tests/apis/avm/genesisdata.test.ts b/tests/apis/avm/genesisdata.test.ts deleted file mode 100644 index 82632005b..000000000 --- a/tests/apis/avm/genesisdata.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import BN from "bn.js" -import { Buffer } from "buffer/" -import { SECPTransferOutput } from "../../../src/apis/avm/outputs" -import { InitialStates } from "../../../src/apis/avm/initialstates" -import { GenesisData, GenesisAsset, AVMConstants } from "../../../src/apis/avm" -import { Serialization, SerializedType } from "../../../src/utils" - -/** - * @ignore - */ -const serialization: Serialization = Serialization.getInstance() -describe("AVM", (): void => { - test("GenesisData", (): void => { - const networkID: number = 1337 - const m: string = "2Zc54v4ek37TEwu4LiV3j41PUMRd6acDDU3ZCVSxE7X" - const cb58: SerializedType = "cb58" - const memo: Buffer = serialization.typeToBuffer(m, cb58) - const amount: BN = new BN(100000) - const address: string = "X-local18jma8ppw3nhx5r4ap8clazz0dps7rv5u00z96u" - const bech32: SerializedType = "bech32" - const addressBuf: Buffer = serialization.typeToBuffer(address, bech32) - const threshold: number = 1 - const locktime: BN = new BN(0) - const assetAlias: string = "asset1" - const name: string = "asset1" - const symbol: string = "MFCA" - const denomination: number = 1 - const vcapSecpOutput = new SECPTransferOutput( - amount, - [addressBuf], - locktime, - threshold - ) - const initialStates: InitialStates = new InitialStates() - initialStates.addOutput(vcapSecpOutput) - const genesisAsset: GenesisAsset = new GenesisAsset( - assetAlias, - name, - symbol, - denomination, - initialStates, - memo - ) - const genesisAssets: GenesisAsset[] = [genesisAsset] - const genesisData: GenesisData = new GenesisData(genesisAssets, networkID) - const genesisData2: GenesisData = new GenesisData() - genesisData2.fromBuffer(genesisData.toBuffer()) - expect(genesisData.toBuffer().toString("hex")).toBe( - genesisData2.toBuffer().toString("hex") - ) - expect(genesisData.getTypeName()).toBe("GenesisData") - expect(genesisData.getTypeID()).toBeUndefined() - expect(genesisData.getCodecID()).toBe(AVMConstants.LATESTCODEC) - expect(genesisData.getNetworkID()).toBe(networkID) - expect(genesisData.getGenesisAssets()).toStrictEqual(genesisAssets) - }) -}) diff --git a/tests/apis/avm/inputs.test.ts b/tests/apis/avm/inputs.test.ts deleted file mode 100644 index 3ff0f7eff..000000000 --- a/tests/apis/avm/inputs.test.ts +++ /dev/null @@ -1,195 +0,0 @@ -import { UTXOSet, UTXO } from "../../../src/apis/avm/utxos" -import { KeyChain } from "../../../src/apis/avm/keychain" -import { - SECPTransferInput, - TransferableInput -} from "../../../src/apis/avm/inputs" -import createHash from "create-hash" -import BinTools from "../../../src/utils/bintools" -import BN from "bn.js" -import { Buffer } from "buffer/" -import { - SECPTransferOutput, - AmountOutput, - TransferableOutput -} from "../../../src/apis/avm/outputs" -import { AVMConstants } from "../../../src/apis/avm/constants" -import { Input } from "../../../src/common/input" -import { Output } from "../../../src/common/output" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() - -describe("Inputs", (): void => { - let set: UTXOSet - let keymgr1: KeyChain - let keymgr2: KeyChain - let addrs1: Buffer[] - let addrs2: Buffer[] - let utxos: UTXO[] - let hrp: string = "tests" - const amnt: number = 10000 - const codecID_zero: number = 0 - const codecID_one: number = 1 - beforeEach((): void => { - set = new UTXOSet() - keymgr1 = new KeyChain(hrp, "X") - keymgr2 = new KeyChain(hrp, "X") - addrs1 = [] - addrs2 = [] - utxos = [] - for (let i: number = 0; i < 3; i++) { - addrs1.push(keymgr1.makeKey().getAddress()) - addrs2.push(keymgr2.makeKey().getAddress()) - } - const amount: BN = new BN(amnt) - const addresses: Buffer[] = keymgr1.getAddresses() - const locktime: BN = new BN(54321) - const threshold: number = 3 - - for (let i: number = 0; i < 3; i++) { - const txid: Buffer = Buffer.from( - createHash("sha256") - .update(bintools.fromBNToBuffer(new BN(i), 32)) - .digest() - ) - const txidx: Buffer = Buffer.from(bintools.fromBNToBuffer(new BN(i), 4)) - const assetID: Buffer = Buffer.from( - createHash("sha256").update(txid).digest() - ) - const out: Output = new SECPTransferOutput( - amount.add(new BN(i)), - addresses, - locktime, - threshold - ) - const xferout: TransferableOutput = new TransferableOutput(assetID, out) - const u: UTXO = new UTXO( - AVMConstants.LATESTCODEC, - txid, - txidx, - assetID, - out - ) - u.fromBuffer( - Buffer.concat([u.getCodecIDBuffer(), txid, txidx, xferout.toBuffer()]) - ) - utxos.push(u) - } - set.addArray(utxos) - }) - test("SECPInput", (): void => { - let u: UTXO - let txid: Buffer - let txidx: Buffer - const amount: BN = new BN(amnt) - let input: SECPTransferInput - let xferinput: TransferableInput - - u = utxos[0] - txid = u.getTxID() - txidx = u.getOutputIdx() - const asset = u.getAssetID() - - input = new SECPTransferInput(amount) - xferinput = new TransferableInput(txid, txidx, asset, input) - expect(xferinput.getUTXOID()).toBe(u.getUTXOID()) - expect(input.getInputID()).toBe(AVMConstants.SECPINPUTID) - - input.addSignatureIdx(0, addrs2[0]) - input.addSignatureIdx(1, addrs2[1]) - - const newin: SECPTransferInput = new SECPTransferInput() - newin.fromBuffer(bintools.b58ToBuffer(input.toString())) - expect(newin.toBuffer().toString("hex")).toBe( - input.toBuffer().toString("hex") - ) - expect(newin.getSigIdxs().toString()).toBe(input.getSigIdxs().toString()) - }) - - test("Input comparator", (): void => { - const inpt1: SECPTransferInput = new SECPTransferInput( - (utxos[0].getOutput() as AmountOutput).getAmount() - ) - const inpt2: SECPTransferInput = new SECPTransferInput( - (utxos[1].getOutput() as AmountOutput).getAmount() - ) - const inpt3: SECPTransferInput = new SECPTransferInput( - (utxos[2].getOutput() as AmountOutput).getAmount() - ) - const cmp = Input.comparator() - expect(cmp(inpt1, inpt2)).toBe(-1) - expect(cmp(inpt1, inpt3)).toBe(-1) - expect(cmp(inpt1, inpt1)).toBe(0) - expect(cmp(inpt2, inpt2)).toBe(0) - expect(cmp(inpt3, inpt3)).toBe(0) - }) - - test("TransferableInput comparator", (): void => { - const inpt1: SECPTransferInput = new SECPTransferInput( - (utxos[0].getOutput() as AmountOutput).getAmount() - ) - const in1: TransferableInput = new TransferableInput( - utxos[0].getTxID(), - utxos[0].getOutputIdx(), - utxos[0].getAssetID(), - inpt1 - ) - - const inpt2: SECPTransferInput = new SECPTransferInput( - (utxos[1].getOutput() as AmountOutput).getAmount() - ) - const in2: TransferableInput = new TransferableInput( - utxos[1].getTxID(), - utxos[1].getOutputIdx(), - utxos[1].getAssetID(), - inpt2 - ) - - const inpt3: SECPTransferInput = new SECPTransferInput( - (utxos[2].getOutput() as AmountOutput).getAmount() - ) - const in3: TransferableInput = new TransferableInput( - utxos[2].getTxID(), - utxos[2].getOutputIdx(), - utxos[2].getAssetID(), - inpt3 - ) - - const cmp = TransferableInput.comparator() - expect(cmp(in1, in2)).toBe(-1) - expect(cmp(in1, in3)).toBe(-1) - expect(cmp(in1, in1)).toBe(0) - expect(cmp(in2, in2)).toBe(0) - expect(cmp(in3, in3)).toBe(0) - }) - - test("SECPTransferInput codecIDs", (): void => { - const secpTransferInput: SECPTransferInput = new SECPTransferInput( - (utxos[0].getOutput() as AmountOutput).getAmount() - ) - expect(secpTransferInput.getCodecID()).toBe(codecID_zero) - expect(secpTransferInput.getInputID()).toBe(AVMConstants.SECPINPUTID) - secpTransferInput.setCodecID(codecID_one) - expect(secpTransferInput.getCodecID()).toBe(codecID_one) - expect(secpTransferInput.getInputID()).toBe( - AVMConstants.SECPINPUTID_CODECONE - ) - secpTransferInput.setCodecID(codecID_zero) - expect(secpTransferInput.getCodecID()).toBe(codecID_zero) - expect(secpTransferInput.getInputID()).toBe(AVMConstants.SECPINPUTID) - }) - - test("Invalid SECPTransferInput codecID", (): void => { - const secpTransferInput: SECPTransferInput = new SECPTransferInput( - (utxos[0].getOutput() as AmountOutput).getAmount() - ) - expect((): void => { - secpTransferInput.setCodecID(2) - }).toThrow( - "Error - SECPTransferInput.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - }) -}) diff --git a/tests/apis/avm/keychain.test.ts b/tests/apis/avm/keychain.test.ts deleted file mode 100644 index 7a59b2e22..000000000 --- a/tests/apis/avm/keychain.test.ts +++ /dev/null @@ -1,271 +0,0 @@ -import { KeyChain, KeyPair } from "../../../src/apis/avm/keychain" -import { Avalanche } from "../../../src/index" -import { Buffer } from "buffer/" -import createHash from "create-hash" -import BinTools from "../../../src/utils/bintools" - -const bintools: BinTools = BinTools.getInstance() -const alias: string = "X" -const hrp: string = "tests" - -describe("AVMKeyPair", (): void => { - const networkID: number = 1337 - const ip: string = "127.0.0.1" - const port: number = 9650 - const protocol: string = "https" - const avalanche: Avalanche = new Avalanche( - ip, - port, - protocol, - networkID, - undefined, - undefined, - undefined, - true - ) - - test("human readable part", (): void => { - let hrp: string = avalanche.getHRP() - - let networkID: number = avalanche.getNetworkID() - expect(hrp).toBe("custom") - expect(networkID).toBe(1337) - - avalanche.setNetworkID(2) - hrp = avalanche.getHRP() - networkID = avalanche.getNetworkID() - expect(hrp).toBe("cascade") - expect(networkID).toBe(2) - - avalanche.setNetworkID(3) - hrp = avalanche.getHRP() - networkID = avalanche.getNetworkID() - expect(hrp).toBe("denali") - expect(networkID).toBe(3) - - avalanche.setNetworkID(4) - hrp = avalanche.getHRP() - networkID = avalanche.getNetworkID() - expect(hrp).toBe("everest") - expect(networkID).toBe(4) - - avalanche.setNetworkID(0) - hrp = avalanche.getHRP() - networkID = avalanche.getNetworkID() - expect(hrp).toBe("custom") - expect(networkID).toBe(0) - - avalanche.setNetworkID(1) - hrp = avalanche.getHRP() - networkID = avalanche.getNetworkID() - expect(hrp).toBe("avax") - expect(networkID).toBe(1) - - avalanche.setNetworkID(12345) - hrp = avalanche.getHRP() - networkID = avalanche.getNetworkID() - expect(hrp).toBe("local") - expect(networkID).toBe(12345) - }) - - test("repeatable 1", (): void => { - const kp: KeyPair = new KeyPair(hrp, alias) - kp.importKey( - Buffer.from( - "ef9bf2d4436491c153967c9709dd8e82795bdb9b5ad44ee22c2903005d1cf676", - "hex" - ) - ) - expect(kp.getPublicKey().toString("hex")).toBe( - "033fad3644deb20d7a210d12757092312451c112d04773cee2699fbb59dc8bb2ef" - ) - - const msg: Buffer = Buffer.from( - createHash("sha256").update(Buffer.from("09090909", "hex")).digest("hex"), - "hex" - ) - const sig: Buffer = kp.sign(msg) - - expect(sig.length).toBe(65) - expect(kp.verify(msg, sig)).toBe(true) - expect(kp.recover(msg, sig).toString("hex")).toBe( - kp.getPublicKey().toString("hex") - ) - }) - - test("bad private key", (): void => { - const kp: KeyPair = new KeyPair("badnetworkid", alias) - const badPrivateKey: string = "safasaf" - const result: boolean = kp.importKey(Buffer.from(badPrivateKey, "hex")) - expect(result).toBe(false) - }) - - test("repeatable 2", (): void => { - const kp: KeyPair = new KeyPair(hrp, alias) - kp.importKey( - Buffer.from( - "17c692d4a99d12f629d9f0ff92ec0dba15c9a83e85487b085c1a3018286995c6", - "hex" - ) - ) - expect(kp.getPublicKey().toString("hex")).toBe( - "02486553b276cfe7abf0efbcd8d173e55db9c03da020c33d0b219df24124da18ee" - ) - - const msg: Buffer = Buffer.from( - createHash("sha256").update(Buffer.from("09090909", "hex")).digest("hex"), - "hex" - ) - const sig: Buffer = kp.sign(msg) - - expect(sig.length).toBe(65) - expect(kp.verify(msg, sig)).toBe(true) - expect(kp.recover(msg, sig).toString("hex")).toBe( - kp.getPublicKey().toString("hex") - ) - }) - - test("repeatable 3", (): void => { - const kp: KeyPair = new KeyPair(hrp, alias) - kp.importKey( - Buffer.from( - "d0e17d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - ) - expect(kp.getPublicKey().toString("hex")).toBe( - "031475b91d4fcf52979f1cf107f058088cc2bea6edd51915790f27185a7586e2f2" - ) - - const msg: Buffer = Buffer.from( - createHash("sha256").update(Buffer.from("09090909", "hex")).digest("hex"), - "hex" - ) - const sig: Buffer = kp.sign(msg) - - expect(sig.length).toBe(65) - expect(kp.verify(msg, sig)).toBe(true) - expect(kp.recover(msg, sig).toString("hex")).toBe( - kp.getPublicKey().toString("hex") - ) - }) - - test("Creation Empty", (): void => { - const kp: KeyPair = new KeyPair(hrp, alias) - expect(kp.getPrivateKey()).not.toBeUndefined() - expect(kp.getAddress()).not.toBeUndefined() - expect(kp.getPrivateKeyString()).not.toBeUndefined() - expect(kp.getPublicKey()).not.toBeUndefined() - expect(kp.getPublicKeyString()).not.toBeUndefined() - const msg: Buffer = Buffer.from( - createHash("sha256").update(Buffer.from("09090909", "hex")).digest("hex"), - "hex" - ) - const sig: Buffer = kp.sign(msg) - - expect(sig.length).toBe(65) - expect(kp.verify(msg, sig)).toBe(true) - expect(kp.recover(msg, sig).toString("hex")).toBe( - kp.getPublicKey().toString("hex") - ) - }) -}) - -describe("AVMKeyChain", (): void => { - test("importKey from Buffer", (): void => { - const keybuff: Buffer = Buffer.from( - "d0e17d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - const kc: KeyChain = new KeyChain(hrp, alias) - const kp2: KeyPair = new KeyPair(hrp, alias) - const addr1: Buffer = kc.importKey(keybuff).getAddress() - const kp1: KeyPair = kc.getKey(addr1) - kp2.importKey(keybuff) - const addr2 = kp1.getAddress() - expect(addr1.toString("hex")).toBe(addr2.toString("hex")) - expect(kp1.getPrivateKeyString()).toBe(kp2.getPrivateKeyString()) - expect(kp1.getPublicKeyString()).toBe(kp2.getPublicKeyString()) - expect(kc.hasKey(addr1)).toBe(true) - }) - - test("importKey from Buffer with leading zeros", (): void => { - const keybuff: Buffer = Buffer.from( - "00007d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - expect(keybuff.length).toBe(32) - const kc: KeyChain = new KeyChain(hrp, alias) - const kp2: KeyPair = new KeyPair(hrp, alias) - const addr1: Buffer = kc.importKey(keybuff).getAddress() - const kp1: KeyPair = kc.getKey(addr1) - kp2.importKey(keybuff) - const addr2 = kp1.getAddress() - expect(addr1.toString("hex")).toBe(addr2.toString("hex")) - expect(kp1.getPrivateKeyString()).toBe(kp2.getPrivateKeyString()) - expect(kp1.getPrivateKey().length).toBe(32) - expect(kp2.getPrivateKey().length).toBe(32) - expect(kp1.getPublicKeyString()).toBe(kp2.getPublicKeyString()) - expect(kp1.getPublicKey().length).toBe(33) - expect(kp2.getPublicKey().length).toBe(33) - expect(kc.hasKey(addr1)).toBe(true) - }) - - test("importKey from serialized string", (): void => { - const keybuff: Buffer = Buffer.from( - "d0e17d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - const kc: KeyChain = new KeyChain(hrp, alias) - const kp2: KeyPair = new KeyPair(hrp, alias) - const addr1: Buffer = kc - .importKey("PrivateKey-" + bintools.cb58Encode(keybuff)) - .getAddress() - const kp1: KeyPair = kc.getKey(addr1) - kp2.importKey(keybuff) - const addr2 = kp1.getAddress() - expect(addr1.toString("hex")).toBe(addr2.toString("hex")) - expect(kp1.getPrivateKeyString()).toBe(kp2.getPrivateKeyString()) - expect(kp1.getPublicKeyString()).toBe(kp2.getPublicKeyString()) - expect(kc.hasKey(addr1)).toBe(true) - }) - - test("removeKey via keypair", (): void => { - const keybuff: Buffer = Buffer.from( - "d0e17d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - const kc: KeyChain = new KeyChain(hrp, alias) - const kp1: KeyPair = new KeyPair(hrp, alias) - const addr1: Buffer = kc.importKey(keybuff).getAddress() - kp1.importKey(keybuff) - expect(kc.hasKey(addr1)).toBe(true) - kc.removeKey(kp1) - expect(kc.hasKey(addr1)).toBe(false) - }) - - test("removeKey via string", (): void => { - const keybuff: Buffer = Buffer.from( - "d0e17d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - const kc: KeyChain = new KeyChain(hrp, alias) - const addr1: Buffer = kc.importKey(keybuff).getAddress() - expect(kc.hasKey(addr1)).toBe(true) - kc.removeKey(addr1) - expect(kc.hasKey(addr1)).toBe(false) - }) - - test("removeKey bad keys", (): void => { - const keybuff: Buffer = Buffer.from( - "d0e17d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - const kc: KeyChain = new KeyChain(hrp, alias) - const addr1: Buffer = kc.importKey(keybuff).getAddress() - expect(kc.hasKey(addr1)).toBe(true) - expect( - kc.removeKey(bintools.cb58Decode("6Y3kysjF9jnHnYkdS9yGAuoHyae2eNmeV")) - ).toBe(false) - }) -}) diff --git a/tests/apis/avm/ops.test.ts b/tests/apis/avm/ops.test.ts deleted file mode 100644 index 8f29bcf5f..000000000 --- a/tests/apis/avm/ops.test.ts +++ /dev/null @@ -1,296 +0,0 @@ -import { UTXO } from "../../../src/apis/avm/utxos" -import createHash from "create-hash" -import BinTools from "../../../src/utils/bintools" -import BN from "bn.js" -import { Buffer } from "buffer/" -import { NFTTransferOutput } from "../../../src/apis/avm/outputs" -import { AVMConstants } from "../../../src/apis/avm/constants" -import { - SelectOperationClass, - Operation, - TransferableOperation, - NFTTransferOperation, - NFTMintOperation -} from "../../../src/apis/avm/ops" -import { OutputOwners } from "../../../src/common/output" -import { SigIdx } from "../../../src/common/credentials" -import { UTXOID } from "../../../src/apis/avm/ops" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() - -describe("Operations", (): void => { - const codecID_zero: number = 0 - const codecID_one: number = 1 - const assetID: string = - "8a5d2d32e68bc50036e4d086044617fe4a0a0296b274999ba568ea92da46d533" - const assetIDBuff: Buffer = Buffer.from(assetID, "hex") - const addrs: Buffer[] = [ - bintools.cb58Decode("B6D4v1VtPYLbiUvYXtW4Px8oE9imC2vGW"), - bintools.cb58Decode("P5wdRuZeaDt28eHMP5S3w9ZdoBfo7wuzF"), - bintools.cb58Decode("6Y3kysjF9jnHnYkdS9yGAuoHyae2eNmeV") - ].sort() - - const locktime: BN = new BN(54321) - - const payload: Buffer = Buffer.alloc(1024) - payload.write( - "All you Trekkies and TV addicts, Don't mean to diss don't mean to bring static.", - 0, - 1024, - "utf8" - ) - - describe("NFTMintOperation", (): void => { - test("SelectOperationClass", (): void => { - const goodop: NFTMintOperation = new NFTMintOperation( - 0, - Buffer.from(""), - [] - ) - const operation: Operation = SelectOperationClass(goodop.getOperationID()) - expect(operation).toBeInstanceOf(NFTMintOperation) - expect(() => { - SelectOperationClass(99) - }).toThrow("Error - SelectOperationClass: unknown opid") - }) - - test("comparator", (): void => { - const outputOwners: OutputOwners[] = [] - outputOwners.push(new OutputOwners(addrs, locktime, 1)) - const op1: NFTMintOperation = new NFTMintOperation( - 1, - payload, - outputOwners - ) - const op2: NFTMintOperation = new NFTMintOperation( - 2, - payload, - outputOwners - ) - const op3: NFTMintOperation = new NFTMintOperation( - 0, - payload, - outputOwners - ) - const cmp = NFTMintOperation.comparator() - expect(cmp(op1, op1)).toBe(0) - expect(cmp(op2, op2)).toBe(0) - expect(cmp(op3, op3)).toBe(0) - expect(cmp(op1, op2)).toBe(-1) - expect(cmp(op1, op3)).toBe(1) - }) - - test("Functionality", (): void => { - const outputOwners: OutputOwners[] = [] - outputOwners.push(new OutputOwners(addrs, locktime, 1)) - const op: NFTMintOperation = new NFTMintOperation( - 0, - payload, - outputOwners - ) - - expect(op.getOperationID()).toBe(AVMConstants.NFTMINTOPID) - expect(op.getOutputOwners().toString()).toBe(outputOwners.toString()) - - const opcopy: NFTMintOperation = new NFTMintOperation() - const opb: Buffer = op.toBuffer() - opcopy.fromBuffer(opb) - expect(opcopy.toString()).toBe(op.toString()) - }) - - test("NFTMintOperation codecIDs", (): void => { - const outputOwners: OutputOwners[] = [] - outputOwners.push(new OutputOwners(addrs, locktime, 1)) - const nftMintOperation: NFTMintOperation = new NFTMintOperation( - 0, - payload, - outputOwners - ) - expect(nftMintOperation.getCodecID()).toBe(codecID_zero) - expect(nftMintOperation.getOperationID()).toBe(AVMConstants.NFTMINTOPID) - nftMintOperation.setCodecID(codecID_one) - expect(nftMintOperation.getCodecID()).toBe(codecID_one) - expect(nftMintOperation.getOperationID()).toBe( - AVMConstants.NFTMINTOPID_CODECONE - ) - nftMintOperation.setCodecID(codecID_zero) - expect(nftMintOperation.getCodecID()).toBe(codecID_zero) - expect(nftMintOperation.getOperationID()).toBe(AVMConstants.NFTMINTOPID) - }) - - test("Invalid NFTMintOperation codecID", (): void => { - const outputOwners: OutputOwners[] = [] - outputOwners.push(new OutputOwners(addrs, locktime, 1)) - const nftMintOperation: NFTMintOperation = new NFTMintOperation( - 0, - payload, - outputOwners - ) - expect(() => { - nftMintOperation.setCodecID(2) - }).toThrow( - "Error - NFTMintOperation.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - }) - }) - - describe("NFTTransferOperation", (): void => { - test("SelectOperationClass", (): void => { - const nout: NFTTransferOutput = new NFTTransferOutput( - 1000, - payload, - addrs, - locktime, - 1 - ) - const goodop: NFTTransferOperation = new NFTTransferOperation(nout) - const operation: Operation = SelectOperationClass(goodop.getOperationID()) - expect(operation).toBeInstanceOf(NFTTransferOperation) - expect((): void => { - SelectOperationClass(99) - }).toThrow("Error - SelectOperationClass: unknown opid") - }) - - test("comparator", (): void => { - const op1: NFTTransferOperation = new NFTTransferOperation( - new NFTTransferOutput(1000, payload, addrs, locktime, 1) - ) - const op2: NFTTransferOperation = new NFTTransferOperation( - new NFTTransferOutput(1001, payload, addrs, locktime, 1) - ) - const op3: NFTTransferOperation = new NFTTransferOperation( - new NFTTransferOutput(999, payload, addrs, locktime, 1) - ) - const cmp = NFTTransferOperation.comparator() - expect(cmp(op1, op1)).toBe(0) - expect(cmp(op2, op2)).toBe(0) - expect(cmp(op3, op3)).toBe(0) - expect(cmp(op1, op2)).toBe(-1) - expect(cmp(op1, op3)).toBe(1) - }) - - test("Functionality", (): void => { - const nout: NFTTransferOutput = new NFTTransferOutput( - 1000, - payload, - addrs, - locktime, - 1 - ) - const op: NFTTransferOperation = new NFTTransferOperation(nout) - - expect(op.getOperationID()).toBe(AVMConstants.NFTXFEROPID) - expect(op.getOutput().toString()).toBe(nout.toString()) - - const opcopy: NFTTransferOperation = new NFTTransferOperation() - opcopy.fromBuffer(op.toBuffer()) - expect(opcopy.toString()).toBe(op.toString()) - - op.addSignatureIdx(0, addrs[0]) - const sigidx: SigIdx[] = op.getSigIdxs() - expect(sigidx[0].getSource().toString("hex")).toBe( - addrs[0].toString("hex") - ) - opcopy.fromBuffer(op.toBuffer()) - expect(opcopy.toString()).toBe(op.toString()) - }) - - test("NFTTransferOperation codecIDs", (): void => { - const nftTransferOperation: NFTTransferOperation = - new NFTTransferOperation( - new NFTTransferOutput(1000, payload, addrs, locktime, 1) - ) - expect(nftTransferOperation.getCodecID()).toBe(codecID_zero) - expect(nftTransferOperation.getOperationID()).toBe( - AVMConstants.NFTXFEROPID - ) - nftTransferOperation.setCodecID(codecID_one) - expect(nftTransferOperation.getCodecID()).toBe(codecID_one) - expect(nftTransferOperation.getOperationID()).toBe( - AVMConstants.NFTXFEROPID_CODECONE - ) - nftTransferOperation.setCodecID(codecID_zero) - expect(nftTransferOperation.getCodecID()).toBe(codecID_zero) - expect(nftTransferOperation.getOperationID()).toBe( - AVMConstants.NFTXFEROPID - ) - }) - - test("Invalid NFTTransferOperation codecID", (): void => { - const nftTransferOperation: NFTTransferOperation = - new NFTTransferOperation( - new NFTTransferOutput(1000, payload, addrs, locktime, 1) - ) - expect((): void => { - nftTransferOperation.setCodecID(2) - }).toThrow( - "Error - NFTTransferOperation.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - }) - }) - - test("TransferableOperation", (): void => { - const nout: NFTTransferOutput = new NFTTransferOutput( - 1000, - payload, - addrs, - locktime, - 1 - ) - const op: NFTTransferOperation = new NFTTransferOperation(nout) - const nfttxid: Buffer = Buffer.from( - createHash("sha256") - .update(bintools.fromBNToBuffer(new BN(1000), 32)) - .digest() - ) - const nftoutputidx: Buffer = Buffer.from( - bintools.fromBNToBuffer(new BN(1000), 4) - ) - const nftutxo: UTXO = new UTXO( - AVMConstants.LATESTCODEC, - nfttxid, - nftoutputidx, - assetIDBuff, - nout - ) - const xferop: TransferableOperation = new TransferableOperation( - assetIDBuff, - [nftutxo.getUTXOID()], - op - ) - - const xferop2: TransferableOperation = new TransferableOperation( - assetIDBuff, - [Buffer.concat([nfttxid, nftoutputidx])], - op - ) - const uid: UTXOID = new UTXOID() - uid.fromString(nftutxo.getUTXOID()) - const xferop3: TransferableOperation = new TransferableOperation( - assetIDBuff, - [uid], - op - ) - - expect(xferop.getAssetID().toString("hex")).toBe(assetID) - const utxoiddeserialized: Buffer = bintools.cb58Decode( - xferop.getUTXOIDs()[0].toString() - ) - expect(bintools.bufferToB58(utxoiddeserialized)).toBe(nftutxo.getUTXOID()) - expect(xferop.getOperation().toString()).toBe(op.toString()) - - const opcopy: TransferableOperation = new TransferableOperation() - opcopy.fromBuffer(xferop.toBuffer()) - expect(opcopy.toString()).toBe(xferop.toString()) - - expect(xferop2.toBuffer().toString("hex")).toBe( - xferop.toBuffer().toString("hex") - ) - expect(xferop3.toBuffer().toString("hex")).toBe( - xferop.toBuffer().toString("hex") - ) - }) -}) diff --git a/tests/apis/avm/outputs.test.ts b/tests/apis/avm/outputs.test.ts deleted file mode 100644 index 22c8e68eb..000000000 --- a/tests/apis/avm/outputs.test.ts +++ /dev/null @@ -1,318 +0,0 @@ -import BN from "bn.js" -import { Buffer } from "buffer/" -import BinTools from "../../../src/utils/bintools" -import { - SECPTransferOutput, - SelectOutputClass, - NFTMintOutput -} from "../../../src/apis/avm/outputs" -import { Output } from "../../../src/common/output" -import { SECPMintOutput } from "../../../src/apis/avm/outputs" -import { AVMConstants } from "../../../src/apis/avm" - -const bintools: BinTools = BinTools.getInstance() - -describe("Outputs", (): void => { - const codecID_zero: number = 0 - const codecID_one: number = 1 - describe("NFTMintOutput", (): void => { - const addrs: Buffer[] = [ - bintools.cb58Decode("B6D4v1VtPYLbiUvYXtW4Px8oE9imC2vGW"), - bintools.cb58Decode("P5wdRuZeaDt28eHMP5S3w9ZdoBfo7wuzF"), - bintools.cb58Decode("6Y3kysjF9jnHnYkdS9yGAuoHyae2eNmeV") - ].sort() - - const locktime: BN = new BN(54321) - const addrpay = [addrs[0], addrs[1]] - const fallLocktime: BN = locktime.add(new BN(50)) - - test("SelectOutputClass", (): void => { - const goodout: NFTMintOutput = new NFTMintOutput( - 0, - addrpay, - fallLocktime, - 1 - ) - const outpayment: Output = SelectOutputClass(goodout.getOutputID()) - expect(outpayment).toBeInstanceOf(NFTMintOutput) - expect((): void => { - SelectOutputClass(99) - }).toThrow("Error - SelectOutputClass: unknown outputid") - }) - - test("comparator", (): void => { - const outpayment1: Output = new NFTMintOutput(1, addrs, fallLocktime, 1) - const outpayment2: Output = new NFTMintOutput(2, addrs, fallLocktime, 1) - const outpayment3: Output = new NFTMintOutput(0, addrs, fallLocktime, 1) - const cmp = Output.comparator() - expect(cmp(outpayment1, outpayment1)).toBe(0) - expect(cmp(outpayment2, outpayment2)).toBe(0) - expect(cmp(outpayment3, outpayment3)).toBe(0) - expect(cmp(outpayment1, outpayment2)).toBe(-1) - expect(cmp(outpayment1, outpayment3)).toBe(1) - }) - - test("NFTMintOutput codecIDs", (): void => { - const nftMintOutput: NFTMintOutput = new NFTMintOutput( - 1, - addrs, - fallLocktime, - 1 - ) - - expect(nftMintOutput.getCodecID()).toBe(codecID_zero) - expect(nftMintOutput.getOutputID()).toBe(AVMConstants.NFTMINTOUTPUTID) - nftMintOutput.setCodecID(codecID_one) - expect(nftMintOutput.getCodecID()).toBe(codecID_one) - expect(nftMintOutput.getOutputID()).toBe( - AVMConstants.NFTMINTOUTPUTID_CODECONE - ) - nftMintOutput.setCodecID(codecID_zero) - expect(nftMintOutput.getCodecID()).toBe(codecID_zero) - expect(nftMintOutput.getOutputID()).toBe(AVMConstants.NFTMINTOUTPUTID) - }) - - test("Invalid NFTMintOutput codecID", (): void => { - const nftMintOutput: NFTMintOutput = new NFTMintOutput( - 1, - addrs, - fallLocktime, - 1 - ) - expect((): void => { - nftMintOutput.setCodecID(2) - }).toThrow( - "Error - NFTMintOutput.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - }) - - test("Functionality", (): void => { - const out: NFTMintOutput = new NFTMintOutput(0, addrs, fallLocktime, 3) - expect(out.getOutputID()).toBe(10) - expect(JSON.stringify(out.getAddresses().sort())).toStrictEqual( - JSON.stringify(addrs.sort()) - ) - - expect(out.getThreshold()).toBe(3) - // expect(out.getLocktime().toNumber()).toBe(locktime.toNumber()) - - const r = out.getAddressIdx(addrs[2]) - expect(out.getAddress(r)).toStrictEqual(addrs[2]) - expect((): void => { - out.getAddress(400) - }).toThrow() - - const b: Buffer = out.toBuffer() - expect(out.toString()).toBe(bintools.bufferToB58(b)) - - const s: Buffer[] = out.getSpenders(addrs) - expect(JSON.stringify(s.sort())).toBe(JSON.stringify(addrs.sort())) - - const m1: boolean = out.meetsThreshold([addrs[0]]) - expect(m1).toBe(false) - const m2: boolean = out.meetsThreshold(addrs, new BN(100)) - expect(m2).toBe(false) - const m3: boolean = out.meetsThreshold(addrs) - expect(m3).toBe(true) - const m4: boolean = out.meetsThreshold(addrs, locktime.add(new BN(100))) - expect(m4).toBe(true) - }) - }) - - describe("SECPTransferOutput", (): void => { - const addrs: Buffer[] = [ - bintools.cb58Decode("B6D4v1VtPYLbiUvYXtW4Px8oE9imC2vGW"), - bintools.cb58Decode("P5wdRuZeaDt28eHMP5S3w9ZdoBfo7wuzF"), - bintools.cb58Decode("6Y3kysjF9jnHnYkdS9yGAuoHyae2eNmeV") - ].sort() - - const locktime: BN = new BN(54321) - const addrpay: Buffer[] = [addrs[0], addrs[1]] - const fallLocktime: BN = locktime.add(new BN(50)) - - test("SelectOutputClass", (): void => { - const goodout: SECPTransferOutput = new SECPTransferOutput( - new BN(2600), - addrpay, - fallLocktime, - 1 - ) - const outpayment: Output = SelectOutputClass(goodout.getOutputID()) - expect(outpayment).toBeInstanceOf(SECPTransferOutput) - expect((): void => { - SelectOutputClass(99) - }).toThrow("Error - SelectOutputClass: unknown outputid") - }) - - test("comparator", (): void => { - const outpayment1: Output = new SECPTransferOutput( - new BN(10000), - addrs, - locktime, - 3 - ) - const outpayment2: Output = new SECPTransferOutput( - new BN(10001), - addrs, - locktime, - 3 - ) - const outpayment3: Output = new SECPTransferOutput( - new BN(9999), - addrs, - locktime, - 3 - ) - const cmp = Output.comparator() - expect(cmp(outpayment1, outpayment1)).toBe(0) - expect(cmp(outpayment2, outpayment2)).toBe(0) - expect(cmp(outpayment3, outpayment3)).toBe(0) - expect(cmp(outpayment1, outpayment2)).toBe(-1) - expect(cmp(outpayment1, outpayment3)).toBe(1) - }) - - test("SECPTransferOutput", (): void => { - const out: SECPTransferOutput = new SECPTransferOutput( - new BN(10000), - addrs, - locktime, - 3 - ) - expect(out.getOutputID()).toBe(7) - expect(JSON.stringify(out.getAddresses().sort())).toStrictEqual( - JSON.stringify(addrs.sort()) - ) - - expect(out.getThreshold()).toBe(3) - expect(out.getLocktime().toNumber()).toBe(locktime.toNumber()) - - const r: number = out.getAddressIdx(addrs[2]) - expect(out.getAddress(r)).toStrictEqual(addrs[2]) - expect((): void => { - out.getAddress(400) - }).toThrow() - - expect(out.getAmount().toNumber()).toBe(10000) - - const b: Buffer = out.toBuffer() - expect(out.toString()).toBe(bintools.bufferToB58(b)) - - const s: Buffer[] = out.getSpenders(addrs) - expect(JSON.stringify(s.sort())).toBe(JSON.stringify(addrs.sort())) - - const m1: boolean = out.meetsThreshold([addrs[0]]) - expect(m1).toBe(false) - const m2: boolean = out.meetsThreshold(addrs, new BN(100)) - expect(m2).toBe(false) - const m3: boolean = out.meetsThreshold(addrs) - expect(m3).toBe(true) - const m4: boolean = out.meetsThreshold(addrs, locktime.add(new BN(100))) - expect(m4).toBe(true) - }) - - test("SECPTransferOutput codecIDs", (): void => { - const secPTransferOutput: SECPTransferOutput = new SECPTransferOutput( - new BN(10000), - addrs, - locktime, - 3 - ) - expect(secPTransferOutput.getCodecID()).toBe(codecID_zero) - expect(secPTransferOutput.getOutputID()).toBe( - AVMConstants.SECPXFEROUTPUTID - ) - secPTransferOutput.setCodecID(codecID_one) - expect(secPTransferOutput.getCodecID()).toBe(codecID_one) - expect(secPTransferOutput.getOutputID()).toBe( - AVMConstants.SECPXFEROUTPUTID_CODECONE - ) - secPTransferOutput.setCodecID(codecID_zero) - expect(secPTransferOutput.getCodecID()).toBe(codecID_zero) - expect(secPTransferOutput.getOutputID()).toBe( - AVMConstants.SECPXFEROUTPUTID - ) - }) - - test("Invalid SECPTransferOutput codecID", (): void => { - const secPTransferOutput: SECPTransferOutput = new SECPTransferOutput( - new BN(10000), - addrs, - locktime, - 3 - ) - expect((): void => { - secPTransferOutput.setCodecID(2) - }).toThrow( - "Error - SECPTransferOutput.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - }) - - test("SECPMintOutput", (): void => { - const out: SECPMintOutput = new SECPMintOutput(addrs, locktime, 3) - expect(out.getOutputID()).toBe(6) - expect(JSON.stringify(out.getAddresses().sort())).toStrictEqual( - JSON.stringify(addrs.sort()) - ) - expect(out.getThreshold()).toBe(3) - expect(out.getLocktime().toNumber()).toBe(locktime.toNumber()) - const r: number = out.getAddressIdx(addrs[2]) - expect(out.getAddress(r)).toStrictEqual(addrs[2]) - expect(() => { - out.getAddress(400) - }).toThrow() - const b: Buffer = out.toBuffer() - expect(out.toString()).toBe(bintools.bufferToB58(b)) - const s: Buffer[] = out.getSpenders(addrs) - expect(JSON.stringify(s.sort())).toBe(JSON.stringify(addrs.sort())) - const m1: boolean = out.meetsThreshold([addrs[0]]) - expect(m1).toBe(false) - const m2: boolean = out.meetsThreshold(addrs, new BN(100)) - expect(m2).toBe(false) - const m3: boolean = out.meetsThreshold(addrs) - expect(m3).toBe(true) - const m4: boolean = out.meetsThreshold(addrs, locktime.add(new BN(100))) - expect(m4).toBe(true) - }) - - test("SECPMintOutput bad address", (): void => { - const badAddress = Buffer.from("adfasdfsas", "hex") - - expect((): void => { - new SECPMintOutput([badAddress], locktime, 3) - }).toThrow( - "Error - NBytes.fromBuffer: Error: Error - NBytes.fromBuffer: not enough space available in buffer." - ) - }) - - test("SECPMintOutput codecIDs", (): void => { - const secpMintOutput: SECPMintOutput = new SECPMintOutput( - addrs, - locktime, - 3 - ) - expect(secpMintOutput.getCodecID()).toBe(codecID_zero) - expect(secpMintOutput.getOutputID()).toBe(AVMConstants.SECPMINTOUTPUTID) - secpMintOutput.setCodecID(codecID_one) - expect(secpMintOutput.getCodecID()).toBe(codecID_one) - expect(secpMintOutput.getOutputID()).toBe( - AVMConstants.SECPMINTOUTPUTID_CODECONE - ) - secpMintOutput.setCodecID(codecID_zero) - expect(secpMintOutput.getCodecID()).toBe(codecID_zero) - expect(secpMintOutput.getOutputID()).toBe(AVMConstants.SECPMINTOUTPUTID) - }) - - test("Invalid SECPMintOutput codecID", (): void => { - const secpMintOutput: SECPMintOutput = new SECPMintOutput( - addrs, - locktime, - 3 - ) - expect(() => { - secpMintOutput.setCodecID(2) - }).toThrow( - "Error - SECPMintOutput.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - }) - }) -}) diff --git a/tests/apis/avm/tx.test.ts b/tests/apis/avm/tx.test.ts deleted file mode 100644 index 1d6668ed2..000000000 --- a/tests/apis/avm/tx.test.ts +++ /dev/null @@ -1,896 +0,0 @@ -import mockAxios from "jest-mock-axios" -import { UTXOSet, UTXO } from "../../../src/apis/avm/utxos" -import { AVMAPI } from "../../../src/apis/avm/api" -import { UnsignedTx, Tx } from "../../../src/apis/avm/tx" -import { KeyChain } from "../../../src/apis/avm/keychain" -import { - SECPTransferInput, - TransferableInput -} from "../../../src/apis/avm/inputs" -import createHash from "create-hash" -import BinTools from "../../../src/utils/bintools" -import BN from "bn.js" -import { Buffer } from "buffer/" -import { - SECPTransferOutput, - NFTTransferOutput, - TransferableOutput -} from "../../../src/apis/avm/outputs" -import { AVMConstants } from "../../../src/apis/avm/constants" -import { - TransferableOperation, - NFTTransferOperation -} from "../../../src/apis/avm/ops" -import { Avalanche } from "../../../src/index" -import { UTF8Payload } from "../../../src/utils/payload" -import { InitialStates } from "../../../src/apis/avm/initialstates" -import { UnixNow } from "../../../src/utils/helperfunctions" -import { BaseTx } from "../../../src/apis/avm/basetx" -import { CreateAssetTx } from "../../../src/apis/avm/createassettx" -import { OperationTx } from "../../../src/apis/avm/operationtx" -import { ImportTx } from "../../../src/apis/avm/importtx" -import { ExportTx } from "../../../src/apis/avm/exporttx" -import { PlatformChainID } from "../../../src/utils/constants" -import { Defaults } from "../../../src/utils/constants" -import { ONEAVAX } from "../../../src/utils/constants" -import { HttpResponse } from "jest-mock-axios/dist/lib/mock-axios-types" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -describe("Transactions", (): void => { - let set: UTXOSet - let keymgr1: KeyChain - let keymgr2: KeyChain - let keymgr3: KeyChain - let addrs1: Buffer[] - let addrs2: Buffer[] - let addrs3: Buffer[] - let utxos: UTXO[] - let inputs: TransferableInput[] - let outputs: TransferableOutput[] - let ops: TransferableOperation[] - let importIns: TransferableInput[] - let importUTXOs: UTXO[] - let exportOuts: TransferableOutput[] - let fungutxos: UTXO[] - let exportUTXOIDS: string[] - let api: AVMAPI - const amnt: number = 10000 - const netid: number = 12345 - const bID: string = Defaults.network[netid].X.blockchainID - const alias: string = "X" - const assetID: Buffer = Buffer.from( - createHash("sha256") - .update( - "Well, now, don't you tell me to smile, you stick around I'll make it worth your while." - ) - .digest() - ) - const NFTassetID: Buffer = Buffer.from( - createHash("sha256") - .update( - "I can't stand it, I know you planned it, I'mma set straight this Watergate.'" - ) - .digest() - ) - const codecID_zero: number = 0 - const codecID_one: number = 1 - let amount: BN - let addresses: Buffer[] - let fallAddresses: Buffer[] - let locktime: BN - let fallLocktime: BN - let threshold: number - let fallThreshold: number - const nftutxoids: string[] = [] - const ip: string = "127.0.0.1" - const port: number = 8080 - const protocol: string = "http" - let avalanche: Avalanche - const blockchainID: Buffer = bintools.cb58Decode(bID) - const name: string = "Mortycoin is the dumb as a sack of hammers." - const symbol: string = "morT" - const denomination: number = 8 - let avaxAssetID: Buffer - - beforeAll(async (): Promise => { - avalanche = new Avalanche( - ip, - port, - protocol, - netid, - undefined, - undefined, - undefined, - true - ) - api = new AVMAPI(avalanche, "/ext/bc/avm", bID) - - const result: Promise = api.getAVAXAssetID() - const payload: object = { - result: { - name, - symbol, - assetID: bintools.cb58Encode(assetID), - denomination: `${denomination}` - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - avaxAssetID = await result - }) - - beforeEach((): void => { - set = new UTXOSet() - keymgr1 = new KeyChain(avalanche.getHRP(), alias) - keymgr2 = new KeyChain(avalanche.getHRP(), alias) - keymgr3 = new KeyChain(avalanche.getHRP(), alias) - addrs1 = [] - addrs2 = [] - addrs3 = [] - utxos = [] - inputs = [] - outputs = [] - importIns = [] - importUTXOs = [] - exportOuts = [] - fungutxos = [] - exportUTXOIDS = [] - ops = [] - for (let i: number = 0; i < 3; i++) { - addrs1.push(keymgr1.makeKey().getAddress()) - addrs2.push(keymgr2.makeKey().getAddress()) - addrs3.push(keymgr3.makeKey().getAddress()) - } - amount = ONEAVAX.mul(new BN(amnt)) - addresses = keymgr1.getAddresses() - fallAddresses = keymgr2.getAddresses() - locktime = new BN(54321) - fallLocktime = locktime.add(new BN(50)) - threshold = 3 - fallThreshold = 1 - - const payload: Buffer = Buffer.alloc(1024) - payload.write( - "All you Trekkies and TV addicts, Don't mean to diss don't mean to bring static.", - 0, - 1024, - "utf8" - ) - - for (let i: number = 0; i < 5; i++) { - let txid: Buffer = Buffer.from( - createHash("sha256") - .update(bintools.fromBNToBuffer(new BN(i), 32)) - .digest() - ) - let txidx: Buffer = Buffer.from(bintools.fromBNToBuffer(new BN(i), 4)) - const out: SECPTransferOutput = new SECPTransferOutput( - amount, - addresses, - locktime, - threshold - ) - const xferout: TransferableOutput = new TransferableOutput(assetID, out) - outputs.push(xferout) - - const u: UTXO = new UTXO( - AVMConstants.LATESTCODEC, - txid, - txidx, - assetID, - out - ) - utxos.push(u) - fungutxos.push(u) - importUTXOs.push(u) - - txid = u.getTxID() - txidx = u.getOutputIdx() - - const input: SECPTransferInput = new SECPTransferInput(amount) - const xferin: TransferableInput = new TransferableInput( - txid, - txidx, - assetID, - input - ) - inputs.push(xferin) - - const nout: NFTTransferOutput = new NFTTransferOutput( - 1000 + i, - payload, - addresses, - locktime, - threshold - ) - const op: NFTTransferOperation = new NFTTransferOperation(nout) - const nfttxid: Buffer = Buffer.from( - createHash("sha256") - .update(bintools.fromBNToBuffer(new BN(1000 + i), 32)) - .digest() - ) - const nftutxo: UTXO = new UTXO( - AVMConstants.LATESTCODEC, - nfttxid, - 1000 + i, - NFTassetID, - nout - ) - nftutxoids.push(nftutxo.getUTXOID()) - const xferop: TransferableOperation = new TransferableOperation( - NFTassetID, - [nftutxo.getUTXOID()], - op - ) - ops.push(xferop) - utxos.push(nftutxo) - } - for (let i: number = 1; i < 4; i++) { - importIns.push(inputs[i]) - exportOuts.push(outputs[i]) - exportUTXOIDS.push(fungutxos[i].getUTXOID()) - } - set.addArray(utxos) - }) - - test("BaseTx codecIDs", (): void => { - const baseTx: BaseTx = new BaseTx() - expect(baseTx.getCodecID()).toBe(codecID_zero) - expect(baseTx.getTypeID()).toBe(AVMConstants.BASETX) - baseTx.setCodecID(codecID_one) - expect(baseTx.getCodecID()).toBe(codecID_one) - expect(baseTx.getTypeID()).toBe(AVMConstants.BASETX_CODECONE) - baseTx.setCodecID(codecID_zero) - expect(baseTx.getCodecID()).toBe(codecID_zero) - expect(baseTx.getTypeID()).toBe(AVMConstants.BASETX) - }) - - test("Invalid BaseTx codecID", (): void => { - const baseTx: BaseTx = new BaseTx() - expect((): void => { - baseTx.setCodecID(2) - }).toThrow( - "Error - BaseTx.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - }) - - test("CreateAssetTx codecIDs", (): void => { - const createAssetTx: CreateAssetTx = new CreateAssetTx() - expect(createAssetTx.getCodecID()).toBe(codecID_zero) - expect(createAssetTx.getTypeID()).toBe(AVMConstants.CREATEASSETTX) - createAssetTx.setCodecID(codecID_one) - expect(createAssetTx.getCodecID()).toBe(codecID_one) - expect(createAssetTx.getTypeID()).toBe(AVMConstants.CREATEASSETTX_CODECONE) - createAssetTx.setCodecID(codecID_zero) - expect(createAssetTx.getCodecID()).toBe(codecID_zero) - expect(createAssetTx.getTypeID()).toBe(AVMConstants.CREATEASSETTX) - }) - - test("Invalid CreateAssetTx codecID", (): void => { - const createAssetTx: CreateAssetTx = new CreateAssetTx() - expect((): void => { - createAssetTx.setCodecID(2) - }).toThrow( - "Error - CreateAssetTx.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - }) - - test("OperationTx codecIDs", (): void => { - const operationTx: OperationTx = new OperationTx() - expect(operationTx.getCodecID()).toBe(codecID_zero) - expect(operationTx.getTypeID()).toBe(AVMConstants.OPERATIONTX) - operationTx.setCodecID(codecID_one) - expect(operationTx.getCodecID()).toBe(codecID_one) - expect(operationTx.getTypeID()).toBe(AVMConstants.OPERATIONTX_CODECONE) - operationTx.setCodecID(codecID_zero) - expect(operationTx.getCodecID()).toBe(codecID_zero) - expect(operationTx.getTypeID()).toBe(AVMConstants.OPERATIONTX) - }) - - test("Invalid OperationTx codecID", (): void => { - const operationTx: OperationTx = new OperationTx() - expect((): void => { - operationTx.setCodecID(2) - }).toThrow( - "Error - OperationTx.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - }) - - test("ImportTx codecIDs", (): void => { - const importTx: ImportTx = new ImportTx() - expect(importTx.getCodecID()).toBe(codecID_zero) - expect(importTx.getTypeID()).toBe(AVMConstants.IMPORTTX) - importTx.setCodecID(codecID_one) - expect(importTx.getCodecID()).toBe(codecID_one) - expect(importTx.getTypeID()).toBe(AVMConstants.IMPORTTX_CODECONE) - importTx.setCodecID(codecID_zero) - expect(importTx.getCodecID()).toBe(codecID_zero) - expect(importTx.getTypeID()).toBe(AVMConstants.IMPORTTX) - }) - - test("Invalid ImportTx codecID", (): void => { - const importTx: ImportTx = new ImportTx() - expect((): void => { - importTx.setCodecID(2) - }).toThrow( - "Error - ImportTx.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - }) - - test("ExportTx codecIDs", (): void => { - const exportTx: ExportTx = new ExportTx() - expect(exportTx.getCodecID()).toBe(codecID_zero) - expect(exportTx.getTypeID()).toBe(AVMConstants.EXPORTTX) - exportTx.setCodecID(codecID_one) - expect(exportTx.getCodecID()).toBe(codecID_one) - expect(exportTx.getTypeID()).toBe(AVMConstants.EXPORTTX_CODECONE) - exportTx.setCodecID(codecID_zero) - expect(exportTx.getCodecID()).toBe(codecID_zero) - expect(exportTx.getTypeID()).toBe(AVMConstants.EXPORTTX) - }) - - test("Invalid ExportTx codecID", (): void => { - const exportTx: ExportTx = new ExportTx() - expect((): void => { - exportTx.setCodecID(2) - }).toThrow( - "Error - ExportTx.setCodecID: invalid codecID. Valid codecIDs are 0 and 1." - ) - }) - - test("Create small BaseTx that is Goose Egg Tx", async (): Promise => { - const outs: TransferableOutput[] = [] - const ins: TransferableInput[] = [] - const outputAmt: BN = new BN("266") - const output: SECPTransferOutput = new SECPTransferOutput( - outputAmt, - addrs1, - new BN(0), - 1 - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - output - ) - outs.push(transferableOutput) - const inputAmt: BN = new BN("400") - const input: SECPTransferInput = new SECPTransferInput(inputAmt) - input.addSignatureIdx(0, addrs1[0]) - const txid: Buffer = bintools.cb58Decode( - "n8XH5JY1EX5VYqDeAhB4Zd4GKxi9UNQy6oPpMsCAj1Q6xkiiL" - ) - const outputIndex: Buffer = Buffer.from( - bintools.fromBNToBuffer(new BN(0), 4) - ) - const transferableInput: TransferableInput = new TransferableInput( - txid, - outputIndex, - avaxAssetID, - input - ) - ins.push(transferableInput) - const baseTx: BaseTx = new BaseTx(netid, blockchainID, outs, ins) - const unsignedTx: UnsignedTx = new UnsignedTx(baseTx) - expect(await api.checkGooseEgg(unsignedTx)).toBe(true) - }) - - test("Create small BaseTx with bad txid", async (): Promise => { - const outs: TransferableOutput[] = [] - const outputAmt: BN = new BN("266") - const output: SECPTransferOutput = new SECPTransferOutput( - outputAmt, - addrs1, - new BN(0), - 1 - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - output - ) - outs.push(transferableOutput) - const inputAmt: BN = new BN("400") - const input: SECPTransferInput = new SECPTransferInput(inputAmt) - input.addSignatureIdx(0, addrs1[0]) - - expect((): void => { - const txid: Buffer = bintools.cb58Decode( - "n8XHaaaa5JY1EX5VYqDeAhB4Zd4GKxi9UNQy6oPpMsCAj1Q6xkiiL" - ) - }).toThrow("Error - BinTools.cb58Decode: invalid checksum") - }) - - test("confirm inputTotal, outputTotal and fee are correct", async (): Promise => { - // AVAX assetID - const assetID: Buffer = bintools.cb58Decode( - "n8XH5JY1EX5VYqDeAhB4Zd4GKxi9UNQy6oPpMsCAj1Q6xkiiL" - ) - const outs: TransferableOutput[] = [] - const ins: TransferableInput[] = [] - const outputAmt: BN = new BN("266") - const output: SECPTransferOutput = new SECPTransferOutput( - outputAmt, - addrs1, - new BN(0), - 1 - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - assetID, - output - ) - outs.push(transferableOutput) - const inputAmt: BN = new BN("400") - const input: SECPTransferInput = new SECPTransferInput(inputAmt) - input.addSignatureIdx(0, addrs1[0]) - const txid: Buffer = bintools.cb58Decode( - "n8XH5JY1EX5VYqDeAhB4Zd4GKxi9UNQy6oPpMsCAj1Q6xkiiL" - ) - const outputIndex: Buffer = Buffer.from( - bintools.fromBNToBuffer(new BN(0), 4) - ) - const transferableInput: TransferableInput = new TransferableInput( - txid, - outputIndex, - assetID, - input - ) - ins.push(transferableInput) - const baseTx: BaseTx = new BaseTx(netid, blockchainID, outs, ins) - const unsignedTx: UnsignedTx = new UnsignedTx(baseTx) - const inputTotal: BN = unsignedTx.getInputTotal(assetID) - const outputTotal: BN = unsignedTx.getOutputTotal(assetID) - const burn: BN = unsignedTx.getBurn(assetID) - expect(inputTotal.toNumber()).toEqual(new BN(400).toNumber()) - expect(outputTotal.toNumber()).toEqual(new BN(266).toNumber()) - expect(burn.toNumber()).toEqual(new BN(134).toNumber()) - }) - - test("Create small BaseTx that isn't Goose Egg Tx", async (): Promise => { - const outs: TransferableOutput[] = [] - const ins: TransferableInput[] = [] - const outputAmt: BN = new BN("267") - const output: SECPTransferOutput = new SECPTransferOutput( - outputAmt, - addrs1, - new BN(0), - 1 - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - output - ) - outs.push(transferableOutput) - const inputAmt: BN = new BN("400") - const input: SECPTransferInput = new SECPTransferInput(inputAmt) - input.addSignatureIdx(0, addrs1[0]) - const txid: Buffer = bintools.cb58Decode( - "n8XH5JY1EX5VYqDeAhB4Zd4GKxi9UNQy6oPpMsCAj1Q6xkiiL" - ) - const outputIndex: Buffer = Buffer.from( - bintools.fromBNToBuffer(new BN(0), 4) - ) - const transferableInput: TransferableInput = new TransferableInput( - txid, - outputIndex, - avaxAssetID, - input - ) - ins.push(transferableInput) - const baseTx: BaseTx = new BaseTx(netid, blockchainID, outs, ins) - const unsignedTx: UnsignedTx = new UnsignedTx(baseTx) - expect(await api.checkGooseEgg(unsignedTx)).toBe(true) - }) - - test("Create large BaseTx that is Goose Egg Tx", async (): Promise => { - const outs: TransferableOutput[] = [] - const ins: TransferableInput[] = [] - const outputAmt: BN = new BN("609555500000") - const output: SECPTransferOutput = new SECPTransferOutput( - outputAmt, - addrs1, - new BN(0), - 1 - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - output - ) - outs.push(transferableOutput) - const inputAmt: BN = new BN("45000000000000000") - const input: SECPTransferInput = new SECPTransferInput(inputAmt) - input.addSignatureIdx(0, addrs1[0]) - const txid: Buffer = bintools.cb58Decode( - "n8XH5JY1EX5VYqDeAhB4Zd4GKxi9UNQy6oPpMsCAj1Q6xkiiL" - ) - const outputIndex: Buffer = Buffer.from( - bintools.fromBNToBuffer(new BN(0), 4) - ) - const transferableInput: TransferableInput = new TransferableInput( - txid, - outputIndex, - avaxAssetID, - input - ) - ins.push(transferableInput) - const baseTx: BaseTx = new BaseTx(netid, blockchainID, outs, ins) - const unsignedTx: UnsignedTx = new UnsignedTx(baseTx) - expect(await api.checkGooseEgg(unsignedTx)).toBe(false) - }) - - test("Create large BaseTx that isn't Goose Egg Tx", async (): Promise => { - const outs: TransferableOutput[] = [] - const ins: TransferableInput[] = [] - const outputAmt: BN = new BN("44995609555500000") - const output: SECPTransferOutput = new SECPTransferOutput( - outputAmt, - addrs1, - new BN(0), - 1 - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - output - ) - outs.push(transferableOutput) - const inputAmt: BN = new BN("45000000000000000") - const input: SECPTransferInput = new SECPTransferInput(inputAmt) - input.addSignatureIdx(0, addrs1[0]) - const txid: Buffer = bintools.cb58Decode( - "n8XH5JY1EX5VYqDeAhB4Zd4GKxi9UNQy6oPpMsCAj1Q6xkiiL" - ) - const outputIndex: Buffer = Buffer.from( - bintools.fromBNToBuffer(new BN(0), 4) - ) - const transferableInput: TransferableInput = new TransferableInput( - txid, - outputIndex, - avaxAssetID, - input - ) - ins.push(transferableInput) - const baseTx: BaseTx = new BaseTx(netid, blockchainID, outs, ins) - const unsignedTx: UnsignedTx = new UnsignedTx(baseTx) - expect(await api.checkGooseEgg(unsignedTx)).toBe(true) - }) - - test("bad asset ID", async (): Promise => { - expect((): void => { - const assetID: Buffer = bintools.cb58Decode( - "badaaaan8XH5JY1EX5VYqDeAhB4Zd4GKxi9UNQy6oPpMsCAj1Q6xkiiL" - ) - }).toThrow() - }) - - test("Creation UnsignedTx", (): void => { - const baseTx: BaseTx = new BaseTx(netid, blockchainID, outputs, inputs) - const txu: UnsignedTx = new UnsignedTx(baseTx) - const txins: TransferableInput[] = txu.getTransaction().getIns() - const txouts: TransferableOutput[] = txu.getTransaction().getOuts() - expect(txins.length).toBe(inputs.length) - expect(txouts.length).toBe(outputs.length) - - expect(txu.getTransaction().getTxType()).toBe(0) - expect(txu.getTransaction().getNetworkID()).toBe(12345) - expect(txu.getTransaction().getBlockchainID().toString("hex")).toBe( - blockchainID.toString("hex") - ) - - let a: string[] = [] - let b: string[] = [] - for (let i: number = 0; i < txins.length; i++) { - a.push(txins[i].toString()) - b.push(inputs[i].toString()) - } - expect(JSON.stringify(a.sort())).toBe(JSON.stringify(b.sort())) - - a = [] - b = [] - - for (let i: number = 0; i < txouts.length; i++) { - a.push(txouts[i].toString()) - b.push(outputs[i].toString()) - } - expect(JSON.stringify(a.sort())).toBe(JSON.stringify(b.sort())) - - const txunew: UnsignedTx = new UnsignedTx() - txunew.fromBuffer(txu.toBuffer()) - expect(txunew.toBuffer().toString("hex")).toBe( - txu.toBuffer().toString("hex") - ) - expect(txunew.toString()).toBe(txu.toString()) - }) - - test("Creation UnsignedTx Check Amount", (): void => { - expect((): void => { - set.buildBaseTx( - netid, - blockchainID, - ONEAVAX.mul(new BN(amnt * 10000)), - assetID, - addrs3, - addrs1, - addrs1 - ) - }).toThrow() - }) - - test("CreateAssetTX", (): void => { - const secpbase1: SECPTransferOutput = new SECPTransferOutput( - new BN(777), - addrs3, - locktime, - 1 - ) - const secpbase2: SECPTransferOutput = new SECPTransferOutput( - new BN(888), - addrs2, - locktime, - 1 - ) - const secpbase3: SECPTransferOutput = new SECPTransferOutput( - new BN(999), - addrs2, - locktime, - 1 - ) - const initialState: InitialStates = new InitialStates() - initialState.addOutput(secpbase1, AVMConstants.SECPFXID) - initialState.addOutput(secpbase2, AVMConstants.SECPFXID) - initialState.addOutput(secpbase3, AVMConstants.SECPFXID) - const name: string = "Rickcoin is the most intelligent coin" - const symbol: string = "RICK" - const denomination: number = 9 - const txu: CreateAssetTx = new CreateAssetTx( - netid, - blockchainID, - outputs, - inputs, - new UTF8Payload("hello world").getPayload(), - name, - symbol, - denomination, - initialState - ) - const txins: TransferableInput[] = txu.getIns() - const txouts: TransferableOutput[] = txu.getOuts() - const initState: InitialStates = txu.getInitialStates() - expect(txins.length).toBe(inputs.length) - expect(txouts.length).toBe(outputs.length) - expect(initState.toBuffer().toString("hex")).toBe( - initialState.toBuffer().toString("hex") - ) - - expect(txu.getTxType()).toBe(AVMConstants.CREATEASSETTX) - expect(txu.getNetworkID()).toBe(12345) - expect(txu.getBlockchainID().toString("hex")).toBe( - blockchainID.toString("hex") - ) - - expect(txu.getName()).toBe(name) - expect(txu.getSymbol()).toBe(symbol) - expect(txu.getDenomination()).toBe(denomination) - expect(txu.getDenominationBuffer().readUInt8(0)).toBe(denomination) - - let a: string[] = [] - let b: string[] = [] - for (let i: number = 0; i < txins.length; i++) { - a.push(txins[i].toString()) - b.push(inputs[i].toString()) - } - expect(JSON.stringify(a.sort())).toBe(JSON.stringify(b.sort())) - - a = [] - b = [] - - for (let i: number = 0; i < txouts.length; i++) { - a.push(txouts[i].toString()) - b.push(outputs[i].toString()) - } - expect(JSON.stringify(a.sort())).toBe(JSON.stringify(b.sort())) - - const txunew: CreateAssetTx = new CreateAssetTx() - txunew.fromBuffer(txu.toBuffer()) - expect(txunew.toBuffer().toString("hex")).toBe( - txu.toBuffer().toString("hex") - ) - expect(txunew.toString()).toBe(txu.toString()) - }) - - test("Creation OperationTx", (): void => { - const optx: OperationTx = new OperationTx( - netid, - blockchainID, - outputs, - inputs, - new UTF8Payload("hello world").getPayload(), - ops - ) - const txunew: OperationTx = new OperationTx() - const opbuff: Buffer = optx.toBuffer() - txunew.fromBuffer(opbuff) - expect(txunew.toBuffer().toString("hex")).toBe(opbuff.toString("hex")) - expect(txunew.toString()).toBe(optx.toString()) - expect(optx.getOperations().length).toBe(ops.length) - }) - - test("Creation ImportTx", (): void => { - const bombtx: ImportTx = new ImportTx( - netid, - blockchainID, - outputs, - inputs, - new UTF8Payload("hello world").getPayload(), - undefined, - importIns - ) - - expect((): void => { - bombtx.toBuffer() - }).toThrow() - - const importTx: ImportTx = new ImportTx( - netid, - blockchainID, - outputs, - inputs, - new UTF8Payload("hello world").getPayload(), - bintools.cb58Decode(PlatformChainID), - importIns - ) - const txunew: ImportTx = new ImportTx() - const importbuff: Buffer = importTx.toBuffer() - txunew.fromBuffer(importbuff) - - expect(importTx).toBeInstanceOf(ImportTx) - expect(importTx.getSourceChain().toString("hex")).toBe( - bintools.cb58Decode(PlatformChainID).toString("hex") - ) - expect(txunew.toBuffer().toString("hex")).toBe(importbuff.toString("hex")) - expect(txunew.toString()).toBe(importTx.toString()) - expect(importTx.getImportInputs().length).toBe(importIns.length) - }) - - test("Creation ExportTx", (): void => { - const bombtx: ExportTx = new ExportTx( - netid, - blockchainID, - outputs, - inputs, - undefined, - undefined, - exportOuts - ) - - expect((): void => { - bombtx.toBuffer() - }).toThrow() - - const exportTx: ExportTx = new ExportTx( - netid, - blockchainID, - outputs, - inputs, - undefined, - bintools.cb58Decode(PlatformChainID), - exportOuts - ) - const txunew: ExportTx = new ExportTx() - const exportbuff: Buffer = exportTx.toBuffer() - txunew.fromBuffer(exportbuff) - - expect(exportTx).toBeInstanceOf(ExportTx) - expect(exportTx.getDestinationChain().toString("hex")).toBe( - bintools.cb58Decode(PlatformChainID).toString("hex") - ) - expect(txunew.toBuffer().toString("hex")).toBe(exportbuff.toString("hex")) - expect(txunew.toString()).toBe(exportTx.toString()) - expect(exportTx.getExportOutputs().length).toBe(exportOuts.length) - }) - - test("Creation Tx1 with asof, locktime, threshold", (): void => { - const txu: UnsignedTx = set.buildBaseTx( - netid, - blockchainID, - new BN(9000), - assetID, - addrs3, - addrs1, - addrs1, - undefined, - undefined, - undefined, - UnixNow(), - UnixNow().add(new BN(50)), - 1 - ) - const tx: Tx = txu.sign(keymgr1) - - const tx2: Tx = new Tx() - tx2.fromString(tx.toString()) - expect(tx2.toBuffer().toString("hex")).toBe(tx.toBuffer().toString("hex")) - expect(tx2.toString()).toBe(tx.toString()) - }) - test("Creation Tx2 without asof, locktime, threshold", (): void => { - const txu: UnsignedTx = set.buildBaseTx( - netid, - blockchainID, - new BN(9000), - assetID, - addrs3, - addrs1, - addrs1 - ) - const tx: Tx = txu.sign(keymgr1) - const tx2: Tx = new Tx() - tx2.fromBuffer(tx.toBuffer()) - expect(tx2.toBuffer().toString("hex")).toBe(tx.toBuffer().toString("hex")) - expect(tx2.toString()).toBe(tx.toString()) - }) - - test("Creation Tx3 using OperationTx", (): void => { - const txu: UnsignedTx = set.buildNFTTransferTx( - netid, - blockchainID, - addrs3, - addrs1, - addrs2, - nftutxoids, - new BN(90), - avaxAssetID, - undefined, - UnixNow(), - UnixNow().add(new BN(50)), - 1 - ) - const tx: Tx = txu.sign(keymgr1) - const tx2: Tx = new Tx() - tx2.fromBuffer(tx.toBuffer()) - expect(tx2.toBuffer().toString("hex")).toBe(tx.toBuffer().toString("hex")) - }) - - test("Creation Tx4 using ImportTx", (): void => { - const txu: UnsignedTx = set.buildImportTx( - netid, - blockchainID, - addrs3, - addrs1, - addrs2, - importUTXOs, - bintools.cb58Decode(PlatformChainID), - new BN(90), - assetID, - new UTF8Payload("hello world").getPayload(), - UnixNow() - ) - const tx: Tx = txu.sign(keymgr1) - const tx2: Tx = new Tx() - tx2.fromBuffer(tx.toBuffer()) - expect(tx2.toBuffer().toString("hex")).toBe(tx.toBuffer().toString("hex")) - }) - - test("Creation Tx5 using ExportTx", (): void => { - const txu: UnsignedTx = set.buildExportTx( - netid, - blockchainID, - new BN(90), - avaxAssetID, - addrs3, - addrs1, - addrs2, - bintools.cb58Decode(PlatformChainID), - undefined, - undefined, - new UTF8Payload("hello world").getPayload(), - UnixNow() - ) - const tx: Tx = txu.sign(keymgr1) - const tx2: Tx = new Tx() - tx2.fromBuffer(tx.toBuffer()) - expect(tx.toBuffer().toString("hex")).toBe(tx2.toBuffer().toString("hex")) - }) -}) diff --git a/tests/apis/avm/types.test.ts b/tests/apis/avm/types.test.ts deleted file mode 100644 index d1ed01161..000000000 --- a/tests/apis/avm/types.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { Buffer } from "buffer/" -import BinTools from "../../../src/utils/bintools" -import { SigIdx, Signature } from "../../../src/common/credentials" -import { Address } from "../../../src/common/output" -import { UnixNow } from "../../../src/utils/helperfunctions" -import BN from "bn.js" - -const bintools: BinTools = BinTools.getInstance() - -describe("UnixNow", (): void => { - test("Does it return the right time?", (): void => { - const now: number = Math.round(new Date().getTime() / 1000) - const unow: BN = UnixNow() - expect(now / 10).toBeCloseTo(unow.divn(10).toNumber(), -1) - }) -}) - -describe("Signature & NBytes", (): void => { - const sig: Signature = new Signature() - const sigpop: number[] = [] - for (let i: number = 0; i < sig.getSize(); i++) { - sigpop[i] = i - } - const sigbuff: Buffer = Buffer.from(sigpop) - const size: number = sig.fromBuffer(sigbuff) - expect(sig.getSize()).toBe(size) - expect(size).toBe(sig.getSize()) - const sigbuff2: Buffer = sig.toBuffer() - for (let i: number = 0; i < sigbuff.length; i++) { - expect(sigbuff2[i]).toBe(sigbuff[i]) - } - const sigbuffstr: string = bintools.bufferToB58(sigbuff) - expect(sig.toString()).toBe(sigbuffstr) - sig.fromString(sigbuffstr) - expect(sig.toString()).toBe(sigbuffstr) -}) - -describe("SigIdx", (): void => { - const sigidx: SigIdx = new SigIdx() - expect(sigidx.getSize()).toBe(sigidx.toBuffer().length) - sigidx.setSource(Buffer.from("abcd", "hex")) - expect(sigidx.getSource().toString("hex")).toBe("abcd") -}) - -describe("Address", (): void => { - const addr1: Address = new Address() - const addr2: Address = new Address() - const smaller: number[] = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 - ] - const bigger: number[] = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1 - ] - const addr1bytes: Buffer = Buffer.from(smaller) - const addr2bytes: Buffer = Buffer.from(bigger) - addr1.fromBuffer(addr1bytes) - addr2.fromBuffer(addr2bytes) - expect(Address.comparator()(addr1, addr2)).toBe(-1) - expect(Address.comparator()(addr2, addr1)).toBe(1) - - const addr2str: string = addr2.toString() - - addr2.fromBuffer(addr1bytes) - expect(Address.comparator()(addr1, addr2)).toBe(0) - - addr2.fromString(addr2str) - expect(Address.comparator()(addr1, addr2)).toBe(-1) - const a1b: Buffer = addr1.toBuffer() - const a1s: string = bintools.bufferToB58(a1b) - addr2.fromString(a1s) - expect(Address.comparator()(addr1, addr2)).toBe(0) - - const badbuff: Buffer = bintools.copyFrom(addr1bytes) - let badbuffout: Buffer = Buffer.concat([badbuff, Buffer.from([1, 2])]) - let badstr: string = bintools.bufferToB58(badbuffout) - const badaddr: Address = new Address() - - expect((): void => { - badaddr.fromString(badstr) - }).toThrow("Error - Address.fromString: invalid address") - - badbuffout = Buffer.concat([badbuff, Buffer.from([1, 2, 3, 4])]) - badstr = bintools.bufferToB58(badbuffout) - expect((): void => { - badaddr.fromString(badstr) - }).toThrow("Error - Address.fromString: invalid checksum on address") -}) diff --git a/tests/apis/avm/utxos.test.ts b/tests/apis/avm/utxos.test.ts deleted file mode 100644 index 9c03c2c82..000000000 --- a/tests/apis/avm/utxos.test.ts +++ /dev/null @@ -1,621 +0,0 @@ -import BN from "bn.js" -import { Buffer } from "buffer/" -import BinTools from "../../../src/utils/bintools" -import { UTXO, UTXOSet } from "../../../src/apis/avm/utxos" -import { AmountOutput } from "../../../src/apis/avm/outputs" -import { UnixNow } from "../../../src/utils/helperfunctions" -import { SerializedEncoding } from "../../../src/utils" - -const bintools: BinTools = BinTools.getInstance() -const display: SerializedEncoding = "display" - -describe("UTXO", (): void => { - const utxohex: string = - "000038d1b9f1138672da6fb6c35125539276a9acc2a668d63bea6ba3c795e2edb0f5000000013e07e38e2f23121be8756412c18db7246a16d26ee9936f3cba28be149cfd3558000000070000000000004dd500000000000000000000000100000001a36fd0c2dbcab311731dde7ef1514bd26fcdc74d" - const outputidx: string = "00000001" - const outtxid: string = - "38d1b9f1138672da6fb6c35125539276a9acc2a668d63bea6ba3c795e2edb0f5" - const outaid: string = - "3e07e38e2f23121be8756412c18db7246a16d26ee9936f3cba28be149cfd3558" - const utxobuff: Buffer = Buffer.from(utxohex, "hex") - - // Payment - const OPUTXOstr: string = bintools.cb58Encode(utxobuff) - // "U9rFgK5jjdXmV8k5tpqeXkimzrN3o9eCCcXesyhMBBZu9MQJCDTDo5Wn5psKvzJVMJpiMbdkfDXkp7sKZddfCZdxpuDmyNy7VFka19zMW4jcz6DRQvNfA2kvJYKk96zc7uizgp3i2FYWrB8mr1sPJ8oP9Th64GQ5yHd8" - - // implies fromString and fromBuffer - test("Creation", (): void => { - const u1: UTXO = new UTXO() - u1.fromBuffer(utxobuff) - const u1hex: string = u1.toBuffer().toString("hex") - expect(u1hex).toBe(utxohex) - }) - - test("Empty Creation", (): void => { - const u1: UTXO = new UTXO() - expect((): void => { - u1.toBuffer() - }).toThrow() - }) - - test("Creation of Type", (): void => { - const op: UTXO = new UTXO() - op.fromString(OPUTXOstr) - expect(op.getOutput().getOutputID()).toBe(7) - }) - - describe("Funtionality", (): void => { - const u1: UTXO = new UTXO() - u1.fromBuffer(utxobuff) - test("getAssetID NonCA", (): void => { - const assetID: Buffer = u1.getAssetID() - expect(assetID.toString("hex", 0, assetID.length)).toBe(outaid) - }) - test("getTxID", (): void => { - const txid: Buffer = u1.getTxID() - expect(txid.toString("hex", 0, txid.length)).toBe(outtxid) - }) - test("getOutputIdx", (): void => { - const txidx: Buffer = u1.getOutputIdx() - expect(txidx.toString("hex", 0, txidx.length)).toBe(outputidx) - }) - test("getUTXOID", (): void => { - const txid: Buffer = Buffer.from(outtxid, "hex") - const txidx: Buffer = Buffer.from(outputidx, "hex") - const utxoid: string = bintools.bufferToB58(Buffer.concat([txid, txidx])) - expect(u1.getUTXOID()).toBe(utxoid) - }) - test("toString", (): void => { - const serialized: string = u1.toString() - expect(serialized).toBe(bintools.cb58Encode(utxobuff)) - }) - }) -}) - -const setMergeTester = ( - input: UTXOSet, - equal: UTXOSet[], - notEqual: UTXOSet[] -): boolean => { - const instr: string = JSON.stringify(input.getUTXOIDs().sort()) - for (let i: number = 0; i < equal.length; i++) { - if (JSON.stringify(equal[i].getUTXOIDs().sort()) != instr) { - return false - } - } - - for (let i: number = 0; i < notEqual.length; i++) { - if (JSON.stringify(notEqual[i].getUTXOIDs().sort()) == instr) { - return false - } - } - return true -} - -describe("UTXOSet", (): void => { - const utxostrs: string[] = [ - bintools.cb58Encode( - Buffer.from( - "000038d1b9f1138672da6fb6c35125539276a9acc2a668d63bea6ba3c795e2edb0f5000000013e07e38e2f23121be8756412c18db7246a16d26ee9936f3cba28be149cfd3558000000070000000000004dd500000000000000000000000100000001a36fd0c2dbcab311731dde7ef1514bd26fcdc74d", - "hex" - ) - ), - bintools.cb58Encode( - Buffer.from( - "0000c3e4823571587fe2bdfc502689f5a8238b9d0ea7f3277124d16af9de0d2d9911000000003e07e38e2f23121be8756412c18db7246a16d26ee9936f3cba28be149cfd355800000007000000000000001900000000000000000000000100000001e1b6b6a4bad94d2e3f20730379b9bcd6f176318e", - "hex" - ) - ), - bintools.cb58Encode( - Buffer.from( - "0000f29dba61fda8d57a911e7f8810f935bde810d3f8d495404685bdb8d9d8545e86000000003e07e38e2f23121be8756412c18db7246a16d26ee9936f3cba28be149cfd355800000007000000000000001900000000000000000000000100000001e1b6b6a4bad94d2e3f20730379b9bcd6f176318e", - "hex" - ) - ) - ] - const addrs: Buffer[] = [ - bintools.cb58Decode("FuB6Lw2D62NuM8zpGLA4Avepq7eGsZRiG"), - bintools.cb58Decode("MaTvKGccbYzCxzBkJpb2zHW7E1WReZqB8") - ] - test("Creation", (): void => { - const set: UTXOSet = new UTXOSet() - set.add(utxostrs[0]) - const utxo: UTXO = new UTXO() - utxo.fromString(utxostrs[0]) - const setArray: UTXO[] = set.getAllUTXOs() - expect(utxo.toString()).toBe(setArray[0].toString()) - }) - - test("bad creation", (): void => { - const set: UTXOSet = new UTXOSet() - const bad: string = bintools.cb58Encode(Buffer.from("aasdfasd", "hex")) - set.add(bad) - const utxo: UTXO = new UTXO() - - expect((): void => { - utxo.fromString(bad) - }).toThrow() - }) - - test("Mutliple add", (): void => { - const set: UTXOSet = new UTXOSet() - // first add - for (let i: number = 0; i < utxostrs.length; i++) { - set.add(utxostrs[i]) - } - // the verify (do these steps separate to ensure no overwrites) - for (let i: number = 0; i < utxostrs.length; i++) { - expect(set.includes(utxostrs[i])).toBe(true) - const utxo: UTXO = new UTXO() - utxo.fromString(utxostrs[i]) - const veriutxo: UTXO = set.getUTXO(utxo.getUTXOID()) as UTXO - expect(veriutxo.toString()).toBe(utxostrs[i]) - } - }) - - test("addArray", (): void => { - const set: UTXOSet = new UTXOSet() - set.addArray(utxostrs) - for (let i: number = 0; i < utxostrs.length; i++) { - const e1: UTXO = new UTXO() - e1.fromString(utxostrs[i]) - expect(set.includes(e1)).toBe(true) - const utxo: UTXO = new UTXO() - utxo.fromString(utxostrs[i]) - const veriutxo: UTXO = set.getUTXO(utxo.getUTXOID()) as UTXO - expect(veriutxo.toString()).toBe(utxostrs[i]) - } - - set.addArray(set.getAllUTXOs()) - for (let i: number = 0; i < utxostrs.length; i++) { - const utxo: UTXO = new UTXO() - utxo.fromString(utxostrs[i]) - expect(set.includes(utxo)).toBe(true) - - const veriutxo: UTXO = set.getUTXO(utxo.getUTXOID()) as UTXO - expect(veriutxo.toString()).toBe(utxostrs[i]) - } - - let o: object = set.serialize("hex") - let s: UTXOSet = new UTXOSet() - s.deserialize(o) - let t: object = set.serialize(display) - let r: UTXOSet = new UTXOSet() - r.deserialize(t) - }) - - test("overwriting UTXO", (): void => { - const set: UTXOSet = new UTXOSet() - set.addArray(utxostrs) - const testutxo: UTXO = new UTXO() - testutxo.fromString(utxostrs[0]) - expect(set.add(utxostrs[0], true).toString()).toBe(testutxo.toString()) - expect(set.add(utxostrs[0], false)).toBeUndefined() - expect(set.addArray(utxostrs, true).length).toBe(3) - expect(set.addArray(utxostrs, false).length).toBe(0) - }) - - describe("Functionality", (): void => { - let set: UTXOSet - let utxos: UTXO[] - beforeEach((): void => { - set = new UTXOSet() - set.addArray(utxostrs) - utxos = set.getAllUTXOs() - }) - - test("remove", (): void => { - const testutxo: UTXO = new UTXO() - testutxo.fromString(utxostrs[0]) - expect(set.remove(utxostrs[0]).toString()).toBe(testutxo.toString()) - expect(set.remove(utxostrs[0])).toBeUndefined() - expect(set.add(utxostrs[0], false).toString()).toBe(testutxo.toString()) - expect(set.remove(utxostrs[0]).toString()).toBe(testutxo.toString()) - }) - - test("removeArray", (): void => { - const testutxo: UTXO = new UTXO() - testutxo.fromString(utxostrs[0]) - expect(set.removeArray(utxostrs).length).toBe(3) - expect(set.removeArray(utxostrs).length).toBe(0) - expect(set.add(utxostrs[0], false).toString()).toBe(testutxo.toString()) - expect(set.removeArray(utxostrs).length).toBe(1) - expect(set.addArray(utxostrs, false).length).toBe(3) - expect(set.removeArray(utxos).length).toBe(3) - }) - - test("getUTXOIDs", (): void => { - const uids: string[] = set.getUTXOIDs() - for (let i: number = 0; i < utxos.length; i++) { - expect(uids.indexOf(utxos[i].getUTXOID())).not.toBe(-1) - } - }) - - test("getAllUTXOs", (): void => { - const allutxos: UTXO[] = set.getAllUTXOs() - const ustrs: string[] = [] - for (let i: number = 0; i < allutxos.length; i++) { - ustrs.push(allutxos[i].toString()) - } - for (let i: number = 0; i < utxostrs.length; i++) { - expect(ustrs.indexOf(utxostrs[i])).not.toBe(-1) - } - const uids: string[] = set.getUTXOIDs() - const allutxos2: UTXO[] = set.getAllUTXOs(uids) - const ustrs2: string[] = [] - for (let i: number = 0; i < allutxos.length; i++) { - ustrs2.push(allutxos2[i].toString()) - } - for (let i: number = 0; i < utxostrs.length; i++) { - expect(ustrs2.indexOf(utxostrs[i])).not.toBe(-1) - } - }) - - test("getUTXOIDs By Address", (): void => { - let utxoids: string[] - utxoids = set.getUTXOIDs([addrs[0]]) - expect(utxoids.length).toBe(1) - utxoids = set.getUTXOIDs(addrs) - expect(utxoids.length).toBe(3) - utxoids = set.getUTXOIDs(addrs, false) - expect(utxoids.length).toBe(3) - }) - - test("getAllUTXOStrings", (): void => { - const ustrs: string[] = set.getAllUTXOStrings() - for (let i: number = 0; i < utxostrs.length; i++) { - expect(ustrs.indexOf(utxostrs[i])).not.toBe(-1) - } - const uids: string[] = set.getUTXOIDs() - const ustrs2: string[] = set.getAllUTXOStrings(uids) - for (let i: number = 0; i < utxostrs.length; i++) { - expect(ustrs2.indexOf(utxostrs[i])).not.toBe(-1) - } - }) - - test("getAddresses", (): void => { - expect(set.getAddresses().sort()).toStrictEqual(addrs.sort()) - }) - - test("getBalance", (): void => { - let balance1: BN - let balance2: BN - balance1 = new BN(0) - balance2 = new BN(0) - for (let i: number = 0; i < utxos.length; i++) { - const assetID = utxos[i].getAssetID() - balance1.add(set.getBalance(addrs, assetID)) - balance2.add((utxos[i].getOutput() as AmountOutput).getAmount()) - } - expect(balance1.toString()).toBe(balance2.toString()) - - balance1 = new BN(0) - balance2 = new BN(0) - const now: BN = UnixNow() - for (let i: number = 0; i < utxos.length; i++) { - const assetID = bintools.cb58Encode(utxos[i].getAssetID()) - balance1.add(set.getBalance(addrs, assetID, now)) - balance2.add((utxos[i].getOutput() as AmountOutput).getAmount()) - } - expect(balance1.toString()).toBe(balance2.toString()) - }) - - test("getAssetIDs", (): void => { - const assetIDs: Buffer[] = set.getAssetIDs() - for (let i: number = 0; i < utxos.length; i++) { - expect(assetIDs).toContain(utxos[i].getAssetID()) - } - const addresses: Buffer[] = set.getAddresses() - expect(set.getAssetIDs(addresses)).toEqual(set.getAssetIDs()) - }) - - describe("Merge Rules", (): void => { - let setA: UTXOSet - let setB: UTXOSet - let setC: UTXOSet - let setD: UTXOSet - let setE: UTXOSet - let setF: UTXOSet - let setG: UTXOSet - let setH: UTXOSet - // Take-or-Leave - const newutxo: string = bintools.cb58Encode( - Buffer.from( - "0000acf88647b3fbaa9fdf4378f3a0df6a5d15d8efb018ad78f12690390e79e1687600000003acf88647b3fbaa9fdf4378f3a0df6a5d15d8efb018ad78f12690390e79e168760000000700000000000186a000000000000000000000000100000001fceda8f90fcb5d30614b99d79fc4baa293077626", - "hex" - ) - ) - - beforeEach((): void => { - setA = new UTXOSet() - setA.addArray([utxostrs[0], utxostrs[2]]) - - setB = new UTXOSet() - setB.addArray([utxostrs[1], utxostrs[2]]) - - setC = new UTXOSet() - setC.addArray([utxostrs[0], utxostrs[1]]) - - setD = new UTXOSet() - setD.addArray([utxostrs[1]]) - - setE = new UTXOSet() - setE.addArray([]) // empty set - - setF = new UTXOSet() - setF.addArray(utxostrs) // full set, separate from self - - setG = new UTXOSet() - setG.addArray([newutxo, ...utxostrs]) // full set with new element - - setH = new UTXOSet() - setH.addArray([newutxo]) // set with only a new element - }) - - test("unknown merge rule", (): void => { - expect((): void => { - set.mergeByRule(setA, "ERROR") - }).toThrow() - }) - - test("intersection", (): void => { - let results: UTXOSet - let test: boolean - - results = set.mergeByRule(setA, "intersection") - test = setMergeTester( - results, - [setA], - [setB, setC, setD, setE, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setF, "intersection") - test = setMergeTester( - results, - [setF], - [setA, setB, setC, setD, setE, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setG, "intersection") - test = setMergeTester( - results, - [setF], - [setA, setB, setC, setD, setE, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setH, "intersection") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - }) - - test("differenceSelf", (): void => { - let results: UTXOSet - let test: boolean - - results = set.mergeByRule(setA, "differenceSelf") - test = setMergeTester( - results, - [setD], - [setA, setB, setC, setE, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setF, "differenceSelf") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setG, "differenceSelf") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setH, "differenceSelf") - test = setMergeTester( - results, - [setF], - [setA, setB, setC, setD, setE, setG, setH] - ) - expect(test).toBe(true) - }) - - test("differenceNew", (): void => { - let results: UTXOSet - let test: boolean - - results = set.mergeByRule(setA, "differenceNew") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setF, "differenceNew") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setG, "differenceNew") - test = setMergeTester( - results, - [setH], - [setA, setB, setC, setD, setE, setF, setG] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setH, "differenceNew") - test = setMergeTester( - results, - [setH], - [setA, setB, setC, setD, setE, setF, setG] - ) - expect(test).toBe(true) - }) - - test("symDifference", (): void => { - let results: UTXOSet - let test: boolean - - results = set.mergeByRule(setA, "symDifference") - test = setMergeTester( - results, - [setD], - [setA, setB, setC, setE, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setF, "symDifference") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setG, "symDifference") - test = setMergeTester( - results, - [setH], - [setA, setB, setC, setD, setE, setF, setG] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setH, "symDifference") - test = setMergeTester( - results, - [setG], - [setA, setB, setC, setD, setE, setF, setH] - ) - expect(test).toBe(true) - }) - - test("union", (): void => { - let results: UTXOSet - let test: boolean - - results = set.mergeByRule(setA, "union") - test = setMergeTester( - results, - [setF], - [setA, setB, setC, setD, setE, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setF, "union") - test = setMergeTester( - results, - [setF], - [setA, setB, setC, setD, setE, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setG, "union") - test = setMergeTester( - results, - [setG], - [setA, setB, setC, setD, setE, setF, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setH, "union") - test = setMergeTester( - results, - [setG], - [setA, setB, setC, setD, setE, setF, setH] - ) - expect(test).toBe(true) - }) - - test("unionMinusNew", (): void => { - let results: UTXOSet - let test: boolean - - results = set.mergeByRule(setA, "unionMinusNew") - test = setMergeTester( - results, - [setD], - [setA, setB, setC, setE, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setF, "unionMinusNew") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setG, "unionMinusNew") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setH, "unionMinusNew") - test = setMergeTester( - results, - [setF], - [setA, setB, setC, setD, setE, setG, setH] - ) - expect(test).toBe(true) - }) - - test("unionMinusSelf", (): void => { - let results: UTXOSet - let test: boolean - - results = set.mergeByRule(setA, "unionMinusSelf") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setF, "unionMinusSelf") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setG, "unionMinusSelf") - test = setMergeTester( - results, - [setH], - [setA, setB, setC, setD, setE, setF, setG] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setH, "unionMinusSelf") - test = setMergeTester( - results, - [setH], - [setA, setB, setC, setD, setE, setF, setG] - ) - expect(test).toBe(true) - }) - }) - }) -}) diff --git a/tests/apis/avm/vertex.test.ts b/tests/apis/avm/vertex.test.ts deleted file mode 100644 index 53035f928..000000000 --- a/tests/apis/avm/vertex.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import BinTools from "../../../src/utils/bintools" -import BN from "bn.js" -import { Buffer } from "buffer/" -import { Vertex, Tx } from "src/apis/avm" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() - -describe("Vertex", (): void => { - beforeEach((): void => {}) - describe("constructor", (): void => { - const networkID: number = 1 - const blockchainID: string = - "2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM" - const height: BN = new BN(12345) - const epoch: number = 0 - const parentIDBuf: Buffer = bintools.cb58Decode( - "2HCoR1WzY3TEFipaxeyXhnKa4MYTjfUc4zN5SFhZHoTJGquVfp" - ) - const parentIDs: Buffer[] = [parentIDBuf] - const txs: Tx[] = [] - - const vertex: Vertex = new Vertex( - networkID, - blockchainID, - height, - epoch, - parentIDs, - txs - ) - - test("getNetworkID", (): void => { - const nID: number = vertex.getNetworkID() - expect(nID).toBe(networkID) - }) - - test("getBlockchainID", (): void => { - const bID: string = vertex.getBlockchainID() - expect(bID).toBe(blockchainID) - }) - - test("getHeight", (): void => { - const h: BN = vertex.getHeight() - expect(h).toBe(height) - }) - - test("getEpoch", (): void => { - const e: number = vertex.getEpoch() - expect(e).toBe(epoch) - }) - - test("getParentIDs", (): void => { - const pIDs: Buffer[] = vertex.getParentIDs() - expect(pIDs).toEqual(parentIDs) - }) - - test("getTxs", (): void => { - const t: Tx[] = vertex.getTxs() - expect(t).toBe(txs) - }) - - test("toBuffer", (): void => { - const b: Buffer = vertex.toBuffer() - const v: Vertex = new Vertex() - v.fromBuffer(b) - expect(v.toBuffer().toString("hex")).toEqual( - vertex.toBuffer().toString("hex") - ) - }) - }) -}) diff --git a/tests/apis/evm/api.test.ts b/tests/apis/evm/api.test.ts deleted file mode 100644 index fda49efe3..000000000 --- a/tests/apis/evm/api.test.ts +++ /dev/null @@ -1,385 +0,0 @@ -import mockAxios from "jest-mock-axios" -import { Avalanche, BN } from "src" -import { EVMAPI } from "../../../src/apis/evm/api" -import BinTools from "../../../src/utils/bintools" -import * as bech32 from "bech32" -import { Defaults } from "../../../src/utils/constants" -import { HttpResponse } from "jest-mock-axios/dist/lib/mock-axios-types" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() - -describe("EVMAPI", (): void => { - const networkID: number = 1337 - const blockchainID: string = Defaults.network[networkID].C.blockchainID - const ip: string = "127.0.0.1" - const port: number = 9650 - const protocol: string = "https" - const username: string = "AvaLabs" - const password: string = "password" - - const avalanche: Avalanche = new Avalanche( - ip, - port, - protocol, - networkID, - undefined, - undefined, - undefined, - true - ) - let api: EVMAPI - - const addrA: string = - "C-" + - bech32.bech32.encode( - avalanche.getHRP(), - bech32.bech32.toWords( - bintools.cb58Decode("B6D4v1VtPYLbiUvYXtW4Px8oE9imC2vGW") - ) - ) - const addrC: string = - "C-" + - bech32.bech32.encode( - avalanche.getHRP(), - bech32.bech32.toWords( - bintools.cb58Decode("6Y3kysjF9jnHnYkdS9yGAuoHyae2eNmeV") - ) - ) - - beforeAll((): void => { - api = new EVMAPI(avalanche, "/ext/bc/C/avax", blockchainID) - }) - - afterEach((): void => { - mockAxios.reset() - }) - - test("importKey", async (): Promise => { - const address: string = addrC - - const result: Promise = api.importKey(username, password, "key") - const payload: object = { - result: { - address - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(address) - }) - - test("fail to import because no user created", async (): Promise => { - const badUserName = "zzzzzzzzzzzzzz" - const message: string = `problem retrieving data: rpc error: code = Unknown desc = incorrect password for user "${badUserName}` - - const result: Promise = api.importKey(badUserName, password, "key") - const payload: object = { - result: { - code: -32000, - message, - data: null - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response["code"]).toBe(-32000) - expect(response["message"]).toBe(message) - }) - - test("exportKey", async (): Promise => { - const key: string = - "PrivateKey-ewoqjP7PxY4yr3iLTpLisriqt94hdyDFNgchSxGGztUrTXtNN" - const privateKeyHex: string = - "0x56289e99c94b6912bfc12adc093c9b51124f0dc54ac7a766b2bc5ccf558d8027" - const object: object = { privateKey: key, privateKeyHex } - - const result: Promise = api.exportKey(username, password, addrA) - const payload: object = { - result: { - privateKey: key, - privateKeyHex - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: object = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toEqual(object) - }) - - test("exportAVAX", async (): Promise => { - let amount: BN = new BN(100) - let to: string = "abcdef" - let username: string = "Robert" - let password: string = "Paulson" - let txID: string = "valid" - let result: Promise = api.exportAVAX(username, password, to, amount) - let payload: object = { - result: { - txID: txID - } - } - let responseObj = { - data: payload - } - - mockAxios.mockResponse(responseObj) - let response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(txID) - }) - - test("export", async (): Promise => { - let amount: BN = new BN(100) - let to: string = "abcdef" - let assetID: string = "2fombhL7aGPwj3KH4bfrmJwW6PVnMobf9Y2fn9GwxiAAJyFDbe" - let username: string = "Robert" - let password: string = "Paulson" - let txID: string = "valid" - let result: Promise = api.export( - username, - password, - to, - amount, - assetID - ) - let payload: object = { - result: { - txID: txID - } - } - let responseObj = { - data: payload - } - - mockAxios.mockResponse(responseObj) - let response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(txID) - }) - - test("importAVAX", async (): Promise => { - let to: string = "abcdef" - let username: string = "Robert" - let password: string = "Paulson" - let txID: string = "valid" - let result: Promise = api.importAVAX( - username, - password, - to, - blockchainID - ) - let payload: object = { - result: { - txID: txID - } - } - let responseObj = { - data: payload - } - - mockAxios.mockResponse(responseObj) - let response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(txID) - }) - - test("import", async (): Promise => { - let to: string = "abcdef" - let username: string = "Robert" - let password: string = "Paulson" - let txID: string = "valid" - let result: Promise = api.import( - username, - password, - to, - blockchainID - ) - let payload: object = { - result: { - txID: txID - } - } - let responseObj = { - data: payload - } - - mockAxios.mockResponse(responseObj) - let response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(txID) - }) - - test("refreshBlockchainID", async (): Promise => { - const n5bcID: string = Defaults.network[5].C["blockchainID"] - const n1337bcID: string = Defaults.network[1337].C["blockchainID"] - const testAPI: EVMAPI = new EVMAPI(avalanche, "/ext/bc/C/avax", n5bcID) - const bc1: string = testAPI.getBlockchainID() - expect(bc1).toBe(n5bcID) - - let res: boolean = testAPI.refreshBlockchainID() - expect(res).toBeTruthy() - const bc2: string = testAPI.getBlockchainID() - expect(bc2).toBe(n1337bcID) - - res = testAPI.refreshBlockchainID(n5bcID) - expect(res).toBeTruthy() - const bc3: string = testAPI.getBlockchainID() - expect(bc3).toBe(n5bcID) - }) - - test("getAssetBalance", async (): Promise => { - const address: string = "0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC" - const hexStr: string = "0x0" - const blockHeight: string = hexStr - const assetID: string = "FCry2Z1Su9KZqK1XRMhxQS6XuPorxDm3C3RBT7hw32ojiqyvP" - - const result: Promise = api.getAssetBalance( - address, - blockHeight, - assetID - ) - const payload: object = { - result: hexStr - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: object = await result - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response["result"]).toBe(hexStr) - }) - - test("getAssetBalance with bad assetID", async (): Promise => { - const address: string = "0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC" - const hexStr: string = "0x0" - const blockHeight: string = hexStr - const assetID: string = "aaa" - - const message: string = - "invalid argument 2: couldn't decode ID to bytes: input string is smaller than the checksum size" - - const result: Promise = api.getAssetBalance( - address, - blockHeight, - assetID - ) - const payload: object = { - result: { - code: -32602, - message - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: object = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response["result"]["code"]).toBe(-32602) - expect(response["result"]["message"]).toBe(message) - }) - - test("getAtomicTxStatus", async (): Promise => { - const txID: string = "FCry2Z1Su9KZqK1XRMhxQS6XuPorxDm3C3RBT7hw32ojiqyvP" - - const result: Promise = api.getAtomicTxStatus(txID) - const payload: object = { - result: { - status: "Accepted" - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe("Accepted") - }) - - test("getBaseFee", async (): Promise => { - const result: Promise = api.getBaseFee() - const payload: object = { - result: "0x34630b8a00" - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe("0x34630b8a00") - }) - - test("getMaxPriorityFeePerGas", async (): Promise => { - const result: Promise = api.getMaxPriorityFeePerGas() - const payload: object = { - result: "0x2540be400" - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe("0x2540be400") - }) - - test("getAtomicTx", async (): Promise => { - const txID: string = "FCry2Z1Su9KZqK1XRMhxQS6XuPorxDm3C3RBT7hw32ojiqyvP" - const tx = - "111119TRhWSj932BnTyhskYtn4j7dY9Nqq8wi3mmmFvHvDEoAfifMnRcUuTFqRxhsqWyXMTHmFBcSrMS6u9F6LRA1G3DmKWoA3Yb27JbhUV7ismLkiEsWJ187q2AwgE2RCVG7eZ9zL89ZBmaVA1bkzsx324LjU9NiYgkceJxm5d3L9ATiLgWt4mWMDR4YKpSv4qKqjfD2fRzYm7gX2C2F1auCvVN6Hd15J3jRUB7vKEEcBZJexdYdqnCX7vFdwoGpJM7tUiFRDgAAPpMoxz6QF7gwKbkkXK5Vg4LG2szScX9qL5BegNwUeNQYB42kF3M3w5tnVekhmHQdZSEYU8NjSnSZnqAFPcHc4StM3yZem3MTFRYJqNc7RAvoMGi8am3Hx4GVpwYqjiqev3XiqfyuTssn4bR1XaJbjQTyC" - - const result: Promise = api.getAtomicTx(txID) - const payload: object = { - result: { - tx, - encoding: "hex", - blockHeight: 8 - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(tx) - }) -}) diff --git a/tests/apis/evm/constants.test.ts b/tests/apis/evm/constants.test.ts deleted file mode 100644 index 5e262b3ea..000000000 --- a/tests/apis/evm/constants.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { BN } from "src" -import { Defaults, Networks, Network } from "../../../src/utils/constants" - -describe("EVMConstants", (): void => { - describe("Compare min and max gas prices", (): void => { - const networks: Networks = Defaults.network - const minNum: number = 25000000000 - const maxNum: number = 1000000000000 - const networkIDs: number[] = [1, 5, 12345] - networkIDs.forEach((networkID: number): void => { - test(`NetworkID: ${networkID}`, async (): Promise => { - const localNetwork: Network = networks[networkID] - - const minGasPriceBN: BN = localNetwork.C.minGasPrice - const minGasPriceNum: number = new BN(minGasPriceBN).toNumber() - - const maxGasPriceBN: BN = localNetwork.C.maxGasPrice - const maxGasPriceNum: number = new BN(maxGasPriceBN).toNumber() - - expect(minGasPriceNum).toBeLessThanOrEqual(maxGasPriceNum) - expect(minGasPriceNum).toEqual(minNum) - expect(minGasPriceBN.isEven()).toBeTruthy() - expect(minGasPriceBN.isNeg()).toBeFalsy() - - expect(maxGasPriceNum).toBeGreaterThanOrEqual(minGasPriceNum) - expect(maxGasPriceNum).toEqual(maxNum) - expect(maxGasPriceBN.isEven()).toBeTruthy() - expect(maxGasPriceBN.isNeg()).toBeFalsy() - }) - }) - }) -}) diff --git a/tests/apis/evm/inputs.test.ts b/tests/apis/evm/inputs.test.ts deleted file mode 100644 index 97ef259c5..000000000 --- a/tests/apis/evm/inputs.test.ts +++ /dev/null @@ -1,240 +0,0 @@ -import { UTXOSet, UTXO } from "../../../src/apis/avm/utxos" -import { KeyChain } from "../../../src/apis/avm/keychain" -import { - SECPTransferInput, - TransferableInput -} from "../../../src/apis/avm/inputs" -import createHash from "create-hash" -import BinTools from "../../../src/utils/bintools" -import BN from "bn.js" -import { Buffer } from "buffer/" -import { - SECPTransferOutput, - AmountOutput, - TransferableOutput -} from "../../../src/apis/avm/outputs" -import { EVMConstants } from "../../../src/apis/evm/constants" -import { Input } from "../../../src/common/input" -import { Output } from "../../../src/common/output" -import { EVMInput } from "../../../src/apis/evm" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -describe("Inputs", (): void => { - let set: UTXOSet - let keymgr1: KeyChain - let keymgr2: KeyChain - let addrs1: Buffer[] - let addrs2: Buffer[] - let utxos: UTXO[] - let hrp: string = "tests" - const amnt: number = 10000 - beforeEach((): void => { - set = new UTXOSet() - keymgr1 = new KeyChain(hrp, "C") - keymgr2 = new KeyChain(hrp, "C") - addrs1 = [] - addrs2 = [] - utxos = [] - for (let i: number = 0; i < 3; i++) { - addrs1.push(keymgr1.makeKey().getAddress()) - addrs2.push(keymgr2.makeKey().getAddress()) - } - const amount: BN = new BN(amnt) - const addresses: Buffer[] = keymgr1.getAddresses() - const locktime: BN = new BN(54321) - const threshold: number = 3 - - for (let i: number = 0; i < 3; i++) { - const txid: Buffer = Buffer.from( - createHash("sha256") - .update(bintools.fromBNToBuffer(new BN(i), 32)) - .digest() - ) - const txidx: Buffer = Buffer.from(bintools.fromBNToBuffer(new BN(i), 4)) - const assetID: Buffer = Buffer.from( - createHash("sha256").update(txid).digest() - ) - const out: Output = new SECPTransferOutput( - amount.add(new BN(i)), - addresses, - locktime, - threshold - ) - const xferout: TransferableOutput = new TransferableOutput(assetID, out) - const u: UTXO = new UTXO( - EVMConstants.LATESTCODEC, - txid, - txidx, - assetID, - out - ) - u.fromBuffer( - Buffer.concat([u.getCodecIDBuffer(), txid, txidx, xferout.toBuffer()]) - ) - utxos.push(u) - } - set.addArray(utxos) - }) - test("SECPInput", (): void => { - let u: UTXO - let txid: Buffer - let txidx: Buffer - const amount: BN = new BN(amnt) - let input: SECPTransferInput - let xferinput: TransferableInput - - u = utxos[0] - txid = u.getTxID() - txidx = u.getOutputIdx() - const asset = u.getAssetID() - - input = new SECPTransferInput(amount) - xferinput = new TransferableInput(txid, txidx, asset, input) - expect(xferinput.getUTXOID()).toBe(u.getUTXOID()) - expect(input.getInputID()).toBe(EVMConstants.SECPINPUTID) - - input.addSignatureIdx(0, addrs2[0]) - input.addSignatureIdx(1, addrs2[1]) - - const newin: SECPTransferInput = new SECPTransferInput() - newin.fromBuffer(bintools.b58ToBuffer(input.toString())) - expect(newin.toBuffer().toString("hex")).toBe( - input.toBuffer().toString("hex") - ) - expect(newin.getSigIdxs().toString()).toBe(input.getSigIdxs().toString()) - }) - - test("Input comparator", (): void => { - const inpt1: SECPTransferInput = new SECPTransferInput( - (utxos[0].getOutput() as AmountOutput).getAmount() - ) - - const inpt2: SECPTransferInput = new SECPTransferInput( - (utxos[1].getOutput() as AmountOutput).getAmount() - ) - - const inpt3: SECPTransferInput = new SECPTransferInput( - (utxos[2].getOutput() as AmountOutput).getAmount() - ) - - const cmp = Input.comparator() - expect(cmp(inpt1, inpt2)).toBe(-1) - expect(cmp(inpt1, inpt3)).toBe(-1) - expect(cmp(inpt1, inpt1)).toBe(0) - expect(cmp(inpt2, inpt2)).toBe(0) - expect(cmp(inpt3, inpt3)).toBe(0) - }) - - test("TransferableInput comparator", (): void => { - const inpt1: SECPTransferInput = new SECPTransferInput( - (utxos[0].getOutput() as AmountOutput).getAmount() - ) - const in1: TransferableInput = new TransferableInput( - utxos[0].getTxID(), - utxos[0].getOutputIdx(), - utxos[0].getAssetID(), - inpt1 - ) - - const inpt2: SECPTransferInput = new SECPTransferInput( - (utxos[1].getOutput() as AmountOutput).getAmount() - ) - const in2: TransferableInput = new TransferableInput( - utxos[1].getTxID(), - utxos[1].getOutputIdx(), - utxos[1].getAssetID(), - inpt2 - ) - - const inpt3: SECPTransferInput = new SECPTransferInput( - (utxos[2].getOutput() as AmountOutput).getAmount() - ) - const in3: TransferableInput = new TransferableInput( - utxos[2].getTxID(), - utxos[2].getOutputIdx(), - utxos[2].getAssetID(), - inpt3 - ) - - const cmp = TransferableInput.comparator() - expect(cmp(in1, in2)).toBe(-1) - expect(cmp(in1, in3)).toBe(-1) - expect(cmp(in1, in1)).toBe(0) - expect(cmp(in2, in2)).toBe(0) - expect(cmp(in3, in3)).toBe(0) - }) - - test("EVMInput comparator", (): void => { - let inputs: EVMInput[] = [] - const address1: string = "0x55ee05dF718f1a5C1441e76190EB1a19eE2C9430" - const address3: string = "0x9632a79656af553F58738B0FB750320158495942" - const address4: string = "0x4Cf2eD3665F6bFA95cE6A11CFDb7A2EF5FC1C7E4" - const address6: string = "0x3C7daE394BBf8e9EE1359ad14C1C47003bD06293" - const address8: string = "0x0Fa8EA536Be85F32724D57A37758761B86416123" - const amount1: number = 1 - const amount2: number = 2 - const amount3: number = 3 - const amount4: number = 4 - const amount5: number = 5 - const amount6: number = 6 - const amount7: number = 7 - const amount8: number = 8 - const assetID1: string = - "2fombhL7aGPwj3KH4bfrmJwW6PVnMobf9Y2fn9GwxiAAJyFDbe" // dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db - const assetID2: string = "vvKCjrpggyQ8FhJ2D5EAKPh8x8y4JK93JQiWRpTKpEouydRbG" // 7a6e1e3c9c66ed8f076180f89d01320795628dca633001ff437ac6ab58b455be - const assetID3: string = "eRo1eb2Yxd87KuMYANBSha3n138wtqRhFz2xjftsXWnmpCxyh" // 54fbd087a8a9c739c2c7926d742ea7b937adbd512b9ff0fd51f460a763d1371a - const assetID5: string = - "2QqUTT3XTgR6HLbCLGtjN2uDHHqNRaBgtBGJ5KCqW7BUaH1P8X" // b9d16d7c7d2674c3c67c5c26d9d6e39a09a5991c588cdf60c4cca732b66fa749 - const assetID6: string = "ZWXaLcAy1YWS3Vvjcrt2KcVA4VxBsMFt8yNDZABJkgBvgpRti" // 49d0dc67846a20dfea79b7beeba84769efa4a0273575f65ca79f9dee1cd1250e - const assetID7: string = "FHfS61NfF5XdZU62bcXp9yRfgrZeiQC7VNJWKcpdb9QMLHs4L" // 2070e77e34941439dc7bcf502dcf555c6ef0e3cc46bbac8a03b22e15c84a81f1 - const assetID8: string = "ZL6NeWgcnxR2zhhKDx7h9Kg2mZgScC5N4RG5FCDayWY7W3whZ" // 496849239bb1541e97fa8f89256965bf7e657f3bb530cad820dd41706c5e3836 - const nonce1: number = 0 - const nonce2: number = 1 - const nonce3: number = 2 - const nonce4: number = 3 - const nonce5: number = 4 - const nonce6: number = 5 - const nonce7: number = 6 - const nonce8: number = 7 - - const input1: EVMInput = new EVMInput(address1, amount1, assetID1, nonce1) - inputs.push(input1) - const input2: EVMInput = new EVMInput(address1, amount2, assetID2, nonce2) - inputs.push(input2) - const input3: EVMInput = new EVMInput(address3, amount3, assetID2, nonce3) - inputs.push(input3) - const input4: EVMInput = new EVMInput(address4, amount4, assetID3, nonce4) - inputs.push(input4) - const input5: EVMInput = new EVMInput(address1, amount5, assetID5, nonce5) - inputs.push(input5) - const input6: EVMInput = new EVMInput(address6, amount6, assetID6, nonce6) - inputs.push(input6) - const input7: EVMInput = new EVMInput(address1, amount7, assetID7, nonce7) - inputs.push(input7) - const input8: EVMInput = new EVMInput(address8, amount8, assetID8, nonce8) - inputs.push(input8) - inputs = inputs.sort(EVMInput.comparator()) - expect(inputs[0].getAmount().toString()).toBe("8") - expect(inputs[1].getAmount().toString()).toBe("6") - expect(inputs[2].getAmount().toString()).toBe("4") - expect(inputs[3].getAmount().toString()).toBe("7") - expect(inputs[4].getAmount().toString()).toBe("2") - expect(inputs[5].getAmount().toString()).toBe("5") - expect(inputs[6].getAmount().toString()).toBe("1") - expect(inputs[7].getAmount().toString()).toBe("3") - - const cmp = EVMInput.comparator() - expect(cmp(input2, input1)).toBe(-1) - expect(cmp(input1, input3)).toBe(-1) - expect(cmp(input2, input3)).toBe(-1) - expect(cmp(input1, input1)).toBe(0) - expect(cmp(input2, input2)).toBe(0) - expect(cmp(input3, input3)).toBe(0) - expect(cmp(input1, input2)).toBe(1) - expect(cmp(input3, input1)).toBe(1) - expect(cmp(input3, input2)).toBe(1) - }) -}) diff --git a/tests/apis/evm/keychain.test.ts b/tests/apis/evm/keychain.test.ts deleted file mode 100644 index e46b2f0e7..000000000 --- a/tests/apis/evm/keychain.test.ts +++ /dev/null @@ -1,263 +0,0 @@ -import { KeyChain, KeyPair } from "../../../src/apis/avm/keychain" -import { Avalanche } from "../../../src/index" -import { Buffer } from "buffer/" -import createHash from "create-hash" -import BinTools from "../../../src/utils/bintools" - -const bintools: BinTools = BinTools.getInstance() -const alias: string = "C" -const hrp: string = "tests" - -describe("EVMKeyPair", (): void => { - const networkID: number = 1337 - const ip: string = "127.0.0.1" - const port: number = 9650 - const protocol: string = "https" - const avalanche: Avalanche = new Avalanche( - ip, - port, - protocol, - networkID, - undefined, - undefined, - undefined, - true - ) - - test("human readable part", (): void => { - let hrp: string = avalanche.getHRP() - let networkID: number = avalanche.getNetworkID() - expect(hrp).toBe("custom") - expect(networkID).toBe(1337) - - avalanche.setNetworkID(2) - hrp = avalanche.getHRP() - networkID = avalanche.getNetworkID() - expect(hrp).toBe("cascade") - expect(networkID).toBe(2) - - avalanche.setNetworkID(3) - hrp = avalanche.getHRP() - networkID = avalanche.getNetworkID() - expect(hrp).toBe("denali") - expect(networkID).toBe(3) - - avalanche.setNetworkID(4) - hrp = avalanche.getHRP() - networkID = avalanche.getNetworkID() - expect(hrp).toBe("everest") - expect(networkID).toBe(4) - - avalanche.setNetworkID(0) - hrp = avalanche.getHRP() - networkID = avalanche.getNetworkID() - expect(hrp).toBe("custom") - expect(networkID).toBe(0) - - avalanche.setNetworkID(1) - hrp = avalanche.getHRP() - networkID = avalanche.getNetworkID() - expect(hrp).toBe("avax") - expect(networkID).toBe(1) - - avalanche.setNetworkID(12345) - hrp = avalanche.getHRP() - networkID = avalanche.getNetworkID() - expect(hrp).toBe("local") - expect(networkID).toBe(12345) - }) - - test("repeatable 1", (): void => { - const kp: KeyPair = new KeyPair(hrp, alias) - kp.importKey( - Buffer.from( - "ef9bf2d4436491c153967c9709dd8e82795bdb9b5ad44ee22c2903005d1cf676", - "hex" - ) - ) - expect(kp.getPublicKey().toString("hex")).toBe( - "033fad3644deb20d7a210d12757092312451c112d04773cee2699fbb59dc8bb2ef" - ) - - const msg: Buffer = Buffer.from( - createHash("sha256").update(Buffer.from("09090909", "hex")).digest("hex"), - "hex" - ) - const sig: Buffer = kp.sign(msg) - - expect(sig.length).toBe(65) - expect(kp.verify(msg, sig)).toBe(true) - expect(kp.recover(msg, sig).toString("hex")).toBe( - kp.getPublicKey().toString("hex") - ) - }) - - test("repeatable 2", (): void => { - const kp: KeyPair = new KeyPair(hrp, alias) - kp.importKey( - Buffer.from( - "17c692d4a99d12f629d9f0ff92ec0dba15c9a83e85487b085c1a3018286995c6", - "hex" - ) - ) - expect(kp.getPublicKey().toString("hex")).toBe( - "02486553b276cfe7abf0efbcd8d173e55db9c03da020c33d0b219df24124da18ee" - ) - - const msg: Buffer = Buffer.from( - createHash("sha256").update(Buffer.from("09090909", "hex")).digest("hex"), - "hex" - ) - const sig: Buffer = kp.sign(msg) - - expect(sig.length).toBe(65) - expect(kp.verify(msg, sig)).toBe(true) - expect(kp.recover(msg, sig).toString("hex")).toBe( - kp.getPublicKey().toString("hex") - ) - }) - - test("repeatable 3", (): void => { - const kp: KeyPair = new KeyPair(hrp, alias) - kp.importKey( - Buffer.from( - "d0e17d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - ) - expect(kp.getPublicKey().toString("hex")).toBe( - "031475b91d4fcf52979f1cf107f058088cc2bea6edd51915790f27185a7586e2f2" - ) - - const msg: Buffer = Buffer.from( - createHash("sha256").update(Buffer.from("09090909", "hex")).digest("hex"), - "hex" - ) - const sig: Buffer = kp.sign(msg) - - expect(sig.length).toBe(65) - expect(kp.verify(msg, sig)).toBe(true) - expect(kp.recover(msg, sig).toString("hex")).toBe( - kp.getPublicKey().toString("hex") - ) - }) - - test("Creation Empty", (): void => { - const kp: KeyPair = new KeyPair(hrp, alias) - expect(kp.getPrivateKey()).not.toBeUndefined() - expect(kp.getAddress()).not.toBeUndefined() - expect(kp.getPrivateKeyString()).not.toBeUndefined() - expect(kp.getPublicKey()).not.toBeUndefined() - expect(kp.getPublicKeyString()).not.toBeUndefined() - const msg: Buffer = Buffer.from( - createHash("sha256").update(Buffer.from("09090909", "hex")).digest("hex"), - "hex" - ) - const sig: Buffer = kp.sign(msg) - - expect(sig.length).toBe(65) - expect(kp.verify(msg, sig)).toBe(true) - expect(kp.recover(msg, sig).toString("hex")).toBe( - kp.getPublicKey().toString("hex") - ) - }) -}) - -describe("EVMKeyChain", (): void => { - test("importKey from Buffer", (): void => { - const keybuff: Buffer = Buffer.from( - "d0e17d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - const kc: KeyChain = new KeyChain(hrp, alias) - const kp2: KeyPair = new KeyPair(hrp, alias) - const addr1: Buffer = kc.importKey(keybuff).getAddress() - const kp1: KeyPair = kc.getKey(addr1) - kp2.importKey(keybuff) - const addr2 = kp1.getAddress() - expect(addr1.toString("hex")).toBe(addr2.toString("hex")) - expect(kp1.getPrivateKeyString()).toBe(kp2.getPrivateKeyString()) - expect(kp1.getPublicKeyString()).toBe(kp2.getPublicKeyString()) - expect(kc.hasKey(addr1)).toBe(true) - }) - - test("importKey from Buffer with leading zeros", (): void => { - const keybuff: Buffer = Buffer.from( - "00007d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - expect(keybuff.length).toBe(32) - const kc: KeyChain = new KeyChain(hrp, alias) - const kp2: KeyPair = new KeyPair(hrp, alias) - const addr1: Buffer = kc.importKey(keybuff).getAddress() - const kp1: KeyPair = kc.getKey(addr1) - kp2.importKey(keybuff) - const addr2 = kp1.getAddress() - expect(addr1.toString("hex")).toBe(addr2.toString("hex")) - expect(kp1.getPrivateKeyString()).toBe(kp2.getPrivateKeyString()) - expect(kp1.getPrivateKey().length).toBe(32) - expect(kp2.getPrivateKey().length).toBe(32) - expect(kp1.getPublicKeyString()).toBe(kp2.getPublicKeyString()) - expect(kp1.getPublicKey().length).toBe(33) - expect(kp2.getPublicKey().length).toBe(33) - expect(kc.hasKey(addr1)).toBe(true) - }) - - test("importKey from serialized string", (): void => { - const keybuff: Buffer = Buffer.from( - "d0e17d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - const kc: KeyChain = new KeyChain(hrp, alias) - const kp2: KeyPair = new KeyPair(hrp, alias) - const addr1: Buffer = kc - .importKey("PrivateKey-" + bintools.cb58Encode(keybuff)) - .getAddress() - const kp1: KeyPair = kc.getKey(addr1) - kp2.importKey(keybuff) - const addr2 = kp1.getAddress() - expect(addr1.toString("hex")).toBe(addr2.toString("hex")) - expect(kp1.getPrivateKeyString()).toBe(kp2.getPrivateKeyString()) - expect(kp1.getPublicKeyString()).toBe(kp2.getPublicKeyString()) - expect(kc.hasKey(addr1)).toBe(true) - }) - - test("removeKey via keypair", (): void => { - const keybuff: Buffer = Buffer.from( - "d0e17d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - const kc: KeyChain = new KeyChain(hrp, alias) - const kp1: KeyPair = new KeyPair(hrp, alias) - const addr1: Buffer = kc.importKey(keybuff).getAddress() - kp1.importKey(keybuff) - expect(kc.hasKey(addr1)).toBe(true) - kc.removeKey(kp1) - expect(kc.hasKey(addr1)).toBe(false) - }) - - test("removeKey via string", (): void => { - const keybuff: Buffer = Buffer.from( - "d0e17d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - const kc: KeyChain = new KeyChain(hrp, alias) - const addr1: Buffer = kc.importKey(keybuff).getAddress() - expect(kc.hasKey(addr1)).toBe(true) - kc.removeKey(addr1) - expect(kc.hasKey(addr1)).toBe(false) - }) - - test("removeKey bad keys", (): void => { - const keybuff: Buffer = Buffer.from( - "d0e17d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - const kc: KeyChain = new KeyChain(hrp, alias) - const addr1: Buffer = kc.importKey(keybuff).getAddress() - expect(kc.hasKey(addr1)).toBe(true) - expect( - kc.removeKey(bintools.cb58Decode("6Y3kysjF9jnHnYkdS9yGAuoHyae2eNmeV")) - ).toBe(false) - }) -}) diff --git a/tests/apis/evm/outputs.test.ts b/tests/apis/evm/outputs.test.ts deleted file mode 100644 index acbe73ee0..000000000 --- a/tests/apis/evm/outputs.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { EVMOutput } from "../../../src/apis/evm" - -describe("Inputs", () => { - test("EVMOutput comparator", () => { - let outs: EVMOutput[] = [] - const address1: string = "0x55ee05dF718f1a5C1441e76190EB1a19eE2C9430" - const address3: string = "0x9632a79656af553F58738B0FB750320158495942" - const address4: string = "0x4Cf2eD3665F6bFA95cE6A11CFDb7A2EF5FC1C7E4" - const address6: string = "0x3C7daE394BBf8e9EE1359ad14C1C47003bD06293" - const address8: string = "0x0Fa8EA536Be85F32724D57A37758761B86416123" - const amount1: number = 1 - const amount2: number = 2 - const amount3: number = 3 - const amount4: number = 4 - const amount5: number = 5 - const amount6: number = 6 - const amount7: number = 7 - const amount8: number = 8 - const assetID1: string = - "2fombhL7aGPwj3KH4bfrmJwW6PVnMobf9Y2fn9GwxiAAJyFDbe" // dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db - const assetID2: string = "vvKCjrpggyQ8FhJ2D5EAKPh8x8y4JK93JQiWRpTKpEouydRbG" // 7a6e1e3c9c66ed8f076180f89d01320795628dca633001ff437ac6ab58b455be - const assetID3: string = "eRo1eb2Yxd87KuMYANBSha3n138wtqRhFz2xjftsXWnmpCxyh" // 54fbd087a8a9c739c2c7926d742ea7b937adbd512b9ff0fd51f460a763d1371a - const assetID5: string = - "2QqUTT3XTgR6HLbCLGtjN2uDHHqNRaBgtBGJ5KCqW7BUaH1P8X" // b9d16d7c7d2674c3c67c5c26d9d6e39a09a5991c588cdf60c4cca732b66fa749 - const assetID6: string = "ZWXaLcAy1YWS3Vvjcrt2KcVA4VxBsMFt8yNDZABJkgBvgpRti" // 49d0dc67846a20dfea79b7beeba84769efa4a0273575f65ca79f9dee1cd1250e - const assetID7: string = "FHfS61NfF5XdZU62bcXp9yRfgrZeiQC7VNJWKcpdb9QMLHs4L" // 2070e77e34941439dc7bcf502dcf555c6ef0e3cc46bbac8a03b22e15c84a81f1 - const assetID8: string = "ZL6NeWgcnxR2zhhKDx7h9Kg2mZgScC5N4RG5FCDayWY7W3whZ" // 496849239bb1541e97fa8f89256965bf7e657f3bb530cad820dd41706c5e3836 - - const output1: EVMOutput = new EVMOutput(address1, amount1, assetID1) - outs.push(output1) - const output2: EVMOutput = new EVMOutput(address1, amount2, assetID2) - outs.push(output2) - const output3: EVMOutput = new EVMOutput(address3, amount3, assetID2) - outs.push(output3) - const output4: EVMOutput = new EVMOutput(address4, amount4, assetID3) - outs.push(output4) - const output5: EVMOutput = new EVMOutput(address1, amount5, assetID5) - outs.push(output5) - const output6: EVMOutput = new EVMOutput(address6, amount6, assetID6) - outs.push(output6) - const output7: EVMOutput = new EVMOutput(address1, amount7, assetID7) - outs.push(output7) - const output8: EVMOutput = new EVMOutput(address8, amount8, assetID8) - outs.push(output8) - outs = outs.sort(EVMOutput.comparator()) - expect(outs[0].getAmount().toString()).toBe("8") - expect(outs[1].getAmount().toString()).toBe("6") - expect(outs[2].getAmount().toString()).toBe("4") - expect(outs[3].getAmount().toString()).toBe("7") - expect(outs[4].getAmount().toString()).toBe("2") - expect(outs[5].getAmount().toString()).toBe("5") - expect(outs[6].getAmount().toString()).toBe("1") - expect(outs[7].getAmount().toString()).toBe("3") - - const cmp = EVMOutput.comparator() - expect(cmp(output2, output1)).toBe(-1) - expect(cmp(output1, output3)).toBe(-1) - expect(cmp(output2, output3)).toBe(-1) - expect(cmp(output1, output1)).toBe(0) - expect(cmp(output2, output2)).toBe(0) - expect(cmp(output3, output3)).toBe(0) - expect(cmp(output1, output2)).toBe(1) - expect(cmp(output3, output1)).toBe(1) - expect(cmp(output3, output2)).toBe(1) - }) - - test("EVMOutput from buffer should return amount", () => { - const address: string = "0x55ee05dF718f1a5C1441e76190EB1a19eE2C9430" - const amount: number = 1 - const assetID: string = "2fombhL7aGPwj3KH4bfrmJwW6PVnMobf9Y2fn9GwxiAAJyFDbe" - const output: EVMOutput = new EVMOutput(address, amount, assetID) - expect(output.getAmount().toString()).toBe("1") - - const outputBuffer = new EVMOutput() - outputBuffer.fromBuffer(output.toBuffer()) - expect(outputBuffer.getAmount().toString()).toBe("1") - }) -}) diff --git a/tests/apis/evm/tx.test.ts b/tests/apis/evm/tx.test.ts deleted file mode 100644 index c0cd1ac46..000000000 --- a/tests/apis/evm/tx.test.ts +++ /dev/null @@ -1,297 +0,0 @@ -import { - ExportTx, - ImportTx, - SECPTransferInput, - TransferableInput -} from "../../../src/apis/evm" -import { - Defaults, - MILLIAVAX, - PlatformChainID -} from "../../../src/utils/constants" -import { ONEAVAX } from "../../../src/utils/constants" -import { EVMOutput } from "../../../src/apis/evm" -import BN from "bn.js" -import { BinTools, Buffer } from "src" -const networkID: number = 1337 -const cHexAddress1: string = "0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC" -const bintools: BinTools = BinTools.getInstance() -const cHexAddress2: string = "0xecC3B2968B277b837a81A7181e0b94EB1Ca54EdE" -const antAssetID: string = "F4MyJcUvq3Rxbqgd4Zs8sUpvwLHApyrp4yxJXe2bAV86Vvp38" -const avaxAssetID: string = Defaults.network[networkID].X.avaxAssetID -const txID: string = "QVb7DtKjcwVYLFWHgnGSdzQtQSc29KeRBYFNCBnbFu6dFqX7z" -const blockchainID: string = Defaults.network[networkID].C.blockchainID -const sourcechainID: string = Defaults.network[networkID].X.blockchainID -let evmOutputs: EVMOutput[] -let importedIns: TransferableInput[] -const fee: BN = Defaults.network[networkID].C.txFee - -beforeEach((): void => { - evmOutputs = [] - importedIns = [] -}) - -describe("EVM Transactions", () => { - describe("ImportTx", () => { - test("Multiple AVAX EVMOutput fail", (): void => { - const outputidx: Buffer = Buffer.from("") - const input: SECPTransferInput = new SECPTransferInput(ONEAVAX) - const xferin: TransferableInput = new TransferableInput( - bintools.cb58Decode(txID), - outputidx, - bintools.cb58Decode(avaxAssetID), - input - ) - importedIns.push(xferin) - // Creating 2 outputs with the same address and AVAX assetID is invalid - let evmOutput: EVMOutput = new EVMOutput( - cHexAddress1, - ONEAVAX, - avaxAssetID - ) - evmOutputs.push(evmOutput) - evmOutput = new EVMOutput(cHexAddress1, ONEAVAX, avaxAssetID) - evmOutputs.push(evmOutput) - - expect((): void => { - new ImportTx( - networkID, - bintools.cb58Decode(blockchainID), - bintools.cb58Decode(sourcechainID), - importedIns, - evmOutputs - ) - }).toThrow( - "Error - ImportTx: duplicate (address, assetId) pair found in outputs: (0x8db97c7cece249c2b98bdc0226cc4c2a57bf52fc, BUuypiq2wyuLMvyhzFXcPyxPMCgSp7eeDohhQRqTChoBjKziC)" - ) - }) - - test("Multiple AVAX EVMOutput success", (): void => { - const outputidx: Buffer = Buffer.from("") - const input: SECPTransferInput = new SECPTransferInput(ONEAVAX) - const xferin: TransferableInput = new TransferableInput( - bintools.cb58Decode(txID), - outputidx, - bintools.cb58Decode(avaxAssetID), - input - ) - importedIns.push(xferin) - // Creating 2 outputs with different addresses valid - let evmOutput: EVMOutput = new EVMOutput( - cHexAddress1, - ONEAVAX.div(new BN(3)), - avaxAssetID - ) - evmOutputs.push(evmOutput) - evmOutput = new EVMOutput( - cHexAddress2, - ONEAVAX.div(new BN(3)), - avaxAssetID - ) - evmOutputs.push(evmOutput) - - const importTx: ImportTx = new ImportTx( - networkID, - bintools.cb58Decode(blockchainID), - bintools.cb58Decode(sourcechainID), - importedIns, - evmOutputs - ) - expect(importTx).toBeInstanceOf(ImportTx) - expect(importTx.getSourceChain().toString("hex")).toBe( - bintools.cb58Decode(sourcechainID).toString("hex") - ) - }) - - test("Multiple ANT EVMOutput fail", (): void => { - const outputidx: Buffer = Buffer.from("") - const input: SECPTransferInput = new SECPTransferInput(new BN(507)) - const xferin: TransferableInput = new TransferableInput( - bintools.cb58Decode(txID), - outputidx, - bintools.cb58Decode(avaxAssetID), - input - ) - importedIns.push(xferin) - // Creating 2 outputs with the same address and ANT assetID is invalid - let evmOutput: EVMOutput = new EVMOutput( - cHexAddress1, - ONEAVAX, - antAssetID - ) - evmOutputs.push(evmOutput) - evmOutput = new EVMOutput(cHexAddress1, ONEAVAX, antAssetID) - evmOutputs.push(evmOutput) - expect((): void => { - new ImportTx( - networkID, - bintools.cb58Decode(blockchainID), - bintools.cb58Decode(sourcechainID), - importedIns, - evmOutputs - ) - }).toThrow( - "Error - ImportTx: duplicate (address, assetId) pair found in outputs: (0x8db97c7cece249c2b98bdc0226cc4c2a57bf52fc, F4MyJcUvq3Rxbqgd4Zs8sUpvwLHApyrp4yxJXe2bAV86Vvp38)" - ) - }) - - test("Multiple ANT EVMOutput success", (): void => { - const outputidx: Buffer = Buffer.from("") - const input: SECPTransferInput = new SECPTransferInput(fee) - const xferin: TransferableInput = new TransferableInput( - bintools.cb58Decode(txID), - outputidx, - bintools.cb58Decode(avaxAssetID), - input - ) - importedIns.push(xferin) - let evmOutput: EVMOutput = new EVMOutput( - cHexAddress1, - ONEAVAX, - antAssetID - ) - evmOutputs.push(evmOutput) - evmOutput = new EVMOutput(cHexAddress2, ONEAVAX, antAssetID) - evmOutputs.push(evmOutput) - - const importTx: ImportTx = new ImportTx( - networkID, - bintools.cb58Decode(blockchainID), - bintools.cb58Decode(sourcechainID), - importedIns, - evmOutputs - ) - expect(importTx).toBeInstanceOf(ImportTx) - }) - - test("Single ANT EVMOutput fail", (): void => { - const outputidx: Buffer = Buffer.from("") - const input: SECPTransferInput = new SECPTransferInput(new BN(0)) - const xferin: TransferableInput = new TransferableInput( - bintools.cb58Decode(txID), - outputidx, - bintools.cb58Decode(avaxAssetID), - input - ) - importedIns.push(xferin) - - // If the output is a non-avax assetID then don't subtract a fee - const evmOutput: EVMOutput = new EVMOutput( - cHexAddress1, - ONEAVAX, - antAssetID - ) - evmOutputs.push(evmOutput) - const baseFee: BN = new BN(25000000000) - expect((): void => { - new ImportTx( - networkID, - bintools.cb58Decode(blockchainID), - bintools.cb58Decode(sourcechainID), - importedIns, - evmOutputs, - baseFee - ) - }).toThrow( - "Error - 25000000000 nAVAX required for fee and only 0 nAVAX provided" - ) - }) - - test("Single ANT EVMOutput success", (): void => { - const outputidx: Buffer = Buffer.from("") - const input: SECPTransferInput = new SECPTransferInput(ONEAVAX) - const xferin: TransferableInput = new TransferableInput( - bintools.cb58Decode(txID), - outputidx, - bintools.cb58Decode(avaxAssetID), - input - ) - importedIns.push(xferin) - const evmOutput: EVMOutput = new EVMOutput( - cHexAddress1, - ONEAVAX, - antAssetID - ) - evmOutputs.push(evmOutput) - const importTx: ImportTx = new ImportTx( - networkID, - bintools.cb58Decode(blockchainID), - bintools.cb58Decode(sourcechainID), - importedIns, - evmOutputs - ) - expect(importTx).toBeInstanceOf(ImportTx) - }) - - test("Single AVAX EVMOutput fail", (): void => { - const outputidx: Buffer = Buffer.from("") - const input: SECPTransferInput = new SECPTransferInput(new BN(507)) - const xferin: TransferableInput = new TransferableInput( - bintools.cb58Decode(txID), - outputidx, - bintools.cb58Decode(avaxAssetID), - input - ) - importedIns.push(xferin) - - const evmOutput: EVMOutput = new EVMOutput( - cHexAddress1, - new BN(0), - avaxAssetID - ) - evmOutputs.push(evmOutput) - const baseFee: BN = new BN(25000000000) - expect((): void => { - new ImportTx( - networkID, - bintools.cb58Decode(blockchainID), - bintools.cb58Decode(sourcechainID), - importedIns, - evmOutputs, - baseFee - ) - }).toThrow( - "Error - 25000000000 nAVAX required for fee and only 507 nAVAX provided" - ) - }) - - test("Single AVAX EVMOutput success", (): void => { - const outputidx: Buffer = Buffer.from("") - const input: SECPTransferInput = new SECPTransferInput(ONEAVAX) - const xferin: TransferableInput = new TransferableInput( - bintools.cb58Decode(txID), - outputidx, - bintools.cb58Decode(avaxAssetID), - input - ) - importedIns.push(xferin) - const evmOutput: EVMOutput = new EVMOutput( - cHexAddress1, - ONEAVAX.sub(MILLIAVAX), - avaxAssetID - ) - evmOutputs.push(evmOutput) - const importTx: ImportTx = new ImportTx( - networkID, - bintools.cb58Decode(blockchainID), - bintools.cb58Decode(sourcechainID), - importedIns, - evmOutputs - ) - expect(importTx).toBeInstanceOf(ImportTx) - }) - }) - describe("ExportTx", () => { - test("getDestinationChain", (): void => { - const exportTx: ExportTx = new ExportTx( - networkID, - bintools.cb58Decode(blockchainID), - bintools.cb58Decode(PlatformChainID) - ) - expect(exportTx).toBeInstanceOf(ExportTx) - expect(exportTx.getDestinationChain().toString("hex")).toBe( - bintools.cb58Decode(PlatformChainID).toString("hex") - ) - }) - }) -}) diff --git a/tests/apis/health/api.test.ts b/tests/apis/health/api.test.ts deleted file mode 100644 index 7ec66460b..000000000 --- a/tests/apis/health/api.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import mockAxios from "jest-mock-axios" - -import { Avalanche } from "src" -import { HealthAPI } from "../../../src/apis/health/api" -import { HealthResponse } from "../../../src/apis/health/interfaces" -import { HttpResponse } from "jest-mock-axios/dist/lib/mock-axios-types" - -describe("Health", (): void => { - const ip: string = "127.0.0.1" - const port: number = 9650 - const protocol: string = "https" - const avalanche: Avalanche = new Avalanche( - ip, - port, - protocol, - 12345, - undefined, - undefined, - undefined, - true - ) - let health: HealthAPI - - beforeAll((): void => { - health = new HealthAPI(avalanche) - }) - - afterEach((): void => { - mockAxios.reset() - }) - - test("health", async (): Promise => { - const result: Promise = health.health() - const payload: any = { - result: { - checks: { - C: { - message: [Object], - timestamp: "2021-09-29T15:31:20.274427-07:00", - duration: 275539, - contiguousFailures: 0, - timeOfFirstFailure: null - }, - P: { - message: [Object], - timestamp: "2021-09-29T15:31:20.274508-07:00", - duration: 14576, - contiguousFailures: 0, - timeOfFirstFailure: null - }, - X: { - message: [Object], - timestamp: "2021-09-29T15:31:20.274529-07:00", - duration: 4563, - contiguousFailures: 0, - timeOfFirstFailure: null - }, - isBootstrapped: { - timestamp: "2021-09-29T15:31:19.448314-07:00", - duration: 392, - contiguousFailures: 0, - timeOfFirstFailure: null - }, - network: { - message: [Object], - timestamp: "2021-09-29T15:31:19.448311-07:00", - duration: 4866, - contiguousFailures: 0, - timeOfFirstFailure: null - }, - router: { - message: [Object], - timestamp: "2021-09-29T15:31:19.448452-07:00", - duration: 3932, - contiguousFailures: 0, - timeOfFirstFailure: null - } - }, - healthy: true - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: any = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(payload.result) - }) -}) diff --git a/tests/apis/index/api.test.ts b/tests/apis/index/api.test.ts deleted file mode 100644 index 0ae31e5db..000000000 --- a/tests/apis/index/api.test.ts +++ /dev/null @@ -1,187 +0,0 @@ -import mockAxios from "jest-mock-axios" -import { HttpResponse } from "jest-mock-axios/dist/lib/mock-axios-types" -import { Avalanche } from "src" -import { IsAcceptedResponse } from "src/apis/index/interfaces" -import { IndexAPI } from "../../../src/apis/index/api" - -describe("Index", () => { - const ip: string = "127.0.0.1" - const port: number = 9650 - const protocol: string = "https" - - const avalanche: Avalanche = new Avalanche(ip, port, protocol, 12345) - let index: IndexAPI - - const id: string = "6fXf5hncR8LXvwtM8iezFQBpK5cubV6y1dWgpJCcNyzGB1EzY" - const bytes: string = - "111115HRzXVDSeonLBcv6QdJkQFjPzPEobMWy7PyGuoheggsMCx73MVXZo2hJMEXXvR5gFFasTRJH36aVkLiWHtTTFcghyFTqjaHnBhdXTRiLaYcro3jpseqLAFVn3ngnAB47nebQiBBKmg3nFWKzQUDxMuE6uDGXgnGouDSaEKZxfKreoLHYNUxH56rgi5c8gKFYSDi8AWBgy26siwAWj6V8EgFnPVgm9pmKCfXio6BP7Bua4vrupoX8jRGqdrdkN12dqGAibJ78Rf44SSUXhEvJtPxAzjEGfiTyAm5BWFqPdheKN72HyrBBtwC6y7wG6suHngZ1PMBh93Ubkbt8jjjGoEgs5NjpasJpE8YA9ZMLTPeNZ6ELFxV99zA46wvkjAwYHGzegBXvzGU5pGPbg28iW3iKhLoYAnReysY4x3fBhjPBsags37Z9P3SqioVifVX4wwzxYqbV72u1AWZ4JNmsnhVDP196Gu99QTzmySGTVGP5ABNdZrngTRfmGTFCRbt9CHsgNbhgetkxbsEG7tySi3gFxMzGuJ2Npk2gnSr68LgtYdSHf48Ns" - const timestamp: string = "2021-04-02T15:34:00.262979-07:00" - const idx: string = "0" - - beforeAll(() => { - index = avalanche.Index() - }) - - afterEach(() => { - mockAxios.reset() - }) - - test("getLastAccepted", async () => { - const encoding: string = "hex" - const baseurl: string = "/ext/index/X/tx" - const respobj = { - id, - bytes, - timestamp, - encoding, - idx - } - const result: Promise = index.getLastAccepted(encoding, baseurl) - - const payload: object = { - result: respobj - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: object = await result - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(JSON.stringify(response)).toBe(JSON.stringify(respobj)) - }) - - test("getContainerByIndex", async () => { - const encoding: string = "hex" - const baseurl: string = "/ext/index/X/tx" - const respobj = { - id, - bytes, - timestamp, - encoding, - idx - } - const result: Promise = index.getContainerByIndex( - idx, - encoding, - baseurl - ) - - const payload: object = { - result: respobj - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: object = await result - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(JSON.stringify(response)).toBe(JSON.stringify(respobj)) - }) - - test("getContainerByID", async () => { - const encoding: string = "hex" - const baseurl: string = "/ext/index/X/tx" - const respobj = { - id, - bytes, - timestamp, - encoding, - idx - } - const result: Promise = index.getContainerByIndex( - id, - encoding, - baseurl - ) - - const payload: object = { - result: respobj - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: object = await result - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(JSON.stringify(response)).toBe(JSON.stringify(respobj)) - }) - - test("getContainerRange", async () => { - const startIndex: number = 0 - const numToFetch: number = 100 - const encoding: string = "hex" - const baseurl: string = "/ext/index/X/tx" - const respobj = { - id, - bytes, - timestamp, - encoding, - idx - } - const result: Promise = index.getContainerRange( - startIndex, - numToFetch, - encoding, - baseurl - ) - - const payload: object = { - result: respobj - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: object = await result - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(JSON.stringify(response)).toBe(JSON.stringify(respobj)) - }) - - test("getIndex", async () => { - const encoding: string = "hex" - const baseurl: string = "/ext/index/X/tx" - const result: Promise = index.getIndex(id, encoding, baseurl) - - const payload: object = { - result: { - index: "0" - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe("0") - }) - - test("isAccepted", async () => { - const encoding: string = "hex" - const baseurl: string = "/ext/index/X/tx" - const result: Promise = index.isAccepted( - id, - encoding, - baseurl - ) - - const payload: object = { - result: true - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: IsAcceptedResponse = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(true) - }) -}) diff --git a/tests/apis/info/api.test.ts b/tests/apis/info/api.test.ts deleted file mode 100644 index de88ab8ac..000000000 --- a/tests/apis/info/api.test.ts +++ /dev/null @@ -1,239 +0,0 @@ -import mockAxios from "jest-mock-axios" -import { Avalanche } from "src" -import { InfoAPI } from "../../../src/apis/info/api" -import BN from "bn.js" -import { - PeersResponse, - UptimeResponse -} from "../../../src/apis/info/interfaces" -import { HttpResponse } from "jest-mock-axios/dist/lib/mock-axios-types" - -describe("Info", (): void => { - const ip: string = "127.0.0.1" - const port: number = 9650 - const protocol: string = "https" - - const avalanche: Avalanche = new Avalanche( - ip, - port, - protocol, - 12345, - "What is my purpose? You pass butter. Oh my god.", - undefined, - undefined, - false - ) - let info: InfoAPI - - beforeAll((): void => { - info = avalanche.Info() - }) - - afterEach((): void => { - mockAxios.reset() - }) - - test("getBlockchainID", async (): Promise => { - const result: Promise = info.getBlockchainID("X") - const payload: object = { - result: { - blockchainID: avalanche.XChain().getBlockchainID() - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe("What is my purpose? You pass butter. Oh my god.") - }) - - test("getNetworkID", async (): Promise => { - const result: Promise = info.getNetworkID() - const payload: object = { - result: { - networkID: 12345 - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: number = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(12345) - }) - - test("getTxFee", async (): Promise => { - const result: Promise<{ txFee: BN; creationTxFee: BN }> = info.getTxFee() - const payload: object = { - result: { - txFee: "1000000", - creationTxFee: "10000000" - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: { txFee: BN; creationTxFee: BN } = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response.txFee.eq(new BN("1000000"))).toBe(true) - expect(response.creationTxFee.eq(new BN("10000000"))).toBe(true) - }) - - test("getNetworkName", async (): Promise => { - const result: Promise = info.getNetworkName() - const payload: object = { - result: { - networkName: "denali" - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe("denali") - }) - - test("getNodeID", async (): Promise => { - const result: Promise = info.getNodeID() - const payload: object = { - result: { - nodeID: "abcd" - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe("abcd") - }) - - test("getNodeVersion", async (): Promise => { - const result: Promise = info.getNodeVersion() - const payload: object = { - result: { - version: "avalanche/0.5.5" - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe("avalanche/0.5.5") - }) - - test("isBootstrapped false", async (): Promise => { - const result: Promise = info.isBootstrapped("X") - const payload: object = { - result: { - isBootstrapped: false - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: boolean = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(false) - }) - - test("isBootstrapped true", async (): Promise => { - const result: Promise = info.isBootstrapped("P") - const payload: object = { - result: { - isBootstrapped: true - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: boolean = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(true) - }) - - test("peers", async (): Promise => { - const peers = [ - { - ip: "127.0.0.1:60300", - publicIP: "127.0.0.1:9659", - nodeID: "NodeID-P7oB2McjBGgW2NXXWVYjV8JEDFoW9xDE5", - version: "avalanche/1.3.2", - lastSent: "2021-04-14T08:15:06-07:00", - lastReceived: "2021-04-14T08:15:06-07:00", - benched: null - }, - { - ip: "127.0.0.1:60302", - publicIP: "127.0.0.1:9655", - nodeID: "NodeID-NFBbbJ4qCmNaCzeW7sxErhvWqvEQMnYcN", - version: "avalanche/1.3.2", - lastSent: "2021-04-14T08:15:06-07:00", - lastReceived: "2021-04-14T08:15:06-07:00", - benched: null - } - ] - const result: Promise = info.peers() - const payload: object = { - result: { - peers - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: PeersResponse[] = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(peers) - }) - - test("uptime", async (): Promise => { - const result: Promise = info.uptime() - const uptimeResponse: UptimeResponse = { - rewardingStakePercentage: "100.0000", - weightedAveragePercentage: "99.2000" - } - const payload: object = { - result: uptimeResponse - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: UptimeResponse = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toEqual(uptimeResponse) - }) -}) diff --git a/tests/apis/keystore/api.test.ts b/tests/apis/keystore/api.test.ts deleted file mode 100644 index 1d69ea799..000000000 --- a/tests/apis/keystore/api.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -import mockAxios from "jest-mock-axios" -import { HttpResponse } from "jest-mock-axios/dist/lib/mock-axios-types" -import { Avalanche } from "src" -import { KeystoreAPI } from "../../../src/apis/keystore/api" - -describe("Keystore", (): void => { - const ip: string = "127.0.0.1" - const port: number = 9650 - const protocol: string = "https" - - const username: string = "AvaLabs" - const password: string = "password" - - const avalanche: Avalanche = new Avalanche( - ip, - port, - protocol, - 12345, - undefined, - undefined, - undefined, - true - ) - let keystore: KeystoreAPI - - beforeAll((): void => { - keystore = new KeystoreAPI(avalanche) - }) - - afterEach((): void => { - mockAxios.reset() - }) - - test("createUser", async (): Promise => { - const result: Promise = keystore.createUser(username, password) - const payload: object = { - result: { - success: true - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: boolean = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(true) - }) - - test("createUser with weak password", async (): Promise => { - const result: Promise = keystore.createUser(username, "aaa") - const message: string = "password is too weak" - const payload: object = { - result: { - code: -32000, - message, - data: null - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: boolean = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response["code"]).toBe(-32000) - expect(response["message"]).toBe(message) - }) - - test("deleteUser", async (): Promise => { - const result: Promise = keystore.deleteUser(username, password) - const payload: object = { - result: { - success: true - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: boolean = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(true) - }) - - test("exportUser", async (): Promise => { - const data: string = "data" - - const result: Promise = keystore.exportUser(username, password) - const payload: object = { - result: { - user: data - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(data) - }) - - test("importUser", async (): Promise => { - const result: Promise = keystore.importUser( - username, - "data", - password - ) - const payload: object = { - result: { - success: true - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: boolean = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(true) - }) - - test("listUsers", async (): Promise => { - const accounts: string[] = ["acc1", "acc2"] - - const result: Promise = keystore.listUsers() - const payload: object = { - result: { - users: accounts - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string[] = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(accounts) - }) -}) diff --git a/tests/apis/metrics/api.test.ts b/tests/apis/metrics/api.test.ts deleted file mode 100644 index 0996098e4..000000000 --- a/tests/apis/metrics/api.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import mockAxios from "jest-mock-axios" -import { HttpResponse } from "jest-mock-axios/dist/lib/mock-axios-types" -import { Avalanche } from "src" -import { MetricsAPI } from "../../../src/apis/metrics/api" - -describe("Metrics", (): void => { - const ip: string = "127.0.0.1" - const port: number = 9650 - const protocol: string = "https" - - const avalanche: Avalanche = new Avalanche( - ip, - port, - protocol, - 12345, - undefined, - undefined, - undefined, - true - ) - let metrics: MetricsAPI - - beforeAll((): void => { - metrics = new MetricsAPI(avalanche) - }) - - afterEach((): void => { - mockAxios.reset() - }) - - test("getMetrics", async (): Promise => { - const result: Promise = metrics.getMetrics() - const payload: string = ` - gecko_timestamp_handler_get_failed_bucket{le="100"} 0 - gecko_timestamp_handler_get_failed_bucket{le="1000"} 0 - gecko_timestamp_handler_get_failed_bucket{le="10000"} 0 - gecko_timestamp_handler_get_failed_bucket{le="100000"} 0 - gecko_timestamp_handler_get_failed_bucket{le="1e+06"} 0 - gecko_timestamp_handler_get_failed_bucket{le="1e+07"} 0 - gecko_timestamp_handler_get_failed_bucket{le="1e+08"} 0 - gecko_timestamp_handler_get_failed_bucket{le="1e+09"} 0 - gecko_timestamp_handler_get_failed_bucket{le="+Inf"} 0 - ` - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(payload) - }) -}) diff --git a/tests/apis/platformvm/addsubnetvalidatortx.test.ts b/tests/apis/platformvm/addsubnetvalidatortx.test.ts deleted file mode 100644 index e0a473ee7..000000000 --- a/tests/apis/platformvm/addsubnetvalidatortx.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -import BN from "bn.js" -import { Buffer } from "buffer/" -import { - AddSubnetValidatorTx, - PlatformVMConstants, - SubnetAuth -} from "src/apis/platformvm" -import { bufferToNodeIDString } from "src/utils" - -describe("AddSubnetValidatorTx", (): void => { - const addSubnetValidatorTxHex: string = - "0000053900000000000000000000000000000000000000000000000000000000000000000000000117cc8b1578ba383544d163958822d8abd3849bb9dfabe39fcbc3e7ee8811fe2f00000007006a94d71389b180000000000000000000000001000000023cb7d3842e8cee6a0ebd09f1fe884f6861e1b29ca43c1f6ecdcb1fcec86d78446b9cf619c64c604b00000001f7fc296b05e7a960e9d2739c1cabdb58f22e5c582e1a7b0877fb10e78cf4e7ec0000000017cc8b1578ba383544d163958822d8abd3849bb9dfabe39fcbc3e7ee8811fe2f00000005006a94d71398f3c00000000100000000000000934d616e75616c6c79206372656174652061204164645375626e657456616c696461746f7254782077686963682063726561746573206120312d6f662d322041564158207574786f20616e64206164647320612076616c696461746f7220746f2061207375626e657420627920636f72726563746c79207369676e696e672074686520322d6f662d33205375626e657441757468de31b4d8b22991d51aa6aa1fc733f23a851a8c94000000006279e79c00000000628d873a00000000000000017fe044f9e97347c0a5ffe5a0f5773b42398c0e2b85948616da681585d460e1a80000000a000000020000000000000001" - const addSubnetValidatorTxBuf: Buffer = Buffer.from( - addSubnetValidatorTxHex, - "hex" - ) - const addSubnetValidatorTx: AddSubnetValidatorTx = new AddSubnetValidatorTx() - addSubnetValidatorTx.fromBuffer(addSubnetValidatorTxBuf) - - test("getTypeName", async (): Promise => { - const addSubnetValidatorTxTypeName: string = - addSubnetValidatorTx.getTypeName() - expect(addSubnetValidatorTxTypeName).toBe("AddSubnetValidatorTx") - }) - - test("getTypeID", async (): Promise => { - const addSubnetValidatorTxTypeID: number = addSubnetValidatorTx.getTypeID() - expect(addSubnetValidatorTxTypeID).toBe( - PlatformVMConstants.ADDSUBNETVALIDATORTX - ) - }) - - test("toBuffer and fromBuffer", async (): Promise => { - const buf: Buffer = addSubnetValidatorTx.toBuffer() - const asvTx: AddSubnetValidatorTx = new AddSubnetValidatorTx() - asvTx.fromBuffer(buf) - const buf2: Buffer = asvTx.toBuffer() - expect(buf.toString("hex")).toBe(buf2.toString("hex")) - }) - - test("getNodeID", async (): Promise => { - const nodeID: string = "NodeID-MFrZFVCXPv5iCn6M9K6XduxGTYp891xXZ" - const nodeIDBuf: Buffer = addSubnetValidatorTx.getNodeID() - const nID: string = bufferToNodeIDString(nodeIDBuf) - expect(nID).toBe(nodeID) - }) - - test("getStartTime", async (): Promise => { - const startTime: BN = new BN(1652156316) - const st: BN = addSubnetValidatorTx.getStartTime() - expect(startTime.toString()).toBe(st.toString()) - }) - - test("getEndTime", async (): Promise => { - const endTime: BN = new BN(1653442362) - const et: BN = addSubnetValidatorTx.getEndTime() - expect(endTime.toString()).toBe(et.toString()) - }) - - test("getWeight", async (): Promise => { - const weight: BN = new BN(1) - const w: BN = addSubnetValidatorTx.getWeight() - expect(weight.toString()).toBe(w.toString()) - }) - - test("getSubnetID", async (): Promise => { - const subnetID: string = "yKRV4EvGYWj7HHXUxSYzaAQVazEvaFPKPhJie4paqbrML5dub" - const sID: string = addSubnetValidatorTx.getSubnetID() - expect(subnetID).toBe(sID) - }) - - describe("SubnetAuth", (): void => { - const sa: SubnetAuth = addSubnetValidatorTx.getSubnetAuth() - - test("getTypeName", async (): Promise => { - const subnetAuthTypeName: string = sa.getTypeName() - expect(subnetAuthTypeName).toBe("SubnetAuth") - }) - - test("getTypeID", async (): Promise => { - const subnetAuthTypeID: number = sa.getTypeID() - expect(subnetAuthTypeID).toBe(PlatformVMConstants.SUBNETAUTH) - }) - - test("getNumAddressIndices", async (): Promise => { - const numAddressIndices: number = sa.getNumAddressIndices() - const nAI: number = 2 - expect(numAddressIndices).toBe(nAI) - }) - - test("addressIndices", async (): Promise => { - const ai: number[] = [0, 1] - const addressIndices: Buffer[] = sa.getAddressIndices() - addressIndices.forEach((addressIndex: Buffer, index: number) => { - expect(addressIndex.readInt32BE(0)).toBe(ai[index]) - }) - }) - }) -}) diff --git a/tests/apis/platformvm/api.test.ts b/tests/apis/platformvm/api.test.ts deleted file mode 100644 index 617f37fad..000000000 --- a/tests/apis/platformvm/api.test.ts +++ /dev/null @@ -1,2570 +0,0 @@ -import mockAxios from "jest-mock-axios" -import { Avalanche } from "src" -import { PlatformVMAPI } from "../../../src/apis/platformvm/api" -import { Buffer } from "buffer/" -import BN from "bn.js" -import BinTools from "../../../src/utils/bintools" -import * as bech32 from "bech32" -import { Defaults, PlatformChainID } from "../../../src/utils/constants" -import { UTXOSet } from "../../../src/apis/platformvm/utxos" -import { PersistanceOptions } from "../../../src/utils/persistenceoptions" -import { KeyChain } from "../../../src/apis/platformvm/keychain" -import { - SECPTransferOutput, - TransferableOutput, - AmountOutput, - ParseableOutput, - StakeableLockOut -} from "../../../src/apis/platformvm/outputs" -import { - TransferableInput, - SECPTransferInput, - AmountInput, - StakeableLockIn -} from "../../../src/apis/platformvm/inputs" -import { UTXO } from "../../../src/apis/platformvm/utxos" -import createHash from "create-hash" -import { UnsignedTx, Tx } from "../../../src/apis/platformvm/tx" -import { UnixNow } from "../../../src/utils/helperfunctions" -import { UTF8Payload } from "../../../src/utils/payload" -import { NodeIDStringToBuffer } from "../../../src/utils/helperfunctions" -import { ONEAVAX } from "../../../src/utils/constants" -import { - Serializable, - Serialization, - SerializedEncoding, - SerializedType -} from "../../../src/utils/serialization" -import { AddValidatorTx } from "../../../src/apis/platformvm/validationtx" -import { - Blockchain, - GetMinStakeResponse, - GetRewardUTXOsResponse, - Subnet, - GetTxStatusResponse, - GetValidatorsAtResponse -} from "../../../src/apis/platformvm/interfaces" -import { ErrorResponseObject } from "../../../src/utils/errors" -import { HttpResponse } from "jest-mock-axios/dist/lib/mock-axios-types" -import { - GetBalanceResponse, - GetUTXOsResponse -} from "src/apis/platformvm/interfaces" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -const serializer: Serialization = Serialization.getInstance() -const display: SerializedEncoding = "display" -const dumpSerialization: boolean = false - -const serialzeit = (aThing: Serializable, name: string): void => { - if (dumpSerialization) { - console.log( - JSON.stringify( - serializer.serialize( - aThing, - "platformvm", - "hex", - name + " -- Hex Encoded" - ) - ) - ) - console.log( - JSON.stringify( - serializer.serialize( - aThing, - "platformvm", - "display", - name + " -- Human-Readable" - ) - ) - ) - } -} - -describe("PlatformVMAPI", (): void => { - const networkID: number = 1337 - const blockchainID: string = PlatformChainID - const ip: string = "127.0.0.1" - const port: number = 9650 - const protocol: string = "https" - - const nodeID: string = "NodeID-B6D4v1VtPYLbiUvYXtW4Px8oE9imC2vGW" - const startTime: BN = UnixNow().add(new BN(60 * 5)) - const endTime: BN = startTime.add(new BN(1209600)) - - const username: string = "AvaLabs" - const password: string = "password" - - const avalanche: Avalanche = new Avalanche( - ip, - port, - protocol, - networkID, - undefined, - undefined, - undefined, - true - ) - let api: PlatformVMAPI - let alias: string - - const addrA: string = - "P-" + - bech32.bech32.encode( - avalanche.getHRP(), - bech32.bech32.toWords( - bintools.cb58Decode("B6D4v1VtPYLbiUvYXtW4Px8oE9imC2vGW") - ) - ) - const addrB: string = - "P-" + - bech32.bech32.encode( - avalanche.getHRP(), - bech32.bech32.toWords( - bintools.cb58Decode("P5wdRuZeaDt28eHMP5S3w9ZdoBfo7wuzF") - ) - ) - const addrC: string = - "P-" + - bech32.bech32.encode( - avalanche.getHRP(), - bech32.bech32.toWords( - bintools.cb58Decode("6Y3kysjF9jnHnYkdS9yGAuoHyae2eNmeV") - ) - ) - - beforeAll((): void => { - api = new PlatformVMAPI(avalanche, "/ext/bc/P") - alias = api.getBlockchainAlias() - }) - - afterEach((): void => { - mockAxios.reset() - }) - - test("getCreateSubnetTxFee", async (): Promise => { - let pchain: PlatformVMAPI = new PlatformVMAPI(avalanche, "/ext/bc/P") - const feeResponse: string = "1000000000" - const fee: BN = pchain.getCreateSubnetTxFee() - expect(fee.toString()).toBe(feeResponse) - }) - - test("getCreateChainTxFee", async (): Promise => { - let pchain: PlatformVMAPI = new PlatformVMAPI(avalanche, "/ext/bc/P") - const feeResponse: string = "1000000000" - const fee: BN = pchain.getCreateChainTxFee() - expect(fee.toString()).toBe(feeResponse) - }) - - test("refreshBlockchainID", async (): Promise => { - let n3bcID: string = Defaults.network[3].P["blockchainID"] - let testAPI: PlatformVMAPI = new PlatformVMAPI(avalanche, "/ext/bc/P") - let bc1: string = testAPI.getBlockchainID() - expect(bc1).toBe(PlatformChainID) - - testAPI.refreshBlockchainID() - let bc2: string = testAPI.getBlockchainID() - expect(bc2).toBe(PlatformChainID) - - testAPI.refreshBlockchainID(n3bcID) - let bc3: string = testAPI.getBlockchainID() - expect(bc3).toBe(n3bcID) - }) - - test("listAddresses", async (): Promise => { - const addresses: string[] = [addrA, addrB] - - const result: Promise = api.listAddresses(username, password) - const payload: object = { - result: { - addresses - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string[] = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(addresses) - }) - - test("importKey", async (): Promise => { - const address: string = addrC - - const result: Promise = api.importKey( - username, - password, - "key" - ) - const payload: object = { - result: { - address - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string | ErrorResponseObject = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(address) - }) - - test("import bad key", async (): Promise => { - const address: string = addrC - const message: string = - 'problem retrieving data: incorrect password for user "test"' - const result: Promise = api.importKey( - username, - "badpassword", - "key" - ) - const payload: object = { - result: { - code: -32000, - message, - data: null - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string | ErrorResponseObject = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - - expect(response["code"]).toBe(-32000) - expect(response["message"]).toBe(message) - }) - - test("getBalance", async (): Promise => { - const balance: BN = new BN("100", 10) - const unlocked: BN = new BN("100", 10) - const lockedStakeable: BN = new BN("100", 10) - const lockedNotStakeable: BN = new BN("100", 10) - const respobj: GetBalanceResponse = { - balance, - unlocked, - lockedStakeable, - lockedNotStakeable, - utxoIDs: [ - { - txID: "LUriB3W919F84LwPMMw4sm2fZ4Y76Wgb6msaauEY7i1tFNmtv", - outputIndex: 0 - } - ] - } - const result: Promise = api.getBalance([addrA]) - const payload: object = { - result: respobj - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: object = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(JSON.stringify(response)).toBe(JSON.stringify(respobj)) - }) - - test("getCurrentSupply", async (): Promise => { - const supply: BN = new BN("1000000000000", 10) - const result: Promise = api.getCurrentSupply() - const payload: object = { - result: { - supply - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: BN = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response.toString(10)).toBe(supply.toString(10)) - }) - - test("getValidatorsAt", async (): Promise => { - const height: number = 0 - const subnetID: string = "11111111111111111111111111111111LpoYY" - const result: Promise = api.getValidatorsAt( - height, - subnetID - ) - const payload: object = { - result: { - validators: { - "NodeID-7Xhw2mDxuDS44j42TCB6U5579esbSt3Lg": 2000000000000000, - "NodeID-GWPcbFJZFfZreETSoWjPimr846mXEKCtu": 2000000000000000, - "NodeID-MFrZFVCXPv5iCn6M9K6XduxGTYp891xXZ": 2000000000000000, - "NodeID-NFBbbJ4qCmNaCzeW7sxErhvWqvEQMnYcN": 2000000000000000, - "NodeID-P7oB2McjBGgW2NXXWVYjV8JEDFoW9xDE5": 2000000000000000 - } - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: GetValidatorsAtResponse = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - }) - - test("getHeight", async (): Promise => { - const height: BN = new BN("100", 10) - const result: Promise = api.getHeight() - const payload: object = { - result: { - height - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: BN = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response.toString(10)).toBe(height.toString(10)) - }) - - test("getMinStake", async (): Promise => { - const minStake: BN = new BN("2000000000000", 10) - const minDelegate: BN = new BN("25000000000", 10) - const result: Promise = api.getMinStake() - const payload: object = { - result: { - minValidatorStake: "2000000000000", - minDelegatorStake: "25000000000" - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: GetMinStakeResponse = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response["minValidatorStake"].toString(10)).toBe( - minStake.toString(10) - ) - expect(response["minDelegatorStake"].toString(10)).toBe( - minDelegate.toString(10) - ) - }) - - test("getStake", async (): Promise => { - const staked: BN = new BN("100", 10) - const stakedOutputs: string[] = [ - "0x000021e67317cbc4be2aeb00677ad6462778a8f52274b9d605df2591b23027a87dff000000160000000060bd6180000000070000000fb750430000000000000000000000000100000001e70060b7051a4838ebe8e29bcbe1403db9b88cc316895eb3", - "0x000021e67317cbc4be2aeb00677ad6462778a8f52274b9d605df2591b23027a87dff000000160000000060bd618000000007000000d18c2e280000000000000000000000000100000001e70060b7051a4838ebe8e29bcbe1403db9b88cc3714de759", - "0x000021e67317cbc4be2aeb00677ad6462778a8f52274b9d605df2591b23027a87dff000000160000000061340880000000070000000fb750430000000000000000000000000100000001e70060b7051a4838ebe8e29bcbe1403db9b88cc379b89461", - "0x000021e67317cbc4be2aeb00677ad6462778a8f52274b9d605df2591b23027a87dff00000016000000006134088000000007000000d18c2e280000000000000000000000000100000001e70060b7051a4838ebe8e29bcbe1403db9b88cc3c7aa35d1", - "0x000021e67317cbc4be2aeb00677ad6462778a8f52274b9d605df2591b23027a87dff00000016000000006134088000000007000001d1a94a200000000000000000000000000100000001e70060b7051a4838ebe8e29bcbe1403db9b88cc38fd232d8" - ] - const objs: TransferableOutput[] = stakedOutputs.map( - (stakedOutput: string): TransferableOutput => { - const transferableOutput: TransferableOutput = new TransferableOutput() - let buf: Buffer = Buffer.from(stakedOutput.replace(/0x/g, ""), "hex") - transferableOutput.fromBuffer(buf, 2) - return transferableOutput - } - ) - const result: Promise = api.getStake([addrA], "hex") - const payload: object = { - result: { - staked, - stakedOutputs - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: object = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(JSON.stringify(response["staked"])).toBe(JSON.stringify(staked)) - expect(JSON.stringify(response["stakedOutputs"])).toBe(JSON.stringify(objs)) - }) - - test("addSubnetValidator 1", async (): Promise => { - const nodeID: string = "abcdef" - const subnetID: string = "4R5p2RXDGLqaifZE4hHWH9owe34pfoBULn1DrQTWivjg8o4aH" - const startTime: Date = new Date(1985, 5, 9, 12, 59, 43, 9) - const endTime: Date = new Date(1982, 3, 1, 12, 58, 33, 7) - const weight: number = 13 - const utx: string = "valid" - const result: Promise = - api.addSubnetValidator( - username, - password, - nodeID, - subnetID, - startTime, - endTime, - weight - ) - const payload: object = { - result: { - txID: utx - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string | ErrorResponseObject = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(utx) - }) - - test("addSubnetValidator", async (): Promise => { - const nodeID: string = "abcdef" - const subnetID: Buffer = Buffer.from("abcdef", "hex") - const startTime: Date = new Date(1985, 5, 9, 12, 59, 43, 9) - const endTime: Date = new Date(1982, 3, 1, 12, 58, 33, 7) - const weight: number = 13 - const utx: string = "valid" - const result: Promise = - api.addSubnetValidator( - username, - password, - nodeID, - subnetID, - startTime, - endTime, - weight - ) - const payload: object = { - result: { - txID: utx - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string | ErrorResponseObject = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(utx) - }) - - test("addDelegator 1", async (): Promise => { - const nodeID: string = "abcdef" - const startTime = new Date(1985, 5, 9, 12, 59, 43, 9) - const endTime: Date = new Date(1982, 3, 1, 12, 58, 33, 7) - const stakeAmount: BN = new BN(13) - const rewardAddress: string = "fedcba" - const utx: string = "valid" - const result: Promise = api.addDelegator( - username, - password, - nodeID, - startTime, - endTime, - stakeAmount, - rewardAddress - ) - const payload: object = { - result: { - txID: utx - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(utx) - }) - - test("getBlockchains 1", async (): Promise => { - const resp: object[] = [ - { - id: "nodeID", - subnetID: "subnetID", - vmID: "vmID" - } - ] - const result: Promise = api.getBlockchains() - const payload: object = { - result: { - blockchains: resp - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: Blockchain[] = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(resp) - }) - - test("getSubnets 1", async (): Promise => { - const resp: object[] = [ - { - id: "id", - controlKeys: ["controlKeys"], - threshold: "threshold" - } - ] - const result: Promise = api.getSubnets() - const payload: object = { - result: { - subnets: resp - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: object = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toEqual(resp) - }) - - test("getCurrentValidators 1", async (): Promise => { - const validators: string[] = ["val1", "val2"] - const result: Promise = api.getCurrentValidators() - const payload: object = { - result: { - validators - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: object = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toStrictEqual({ validators }) - }) - - test("getCurrentValidators 2", async (): Promise => { - const subnetID: string = "abcdef" - const validators: string[] = ["val1", "val2"] - const result: Promise = api.getCurrentValidators(subnetID) - const payload: object = { - result: { - validators - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: object = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toStrictEqual({ validators }) - }) - - test("getCurrentValidators 3", async (): Promise => { - const subnetID: Buffer = Buffer.from("abcdef", "hex") - const validators: string[] = ["val1", "val2"] - const result: Promise = api.getCurrentValidators(subnetID) - const payload: object = { - result: { - validators - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: object = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toStrictEqual({ validators }) - }) - - test("exportKey", async (): Promise => { - const key: string = "sdfglvlj2h3v45" - - const result: Promise = api.exportKey( - username, - password, - addrA - ) - const payload: object = { - result: { - privateKey: key - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string | ErrorResponseObject = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(key) - }) - - test("exportAVAX", async (): Promise => { - const amount: BN = new BN(100) - const to: string = "abcdef" - const username: string = "Robert" - const password: string = "Paulson" - const txID: string = "valid" - const result: Promise = api.exportAVAX( - username, - password, - amount, - to - ) - const payload: object = { - result: { - txID: txID - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string | ErrorResponseObject = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(txID) - }) - - test("importAVAX", async (): Promise => { - const to: string = "abcdef" - const username: string = "Robert" - const password = "Paulson" - const txID = "valid" - const result: Promise = api.importAVAX( - username, - password, - to, - blockchainID - ) - const payload: object = { - result: { - txID: txID - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string | ErrorResponseObject = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(txID) - }) - - test("createBlockchain", async (): Promise => { - const blockchainID: string = "7sik3Pr6r1FeLrvK1oWwECBS8iJ5VPuSh" - const vmID: string = "7sik3Pr6r1FeLrvK1oWwECBS8iJ5VPuSh" - const name: string = "Some Blockchain" - const genesis: string = '{ruh:"roh"}' - const subnetID: Buffer = Buffer.from("abcdef", "hex") - const result: Promise = api.createBlockchain( - username, - password, - subnetID, - vmID, - [1, 2, 3], - name, - genesis - ) - const payload: object = { - result: { - txID: blockchainID - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string | ErrorResponseObject = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(blockchainID) - }) - - test("getBlockchainStatus", async (): Promise => { - const blockchainID: string = "7sik3Pr6r1FeLrvK1oWwECBS8iJ5VPuSh" - const result: Promise = api.getBlockchainStatus(blockchainID) - const payload: object = { - result: { - status: "Accepted" - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe("Accepted") - }) - - test("createAddress", async (): Promise => { - const alias: string = "randomalias" - - const result: Promise = api.createAddress(username, password) - const payload: object = { - result: { - address: alias - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(alias) - }) - - test("createSubnet 1", async (): Promise => { - const controlKeys: string[] = ["abcdef"] - const threshold: number = 13 - const utx: string = "valid" - const result: Promise = api.createSubnet( - username, - password, - controlKeys, - threshold - ) - const payload: object = { - result: { - txID: utx - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string | ErrorResponseObject = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(utx) - }) - - test("sampleValidators 1", async (): Promise => { - let subnetID - const validators: string[] = ["val1", "val2"] - const result: Promise = api.sampleValidators(10, subnetID) - const payload: object = { - result: { - validators - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string[] = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(validators) - }) - - test("sampleValidators 2", async (): Promise => { - const subnetID: string = "abcdef" - const validators: string[] = ["val1", "val2"] - const result: Promise = api.sampleValidators(10, subnetID) - const payload: object = { - result: { - validators - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string[] = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(validators) - }) - - test("sampleValidators 3", async (): Promise => { - const subnetID = Buffer.from("abcdef", "hex") - const validators: string[] = ["val1", "val2"] - const result: Promise = api.sampleValidators(10, subnetID) - const payload: object = { - result: { - validators - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string[] = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(validators) - }) - - test("validatedBy 1", async (): Promise => { - const blockchainID: string = "abcdef" - const resp: string = "valid" - const result: Promise = api.validatedBy(blockchainID) - const payload: object = { - result: { - subnetID: resp - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(resp) - }) - - test("validates 1", async (): Promise => { - let subnetID - const resp: string[] = ["valid"] - const result: Promise = api.validates(subnetID) - const payload: object = { - result: { - blockchainIDs: resp - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string[] = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(resp) - }) - - test("validates 2", async (): Promise => { - const subnetID: string = "deadbeef" - const resp: string[] = ["valid"] - const result: Promise = api.validates(subnetID) - const payload: object = { - result: { - blockchainIDs: resp - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string[] = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(resp) - }) - - test("validates 3", async (): Promise => { - const subnetID = Buffer.from("abcdef", "hex") - const resp: string[] = ["valid"] - const result: Promise = api.validates(subnetID) - const payload: object = { - result: { - blockchainIDs: resp - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string[] = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(resp) - }) - - test("getTx", async (): Promise => { - const txid: string = - "f966750f438867c3c9828ddcdbe660e21ccdbb36a9276958f011ba472f75d4e7" - - const result: Promise = api.getTx(txid) - const payload: object = { - result: { - tx: "sometx" - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string | object = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe("sometx") - }) - - test("getTxStatus", async (): Promise => { - const txid: string = - "f966750f438867c3c9828ddcdbe660e21ccdbb36a9276958f011ba472f75d4e7" - - const result: Promise = api.getTxStatus(txid) - const payload: object = { - result: "accepted" - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: string | GetTxStatusResponse = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe("accepted") - }) - - test("getUTXOs", async (): Promise => { - // Payment - const OPUTXOstr1: string = bintools.cb58Encode( - Buffer.from( - "000038d1b9f1138672da6fb6c35125539276a9acc2a668d63bea6ba3c795e2edb0f5000000013e07e38e2f23121be8756412c18db7246a16d26ee9936f3cba28be149cfd3558000000070000000000004dd500000000000000000000000100000001a36fd0c2dbcab311731dde7ef1514bd26fcdc74d", - "hex" - ) - ) - const OPUTXOstr2: string = bintools.cb58Encode( - Buffer.from( - "0000c3e4823571587fe2bdfc502689f5a8238b9d0ea7f3277124d16af9de0d2d9911000000003e07e38e2f23121be8756412c18db7246a16d26ee9936f3cba28be149cfd355800000007000000000000001900000000000000000000000100000001e1b6b6a4bad94d2e3f20730379b9bcd6f176318e", - "hex" - ) - ) - const OPUTXOstr3: string = bintools.cb58Encode( - Buffer.from( - "0000f29dba61fda8d57a911e7f8810f935bde810d3f8d495404685bdb8d9d8545e86000000003e07e38e2f23121be8756412c18db7246a16d26ee9936f3cba28be149cfd355800000007000000000000001900000000000000000000000100000001e1b6b6a4bad94d2e3f20730379b9bcd6f176318e", - "hex" - ) - ) - - const set: UTXOSet = new UTXOSet() - set.add(OPUTXOstr1) - set.addArray([OPUTXOstr2, OPUTXOstr3]) - - const persistOpts: PersistanceOptions = new PersistanceOptions( - "test", - true, - "union" - ) - expect(persistOpts.getMergeRule()).toBe("union") - let addresses: string[] = set - .getAddresses() - .map((a): string => api.addressFromBuffer(a)) - let result: Promise = api.getUTXOs( - addresses, - api.getBlockchainID(), - 0, - undefined, - persistOpts - ) - const payload: object = { - result: { - numFetched: 3, - utxos: [OPUTXOstr1, OPUTXOstr2, OPUTXOstr3], - stopIndex: { address: "a", utxo: "b" } - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - let response: UTXOSet = (await result).utxos - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(JSON.stringify(response.getAllUTXOStrings().sort())).toBe( - JSON.stringify(set.getAllUTXOStrings().sort()) - ) - - addresses = set.getAddresses().map((a) => api.addressFromBuffer(a)) - result = api.getUTXOs( - addresses, - api.getBlockchainID(), - 0, - undefined, - persistOpts - ) - - mockAxios.mockResponse(responseObj) - response = (await result).utxos - - expect(mockAxios.request).toHaveBeenCalledTimes(2) - expect(JSON.stringify(response.getAllUTXOStrings().sort())).toBe( - JSON.stringify(set.getAllUTXOStrings().sort()) - ) - }) - - describe("Transactions", (): void => { - let set: UTXOSet - let lset: UTXOSet - let keymgr2: KeyChain - let keymgr3: KeyChain - let addrs1: string[] - let addrs2: string[] - let addrs3: string[] - let addressbuffs: Buffer[] = [] - let addresses: string[] = [] - let utxos: UTXO[] - let lutxos: UTXO[] - let inputs: TransferableInput[] - let outputs: TransferableOutput[] - const amnt: number = 10000 - const assetID: Buffer = Buffer.from( - createHash("sha256").update("mary had a little lamb").digest() - ) - let secpbase1: SECPTransferOutput - let secpbase2: SECPTransferOutput - let secpbase3: SECPTransferOutput - let fungutxoids: string[] = [] - let platformvm: PlatformVMAPI - const fee: number = 10 - const name: string = "Mortycoin is the dumb as a sack of hammers." - const symbol: string = "morT" - const denomination: number = 8 - - beforeEach(async (): Promise => { - platformvm = new PlatformVMAPI(avalanche, "/ext/bc/P") - const result: Promise = platformvm.getAVAXAssetID() - const payload: object = { - result: { - name, - symbol, - assetID: bintools.cb58Encode(assetID), - denomination: `${denomination}` - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - await result - set = new UTXOSet() - lset = new UTXOSet() - platformvm.newKeyChain() - keymgr2 = new KeyChain(avalanche.getHRP(), alias) - keymgr3 = new KeyChain(avalanche.getHRP(), alias) - addrs1 = [] - addrs2 = [] - addrs3 = [] - utxos = [] - lutxos = [] - inputs = [] - outputs = [] - fungutxoids = [] - const pload: Buffer = Buffer.alloc(1024) - pload.write( - "All you Trekkies and TV addicts, Don't mean to diss don't mean to bring static.", - 0, - 1024, - "utf8" - ) - - for (let i: number = 0; i < 3; i++) { - addrs1.push( - platformvm.addressFromBuffer( - platformvm.keyChain().makeKey().getAddress() - ) - ) - addrs2.push( - platformvm.addressFromBuffer(keymgr2.makeKey().getAddress()) - ) - addrs3.push( - platformvm.addressFromBuffer(keymgr3.makeKey().getAddress()) - ) - } - const amount: BN = ONEAVAX.mul(new BN(amnt)) - addressbuffs = platformvm.keyChain().getAddresses() - addresses = addressbuffs.map((a) => platformvm.addressFromBuffer(a)) - const locktime: BN = new BN(54321) - const threshold: number = 3 - for (let i: number = 0; i < 5; i++) { - let txid: Buffer = Buffer.from( - createHash("sha256") - .update(bintools.fromBNToBuffer(new BN(i), 32)) - .digest() - ) - let txidx: Buffer = Buffer.alloc(4) - txidx.writeUInt32BE(i, 0) - - const out: SECPTransferOutput = new SECPTransferOutput( - amount, - addressbuffs, - locktime, - threshold - ) - const xferout: TransferableOutput = new TransferableOutput(assetID, out) - outputs.push(xferout) - - const u: UTXO = new UTXO() - u.fromBuffer( - Buffer.concat([u.getCodecIDBuffer(), txid, txidx, xferout.toBuffer()]) - ) - fungutxoids.push(u.getUTXOID()) - utxos.push(u) - - txid = u.getTxID() - txidx = u.getOutputIdx() - const asset = u.getAssetID() - - const input: SECPTransferInput = new SECPTransferInput(amount) - const xferinput: TransferableInput = new TransferableInput( - txid, - txidx, - asset, - input - ) - inputs.push(xferinput) - } - set.addArray(utxos) - for (let i: number = 0; i < 4; i++) { - let txid: Buffer = Buffer.from( - createHash("sha256") - .update(bintools.fromBNToBuffer(new BN(i), 32)) - .digest() - ) - let txidx: Buffer = Buffer.alloc(4) - txidx.writeUInt32BE(i, 0) - - const out: SECPTransferOutput = new SECPTransferOutput( - ONEAVAX.mul(new BN(5)), - addressbuffs, - locktime, - 1 - ) - const pout: ParseableOutput = new ParseableOutput(out) - const lockout: StakeableLockOut = new StakeableLockOut( - ONEAVAX.mul(new BN(5)), - addressbuffs, - locktime, - 1, - locktime.add(new BN(86400)), - pout - ) - const xferout: TransferableOutput = new TransferableOutput( - assetID, - lockout - ) - - const u: UTXO = new UTXO() - u.fromBuffer( - Buffer.concat([u.getCodecIDBuffer(), txid, txidx, xferout.toBuffer()]) - ) - lutxos.push(u) - } - - lset.addArray(lutxos) - lset.addArray(set.getAllUTXOs()) - - secpbase1 = new SECPTransferOutput( - new BN(777), - addrs3.map((a) => platformvm.parseAddress(a)), - UnixNow(), - 1 - ) - secpbase2 = new SECPTransferOutput( - new BN(888), - addrs2.map((a) => platformvm.parseAddress(a)), - UnixNow(), - 1 - ) - secpbase3 = new SECPTransferOutput( - new BN(999), - addrs2.map((a) => platformvm.parseAddress(a)), - UnixNow(), - 1 - ) - }) - - test("signTx", async (): Promise => { - const assetID: Buffer = await platformvm.getAVAXAssetID() - const txu2: UnsignedTx = set.buildBaseTx( - networkID, - bintools.cb58Decode(blockchainID), - new BN(amnt), - assetID, - addrs3.map((a): Buffer => platformvm.parseAddress(a)), - addrs1.map((a): Buffer => platformvm.parseAddress(a)), - addrs1.map((a): Buffer => platformvm.parseAddress(a)), - platformvm.getTxFee(), - assetID, - undefined, - UnixNow(), - new BN(0), - 1 - ) - - txu2.sign(platformvm.keyChain()) - }) - - test("buildImportTx", async (): Promise => { - const locktime: BN = new BN(0) - const threshold: number = 1 - platformvm.setTxFee(new BN(fee)) - const addrbuff1 = addrs1.map((a) => platformvm.parseAddress(a)) - const addrbuff2 = addrs2.map((a) => platformvm.parseAddress(a)) - const addrbuff3 = addrs3.map((a) => platformvm.parseAddress(a)) - const fungutxo: UTXO = set.getUTXO(fungutxoids[1]) - const fungutxostr: string = fungutxo.toString() - - const result: Promise = platformvm.buildImportTx( - set, - addrs1, - PlatformChainID, - addrs3, - addrs1, - addrs2, - new UTF8Payload("hello world"), - UnixNow(), - locktime, - threshold - ) - const payload: object = { - result: { - utxos: [fungutxostr] - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const txu1: UnsignedTx = await result - - const txu2: UnsignedTx = set.buildImportTx( - networkID, - bintools.cb58Decode(blockchainID), - addrbuff3, - addrbuff1, - addrbuff2, - [fungutxo], - bintools.cb58Decode(PlatformChainID), - platformvm.getTxFee(), - await platformvm.getAVAXAssetID(), - new UTF8Payload("hello world").getPayload(), - UnixNow(), - locktime, - threshold - ) - - expect(txu2.toBuffer().toString("hex")).toBe( - txu1.toBuffer().toString("hex") - ) - expect(txu2.toString()).toBe(txu1.toString()) - - const tx1: Tx = txu1.sign(platformvm.keyChain()) - const checkTx: string = tx1.toBuffer().toString("hex") - const tx1obj: object = tx1.serialize("hex") - const tx1str: string = JSON.stringify(tx1obj) - - const tx2newobj: object = JSON.parse(tx1str) - const tx2: Tx = new Tx() - tx2.deserialize(tx2newobj, "hex") - - expect(tx2.toBuffer().toString("hex")).toBe(checkTx) - - const tx3: Tx = txu1.sign(platformvm.keyChain()) - const tx3obj: object = tx3.serialize(display) - const tx3str: string = JSON.stringify(tx3obj) - - const tx4newobj: object = JSON.parse(tx3str) - const tx4: Tx = new Tx() - tx4.deserialize(tx4newobj, display) - - expect(tx4.toBuffer().toString("hex")).toBe(checkTx) - - serialzeit(tx1, "ImportTx") - }) - - test("buildExportTx", async (): Promise => { - platformvm.setTxFee(new BN(fee)) - const addrbuff1 = addrs1.map((a) => platformvm.parseAddress(a)) - const addrbuff2 = addrs2.map((a) => platformvm.parseAddress(a)) - const addrbuff3 = addrs3.map((a) => platformvm.parseAddress(a)) - const amount: BN = new BN(90) - const type: SerializedType = "bech32" - const txu1: UnsignedTx = await platformvm.buildExportTx( - set, - amount, - bintools.cb58Decode( - Defaults.network[avalanche.getNetworkID()].X["blockchainID"] - ), - addrbuff3.map((a) => - serializer.bufferToType(a, type, avalanche.getHRP(), "P") - ), - addrs1, - addrs2, - new UTF8Payload("hello world"), - UnixNow() - ) - - const txu2: UnsignedTx = set.buildExportTx( - networkID, - bintools.cb58Decode(blockchainID), - amount, - assetID, - addrbuff3, - addrbuff1, - addrbuff2, - bintools.cb58Decode( - Defaults.network[avalanche.getNetworkID()].X["blockchainID"] - ), - platformvm.getTxFee(), - assetID, - new UTF8Payload("hello world").getPayload(), - UnixNow() - ) - - expect(txu2.toBuffer().toString("hex")).toBe( - txu1.toBuffer().toString("hex") - ) - expect(txu2.toString()).toBe(txu1.toString()) - - const txu3: UnsignedTx = await platformvm.buildExportTx( - set, - amount, - bintools.cb58Decode( - Defaults.network[avalanche.getNetworkID()].X["blockchainID"] - ), - addrs3, - addrs1, - addrs2, - new UTF8Payload("hello world"), - UnixNow() - ) - - const txu4: UnsignedTx = set.buildExportTx( - networkID, - bintools.cb58Decode(blockchainID), - amount, - assetID, - addrbuff3, - addrbuff1, - addrbuff2, - undefined, - platformvm.getTxFee(), - assetID, - new UTF8Payload("hello world").getPayload(), - UnixNow() - ) - - expect(txu4.toBuffer().toString("hex")).toBe( - txu3.toBuffer().toString("hex") - ) - expect(txu4.toString()).toBe(txu3.toString()) - - expect(txu2.toBuffer().toString("hex")).toBe( - txu1.toBuffer().toString("hex") - ) - expect(txu2.toString()).toBe(txu1.toString()) - - const tx1: Tx = txu1.sign(platformvm.keyChain()) - const checkTx: string = tx1.toBuffer().toString("hex") - const tx1obj: object = tx1.serialize("hex") - const tx1str: string = JSON.stringify(tx1obj) - - const tx2newobj: object = JSON.parse(tx1str) - const tx2: Tx = new Tx() - tx2.deserialize(tx2newobj, "hex") - - expect(tx2.toBuffer().toString("hex")).toBe(checkTx) - - const tx3: Tx = txu1.sign(platformvm.keyChain()) - const tx3obj: object = tx3.serialize(display) - const tx3str: string = JSON.stringify(tx3obj) - - const tx4newobj: object = JSON.parse(tx3str) - const tx4: Tx = new Tx() - tx4.deserialize(tx4newobj, display) - - expect(tx4.toBuffer().toString("hex")).toBe(checkTx) - - serialzeit(tx1, "ExportTx") - }) - /* - test('buildAddSubnetValidatorTx', async (): Promise => { - platformvm.setFee(new BN(fee)); - const addrbuff1 = addrs1.map((a) => platformvm.parseAddress(a)); - const addrbuff2 = addrs2.map((a) => platformvm.parseAddress(a)); - const addrbuff3 = addrs3.map((a) => platformvm.parseAddress(a)); - const amount:BN = new BN(90); - - const txu1:UnsignedTx = await platformvm.buildAddSubnetValidatorTx( - set, - addrs1, - addrs2, - nodeID, - startTime, - endTime, - PlatformVMConstants.MINSTAKE, - new UTF8Payload("hello world"), UnixNow() - ); - - const txu2:UnsignedTx = set.buildAddSubnetValidatorTx( - networkID, bintools.cb58Decode(blockchainID), - addrbuff1, - addrbuff2, - NodeIDStringToBuffer(nodeID), - startTime, - endTime, - PlatformVMConstants.MINSTAKE, - platformvm.getFee(), - assetID, - new UTF8Payload("hello world").getPayload(), UnixNow() - ); - expect(txu2.toBuffer().toString('hex')).toBe(txu1.toBuffer().toString('hex')); - expect(txu2.toString()).toBe(txu1.toString()); - - }); - */ - test("buildAddDelegatorTx 1", async (): Promise => { - const addrbuff1 = addrs1.map((a) => platformvm.parseAddress(a)) - const addrbuff2 = addrs2.map((a) => platformvm.parseAddress(a)) - const addrbuff3 = addrs3.map((a) => platformvm.parseAddress(a)) - const amount: BN = Defaults.network[networkID]["P"].minDelegationStake - - const locktime: BN = new BN(54321) - const threshold: number = 2 - - platformvm.setMinStake( - Defaults.network[networkID]["P"].minStake, - Defaults.network[networkID]["P"].minDelegationStake - ) - - const txu1: UnsignedTx = await platformvm.buildAddDelegatorTx( - set, - addrs3, - addrs1, - addrs2, - nodeID, - startTime, - endTime, - amount, - addrs3, - locktime, - threshold, - new UTF8Payload("hello world"), - UnixNow() - ) - - const txu2: UnsignedTx = set.buildAddDelegatorTx( - networkID, - bintools.cb58Decode(blockchainID), - assetID, - addrbuff3, - addrbuff1, - addrbuff2, - NodeIDStringToBuffer(nodeID), - startTime, - endTime, - amount, - locktime, - threshold, - addrbuff3, - new BN(0), - assetID, - new UTF8Payload("hello world").getPayload(), - UnixNow() - ) - expect(txu2.toBuffer().toString("hex")).toBe( - txu1.toBuffer().toString("hex") - ) - expect(txu2.toString()).toBe(txu1.toString()) - - const tx1: Tx = txu1.sign(platformvm.keyChain()) - const checkTx: string = tx1.toBuffer().toString("hex") - const tx1obj: object = tx1.serialize("hex") - const tx1str: string = JSON.stringify(tx1obj) - - const tx2newobj: object = JSON.parse(tx1str) - const tx2: Tx = new Tx() - tx2.deserialize(tx2newobj, "hex") - - expect(tx2.toBuffer().toString("hex")).toBe(checkTx) - - const tx3: Tx = txu1.sign(platformvm.keyChain()) - const tx3obj: object = tx3.serialize(display) - const tx3str: string = JSON.stringify(tx3obj) - - const tx4newobj: object = JSON.parse(tx3str) - const tx4: Tx = new Tx() - tx4.deserialize(tx4newobj, display) - - expect(tx4.toBuffer().toString("hex")).toBe(checkTx) - - serialzeit(tx1, "AddDelegatorTx") - }) - - test("buildAddValidatorTx sort StakeableLockOuts 1", async (): Promise => { - // two UTXO. The 1st has a lesser stakeablelocktime and a greater amount of AVAX. The 2nd has a greater stakeablelocktime and a lesser amount of AVAX. - // We expect this test to only consume the 2nd UTXO since it has the greater locktime. - const addrbuff1: Buffer[] = addrs1.map((a) => platformvm.parseAddress(a)) - const amount1: BN = new BN("20000000000000000") - const amount2: BN = new BN("10000000000000000") - const locktime1: BN = new BN(0) - const threshold: number = 1 - - const stakeableLockTime1: BN = new BN(1633824000) - const secpTransferOutput1: SECPTransferOutput = new SECPTransferOutput( - amount1, - addrbuff1, - locktime1, - threshold - ) - const parseableOutput1: ParseableOutput = new ParseableOutput( - secpTransferOutput1 - ) - const stakeableLockOut1: StakeableLockOut = new StakeableLockOut( - amount1, - addrbuff1, - locktime1, - threshold, - stakeableLockTime1, - parseableOutput1 - ) - const stakeableLockTime2: BN = new BN(1733824000) - const secpTransferOutput2: SECPTransferOutput = new SECPTransferOutput( - amount2, - addrbuff1, - locktime1, - threshold - ) - const parseableOutput2: ParseableOutput = new ParseableOutput( - secpTransferOutput2 - ) - const stakeableLockOut2: StakeableLockOut = new StakeableLockOut( - amount2, - addrbuff1, - locktime1, - threshold, - stakeableLockTime2, - parseableOutput2 - ) - const nodeID: string = "NodeID-36giFye5epwBTpGqPk7b4CCYe3hfyoFr1" - const stakeAmount: BN = Defaults.network[networkID]["P"].minStake - platformvm.setMinStake( - stakeAmount, - Defaults.network[networkID]["P"].minDelegationStake - ) - const delegationFeeRate: number = new BN(2).toNumber() - const codecID: number = 0 - const txid: Buffer = bintools.cb58Decode( - "auhMFs24ffc2BRWKw6i7Qngcs8jSQUS9Ei2XwJsUpEq4sTVib" - ) - const txid2: Buffer = bintools.cb58Decode( - "2JwDfm3C7p88rJQ1Y1xWLkWNMA1nqPzqnaC2Hi4PDNKiPnXgGv" - ) - const outputidx0: number = 0 - const outputidx1: number = 0 - const assetID = await platformvm.getAVAXAssetID() - const assetID2 = await platformvm.getAVAXAssetID() - const utxo1: UTXO = new UTXO( - codecID, - txid, - outputidx0, - assetID, - stakeableLockOut1 - ) - const utxo2: UTXO = new UTXO( - codecID, - txid2, - outputidx1, - assetID2, - stakeableLockOut2 - ) - const utxoSet: UTXOSet = new UTXOSet() - utxoSet.add(utxo1) - utxoSet.add(utxo2) - const txu1: UnsignedTx = await platformvm.buildAddValidatorTx( - utxoSet, - addrs3, - addrs1, - addrs2, - nodeID, - startTime, - endTime, - stakeAmount, - addrs3, - delegationFeeRate - ) - const tx = txu1.getTransaction() as AddValidatorTx - const ins: TransferableInput[] = tx.getIns() - // start test inputs - // confirm only 1 input - expect(ins.length).toBe(1) - const input: TransferableInput = ins[0] - const ai = input.getInput() as AmountInput - const ao = stakeableLockOut2 - .getTransferableOutput() - .getOutput() as AmountOutput - const ao2 = stakeableLockOut1 - .getTransferableOutput() - .getOutput() as AmountOutput - // confirm input amount matches the output w/ the greater staekablelock time but lesser amount - expect(ai.getAmount().toString()).toEqual(ao.getAmount().toString()) - // confirm input amount doesn't match the output w/ the lesser staekablelock time but greater amount - expect(ai.getAmount().toString()).not.toEqual(ao2.getAmount().toString()) - - const sli: StakeableLockIn = input.getInput() as StakeableLockIn - // confirm input stakeablelock time matches the output w/ the greater stakeablelock time but lesser amount - expect(sli.getStakeableLocktime().toString()).toEqual( - stakeableLockOut2.getStakeableLocktime().toString() - ) - // confirm input stakeablelock time doesn't match the output w/ the lesser stakeablelock time but greater amount - expect(sli.getStakeableLocktime().toString()).not.toEqual( - stakeableLockOut1.getStakeableLocktime().toString() - ) - // stop test inputs - - // start test outputs - const outs: TransferableOutput[] = tx.getOuts() - // confirm only 1 output - expect(outs.length).toBe(1) - const output: TransferableOutput = outs[0] - const ao3 = output.getOutput() as AmountOutput - // confirm output amount matches the output w/ the greater stakeablelock time but lesser amount sans the stake amount - expect(ao3.getAmount().toString()).toEqual( - ao.getAmount().sub(stakeAmount).toString() - ) - // confirm output amount doesn't match the output w/ the lesser stakeablelock time but greater amount - expect(ao3.getAmount().toString()).not.toEqual(ao2.getAmount().toString()) - - const slo: StakeableLockOut = output.getOutput() as StakeableLockOut - // confirm output stakeablelock time matches the output w/ the greater stakeablelock time but lesser amount - expect(slo.getStakeableLocktime().toString()).toEqual( - stakeableLockOut2.getStakeableLocktime().toString() - ) - // confirm output stakeablelock time doesn't match the output w/ the greater stakeablelock time but lesser amount - expect(slo.getStakeableLocktime().toString()).not.toEqual( - stakeableLockOut1.getStakeableLocktime().toString() - ) - - // confirm tx nodeID matches nodeID - expect(tx.getNodeIDString()).toEqual(nodeID) - // confirm tx starttime matches starttime - expect(tx.getStartTime().toString()).toEqual(startTime.toString()) - // confirm tx endtime matches endtime - expect(tx.getEndTime().toString()).toEqual(endTime.toString()) - // confirm tx stake amount matches stakeAmount - expect(tx.getStakeAmount().toString()).toEqual(stakeAmount.toString()) - - const stakeOuts: TransferableOutput[] = tx.getStakeOuts() - // confirm only 1 stakeOut - expect(stakeOuts.length).toBe(1) - - const stakeOut: TransferableOutput = stakeOuts[0] - const slo2 = stakeOut.getOutput() as StakeableLockOut - // confirm stakeOut stakeablelock time matches the output w/ the greater stakeablelock time but lesser amount - expect(slo2.getStakeableLocktime().toString()).toEqual( - stakeableLockOut2.getStakeableLocktime().toString() - ) - // confirm stakeOut stakeablelock time doesn't match the output w/ the greater stakeablelock time but lesser amount - expect(slo2.getStakeableLocktime().toString()).not.toEqual( - stakeableLockOut1.getStakeableLocktime().toString() - ) - slo2.getAmount() - // confirm stakeOut stake amount matches stakeAmount - expect(slo2.getAmount().toString()).toEqual(stakeAmount.toString()) - }) - - test("buildAddValidatorTx sort StakeableLockOuts 2", async (): Promise => { - // TODO - debug test - // two UTXO. The 1st has a lesser stakeablelocktime and a greater amount of AVAX. The 2nd has a greater stakeablelocktime and a lesser amount of AVAX. - // this time we're staking a greater amount than is available in the 2nd UTXO. - // We expect this test to consume the full 2nd UTXO and a fraction of the 1st UTXO.. - const addrbuff1: Buffer[] = addrs1.map( - (a): Buffer => platformvm.parseAddress(a) - ) - const amount1: BN = new BN("20000000000000000") - const amount2: BN = new BN("10000000000000000") - const locktime1: BN = new BN(0) - const threshold: number = 1 - - const stakeableLockTime1: BN = new BN(1633824000) - const secpTransferOutput1: SECPTransferOutput = new SECPTransferOutput( - amount1, - addrbuff1, - locktime1, - threshold - ) - const parseableOutput1: ParseableOutput = new ParseableOutput( - secpTransferOutput1 - ) - const stakeableLockOut1: StakeableLockOut = new StakeableLockOut( - amount1, - addrbuff1, - locktime1, - threshold, - stakeableLockTime1, - parseableOutput1 - ) - const stakeableLockTime2: BN = new BN(1733824000) - const secpTransferOutput2: SECPTransferOutput = new SECPTransferOutput( - amount2, - addrbuff1, - locktime1, - threshold - ) - const parseableOutput2: ParseableOutput = new ParseableOutput( - secpTransferOutput2 - ) - const stakeableLockOut2: StakeableLockOut = new StakeableLockOut( - amount2, - addrbuff1, - locktime1, - threshold, - stakeableLockTime2, - parseableOutput2 - ) - const nodeID: string = "NodeID-36giFye5epwBTpGqPk7b4CCYe3hfyoFr1" - const stakeAmount: BN = new BN("10000003000000000") - platformvm.setMinStake( - stakeAmount, - Defaults.network[networkID]["P"].minDelegationStake - ) - const delegationFeeRate: number = new BN(2).toNumber() - const codecID: number = 0 - const txid: Buffer = bintools.cb58Decode( - "auhMFs24ffc2BRWKw6i7Qngcs8jSQUS9Ei2XwJsUpEq4sTVib" - ) - const txid2: Buffer = bintools.cb58Decode( - "2JwDfm3C7p88rJQ1Y1xWLkWNMA1nqPzqnaC2Hi4PDNKiPnXgGv" - ) - const outputidx0: number = 0 - const outputidx1: number = 0 - const assetID: Buffer = await platformvm.getAVAXAssetID() - const assetID2: Buffer = await platformvm.getAVAXAssetID() - const utxo1: UTXO = new UTXO( - codecID, - txid, - outputidx0, - assetID, - stakeableLockOut1 - ) - const utxo2: UTXO = new UTXO( - codecID, - txid2, - outputidx1, - assetID2, - stakeableLockOut2 - ) - const utxoSet: UTXOSet = new UTXOSet() - utxoSet.add(utxo1) - utxoSet.add(utxo2) - const txu1: UnsignedTx = await platformvm.buildAddValidatorTx( - utxoSet, - addrs3, - addrs1, - addrs2, - nodeID, - startTime, - endTime, - stakeAmount, - addrs3, - delegationFeeRate - ) - const tx = txu1.getTransaction() as AddValidatorTx - const ins: TransferableInput[] = tx.getIns() - // start test inputs - // confirm only 1 input - expect(ins.length).toBe(2) - const input1: TransferableInput = ins[0] - const input2: TransferableInput = ins[1] - const ai1 = input1.getInput() as AmountInput - const ai2 = input2.getInput() as AmountInput - const ao1 = stakeableLockOut2 - .getTransferableOutput() - .getOutput() as AmountOutput - const ao2 = stakeableLockOut1 - .getTransferableOutput() - .getOutput() as AmountOutput - // confirm each input amount matches the corresponding output - expect(ai2.getAmount().toString()).toEqual(ao1.getAmount().toString()) - expect(ai1.getAmount().toString()).toEqual(ao2.getAmount().toString()) - - const sli1 = input1.getInput() as StakeableLockIn - const sli2 = input2.getInput() as StakeableLockIn - // confirm input strakeablelock time matches the output w/ the greater staekablelock time but lesser amount - // expect(sli1.getStakeableLocktime().toString()).toEqual( - // stakeableLockOut1.getStakeableLocktime().toString() - // ) - expect(sli2.getStakeableLocktime().toString()).toEqual( - stakeableLockOut2.getStakeableLocktime().toString() - ) - // stop test inputs - - // start test outputs - const outs: TransferableOutput[] = tx.getOuts() - // confirm only 1 output - expect(outs.length).toBe(1) - const output: TransferableOutput = outs[0] - const ao3 = output.getOutput() as AmountOutput - // confirm output amount matches the output amount sans the 2nd utxo amount and the stake amount - expect(ao3.getAmount().toString()).toEqual( - ao2.getAmount().sub(stakeAmount.sub(ao1.getAmount())).toString() - ) - - const slo = output.getOutput() as StakeableLockOut - // confirm output stakeablelock time matches the output w/ the lesser stakeablelock since the other was consumed - // expect(slo.getStakeableLocktime().toString()).toEqual( - // stakeableLockOut1.getStakeableLocktime().toString() - // ) - // confirm output stakeablelock time doesn't match the output w/ the greater stakeablelock time - // expect(slo.getStakeableLocktime().toString()).not.toEqual( - // stakeableLockOut2.getStakeableLocktime().toString() - // ) - - // confirm tx nodeID matches nodeID - expect(tx.getNodeIDString()).toEqual(nodeID) - // confirm tx starttime matches starttime - expect(tx.getStartTime().toString()).toEqual(startTime.toString()) - // confirm tx endtime matches endtime - expect(tx.getEndTime().toString()).toEqual(endTime.toString()) - // confirm tx stake amount matches stakeAmount - expect(tx.getStakeAmount().toString()).toEqual(stakeAmount.toString()) - - let stakeOuts: TransferableOutput[] = tx.getStakeOuts() - // confirm 2 stakeOuts - expect(stakeOuts.length).toBe(2) - - let stakeOut1: TransferableOutput = stakeOuts[0] - let stakeOut2: TransferableOutput = stakeOuts[1] - let slo2 = stakeOut1.getOutput() as StakeableLockOut - let slo3 = stakeOut2.getOutput() as StakeableLockOut - // confirm both stakeOut strakeablelock times matche the corresponding output - // expect(slo3.getStakeableLocktime().toString()).toEqual( - // stakeableLockOut1.getStakeableLocktime().toString() - // ) - expect(slo2.getStakeableLocktime().toString()).toEqual( - stakeableLockOut2.getStakeableLocktime().toString() - ) - }) - - test("buildAddValidatorTx sort StakeableLockOuts 3", async (): Promise => { - // TODO - debug test - // three UTXO. - // The 1st is a SecpTransferableOutput. - // The 2nd has a lesser stakeablelocktime and a greater amount of AVAX. - // The 3rd has a greater stakeablelocktime and a lesser amount of AVAX. - // - // this time we're staking a greater amount than is available in the 3rd UTXO. - // We expect this test to consume the full 3rd UTXO and a fraction of the 2nd UTXO and not to consume the SecpTransferableOutput - const addrbuff1: Buffer[] = addrs1.map((a) => platformvm.parseAddress(a)) - const amount1: BN = new BN("20000000000000000") - const amount2: BN = new BN("10000000000000000") - const locktime1: BN = new BN(0) - const threshold: number = 1 - - const stakeableLockTime1: BN = new BN(1633824000) - const secpTransferOutput0: SECPTransferOutput = new SECPTransferOutput( - amount1, - addrbuff1, - locktime1, - threshold - ) - const secpTransferOutput1: SECPTransferOutput = new SECPTransferOutput( - amount1, - addrbuff1, - locktime1, - threshold - ) - const parseableOutput1: ParseableOutput = new ParseableOutput( - secpTransferOutput1 - ) - const stakeableLockOut1: StakeableLockOut = new StakeableLockOut( - amount1, - addrbuff1, - locktime1, - threshold, - stakeableLockTime1, - parseableOutput1 - ) - const stakeableLockTime2: BN = new BN(1733824000) - const secpTransferOutput2: SECPTransferOutput = new SECPTransferOutput( - amount2, - addrbuff1, - locktime1, - threshold - ) - const parseableOutput2: ParseableOutput = new ParseableOutput( - secpTransferOutput2 - ) - const stakeableLockOut2: StakeableLockOut = new StakeableLockOut( - amount2, - addrbuff1, - locktime1, - threshold, - stakeableLockTime2, - parseableOutput2 - ) - const nodeID: string = "NodeID-36giFye5epwBTpGqPk7b4CCYe3hfyoFr1" - const stakeAmount: BN = new BN("10000003000000000") - platformvm.setMinStake( - stakeAmount, - Defaults.network[networkID]["P"].minDelegationStake - ) - const delegationFeeRate: number = new BN(2).toNumber() - const codecID: number = 0 - const txid0: Buffer = bintools.cb58Decode( - "auhMFs24ffc2BRWKw6i7Qngcs8jSQUS9Ei2XwJsUpEq4sTVib" - ) - const txid1: Buffer = bintools.cb58Decode( - "2jhyJit8kWA6SwkRwKxXepFnfhs971CEqaGkjJmiADM8H4g2LR" - ) - const txid2: Buffer = bintools.cb58Decode( - "2JwDfm3C7p88rJQ1Y1xWLkWNMA1nqPzqnaC2Hi4PDNKiPnXgGv" - ) - const outputidx0: number = 0 - const outputidx1: number = 0 - const assetID: Buffer = await platformvm.getAVAXAssetID() - const assetID2: Buffer = await platformvm.getAVAXAssetID() - const utxo0: UTXO = new UTXO( - codecID, - txid0, - outputidx0, - assetID, - secpTransferOutput0 - ) - const utxo1: UTXO = new UTXO( - codecID, - txid1, - outputidx0, - assetID, - stakeableLockOut1 - ) - const utxo2: UTXO = new UTXO( - codecID, - txid2, - outputidx1, - assetID2, - stakeableLockOut2 - ) - const utxoSet: UTXOSet = new UTXOSet() - utxoSet.add(utxo0) - utxoSet.add(utxo1) - utxoSet.add(utxo2) - const txu1: UnsignedTx = await platformvm.buildAddValidatorTx( - utxoSet, - addrs3, - addrs1, - addrs2, - nodeID, - startTime, - endTime, - stakeAmount, - addrs3, - delegationFeeRate - ) - const tx = txu1.getTransaction() as AddValidatorTx - const ins: TransferableInput[] = tx.getIns() - // start test inputs - // confirm only 1 input - expect(ins.length).toBe(2) - const input1: TransferableInput = ins[0] - const input2: TransferableInput = ins[1] - const ai1 = input1.getInput() as AmountInput - const ai2 = input2.getInput() as AmountInput - const ao1 = stakeableLockOut2 - .getTransferableOutput() - .getOutput() as AmountOutput - const ao2 = stakeableLockOut1 - .getTransferableOutput() - .getOutput() as AmountOutput - // confirm each input amount matches the corresponding output - expect(ai2.getAmount().toString()).toEqual(ao2.getAmount().toString()) - expect(ai1.getAmount().toString()).toEqual(ao1.getAmount().toString()) - - const sli1 = input1.getInput() as StakeableLockIn - const sli2 = input2.getInput() as StakeableLockIn - // confirm input strakeablelock time matches the output w/ the greater staekablelock time but lesser amount - expect(sli1.getStakeableLocktime().toString()).toEqual( - stakeableLockOut2.getStakeableLocktime().toString() - ) - // expect(sli2.getStakeableLocktime().toString()).toEqual( - // stakeableLockOut1.getStakeableLocktime().toString() - // ) - // stop test inputs - - // start test outputs - const outs: TransferableOutput[] = tx.getOuts() - // confirm only 1 output - expect(outs.length).toBe(1) - const output: TransferableOutput = outs[0] - const ao3 = output.getOutput() as AmountOutput - // confirm output amount matches the output amount sans the 2nd utxo amount and the stake amount - expect(ao3.getAmount().toString()).toEqual( - ao2.getAmount().sub(stakeAmount.sub(ao1.getAmount())).toString() - ) - - const slo = output.getOutput() as StakeableLockOut - // confirm output stakeablelock time matches the output w/ the lesser stakeablelock since the other was consumed - // expect(slo.getStakeableLocktime().toString()).toEqual( - // stakeableLockOut1.getStakeableLocktime().toString() - // ) - // confirm output stakeablelock time doesn't match the output w/ the greater stakeablelock time - // expect(slo.getStakeableLocktime().toString()).not.toEqual( - // stakeableLockOut2.getStakeableLocktime().toString() - // ) - - // confirm tx nodeID matches nodeID - expect(tx.getNodeIDString()).toEqual(nodeID) - // confirm tx starttime matches starttime - expect(tx.getStartTime().toString()).toEqual(startTime.toString()) - // confirm tx endtime matches endtime - expect(tx.getEndTime().toString()).toEqual(endTime.toString()) - // confirm tx stake amount matches stakeAmount - expect(tx.getStakeAmount().toString()).toEqual(stakeAmount.toString()) - - const stakeOuts: TransferableOutput[] = tx.getStakeOuts() - // confirm 2 stakeOuts - expect(stakeOuts.length).toBe(2) - - const stakeOut1: TransferableOutput = stakeOuts[0] - const stakeOut2: TransferableOutput = stakeOuts[1] - const slo2 = stakeOut1.getOutput() as StakeableLockOut - const slo3 = stakeOut2.getOutput() as StakeableLockOut - // confirm both stakeOut strakeablelock times matche the corresponding output - // expect(slo3.getStakeableLocktime().toString()).toEqual( - // stakeableLockOut1.getStakeableLocktime().toString() - // ) - expect(slo2.getStakeableLocktime().toString()).toEqual( - stakeableLockOut2.getStakeableLocktime().toString() - ) - }) - - test("buildAddValidatorTx 1", async (): Promise => { - const addrbuff1 = addrs1.map((a) => platformvm.parseAddress(a)) - const addrbuff2 = addrs2.map((a) => platformvm.parseAddress(a)) - const addrbuff3 = addrs3.map((a) => platformvm.parseAddress(a)) - const amount: BN = Defaults.network[networkID]["P"].minStake.add( - new BN(fee) - ) - - const locktime: BN = new BN(54321) - const threshold: number = 2 - - platformvm.setMinStake( - Defaults.network[networkID]["P"].minStake, - Defaults.network[networkID]["P"].minDelegationStake - ) - - const txu1: UnsignedTx = await platformvm.buildAddValidatorTx( - set, - addrs3, - addrs1, - addrs2, - nodeID, - startTime, - endTime, - amount, - addrs3, - 0.1334556, - locktime, - threshold, - new UTF8Payload("hello world"), - UnixNow() - ) - - const txu2: UnsignedTx = set.buildAddValidatorTx( - networkID, - bintools.cb58Decode(blockchainID), - assetID, - addrbuff3, - addrbuff1, - addrbuff2, - NodeIDStringToBuffer(nodeID), - startTime, - endTime, - amount, - locktime, - threshold, - addrbuff3, - 0.1335, - new BN(0), - assetID, - new UTF8Payload("hello world").getPayload(), - UnixNow() - ) - expect(txu2.toBuffer().toString("hex")).toBe( - txu1.toBuffer().toString("hex") - ) - expect(txu2.toString()).toBe(txu1.toString()) - - const tx1: Tx = txu1.sign(platformvm.keyChain()) - const checkTx: string = tx1.toBuffer().toString("hex") - const tx1obj: object = tx1.serialize("hex") - const tx1str: string = JSON.stringify(tx1obj) - - const tx2newobj: object = JSON.parse(tx1str) - const tx2: Tx = new Tx() - tx2.deserialize(tx2newobj, "hex") - - expect(tx2.toBuffer().toString("hex")).toBe(checkTx) - - const tx3: Tx = txu1.sign(platformvm.keyChain()) - const tx3obj: object = tx3.serialize(display) - const tx3str: string = JSON.stringify(tx3obj) - - const tx4newobj: object = JSON.parse(tx3str) - const tx4: Tx = new Tx() - tx4.deserialize(tx4newobj, display) - - expect(tx4.toBuffer().toString("hex")).toBe(checkTx) - - serialzeit(tx1, "AddValidatorTx") - }) - - test("buildAddDelegatorTx 2", async (): Promise => { - const addrbuff1 = addrs1.map((a) => platformvm.parseAddress(a)) - const addrbuff2 = addrs2.map((a) => platformvm.parseAddress(a)) - const addrbuff3 = addrs3.map((a) => platformvm.parseAddress(a)) - const amount: BN = Defaults.network[networkID]["P"].minDelegationStake - const locktime: BN = new BN(54321) - const threshold: number = 2 - - platformvm.setMinStake( - Defaults.network[networkID]["P"].minStake, - Defaults.network[networkID]["P"].minDelegationStake - ) - - const txu1: UnsignedTx = await platformvm.buildAddDelegatorTx( - lset, - addrs3, - addrs1, - addrs2, - nodeID, - startTime, - endTime, - amount, - addrs3, - locktime, - threshold, - new UTF8Payload("hello world"), - UnixNow() - ) - - const txu2: UnsignedTx = lset.buildAddDelegatorTx( - networkID, - bintools.cb58Decode(blockchainID), - assetID, - addrbuff3, - addrbuff1, - addrbuff2, - NodeIDStringToBuffer(nodeID), - startTime, - endTime, - amount, - locktime, - threshold, - addrbuff3, - new BN(0), - assetID, - new UTF8Payload("hello world").getPayload(), - UnixNow() - ) - expect(txu2.toBuffer().toString("hex")).toBe( - txu1.toBuffer().toString("hex") - ) - expect(txu2.toString()).toBe(txu1.toString()) - - const tx1: Tx = txu1.sign(platformvm.keyChain()) - const checkTx: string = tx1.toBuffer().toString("hex") - const tx1obj: object = tx1.serialize("hex") - const tx1str: string = JSON.stringify(tx1obj) - - const tx2newobj: object = JSON.parse(tx1str) - const tx2: Tx = new Tx() - tx2.deserialize(tx2newobj, "hex") - - expect(tx2.toBuffer().toString("hex")).toBe(checkTx) - - const tx3: Tx = txu1.sign(platformvm.keyChain()) - const tx3obj: object = tx3.serialize(display) - const tx3str: string = JSON.stringify(tx3obj) - - const tx4newobj: object = JSON.parse(tx3str) - const tx4: Tx = new Tx() - tx4.deserialize(tx4newobj, display) - - expect(tx4.toBuffer().toString("hex")).toBe(checkTx) - - serialzeit(tx1, "AddDelegatorTx") - }) - - test("buildAddValidatorTx 2", async (): Promise => { - const addrbuff1 = addrs1.map((a) => platformvm.parseAddress(a)) - const addrbuff2 = addrs2.map((a) => platformvm.parseAddress(a)) - const addrbuff3 = addrs3.map((a) => platformvm.parseAddress(a)) - const amount: BN = ONEAVAX.mul(new BN(25)) - - const locktime: BN = new BN(54321) - const threshold: number = 2 - - platformvm.setMinStake(ONEAVAX.mul(new BN(25)), ONEAVAX.mul(new BN(25))) - - const txu1: UnsignedTx = await platformvm.buildAddValidatorTx( - lset, - addrs3, - addrs1, - addrs2, - nodeID, - startTime, - endTime, - amount, - addrs3, - 0.1334556, - locktime, - threshold, - new UTF8Payload("hello world"), - UnixNow() - ) - - const txu2: UnsignedTx = lset.buildAddValidatorTx( - networkID, - bintools.cb58Decode(blockchainID), - assetID, - addrbuff3, - addrbuff1, - addrbuff2, - NodeIDStringToBuffer(nodeID), - startTime, - endTime, - amount, - locktime, - threshold, - addrbuff3, - 0.1335, - new BN(0), - assetID, - new UTF8Payload("hello world").getPayload(), - UnixNow() - ) - expect(txu2.toBuffer().toString("hex")).toBe( - txu1.toBuffer().toString("hex") - ) - expect(txu2.toString()).toBe(txu1.toString()) - - const tx1: Tx = txu1.sign(platformvm.keyChain()) - const checkTx: string = tx1.toBuffer().toString("hex") - const tx1obj: object = tx1.serialize("hex") - const tx1str: string = JSON.stringify(tx1obj) - - const tx2newobj: object = JSON.parse(tx1str) - const tx2: Tx = new Tx() - tx2.deserialize(tx2newobj, "hex") - - expect(tx2.toBuffer().toString("hex")).toBe(checkTx) - - const tx3: Tx = txu1.sign(platformvm.keyChain()) - const tx3obj: object = tx3.serialize(display) - const tx3str: string = JSON.stringify(tx3obj) - - const tx4newobj: object = JSON.parse(tx3str) - const tx4: Tx = new Tx() - tx4.deserialize(tx4newobj, display) - - expect(tx4.toBuffer().toString("hex")).toBe(checkTx) - - serialzeit(tx1, "AddValidatorTx") - }) - - test("buildAddValidatorTx 3", async (): Promise => { - const addrbuff1 = addrs1.map((a) => platformvm.parseAddress(a)) - const addrbuff2 = addrs2.map((a) => platformvm.parseAddress(a)) - const addrbuff3 = addrs3.map((a) => platformvm.parseAddress(a)) - const amount: BN = ONEAVAX.mul(new BN(3)) - - const locktime: BN = new BN(54321) - const threshold: number = 2 - - platformvm.setMinStake(ONEAVAX.mul(new BN(3)), ONEAVAX.mul(new BN(3))) - - //2 utxos; one lockedstakeable; other unlocked; both utxos have 2 avax; stake 3 AVAX - - const dummySet: UTXOSet = new UTXOSet() - - const lockedBaseOut: SECPTransferOutput = new SECPTransferOutput( - ONEAVAX.mul(new BN(2)), - addrbuff1, - locktime, - 1 - ) - const lockedBaseXOut: ParseableOutput = new ParseableOutput(lockedBaseOut) - const lockedOut: StakeableLockOut = new StakeableLockOut( - ONEAVAX.mul(new BN(2)), - addrbuff1, - locktime, - 1, - locktime, - lockedBaseXOut - ) - - const txidLocked: Buffer = Buffer.alloc(32) - txidLocked.fill(1) - const txidxLocked: Buffer = Buffer.alloc(4) - txidxLocked.writeUInt32BE(1, 0) - const lu: UTXO = new UTXO(0, txidLocked, txidxLocked, assetID, lockedOut) - - const txidUnlocked: Buffer = Buffer.alloc(32) - txidUnlocked.fill(2) - const txidxUnlocked: Buffer = Buffer.alloc(4) - txidxUnlocked.writeUInt32BE(2, 0) - const unlockedOut: SECPTransferOutput = new SECPTransferOutput( - ONEAVAX.mul(new BN(2)), - addrbuff1, - locktime, - 1 - ) - const ulu: UTXO = new UTXO( - 0, - txidUnlocked, - txidxUnlocked, - assetID, - unlockedOut - ) - - dummySet.add(ulu) - dummySet.add(lu) - - const txu1: UnsignedTx = await platformvm.buildAddValidatorTx( - dummySet, - addrs3, - addrs1, - addrs2, - nodeID, - startTime, - endTime, - amount, - addrs3, - 0.1334556, - locktime, - threshold, - new UTF8Payload("hello world"), - UnixNow() - ) - - const txu1Ins: TransferableInput[] = ( - txu1.getTransaction() as AddValidatorTx - ).getIns() - const txu1Outs: TransferableOutput[] = ( - txu1.getTransaction() as AddValidatorTx - ).getOuts() - const txu1Stake: TransferableOutput[] = ( - txu1.getTransaction() as AddValidatorTx - ).getStakeOuts() - const txu1Total: TransferableOutput[] = ( - txu1.getTransaction() as AddValidatorTx - ).getTotalOuts() - - let intotal: BN = new BN(0) - - for (let i: number = 0; i < txu1Ins.length; i++) { - intotal = intotal.add( - (txu1Ins[i].getInput() as AmountInput).getAmount() - ) - } - - let outtotal: BN = new BN(0) - - for (let i: number = 0; i < txu1Outs.length; i++) { - outtotal = outtotal.add( - (txu1Outs[i].getOutput() as AmountOutput).getAmount() - ) - } - - let staketotal: BN = new BN(0) - - for (let i: number = 0; i < txu1Stake.length; i++) { - staketotal = staketotal.add( - (txu1Stake[i].getOutput() as AmountOutput).getAmount() - ) - } - - let totaltotal: BN = new BN(0) - - for (let i: number = 0; i < txu1Total.length; i++) { - totaltotal = totaltotal.add( - (txu1Total[i].getOutput() as AmountOutput).getAmount() - ) - } - - expect(intotal.toString(10)).toBe("4000000000") - expect(outtotal.toString(10)).toBe("1000000000") - expect(staketotal.toString(10)).toBe("3000000000") - expect(totaltotal.toString(10)).toBe("4000000000") - }) - - test("buildCreateSubnetTx1", async (): Promise => { - platformvm.setCreationTxFee(new BN(10)) - const addrbuff1: Buffer[] = addrs1.map( - (a): Buffer => platformvm.parseAddress(a) - ) - const addrbuff2: Buffer[] = addrs2.map( - (a): Buffer => platformvm.parseAddress(a) - ) - const addrbuff3: Buffer[] = addrs3.map( - (a): Buffer => platformvm.parseAddress(a) - ) - - const txu1: UnsignedTx = await platformvm.buildCreateSubnetTx( - set, - addrs1, - addrs2, - [addrs1[0]], - 1, - new UTF8Payload("hello world"), - UnixNow() - ) - - const txu2: UnsignedTx = set.buildCreateSubnetTx( - networkID, - bintools.cb58Decode(blockchainID), - addrbuff1, - addrbuff2, - [addrbuff1[0]], - 1, - platformvm.getCreateSubnetTxFee(), - assetID, - new UTF8Payload("hello world").getPayload(), - UnixNow() - ) - expect(txu2.toBuffer().toString("hex")).toBe( - txu1.toBuffer().toString("hex") - ) - expect(txu2.toString()).toBe(txu1.toString()) - - const tx1: Tx = txu1.sign(platformvm.keyChain()) - const checkTx: string = tx1.toBuffer().toString("hex") - const tx1obj: object = tx1.serialize("hex") - const tx1str: string = JSON.stringify(tx1obj) - - const tx2newobj: object = JSON.parse(tx1str) - const tx2: Tx = new Tx() - tx2.deserialize(tx2newobj, "hex") - - expect(tx2.toBuffer().toString("hex")).toBe(checkTx) - - const tx3: Tx = txu1.sign(platformvm.keyChain()) - const tx3obj: object = tx3.serialize(display) - const tx3str: string = JSON.stringify(tx3obj) - - const tx4newobj: object = JSON.parse(tx3str) - const tx4: Tx = new Tx() - tx4.deserialize(tx4newobj, display) - - expect(tx4.toBuffer().toString("hex")).toBe(checkTx) - - serialzeit(tx1, "CreateSubnetTx") - }) - - test("buildCreateSubnetTx2", async (): Promise => { - platformvm.setCreationTxFee(new BN(10)) - const addrbuff1: Buffer[] = addrs1.map((a: string) => - platformvm.parseAddress(a) - ) - const addrbuff2: Buffer[] = addrs2.map((a: string) => - platformvm.parseAddress(a) - ) - const addrbuff3: Buffer[] = addrs3.map((a: string) => - platformvm.parseAddress(a) - ) - - const txu1: UnsignedTx = await platformvm.buildCreateSubnetTx( - lset, - addrs1, - addrs2, - [addrs1[0]], - 1, - new UTF8Payload("hello world"), - UnixNow() - ) - - const txu2: UnsignedTx = lset.buildCreateSubnetTx( - networkID, - bintools.cb58Decode(blockchainID), - addrbuff1, - addrbuff2, - [addrbuff1[0]], - 1, - platformvm.getCreateSubnetTxFee(), - assetID, - new UTF8Payload("hello world").getPayload(), - UnixNow() - ) - expect(txu2.toBuffer().toString("hex")).toBe( - txu1.toBuffer().toString("hex") - ) - expect(txu2.toString()).toBe(txu1.toString()) - }) - }) - - test("getRewardUTXOs", async (): Promise => { - const txID: string = "7sik3Pr6r1FeLrvK1oWwECBS8iJ5VPuSh" - const result: Promise = api.getRewardUTXOs(txID) - const payload: object = { - result: { numFetched: "0", utxos: [], encoding: "cb58" } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - const response: GetRewardUTXOsResponse = await result - - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response).toBe(payload["result"]) - }) -}) diff --git a/tests/apis/platformvm/createchaintx.test.ts b/tests/apis/platformvm/createchaintx.test.ts deleted file mode 100644 index 4f2320388..000000000 --- a/tests/apis/platformvm/createchaintx.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import BinTools from "../../../src/utils/bintools" -import { Buffer } from "buffer/" -import { PlatformVMConstants } from "../../../src/apis/platformvm/constants" -import { GenesisAsset, GenesisData } from "../../../src/index" -import { CreateChainTx, SubnetAuth } from "src/apis/platformvm" - -describe("CreateChainTx", (): void => { - /** - * @ignore - */ - const bintools: BinTools = BinTools.getInstance() - - const createChainTxHex: string = - "0000053900000000000000000000000000000000000000000000000000000000000000000000000117cc8b1578ba383544d163958822d8abd3849bb9dfabe39fcbc3e7ee8811fe2f00000007006a94d6d80d6c00000000000000000000000001000000023cb7d3842e8cee6a0ebd09f1fe884f6861e1b29ca43c1f6ecdcb1fcec86d78446b9cf619c64c604b000000017fe044f9e97347c0a5ffe5a0f5773b42398c0e2b85948616da681585d460e1a80000000017cc8b1578ba383544d163958822d8abd3849bb9dfabe39fcbc3e7ee8811fe2f00000005006a94d713a836000000000100000000000000934d616e75616c6c7920637265617465206120437265617465436861696e54782077686963682063726561746573206120312d6f662d322041564158207574786f20616e6420696e7374616e746961746573206120564d20696e746f206120626c6f636b636861696e20627920636f72726563746c79207369676e696e672074686520322d6f662d33205375626e6574417574687fe044f9e97347c0a5ffe5a0f5773b42398c0e2b85948616da681585d460e1a80008455049432041564d61766d0000000000000000000000000000000000000000000000000000000000000000036e6674667800000000000000000000000000000000000000000000000000000070726f7065727479667800000000000000000000000000000000000000000000736563703235366b3166780000000000000000000000000000000000000000000000013c000000000001000e4173736574416c696173546573740000053900000000000000000000000000000000000000000000000000000000000000000000000000000000000000934d616e75616c6c7920637265617465206120437265617465436861696e54782077686963682063726561746573206120312d6f662d322041564158207574786f20616e6420696e7374616e746961746573206120564d20696e746f206120626c6f636b636861696e20627920636f72726563746c79207369676e696e672074686520322d6f662d33205375626e657441757468000a54657374204173736574000454455354000000000100000000000000010000000700000000000001fb000000000000000000000001000000023cb7d3842e8cee6a0ebd09f1fe884f6861e1b29ca43c1f6ecdcb1fcec86d78446b9cf619c64c604b0000000a000000020000000000000001" - const createChainTxBuf: Buffer = Buffer.from(createChainTxHex, "hex") - const createChainTx: CreateChainTx = new CreateChainTx() - createChainTx.fromBuffer(createChainTxBuf) - - test("getTypeName", async (): Promise => { - const createChainTxTypeName: string = createChainTx.getTypeName() - expect(createChainTxTypeName).toBe("CreateChainTx") - }) - - test("getTypeID", async (): Promise => { - const createChainTxTypeID: number = createChainTx.getTypeID() - expect(createChainTxTypeID).toBe(PlatformVMConstants.CREATECHAINTX) - }) - - test("toBuffer and fromBuffer", async (): Promise => { - const buf: Buffer = createChainTx.toBuffer() - const ccTx: CreateChainTx = new CreateChainTx() - ccTx.fromBuffer(buf) - const buf2: Buffer = ccTx.toBuffer() - expect(buf.toString("hex")).toBe(buf2.toString("hex")) - }) - - test("getSubnetID", (): void => { - const snID: string = "yKRV4EvGYWj7HHXUxSYzaAQVazEvaFPKPhJie4paqbrML5dub" - const subnetID: string = createChainTx.getSubnetID() - expect(subnetID).toBe(snID) - }) - - test("getChainName", (): void => { - const cn: string = "EPIC AVM" - const chainName: string = createChainTx.getChainName() - expect(chainName).toBe(cn) - }) - - test("getVMID", (): void => { - const vmIDHex: string = - "61766d0000000000000000000000000000000000000000000000000000000000" - const vmID: string = createChainTx.getVMID().toString("hex") - expect(vmID).toBe(vmIDHex) - }) - - test("getFXIDs", (): void => { - const fxIDsHex: string[] = [ - "6e66746678000000000000000000000000000000000000000000000000000000", - "70726f7065727479667800000000000000000000000000000000000000000000", - "736563703235366b316678000000000000000000000000000000000000000000" - ] - const fxIDs: Buffer[] = createChainTx.getFXIDs() - expect(fxIDs.length).toBe(3) - fxIDs.forEach((fxID: Buffer, index: number) => { - expect(fxID.toString("hex")).toBe(fxIDsHex[index]) - }) - }) - - test("getGenesisData", (): void => { - const gd: string = createChainTx.getGenesisData() - const genesisData: GenesisData = new GenesisData() - const buf: Buffer = bintools.cb58Decode(gd) - genesisData.fromBuffer(buf) - const genesisAssets: GenesisAsset[] = genesisData.getGenesisAssets() - const genesisAsset: GenesisAsset = genesisAssets[0] - - const n: string = "Test Asset" - const name: string = genesisAsset.getName() - expect(name).toBe(n) - - const s: string = "TEST" - const symbol: string = genesisAsset.getSymbol() - expect(symbol).toBe(s) - - const d: number = 0 - const denomination = genesisAsset.getDenomination() - expect(denomination).toBe(d) - }) - - describe("SubnetAuth", (): void => { - const sa: SubnetAuth = createChainTx.getSubnetAuth() - - test("getTypeName", async (): Promise => { - const subnetAuthTypeName: string = sa.getTypeName() - expect(subnetAuthTypeName).toBe("SubnetAuth") - }) - - test("getTypeID", async (): Promise => { - const subnetAuthTypeID: number = sa.getTypeID() - expect(subnetAuthTypeID).toBe(PlatformVMConstants.SUBNETAUTH) - }) - - test("getNumAddressIndices", async (): Promise => { - const numAddressIndices: number = sa.getNumAddressIndices() - const nAI: number = 2 - expect(numAddressIndices).toBe(nAI) - }) - - test("addressIndices", async (): Promise => { - const ai: number[] = [0, 1] - const addressIndices: Buffer[] = sa.getAddressIndices() - addressIndices.forEach((addressIndex: Buffer, index: number) => { - expect(addressIndex.readInt32BE(0)).toBe(ai[index]) - }) - }) - }) -}) diff --git a/tests/apis/platformvm/createsubnettx.test.ts b/tests/apis/platformvm/createsubnettx.test.ts deleted file mode 100644 index 84cdf34f2..000000000 --- a/tests/apis/platformvm/createsubnettx.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import BN from "bn.js" -import { Buffer } from "buffer/" -import { SECPOwnerOutput } from "../../../src/apis/platformvm/outputs" -import { PlatformVMConstants } from "../../../src/apis/platformvm/constants" -import { CreateSubnetTx } from "src/apis/platformvm" - -describe("CreateSubnetTx", (): void => { - const createSubnetTxHex: string = - "0000053900000000000000000000000000000000000000000000000000000000000000000000000117cc8b1578ba383544d163958822d8abd3849bb9dfabe39fcbc3e7ee8811fe2f00000007006a94d69c2656c0000000000000000000000001000000023cb7d3842e8cee6a0ebd09f1fe884f6861e1b29ca43c1f6ecdcb1fcec86d78446b9cf619c64c604b00000001ec7f57aeda7824b9d785e5ca631d96ef7323988a9fcfc6832cbc73ac4b27f7040000000017cc8b1578ba383544d163958822d8abd3849bb9dfabe39fcbc3e7ee8811fe2f00000005006a94d6d7c120c00000000100000000000000594d616e75616c6c79206372656174652061204372656174655375626e657454782077686963682063726561746573206120312d6f662d322041564158207574786f20616e64206120322d6f662d33205375626e6574417574680000000b000000000000000000000002000000035c412ef1414c4903c49dffc0ba9286c47fa27689a43c1f6ecdcb1fcec86d78446b9cf619c64c604be6b2bba9288c499d477327292839728ab52e902c" - const createSubnetTxBuf: Buffer = Buffer.from(createSubnetTxHex, "hex") - const createSubnetTx: CreateSubnetTx = new CreateSubnetTx() - createSubnetTx.fromBuffer(createSubnetTxBuf) - - test("getTypeName", async (): Promise => { - const createSubnetTxTypeName: string = createSubnetTx.getTypeName() - expect(createSubnetTxTypeName).toBe("CreateSubnetTx") - }) - - test("getTypeID", async (): Promise => { - const createSubnetTxTypeID: number = createSubnetTx.getTypeID() - expect(createSubnetTxTypeID).toBe(PlatformVMConstants.CREATESUBNETTX) - }) - - test("toBuffer and fromBuffer", async (): Promise => { - const buf: Buffer = createSubnetTx.toBuffer() - const csTx: CreateSubnetTx = new CreateSubnetTx() - csTx.fromBuffer(buf) - const buf2: Buffer = csTx.toBuffer() - expect(buf.toString("hex")).toBe(buf2.toString("hex")) - }) - - describe("SubnetOwners", (): void => { - const subnetOwners: SECPOwnerOutput = createSubnetTx.getSubnetOwners() - - test("getTypeName", async (): Promise => { - const subnetOwnersTypeName: string = subnetOwners.getTypeName() - expect(subnetOwnersTypeName).toBe("SECPOwnerOutput") - }) - - test("getTypeID", async (): Promise => { - const subnetOwnersTypeID: number = subnetOwners.getTypeID() - expect(subnetOwnersTypeID).toBe(PlatformVMConstants.SECPOWNEROUTPUTID) - }) - - test("getOutputID", async (): Promise => { - const outputID: number = subnetOwners.getOutputID() - expect(outputID).toBe(PlatformVMConstants.SECPOWNEROUTPUTID) - }) - - test("get addresses", async (): Promise => { - const addresses: Buffer[] = subnetOwners.getAddresses() - expect(addresses.length).toBe(3) - }) - - test("get threshold", async (): Promise => { - const threshold: number = subnetOwners.getThreshold() - expect(threshold).toBe(2) - }) - - test("get locktime", async (): Promise => { - const locktime: BN = subnetOwners.getLocktime() - expect(locktime.toNumber()).toBe(0) - }) - }) -}) diff --git a/tests/apis/platformvm/inputs.test.ts b/tests/apis/platformvm/inputs.test.ts deleted file mode 100644 index a45358e13..000000000 --- a/tests/apis/platformvm/inputs.test.ts +++ /dev/null @@ -1,168 +0,0 @@ -import { UTXOSet, UTXO } from "../../../src/apis/platformvm/utxos" -import { KeyChain } from "../../../src/apis/platformvm/keychain" -import { - SECPTransferInput, - TransferableInput -} from "../../../src/apis/platformvm/inputs" -import createHash from "create-hash" -import BinTools from "../../../src/utils/bintools" -import BN from "bn.js" -import { Buffer } from "buffer/" -import { - SECPTransferOutput, - AmountOutput, - TransferableOutput -} from "../../../src/apis/platformvm/outputs" -import { PlatformVMConstants } from "../../../src/apis/platformvm/constants" -import { Input } from "../../../src/common/input" -import { Output } from "../../../src/common/output" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() -describe("Inputs", (): void => { - let set: UTXOSet - let keymgr1: KeyChain - let keymgr2: KeyChain - let addrs1: Buffer[] - let addrs2: Buffer[] - let utxos: UTXO[] - let hrp: string = "tests" - const amnt: number = 10000 - beforeEach((): void => { - set = new UTXOSet() - keymgr1 = new KeyChain(hrp, "X") - keymgr2 = new KeyChain(hrp, "X") - addrs1 = [] - addrs2 = [] - utxos = [] - for (let i: number = 0; i < 3; i++) { - addrs1.push(keymgr1.makeKey().getAddress()) - addrs2.push(keymgr2.makeKey().getAddress()) - } - const amount: BN = new BN(amnt) - const addresses: Buffer[] = keymgr1.getAddresses() - const locktime: BN = new BN(54321) - const threshold: number = 3 - - for (let i: number = 0; i < 3; i++) { - const txid: Buffer = Buffer.from( - createHash("sha256") - .update(bintools.fromBNToBuffer(new BN(i), 32)) - .digest() - ) - const txidx: Buffer = Buffer.from(bintools.fromBNToBuffer(new BN(i), 4)) - const assetID: Buffer = Buffer.from( - createHash("sha256").update(txid).digest() - ) - const out: Output = new SECPTransferOutput( - amount.add(new BN(i)), - addresses, - locktime, - threshold - ) - const xferout: TransferableOutput = new TransferableOutput(assetID, out) - const u: UTXO = new UTXO( - PlatformVMConstants.LATESTCODEC, - txid, - txidx, - assetID, - out - ) - u.fromBuffer( - Buffer.concat([u.getCodecIDBuffer(), txid, txidx, xferout.toBuffer()]) - ) - utxos.push(u) - } - set.addArray(utxos) - }) - test("SECPInput", (): void => { - let u: UTXO - let txid: Buffer - let txidx: Buffer - const amount: BN = new BN(amnt) - let input: SECPTransferInput - let xferinput: TransferableInput - - u = utxos[0] - txid = u.getTxID() - txidx = u.getOutputIdx() - const asset = u.getAssetID() - - input = new SECPTransferInput(amount) - xferinput = new TransferableInput(txid, txidx, asset, input) - expect(xferinput.getUTXOID()).toBe(u.getUTXOID()) - expect(input.getInputID()).toBe(PlatformVMConstants.SECPINPUTID) - - input.addSignatureIdx(0, addrs2[0]) - input.addSignatureIdx(1, addrs2[1]) - - const newin: SECPTransferInput = new SECPTransferInput() - newin.fromBuffer(bintools.b58ToBuffer(input.toString())) - expect(newin.toBuffer().toString("hex")).toBe( - input.toBuffer().toString("hex") - ) - expect(newin.getSigIdxs().toString()).toBe(input.getSigIdxs().toString()) - }) - - test("Input comparator", (): void => { - const inpt1: SECPTransferInput = new SECPTransferInput( - (utxos[0].getOutput() as AmountOutput).getAmount() - ) - - const inpt2: SECPTransferInput = new SECPTransferInput( - (utxos[1].getOutput() as AmountOutput).getAmount() - ) - - const inpt3: SECPTransferInput = new SECPTransferInput( - (utxos[2].getOutput() as AmountOutput).getAmount() - ) - - const cmp = Input.comparator() - expect(cmp(inpt1, inpt2)).toBe(-1) - expect(cmp(inpt1, inpt3)).toBe(-1) - expect(cmp(inpt1, inpt1)).toBe(0) - expect(cmp(inpt2, inpt2)).toBe(0) - expect(cmp(inpt3, inpt3)).toBe(0) - }) - - test("TransferableInput comparator", (): void => { - const inpt1: SECPTransferInput = new SECPTransferInput( - (utxos[0].getOutput() as AmountOutput).getAmount() - ) - const in1: TransferableInput = new TransferableInput( - utxos[0].getTxID(), - utxos[0].getOutputIdx(), - utxos[0].getAssetID(), - inpt1 - ) - - const inpt2: SECPTransferInput = new SECPTransferInput( - (utxos[1].getOutput() as AmountOutput).getAmount() - ) - const in2: TransferableInput = new TransferableInput( - utxos[1].getTxID(), - utxos[1].getOutputIdx(), - utxos[1].getAssetID(), - inpt2 - ) - - const inpt3: SECPTransferInput = new SECPTransferInput( - (utxos[2].getOutput() as AmountOutput).getAmount() - ) - const in3: TransferableInput = new TransferableInput( - utxos[2].getTxID(), - utxos[2].getOutputIdx(), - utxos[2].getAssetID(), - inpt3 - ) - - const cmp = TransferableInput.comparator() - expect(cmp(in1, in2)).toBe(-1) - expect(cmp(in1, in3)).toBe(-1) - expect(cmp(in1, in1)).toBe(0) - expect(cmp(in2, in2)).toBe(0) - expect(cmp(in3, in3)).toBe(0) - }) -}) diff --git a/tests/apis/platformvm/keychain.test.ts b/tests/apis/platformvm/keychain.test.ts deleted file mode 100644 index b9aee4e37..000000000 --- a/tests/apis/platformvm/keychain.test.ts +++ /dev/null @@ -1,446 +0,0 @@ -import { KeyChain, KeyPair } from "../../../src/apis/platformvm/keychain" -import { Avalanche } from "../../../src/index" -import { Buffer } from "buffer/" -import createHash from "create-hash" -import BinTools from "../../../src/utils/bintools" - -const bintools: BinTools = BinTools.getInstance() -const alias: string = "P" -const hrp: string = "tests" -describe("PlatformVMKeyPair", (): void => { - const networkID: number = 1337 - const ip: string = "127.0.0.1" - const port: number = 9650 - const protocol: string = "https" - const avalanche: Avalanche = new Avalanche( - ip, - port, - protocol, - networkID, - undefined, - undefined, - undefined, - true - ) - - test("human readable part", (): void => { - let hrp: string = avalanche.getHRP() - let networkID: number = avalanche.getNetworkID() - expect(hrp).toBe("custom") - expect(networkID).toBe(1337) - - avalanche.setNetworkID(2) - hrp = avalanche.getHRP() - networkID = avalanche.getNetworkID() - expect(hrp).toBe("cascade") - expect(networkID).toBe(2) - - avalanche.setNetworkID(3) - hrp = avalanche.getHRP() - networkID = avalanche.getNetworkID() - expect(hrp).toBe("denali") - expect(networkID).toBe(3) - - avalanche.setNetworkID(4) - hrp = avalanche.getHRP() - networkID = avalanche.getNetworkID() - expect(hrp).toBe("everest") - expect(networkID).toBe(4) - - avalanche.setNetworkID(0) - hrp = avalanche.getHRP() - networkID = avalanche.getNetworkID() - expect(hrp).toBe("custom") - expect(networkID).toBe(0) - - avalanche.setNetworkID(1) - hrp = avalanche.getHRP() - networkID = avalanche.getNetworkID() - expect(hrp).toBe("avax") - expect(networkID).toBe(1) - - avalanche.setNetworkID(12345) - hrp = avalanche.getHRP() - networkID = avalanche.getNetworkID() - expect(hrp).toBe("local") - expect(networkID).toBe(12345) - }) - - // See: https://bitcointalk.org/index.php?topic=285142.msg3300992#msg3300992 - // as the source of the RFC6979 test vectors. - test("rfc6979 1", (): void => { - const kp: KeyPair = new KeyPair(hrp, alias) - kp.importKey( - Buffer.from( - "0000000000000000000000000000000000000000000000000000000000000001", - "hex" - ) - ) - - const msg: Buffer = Buffer.from( - createHash("sha256") - .update( - Buffer.from( - "Everything should be made as simple as possible, but not simpler." - ) - ) - .digest("hex"), - "hex" - ) - const sig: string = kp.sign(msg).slice(0, 64).toString("hex") - - expect(sig).toBe( - "33a69cd2065432a30f3d1ce4eb0d59b8ab58c74f27c41a7fdb5696ad4e6108c96f807982866f785d3f6418d24163ddae117b7db4d5fdf0071de069fa54342262" - ) - }) - - test("rfc6979 2", (): void => { - const kp: KeyPair = new KeyPair(hrp, alias) - kp.importKey( - Buffer.from( - "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140", - "hex" - ) - ) - - const msg: Buffer = Buffer.from( - createHash("sha256") - .update( - Buffer.from( - "Equations are more important to me, because politics is for the present, but an equation is something for eternity." - ) - ) - .digest("hex"), - "hex" - ) - const sig: string = kp.sign(msg).slice(0, 64).toString("hex") - - expect(sig).toBe( - "54c4a33c6423d689378f160a7ff8b61330444abb58fb470f96ea16d99d4a2fed07082304410efa6b2943111b6a4e0aaa7b7db55a07e9861d1fb3cb1f421044a5" - ) - }) - - test("rfc6979 3", (): void => { - const kp: KeyPair = new KeyPair(hrp, alias) - kp.importKey( - Buffer.from( - "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140", - "hex" - ) - ) - - const msg: Buffer = Buffer.from( - createHash("sha256") - .update( - Buffer.from( - "Not only is the Universe stranger than we think, it is stranger than we can think." - ) - ) - .digest("hex"), - "hex" - ) - const sig: string = kp.sign(msg).slice(0, 64).toString("hex") - - expect(sig).toBe( - "ff466a9f1b7b273e2f4c3ffe032eb2e814121ed18ef84665d0f515360dab3dd06fc95f5132e5ecfdc8e5e6e616cc77151455d46ed48f5589b7db7771a332b283" - ) - }) - - test("rfc6979 4", (): void => { - const kp: KeyPair = new KeyPair(hrp, alias) - kp.importKey( - Buffer.from( - "0000000000000000000000000000000000000000000000000000000000000001", - "hex" - ) - ) - - const msg: Buffer = Buffer.from( - createHash("sha256") - .update( - Buffer.from( - "How wonderful that we have met with a paradox. Now we have some hope of making progress." - ) - ) - .digest("hex"), - "hex" - ) - const sig: string = kp.sign(msg).slice(0, 64).toString("hex") - - expect(sig).toBe( - "c0dafec8251f1d5010289d210232220b03202cba34ec11fec58b3e93a85b91d375afdc06b7d6322a590955bf264e7aaa155847f614d80078a90292fe205064d3" - ) - }) - - test("rfc6979 5", (): void => { - const kp: KeyPair = new KeyPair(hrp, alias) - kp.importKey( - Buffer.from( - "69ec59eaa1f4f2e36b639716b7c30ca86d9a5375c7b38d8918bd9c0ebc80ba64", - "hex" - ) - ) - - const msg: Buffer = Buffer.from( - createHash("sha256") - .update( - Buffer.from( - "Computer science is no more about computers than astronomy is about telescopes." - ) - ) - .digest("hex"), - "hex" - ) - const sig: string = kp.sign(msg).slice(0, 64).toString("hex") - - expect(sig).toBe( - "7186363571d65e084e7f02b0b77c3ec44fb1b257dee26274c38c928986fea45d0de0b38e06807e46bda1f1e293f4f6323e854c86d58abdd00c46c16441085df6" - ) - }) - - test("rfc6979 6", (): void => { - const kp: KeyPair = new KeyPair(hrp, alias) - kp.importKey( - Buffer.from( - "00000000000000000000000000007246174ab1e92e9149c6e446fe194d072637", - "hex" - ) - ) - - const msg: Buffer = Buffer.from( - createHash("sha256") - .update( - Buffer.from( - "...if you aren't, at any given time, scandalized by code you wrote five or even three years ago, you're not learning anywhere near enough" - ) - ) - .digest("hex"), - "hex" - ) - const sig: string = kp.sign(msg).slice(0, 64).toString("hex") - - expect(sig).toBe( - "fbfe5076a15860ba8ed00e75e9bd22e05d230f02a936b653eb55b61c99dda4870e68880ebb0050fe4312b1b1eb0899e1b82da89baa5b895f612619edf34cbd37" - ) - }) - - test("rfc6979 7", (): void => { - const kp: KeyPair = new KeyPair(hrp, alias) - kp.importKey( - Buffer.from( - "000000000000000000000000000000000000000000056916d0f9b31dc9b637f3", - "hex" - ) - ) - - const msg: Buffer = Buffer.from( - createHash("sha256") - .update( - Buffer.from( - "The question of whether computers can think is like the question of whether submarines can swim." - ) - ) - .digest("hex"), - "hex" - ) - const sig: string = kp.sign(msg).slice(0, 64).toString("hex") - - expect(sig).toBe( - "cde1302d83f8dd835d89aef803c74a119f561fbaef3eb9129e45f30de86abbf906ce643f5049ee1f27890467b77a6a8e11ec4661cc38cd8badf90115fbd03cef" - ) - }) - - test("repeatable 1", (): void => { - const kp: KeyPair = new KeyPair(hrp, alias) - kp.importKey( - Buffer.from( - "ef9bf2d4436491c153967c9709dd8e82795bdb9b5ad44ee22c2903005d1cf676", - "hex" - ) - ) - expect(kp.getPublicKey().toString("hex")).toBe( - "033fad3644deb20d7a210d12757092312451c112d04773cee2699fbb59dc8bb2ef" - ) - - const msg: Buffer = Buffer.from( - createHash("sha256").update(Buffer.from("09090909", "hex")).digest("hex"), - "hex" - ) - const sig: Buffer = kp.sign(msg) - - expect(sig.length).toBe(65) - expect(kp.verify(msg, sig)).toBe(true) - expect(kp.recover(msg, sig).toString("hex")).toBe( - kp.getPublicKey().toString("hex") - ) - }) - - test("repeatable 2", (): void => { - const kp: KeyPair = new KeyPair(hrp, alias) - kp.importKey( - Buffer.from( - "17c692d4a99d12f629d9f0ff92ec0dba15c9a83e85487b085c1a3018286995c6", - "hex" - ) - ) - expect(kp.getPublicKey().toString("hex")).toBe( - "02486553b276cfe7abf0efbcd8d173e55db9c03da020c33d0b219df24124da18ee" - ) - - const msg: Buffer = Buffer.from( - createHash("sha256").update(Buffer.from("09090909", "hex")).digest("hex"), - "hex" - ) - const sig: Buffer = kp.sign(msg) - - expect(sig.length).toBe(65) - expect(kp.verify(msg, sig)).toBe(true) - expect(kp.recover(msg, sig).toString("hex")).toBe( - kp.getPublicKey().toString("hex") - ) - }) - - test("repeatable 3", (): void => { - const kp: KeyPair = new KeyPair(hrp, alias) - kp.importKey( - Buffer.from( - "d0e17d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - ) - expect(kp.getPublicKey().toString("hex")).toBe( - "031475b91d4fcf52979f1cf107f058088cc2bea6edd51915790f27185a7586e2f2" - ) - - const msg: Buffer = Buffer.from( - createHash("sha256").update(Buffer.from("09090909", "hex")).digest("hex"), - "hex" - ) - const sig: Buffer = kp.sign(msg) - - expect(sig.length).toBe(65) - expect(kp.verify(msg, sig)).toBe(true) - expect(kp.recover(msg, sig).toString("hex")).toBe( - kp.getPublicKey().toString("hex") - ) - }) - - test("Creation Empty", (): void => { - const kp: KeyPair = new KeyPair(hrp, alias) - expect(kp.getPrivateKey()).not.toBeUndefined() - expect(kp.getAddress()).not.toBeUndefined() - expect(kp.getPrivateKeyString()).not.toBeUndefined() - expect(kp.getPublicKey()).not.toBeUndefined() - expect(kp.getPublicKeyString()).not.toBeUndefined() - const msg: Buffer = Buffer.from( - createHash("sha256").update(Buffer.from("09090909", "hex")).digest("hex"), - "hex" - ) - const sig: Buffer = kp.sign(msg) - - expect(sig.length).toBe(65) - expect(kp.verify(msg, sig)).toBe(true) - expect(kp.recover(msg, sig).toString("hex")).toBe( - kp.getPublicKey().toString("hex") - ) - }) -}) - -describe("PlatformVMKeyChain", (): void => { - test("importKey from Buffer", (): void => { - const keybuff: Buffer = Buffer.from( - "d0e17d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - const kc: KeyChain = new KeyChain(hrp, alias) - const kp2: KeyPair = new KeyPair(hrp, alias) - const addr1: Buffer = kc.importKey(keybuff).getAddress() - const kp1: KeyPair = kc.getKey(addr1) - kp2.importKey(keybuff) - const addr2 = kp1.getAddress() - expect(addr1.toString("hex")).toBe(addr2.toString("hex")) - expect(kp1.getPrivateKeyString()).toBe(kp2.getPrivateKeyString()) - expect(kp1.getPublicKeyString()).toBe(kp2.getPublicKeyString()) - expect(kc.hasKey(addr1)).toBe(true) - }) - - test("importKey from Buffer with leading zeros", (): void => { - const keybuff: Buffer = Buffer.from( - "00007d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - expect(keybuff.length).toBe(32) - const kc: KeyChain = new KeyChain(hrp, alias) - const kp2: KeyPair = new KeyPair(hrp, alias) - const addr1: Buffer = kc.importKey(keybuff).getAddress() - const kp1: KeyPair = kc.getKey(addr1) - kp2.importKey(keybuff) - const addr2 = kp1.getAddress() - expect(addr1.toString("hex")).toBe(addr2.toString("hex")) - expect(kp1.getPrivateKeyString()).toBe(kp2.getPrivateKeyString()) - expect(kp1.getPrivateKey().length).toBe(32) - expect(kp2.getPrivateKey().length).toBe(32) - expect(kp1.getPublicKeyString()).toBe(kp2.getPublicKeyString()) - expect(kp1.getPublicKey().length).toBe(33) - expect(kp2.getPublicKey().length).toBe(33) - expect(kc.hasKey(addr1)).toBe(true) - }) - - test("importKey from serialized string", (): void => { - const keybuff: Buffer = Buffer.from( - "d0e17d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - const kc: KeyChain = new KeyChain(hrp, alias) - const kp2: KeyPair = new KeyPair(hrp, alias) - const addr1: Buffer = kc - .importKey("PrivateKey-" + bintools.cb58Encode(keybuff)) - .getAddress() - const kp1: KeyPair = kc.getKey(addr1) - kp2.importKey(keybuff) - const addr2 = kp1.getAddress() - expect(addr1.toString("hex")).toBe(addr2.toString("hex")) - expect(kp1.getPrivateKeyString()).toBe(kp2.getPrivateKeyString()) - expect(kp1.getPublicKeyString()).toBe(kp2.getPublicKeyString()) - expect(kc.hasKey(addr1)).toBe(true) - }) - - test("removeKey via keypair", (): void => { - const keybuff: Buffer = Buffer.from( - "d0e17d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - const kc: KeyChain = new KeyChain(hrp, alias) - const kp1: KeyPair = new KeyPair(hrp, alias) - const addr1: Buffer = kc.importKey(keybuff).getAddress() - kp1.importKey(keybuff) - expect(kc.hasKey(addr1)).toBe(true) - kc.removeKey(kp1) - expect(kc.hasKey(addr1)).toBe(false) - }) - - test("removeKey via string", (): void => { - const keybuff: Buffer = Buffer.from( - "d0e17d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - const kc: KeyChain = new KeyChain(hrp, alias) - const addr1: Buffer = kc.importKey(keybuff).getAddress() - expect(kc.hasKey(addr1)).toBe(true) - kc.removeKey(addr1) - expect(kc.hasKey(addr1)).toBe(false) - }) - - test("removeKey bad keys", (): void => { - const keybuff: Buffer = Buffer.from( - "d0e17d4b31380f96a42b3e9ffc4c1b2a93589a1e51d86d7edc107f602fbc7475", - "hex" - ) - const kc: KeyChain = new KeyChain(hrp, alias) - const addr1: Buffer = kc.importKey(keybuff).getAddress() - expect(kc.hasKey(addr1)).toBe(true) - expect( - kc.removeKey(bintools.cb58Decode("6Y3kysjF9jnHnYkdS9yGAuoHyae2eNmeV")) - ).toBe(false) - }) -}) diff --git a/tests/apis/platformvm/outputs.test.ts b/tests/apis/platformvm/outputs.test.ts deleted file mode 100644 index 81329aed1..000000000 --- a/tests/apis/platformvm/outputs.test.ts +++ /dev/null @@ -1,104 +0,0 @@ -import BN from "bn.js" -import { Buffer } from "buffer/" -import BinTools from "../../../src/utils/bintools" -import { - SECPTransferOutput, - SelectOutputClass -} from "../../../src/apis/platformvm/outputs" -import { Output } from "../../../src/common/output" - -const bintools: BinTools = BinTools.getInstance() - -describe("Outputs", (): void => { - describe("SECPTransferOutput", (): void => { - const addrs: Buffer[] = [ - bintools.cb58Decode("B6D4v1VtPYLbiUvYXtW4Px8oE9imC2vGW"), - bintools.cb58Decode("P5wdRuZeaDt28eHMP5S3w9ZdoBfo7wuzF"), - bintools.cb58Decode("6Y3kysjF9jnHnYkdS9yGAuoHyae2eNmeV") - ].sort() - - const locktime: BN = new BN(54321) - const addrpay = [addrs[0], addrs[1]] - const fallLocktime: BN = locktime.add(new BN(50)) - - test("SelectOutputClass", (): void => { - const goodout: SECPTransferOutput = new SECPTransferOutput( - new BN(2600), - addrpay, - fallLocktime, - 1 - ) - const outpayment: Output = SelectOutputClass(goodout.getOutputID()) - expect(outpayment).toBeInstanceOf(SECPTransferOutput) - expect(() => { - SelectOutputClass(99) - }).toThrow("Error - SelectOutputClass: unknown outputid") - }) - - test("comparator", (): void => { - const outpayment1: Output = new SECPTransferOutput( - new BN(10000), - addrs, - locktime, - 3 - ) - const outpayment2: Output = new SECPTransferOutput( - new BN(10001), - addrs, - locktime, - 3 - ) - const outpayment3: Output = new SECPTransferOutput( - new BN(9999), - addrs, - locktime, - 3 - ) - const cmp = Output.comparator() - expect(cmp(outpayment1, outpayment1)).toBe(0) - expect(cmp(outpayment2, outpayment2)).toBe(0) - expect(cmp(outpayment3, outpayment3)).toBe(0) - expect(cmp(outpayment1, outpayment2)).toBe(-1) - expect(cmp(outpayment1, outpayment3)).toBe(1) - }) - - test("SECPTransferOutput", (): void => { - const out: SECPTransferOutput = new SECPTransferOutput( - new BN(10000), - addrs, - locktime, - 3 - ) - expect(out.getOutputID()).toBe(7) - expect(JSON.stringify(out.getAddresses().sort())).toStrictEqual( - JSON.stringify(addrs.sort()) - ) - - expect(out.getThreshold()).toBe(3) - expect(out.getLocktime().toNumber()).toBe(locktime.toNumber()) - - const r: number = out.getAddressIdx(addrs[2]) - expect(out.getAddress(r)).toStrictEqual(addrs[2]) - expect((): void => { - out.getAddress(400) - }).toThrow() - - expect(out.getAmount().toNumber()).toBe(10000) - - const b: Buffer = out.toBuffer() - expect(out.toString()).toBe(bintools.bufferToB58(b)) - - const s: Buffer[] = out.getSpenders(addrs) - expect(JSON.stringify(s.sort())).toBe(JSON.stringify(addrs.sort())) - - const m1: boolean = out.meetsThreshold([addrs[0]]) - expect(m1).toBe(false) - const m2: boolean = out.meetsThreshold(addrs, new BN(100)) - expect(m2).toBe(false) - const m3: boolean = out.meetsThreshold(addrs) - expect(m3).toBe(true) - const m4: boolean = out.meetsThreshold(addrs, locktime.add(new BN(100))) - expect(m4).toBe(true) - }) - }) -}) diff --git a/tests/apis/platformvm/proofofpossession.test.ts b/tests/apis/platformvm/proofofpossession.test.ts deleted file mode 100644 index ee91f5ec3..000000000 --- a/tests/apis/platformvm/proofofpossession.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { Buffer } from "buffer/" -import { ProofOfPossession } from "../../../src/apis/platformvm" - -describe("ProofOfPossession", (): void => { - // publicKey and signature generated with: https://www.npmjs.com/package/@noble/bls12-381 - const publicKey: string = "a38ef4a5ec3177db895065ad751c7f24ea44c8ccafd5b892782a22d793df8fda6cd92787ff352b73ca8fe9f153e9760b" - const publicKeyBuffer: Buffer = Buffer.from(publicKey, "hex") - const signature: string = "a38aa4e58c67c2092c72bc03780e6f575b6f626bc9133c30a38817282b2764ecea49f77c22fc909a441f653e0c92290a148338b2f903d35939f6bef281bed0e333d9b6ebfa49891b1bac5df4378b06d569c877439cdbe0534268682adc00cb88" - const signatureBuffer: Buffer = Buffer.from(signature, "hex") - const proofOfPossession: ProofOfPossession = new ProofOfPossession( - publicKeyBuffer, - signatureBuffer - ) - - test("get public key", async (): Promise => { - const pubKey: Buffer = proofOfPossession.getPublicKey() - expect(pubKey).toBe(publicKeyBuffer) - const pubKeyHex: string = Buffer.from(pubKey).toString('hex') - expect(pubKeyHex).toBe(publicKey) - }) - - test("get signature", async (): Promise => { - const sig: Buffer = proofOfPossession.getSignature() - expect(sig).toBe(signatureBuffer) - const sigHex: string = Buffer.from(sig).toString('hex') - expect(sigHex).toBe(signature) - }) - - test("toBuffer and fromBuffer", async (): Promise => { - const buff: Buffer = proofOfPossession.toBuffer() - const prfOfPossession: ProofOfPossession = new ProofOfPossession() - prfOfPossession.fromBuffer(buff) - const buff2: Buffer = prfOfPossession.toBuffer() - expect(buff).toStrictEqual(buff2) - }) -}) diff --git a/tests/apis/platformvm/removesubnetvalidatortx.test.ts b/tests/apis/platformvm/removesubnetvalidatortx.test.ts deleted file mode 100644 index 8b3d4961b..000000000 --- a/tests/apis/platformvm/removesubnetvalidatortx.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { Buffer } from "buffer/" -import { - RemoveSubnetValidatorTx, - PlatformVMConstants, - SubnetAuth -} from "src/apis/platformvm" -import { bufferToNodeIDString } from "src/utils" - -describe("RemoveSubnetValidatorTx", (): void => { - const removeSubnetValidatorTxHex: string = - "0000053900000000000000000000000000000000000000000000000000000000000000000000000117cc8b1578ba383544d163958822d8abd3849bb9dfabe39fcbc3e7ee8811fe2f0000000700470de4a3c8b180000000000000000000000001000000023cb7d3842e8cee6a0ebd09f1fe884f6861e1b29ca43c1f6ecdcb1fcec86d78446b9cf619c64c604b000000018ced4aeb38582518eef8c67aad4df719d7f65f68c676e745a56762e94db0dfeb0000000017cc8b1578ba383544d163958822d8abd3849bb9dfabe39fcbc3e7ee8811fe2f0000000500470de4a3d7f3c000000001000000000000009b4d616e75616c6c792063726561746520612072656d6f76655375626e657456616c696461746f7254782077686963682063726561746573206120312d6f662d322041564158207574786f20616e642072656d6f76657320612076616c696461746f722066726f6d2061207375626e657420627920636f72726563746c79207369676e696e672074686520322d6f662d33205375626e657441757468e9094f73698002fd52c90819b457b9fbc866ab8010ea2f81249b0a7fe756533a2191aef6377eeaeb192b4c1b42c406366dbff3dd0000000a000000020000000000000001" - const removeSubnetValidatorTxBuf: Buffer = Buffer.from( - removeSubnetValidatorTxHex, - "hex" - ) - const removeSubnetValidatorTx: RemoveSubnetValidatorTx = new RemoveSubnetValidatorTx() - removeSubnetValidatorTx.fromBuffer(removeSubnetValidatorTxBuf) - - test("getTypeName", async (): Promise => { - const removeSubnetValidatorTxTypeName: string = - removeSubnetValidatorTx.getTypeName() - expect(removeSubnetValidatorTxTypeName).toBe("RemoveSubnetValidatorTx") - }) - - test("getTypeID", async (): Promise => { - const removeSubnetValidatorTxTypeID: number = removeSubnetValidatorTx.getTypeID() - expect(removeSubnetValidatorTxTypeID).toBe( - PlatformVMConstants.REMOVESUBNETVALIDATORTX - ) - }) - - test("toBuffer and fromBuffer", async (): Promise => { - const buf: Buffer = removeSubnetValidatorTx.toBuffer() - const rsvTx: RemoveSubnetValidatorTx = new RemoveSubnetValidatorTx() - rsvTx.fromBuffer(buf) - const buf2: Buffer = rsvTx.toBuffer() - expect(buf.toString("hex")).toBe(buf2.toString("hex")) - }) - - test("getNodeID", async (): Promise => { - const nodeID: string = "NodeID-NFBbbJ4qCmNaCzeW7sxErhvWqvEQMnYcN" - const nodeIDBuf: Buffer = removeSubnetValidatorTx.getNodeID() - const nID: string = bufferToNodeIDString(nodeIDBuf) - expect(nID).toBe(nodeID) - }) - - test("getSubnetID", async (): Promise => { - const subnetID: string = "8T4oUrP7kXzetGF2bYWF21oJHUT18rJCjfBt3J299hA1Smcqa" - const sID: string = removeSubnetValidatorTx.getSubnetID() - expect(subnetID).toBe(sID) - }) - - describe("SubnetAuth", (): void => { - const sa: SubnetAuth = removeSubnetValidatorTx.getSubnetAuth() - - test("getTypeName", async (): Promise => { - const subnetAuthTypeName: string = sa.getTypeName() - expect(subnetAuthTypeName).toBe("SubnetAuth") - }) - - test("getTypeID", async (): Promise => { - const subnetAuthTypeID: number = sa.getTypeID() - expect(subnetAuthTypeID).toBe(PlatformVMConstants.SUBNETAUTH) - }) - - test("getNumAddressIndices", async (): Promise => { - const numAddressIndices: number = sa.getNumAddressIndices() - const nAI: number = 2 - expect(numAddressIndices).toBe(nAI) - }) - - test("addressIndices", async (): Promise => { - const ai: number[] = [0, 1] - const addressIndices: Buffer[] = sa.getAddressIndices() - addressIndices.forEach((addressIndex: Buffer, index: number) => { - expect(addressIndex.readInt32BE(0)).toBe(ai[index]) - }) - }) - }) -}) diff --git a/tests/apis/platformvm/subnetauth.test.ts b/tests/apis/platformvm/subnetauth.test.ts deleted file mode 100644 index 8e2e985e0..000000000 --- a/tests/apis/platformvm/subnetauth.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { Buffer } from "buffer/" -import { SubnetAuth } from "src/apis/platformvm" -import BinTools from "src/utils/bintools" - -/** - * @ignore - */ -const bintools: BinTools = BinTools.getInstance() - -describe("SubnetAuth", (): void => { - const subnetAuth1: SubnetAuth = new SubnetAuth() - const subnetAuth2: SubnetAuth = new SubnetAuth() - - test("getters", (): void => { - const typeName: string = subnetAuth1.getTypeName() - expect(typeName).toBe("SubnetAuth") - - const typeID: number = subnetAuth1.getTypeID() - expect(typeID).toBe(10) - - let addressIndex: Buffer = Buffer.alloc(4) - addressIndex.writeUIntBE(0, 0, 4) - subnetAuth1.addAddressIndex(addressIndex) - addressIndex = Buffer.alloc(4) - addressIndex.writeUIntBE(1, 0, 4) - subnetAuth1.addAddressIndex(addressIndex) - - const numAddressIndices: number = subnetAuth1.getNumAddressIndices() - expect(numAddressIndices).toBe(2) - - const addressIndices: Buffer[] = subnetAuth1.getAddressIndices() - expect(Buffer.isBuffer(addressIndices[0])).toBeTruthy() - expect(bintools.fromBufferToBN(addressIndices[0]).toNumber()).toBe(0) - expect(bintools.fromBufferToBN(addressIndices[1]).toNumber()).toBe(1) - }) - - test("toBuffer", (): void => { - const subnetAuth1Buf: Buffer = subnetAuth1.toBuffer() - subnetAuth2.fromBuffer(subnetAuth1Buf) - const subnetAuth1Hex: string = subnetAuth1.toBuffer().toString("hex") - const subnetAuth2Hex: string = subnetAuth2.toBuffer().toString("hex") - expect(subnetAuth1Hex).toBe(subnetAuth2Hex) - }) -}) diff --git a/tests/apis/platformvm/tx.test.ts b/tests/apis/platformvm/tx.test.ts deleted file mode 100644 index 632e338ae..000000000 --- a/tests/apis/platformvm/tx.test.ts +++ /dev/null @@ -1,601 +0,0 @@ -import mockAxios from "jest-mock-axios" -import { UTXOSet, UTXO } from "../../../src/apis/platformvm/utxos" -import { PlatformVMAPI } from "../../../src/apis/platformvm/api" -import { UnsignedTx, Tx } from "../../../src/apis/platformvm/tx" -import { KeyChain } from "../../../src/apis/platformvm/keychain" -import { - SECPTransferInput, - TransferableInput -} from "../../../src/apis/platformvm/inputs" -import createHash from "create-hash" -import BinTools from "../../../src/utils/bintools" -import BN from "bn.js" -import { Buffer } from "buffer/" -import { - SECPTransferOutput, - TransferableOutput -} from "../../../src/apis/platformvm/outputs" -import { PlatformVMConstants } from "../../../src/apis/platformvm/constants" -import { Avalanche, GenesisData } from "../../../src/index" -import { UTF8Payload } from "../../../src/utils/payload" -import { - NodeIDStringToBuffer, - UnixNow -} from "../../../src/utils/helperfunctions" -import { BaseTx } from "../../../src/apis/platformvm/basetx" -import { ImportTx } from "../../../src/apis/platformvm/importtx" -import { ExportTx } from "../../../src/apis/platformvm/exporttx" -import { PlatformChainID } from "../../../src/utils/constants" -import { HttpResponse } from "jest-mock-axios/dist/lib/mock-axios-types" - -describe("Transactions", (): void => { - /** - * @ignore - */ - const bintools: BinTools = BinTools.getInstance() - - const networkID: number = 1337 - let set: UTXOSet - let keymgr1: KeyChain - let keymgr2: KeyChain - let keymgr3: KeyChain - let addrs1: Buffer[] - let addrs2: Buffer[] - let addrs3: Buffer[] - let utxos: UTXO[] - let inputs: TransferableInput[] - let outputs: TransferableOutput[] - let importIns: TransferableInput[] - let importUTXOs: UTXO[] - let exportOuts: TransferableOutput[] - let fungutxos: UTXO[] - let exportUTXOIDS: string[] - let api: PlatformVMAPI - const amnt: number = 10000 - const netid: number = 12345 - const blockchainID: Buffer = bintools.cb58Decode(PlatformChainID) - const alias: string = "X" - const assetID: Buffer = Buffer.from( - createHash("sha256") - .update( - "Well, now, don't you tell me to smile, you stick around I'll make it worth your while." - ) - .digest() - ) - let amount: BN - let addresses: Buffer[] - let fallAddresses: Buffer[] - let locktime: BN - let fallLocktime: BN - let threshold: number - let fallThreshold: number - const ip: string = "127.0.0.1" - const port: number = 8080 - const protocol: string = "http" - let avalanche: Avalanche - const name: string = "Mortycoin is the dumb as a sack of hammers." - const symbol: string = "morT" - const denomination: number = 8 - let avaxAssetID: Buffer - const genesisDataStr: string = - "11111DdZMhYXUZiFV9FNpfpTSQroysjHyMuT5zapYkPYrmap7t7S3sDNNwFzngxR9x1XmoRj5JK1XomX8RHvXYY5h3qYeEsMQRF8Ypia7p1CFHDo6KGSjMdiQkrmpvL8AvoezSxVWKXt2ubmBCnSkpPjnQbBSF7gNg4sPu1PXdh1eKgthaSFREqqG5FKMrWNiS6U87kxCmbKjkmBvwnAd6TpNx75YEiS9YKMyHaBZjkRDNf6Nj1" - const gd: GenesisData = new GenesisData() - gd.fromBuffer(bintools.cb58Decode(genesisDataStr)) - const addressIndex: Buffer = Buffer.alloc(4) - addressIndex.writeUIntBE(0x0, 0, 4) - - beforeAll(async (): Promise => { - avalanche = new Avalanche( - ip, - port, - protocol, - 12345, - undefined, - undefined, - undefined, - true - ) - api = new PlatformVMAPI(avalanche, "/ext/bc/P") - const result: Promise = api.getAVAXAssetID() - const payload: object = { - result: { - name, - symbol, - assetID: bintools.cb58Encode(assetID), - denomination: `${denomination}` - } - } - const responseObj: HttpResponse = { - data: payload - } - - mockAxios.mockResponse(responseObj) - avaxAssetID = await result - }) - - beforeEach((): void => { - set = new UTXOSet() - keymgr1 = new KeyChain(avalanche.getHRP(), alias) - keymgr2 = new KeyChain(avalanche.getHRP(), alias) - keymgr3 = new KeyChain(avalanche.getHRP(), alias) - addrs1 = [] - addrs2 = [] - addrs3 = [] - utxos = [] - inputs = [] - outputs = [] - importIns = [] - importUTXOs = [] - exportOuts = [] - fungutxos = [] - exportUTXOIDS = [] - for (let i: number = 0; i < 3; i++) { - addrs1.push(keymgr1.makeKey().getAddress()) - addrs2.push(keymgr2.makeKey().getAddress()) - addrs3.push(keymgr3.makeKey().getAddress()) - } - amount = new BN(amnt) - addresses = keymgr1.getAddresses() - fallAddresses = keymgr2.getAddresses() - locktime = new BN(54321) - fallLocktime = locktime.add(new BN(50)) - threshold = 3 - fallThreshold = 1 - - const payload: Buffer = Buffer.alloc(1024) - payload.write( - "All you Trekkies and TV addicts, Don't mean to diss don't mean to bring static.", - 0, - 1024, - "utf8" - ) - - for (let i: number = 0; i < 5; i++) { - let txid: Buffer = Buffer.from( - createHash("sha256") - .update(bintools.fromBNToBuffer(new BN(i), 32)) - .digest() - ) - let txidx: Buffer = Buffer.from(bintools.fromBNToBuffer(new BN(i), 4)) - const out: SECPTransferOutput = new SECPTransferOutput( - amount, - addresses, - locktime, - threshold - ) - const xferout: TransferableOutput = new TransferableOutput(assetID, out) - outputs.push(xferout) - - const u: UTXO = new UTXO( - PlatformVMConstants.LATESTCODEC, - txid, - txidx, - assetID, - out - ) - utxos.push(u) - fungutxos.push(u) - importUTXOs.push(u) - - txid = u.getTxID() - txidx = u.getOutputIdx() - - const input: SECPTransferInput = new SECPTransferInput(amount) - const xferin: TransferableInput = new TransferableInput( - txid, - txidx, - assetID, - input - ) - inputs.push(xferin) - } - for (let i: number = 1; i < 4; i++) { - importIns.push(inputs[i]) - exportOuts.push(outputs[i]) - exportUTXOIDS.push(fungutxos[i].getUTXOID()) - } - set.addArray(utxos) - }) - - test("Create small BaseTx that is Goose Egg Tx", async (): Promise => { - const outs: TransferableOutput[] = [] - const ins: TransferableInput[] = [] - const outputAmt: BN = new BN("266") - const output: SECPTransferOutput = new SECPTransferOutput( - outputAmt, - addrs1, - new BN(0), - 1 - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - output - ) - outs.push(transferableOutput) - const inputAmt: BN = new BN("400") - const input: SECPTransferInput = new SECPTransferInput(inputAmt) - input.addSignatureIdx(0, addrs1[0]) - const txid: Buffer = bintools.cb58Decode( - "n8XH5JY1EX5VYqDeAhB4Zd4GKxi9UNQy6oPpMsCAj1Q6xkiiL" - ) - const outputIndex: Buffer = Buffer.from( - bintools.fromBNToBuffer(new BN(0), 4) - ) - const transferableInput: TransferableInput = new TransferableInput( - txid, - outputIndex, - avaxAssetID, - input - ) - ins.push(transferableInput) - const baseTx: BaseTx = new BaseTx(networkID, blockchainID, outs, ins) - const unsignedTx: UnsignedTx = new UnsignedTx(baseTx) - expect(await api.checkGooseEgg(unsignedTx)).toBe(true) - }) - - test("confirm inputTotal, outputTotal and fee are correct", async (): Promise => { - const bintools: BinTools = BinTools.getInstance() - // local network P Chain ID - // AVAX assetID - const assetID: Buffer = bintools.cb58Decode( - "n8XH5JY1EX5VYqDeAhB4Zd4GKxi9UNQy6oPpMsCAj1Q6xkiiL" - ) - const outs: TransferableOutput[] = [] - const ins: TransferableInput[] = [] - const outputAmt: BN = new BN("266") - const output: SECPTransferOutput = new SECPTransferOutput( - outputAmt, - addrs1, - new BN(0), - 1 - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - assetID, - output - ) - outs.push(transferableOutput) - const inputAmt: BN = new BN("400") - const input: SECPTransferInput = new SECPTransferInput(inputAmt) - input.addSignatureIdx(0, addrs1[0]) - const txid: Buffer = bintools.cb58Decode( - "n8XH5JY1EX5VYqDeAhB4Zd4GKxi9UNQy6oPpMsCAj1Q6xkiiL" - ) - const outputIndex: Buffer = Buffer.from( - bintools.fromBNToBuffer(new BN(0), 4) - ) - const transferableInput: TransferableInput = new TransferableInput( - txid, - outputIndex, - assetID, - input - ) - ins.push(transferableInput) - const baseTx: BaseTx = new BaseTx(networkID, blockchainID, outs, ins) - const unsignedTx: UnsignedTx = new UnsignedTx(baseTx) - const inputTotal: BN = unsignedTx.getInputTotal(assetID) - const outputTotal: BN = unsignedTx.getOutputTotal(assetID) - const burn: BN = unsignedTx.getBurn(assetID) - expect(inputTotal.toNumber()).toEqual(new BN(400).toNumber()) - expect(outputTotal.toNumber()).toEqual(new BN(266).toNumber()) - expect(burn.toNumber()).toEqual(new BN(134).toNumber()) - }) - - test("Create small BaseTx that isn't Goose Egg Tx", async (): Promise => { - // local network X Chain ID - const outs: TransferableOutput[] = [] - const ins: TransferableInput[] = [] - const outputAmt: BN = new BN("267") - const output: SECPTransferOutput = new SECPTransferOutput( - outputAmt, - addrs1, - new BN(0), - 1 - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - output - ) - outs.push(transferableOutput) - const inputAmt: BN = new BN("400") - const input: SECPTransferInput = new SECPTransferInput(inputAmt) - input.addSignatureIdx(0, addrs1[0]) - const txid: Buffer = bintools.cb58Decode( - "n8XH5JY1EX5VYqDeAhB4Zd4GKxi9UNQy6oPpMsCAj1Q6xkiiL" - ) - const outputIndex: Buffer = Buffer.from( - bintools.fromBNToBuffer(new BN(0), 4) - ) - const transferableInput: TransferableInput = new TransferableInput( - txid, - outputIndex, - avaxAssetID, - input - ) - ins.push(transferableInput) - const baseTx: BaseTx = new BaseTx(networkID, blockchainID, outs, ins) - const unsignedTx: UnsignedTx = new UnsignedTx(baseTx) - expect(await api.checkGooseEgg(unsignedTx)).toBe(true) - }) - - test("Create large BaseTx that is Goose Egg Tx", async (): Promise => { - // local network P Chain ID - const outs: TransferableOutput[] = [] - const ins: TransferableInput[] = [] - const outputAmt: BN = new BN("609555500000") - const output: SECPTransferOutput = new SECPTransferOutput( - outputAmt, - addrs1, - new BN(0), - 1 - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - output - ) - outs.push(transferableOutput) - const inputAmt: BN = new BN("45000000000000000") - const input: SECPTransferInput = new SECPTransferInput(inputAmt) - input.addSignatureIdx(0, addrs1[0]) - const txid: Buffer = bintools.cb58Decode( - "n8XH5JY1EX5VYqDeAhB4Zd4GKxi9UNQy6oPpMsCAj1Q6xkiiL" - ) - const outputIndex: Buffer = Buffer.from( - bintools.fromBNToBuffer(new BN(0), 4) - ) - const transferableInput: TransferableInput = new TransferableInput( - txid, - outputIndex, - avaxAssetID, - input - ) - ins.push(transferableInput) - const baseTx: BaseTx = new BaseTx(networkID, blockchainID, outs, ins) - const unsignedTx: UnsignedTx = new UnsignedTx(baseTx) - expect(await api.checkGooseEgg(unsignedTx)).toBe(false) - }) - - test("Create large BaseTx that isn't Goose Egg Tx", async (): Promise => { - // local network P Chain ID - const outs: TransferableOutput[] = [] - const ins: TransferableInput[] = [] - const outputAmt: BN = new BN("44995609555500000") - const output: SECPTransferOutput = new SECPTransferOutput( - outputAmt, - addrs1, - new BN(0), - 1 - ) - const transferableOutput: TransferableOutput = new TransferableOutput( - avaxAssetID, - output - ) - outs.push(transferableOutput) - const inputAmt: BN = new BN("45000000000000000") - const input: SECPTransferInput = new SECPTransferInput(inputAmt) - input.addSignatureIdx(0, addrs1[0]) - const txid: Buffer = bintools.cb58Decode( - "n8XH5JY1EX5VYqDeAhB4Zd4GKxi9UNQy6oPpMsCAj1Q6xkiiL" - ) - const outputIndex: Buffer = Buffer.from( - bintools.fromBNToBuffer(new BN(0), 4) - ) - const transferableInput: TransferableInput = new TransferableInput( - txid, - outputIndex, - avaxAssetID, - input - ) - ins.push(transferableInput) - const baseTx: BaseTx = new BaseTx(networkID, blockchainID, outs, ins) - const unsignedTx: UnsignedTx = new UnsignedTx(baseTx) - expect(await api.checkGooseEgg(unsignedTx)).toBe(true) - }) - - test("Creation UnsignedTx", (): void => { - const baseTx: BaseTx = new BaseTx(netid, blockchainID, outputs, inputs) - const txu: UnsignedTx = new UnsignedTx(baseTx) - const txins: TransferableInput[] = txu.getTransaction().getIns() - const txouts: TransferableOutput[] = txu.getTransaction().getOuts() - expect(txins.length).toBe(inputs.length) - expect(txouts.length).toBe(outputs.length) - - expect(txu.getTransaction().getTxType()).toBe(0) - expect(txu.getTransaction().getNetworkID()).toBe(12345) - expect(txu.getTransaction().getBlockchainID().toString("hex")).toBe( - blockchainID.toString("hex") - ) - - let a: string[] = [] - let b: string[] = [] - for (let i: number = 0; i < txins.length; i++) { - a.push(txins[i].toString()) - b.push(inputs[i].toString()) - } - expect(JSON.stringify(a.sort())).toBe(JSON.stringify(b.sort())) - - a = [] - b = [] - - for (let i: number = 0; i < txouts.length; i++) { - a.push(txouts[i].toString()) - b.push(outputs[i].toString()) - } - expect(JSON.stringify(a.sort())).toBe(JSON.stringify(b.sort())) - - const txunew: UnsignedTx = new UnsignedTx() - txunew.fromBuffer(txu.toBuffer()) - expect(txunew.toBuffer().toString("hex")).toBe( - txu.toBuffer().toString("hex") - ) - expect(txunew.toString()).toBe(txu.toString()) - }) - - test("Creation UnsignedTx Check Amount", (): void => { - expect((): void => { - set.buildBaseTx( - netid, - blockchainID, - new BN(amnt * 1000), - assetID, - addrs3, - addrs1, - addrs1 - ) - }).toThrow() - }) - - test("Creation ImportTx", (): void => { - const bombtx: ImportTx = new ImportTx( - netid, - blockchainID, - outputs, - inputs, - new UTF8Payload("hello world").getPayload(), - undefined, - importIns - ) - - expect((): void => { - bombtx.toBuffer() - }).toThrow() - - const importTx: ImportTx = new ImportTx( - netid, - blockchainID, - outputs, - inputs, - new UTF8Payload("hello world").getPayload(), - bintools.cb58Decode(PlatformChainID), - importIns - ) - const txunew: ImportTx = new ImportTx() - const importbuff: Buffer = importTx.toBuffer() - txunew.fromBuffer(importbuff) - - expect(importTx).toBeInstanceOf(ImportTx) - expect(importTx.getSourceChain().toString("hex")).toBe( - bintools.cb58Decode(PlatformChainID).toString("hex") - ) - expect(txunew.toBuffer().toString("hex")).toBe(importbuff.toString("hex")) - expect(txunew.toString()).toBe(importTx.toString()) - expect(importTx.getImportInputs().length).toBe(importIns.length) - }) - - test("Creation ExportTx", (): void => { - const bombtx: ExportTx = new ExportTx( - netid, - blockchainID, - outputs, - inputs, - undefined, - undefined, - exportOuts - ) - - expect((): void => { - bombtx.toBuffer() - }).toThrow() - - const exportTx: ExportTx = new ExportTx( - netid, - blockchainID, - outputs, - inputs, - undefined, - bintools.cb58Decode(PlatformChainID), - exportOuts - ) - const txunew: ExportTx = new ExportTx() - const exportbuff: Buffer = exportTx.toBuffer() - txunew.fromBuffer(exportbuff) - - expect(exportTx).toBeInstanceOf(ExportTx) - expect(exportTx.getDestinationChain().toString("hex")).toBe( - bintools.cb58Decode(PlatformChainID).toString("hex") - ) - expect(txunew.toBuffer().toString("hex")).toBe(exportbuff.toString("hex")) - expect(txunew.toString()).toBe(exportTx.toString()) - expect(exportTx.getExportOutputs().length).toBe(exportOuts.length) - }) - - test("Creation Tx1 with asof, locktime, threshold", (): void => { - const txu: UnsignedTx = set.buildBaseTx( - netid, - blockchainID, - new BN(9000), - assetID, - addrs3, - addrs1, - addrs1, - undefined, - undefined, - undefined, - UnixNow(), - UnixNow().add(new BN(50)), - 1 - ) - const tx: Tx = txu.sign(keymgr1) - - const tx2: Tx = new Tx() - tx2.fromString(tx.toString()) - expect(tx2.toBuffer().toString("hex")).toBe(tx.toBuffer().toString("hex")) - expect(tx2.toString()).toBe(tx.toString()) - }) - test("Creation Tx2 without asof, locktime, threshold", (): void => { - const txu: UnsignedTx = set.buildBaseTx( - netid, - blockchainID, - new BN(9000), - assetID, - addrs3, - addrs1, - addrs1 - ) - const tx: Tx = txu.sign(keymgr1) - const tx2: Tx = new Tx() - tx2.fromBuffer(tx.toBuffer()) - expect(tx2.toBuffer().toString("hex")).toBe(tx.toBuffer().toString("hex")) - expect(tx2.toString()).toBe(tx.toString()) - }) - - test("Creation Tx4 using ImportTx", (): void => { - const txu: UnsignedTx = set.buildImportTx( - netid, - blockchainID, - addrs3, - addrs1, - addrs2, - importUTXOs, - bintools.cb58Decode(PlatformChainID), - new BN(90), - assetID, - new UTF8Payload("hello world").getPayload(), - UnixNow() - ) - const tx: Tx = txu.sign(keymgr1) - const tx2: Tx = new Tx() - tx2.fromBuffer(tx.toBuffer()) - expect(tx2.toBuffer().toString("hex")).toBe(tx.toBuffer().toString("hex")) - }) - - test("Creation Tx5 using ExportTx", (): void => { - const txu: UnsignedTx = set.buildExportTx( - netid, - blockchainID, - new BN(90), - avaxAssetID, - addrs3, - addrs1, - addrs2, - bintools.cb58Decode(PlatformChainID), - undefined, - undefined, - new UTF8Payload("hello world").getPayload(), - UnixNow() - ) - const tx: Tx = txu.sign(keymgr1) - const tx2: Tx = new Tx() - tx2.fromBuffer(tx.toBuffer()) - expect(tx.toBuffer().toString("hex")).toBe(tx2.toBuffer().toString("hex")) - }) -}) diff --git a/tests/apis/platformvm/utxos.test.ts b/tests/apis/platformvm/utxos.test.ts deleted file mode 100644 index 75ab1da25..000000000 --- a/tests/apis/platformvm/utxos.test.ts +++ /dev/null @@ -1,649 +0,0 @@ -import BN from "bn.js" -import { Buffer } from "buffer/" -import BinTools from "../../../src/utils/bintools" -import { UTXO, UTXOSet } from "../../../src/apis/platformvm/utxos" -import { AmountOutput } from "../../../src/apis/platformvm/outputs" -import { UnixNow } from "../../../src/utils/helperfunctions" -import { SerializedEncoding } from "../../../src/utils" - -const bintools: BinTools = BinTools.getInstance() -const display: SerializedEncoding = "display" - -describe("UTXO", (): void => { - const utxohex: string = - "000038d1b9f1138672da6fb6c35125539276a9acc2a668d63bea6ba3c795e2edb0f5000000013e07e38e2f23121be8756412c18db7246a16d26ee9936f3cba28be149cfd3558000000070000000000004dd500000000000000000000000100000001a36fd0c2dbcab311731dde7ef1514bd26fcdc74d" - const outputidx: string = "00000001" - const outtxid: string = - "38d1b9f1138672da6fb6c35125539276a9acc2a668d63bea6ba3c795e2edb0f5" - const outaid: string = - "3e07e38e2f23121be8756412c18db7246a16d26ee9936f3cba28be149cfd3558" - const utxobuff: Buffer = Buffer.from(utxohex, "hex") - - // Payment - const OPUTXOstr: string = bintools.cb58Encode(utxobuff) - // "U9rFgK5jjdXmV8k5tpqeXkimzrN3o9eCCcXesyhMBBZu9MQJCDTDo5Wn5psKvzJVMJpiMbdkfDXkp7sKZddfCZdxpuDmyNy7VFka19zMW4jcz6DRQvNfA2kvJYKk96zc7uizgp3i2FYWrB8mr1sPJ8oP9Th64GQ5yHd8" - - // implies fromString and fromBuffer - test("Creation", (): void => { - const u1: UTXO = new UTXO() - u1.fromBuffer(utxobuff) - const u1hex: string = u1.toBuffer().toString("hex") - expect(u1hex).toBe(utxohex) - }) - - test("Empty Creation", (): void => { - const u1: UTXO = new UTXO() - expect(() => { - u1.toBuffer() - }).toThrow() - }) - - test("Creation of Type", (): void => { - const op: UTXO = new UTXO() - op.fromString(OPUTXOstr) - expect(op.getOutput().getOutputID()).toBe(7) - }) - - describe("Funtionality", (): void => { - const u1: UTXO = new UTXO() - u1.fromBuffer(utxobuff) - const u1hex: string = u1.toBuffer().toString("hex") - test("getAssetID NonCA", (): void => { - const assetID: Buffer = u1.getAssetID() - expect(assetID.toString("hex", 0, assetID.length)).toBe(outaid) - }) - test("getTxID", (): void => { - const txid: Buffer = u1.getTxID() - expect(txid.toString("hex", 0, txid.length)).toBe(outtxid) - }) - test("getOutputIdx", (): void => { - const txidx: Buffer = u1.getOutputIdx() - expect(txidx.toString("hex", 0, txidx.length)).toBe(outputidx) - }) - test("getUTXOID", (): void => { - const txid: Buffer = Buffer.from(outtxid, "hex") - const txidx: Buffer = Buffer.from(outputidx, "hex") - const utxoid: string = bintools.bufferToB58(Buffer.concat([txid, txidx])) - expect(u1.getUTXOID()).toBe(utxoid) - }) - test("toString", (): void => { - const serialized: string = u1.toString() - expect(serialized).toBe(bintools.cb58Encode(utxobuff)) - }) - }) -}) - -const setMergeTester = ( - input: UTXOSet, - equal: UTXOSet[], - notEqual: UTXOSet[] -): boolean => { - const instr: string = JSON.stringify(input.getUTXOIDs().sort()) - for (let i: number = 0; i < equal.length; i++) { - if (JSON.stringify(equal[i].getUTXOIDs().sort()) != instr) { - return false - } - } - - for (let i: number = 0; i < notEqual.length; i++) { - if (JSON.stringify(notEqual[i].getUTXOIDs().sort()) == instr) { - return false - } - } - return true -} - -describe("UTXOSet", (): void => { - const hexteststring = "000038d1b9f1138672da6fb6c35125539276a9acc2a668d63bea6ba3c795e2edb0f5000000013e07e38e2f23121be8756412c18db7246a16d26ee9936f3cba28be149cfd3558000000070000000000004dd500000000000000000000000100000001a36fd0c2dbcab311731dde7ef1514bd26fcdc74d" - const utxostrs: string[] = [ - bintools.cb58Encode( - Buffer.from( - hexteststring, - "hex" - ) - ), - bintools.cb58Encode( - Buffer.from( - "0000c3e4823571587fe2bdfc502689f5a8238b9d0ea7f3277124d16af9de0d2d9911000000003e07e38e2f23121be8756412c18db7246a16d26ee9936f3cba28be149cfd355800000007000000000000001900000000000000000000000100000001e1b6b6a4bad94d2e3f20730379b9bcd6f176318e", - "hex" - ) - ), - bintools.cb58Encode( - Buffer.from( - "0000f29dba61fda8d57a911e7f8810f935bde810d3f8d495404685bdb8d9d8545e86000000003e07e38e2f23121be8756412c18db7246a16d26ee9936f3cba28be149cfd355800000007000000000000001900000000000000000000000100000001e1b6b6a4bad94d2e3f20730379b9bcd6f176318e", - "hex" - ) - ) - ] - const addrs: Buffer[] = [ - bintools.cb58Decode("FuB6Lw2D62NuM8zpGLA4Avepq7eGsZRiG"), - bintools.cb58Decode("MaTvKGccbYzCxzBkJpb2zHW7E1WReZqB8") - ] - test("Creation", (): void => { - const set: UTXOSet = new UTXOSet() - set.add(utxostrs[0]) - const utxo: UTXO = new UTXO() - utxo.fromString(utxostrs[0]) - const setArray: UTXO[] = set.getAllUTXOs() - expect(utxo.toString()).toBe(setArray[0].toString()) - }) - test("Creation (explicit cb58 specification)", (): void => { - const set: UTXOSet = new UTXOSet() - set.add(utxostrs[0]) - const utxo: UTXO = new UTXO() - utxo.fromString(utxostrs[0], 'cb58') - const setArray: UTXO[] = set.getAllUTXOs() - expect(utxo.toString()).toBe(setArray[0].toString()) - }) - test("Creation (explicit hex specification)", (): void => { - const set: UTXOSet = new UTXOSet() - set.add(utxostrs[0]) - const utxo: UTXO = new UTXO() - utxo.fromString(hexteststring, 'hex') - const setArray: UTXO[] = set.getAllUTXOs() - expect(utxo.toString()).toBe(setArray[0].toString()) - }) - - test("Serialization", (): void => { - const set: UTXOSet = new UTXOSet() - set.addArray([...utxostrs]) - let setobj: object = set.serialize("cb58") - let setstr: string = JSON.stringify(setobj) - let set2newobj: object = JSON.parse(setstr) - let set2: UTXOSet = new UTXOSet() - set2.deserialize(set2newobj, "cb58") - let set2obj: object = set2.serialize("cb58") - let set2str: string = JSON.stringify(set2obj) - expect(set2.getAllUTXOStrings().sort().join(",")).toBe( - set.getAllUTXOStrings().sort().join(",") - ) - }) - - test("Mutliple add", (): void => { - const set: UTXOSet = new UTXOSet() - // first add - for (let i: number = 0; i < utxostrs.length; i++) { - set.add(utxostrs[i]) - } - // the verify (do these steps separate to ensure no overwrites) - for (let i: number = 0; i < utxostrs.length; i++) { - expect(set.includes(utxostrs[i])).toBe(true) - const utxo: UTXO = new UTXO() - utxo.fromString(utxostrs[i]) - const veriutxo: UTXO = set.getUTXO(utxo.getUTXOID()) as UTXO - expect(veriutxo.toString()).toBe(utxostrs[i]) - } - }) - - test("addArray", (): void => { - const set: UTXOSet = new UTXOSet() - set.addArray(utxostrs) - for (let i: number = 0; i < utxostrs.length; i++) { - const e1: UTXO = new UTXO() - e1.fromString(utxostrs[i]) - expect(set.includes(e1)).toBe(true) - const utxo: UTXO = new UTXO() - utxo.fromString(utxostrs[i]) - const veriutxo: UTXO = set.getUTXO(utxo.getUTXOID()) as UTXO - expect(veriutxo.toString()).toBe(utxostrs[i]) - } - - set.addArray(set.getAllUTXOs()) - for (let i: number = 0; i < utxostrs.length; i++) { - const utxo: UTXO = new UTXO() - utxo.fromString(utxostrs[i]) - expect(set.includes(utxo)).toBe(true) - - const veriutxo: UTXO = set.getUTXO(utxo.getUTXOID()) as UTXO - expect(veriutxo.toString()).toBe(utxostrs[i]) - } - let o: object = set.serialize("hex") - let s: UTXOSet = new UTXOSet() - s.deserialize(o) - let t: object = set.serialize(display) - let r: UTXOSet = new UTXOSet() - r.deserialize(t) - }) - - test("overwriting UTXO", (): void => { - const set: UTXOSet = new UTXOSet() - set.addArray(utxostrs) - const testutxo: UTXO = new UTXO() - testutxo.fromString(utxostrs[0]) - expect(set.add(utxostrs[0], true).toString()).toBe(testutxo.toString()) - expect(set.add(utxostrs[0], false)).toBeUndefined() - expect(set.addArray(utxostrs, true).length).toBe(3) - expect(set.addArray(utxostrs, false).length).toBe(0) - }) - - describe("Functionality", (): void => { - let set: UTXOSet - let utxos: UTXO[] - beforeEach(() => { - set = new UTXOSet() - set.addArray(utxostrs) - utxos = set.getAllUTXOs() - }) - - test("remove", (): void => { - const testutxo: UTXO = new UTXO() - testutxo.fromString(utxostrs[0]) - expect(set.remove(utxostrs[0]).toString()).toBe(testutxo.toString()) - expect(set.remove(utxostrs[0])).toBeUndefined() - expect(set.add(utxostrs[0], false).toString()).toBe(testutxo.toString()) - expect(set.remove(utxostrs[0]).toString()).toBe(testutxo.toString()) - }) - - test("removeArray", (): void => { - const testutxo: UTXO = new UTXO() - testutxo.fromString(utxostrs[0]) - expect(set.removeArray(utxostrs).length).toBe(3) - expect(set.removeArray(utxostrs).length).toBe(0) - expect(set.add(utxostrs[0], false).toString()).toBe(testutxo.toString()) - expect(set.removeArray(utxostrs).length).toBe(1) - expect(set.addArray(utxostrs, false).length).toBe(3) - expect(set.removeArray(utxos).length).toBe(3) - }) - - test("getUTXOIDs", (): void => { - const uids: string[] = set.getUTXOIDs() - for (let i: number = 0; i < utxos.length; i++) { - expect(uids.indexOf(utxos[i].getUTXOID())).not.toBe(-1) - } - }) - - test("getAllUTXOs", (): void => { - const allutxos: UTXO[] = set.getAllUTXOs() - const ustrs: string[] = [] - for (let i: number = 0; i < allutxos.length; i++) { - ustrs.push(allutxos[i].toString()) - } - for (let i: number = 0; i < utxostrs.length; i++) { - expect(ustrs.indexOf(utxostrs[i])).not.toBe(-1) - } - const uids: string[] = set.getUTXOIDs() - const allutxos2: UTXO[] = set.getAllUTXOs(uids) - const ustrs2: string[] = [] - for (let i: number = 0; i < allutxos.length; i++) { - ustrs2.push(allutxos2[i].toString()) - } - for (let i: number = 0; i < utxostrs.length; i++) { - expect(ustrs2.indexOf(utxostrs[i])).not.toBe(-1) - } - }) - - test("getUTXOIDs By Address", (): void => { - let utxoids: string[] - utxoids = set.getUTXOIDs([addrs[0]]) - expect(utxoids.length).toBe(1) - utxoids = set.getUTXOIDs(addrs) - expect(utxoids.length).toBe(3) - utxoids = set.getUTXOIDs(addrs, false) - expect(utxoids.length).toBe(3) - }) - - test("getAllUTXOStrings", (): void => { - const ustrs: string[] = set.getAllUTXOStrings() - for (let i: number = 0; i < utxostrs.length; i++) { - expect(ustrs.indexOf(utxostrs[i])).not.toBe(-1) - } - const uids: string[] = set.getUTXOIDs() - const ustrs2: string[] = set.getAllUTXOStrings(uids) - for (let i: number = 0; i < utxostrs.length; i++) { - expect(ustrs2.indexOf(utxostrs[i])).not.toBe(-1) - } - }) - - test("getAddresses", (): void => { - expect(set.getAddresses().sort()).toStrictEqual(addrs.sort()) - }) - - test("getBalance", (): void => { - let balance1: BN - let balance2: BN - balance1 = new BN(0) - balance2 = new BN(0) - for (let i: number = 0; i < utxos.length; i++) { - const assetID = utxos[i].getAssetID() - balance1 = balance1.add(set.getBalance(addrs, assetID)) - balance2 = balance2.add( - (utxos[i].getOutput() as AmountOutput).getAmount() - ) - } - expect(balance1.gt(new BN(0))).toBe(true) - expect(balance2.gt(new BN(0))).toBe(true) - - balance1 = new BN(0) - balance2 = new BN(0) - const now: BN = UnixNow() - for (let i: number = 0; i < utxos.length; i++) { - const assetID = bintools.cb58Encode(utxos[i].getAssetID()) - balance1 = balance1.add(set.getBalance(addrs, assetID, now)) - balance2 = balance2.add( - (utxos[i].getOutput() as AmountOutput).getAmount() - ) - } - expect(balance1.gt(new BN(0))).toBe(true) - expect(balance2.gt(new BN(0))).toBe(true) - }) - - test("getAssetIDs", (): void => { - const assetIDs: Buffer[] = set.getAssetIDs() - for (let i: number = 0; i < utxos.length; i++) { - expect(assetIDs).toContain(utxos[i].getAssetID()) - } - const addresses: Buffer[] = set.getAddresses() - expect(set.getAssetIDs(addresses)).toEqual(set.getAssetIDs()) - }) - - describe("Merge Rules", (): void => { - let setA: UTXOSet - let setB: UTXOSet - let setC: UTXOSet - let setD: UTXOSet - let setE: UTXOSet - let setF: UTXOSet - let setG: UTXOSet - let setH: UTXOSet - // Take-or-Leave - const newutxo: string = bintools.cb58Encode( - Buffer.from( - "0000acf88647b3fbaa9fdf4378f3a0df6a5d15d8efb018ad78f12690390e79e1687600000003acf88647b3fbaa9fdf4378f3a0df6a5d15d8efb018ad78f12690390e79e168760000000700000000000186a000000000000000000000000100000001fceda8f90fcb5d30614b99d79fc4baa293077626", - "hex" - ) - ) - - beforeEach((): void => { - setA = new UTXOSet() - setA.addArray([utxostrs[0], utxostrs[2]]) - - setB = new UTXOSet() - setB.addArray([utxostrs[1], utxostrs[2]]) - - setC = new UTXOSet() - setC.addArray([utxostrs[0], utxostrs[1]]) - - setD = new UTXOSet() - setD.addArray([utxostrs[1]]) - - setE = new UTXOSet() - setE.addArray([]) // empty set - - setF = new UTXOSet() - setF.addArray(utxostrs) // full set, separate from self - - setG = new UTXOSet() - setG.addArray([newutxo, ...utxostrs]) // full set with new element - - setH = new UTXOSet() - setH.addArray([newutxo]) // set with only a new element - }) - - test("unknown merge rule", (): void => { - expect((): void => { - set.mergeByRule(setA, "ERROR") - }).toThrow() - const setArray: UTXO[] = setG.getAllUTXOs() - }) - - test("intersection", (): void => { - let results: UTXOSet - let test: boolean - - results = set.mergeByRule(setA, "intersection") - test = setMergeTester( - results, - [setA], - [setB, setC, setD, setE, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setF, "intersection") - test = setMergeTester( - results, - [setF], - [setA, setB, setC, setD, setE, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setG, "intersection") - test = setMergeTester( - results, - [setF], - [setA, setB, setC, setD, setE, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setH, "intersection") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - }) - - test("differenceSelf", (): void => { - let results: UTXOSet - let test: boolean - - results = set.mergeByRule(setA, "differenceSelf") - test = setMergeTester( - results, - [setD], - [setA, setB, setC, setE, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setF, "differenceSelf") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setG, "differenceSelf") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setH, "differenceSelf") - test = setMergeTester( - results, - [setF], - [setA, setB, setC, setD, setE, setG, setH] - ) - expect(test).toBe(true) - }) - - test("differenceNew", (): void => { - let results: UTXOSet - let test: boolean - - results = set.mergeByRule(setA, "differenceNew") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setF, "differenceNew") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setG, "differenceNew") - test = setMergeTester( - results, - [setH], - [setA, setB, setC, setD, setE, setF, setG] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setH, "differenceNew") - test = setMergeTester( - results, - [setH], - [setA, setB, setC, setD, setE, setF, setG] - ) - expect(test).toBe(true) - }) - - test("symDifference", (): void => { - let results: UTXOSet - let test: boolean - - results = set.mergeByRule(setA, "symDifference") - test = setMergeTester( - results, - [setD], - [setA, setB, setC, setE, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setF, "symDifference") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setG, "symDifference") - test = setMergeTester( - results, - [setH], - [setA, setB, setC, setD, setE, setF, setG] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setH, "symDifference") - test = setMergeTester( - results, - [setG], - [setA, setB, setC, setD, setE, setF, setH] - ) - expect(test).toBe(true) - }) - - test("union", (): void => { - let results: UTXOSet - let test: boolean - - results = set.mergeByRule(setA, "union") - test = setMergeTester( - results, - [setF], - [setA, setB, setC, setD, setE, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setF, "union") - test = setMergeTester( - results, - [setF], - [setA, setB, setC, setD, setE, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setG, "union") - test = setMergeTester( - results, - [setG], - [setA, setB, setC, setD, setE, setF, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setH, "union") - test = setMergeTester( - results, - [setG], - [setA, setB, setC, setD, setE, setF, setH] - ) - expect(test).toBe(true) - }) - - test("unionMinusNew", (): void => { - let results: UTXOSet - let test: boolean - - results = set.mergeByRule(setA, "unionMinusNew") - test = setMergeTester( - results, - [setD], - [setA, setB, setC, setE, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setF, "unionMinusNew") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setG, "unionMinusNew") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setH, "unionMinusNew") - test = setMergeTester( - results, - [setF], - [setA, setB, setC, setD, setE, setG, setH] - ) - expect(test).toBe(true) - }) - - test("unionMinusSelf", (): void => { - let results: UTXOSet - let test: boolean - - results = set.mergeByRule(setA, "unionMinusSelf") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setF, "unionMinusSelf") - test = setMergeTester( - results, - [setE], - [setA, setB, setC, setD, setF, setG, setH] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setG, "unionMinusSelf") - test = setMergeTester( - results, - [setH], - [setA, setB, setC, setD, setE, setF, setG] - ) - expect(test).toBe(true) - - results = set.mergeByRule(setH, "unionMinusSelf") - test = setMergeTester( - results, - [setH], - [setA, setB, setC, setD, setE, setF, setG] - ) - expect(test).toBe(true) - }) - }) - }) -}) diff --git a/tests/avalanche.test.ts b/tests/avalanche.test.ts deleted file mode 100644 index acca964c3..000000000 --- a/tests/avalanche.test.ts +++ /dev/null @@ -1,295 +0,0 @@ -import mockAxios from "jest-mock-axios" -import { Avalanche, AvalancheCore } from "../src" -import { AVMAPI } from "../src/apis/avm/api" -import { AdminAPI } from "../src/apis/admin/api" -import { HealthAPI } from "../src/apis/health/api" -import { InfoAPI } from "../src/apis/info/api" -import { KeystoreAPI } from "../src/apis/keystore/api" -import { MetricsAPI } from "../src/apis/metrics/api" -import { PlatformVMAPI } from "../src/apis/platformvm/api" -import { TestAPI } from "./testlib" -import { AxiosRequestConfig } from "axios" -import { HttpResponse } from "jest-mock-axios/dist/lib/mock-axios-types" - -describe("Avalanche", (): void => { - const blockchainID: string = - "6h2s5de1VC65meajE1L2PjvZ1MXvHc3F6eqPCGKuDt4MxiweF" - let host: string = "127.0.0.1" - const port: number = 9650 - const networkID: number = 1337 - let protocol: string = "https" - let avalanche: Avalanche - let avalancheCore: AvalancheCore - const api: string = "api.avax.network" - const url: string = "https://api.avax.network:9650" - const encrypted: string = "https" - const skipinit: boolean = true - beforeAll((): void => { - avalanche = new Avalanche( - host, - port, - protocol, - networkID, - undefined, - undefined, - undefined, - skipinit - ) - avalanche.addAPI("admin", AdminAPI) - avalanche.addAPI("xchain", AVMAPI, "/ext/subnet/avm", blockchainID) - avalanche.addAPI("health", HealthAPI) - avalanche.addAPI("info", InfoAPI) - avalanche.addAPI("keystore", KeystoreAPI) - avalanche.addAPI("metrics", MetricsAPI) - avalanche.addAPI("pchain", PlatformVMAPI) - }) - test("Remove special characters", (): void => { - host = "a&&&&p#i,.@a+v(a)x$.~n%e't:w*o?r" - protocol = "h@t&@&@t#p+s()$" - avalanche = new Avalanche(host, port, protocol, networkID) - expect(avalanche.getHost()).toBe(api) - expect(avalanche.getProtocol()).toBe(encrypted) - expect(avalanche.getURL()).toBe(url) - avalancheCore = new AvalancheCore(host, port, protocol) - expect(avalancheCore.getHost()).toBe(api) - expect(avalancheCore.getProtocol()).toBe(encrypted) - expect(avalancheCore.getURL()).toBe(url) - }) - test("Can specify base endpoint", (): void => { - avalanche = new Avalanche() - avalanche.setAddress(api, port, encrypted, "rpc") - avalanche.setNetworkID(networkID) - expect(avalanche.getHost()).toBe(api) - expect(avalanche.getProtocol()).toBe(encrypted) - expect(avalanche.getPort()).toBe(port) - expect(avalanche.getBaseEndpoint()).toBe("rpc") - expect(avalanche.getURL()).toBe(`${url}/rpc`) - expect(avalanche.getNetworkID()).toBe(networkID) - }) - test("Can initialize without port", (): void => { - protocol = encrypted - host = api - avalanche = new Avalanche(host, undefined, protocol, networkID) - expect(avalanche.getPort()).toBe(undefined) - expect(avalanche.getURL()).toBe(`${protocol}://${api}`) - avalancheCore = new AvalancheCore(host, undefined, protocol) - expect(avalancheCore.getPort()).toBe(undefined) - expect(avalancheCore.getURL()).toBe(`${protocol}://${api}`) - }) - test("Can initialize with port", (): void => { - protocol = encrypted - avalanche = new Avalanche(host, port, protocol, networkID) - expect(avalanche.getIP()).toBe(host) - expect(avalanche.getHost()).toBe(host) - expect(avalanche.getPort()).toBe(port) - expect(avalanche.getProtocol()).toBe(protocol) - expect(avalanche.getURL()).toBe(`${protocol}://${host}:${port}`) - expect(avalanche.getNetworkID()).toBe(1337) - expect(avalanche.getHeaders()).toStrictEqual({}) - avalanche.setNetworkID(50) - expect(avalanche.getNetworkID()).toBe(50) - avalanche.setNetworkID(12345) - expect(avalanche.getNetworkID()).toBe(12345) - }) - - test("Endpoints correct", (): void => { - expect(avalanche.Admin()).not.toBeInstanceOf(AVMAPI) - expect(avalanche.Admin()).toBeInstanceOf(AdminAPI) - - expect(avalanche.XChain()).not.toBeInstanceOf(AdminAPI) - expect(avalanche.XChain()).toBeInstanceOf(AVMAPI) - - expect(avalanche.Health()).not.toBeInstanceOf(KeystoreAPI) - expect(avalanche.Health()).toBeInstanceOf(HealthAPI) - - expect(avalanche.Info()).not.toBeInstanceOf(KeystoreAPI) - expect(avalanche.Info()).toBeInstanceOf(InfoAPI) - - expect(avalanche.PChain()).not.toBeInstanceOf(KeystoreAPI) - expect(avalanche.PChain()).toBeInstanceOf(PlatformVMAPI) - - expect(avalanche.NodeKeys()).not.toBeInstanceOf(PlatformVMAPI) - expect(avalanche.NodeKeys()).toBeInstanceOf(KeystoreAPI) - - expect(avalanche.Metrics()).not.toBeInstanceOf(KeystoreAPI) - expect(avalanche.Metrics()).toBeInstanceOf(MetricsAPI) - - expect(avalanche.Admin().getRPCID()).toBe(1) - expect(avalanche.XChain().getRPCID()).toBe(1) - expect(avalanche.PChain().getRPCID()).toBe(1) - expect(avalanche.NodeKeys().getRPCID()).toBe(1) - }) - - test("Create new API", (): void => { - avalanche.addAPI("avm2", AVMAPI) - expect(avalanche.api("avm2")).toBeInstanceOf(AVMAPI) - - avalanche.addAPI("keystore2", KeystoreAPI, "/ext/keystore2") - expect(avalanche.api("keystore2")).toBeInstanceOf(KeystoreAPI) - - avalanche.api("keystore2").setBaseURL("/ext/keystore3") - expect(avalanche.api("keystore2").getBaseURL()).toBe("/ext/keystore3") - - expect(avalanche.api("keystore2").getDB()).toHaveProperty("namespace") - }) - - test("Customize headers", (): void => { - avalanche.setHeader("X-Custom-Header", "example") - avalanche.setHeader("X-Foo", "Foo") - avalanche.setHeader("X-Bar", "Bar") - expect(avalanche.getHeaders()).toStrictEqual({ - "X-Custom-Header": "example", - "X-Foo": "Foo", - "X-Bar": "Bar" - }) - avalanche.removeHeader("X-Foo") - expect(avalanche.getHeaders()).toStrictEqual({ - "X-Custom-Header": "example", - "X-Bar": "Bar" - }) - avalanche.removeAllHeaders() - expect(avalanche.getHeaders()).toStrictEqual({}) - }) - - test("Customize request config", (): void => { - expect(avalanche.getRequestConfig()).toStrictEqual({}) - avalanche.setRequestConfig("withCredentials", true) - avalanche.setRequestConfig("withFoo", "Foo") - avalanche.setRequestConfig("withBar", "Bar") - expect(avalanche.getRequestConfig()).toStrictEqual({ - withCredentials: true, - withFoo: "Foo", - withBar: "Bar" - }) - avalanche.removeRequestConfig("withFoo") - expect(avalanche.getRequestConfig()).toStrictEqual({ - withCredentials: true, - withBar: "Bar" - }) - avalanche.removeAllRequestConfigs() - expect(avalanche.getRequestConfig()).toStrictEqual({}) - }) -}) - -describe("HTTP Operations", (): void => { - const host: string = "127.0.0.1" - const port: number = 8080 - const protocol: string = "http" - const path: string = "/ext/testingrequests" - let avalanche: Avalanche - beforeAll((): void => { - avalanche = new Avalanche( - host, - port, - protocol, - 12345, - undefined, - undefined, - undefined, - true - ) - avalanche.addAPI("testingrequests", TestAPI, path) - }) - - afterEach((): void => { - mockAxios.reset() - }) - - test("GET works", async (): Promise => { - const input: string = "TestGET" - const api: TestAPI = avalanche.api("testingrequests") - const result: Promise = api.TestGET(input, `/${input}`) - const payload: object = { - result: { - output: input - } - } - const responseObj: HttpResponse = { - data: payload - } - mockAxios.mockResponse(responseObj) - const response: any = await result - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response.output).toBe(input) - }) - - test("DELETE works", async (): Promise => { - const input: string = "TestDELETE" - const api: TestAPI = avalanche.api("testingrequests") - const axiosConfig: AxiosRequestConfig = { - baseURL: `${protocol}://${host}:${port}`, - responseType: "text" - } - const result: Promise = api.TestDELETE( - input, - `/${input}`, - axiosConfig - ) - const payload: object = { - result: { - output: input - } - } - const responseObj: HttpResponse = { - data: payload - } - mockAxios.mockResponse(responseObj) - const response: any = await result - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response.output).toBe(input) - }) - - test("POST works", async (): Promise => { - const input: string = "TestPOST" - const api: TestAPI = avalanche.api("testingrequests") - const result: Promise = api.TestPOST(input, `/${input}`) - const payload: object = { - result: { - output: input - } - } - const responseObj: HttpResponse = { - data: payload - } - mockAxios.mockResponse(responseObj) - const response: any = await result - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response.output).toBe(input) - }) - - test("PUT works", async (): Promise => { - const input: string = "TestPUT" - const api: TestAPI = avalanche.api("testingrequests") - const result: Promise = api.TestPUT(input, `/${input}`) - const payload: object = { - result: { - output: input - } - } - const responseObj: HttpResponse = { - data: payload - } - mockAxios.mockResponse(responseObj) - const response: any = await result - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response.output).toBe(input) - }) - - test("PATCH works", async (): Promise => { - const input: string = "TestPATCH" - const api: TestAPI = avalanche.api("testingrequests") - const result: Promise = api.TestPATCH(input, `/${input}`) - const payload: object = { - result: { - output: input - } - } - const responseObj: HttpResponse = { - data: payload - } - mockAxios.mockResponse(responseObj) - const response: any = await result - expect(mockAxios.request).toHaveBeenCalledTimes(1) - expect(response.output).toBe(input) - }) -}) diff --git a/tests/common/payload.test.ts b/tests/common/payload.test.ts deleted file mode 100644 index 9eeae2d7e..000000000 --- a/tests/common/payload.test.ts +++ /dev/null @@ -1,207 +0,0 @@ -import { Buffer } from "buffer/" -import { - PayloadTypes, - BINPayload, - PayloadBase, - UTF8Payload, - HEXSTRPayload, - B58STRPayload, - B64STRPayload, - BIGNUMPayload, - XCHAINADDRPayload, - PCHAINADDRPayload, - CCHAINADDRPayload, - TXIDPayload, - JSONPayload, - EMAILPayload -} from "../../src/utils/payload" -import BinTools from "../../src/utils/bintools" -import BN from "bn.js" -import * as bech32 from "bech32" -const payloadTypes: PayloadTypes = PayloadTypes.getInstance() -const bintools: BinTools = BinTools.getInstance() - -describe("Payload", (): void => { - const hrp: string = "tests" - - const cb58str: string = "MBcQpm1PsdfBKYscN3AYP56MusRDMZGF9" - const cb58buf: string = bintools.bufferToB58(bintools.cb58Decode(cb58str)) - const bech: string = bech32.bech32.encode( - hrp, - bech32.bech32.toWords(bintools.b58ToBuffer(cb58buf)) - ) - const binstr: string = "Bx4v7ytutz3" - const utf8str: string = "I am the very model of a modern Major-General." - const utf8b58: string = bintools.bufferToB58(Buffer.from(utf8str)) - const utf8hex: string = Buffer.from(utf8str).toString("hex") - const utf8b64: string = Buffer.from(utf8str).toString("base64") - const bnhex: string = "deadbeef" - const svgstr: string = "hi mom" - const csvstr: string = - "1,2,3,4,5\neverybody,in the,house,come along, let's ride" - const jsonobj: object = { boom: "goes the dynamite" } - const yamlstr: string = - "---\nrootproperty: blah\nsection:\n one: two\n three: four\n Foo: Bar\n empty: ~" - const emailstr: string = "example@example.com" - const urlstr: string = "https://example.com" - const ipfsstr: string = "QmUy4jh5mGNZvLkjies1RWM4YuvJh5o2FYopNPVYwrRVGV" - const onionstr: string = "https://el33th4xor.onion" - const magnetstr: string = - "magnet:?xt=urn:btih:c12fe1c06bba254a9dc9f519b335aa7c1367a88a" - - test("PayloadTypes", (): void => { - expect((): void => { - payloadTypes.select(867309) - }).toThrow() - - expect(payloadTypes.lookupID("BIN")).toBe(0) - - const binpayload = payloadTypes.select(0, binstr) as BINPayload - const utf8payload = payloadTypes.select(1, utf8str) as UTF8Payload - const hexstrpayload = payloadTypes.select(2, bnhex) as HEXSTRPayload - const emailpayload = payloadTypes.select(26, emailstr) as EMAILPayload - - expect(payloadTypes.getTypeID(binpayload.toBuffer())).toBe(0) - expect(payloadTypes.getTypeID(utf8payload.toBuffer())).toBe(1) - expect(payloadTypes.getTypeID(hexstrpayload.toBuffer())).toBe(2) - expect(payloadTypes.getTypeID(emailpayload.toBuffer())).toBe(26) - - const pp: Buffer = payloadTypes.getContent(binpayload.toBuffer()) - - expect(bintools.b58ToBuffer(binstr).toString("hex")).toBe( - pp.toString("hex") - ) - expect(payloadTypes.lookupType(0)).toBe("BIN") - expect(payloadTypes.recast(binpayload).toBuffer().toString("hex")).toBe( - binpayload.toBuffer().toString("hex") - ) - }) - - const testTable: any[] = [ - ["BIN", binstr, binstr], - ["UTF8", utf8str, utf8b58], - ["HEXSTR", utf8hex, utf8b58], - ["B58STR", utf8b58, utf8b58], - ["B64STR", utf8b64, utf8b58], - ["BIGNUM", bnhex, bintools.bufferToB58(Buffer.from(bnhex, "hex"))], - ["XCHAINADDR", "X-" + bech, cb58buf], - ["PCHAINADDR", "P-" + bech, cb58buf], - ["CCHAINADDR", "C-" + bech, cb58buf], - ["TXID", cb58str, cb58buf], - ["ASSETID", cb58str, cb58buf], - ["UTXOID", cb58str, cb58buf], - ["NFTID", cb58str, cb58buf], - ["SUBNETID", cb58str, cb58buf], - ["CHAINID", cb58str, cb58buf], - ["NODEID", cb58str, cb58buf], - ["SECPSIG", cb58str, cb58str], - ["SECPENC", cb58str, cb58str], - ["JPEG", binstr, binstr], - ["PNG", binstr, binstr], - ["BMP", binstr, binstr], - ["ICO", binstr, binstr], - ["SVG", svgstr, bintools.bufferToB58(Buffer.from(svgstr))], - ["CSV", csvstr, bintools.bufferToB58(Buffer.from(csvstr))], - [ - "JSON", - JSON.stringify(jsonobj), - bintools.bufferToB58(Buffer.from(JSON.stringify(jsonobj))) - ], - ["YAML", yamlstr, bintools.bufferToB58(Buffer.from(yamlstr))], - ["EMAIL", emailstr, bintools.bufferToB58(Buffer.from(emailstr))], - ["URL", urlstr, bintools.bufferToB58(Buffer.from(urlstr))], - ["IPFS", ipfsstr, ipfsstr], - ["ONION", onionstr, bintools.bufferToB58(Buffer.from(onionstr))], - ["MAGNET", magnetstr, bintools.bufferToB58(Buffer.from(magnetstr))] - ] - test.each(testTable)( - "Basic Payload Test: typestr %s input %s inputbuff %s", - (typestr: string, inputstr: string, inputbuff: string): void => { - const buff: Buffer = bintools.b58ToBuffer(inputbuff) - const typeid: number = payloadTypes.lookupID(typestr) - const typename: string = payloadTypes.lookupType(typeid) - expect(typename).toBe(typestr) - const c0: PayloadBase = payloadTypes.select(typeid) - expect(c0.typeID()).toBe(typeid) - expect(c0.typeName()).toBe(typename) - const c1: PayloadBase = payloadTypes.select(typeid, buff) - const c2: PayloadBase = payloadTypes.select(typeid, inputstr, hrp) - const c3: PayloadBase = payloadTypes.select(typeid) - c3.fromBuffer(c1.toBuffer()) - const c4: PayloadBase = payloadTypes.select(typeid) - c4.fromBuffer(c2.toBuffer()) - - const s1: string = c1.toBuffer().toString("hex") - const s2: string = c2.toBuffer().toString("hex") - const s3: string = c3.toBuffer().toString("hex") - const s4: string = c4.toBuffer().toString("hex") - - expect(s1).toBe(s2) - expect(s2).toBe(s3) - expect(s3).toBe(s4) - } - ) - - test("BINPayload special cases", (): void => { - const pl: BINPayload = payloadTypes.select(0, binstr) as BINPayload - expect(bintools.bufferToB58(pl.returnType())).toBe(binstr) - }) - - test("UTF8Payload special cases", (): void => { - const pl: UTF8Payload = new UTF8Payload(utf8str) - expect(pl.returnType()).toBe(utf8str) - }) - - test("HEXSTRPayload special cases", (): void => { - const pl: HEXSTRPayload = new HEXSTRPayload(utf8hex) - expect(pl.returnType()).toBe(utf8hex) - }) - - test("B58STRPayload special cases", (): void => { - const pl: B58STRPayload = new B58STRPayload(utf8b58) - expect(pl.returnType()).toBe(utf8b58) - }) - - test("B64STRPayload special cases", (): void => { - const pl: B64STRPayload = new B64STRPayload(utf8b64) - expect(pl.returnType()).toBe(utf8b64) - }) - - test("BIGNUMPayload special cases", (): void => { - const jenny: BN = new BN(8675309) - const pl: BIGNUMPayload = new BIGNUMPayload(jenny) - expect(pl.returnType().toString("hex")).toBe(jenny.toString("hex")) - }) - - test("XCHAINADDRPayload special cases", (): void => { - const addr: string = `X-${bech}` - const pl: XCHAINADDRPayload = new XCHAINADDRPayload(addr, hrp) - expect(pl.returnType(hrp)).toBe(addr) - expect(pl.returnChainID()).toBe("X") - }) - - test("PCHAINADDRPayload special cases", (): void => { - const addr: string = `P-${bech}` - const pl: PCHAINADDRPayload = new PCHAINADDRPayload(addr, hrp) - expect(pl.returnType(hrp)).toBe(addr) - expect(pl.returnChainID()).toBe("P") - }) - - test("CCHAINADDRPayload special cases", (): void => { - const addr: string = `C-${bech}` - const pl: CCHAINADDRPayload = new CCHAINADDRPayload(addr, hrp) - expect(pl.returnType(hrp)).toBe(addr) - expect(pl.returnChainID()).toBe("C") - }) - - // handles all of cb58EncodedPayload - test("TXIDPayload special cases", (): void => { - const pl: TXIDPayload = new TXIDPayload(cb58str) - expect(pl.returnType()).toBe(cb58str) - }) - - test("JSONPayload special cases", (): void => { - const pl: JSONPayload = new JSONPayload(jsonobj) - expect(JSON.stringify(pl.returnType())).toBe(JSON.stringify(jsonobj)) - }) -}) diff --git a/tests/common/secp256k1.test.ts b/tests/common/secp256k1.test.ts deleted file mode 100644 index d3cfe824a..000000000 --- a/tests/common/secp256k1.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { Buffer } from "buffer/" -import BinTools from "../../src/utils/bintools" -import { KeyPair } from "src/apis/evm" - -const bintools: BinTools = BinTools.getInstance() - -describe("SECP256K1", (): void => { - test("addressFromPublicKey", (): void => { - const pubkeys: string[] = [ - "7ECaZ7TpWLq6mh3858DkR3EzEToGi8iFFxnjY5hUGePoCHqdjw", - "5dS4sSyL4dHziqLYanMoath8dqUMe6ZkY1VbnVuQQSsCcgtVET" - ] - const addrs: string[] = [ - "b0c9654511ebb78d490bb0d7a54997d4a933972c", - "d5bb99a29e09853da983be63a76f02259ceedf15" - ] - pubkeys.forEach((pubkey: string, index: number): void => { - const pubkeyBuf: Buffer = bintools.cb58Decode(pubkey) - const addrBuf: Buffer = KeyPair.addressFromPublicKey(pubkeyBuf) - expect(addrBuf.toString("hex")).toBe(addrs[index]) - }) - }) -}) diff --git a/tests/testlib.ts b/tests/testlib.ts deleted file mode 100644 index 4ed4b9aca..000000000 --- a/tests/testlib.ts +++ /dev/null @@ -1,75 +0,0 @@ -import AvalancheCore from "../src/avalanche" -import { AxiosRequestConfig } from "axios" -import { APIBase, RequestResponseData } from "../src/common/apibase" - -export class TestAPI extends APIBase { - TestGET = async ( - input: string, - path: string = "", - axiosConfig: AxiosRequestConfig = undefined - ): Promise => this._TestMethod("get", path, { input }, axiosConfig) - TestDELETE = async ( - input: string, - path: string = "", - axiosConfig: AxiosRequestConfig = undefined - ): Promise => this._TestMethod("delete", path, { input }, axiosConfig) - TestPOST = async ( - input: string, - path: string = "", - axiosConfig: AxiosRequestConfig = undefined - ): Promise => - this._TestMethod("post", path, {}, { input }, axiosConfig) - TestPUT = async ( - input: string, - path: string = "", - axiosConfig: AxiosRequestConfig = undefined - ): Promise => - this._TestMethod("put", path, {}, { input }, axiosConfig) - TestPATCH = async ( - input: string, - path: string = "", - axiosConfig: AxiosRequestConfig = undefined - ): Promise => - this._TestMethod("patch", path, {}, { input }, axiosConfig) - - protected _respFn = (res: RequestResponseData): any => { - let response: any - if (typeof res.data === "string") { - response = JSON.parse(res.data) - } else { - response = res.data as object - } - return response.result - } - - protected _TestMethod = async ( - method: string, - path: string = "", - getdata: object = {}, - postdata: object = undefined, - axiosConfig: AxiosRequestConfig = undefined - ): Promise => { - if (postdata === undefined) { - const res: RequestResponseData = await this.core[method]( - this.baseURL + path, - getdata, - {}, - axiosConfig - ) - return this._respFn(res) - } - const res: RequestResponseData = await this.core[method]( - this.baseURL + path, - getdata, - postdata, - {}, - axiosConfig - ) - res.data = JSON.stringify(res.data) // coverage completeness - return this._respFn(res) - } - - constructor(avax: AvalancheCore, endpoint: string = "/ext/testing") { - super(avax, endpoint) - } -} diff --git a/tests/utils/bintools.test.ts b/tests/utils/bintools.test.ts deleted file mode 100644 index 6c6f48542..000000000 --- a/tests/utils/bintools.test.ts +++ /dev/null @@ -1,416 +0,0 @@ -import BinTools from "src/utils/bintools" -import BN from "bn.js" -import { Buffer } from "buffer/" - -const bintools: BinTools = BinTools.getInstance() - -describe("BinTools", (): void => { - const hexstr: string = "00112233445566778899aabbccddeeff" - const hexstr2: string = "0001020304050607080909080706050403020100" - const hexstr3: string = "0001020304050607080909080706050403020101" - const hexbuffstr1: string = "000461736466" // = asdf - const hexbuffstr2: string = "000761626364656667" // = abcdefg - const hexbuffstr3: string = "00076f6b0066696e65" // = okfineokfine - const b58str: string = "1UoWww8DGaVGLtea7zU7p" - const b58str2: string = "1Bhh3pU9gLXZiJv73kmqZwHJ4F" - const b58str3: string = "1Bhh3pU9gLXZiJv73kmqZwHJ4G" - const buff: Buffer = Buffer.from(hexstr, "hex") - const buff2: Buffer = Buffer.from(hexstr2, "hex") - const buff3: Buffer = Buffer.from(hexstr3, "hex") - const checksum: string = "323e6811" - const serializedChecksum: string = "148vjpuxYXixb8DcbaWyeDE2fEG" // serialized hexstr + checksum - const longSerializedChecksum: string = - "111Bit5JNASbJyTLrd2kWkYRoc96swEWoWdmEhuGAFK3rCAyTnTzomuFwgx1SCUdUE71KbtXPnqj93KGr3CeftpPN37kVyqBaAQ5xaDjr7wVBTUYi9iV7kYJnHF61yovViJF74mJJy7WWQKeRMDRTiPuii5gsd11gtNahCCsKbm9seJtk2h1wAPZn9M1eL84CGVPnLUiLP" // serialized hexstr + checksum - const checksummedHexStr = - "0x00000009de31b4d8b22991d51aa6aa1fc733f23a851a8c9400000000000186a0000000005f041280000000005f9ca900000030390000000000000001fceda8f90fcb5d30614b99d79fc4baa29307762668f16eb0259a57c2d3b78c875c86ec2045792d4df2d926c40f829196e0bb97ee697af71f5b0a966dabff749634c8b729855e937715b0e44303fd1014daedc752006011b730" - test("copyFrom conducts a true copy", (): void => { - const buff: Buffer = Buffer.from(hexstr, "hex") - const newbuff: Buffer = bintools.copyFrom(buff, 0, 10) - expect(newbuff.length).toBe(10) - expect(newbuff.readUInt8(0)).toBe(0) - expect(newbuff.readUInt8(9)).toBe(153) - // verify that the original buffer isn't touched by writes - newbuff.writeUInt8(153, 4) - expect(newbuff.readUInt8(4)).toBe(153) - expect(buff.readUInt8(4)).toBe(68) - // test with no end specified - const newbuff2: Buffer = bintools.copyFrom(buff, 2) - expect(newbuff2.length).toBe(14) - expect(newbuff2.readUInt8(0)).toBe(34) - expect(newbuff2.readUInt8(7)).toBe(153) - }) - - test("bufferToString", (): void => { - const bres: string = bintools.bufferToString( - Buffer.from(hexbuffstr1, "hex") - ) - expect(bres).toBe(Buffer.from(hexbuffstr1.slice(4), "hex").toString("utf8")) - // testing null character edge case - const bres2: string = bintools.bufferToString( - Buffer.from(hexbuffstr2, "hex") - ) - expect(bres2).toBe( - Buffer.from(hexbuffstr2.slice(4), "hex").toString("utf8") - ) - // testing null character edge case - const bres3: string = bintools.bufferToString( - Buffer.from(hexbuffstr3, "hex") - ) - expect(bres3).toBe( - Buffer.from(hexbuffstr3.slice(4), "hex").toString("utf8") - ) - }) - - test("stringToBuffer", (): void => { - const bres: Buffer = bintools.stringToBuffer("asdf") - expect(bres.slice(2).toString()).toBe( - Buffer.from(hexbuffstr1.slice(4), "hex").toString("utf8") - ) - // testing null character edge case - const bres2: Buffer = bintools.stringToBuffer("abcdefg") - expect(bres2.slice(2).toString()).toBe( - Buffer.from(hexbuffstr2.slice(4), "hex").toString("utf8") - ) - // testing null character edge case - const bres3: Buffer = bintools.stringToBuffer( - Buffer.from(hexbuffstr3.slice(4), "hex").toString("utf8") - ) - expect(bres3.slice(2).toString()).toBe( - Buffer.from(hexbuffstr3.slice(4), "hex").toString("utf8") - ) - }) - - test("bufferToB58", (): void => { - const b58res: string = bintools.bufferToB58(buff) - expect(b58res).toBe(b58str) - // testing null character edge case - const b58res2: string = bintools.bufferToB58(buff2) - expect(b58res2).toBe(b58str2) - // testing null character edge case - const b58res3: string = bintools.bufferToB58(buff3) - expect(b58res3).toBe(b58str3) - }) - - test("b58ToBuffer", (): void => { - expect((): void => { - bintools.b58ToBuffer("0OO0O not a valid b58 string 0OO0O") - }).toThrow("Error - Base58.decode: not a valid base58 string") - - const buffres: Buffer = bintools.b58ToBuffer(b58str) - expect(buffres.toString()).toBe(buff.toString()) - // testing zeros character edge case - const buffres2: Buffer = bintools.b58ToBuffer(b58str2) - expect(buffres2.toString()).toBe(buff2.toString()) - // testing zeros character edge case - const buffres3: Buffer = bintools.b58ToBuffer(b58str3) - expect(buffres3.toString()).toBe(buff3.toString()) - }) - - test("fromBufferToArrayBuffer", (): void => { - const arrbuff: ArrayBuffer = bintools.fromBufferToArrayBuffer(buff) - expect(arrbuff.byteLength).toBe(buff.length) - for (let i: number = 0; i < buff.length; i++) { - expect(arrbuff[i]).toBe(buff[i]) - } - // verify that the original buffer isn't touched by writes - arrbuff[2] = 55 - expect(buff[2]).not.toBe(55) - }) - - test("fromArrayBufferToBuffer", (): void => { - const arrbuff: ArrayBuffer = new ArrayBuffer(10) - for (let i: number = 0; i < 10; i++) { - arrbuff[i] = i - } - const newbuff: Buffer = bintools.fromArrayBufferToBuffer(arrbuff) - expect(newbuff.length).toBe(arrbuff.byteLength) - for (let i: number = 0; i < newbuff.length; i++) { - expect(newbuff[i]).toBe(arrbuff[i]) - } - // verify that the original buffer isnt touched by writes - newbuff[3] = 55 - expect(arrbuff[3]).not.toBe(newbuff[3]) - }) - - test("fromBufferToBN", (): void => { - const bign: BN = bintools.fromBufferToBN(buff) - expect(bign.toString("hex", hexstr.length)).toBe(hexstr) - }) - - test("fromBNToBuffer", (): void => { - const bn1: BN = new BN(hexstr, "hex", "be") - const bn2: BN = new BN(hexstr, "hex", "be") - const b1: Buffer = bintools.fromBNToBuffer(bn1) - const b2: Buffer = bintools.fromBNToBuffer(bn2, buff.length) - - expect(b1.length).toBe(buff.length - 1) - expect(b1.toString("hex")).toBe(hexstr.slice(2)) - - expect(b2.length).toBe(buff.length) - expect(b2.toString("hex")).toBe(hexstr) - }) - - test("addChecksum", (): void => { - const buffchecked: Buffer = bintools.addChecksum(buff) - expect(buffchecked.length).toBe(buff.length + 4) - expect(buffchecked.slice(16).toString("hex")).toBe(checksum) - }) - - test("validteChecksum", (): void => { - const checksummed: string = hexstr + checksum - const badsummed: string = `${hexstr}324e7822` - expect(bintools.validateChecksum(Buffer.from(checksummed, "hex"))).toBe( - true - ) - expect(bintools.validateChecksum(buff)).toBe(false) - expect(bintools.validateChecksum(Buffer.from(badsummed, "hex"))).toBe(false) - }) - - test("cb58Encode", (): void => { - const fromBuff: string = bintools.cb58Encode(buff) - expect(fromBuff).toBe(serializedChecksum) - }) - - test("cb58Decode", (): void => { - const serbuff: Buffer = bintools.b58ToBuffer(serializedChecksum) - const dsr1: Buffer = bintools.cb58Decode(serializedChecksum) - const dsr2: Buffer = bintools.cb58Decode(serbuff) - const serbufffaulty: Buffer = bintools.copyFrom(serbuff) - serbufffaulty[serbufffaulty.length - 1] = - serbufffaulty[serbufffaulty.length - 1] - 1 - expect(dsr1.toString("hex")).toBe(hexstr) - expect(dsr2.toString("hex")).toBe(hexstr) - expect((): void => { - bintools.cb58Decode(serbufffaulty) - }).toThrow("Error - BinTools.cb58Decode: invalid checksum") - }) - - test("cb58DecodeWithChecksum", (): void => { - const serbuff: Buffer = bintools.b58ToBuffer(longSerializedChecksum) - const dsr1: string = bintools.cb58DecodeWithChecksum(longSerializedChecksum) - const dsr2: string = bintools.cb58DecodeWithChecksum(serbuff) - const serbufffaulty: Buffer = bintools.copyFrom(serbuff) - serbufffaulty[serbufffaulty.length - 1] = - serbufffaulty[serbufffaulty.length - 1] - 1 - expect(dsr1).toBe(checksummedHexStr) - expect(dsr2).toBe(checksummedHexStr) - expect((): void => { - bintools.cb58Decode(serbufffaulty) - }).toThrow("Error - BinTools.cb58Decode: invalid checksum") - }) - - test("isCB58", (): void => { - const validCB581: string = - "isGvtnDqETNmmFw7guSJ7mmWhCqboExrpmC8VsWxckHcH9oXb" - const validCB582: string = - "2PwX8qwMHbwVAm28howu3Ef7Lk4ib2XG7AaY9aK8dTTGNXQkCz" - const invalidCB581: string = - "ddd.tnDqETNmmFw7guSJ7mmWhCqboExrpmC8VsWxckHcHzzzz" - const invalidCB582: string = "" - expect(bintools.isCB58(validCB581)).toBe(true) - expect(bintools.isCB58(validCB582)).toBe(true) - expect(bintools.isCB58(invalidCB581)).toBe(false) - expect(bintools.isCB58(invalidCB582)).toBe(false) - }) - - test("isBase58", (): void => { - const validBase581: string = - "isGvtnDqETNmmFw7guSJ7mmWhCqboExrpmC8VsWxckHcH9oXb" - const validBase582: string = - "2PwX8qwMHbwVAm28howu3Ef7Lk4ib2XG7AaY9aK8dTTGNXQkCz" - const invalidBase581: string = - "ddd.tnDqETNmmFw7guSJ7mmWhCqboExrpmC8VsWxckHcHzzzz" - const invalidBase582: string = "" - expect(bintools.isBase58(validBase581)).toBe(true) - expect(bintools.isBase58(validBase582)).toBe(true) - expect(bintools.isBase58(invalidBase581)).toBe(false) - expect(bintools.isBase58(invalidBase582)).toBe(false) - }) - - test("isHex", (): void => { - const validHex1: string = - "0x95eaac2b7a6ee7ad7e597c2f5349b03e461c36c2e1e50fc98a84d01612940bd5" - const validHex2: string = - "95eaac2b7a6ee7ad7e597c2f5349b03e461c36c2e1e50fc98a84d01612940bd5" - const invalidHex1: string = - "rrrrr.c2b7a6ee7ad7e597c2f5349b03e461c36c2e1e5.fc98a84d016129zzzzz" - const invalidHex2: string = - "0x95eaac2b7a6ee7ad7e597c2f5349b03e461c36c2e1e50fc98a84d016129zzzz" - const invalidHex3: string = - "95eaac2b7a6ee7ad7e597c2f5349b03e461c36c2e1e50fc98a84d016129zzzz" - const invalidHex4: string = - "isGvtnDqETNmmFw7guSJ7mmWhCqboExrpmC8VsWxckHcH9oXb" - const invalidHex5: string = "" - const invalidHex6: string = " " - expect(bintools.isHex(validHex1)).toBe(true) - expect(bintools.isHex(validHex2)).toBe(true) - expect(bintools.isHex(invalidHex1)).toBe(false) - expect(bintools.isHex(invalidHex2)).toBe(false) - expect(bintools.isHex(invalidHex3)).toBe(false) - expect(bintools.isHex(invalidHex3)).toBe(false) - expect(bintools.isHex(invalidHex5)).toBe(false) - expect(bintools.isHex(invalidHex6)).toBe(false) - }) - - test("stringToAddress", (): void => { - // Missing prefix - let addr: string = "-avax13a4ye34zdfa33zeg3udnz533d6msfuqkds9hq7" - expect((): void => { - bintools.stringToAddress(addr) - }).toThrow("Error - Valid address must have prefix before -") - - // Missing - - addr = "Xavax13a4ye34zdfa33zeg3udnz533d6msfuqkds9hq7" - expect((): void => { - bintools.stringToAddress(addr) - }).toThrow("Error - Valid address should include -") - - // Missing seperator (1) - addr = "X-avax3a4ye34zdfa33zeg3udnz533d6msfuqkds9hq7" - expect((): void => { - bintools.stringToAddress(addr) - }).toThrow("Error - Valid address must include separator (1)") - - // Missing HRP - addr = "X-13a4ye34zdfa33zeg3udnz533d6msfuqkds9hq7" - expect((): void => { - bintools.stringToAddress(addr) - }).toThrow("Error - HRP should be at least 1 character") - - // Invalid HRP - addr = "X-avax11ycxp65vz60m87mkm2hsw3m5fadjlpldzntvr33" - expect((): void => { - bintools.stringToAddress(addr) - }).toThrow("Error - Invalid HRP") - - // Extra character in data bytes - addr = "X-local1dcfyuug87xqayl4fpp02z9dvknwhafdswtvnucd" - expect((): void => { - bintools.stringToAddress(addr) - }).toThrow( - "Invalid checksum for local1dcfyuug87xqayl4fpp02z9dvknwhafdswtvnucd" - ) - - // Change character in data bytes - addr = "X-local1dcfyuug8fxqayl4fpp02z9dvknwhafdstvnucd" - expect((): void => { - bintools.stringToAddress(addr) - }).toThrow( - "Invalid checksum for local1dcfyuug8fxqayl4fpp02z9dvknwhafdstvnucd" - ) - - // Invalid character in data bytes - addr = "X-local1dcfyuug87xqbyl4fpp02z9dvknwhafdstvnucd" - expect((): void => { - bintools.stringToAddress(addr) - }).toThrow("Unknown character b") - - // Change character in checksum - addr = "X-local1dcfyuug87xqayl4fpp02z9dvknwhafdstvnuce" - expect((): void => { - bintools.stringToAddress(addr) - }).toThrow( - "Invalid checksum for local1dcfyuug87xqayl4fpp02z9dvknwhafdstvnuce" - ) - - // Invalid ETH-style address - addr = "0x.db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC" - expect((): void => { - bintools.stringToAddress(addr) - }).toThrow("Error - Invalid address") - - let addrs: string[] = [ - "X-local1dcfyuug87xqayl4fpp02z9dvknwhafdstvnucd", - "X-local1ltghj033re64920k786uprcp82p9e36j7hzc5x", - "X-local1dq4q9seql2spxrkd7rl82uck5ej3nvlhrluh4u" - ] - addrs.forEach((address: string): void => { - bintools.stringToAddress(address) - }) - addrs = [ - "X-fuji1dcfyuug87xqayl4fpp02z9dvknwhafds7d29h6", - "X-fuji1ltghj033re64920k786uprcp82p9e36jtkmpm3", - "X-fuji1dq4q9seql2spxrkd7rl82uck5ej3nvlhk79w6t" - ] - addrs.forEach((address: string): void => { - bintools.stringToAddress(address) - }) - addrs = [ - "X-avax1dcfyuug87xqayl4fpp02z9dvknwhafdsjlw6m9", - "X-avax1ltghj033re64920k786uprcp82p9e36j8yl7hw", - "X-avax1dq4q9seql2spxrkd7rl82uck5ej3nvlh6vp3k5" - ] - addrs.forEach((address: string): void => { - bintools.stringToAddress(address) - }) - addrs = [ - "P-local1dcfyuug87xqayl4fpp02z9dvknwhafdstvnucd", - "P-local1ltghj033re64920k786uprcp82p9e36j7hzc5x", - "P-local1dq4q9seql2spxrkd7rl82uck5ej3nvlhrluh4u" - ] - addrs.forEach((address: string): void => { - bintools.stringToAddress(address) - }) - addrs = [ - "P-fuji1dcfyuug87xqayl4fpp02z9dvknwhafds7d29h6", - "P-fuji1ltghj033re64920k786uprcp82p9e36jtkmpm3", - "P-fuji1dq4q9seql2spxrkd7rl82uck5ej3nvlhk79w6t" - ] - addrs.forEach((address: string): void => { - bintools.stringToAddress(address) - }) - addrs = [ - "P-avax1dcfyuug87xqayl4fpp02z9dvknwhafdsjlw6m9", - "P-avax1ltghj033re64920k786uprcp82p9e36j8yl7hw", - "P-avax1dq4q9seql2spxrkd7rl82uck5ej3nvlh6vp3k5" - ] - addrs.forEach((address: string): void => { - bintools.stringToAddress(address) - }) - - addrs = [ - "C-local1dcfyuug87xqayl4fpp02z9dvknwhafdstvnucd", - "C-local1ltghj033re64920k786uprcp82p9e36j7hzc5x", - "C-local1dq4q9seql2spxrkd7rl82uck5ej3nvlhrluh4u" - ] - addrs.forEach((address: string): void => { - bintools.stringToAddress(address) - }) - - addrs = [ - "C-fuji1dcfyuug87xqayl4fpp02z9dvknwhafds7d29h6", - "C-fuji1ltghj033re64920k786uprcp82p9e36jtkmpm3", - "C-fuji1dq4q9seql2spxrkd7rl82uck5ej3nvlhk79w6t" - ] - addrs.forEach((address: string): void => { - bintools.stringToAddress(address) - }) - - addrs = [ - "C-avax1dcfyuug87xqayl4fpp02z9dvknwhafdsjlw6m9", - "C-avax1ltghj033re64920k786uprcp82p9e36j8yl7hw", - "C-avax1dq4q9seql2spxrkd7rl82uck5ej3nvlh6vp3k5" - ] - addrs.forEach((address: string): void => { - bintools.stringToAddress(address) - }) - - addrs = [ - "X-foo1dcfyuug87xqayl4fpp02z9dvknwhafds4k3km3", - "X-foo1ltghj033re64920k786uprcp82p9e36jqdqjh6", - "X-foo1dq4q9seql2spxrkd7rl82uck5ej3nvlha97akq" - ] - addrs.forEach((address: string): void => { - bintools.stringToAddress(address, "foo") - }) - - addrs = [ - "0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC", - "0xC1ad78FDd4aEd027EbD5e9eee878f44dc1E29358", - "0x5B44bC2622dc5DD66a94cd5f2aDc3a49abb864dE" - ] - addrs.forEach((address: string): void => { - bintools.stringToAddress(address) - }) - }) -}) diff --git a/tests/utils/db.test.ts b/tests/utils/db.test.ts deleted file mode 100644 index c1103b297..000000000 --- a/tests/utils/db.test.ts +++ /dev/null @@ -1,9 +0,0 @@ -import DB from "src/utils/db" - -describe("DB", (): void => { - test("instantiate singletone", (): void => { - const db1: DB = DB.getInstance() - const db2: DB = DB.getInstance() - expect(db1).toEqual(db2) - }) -}) diff --git a/tests/utils/errors.test.ts b/tests/utils/errors.test.ts deleted file mode 100644 index 052f6280e..000000000 --- a/tests/utils/errors.test.ts +++ /dev/null @@ -1,665 +0,0 @@ -import BinTools from "../../src/utils/bintools" -import { - AvalancheError, - AddressError, - GooseEggCheckError, - ChainIdError, - NoAtomicUTXOsError, - SymbolError, - NameError, - TransactionError, - CodecIdError, - CredIdError, - TransferableOutputError, - TransferableInputError, - InputIdError, - OperationError, - InvalidOperationIdError, - ChecksumError, - OutputIdError, - UTXOError, - InsufficientFundsError, - ThresholdError, - SECPMintOutputError, - EVMInputError, - EVMOutputError, - FeeAssetError, - StakeError, - TimeError, - DelegationFeeError, - SubnetOwnerError, - BufferSizeError, - AddressIndexError, - PublicKeyError, - MergeRuleError, - Base58Error, - PrivateKeyError, - NodeIdError, - HexError, - TypeIdError, - TypeNameError, - UnknownTypeError, - Bech32Error, - EVMFeeError, - InvalidEntropy, - ProtocolError, - SubnetIdError -} from "src/utils" - -describe("Errors", (): void => { - test("AvalancheError", (): void => { - try { - throw new AvalancheError("Testing AvalancheError", "0") - } catch (error: any) { - expect(error.getCode()).toBe("0") - } - expect((): void => { - throw new AvalancheError("Testing AvalancheError", "0") - }).toThrow("Testing AvalancheError") - expect((): void => { - throw new AvalancheError("Testing AvalancheError", "0") - }).toThrowError() - }) - - test("AddressError", (): void => { - try { - throw new AddressError("Testing AddressError") - } catch (error: any) { - expect(error.getCode()).toBe("1000") - } - expect((): void => { - throw new AddressError("Testing AddressError") - }).toThrow("Testing AddressError") - expect((): void => { - throw new AddressError("Testing AddressError") - }).toThrowError() - }) - - test("GooseEggCheckError", (): void => { - try { - throw new GooseEggCheckError("Testing GooseEggCheckError") - } catch (error: any) { - expect(error.getCode()).toBe("1001") - } - expect((): void => { - throw new GooseEggCheckError("Testing GooseEggCheckError") - }).toThrow("Testing GooseEggCheckError") - expect((): void => { - throw new GooseEggCheckError("Testing GooseEggCheckError") - }).toThrowError() - }) - - test("ChainIdError", (): void => { - try { - throw new ChainIdError("Testing ChainIdError") - } catch (error: any) { - expect(error.getCode()).toBe("1002") - } - expect((): void => { - throw new ChainIdError("Testing ChainIdError") - }).toThrow("Testing ChainIdError") - expect((): void => { - throw new ChainIdError("Testing ChainIdError") - }).toThrowError() - }) - - test("NoAtomicUTXOsError", (): void => { - try { - throw new NoAtomicUTXOsError("Testing NoAtomicUTXOsError") - } catch (error: any) { - expect(error.getCode()).toBe("1003") - } - expect((): void => { - throw new NoAtomicUTXOsError("Testing NoAtomicUTXOsError") - }).toThrow("Testing NoAtomicUTXOsError") - expect((): void => { - throw new NoAtomicUTXOsError("Testing NoAtomicUTXOsError") - }).toThrowError() - }) - - test("SymbolError", (): void => { - try { - throw new SymbolError("Testing SymbolError") - } catch (error: any) { - expect(error.getCode()).toBe("1004") - } - expect((): void => { - throw new SymbolError("Testing SymbolError") - }).toThrow("Testing SymbolError") - expect((): void => { - throw new SymbolError("Testing SymbolError") - }).toThrowError() - }) - - test("NameError", (): void => { - try { - throw new NameError("Testing NameError") - } catch (error: any) { - expect(error.getCode()).toBe("1005") - } - expect((): void => { - throw new NameError("Testing NameError") - }).toThrow("Testing NameError") - expect((): void => { - throw new NameError("Testing NameError") - }).toThrowError() - }) - - test("TransactionError", (): void => { - try { - throw new TransactionError("Testing TransactionError") - } catch (error: any) { - expect(error.getCode()).toBe("1006") - } - expect((): void => { - throw new TransactionError("Testing TransactionError") - }).toThrow("Testing TransactionError") - expect((): void => { - throw new TransactionError("Testing TransactionError") - }).toThrowError() - }) - - test("CodecIdError", (): void => { - try { - throw new CodecIdError("Testing CodecIdError") - } catch (error: any) { - expect(error.getCode()).toBe("1007") - } - expect((): void => { - throw new CodecIdError("Testing CodecIdError") - }).toThrow("Testing CodecIdError") - expect((): void => { - throw new CodecIdError("Testing CodecIdError") - }).toThrowError() - }) - - test("CredIdError", (): void => { - try { - throw new CredIdError("Testing CredIdError") - } catch (error: any) { - expect(error.getCode()).toBe("1008") - } - expect((): void => { - throw new CredIdError("Testing CredIdError") - }).toThrow("Testing CredIdError") - expect((): void => { - throw new CredIdError("Testing CredIdError") - }).toThrowError() - }) - - test("TransferableOutputError", (): void => { - try { - throw new TransferableOutputError("Testing TransferableOutputError") - } catch (error: any) { - expect(error.getCode()).toBe("1009") - } - expect((): void => { - throw new TransferableOutputError("Testing TransferableOutputError") - }).toThrow("Testing TransferableOutputError") - expect((): void => { - throw new TransferableOutputError("Testing TransferableOutputError") - }).toThrowError() - }) - - test("TransferableInputError", (): void => { - try { - throw new TransferableInputError("Testing TransferableInputError") - } catch (error: any) { - expect(error.getCode()).toBe("1010") - } - expect((): void => { - throw new TransferableInputError("Testing TransferableInputError") - }).toThrow("Testing TransferableInputError") - expect((): void => { - throw new TransferableInputError("Testing TransferableInputError") - }).toThrowError() - }) - - test("InputIdError", (): void => { - try { - throw new InputIdError("Testing InputIdError") - } catch (error: any) { - expect(error.getCode()).toBe("1011") - } - expect((): void => { - throw new InputIdError("Testing InputIdError") - }).toThrow("Testing InputIdError") - expect((): void => { - throw new InputIdError("Testing InputIdError") - }).toThrowError() - }) - - test("OperationError", (): void => { - try { - throw new OperationError("Testing OperationError") - } catch (error: any) { - expect(error.getCode()).toBe("1012") - } - expect((): void => { - throw new OperationError("Testing OperationError") - }).toThrow("Testing OperationError") - expect((): void => { - throw new OperationError("Testing OperationError") - }).toThrowError() - }) - - test("InvalidOperationIdError", (): void => { - try { - throw new InvalidOperationIdError("Testing InvalidOperationIdError") - } catch (error: any) { - expect(error.getCode()).toBe("1013") - } - expect((): void => { - throw new InvalidOperationIdError("Testing InvalidOperationIdError") - }).toThrow("Testing InvalidOperationIdError") - expect((): void => { - throw new InvalidOperationIdError("Testing InvalidOperationIdError") - }).toThrowError() - }) - - test("ChecksumError", (): void => { - try { - throw new ChecksumError("Testing ChecksumError") - } catch (error: any) { - expect(error.getCode()).toBe("1014") - } - expect((): void => { - throw new ChecksumError("Testing ChecksumError") - }).toThrow("Testing ChecksumError") - expect((): void => { - throw new ChecksumError("Testing ChecksumError") - }).toThrowError() - }) - - test("OutputIdError", (): void => { - try { - throw new OutputIdError("Testing OutputIdError") - } catch (error: any) { - expect(error.getCode()).toBe("1015") - } - expect((): void => { - throw new OutputIdError("Testing OutputIdError") - }).toThrow("Testing OutputIdError") - expect((): void => { - throw new OutputIdError("Testing OutputIdError") - }).toThrowError() - }) - - test("UTXOError", (): void => { - try { - throw new UTXOError("Testing UTXOError") - } catch (error: any) { - expect(error.getCode()).toBe("1016") - } - expect((): void => { - throw new UTXOError("Testing UTXOError") - }).toThrow("Testing UTXOError") - expect((): void => { - throw new UTXOError("Testing UTXOError") - }).toThrowError() - }) - - test("InsufficientFundsError", (): void => { - try { - throw new InsufficientFundsError("Testing InsufficientFundsError") - } catch (error: any) { - expect(error.getCode()).toBe("1017") - } - expect((): void => { - throw new InsufficientFundsError("Testing InsufficientFundsError") - }).toThrow("Testing InsufficientFundsError") - expect((): void => { - throw new InsufficientFundsError("Testing InsufficientFundsError") - }).toThrowError() - }) - - test("ThresholdError", (): void => { - try { - throw new ThresholdError("Testing ThresholdError") - } catch (error: any) { - expect(error.getCode()).toBe("1018") - } - expect((): void => { - throw new ThresholdError("Testing ThresholdError") - }).toThrow("Testing ThresholdError") - expect((): void => { - throw new ThresholdError("Testing ThresholdError") - }).toThrowError() - }) - - test("SECPMintOutputError", (): void => { - try { - throw new SECPMintOutputError("Testing SECPMintOutputError") - } catch (error: any) { - expect(error.getCode()).toBe("1019") - } - expect((): void => { - throw new SECPMintOutputError("Testing SECPMintOutputError") - }).toThrow("Testing SECPMintOutputError") - expect((): void => { - throw new SECPMintOutputError("Testing SECPMintOutputError") - }).toThrowError() - }) - - test("EVMInputError", (): void => { - try { - throw new EVMInputError("Testing EVMInputError") - } catch (error: any) { - expect(error.getCode()).toBe("1020") - } - expect((): void => { - throw new EVMInputError("Testing EVMInputError") - }).toThrow("Testing EVMInputError") - expect((): void => { - throw new EVMInputError("Testing EVMInputError") - }).toThrowError() - }) - - test("EVMOutputError", (): void => { - try { - throw new EVMOutputError("Testing EVMOutputError") - } catch (error: any) { - expect(error.getCode()).toBe("1021") - } - expect((): void => { - throw new EVMOutputError("Testing EVMOutputError") - }).toThrow("Testing EVMOutputError") - expect((): void => { - throw new EVMOutputError("Testing EVMOutputError") - }).toThrowError() - }) - - test("FeeAssetError", (): void => { - try { - throw new FeeAssetError("Testing FeeAssetError") - } catch (error: any) { - expect(error.getCode()).toBe("1022") - } - expect((): void => { - throw new FeeAssetError("Testing FeeAssetError") - }).toThrow("Testing FeeAssetError") - expect((): void => { - throw new FeeAssetError("Testing FeeAssetError") - }).toThrowError() - }) - - test("StakeError", (): void => { - try { - throw new StakeError("Testing StakeError") - } catch (error: any) { - expect(error.getCode()).toBe("1023") - } - expect((): void => { - throw new StakeError("Testing StakeError") - }).toThrow("Testing StakeError") - expect((): void => { - throw new StakeError("Testing StakeError") - }).toThrowError() - }) - - test("TimeError", (): void => { - try { - throw new TimeError("Testing TimeError") - } catch (error: any) { - expect(error.getCode()).toBe("1024") - } - expect((): void => { - throw new TimeError("Testing TimeError") - }).toThrow("Testing TimeError") - expect((): void => { - throw new TimeError("Testing TimeError") - }).toThrowError() - }) - - test("DelegationFeeError", (): void => { - try { - throw new DelegationFeeError("Testing DelegationFeeError") - } catch (error: any) { - expect(error.getCode()).toBe("1025") - } - expect((): void => { - throw new DelegationFeeError("Testing DelegationFeeError") - }).toThrow("Testing DelegationFeeError") - expect((): void => { - throw new DelegationFeeError("Testing DelegationFeeError") - }).toThrowError() - }) - - test("SubnetOwnerError", (): void => { - try { - throw new SubnetOwnerError("Testing SubnetOwnerError") - } catch (error: any) { - expect(error.getCode()).toBe("1026") - } - expect((): void => { - throw new SubnetOwnerError("Testing SubnetOwnerError") - }).toThrow("Testing SubnetOwnerError") - expect((): void => { - throw new SubnetOwnerError("Testing SubnetOwnerError") - }).toThrowError() - }) - - test("BufferSizeError", (): void => { - try { - throw new BufferSizeError("Testing BufferSizeError") - } catch (error: any) { - expect(error.getCode()).toBe("1027") - } - expect((): void => { - throw new BufferSizeError("Testing BufferSizeError") - }).toThrow("Testing BufferSizeError") - expect((): void => { - throw new BufferSizeError("Testing BufferSizeError") - }).toThrowError() - }) - - test("AddressIndexError", (): void => { - try { - throw new AddressIndexError("Testing AddressIndexError") - } catch (error: any) { - expect(error.getCode()).toBe("1028") - } - expect((): void => { - throw new AddressIndexError("Testing AddressIndexError") - }).toThrow("Testing AddressIndexError") - expect((): void => { - throw new AddressIndexError("Testing AddressIndexError") - }).toThrowError() - }) - - test("PublicKeyError", (): void => { - try { - throw new PublicKeyError("Testing PublicKeyError") - } catch (error: any) { - expect(error.getCode()).toBe("1029") - } - expect((): void => { - throw new PublicKeyError("Testing PublicKeyError") - }).toThrow("Testing PublicKeyError") - expect((): void => { - throw new PublicKeyError("Testing PublicKeyError") - }).toThrowError() - }) - - test("MergeRuleError", (): void => { - try { - throw new MergeRuleError("Testing MergeRuleError") - } catch (error: any) { - expect(error.getCode()).toBe("1030") - } - expect((): void => { - throw new MergeRuleError("Testing MergeRuleError") - }).toThrow("Testing MergeRuleError") - expect((): void => { - throw new MergeRuleError("Testing MergeRuleError") - }).toThrowError() - }) - - test("Base58Error", (): void => { - try { - throw new Base58Error("Testing Base58Error") - } catch (error: any) { - expect(error.getCode()).toBe("1031") - } - expect((): void => { - throw new Base58Error("Testing Base58Error") - }).toThrow("Testing Base58Error") - expect((): void => { - throw new Base58Error("Testing Base58Error") - }).toThrowError() - }) - - test("PrivateKeyError", (): void => { - try { - throw new PrivateKeyError("Testing PrivateKeyError") - } catch (error: any) { - expect(error.getCode()).toBe("1032") - } - expect((): void => { - throw new PrivateKeyError("Testing PrivateKeyError") - }).toThrow("Testing PrivateKeyError") - expect((): void => { - throw new PrivateKeyError("Testing PrivateKeyError") - }).toThrowError() - }) - - test("NodeIdError", (): void => { - try { - throw new NodeIdError("Testing NodeIdError") - } catch (error: any) { - expect(error.getCode()).toBe("1033") - } - expect((): void => { - throw new NodeIdError("Testing NodeIdError") - }).toThrow("Testing NodeIdError") - expect((): void => { - throw new NodeIdError("Testing NodeIdError") - }).toThrowError() - }) - - test("HexError", (): void => { - try { - throw new HexError("Testing HexError") - } catch (error: any) { - expect(error.getCode()).toBe("1034") - } - expect((): void => { - throw new HexError("Testing HexError") - }).toThrow("Testing HexError") - expect((): void => { - throw new HexError("Testing HexError") - }).toThrowError() - }) - - test("TypeIdError", (): void => { - try { - throw new TypeIdError("Testing TypeIdError") - } catch (error: any) { - expect(error.getCode()).toBe("1035") - } - expect((): void => { - throw new TypeIdError("Testing TypeIdError") - }).toThrow("Testing TypeIdError") - expect((): void => { - throw new TypeIdError("Testing TypeIdError") - }).toThrowError() - }) - - test("TypeNameError", (): void => { - try { - throw new TypeNameError("Testing TypeNameError") - } catch (error: any) { - expect(error.getCode()).toBe("1042") - } - expect((): void => { - throw new TypeNameError("Testing TypeNameError") - }).toThrow("Testing TypeNameError") - expect((): void => { - throw new TypeNameError("Testing TypeNameError") - }).toThrowError() - }) - - test("UnknownTypeError", (): void => { - try { - throw new UnknownTypeError("Testing UnknownTypeError") - } catch (error: any) { - expect(error.getCode()).toBe("1036") - } - expect((): void => { - throw new UnknownTypeError("Testing UnknownTypeError") - }).toThrow("Testing UnknownTypeError") - expect((): void => { - throw new UnknownTypeError("Testing UnknownTypeError") - }).toThrowError() - }) - - test("Bech32Error", (): void => { - try { - throw new Bech32Error("Testing Bech32Error") - } catch (error: any) { - expect(error.getCode()).toBe("1037") - } - expect((): void => { - throw new Bech32Error("Testing Bech32Error") - }).toThrow("Testing Bech32Error") - expect((): void => { - throw new Bech32Error("Testing Bech32Error") - }).toThrowError() - }) - - test("EVMFeeError", (): void => { - try { - throw new EVMFeeError("Testing EVMFeeError") - } catch (error: any) { - expect(error.getCode()).toBe("1038") - } - expect((): void => { - throw new EVMFeeError("Testing EVMFeeError") - }).toThrow("Testing EVMFeeError") - expect((): void => { - throw new EVMFeeError("Testing EVMFeeError") - }).toThrowError() - }) - - test("InvalidEntropy", (): void => { - try { - throw new InvalidEntropy("Testing InvalidEntropy") - } catch (error: any) { - expect(error.getCode()).toBe("1039") - } - expect((): void => { - throw new InvalidEntropy("Testing InvalidEntropy") - }).toThrow("Testing InvalidEntropy") - expect((): void => { - throw new InvalidEntropy("Testing InvalidEntropy") - }).toThrowError() - }) - - test("ProtocolError", (): void => { - try { - throw new ProtocolError("Testing ProtocolError") - } catch (error: any) { - expect(error.getCode()).toBe("1040") - } - expect((): void => { - throw new ProtocolError("Testing ProtocolError") - }).toThrow("Testing ProtocolError") - expect((): void => { - throw new ProtocolError("Testing ProtocolError") - }).toThrowError() - }) - - test("SubnetIdError", (): void => { - try { - throw new SubnetIdError("Testing SubnetIdError") - } catch (error: any) { - expect(error.getCode()).toBe("1041") - } - expect((): void => { - throw new SubnetIdError("Testing SubnetIdError") - }).toThrow("Testing SubnetIdError") - expect((): void => { - throw new SubnetIdError("Testing SubnetIdError") - }).toThrowError() - }) -}) diff --git a/tests/utils/hdnode.test.ts b/tests/utils/hdnode.test.ts deleted file mode 100644 index 59a4b17cd..000000000 --- a/tests/utils/hdnode.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -import Avalanche, { HDNode, Mnemonic } from "src" -import { Buffer } from "buffer/" -import { AVMAPI, KeyChain } from "src/apis/avm" - -const ip: string = "localhost" -const port: number = 9650 -const protocol: string = "http" -const networkID: number = 1 -const avalanche: Avalanche = new Avalanche(ip, port, protocol, networkID) -const mnemonic: Mnemonic = Mnemonic.getInstance() -const xchain: AVMAPI = avalanche.XChain() -const xKeychain: KeyChain = xchain.keyChain() - -describe("HDNode", (): void => { - const xPriv: string = - "xprv9s21ZrQH143K4RH1nRkHwuVz3qGREBLobwUoUBowLDucQXm4do8jvz12agvjHrAwjJXtq9BZ87WBPUPScDBnjKvBKVQ5xbS7GQwJKW7vXLD" - const childXPriv: string = - "xprvA7X7udsZk3q9mNMcGnN8PKHv5eHm6JA3TRzW2HsWnrYHbccXh5YMnRLA83VCPKWQUFmKf9AfCXSmoFs7HJ8Yr1LK52wJDVk262vGFszM4nb" - const xPub: string = - "xpub661MyMwAqRbcFSdAk5S6UECmA6MFQWiRBfPU5AsVcmrKY5HoFKPNYrKEq7isvaZVfNxhkrv5oXxFpQc6AVEcVW5NxeamKD6LyLUDMntbnq7" - const seed: string = - "a0c42a9c3ac6abf2ba6a9946ae83af18f51bf1c9fa7dacc4c92513cc4dd015834341c775dcd4c0fac73547c5662d81a9e9361a0aac604a73a321bd9103bce8af" - const msg: string = "bb413645935a9bf1ecf0c3d30df2d573" - const m: string = - "immune year obscure laptop wage diamond join glue ecology envelope box fade mixed cradle athlete absorb stick rival punch dinosaur skin blind benefit pretty" - const addrs: string[] = [ - "X-avax15qwuklmrfcmfw78yvka9pjsukjeevl4aveehq0", - "X-avax13wqaxm6zgjq5qwzuyyxyl9yrz3edcgwgfht6gt", - "X-avax1z3dn3vczxttts8dsdjfgtnkekf8nvqhhsj5stl", - "X-avax1j6kze9n7r3e8wq6jta5mf6pd3fwnu0v9wygc8p", - "X-avax1ngasfmvl8g63lzwznp0374myz7ajt4746g750m", - "X-avax1pr7pzcggtrk6uap58sfsrlnhqhayly2gtlux9l", - "X-avax1wwtn3gx7ke4ge2c29eg5sun36nyj55u4dle9gn", - "X-avax13527pvlnxa4wrfgt0h8ya7nkjawqq29sv5s89x", - "X-avax1gw6agtcsz969ugpqh2zx2lmjchg6npklvp43qq", - "X-avax10agjetvj0a0vf6wtlh7s6ctr8ha8ch8km8z567" - ] - - test("derive", (): void => { - const hdnode: HDNode = new HDNode(seed) - const path: string = "m/9000'/2614666'/4849181'/4660'/2'/1/3" - const child = hdnode.derive(path) - expect(child.privateExtendedKey).toBe(childXPriv) - }) - - test("fromMasterSeedBuffer", (): void => { - const hdnode: HDNode = new HDNode(Buffer.from(seed)) - expect(hdnode.privateExtendedKey).toBe(xPriv) - }) - - test("fromMasterSeedString", (): void => { - const hdnode: HDNode = new HDNode(seed) - expect(hdnode.privateExtendedKey).toBe(xPriv) - }) - - test("fromXPriv", (): void => { - const hdnode: HDNode = new HDNode(xPriv) - expect(hdnode.privateExtendedKey).toBe(xPriv) - }) - - test("fromXPub", (): void => { - const hdnode: HDNode = new HDNode(xPub) - expect(hdnode.publicExtendedKey).toBe(xPub) - }) - - test("sign", (): void => { - const hdnode: HDNode = new HDNode(xPriv) - const sig: Buffer = hdnode.sign(Buffer.from(msg)) - expect(Buffer.isBuffer(sig)).toBeTruthy() - }) - - test("verify", (): void => { - const hdnode: HDNode = new HDNode(xPriv) - const sig: Buffer = hdnode.sign(Buffer.from(msg)) - const verify: boolean = hdnode.verify(Buffer.from(msg), sig) - expect(verify).toBeTruthy() - }) - - test("wipePrivateData", (): void => { - const hdnode: HDNode = new HDNode(xPriv) - hdnode.wipePrivateData() - expect(hdnode.privateKey).toBeNull() - }) - - test("BIP44", (): void => { - const seed: Buffer = mnemonic.mnemonicToSeedSync(m) - const hdnode: HDNode = new HDNode(seed) - for (let i: number = 0; i <= 9; i++) { - const child: HDNode = hdnode.derive(`m/44'/9000'/0'/0/${i}`) - xKeychain.importKey(child.privateKeyCB58) - } - const xAddressStrings: string[] = xchain.keyChain().getAddressStrings() - expect(xAddressStrings).toStrictEqual(addrs) - }) -}) diff --git a/tests/utils/helperfunctions.test.ts b/tests/utils/helperfunctions.test.ts deleted file mode 100644 index b705833cc..000000000 --- a/tests/utils/helperfunctions.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { ExportTx, ImportTx, UnsignedTx } from "src/apis/evm" -import { calcBytesCost, costExportTx, costImportTx } from "src/utils" -import { Buffer } from "buffer/" - -describe("HelperFunctions", (): void => { - test("calcBytesCost", (): void => { - const importTx: ImportTx = new ImportTx() - // an empty EVM ImportTx is 76 bytes - let cost: number = 76 - let bytesCost: number = calcBytesCost(importTx.toBuffer().byteLength) - expect(cost).toEqual(bytesCost) - - // the byteCost should always be 1 unit of gas per byte - let size: number = 100 - cost = 100 - bytesCost = calcBytesCost(size) - expect(cost).toEqual(bytesCost) - - size = 507 - cost = 507 - bytesCost = calcBytesCost(size) - expect(cost).toEqual(bytesCost) - - let hex: string = - "000030399d0775f450604bd2fbc49ce0c5c1c6dfeb2dc2acb8c92c26eeae6e6df4502b19d891ad56056d9c01f18f43f58b5c784ad07a4a49cf3d1f11623804b5cba2c6bf000000018db97c7cece249c2b98bdc0226cc4c2a57bf52fc00b1a2bc2ec50000dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db000000000000000000000001dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db0000000700b1a2bc2eb5bdc0000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c" - const exportTx: ExportTx = new ExportTx() - let unsignedTx: UnsignedTx = new UnsignedTx(exportTx) - exportTx.fromBuffer(new Buffer(hex, "hex")) - cost = costExportTx(unsignedTx) - bytesCost = 11230 - expect(cost).toEqual(bytesCost) - - hex = - "000030399d0775f450604bd2fbc49ce0c5c1c6dfeb2dc2acb8c92c26eeae6e6df4502b19d891ad56056d9c01f18f43f58b5c784ad07a4a49cf3d1f11623804b5cba2c6bf0000000000000000" - importTx.fromBuffer(new Buffer(hex, "hex")) - unsignedTx = new UnsignedTx(importTx) - cost = costImportTx(unsignedTx) - bytesCost = 10082 - expect(cost).toEqual(bytesCost) - }) -}) diff --git a/tests/utils/mnemonic.test.ts b/tests/utils/mnemonic.test.ts deleted file mode 100644 index ac3f325d7..000000000 --- a/tests/utils/mnemonic.test.ts +++ /dev/null @@ -1,425 +0,0 @@ -import Mnemonic from "src/utils/mnemonic" -import { Buffer } from "buffer/" - -const randomBytes: any = require("randombytes") -const mnemonic = Mnemonic.getInstance() -const entropy: string = - "9d7c99e77261acb88a5ed717f625d5d3ed5569e0f60429cc6eb9c4e91f48fb7c" -const langs: string[] = [ - "japanese", - "spanish", - "italian", - "french", - "korean", - "czech", - "portuguese", - "chinese_traditional", - "chinese_simplified" -] - -const mnemnonics: string[] = [ - "ていし みっか せんせい みっか えいぶん さつたば かいよう へんたい うやまう にちじょう せっかく とける ぶどう にんぷ たいうん はいそう かえる したて なめらか だじゃれ だんれつ てんぼうだい もくようび そむく", - "nueve tenis lágrima tenis baile folleto canica sonoro autor perla jardín oxígeno sensor piscina lonja rabo cañón germen pegar marrón molino opuesto trébol llaga", - "pergamena tensione maratona tensione becco geco cena srotolato badilata regola lumaca prelievo somma rifasare motivato sarcasmo ceramica ibernato randagio ninfa orafo polmonite tuffato modulo", - "mobile surface héron surface batterie éthanol capsule serein bafouer pangolin gravir nuisible salive peintre intense préfixe carabine fatal orque label lucide neurone toucher informer", - "운반 특별 시인 특별 귀신 빗물 농민 취업 구입 작년 스님 이윽고 체험 장애인 아흔 제작 농장 상추 입사 언덕 염려 의외로 학급 씨름", - "pohnutka vize nikam vize datum ledvina export uklidnit cirkus revolver naslepo procento traverza rozjezd odliv slavnost fajfka lyra rande omluva panovat poukaz vyrvat ochladit", - "mesada surdina guincho surdina aumentar escrita brilho sediado assador ostentar goela nevoeiro rouco panqueca inovador postal brochura faceta ontem judoca linhagem munido torque indeciso", - "烯 逮 岩 逮 資 衛 走 賦 料 默 膠 辛 杯 挑 戶 陶 議 劉 拍 謀 浮 休 煩 慮", - "烯 逮 岩 逮 资 卫 走 赋 料 默 胶 辛 杯 挑 户 陶 议 刘 拍 谋 浮 休 烦 虑" -] - -const seeds: string[] = [ - "2ed50c99aa2ee350f0a46c8427d69f9f5c7c5864be7a64ae96695374a0a5a02a3c5075312234f05f8f4c840aa486c99131f84b81c56daff5c31a89cdc7b50424", - "04c6cfd9337642f47e21e28632f9744fd1b56c57454ebae5c627c2a4b16e47c0948b9c582041bbb1590e128a25ae79d7055ed8aecdbc030920a67205da24846d", - "c4274544eb6c375d2caa70af8c6a67e3b751c518cbb35244891c7b74a12a5e06d5ce5b925f134930e17f5e86b21146d096715c7645a250dbba1d2ba35bc07317", - "00e5b5e4785763d6f92fe1ad7c5a7e7dd0fd375bd441473198d2486990ca5a924b5cb6b6831dc94d446c9b3180eefe2d799887bcfc1ee6d8f4f0650e594c9d1b", - "d8dcc049712867ba7d1bc0e2874d8ec38ee26088d1e2affa10ffac30cf1d0b915bbb6c79bfafbb1db0e8cd66880bf4ba52c53b949f6a3adbba1821dd3045c7cb", - "a81d8a917861cb8a1ffd2e94452e08fd6dc4d2577bad3ac089f56279521b1c95caebe57ac6c3d126d8abd4d6a3f2c3d8c207bd36fbf75a5e797c5a8f1992c651", - "b9fc39d7f138a95b8f31436e02a8711b3164cd45a211673f7137429b45faf77a1604682b51803a983638c46a8b2c13237c87ab4b685a1fa5c65700dc7136ccfc", - "1a5f3eab01276bf7d9b06c42be90fb4b8106b278b4bbaf922f3da6821a63b4d69fa9285fec0936e0f04a1b2a25a65064cd51c111c75063dbe59e4de336b35f85", - "53bcb9fe403a4a45bee2a2a04dabfa3f2018db349d0e5200175bd345aaa3a3bd45a88a6fb7244914ad156961742f7b4ea7f8ffd83fcae5b1166b73b2ad943f76" -] - -interface Vector { - entropy: string - mnemonic: string - seed: string -} - -const vectors: Vector[] = [ - { - entropy: "00000000000000000000000000000000", - mnemonic: - "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", - seed: "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04" - }, - { - entropy: "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", - mnemonic: - "legal winner thank year wave sausage worth useful legal winner thank yellow", - seed: "2e8905819b8723fe2c1d161860e5ee1830318dbf49a83bd451cfb8440c28bd6fa457fe1296106559a3c80937a1c1069be3a3a5bd381ee6260e8d9739fce1f607" - }, - { - entropy: "80808080808080808080808080808080", - mnemonic: - "letter advice cage absurd amount doctor acoustic avoid letter advice cage above", - seed: "d71de856f81a8acc65e6fc851a38d4d7ec216fd0796d0a6827a3ad6ed5511a30fa280f12eb2e47ed2ac03b5c462a0358d18d69fe4f985ec81778c1b370b652a8" - }, - { - entropy: "ffffffffffffffffffffffffffffffff", - mnemonic: "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong", - seed: "ac27495480225222079d7be181583751e86f571027b0497b5b5d11218e0a8a13332572917f0f8e5a589620c6f15b11c61dee327651a14c34e18231052e48c069" - }, - { - entropy: "000000000000000000000000000000000000000000000000", - mnemonic: - "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon agent", - seed: "035895f2f481b1b0f01fcf8c289c794660b289981a78f8106447707fdd9666ca06da5a9a565181599b79f53b844d8a71dd9f439c52a3d7b3e8a79c906ac845fa" - }, - { - entropy: "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", - mnemonic: - "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal will", - seed: "f2b94508732bcbacbcc020faefecfc89feafa6649a5491b8c952cede496c214a0c7b3c392d168748f2d4a612bada0753b52a1c7ac53c1e93abd5c6320b9e95dd" - }, - { - entropy: "808080808080808080808080808080808080808080808080", - mnemonic: - "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter always", - seed: "107d7c02a5aa6f38c58083ff74f04c607c2d2c0ecc55501dadd72d025b751bc27fe913ffb796f841c49b1d33b610cf0e91d3aa239027f5e99fe4ce9e5088cd65" - }, - { - entropy: "ffffffffffffffffffffffffffffffffffffffffffffffff", - mnemonic: - "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo when", - seed: "0cd6e5d827bb62eb8fc1e262254223817fd068a74b5b449cc2f667c3f1f985a76379b43348d952e2265b4cd129090758b3e3c2c49103b5051aac2eaeb890a528" - }, - { - entropy: "0000000000000000000000000000000000000000000000000000000000000000", - mnemonic: - "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art", - seed: "bda85446c68413707090a52022edd26a1c9462295029f2e60cd7c4f2bbd3097170af7a4d73245cafa9c3cca8d561a7c3de6f5d4a10be8ed2a5e608d68f92fcc8" - }, - { - entropy: "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", - mnemonic: - "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth title", - seed: "bc09fca1804f7e69da93c2f2028eb238c227f2e9dda30cd63699232578480a4021b146ad717fbb7e451ce9eb835f43620bf5c514db0f8add49f5d121449d3e87" - }, - { - entropy: "8080808080808080808080808080808080808080808080808080808080808080", - mnemonic: - "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic bless", - seed: "c0c519bd0e91a2ed54357d9d1ebef6f5af218a153624cf4f2da911a0ed8f7a09e2ef61af0aca007096df430022f7a2b6fb91661a9589097069720d015e4e982f" - }, - { - entropy: "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - mnemonic: - "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo vote", - seed: "dd48c104698c30cfe2b6142103248622fb7bb0ff692eebb00089b32d22484e1613912f0a5b694407be899ffd31ed3992c456cdf60f5d4564b8ba3f05a69890ad" - }, - { - entropy: "77c2b00716cec7213839159e404db50d", - mnemonic: - "jelly better achieve collect unaware mountain thought cargo oxygen act hood bridge", - seed: "b5b6d0127db1a9d2226af0c3346031d77af31e918dba64287a1b44b8ebf63cdd52676f672a290aae502472cf2d602c051f3e6f18055e84e4c43897fc4e51a6ff" - }, - { - entropy: "b63a9c59a6e641f288ebc103017f1da9f8290b3da6bdef7b", - mnemonic: - "renew stay biology evidence goat welcome casual join adapt armor shuffle fault little machine walk stumble urge swap", - seed: "9248d83e06f4cd98debf5b6f010542760df925ce46cf38a1bdb4e4de7d21f5c39366941c69e1bdbf2966e0f6e6dbece898a0e2f0a4c2b3e640953dfe8b7bbdc5" - }, - { - entropy: "3e141609b97933b66a060dcddc71fad1d91677db872031e85f4c015c5e7e8982", - mnemonic: - "dignity pass list indicate nasty swamp pool script soccer toe leaf photo multiply desk host tomato cradle drill spread actor shine dismiss champion exotic", - seed: "ff7f3184df8696d8bef94b6c03114dbee0ef89ff938712301d27ed8336ca89ef9635da20af07d4175f2bf5f3de130f39c9d9e8dd0472489c19b1a020a940da67" - }, - { - entropy: "0460ef47585604c5660618db2e6a7e7f", - mnemonic: - "afford alter spike radar gate glance object seek swamp infant panel yellow", - seed: "65f93a9f36b6c85cbe634ffc1f99f2b82cbb10b31edc7f087b4f6cb9e976e9faf76ff41f8f27c99afdf38f7a303ba1136ee48a4c1e7fcd3dba7aa876113a36e4" - }, - { - entropy: "72f60ebac5dd8add8d2a25a797102c3ce21bc029c200076f", - mnemonic: - "indicate race push merry suffer human cruise dwarf pole review arch keep canvas theme poem divorce alter left", - seed: "3bbf9daa0dfad8229786ace5ddb4e00fa98a044ae4c4975ffd5e094dba9e0bb289349dbe2091761f30f382d4e35c4a670ee8ab50758d2c55881be69e327117ba" - }, - { - entropy: "2c85efc7f24ee4573d2b81a6ec66cee209b2dcbd09d8eddc51e0215b0b68e416", - mnemonic: - "clutch control vehicle tonight unusual clog visa ice plunge glimpse recipe series open hour vintage deposit universe tip job dress radar refuse motion taste", - seed: "fe908f96f46668b2d5b37d82f558c77ed0d69dd0e7e043a5b0511c48c2f1064694a956f86360c93dd04052a8899497ce9e985ebe0c8c52b955e6ae86d4ff4449" - }, - { - entropy: "eaebabb2383351fd31d703840b32e9e2", - mnemonic: - "turtle front uncle idea crush write shrug there lottery flower risk shell", - seed: "bdfb76a0759f301b0b899a1e3985227e53b3f51e67e3f2a65363caedf3e32fde42a66c404f18d7b05818c95ef3ca1e5146646856c461c073169467511680876c" - }, - { - entropy: "7ac45cfe7722ee6c7ba84fbc2d5bd61b45cb2fe5eb65aa78", - mnemonic: - "kiss carry display unusual confirm curtain upgrade antique rotate hello void custom frequent obey nut hole price segment", - seed: "ed56ff6c833c07982eb7119a8f48fd363c4a9b1601cd2de736b01045c5eb8ab4f57b079403485d1c4924f0790dc10a971763337cb9f9c62226f64fff26397c79" - }, - { - entropy: "4fa1a8bc3e6d80ee1316050e862c1812031493212b7ec3f3bb1b08f168cabeef", - mnemonic: - "exile ask congress lamp submit jacket era scheme attend cousin alcohol catch course end lucky hurt sentence oven short ball bird grab wing top", - seed: "095ee6f817b4c2cb30a5a797360a81a40ab0f9a4e25ecd672a3f58a0b5ba0687c096a6b14d2c0deb3bdefce4f61d01ae07417d502429352e27695163f7447a8c" - }, - { - entropy: "18ab19a9f54a9274f03e5209a2ac8a91", - mnemonic: - "board flee heavy tunnel powder denial science ski answer betray cargo cat", - seed: "6eff1bb21562918509c73cb990260db07c0ce34ff0e3cc4a8cb3276129fbcb300bddfe005831350efd633909f476c45c88253276d9fd0df6ef48609e8bb7dca8" - }, - { - entropy: "18a2e1d81b8ecfb2a333adcb0c17a5b9eb76cc5d05db91a4", - mnemonic: - "board blade invite damage undo sun mimic interest slam gaze truly inherit resist great inject rocket museum chief", - seed: "f84521c777a13b61564234bf8f8b62b3afce27fc4062b51bb5e62bdfecb23864ee6ecf07c1d5a97c0834307c5c852d8ceb88e7c97923c0a3b496bedd4e5f88a9" - }, - { - entropy: "15da872c95a13dd738fbf50e427583ad61f18fd99f628c417a61cf8343c90419", - mnemonic: - "beyond stage sleep clip because twist token leaf atom beauty genius food business side grid unable middle armed observe pair crouch tonight away coconut", - seed: "b15509eaa2d09d3efd3e006ef42151b30367dc6e3aa5e44caba3fe4d3e352e65101fbdb86a96776b91946ff06f8eac594dc6ee1d3e82a42dfe1b40fef6bcc3fd" - } -] - -interface BadMnemonic { - mnemonic: string -} - -const badMnemonics: BadMnemonic[] = [ - { - mnemonic: - "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon" - }, - { - mnemonic: - "legal winner thank year wave sausage worth useful legal winner thank yellow yellow" - }, - { - mnemonic: - "letter advice cage absurd amount doctor acoustic avoid letter advice caged above" - }, - { mnemonic: "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo, wrong" }, - { - mnemonic: - "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon" - }, - { - mnemonic: - "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal will will will" - }, - { - mnemonic: - "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter always." - }, - { - mnemonic: - "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo why" - }, - { - mnemonic: - "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art art" - }, - { - mnemonic: - "legal winner thank year wave sausage worth useful legal winner thanks year wave worth useful legal winner thank year wave sausage worth title" - }, - { - mnemonic: - "letter advice cage absurd amount doctor acoustic avoid letters advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic bless" - }, - { - mnemonic: - "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo voted" - }, - { - mnemonic: - "jello better achieve collect unaware mountain thought cargo oxygen act hood bridge" - }, - { - mnemonic: - "renew, stay, biology, evidence, goat, welcome, casual, join, adapt, armor, shuffle, fault, little, machine, walk, stumble, urge, swap" - }, - { mnemonic: "dignity pass list indicate nasty" }, - - // From issue 32 - { - mnemonic: - "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon letter" - } -] - -const malformedMnemonics: string[] = [ - "a a a a a a a a a a a a a a a a a a a a a a a a a", // Too many words - "a", // Too few - "a a a a a a a a a a a a a a" // Not multiple of 3 -] - -describe("Mnemonic", () => { - test("vectors", (): void => { - vectors.forEach(async (vector: Vector, index: number): Promise => { - const wordlist = mnemonic.getWordlists("english") as string[] - const entropyToMnemonic: string = mnemonic.entropyToMnemonic( - vector.entropy, - wordlist - ) - expect(vector.mnemonic).toBe(entropyToMnemonic) - const mnemonicToEntropy: string = mnemonic.mnemonicToEntropy( - vector.mnemonic, - wordlist - ) - expect(mnemonicToEntropy).toBe(vector.entropy) - const password: string = "TREZOR" - const mnemonicToSeed: Buffer = await mnemonic.mnemonicToSeed( - vector.mnemonic, - password - ) - expect(mnemonicToSeed.toString("hex")).toBe(vector.seed) - }) - }) - - test("badMnemonics", (): void => { - const wordlist = mnemonic.getWordlists("english") as string[] - badMnemonics.forEach((badMnemonic: BadMnemonic, index: number): void => { - const validateMnemonic: string = mnemonic.validateMnemonic( - badMnemonic.mnemonic, - wordlist - ) - expect(validateMnemonic).toBeFalsy() - }) - }) - - test("malformedMnemonics", (): void => { - const wordlist = mnemonic.getWordlists("english") as string[] - malformedMnemonics.forEach( - (malformedMnemonic: string, index: number): void => { - const validateMnemonic: string = mnemonic.validateMnemonic( - malformedMnemonic, - wordlist - ) - expect(validateMnemonic).toBeFalsy() - } - ) - }) - - test("entropyToMnemonic", (): void => { - langs.forEach((lang: string, index: number): void => { - const wordlist = mnemonic.getWordlists(lang) as string[] - const entropyToMnemonic: string = mnemonic.entropyToMnemonic( - entropy, - wordlist - ) - expect(mnemnonics[index]).toBe(entropyToMnemonic) - }) - }) - - test("generateMnemonic", (): void => { - const strength: number = 256 - langs.forEach((lang: string): void => { - const wordlist = mnemonic.getWordlists(lang) as string[] - const m: string = mnemonic.generateMnemonic( - strength, - randomBytes, - wordlist - ) - expect(typeof m === "string").toBeTruthy() - }) - }) - - test("test mnemonic lengths", (): void => { - const wordlist = mnemonic.getWordlists("english") as string[] - let strength: number = 128 - let mnemnnic: string = mnemonic.generateMnemonic( - strength, - randomBytes, - wordlist - ) - expect(mnemnnic.split(" ").length).toBe(12) - strength = 160 - mnemnnic = mnemonic.generateMnemonic(strength, randomBytes, wordlist) - expect(mnemnnic.split(" ").length).toBe(15) - strength = 192 - mnemnnic = mnemonic.generateMnemonic(strength, randomBytes, wordlist) - expect(mnemnnic.split(" ").length).toBe(18) - strength = 224 - mnemnnic = mnemonic.generateMnemonic(strength, randomBytes, wordlist) - expect(mnemnnic.split(" ").length).toBe(21) - strength = 256 - mnemnnic = mnemonic.generateMnemonic(strength, randomBytes, wordlist) - expect(mnemnnic.split(" ").length).toBe(24) - }) - - test("getWordlists", (): void => { - langs.forEach((lang: string): void => { - const wordlist = mnemonic.getWordlists(lang) as string[] - expect(typeof wordlist === "object").toBeTruthy() - }) - }) - - test("mnemonicToEntropy", (): void => { - mnemnonics.forEach((mnemnnic: string, index: number): void => { - const wordlist = mnemonic.getWordlists(langs[index]) as string[] - const mnemonicToEntropy: string = mnemonic.mnemonicToEntropy( - mnemnnic, - wordlist - ) - expect(mnemonicToEntropy).toBe(entropy) - }) - }) - - test("mnemonicToSeed", async (): Promise => { - mnemnonics.forEach(async (mnemnnic: string): Promise => { - const password: string = "password" - const mnemonicToSeed: Buffer = await mnemonic.mnemonicToSeed( - mnemnnic, - password - ) - expect(typeof mnemonicToSeed === "object").toBeTruthy() - }) - }) - - test("mnemonicToSeedSync", (): void => { - mnemnonics.forEach((mnemnnic: string, index: number): void => { - const password: string = "password" - const mnemonicToSeedSync: Buffer = mnemonic.mnemonicToSeedSync( - mnemnnic, - password - ) - expect(mnemonicToSeedSync.toString("hex")).toBe(seeds[index]) - }) - }) - - test("validateMnemonic", (): void => { - mnemnonics.forEach((mnemnnic: string, index: number): void => { - const wordlist = mnemonic.getWordlists(langs[index]) as string[] - const validateMnemonic: string = mnemonic.validateMnemonic( - mnemnnic, - wordlist - ) - expect(validateMnemonic).toBeTruthy() - }) - }) - - test("setDefaultWordlist", (): void => { - langs.forEach((lang: string, index: number): void => { - mnemonic.setDefaultWordlist(lang) - const getDefaultWordlist: string = mnemonic.getDefaultWordlist() - const wordlist = mnemonic.getWordlists(lang) as string[] - const m: string = mnemonic.generateMnemonic(256, randomBytes, wordlist) - expect(getDefaultWordlist).toBe(lang) - expect(typeof wordlist === "object").toBeTruthy() - expect(typeof m === "string").toBeTruthy() - }) - }) -}) diff --git a/tests/utils/pubsub.test.ts b/tests/utils/pubsub.test.ts deleted file mode 100644 index 835df81d8..000000000 --- a/tests/utils/pubsub.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { PubSub } from "src" - -const pubsub: PubSub = new PubSub() - -describe("PubSub", (): void => { - test("newSet", (): void => { - const data: string = '{"newSet":{}}' - const newSet: string = pubsub.newSet() - expect(newSet).toEqual(data) - }) - - test("newBloom", (): void => { - const data: string = - '{"newBloom":{"maxElements":1000,"collisionProb":0.01}}' - const newBloom: string = pubsub.newBloom() - expect(newBloom).toEqual(data) - }) - - test("addAddresses", (): void => { - const data: string = - '{"addAddresses":{"addresses":["X-avax1wst8jt3z3fm9ce0z6akj3266zmgccdp03hjlaj"]}}' - const addresses: string[] = [ - "X-avax1wst8jt3z3fm9ce0z6akj3266zmgccdp03hjlaj" - ] - const addAddresses: string = pubsub.addAddresses(addresses) - expect(addAddresses).toEqual(data) - }) -}) diff --git a/tests/utils/serialization.test.ts b/tests/utils/serialization.test.ts deleted file mode 100644 index aa73bc79b..000000000 --- a/tests/utils/serialization.test.ts +++ /dev/null @@ -1,1402 +0,0 @@ -import BN from "bn.js" -import { Buffer } from "buffer/" -import { - BaseTx, - CreateAssetTx, - ExportTx, - GenesisAsset, - ImportTx, - InitialStates, - MinterSet, - NFTCredential, - NFTMintOperation, - NFTMintOutput, - NFTTransferOperation, - NFTTransferOutput, - OperationTx, - SECPCredential, - SECPMintOperation, - SECPMintOutput, - SECPTransferInput, - SECPTransferOutput, - TransferableInput, - TransferableOperation, - TransferableOutput, - Tx, - UnsignedTx, - UTXO, - UTXOID, - UTXOSet -} from "src/apis/avm" -import { Address, Serialized, Signature } from "src/common" -import { - DefaultNetworkID, - Defaults, - Serialization, - SerializedEncoding, - SerializedType -} from "../../src/utils" -import { getPreferredHRP } from "../../src/utils" - -const serialization: Serialization = Serialization.getInstance() - -describe("Serialization", (): void => { - const address: string = "X-avax1wst8jt3z3fm9ce0z6akj3266zmgccdp03hjlaj" - const nodeID: string = "NodeID-MFrZFVCXPv5iCn6M9K6XduxGTYp891xXZ" - const privateKey: string = - "PrivateKey-ewoqjP7PxY4yr3iLTpLisriqt94hdyDFNgchSxGGztUrTXtNN" - const cb58: string = "2eNy1mUFdmaxXNj1eQHUe7Np4gju9sJsEtWQ4MX3ToiNKuADed" - const base64: string = "ZnJvbSBzbm93Zmxha2UgdG8gQXZhbGFuY2hl" - const hex: string = "66726f6d20736e6f77666c616b6520746f204176616c616e636865" - const decimalString: string = "12345" - const num: number = 12345 - const utf8: string = "from snowflake to Avalanche" - const bn: BN = new BN(9000) - const name: string = "BaseTx" - const denomination: Buffer = Buffer.alloc(1) - const chainID: string = "X" - const hrp: any = getPreferredHRP(1) - - test("instance of", (): void => { - expect(serialization).toBeInstanceOf(Serialization) - }) - - describe("typeToBuffer && bufferToType", (): void => { - let t: SerializedType - let buf: Buffer - test("BN", (): void => { - t = "BN" - const bn: BN = new BN(9000) - buf = serialization.typeToBuffer(bn, t) - const b: BN = serialization.bufferToType(buf, t) - expect(bn.toString()).toEqual(b.toString()) - }) - - test("bech32", (): void => { - t = "bech32" - buf = serialization.typeToBuffer(address, t) - const bech32: string = serialization.bufferToType(buf, t, hrp, chainID) - expect(bech32).toEqual(address) - }) - - test("nodeID", (): void => { - t = "nodeID" - buf = serialization.typeToBuffer(nodeID, t) - const n: string = serialization.bufferToType(buf, t) - expect(nodeID).toEqual(n) - }) - - test("privateKey", (): void => { - t = "privateKey" - buf = serialization.typeToBuffer(privateKey, t) - const p: string = serialization.bufferToType(buf, t) - expect(privateKey).toEqual(p) - }) - - test("cb58", (): void => { - t = "cb58" - buf = serialization.typeToBuffer(cb58, t) - const c: string = serialization.bufferToType(buf, t) - expect(cb58).toEqual(c) - }) - - test("base58", (): void => { - t = "cb58" - buf = serialization.typeToBuffer(cb58, t) - const c: string = serialization.bufferToType(buf, t) - expect(cb58).toEqual(c) - }) - - test("base64", (): void => { - t = "base64" - buf = serialization.typeToBuffer(base64, t) - const b64: string = serialization.bufferToType(buf, t) - expect(base64).toEqual(b64) - }) - - test("hex", (): void => { - t = "hex" - buf = serialization.typeToBuffer(hex, t) - const h: string = serialization.bufferToType(buf, t) - expect(hex).toEqual(h) - }) - - test("decimalString", (): void => { - t = "decimalString" - buf = serialization.typeToBuffer(decimalString, t) - const d: string = serialization.bufferToType(buf, t) - expect(decimalString).toEqual(d) - }) - - test("number", (): void => { - t = "number" - buf = serialization.typeToBuffer(num, t) - const nu: string = serialization.bufferToType(buf, t) - expect(num).toEqual(nu) - }) - - test("utf8", (): void => { - t = "utf8" - buf = serialization.typeToBuffer(utf8, t) - const u: string = serialization.bufferToType(buf, t) - expect(utf8).toEqual(u) - }) - }) - - describe("encoder && decoder", (): void => { - const encoding: SerializedEncoding = "hex" - test("BN", (): void => { - const str: string = serialization.encoder(bn, encoding, "BN", "BN") - const decoded: string = serialization.decoder(str, encoding, "BN", "BN") - expect(bn.toString()).toEqual(decoded.toString()) - }) - - test("bech32", (): void => { - const str: string = serialization.encoder( - address, - encoding, - "bech32", - "bech32" - ) - const decoded: string = serialization.decoder( - str, - encoding, - "bech32", - "bech32", - hrp, - chainID - ) - expect(address).toEqual(decoded) - }) - - test("nodeID", (): void => { - const str: string = serialization.encoder( - nodeID, - encoding, - "nodeID", - "nodeID" - ) - const decoded: string = serialization.decoder( - str, - encoding, - "nodeID", - "nodeID" - ) - expect(nodeID).toEqual(decoded) - }) - - test("privateKey", (): void => { - const str: string = serialization.encoder( - privateKey, - encoding, - "privateKey", - "privateKey" - ) - const decoded: string = serialization.decoder( - str, - encoding, - "privateKey", - "privateKey" - ) - expect(privateKey).toEqual(decoded) - }) - - test("cb58", (): void => { - const str: string = serialization.encoder(cb58, encoding, "cb58", "cb58") - const decoded: string = serialization.decoder( - str, - encoding, - "cb58", - "cb58" - ) - expect(cb58).toEqual(decoded) - }) - - test("base58", (): void => { - const str: string = serialization.encoder( - cb58, - encoding, - "base58", - "base58" - ) - const decoded: string = serialization.decoder( - str, - encoding, - "base58", - "base58" - ) - expect(cb58).toEqual(decoded) - }) - - test("base64", (): void => { - const str: string = serialization.encoder( - base64, - encoding, - "base64", - "base64" - ) - const decoded: string = serialization.decoder( - str, - encoding, - "base64", - "base64" - ) - expect(base64).toEqual(decoded) - }) - - test("hex", (): void => { - const str: string = serialization.encoder(hex, encoding, "hex", "hex") - const decoded: string = serialization.decoder(str, encoding, "hex", "hex") - expect(hex).toEqual(decoded) - }) - - test("utf8", (): void => { - const str: string = serialization.encoder(name, encoding, "utf8", "utf8") - const decoded: string = serialization.decoder( - str, - encoding, - "utf8", - "utf8" - ) - expect(name).toBe(decoded) - }) - - test("decimalString", (): void => { - const str: string = serialization.encoder( - decimalString, - encoding, - "decimalString", - "decimalString" - ) - const decoded: string = serialization.decoder( - str, - encoding, - "decimalString", - "decimalString" - ) - expect(decimalString).toBe(decoded) - }) - - test("number", (): void => { - const str: string = serialization.encoder( - num, - encoding, - "number", - "number" - ) - const decoded: string = serialization.decoder( - str, - encoding, - "number", - "number" - ) - expect(num).toBe(decoded) - }) - - test("Buffer", (): void => { - const str: string = serialization.encoder( - denomination, - encoding, - "Buffer", - "decimalString", - 1 - ) - const decoded: Buffer = serialization.decoder( - str, - encoding, - "decimalString", - "Buffer", - 1 - ) - expect(denomination.toString("hex")).toBe(decoded.toString("hex")) - }) - }) - - describe("serialize && deserialize", (): void => { - const networkID: number = 1337 - const m: string = "2Zc54v4ek37TEwu4LiV3j41PUMRd6acDDU3ZCVSxE7X" - const mHex: string = - "66726f6d20736e6f77666c616b6520746f206176616c616e636865" - const memo: Buffer = serialization.typeToBuffer(m, "cb58") - const cChainID: string = - "2CA6j5zYzasynPsFeNoqWkmTCt3VScMvXUZHbfDJ8k3oGzAPtU" - const cChainIDHex: string = - "9d0775f450604bd2fbc49ce0c5c1c6dfeb2dc2acb8c92c26eeae6e6df4502b19" - const hex: SerializedEncoding = "hex" - const cb58: SerializedEncoding = "cb58" - const utf8: SerializedType = "utf8" - const amount: BN = new BN(0) - const amountHex: string = "0000000000000000" - const bytes: string = "0000000000000000000000000000000000000000" - const xAddress: string = "X-avax1pdurs53v6vtue9sw7am9ayjqh9mcnqe9s80sgn" - const xAddressHex: string = "0b7838522cd317cc960ef7765e9240b977898325" - const address: string = "X-local18jma8ppw3nhx5r4ap8clazz0dps7rv5u00z96u" - const bech32: SerializedType = "bech32" - const addressBuf: Buffer = serialization.typeToBuffer(address, bech32) - const threshold: number = 1 - const thresholdHex: string = "00000001" - const minters: string[] = [xAddress] - const assetID: Buffer = serialization.typeToBuffer(cChainID, cb58) - const assetidHex: string = - "9d0775f450604bd2fbc49ce0c5c1c6dfeb2dc2acb8c92c26eeae6e6df4502b19" - const payload: Buffer = Buffer.from("From snowflake to Avalanche") - const groupIDHex: string = "00003039" - const payloadHex: string = - "46726f6d20736e6f77666c616b6520746f204176616c616e636865" - const locktime: BN = new BN(0) - const locktimeHex: string = "0000000000000000" - - describe("AVM", (): void => { - const blockchainIDCB58: Buffer = serialization.typeToBuffer( - Defaults.network[12345]["X"].blockchainID, - cb58 - ) - const blockchainIDHex: string = - "d891ad56056d9c01f18f43f58b5c784ad07a4a49cf3d1f11623804b5cba2c6bf" - const defaultNetworkIDHex: string = "00000001" - const localNetworkIDHex: string = "00000539" - const outs: TransferableOutput[] = [] - const ins: TransferableInput[] = [] - const vm: string = "AVM" - const groupID: number = 12345 - - test("GenesisAsset", (): void => { - const assetAlias: string = "asset1" - const name: string = "asset1" - const symbol: string = "MFCA" - const nameHex: string = serialization.encoder(name, hex, utf8, utf8) - const symbolHex: string = serialization.encoder(symbol, hex, utf8, utf8) - const denomination: number = 1 - const vcapSecpOutput = new SECPTransferOutput( - amount, - [addressBuf], - locktime, - threshold - ) - const initialStates: InitialStates = new InitialStates() - initialStates.addOutput(vcapSecpOutput) - const genesisasset: GenesisAsset = new GenesisAsset( - assetAlias, - name, - symbol, - denomination, - initialStates, - memo - ) - const genesisasset2: GenesisAsset = new GenesisAsset() - const notes: string = "AVM GenesisAsset" - const serialized: Serialized = serialization.serialize( - genesisasset, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("GenesisAsset") - expect(serialized.fields["_typeID"]).toBeNull() - expect(serialized.fields["_codecID"]).toBeNull() - expect(serialized.fields["networkID"]).toBe(defaultNetworkIDHex) - expect(serialized.fields["name"]).toBe(nameHex) - expect(serialized.fields["symbol"]).toBe(symbolHex) - expect(serialized.fields["denomination"]).toBe("01") - expect(serialized.fields["memo"]).toBe(mHex) - - serialization.deserialize(serialized, genesisasset2) - expect(genesisasset2.getTypeName()).toBe("GenesisAsset") - expect(genesisasset2.getTypeID()).toBeUndefined() - expect(genesisasset2.getCodecID()).toBeUndefined() - expect(genesisasset2.getBlockchainID().toString(hex)).toBe( - "1010101010101010101010101010101010101010101010101010101010101010" - ) - expect(genesisasset2.getNetworkID()).toBe(DefaultNetworkID) - expect(genesisasset2.getOuts()).toStrictEqual([]) - expect(genesisasset2.getIns()).toStrictEqual([]) - expect(genesisasset2.getAssetAlias()).toBe(assetAlias) - expect(genesisasset2.getName()).toBe(name) - expect(genesisasset2.getSymbol()).toBe(symbol) - expect(genesisasset2.getDenomination()).toBe(denomination) - expect(serialization.bufferToType(genesisasset2.getMemo(), cb58)).toBe( - m - ) - expect(genesisasset2.toBuffer().toString(hex)).toBe( - genesisasset.toBuffer().toString(hex) - ) - expect(genesisasset2.toString()).toBe(genesisasset.toString()) - }) - - test("BaseTx", (): void => { - const basetx: BaseTx = new BaseTx( - networkID, - blockchainIDCB58, - outs, - ins, - memo - ) - const basetx2: BaseTx = new BaseTx() - const notes: string = "AVM BaseTx" - const serialized: Serialized = serialization.serialize( - basetx, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("BaseTx") - expect(serialized.fields["_typeID"]).toBe(0) - expect(serialized.fields["_codecID"]).toBe(0) - expect(serialized.fields["blockchainID"]).toBe(blockchainIDHex) - expect(serialized.fields["networkID"]).toBe(localNetworkIDHex) - expect(serialized.fields["outs"]).toStrictEqual([]) - expect(serialized.fields["ins"]).toStrictEqual([]) - expect(serialized.fields["memo"]).toBe(mHex) - - serialization.deserialize(serialized, basetx2) - expect(basetx2.getTypeName()).toBe("BaseTx") - expect(basetx2.getTypeID()).toBe(0) - expect(basetx2.getCodecID()).toBe(0) - expect(basetx2.getBlockchainID().toString(hex)).toBe(blockchainIDHex) - expect(basetx2.getNetworkID()).toBe(networkID) - expect(basetx2.getOuts()).toStrictEqual([]) - expect(basetx2.getIns()).toStrictEqual([]) - expect(serialization.bufferToType(basetx2.getMemo(), cb58)).toBe(m) - expect(basetx2.toBuffer().toString(hex)).toBe( - basetx.toBuffer().toString(hex) - ) - expect(basetx2.toString()).toBe(basetx.toString()) - }) - - test("CreateAssetTx", (): void => { - const name: string = "Test Token" - const nameHex: string = "5465737420546f6b656e" - const symbol: string = "TEST" - const symbolHex: string = "54455354" - const denomination: number = 1 - const denominationHex: string = "01" - const initialState: InitialStates = new InitialStates() - const createassettx: CreateAssetTx = new CreateAssetTx( - networkID, - blockchainIDCB58, - outs, - ins, - memo, - name, - symbol, - denomination, - initialState - ) - const createassettx2: CreateAssetTx = new CreateAssetTx() - const notes: string = "AVM CreateAssetTx" - const serialized: Serialized = serialization.serialize( - createassettx, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("CreateAssetTx") - expect(serialized.fields["_typeID"]).toBe(1) - expect(serialized.fields["_codecID"]).toBe(0) - expect(serialized.fields["blockchainID"]).toBe(blockchainIDHex) - expect(serialized.fields["networkID"]).toBe(localNetworkIDHex) - expect(serialized.fields["outs"]).toStrictEqual([]) - expect(serialized.fields["ins"]).toStrictEqual([]) - expect(serialized.fields["memo"]).toBe(mHex) - expect(serialized.fields["name"]).toBe(nameHex) - expect(serialized.fields["symbol"]).toBe(symbolHex) - expect(serialized.fields["denomination"]).toBe(denominationHex) - - serialization.deserialize(serialized, createassettx2) - expect(createassettx2.getTypeName()).toBe("CreateAssetTx") - expect(createassettx2.getTypeID()).toBe(1) - expect(createassettx2.getCodecID()).toBe(0) - expect(createassettx2.getBlockchainID().toString(hex)).toBe( - blockchainIDHex - ) - expect(createassettx2.getNetworkID()).toBe(networkID) - expect(createassettx2.getOuts()).toStrictEqual([]) - expect(createassettx2.getIns()).toStrictEqual([]) - expect(createassettx2.getName()).toBe(name) - expect(createassettx2.getSymbol()).toBe(symbol) - expect(createassettx2.getDenomination()).toBe(denomination) - expect(serialization.bufferToType(createassettx2.getMemo(), cb58)).toBe( - m - ) - expect(createassettx2.toBuffer().toString(hex)).toBe( - createassettx.toBuffer().toString(hex) - ) - expect(createassettx2.toString()).toBe(createassettx.toString()) - }) - - test("OperationTx", (): void => { - const ops: TransferableOperation[] = [] - const operationtx: OperationTx = new OperationTx( - networkID, - blockchainIDCB58, - outs, - ins, - memo, - ops - ) - const operationtx2: OperationTx = new OperationTx() - const notes: string = "AVM OperationTx" - const serialized: Serialized = serialization.serialize( - operationtx, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("OperationTx") - expect(serialized.fields["_typeID"]).toBe(2) - expect(serialized.fields["_codecID"]).toBe(0) - expect(serialized.fields["blockchainID"]).toBe(blockchainIDHex) - expect(serialized.fields["networkID"]).toBe(localNetworkIDHex) - expect(serialized.fields["outs"]).toStrictEqual([]) - expect(serialized.fields["ins"]).toStrictEqual([]) - expect(serialized.fields["memo"]).toBe(mHex) - expect(serialized.fields["ops"]).toStrictEqual([]) - - serialization.deserialize(serialized, operationtx2) - expect(operationtx2.getTypeName()).toBe("OperationTx") - expect(operationtx2.getTypeID()).toBe(2) - expect(operationtx2.getCodecID()).toBe(0) - expect(operationtx2.getBlockchainID().toString(hex)).toBe( - blockchainIDHex - ) - expect(operationtx2.getNetworkID()).toBe(networkID) - expect(operationtx2.getOuts()).toStrictEqual([]) - expect(operationtx2.getIns()).toStrictEqual([]) - expect(operationtx2.getOperations()).toStrictEqual([]) - expect(serialization.bufferToType(operationtx2.getMemo(), cb58)).toBe(m) - expect(operationtx2.toBuffer().toString(hex)).toBe( - operationtx.toBuffer().toString(hex) - ) - expect(operationtx2.toString()).toBe(operationtx.toString()) - }) - - test("ImportTx", (): void => { - const sourceChain: Buffer = serialization.typeToBuffer(cChainID, cb58) - const importIns: TransferableInput[] = [] - const importtx: ImportTx = new ImportTx( - networkID, - blockchainIDCB58, - outs, - ins, - memo, - sourceChain, - importIns - ) - const importtx2: ImportTx = new ImportTx() - const notes: string = "AVM ImportTx" - const serialized: Serialized = serialization.serialize( - importtx, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("ImportTx") - expect(serialized.fields["_typeID"]).toBe(3) - expect(serialized.fields["_codecID"]).toBe(0) - expect(serialized.fields["blockchainID"]).toBe(blockchainIDHex) - expect(serialized.fields["networkID"]).toBe(localNetworkIDHex) - expect(serialized.fields["outs"]).toStrictEqual([]) - expect(serialized.fields["ins"]).toStrictEqual([]) - expect(serialized.fields["memo"]).toBe(mHex) - expect(serialized.fields["sourceChain"]).toBe(cChainIDHex) - expect(serialized.fields["importIns"]).toStrictEqual([]) - - serialization.deserialize(serialized, importtx2) - expect(importtx2.getTypeName()).toBe("ImportTx") - expect(importtx2.getTypeID()).toBe(3) - expect(importtx2.getCodecID()).toBe(0) - expect(importtx2.getBlockchainID().toString(hex)).toBe(blockchainIDHex) - expect(importtx2.getNetworkID()).toBe(networkID) - expect(importtx2.getOuts()).toStrictEqual([]) - expect(importtx2.getIns()).toStrictEqual([]) - expect(importtx2.getSourceChain().toString(hex)).toBe( - sourceChain.toString(hex) - ) - expect(importtx2.getImportInputs()).toStrictEqual([]) - expect(serialization.bufferToType(importtx2.getMemo(), cb58)).toBe(m) - expect(importtx2.toBuffer().toString(hex)).toBe( - importtx.toBuffer().toString(hex) - ) - expect(importtx2.toString()).toBe(importtx.toString()) - }) - - test("ExportTx", (): void => { - const destinationChain: Buffer = serialization.typeToBuffer( - cChainID, - cb58 - ) - const exportOuts: TransferableOutput[] = [] - const exporttx: ExportTx = new ExportTx( - networkID, - blockchainIDCB58, - outs, - ins, - memo, - destinationChain, - exportOuts - ) - const exporttx2: ExportTx = new ExportTx() - const notes: string = "AVM ExportTx" - const serialized: Serialized = serialization.serialize( - exporttx, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("ExportTx") - expect(serialized.fields["_typeID"]).toBe(4) - expect(serialized.fields["_codecID"]).toBe(0) - expect(serialized.fields["blockchainID"]).toBe(blockchainIDHex) - expect(serialized.fields["networkID"]).toBe(localNetworkIDHex) - expect(serialized.fields["outs"]).toStrictEqual([]) - expect(serialized.fields["ins"]).toStrictEqual([]) - expect(serialized.fields["memo"]).toBe(mHex) - expect(serialized.fields["destinationChain"]).toBe(cChainIDHex) - expect(serialized.fields["exportOuts"]).toStrictEqual([]) - - serialization.deserialize(serialized, exporttx2) - expect(exporttx2.getTypeName()).toBe("ExportTx") - expect(exporttx2.getTypeID()).toBe(4) - expect(exporttx2.getCodecID()).toBe(0) - expect(exporttx2.getBlockchainID().toString(hex)).toBe(blockchainIDHex) - expect(exporttx2.getNetworkID()).toBe(networkID) - expect(exporttx2.getOuts()).toStrictEqual([]) - expect(exporttx2.getIns()).toStrictEqual([]) - expect(exporttx2.getDestinationChain().toString(hex)).toBe( - destinationChain.toString(hex) - ) - expect(exporttx2.getExportOutputs()).toStrictEqual([]) - expect(serialization.bufferToType(exporttx2.getMemo(), cb58)).toBe(m) - expect(exporttx2.toBuffer().toString(hex)).toBe( - exporttx.toBuffer().toString(hex) - ) - expect(exporttx2.toString()).toBe(exporttx.toString()) - }) - - test("SECPCredential", (): void => { - const sigArray: Signature[] = [] - const secpcredential: SECPCredential = new SECPCredential(sigArray) - const secpcredential2: SECPCredential = new SECPCredential() - const notes: string = "AVM SECPCredential" - const serialized: Serialized = serialization.serialize( - secpcredential, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("SECPCredential") - expect(serialized.fields["_typeID"]).toBe(9) - expect(serialized.fields["_codecID"]).toBe(0) - expect(serialized.fields["sigArray"]).toStrictEqual([]) - - serialization.deserialize(serialized, secpcredential2) - expect(secpcredential2.getTypeName()).toBe("SECPCredential") - expect(secpcredential2.getTypeID()).toBe(9) - expect(secpcredential2.getCodecID()).toBe(0) - expect(secpcredential2.getCredentialID()).toBe(9) - expect(secpcredential2.toBuffer().toString(hex)).toBe( - secpcredential.toBuffer().toString(hex) - ) - expect(secpcredential2.toString()).toBe(secpcredential.toString()) - }) - - test("NFTCredential", (): void => { - const sigArray: Signature[] = [] - const nftcredential: NFTCredential = new NFTCredential(sigArray) - const nftcredential2: NFTCredential = new NFTCredential() - const notes: string = "AVM NFTCredential" - const serialized: Serialized = serialization.serialize( - nftcredential, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("NFTCredential") - expect(serialized.fields["_typeID"]).toBe(14) - expect(serialized.fields["_codecID"]).toBe(0) - expect(serialized.fields["sigArray"]).toStrictEqual([]) - - serialization.deserialize(serialized, nftcredential2) - expect(nftcredential2.getTypeName()).toBe("NFTCredential") - expect(nftcredential2.getTypeID()).toBe(14) - expect(nftcredential2.getCodecID()).toBe(0) - expect(nftcredential2.getCredentialID()).toBe(14) - expect(nftcredential2.toBuffer().toString(hex)).toBe( - nftcredential.toBuffer().toString(hex) - ) - expect(nftcredential2.toString()).toBe(nftcredential.toString()) - }) - - test("InitialStates", (): void => { - const initialStates: InitialStates = new InitialStates() - const initialStates2: InitialStates = new InitialStates() - const notes: string = "AVM InitialStates" - const serialized: Serialized = serialization.serialize( - initialStates, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("InitialStates") - expect(serialized.fields["_typeID"]).toBeNull() - expect(serialized.fields["_codecID"]).toBeNull() - expect(serialized.fields["fxs"]).toStrictEqual({}) - - serialization.deserialize(serialized, initialStates2) - expect(initialStates2.getTypeName()).toBe("InitialStates") - expect(initialStates2.getTypeID()).toBeUndefined() - expect(initialStates2.getCodecID()).toBeUndefined() - expect(initialStates2.toBuffer().toString(hex)).toBe( - initialStates.toBuffer().toString(hex) - ) - expect(initialStates2.toString()).toBe(initialStates.toString()) - }) - - test("SECPTransferInput", (): void => { - const secptransferinput: SECPTransferInput = new SECPTransferInput() - const secptransferinput2: SECPTransferInput = new SECPTransferInput() - const notes: string = "AVM SECPTransferInput" - const serialized: Serialized = serialization.serialize( - secptransferinput, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("SECPTransferInput") - expect(serialized.fields["_typeID"]).toBe(5) - expect(serialized.fields["_codecID"]).toBe(0) - expect(serialized.fields["sigIdxs"]).toStrictEqual([]) - expect(serialized.fields["amount"]).toBe(amountHex) - - serialization.deserialize(serialized, secptransferinput2) - expect(secptransferinput2.getTypeName()).toBe("SECPTransferInput") - expect(secptransferinput2.getTypeID()).toBe(5) - expect(secptransferinput2.getCodecID()).toBe(0) - expect(secptransferinput2.getAmount().toString()).toBe( - amount.toString() - ) - expect(secptransferinput2.getSigIdxs()).toStrictEqual([]) - expect(secptransferinput2.toBuffer().toString(hex)).toBe( - secptransferinput.toBuffer().toString(hex) - ) - expect(secptransferinput2.toString()).toBe(secptransferinput.toString()) - }) - - test("MinterSet", (): void => { - const minterset: MinterSet = new MinterSet(threshold, minters) - const minterset2: MinterSet = new MinterSet() - const notes: string = "AVM MinterSet" - const serialized: Serialized = serialization.serialize( - minterset, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("MinterSet") - expect(serialized.fields["_typeID"]).toBeNull() - expect(serialized.fields["_codecID"]).toBeNull() - expect(serialized.fields["threshold"]).toBe(thresholdHex) - expect(serialized.fields["minters"]).toStrictEqual([xAddressHex]) - - serialization.deserialize(serialized, minterset2) - expect(minterset2.getTypeName()).toBe("MinterSet") - expect(minterset2.getTypeID()).toBeUndefined() - expect(minterset2.getCodecID()).toBeUndefined() - expect(minterset2.getThreshold()).toBe(threshold) - expect(minterset2.getMinters()).toStrictEqual([ - serialization.typeToBuffer(xAddressHex, hex) - ]) - }) - - test("TransferableOperation", (): void => { - const secpmintoutput: SECPMintOutput = new SECPMintOutput() - const transferOutput: SECPTransferOutput = new SECPTransferOutput() - const utxoids: string[] = [] - const secpmintoperation: SECPMintOperation = new SECPMintOperation( - secpmintoutput, - transferOutput - ) - const transferableoperation: TransferableOperation = - new TransferableOperation(assetID, utxoids, secpmintoperation) - const transferableoperation2: TransferableOperation = - new TransferableOperation() - const notes: string = "AVM TransferableOperation" - const serialized: Serialized = serialization.serialize( - transferableoperation, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("TransferableOperation") - expect(serialized.fields["_typeID"]).toBeNull() - expect(serialized.fields["_codecID"]).toBeNull() - expect(serialized.fields["assetID"]).toBe(assetidHex) - expect(serialized.fields["utxoIDs"]).toStrictEqual([]) - - serialization.deserialize(serialized, transferableoperation2) - expect(transferableoperation2.getTypeName()).toBe( - "TransferableOperation" - ) - expect(transferableoperation2.getTypeID()).toBeUndefined() - expect(transferableoperation2.getCodecID()).toBeUndefined() - expect(transferableoperation2.getAssetID().toString(hex)).toBe( - assetID.toString(hex) - ) - expect(transferableoperation2.getUTXOIDs()).toStrictEqual([]) - expect(transferableoperation2.toBuffer().toString(hex)).toBe( - transferableoperation.toBuffer().toString(hex) - ) - expect(transferableoperation2.toString()).toBe( - transferableoperation.toString() - ) - }) - - test("SECPMintOperation", (): void => { - const secpmintoutput: SECPMintOutput = new SECPMintOutput() - const secptransferoutput: SECPTransferOutput = new SECPTransferOutput() - const secpmintoperation: SECPMintOperation = new SECPMintOperation( - secpmintoutput, - secptransferoutput - ) - const secpmintoperation2: SECPMintOperation = new SECPMintOperation() - const notes: string = "AVM SECPMintOperation" - const serialized: Serialized = serialization.serialize( - secpmintoperation, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("SECPMintOperation") - expect(serialized.fields["_typeID"]).toBe(8) - expect(serialized.fields["_codecID"]).toBe(0) - expect(serialized.fields["sigIdxs"]).toStrictEqual([]) - - serialization.deserialize(serialized, secpmintoperation2) - expect(secpmintoperation2.getTypeName()).toBe("SECPMintOperation") - expect(secpmintoperation2.getTypeID()).toBe(8) - expect(secpmintoperation2.getCodecID()).toBe(0) - expect(secpmintoperation2.getSigIdxs()).toStrictEqual([]) - expect(secpmintoperation2.toBuffer().toString(hex)).toBe( - secpmintoperation.toBuffer().toString(hex) - ) - expect(secpmintoperation2.toString()).toBe(secpmintoperation.toString()) - }) - - test("NFTMintOperation", (): void => { - // TODO - fix this type mismatch - // Error - Serializable.deserialize: _typeName mismatch -- expected: OutputOwners -- received: NFTMintOutput - // const nftmintoutput: NFTMintOutput = new NFTMintOutput() - // const nftmintoperation: NFTMintOperation = new NFTMintOperation(groupID, payload, [nftmintoutput]) - // const nftmintoperation2: NFTMintOperation = new NFTMintOperation() - // const notes: string = "AVM NFTMintOperation" - // const serialized: Serialized = serialization.serialize(nftmintoperation, vm, hex, notes) - // expect(serialized.vm).toBe(vm) - // expect(serialized.encoding).toBe(hex) - // expect(serialized.notes).toBe(notes) - // expect(serialized.fields["_typeName"]).toBe("NFTMintOperation") - // expect(serialized.fields["_typeID"]).toBe(12) - // expect(serialized.fields["_codecID"]).toBe(0) - // expect(serialized.fields["sigIdxs"]).toStrictEqual([]) - // expect(serialized.fields["groupID"]).toBe(groupIDHex) - // expect(serialized.fields["payload"]).toBe(payloadHex) - // serialization.deserialize(serialized, nftmintoperation2) - // expect(nftmintoperation2.getTypeName()).toBe("NFTMintOperation") - // expect(nftmintoperation2.getTypeID()).toBe(12) - // expect(nftmintoperation2.getCodecID()).toBe(0) - // expect(nftmintoperation2.getSigIdxs()).toStrictEqual([]) - // expect(nftmintoperation2.getGroupID()).toBe(groupIDHex) - // expect(nftmintoperation2.getPayload().toString("hex")).toBe(payload.toString("hex")) - // expect(nftmintoperation2.toBuffer().toString("hex")).toBe(nftmintoperation.toBuffer().toString("hex")) - // expect(nftmintoperation2.toString()).toBe(nftmintoperation.toString()) - }) - - test("NFTTransferOperation", (): void => { - const nfttransferoutput: NFTTransferOutput = new NFTTransferOutput( - groupID, - payload - ) - const nfttransferoperation: NFTTransferOperation = - new NFTTransferOperation(nfttransferoutput) - const nfttransferoperation2: NFTTransferOperation = - new NFTTransferOperation() - const notes: string = "AVM NFTTransferOperation" - const serialized: Serialized = serialization.serialize( - nfttransferoperation, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("NFTTransferOperation") - expect(serialized.fields["_typeID"]).toBe(13) - expect(serialized.fields["_codecID"]).toBe(0) - expect(serialized.fields["sigIdxs"]).toStrictEqual([]) - - serialization.deserialize(serialized, nfttransferoperation2) - expect(nfttransferoperation2.getTypeName()).toBe("NFTTransferOperation") - expect(nfttransferoperation2.getTypeID()).toBe(13) - expect(nfttransferoperation2.getCodecID()).toBe(0) - expect(nfttransferoperation2.getOperationID()).toBe(13) - expect(nfttransferoperation2.getCredentialID()).toBe(14) - expect(nfttransferoperation2.getOutput().toBuffer().toString(hex)).toBe( - nfttransferoutput.toBuffer().toString(hex) - ) - expect(nfttransferoperation2.getSigIdxs()).toStrictEqual([]) - expect(nfttransferoperation2.toBuffer().toString(hex)).toBe( - nfttransferoperation.toBuffer().toString(hex) - ) - expect(nfttransferoperation2.toString()).toBe( - nfttransferoperation.toString() - ) - }) - - test("UTXOID", (): void => { - const bsize: string = "00000024" - const size: number = 36 - const bytes: string = - "000000000000000000000000000000000000000000000000000000000000000000000000" - const utxoid: UTXOID = new UTXOID() - const utxoid2: UTXOID = new UTXOID() - const notes: string = "AVM UTXOID" - const serialized: Serialized = serialization.serialize( - utxoid, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("UTXOID") - expect(serialized.fields["_typeID"]).toBeNull() - expect(serialized.fields["_codecID"]).toBeNull() - expect(serialized.fields["bsize"]).toBe(bsize) - expect(serialized.fields["bytes"]).toBe(bytes) - - serialization.deserialize(serialized, utxoid2) - expect(utxoid2.getTypeName()).toBe("UTXOID") - expect(utxoid2.getTypeID()).toBeUndefined() - expect(utxoid2.getCodecID()).toBeUndefined() - expect(utxoid2.getSize()).toBe(size) - expect(utxoid2.toBuffer().toString(hex)).toBe( - utxoid.toBuffer().toString(hex) - ) - expect(utxoid2.toString()).toBe(utxoid2.toString()) - }) - - test("TransferableOutput", (): void => { - const secpmintoutput: SECPMintOutput = new SECPMintOutput() - const transferableoutput: TransferableOutput = new TransferableOutput( - assetID, - secpmintoutput - ) - const transferableoutput2: TransferableOutput = new TransferableOutput() - const notes: string = "AVM TransferableOutput" - const serialized: Serialized = serialization.serialize( - transferableoutput, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("TransferableOutput") - expect(serialized.fields["_typeID"]).toBeNull() - expect(serialized.fields["_codecID"]).toBeNull() - expect(serialized.fields["assetID"]).toBe(assetidHex) - - serialization.deserialize(serialized, transferableoutput2) - expect(transferableoutput2.getTypeName()).toBe("TransferableOutput") - expect(transferableoutput2.getTypeID()).toBeUndefined() - expect(transferableoutput2.getCodecID()).toBeUndefined() - expect(transferableoutput2.getAssetID().toString(hex)).toBe( - assetID.toString(hex) - ) - expect(transferableoutput2.toBuffer().toString(hex)).toBe( - transferableoutput.toBuffer().toString(hex) - ) - expect(transferableoutput2.toString()).toBe( - transferableoutput.toString() - ) - }) - - test("SECPTransferOutput", (): void => { - const secptransferoutput: SECPTransferOutput = new SECPTransferOutput() - const secptransferoutput2: SECPTransferOutput = new SECPTransferOutput() - const notes: string = "AVM SECPTransferOutput" - const serialized: Serialized = serialization.serialize( - secptransferoutput, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("SECPTransferOutput") - expect(serialized.fields["_typeID"]).toBe(7) - expect(serialized.fields["_codecID"]).toBe(0) - expect(serialized.fields["locktime"]).toBe(locktimeHex) - expect(serialized.fields["threshold"]).toBe(thresholdHex) - expect(serialized.fields["addresses"]).toStrictEqual([]) - expect(serialized.fields["amount"]).toBe(amountHex) - - serialization.deserialize(serialized, secptransferoutput2) - expect(secptransferoutput2.getTypeName()).toBe("SECPTransferOutput") - expect(secptransferoutput2.getTypeID()).toBe(7) - expect(secptransferoutput2.getCodecID()).toBe(0) - expect(secptransferoutput2.getLocktime().toString()).toBe( - locktime.toString() - ) - expect(secptransferoutput2.getThreshold()).toBe(threshold) - expect(secptransferoutput2.getAddresses()).toStrictEqual([]) - expect(secptransferoutput2.getAmount().toString()).toStrictEqual( - amount.toString() - ) - expect(secptransferoutput2.toBuffer().toString(hex)).toBe( - secptransferoutput.toBuffer().toString(hex) - ) - expect(secptransferoutput2.toString()).toBe( - secptransferoutput.toString() - ) - }) - - test("SECPMintOutput", (): void => { - const secpmintoutput: SECPMintOutput = new SECPMintOutput() - const secpmintoutput2: SECPMintOutput = new SECPMintOutput() - const notes: string = "AVM SECPMintOutput" - const serialized: Serialized = serialization.serialize( - secpmintoutput, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("SECPMintOutput") - expect(serialized.fields["_typeID"]).toBe(6) - expect(serialized.fields["_codecID"]).toBe(0) - expect(serialized.fields["locktime"]).toBe(locktimeHex) - expect(serialized.fields["threshold"]).toBe(thresholdHex) - expect(serialized.fields["addresses"]).toStrictEqual([]) - - serialization.deserialize(serialized, secpmintoutput2) - expect(secpmintoutput2.getTypeName()).toBe("SECPMintOutput") - expect(secpmintoutput2.getTypeID()).toBe(6) - expect(secpmintoutput2.getCodecID()).toBe(0) - expect(secpmintoutput2.getLocktime().toString()).toBe( - locktime.toString() - ) - expect(secpmintoutput2.getThreshold()).toBe(threshold) - expect(secpmintoutput2.getAddresses()).toStrictEqual([]) - expect(secpmintoutput2.toBuffer().toString(hex)).toBe( - secpmintoutput.toBuffer().toString(hex) - ) - expect(secpmintoutput2.toString()).toBe(secpmintoutput.toString()) - }) - - test("NFTMintOutput", (): void => { - const nftmintoutput: NFTMintOutput = new NFTMintOutput(groupID) - const nftmintoutput2: NFTMintOutput = new NFTMintOutput() - const notes: string = "AVM NFTMintOutput" - const serialized: Serialized = serialization.serialize( - nftmintoutput, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("NFTMintOutput") - expect(serialized.fields["_typeID"]).toBe(10) - expect(serialized.fields["_codecID"]).toBe(0) - expect(serialized.fields["locktime"]).toBe(locktimeHex) - expect(serialized.fields["threshold"]).toBe(thresholdHex) - expect(serialized.fields["addresses"]).toStrictEqual([]) - expect(serialized.fields["groupID"]).toBe(groupIDHex) - - serialization.deserialize(serialized, nftmintoutput2) - expect(nftmintoutput2.getTypeName()).toBe("NFTMintOutput") - expect(nftmintoutput2.getTypeID()).toBe(10) - expect(nftmintoutput2.getCodecID()).toBe(0) - expect(nftmintoutput2.getLocktime().toString()).toBe( - locktime.toString() - ) - expect(nftmintoutput2.getThreshold()).toBe(threshold) - expect(nftmintoutput2.getAddresses()).toStrictEqual([]) - expect(nftmintoutput2.getGroupID()).toBe(groupID) - expect(nftmintoutput2.toBuffer().toString(hex)).toBe( - nftmintoutput.toBuffer().toString(hex) - ) - expect(nftmintoutput2.toString()).toBe(nftmintoutput.toString()) - }) - - test("NFTTransferOutput", (): void => { - const nfttransferoutput: NFTTransferOutput = new NFTTransferOutput( - groupID, - payload - ) - const nfttransferoutput2: NFTTransferOutput = new NFTTransferOutput() - const notes: string = "AVM NFTTransferOutput" - const serialized: Serialized = serialization.serialize( - nfttransferoutput, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("NFTTransferOutput") - expect(serialized.fields["_typeID"]).toBe(11) - expect(serialized.fields["_codecID"]).toBe(0) - expect(serialized.fields["locktime"]).toBe(locktimeHex) - expect(serialized.fields["threshold"]).toBe(thresholdHex) - expect(serialized.fields["addresses"]).toStrictEqual([]) - expect(serialized.fields["groupID"]).toBe(groupIDHex) - expect(serialized.fields["payload"]).toBe(payloadHex) - - serialization.deserialize(serialized, nfttransferoutput2) - expect(nfttransferoutput2.getTypeName()).toBe("NFTTransferOutput") - expect(nfttransferoutput2.getTypeID()).toBe(11) - expect(nfttransferoutput2.getCodecID()).toBe(0) - expect(nfttransferoutput2.getLocktime().toString()).toBe( - locktime.toString() - ) - expect(nfttransferoutput2.getThreshold()).toBe(threshold) - expect(nfttransferoutput2.getAddresses()).toStrictEqual([]) - expect(nfttransferoutput2.getGroupID()).toBe(groupID) - expect(nfttransferoutput2.getPayload().toString(hex)).toBe(payloadHex) - expect(nfttransferoutput2.toBuffer().toString(hex)).toBe( - nfttransferoutput.toBuffer().toString(hex) - ) - expect(nfttransferoutput2.toString()).toBe(nfttransferoutput.toString()) - }) - - test("UnsignedTx", (): void => { - const basetx: BaseTx = new BaseTx( - networkID, - blockchainIDCB58, - outs, - ins, - memo - ) - const unsignedtx: UnsignedTx = new UnsignedTx(basetx) - const unsignedtx2: UnsignedTx = new UnsignedTx() - const notes: string = "AVM UnsignedTx" - const serialized: Serialized = serialization.serialize( - unsignedtx, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("UnsignedTx") - expect(serialized.fields["_typeID"]).toBeNull() - expect(serialized.fields["_codecID"]).toBeNull() - - serialization.deserialize(serialized, unsignedtx2) - expect(unsignedtx2.getTypeName()).toBe("UnsignedTx") - expect(unsignedtx2.getTypeID()).toBeUndefined() - // TODO - StandardUnsignedTx is setting codecID to 0 - // Bring this inline w/ the new codecID patterns - // expect(unsignedtx2.getCodecID()).toBeUndefined() - expect(unsignedtx2.toBuffer().toString(hex)).toBe( - unsignedtx.toBuffer().toString(hex) - ) - expect(unsignedtx2.toString()).toBe(unsignedtx.toString()) - }) - - test("Tx", (): void => { - const basetx: BaseTx = new BaseTx( - networkID, - blockchainIDCB58, - outs, - ins, - memo - ) - const unsignedtx: UnsignedTx = new UnsignedTx(basetx) - const tx: Tx = new Tx(unsignedtx) - const tx2: Tx = new Tx() - const notes: string = "AVM Tx" - const serialized: Serialized = serialization.serialize( - tx, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("Tx") - expect(serialized.fields["_typeID"]).toBeNull() - expect(serialized.fields["_codecID"]).toBeNull() - expect(serialized.fields["credentials"]).toStrictEqual([]) - - serialization.deserialize(serialized, tx2) - expect(tx2.getTypeName()).toBe("Tx") - expect(tx2.getTypeID()).toBeUndefined() - expect(tx2.getCodecID()).toBeUndefined() - expect(tx2.getCredentials()).toStrictEqual([]) - expect(tx2.toBuffer().toString(hex)).toBe(tx.toBuffer().toString(hex)) - expect(tx2.toString()).toBe(tx.toString()) - }) - - test("UTXO", (): void => { - const codecID: number = 0 - const txID: Buffer = serialization.typeToBuffer(cChainID, cb58) - const txidHex: string = - "9d0775f450604bd2fbc49ce0c5c1c6dfeb2dc2acb8c92c26eeae6e6df4502b19" - const outputidx: number = 0 - const outputidxHex: string = "00000000" - const assetID: Buffer = serialization.typeToBuffer(cChainID, cb58) - const nfttransferoutput: NFTTransferOutput = new NFTTransferOutput( - groupID, - payload - ) - const utxo: UTXO = new UTXO( - codecID, - txID, - outputidx, - assetID, - nfttransferoutput - ) - const utxo2: UTXO = new UTXO() - const notes: string = "AVM UTXO" - const serialized: Serialized = serialization.serialize( - utxo, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("UTXO") - expect(serialized.fields["_typeID"]).toBeNull() - expect(serialized.fields["_codecID"]).toBeNull() - expect(serialized.fields["txid"]).toBe(txidHex) - expect(serialized.fields["outputidx"]).toBe(outputidxHex) - expect(serialized.fields["assetID"]).toBe(assetidHex) - - serialization.deserialize(serialized, utxo2) - expect(utxo2.getTypeName()).toBe("UTXO") - expect(utxo2.getTypeID()).toBeUndefined() - // TODO - StandardUnsignedTx is setting codecID to 0 - // Bring this inline w/ the new codecID patterns - // expect(utxo2.getCodecID()).toBeUndefined() - expect(utxo2.getTxID().toString(hex)).toBe(txidHex) - expect(utxo2.getOutputIdx().toString(hex)).toBe(outputidxHex) - expect(utxo2.getAssetID().toString(hex)).toBe(assetID.toString(hex)) - expect(utxo2.toBuffer().toString(hex)).toBe( - utxo.toBuffer().toString(hex) - ) - expect(utxo2.toString()).toBe(utxo.toString()) - }) - - test("UTXOSet", (): void => { - const utxoset: UTXOSet = new UTXOSet() - const utxoset2: UTXOSet = new UTXOSet() - const notes: string = "AVM UTXOSet" - const serialized: Serialized = serialization.serialize( - utxoset, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("UTXOSet") - expect(serialized.fields["_typeID"]).toBeNull() - expect(serialized.fields["_codecID"]).toBeNull() - expect(serialized.fields["utxos"]).toStrictEqual({}) - expect(serialized.fields["addressUTXOs"]).toStrictEqual({}) - - serialization.deserialize(serialized, utxoset2) - expect(utxoset2.getTypeName()).toBe("UTXOSet") - expect(utxoset2.getTypeID()).toBeUndefined() - expect(utxoset2.getCodecID()).toBeUndefined() - expect(utxoset2.getAllUTXOs()).toStrictEqual([]) - expect(utxoset2.getAllUTXOStrings()).toStrictEqual([]) - expect(utxoset2.getAddresses()).toStrictEqual([]) - }) - - test("Address", (): void => { - const bsize: string = "00000014" - const address: Address = new Address() - const address2: Address = new Address() - const notes: string = "Address" - const serialized: Serialized = serialization.serialize( - address, - vm, - hex, - notes - ) - expect(serialized.vm).toBe(vm) - expect(serialized.encoding).toBe(hex) - expect(serialized.notes).toBe(notes) - expect(serialized.fields["_typeName"]).toBe("Address") - expect(serialized.fields["_typeID"]).toBeNull() - expect(serialized.fields["_codecID"]).toBeNull() - expect(serialized.fields["bsize"]).toBe(bsize) - expect(serialized.fields["bytes"]).toBe(bytes) - - serialization.deserialize(serialized, address2) - expect(address2.getTypeName()).toBe("Address") - expect(address2.getTypeID()).toBeUndefined() - expect(address2.getCodecID()).toBeUndefined() - expect(address2.toBuffer().toString(hex)).toBe( - address.toBuffer().toString(hex) - ) - expect(address2.toString()).toBe(address.toString()) - }) - }) - }) -}) diff --git a/tsconfig.json b/tsconfig.json index 5dd48fc9c..6c1978868 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,25 +1,33 @@ { "compilerOptions": { - "outDir": "./dist/", - "baseUrl": ".", - "module": "commonjs", - "target": "ES2015", - "lib": ["dom", "es2016"], + "allowSyntheticDefaultImports": true, "declaration": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "inlineSourceMap": true, - "inlineSources": true, "declarationMap": true, - "noFallthroughCasesInSwitch": true, - "strictFunctionTypes": true, "esModuleInterop": true, - "typeRoots": ["./typings/**", "./node_modules/@types"] + "forceConsistentCasingInFileNames": true, + "moduleResolution": "node", + "noEmit": true, + "noFallthroughCasesInSwitch": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "sourceMap": true, + "strict": true, + "module": "ESNext", + "removeComments": true, + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "target": "esnext", + "outDir": "./dist", + "baseUrl": "src", + "rootDir": "src", + "strictNullChecks": true, + "noImplicitAny": false, + "strictBindCallApply": false }, - "exclude": ["node_modules", "examples", "*/**/*.test.ts", "e2e_tests"], - "include": ["src/"], - "typeAcquisition": { - "enable": true, - "exclude": ["bn.js"] + "include": ["src", "index.d.ts"], + "ts-node": { + "esm": true, + "include": ["index.ts"], + "experimentalSpecifierResolution": "node" } } diff --git a/typedoc.json b/typedoc.json deleted file mode 100644 index 8daf822a6..000000000 --- a/typedoc.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - // Comments are supported, like tsconfig.json - "entryPoints": ["src/index.ts"], - "out": "docs", - "plugin": ["typedoc-plugin-markdown"] -} diff --git a/web/COMMITHASH b/web/COMMITHASH deleted file mode 100644 index 811c9cca4..000000000 --- a/web/COMMITHASH +++ /dev/null @@ -1 +0,0 @@ -616bc4593468b53543d361bfdac061028a650c7f \ No newline at end of file diff --git a/web/LASTCOMMITDATETIME b/web/LASTCOMMITDATETIME deleted file mode 100644 index b34359a7a..000000000 --- a/web/LASTCOMMITDATETIME +++ /dev/null @@ -1 +0,0 @@ -2022-10-26T16:28:52-07:00 \ No newline at end of file diff --git a/web/VERSION b/web/VERSION deleted file mode 100644 index 3db4ad975..000000000 --- a/web/VERSION +++ /dev/null @@ -1 +0,0 @@ -v3.15.4-23-g616bc45 \ No newline at end of file diff --git a/web/avalanche.js b/web/avalanche.js deleted file mode 100644 index 2b2718acc..000000000 --- a/web/avalanche.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! For license information please see avalanche.js.LICENSE.txt */ -!function webpackUniversalModuleDefinition(root,factory){"object"==typeof exports&&"object"==typeof module?module.exports=factory():"function"==typeof define&&define.amd?define("avalanche",[],factory):"object"==typeof exports?exports.avalanche=factory():root.avalanche=factory()}(self,(()=>(()=>{var __webpack_modules__={6522:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.AdminAPI=void 0;const jrpcapi_1=__webpack_require__(5912);class AdminAPI extends jrpcapi_1.JRPCAPI{constructor(core,baseURL="/ext/admin"){super(core,baseURL),this.alias=(endpoint,alias)=>__awaiter(this,void 0,void 0,(function*(){const params={endpoint,alias},response=yield this.callMethod("admin.alias",params);return response.data.result.success?response.data.result.success:response.data.result})),this.aliasChain=(chain,alias)=>__awaiter(this,void 0,void 0,(function*(){const params={chain,alias},response=yield this.callMethod("admin.aliasChain",params);return response.data.result.success?response.data.result.success:response.data.result})),this.getChainAliases=chain=>__awaiter(this,void 0,void 0,(function*(){const params={chain},response=yield this.callMethod("admin.getChainAliases",params);return response.data.result.aliases?response.data.result.aliases:response.data.result})),this.getLoggerLevel=loggerName=>__awaiter(this,void 0,void 0,(function*(){const params={};void 0!==loggerName&&(params.loggerName=loggerName);return(yield this.callMethod("admin.getLoggerLevel",params)).data.result})),this.loadVMs=()=>__awaiter(this,void 0,void 0,(function*(){const response=yield this.callMethod("admin.loadVMs");return response.data.result.aliases?response.data.result.aliases:response.data.result})),this.lockProfile=()=>__awaiter(this,void 0,void 0,(function*(){const response=yield this.callMethod("admin.lockProfile");return response.data.result.success?response.data.result.success:response.data.result})),this.memoryProfile=()=>__awaiter(this,void 0,void 0,(function*(){const response=yield this.callMethod("admin.memoryProfile");return response.data.result.success?response.data.result.success:response.data.result})),this.setLoggerLevel=(loggerName,logLevel,displayLevel)=>__awaiter(this,void 0,void 0,(function*(){const params={};void 0!==loggerName&&(params.loggerName=loggerName),void 0!==logLevel&&(params.logLevel=logLevel),void 0!==displayLevel&&(params.displayLevel=displayLevel);return(yield this.callMethod("admin.setLoggerLevel",params)).data.result})),this.startCPUProfiler=()=>__awaiter(this,void 0,void 0,(function*(){const response=yield this.callMethod("admin.startCPUProfiler");return response.data.result.success?response.data.result.success:response.data.result})),this.stopCPUProfiler=()=>__awaiter(this,void 0,void 0,(function*(){const response=yield this.callMethod("admin.stopCPUProfiler");return response.data.result.success?response.data.result.success:response.data.result}))}}exports.AdminAPI=AdminAPI},7458:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)"default"===p||Object.prototype.hasOwnProperty.call(exports,p)||__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:!0}),__exportStar(__webpack_require__(6522),exports)},3920:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.AuthAPI=void 0;const jrpcapi_1=__webpack_require__(5912);class AuthAPI extends jrpcapi_1.JRPCAPI{constructor(core,baseURL="/ext/auth"){super(core,baseURL),this.newToken=(password,endpoints)=>__awaiter(this,void 0,void 0,(function*(){const params={password,endpoints},response=yield this.callMethod("auth.newToken",params);return response.data.result.token?response.data.result.token:response.data.result})),this.revokeToken=(password,token)=>__awaiter(this,void 0,void 0,(function*(){const params={password,token};return(yield this.callMethod("auth.revokeToken",params)).data.result.success})),this.changePassword=(oldPassword,newPassword)=>__awaiter(this,void 0,void 0,(function*(){const params={oldPassword,newPassword};return(yield this.callMethod("auth.changePassword",params)).data.result.success}))}}exports.AuthAPI=AuthAPI},7843:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)"default"===p||Object.prototype.hasOwnProperty.call(exports,p)||__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:!0}),__exportStar(__webpack_require__(3920),exports)},8313:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))},__importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.AVMAPI=void 0;const bn_js_1=__importDefault(__webpack_require__(3550)),buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),utxos_1=__webpack_require__(3140),constants_1=__webpack_require__(6667),keychain_1=__webpack_require__(2209),tx_1=__webpack_require__(2577),payload_1=__webpack_require__(9836),helperfunctions_1=__webpack_require__(5554),jrpcapi_1=__webpack_require__(5912),constants_2=__webpack_require__(8779),output_1=__webpack_require__(8556),errors_1=__webpack_require__(611),utils_1=__webpack_require__(338),bintools=bintools_1.default.getInstance(),serialization=utils_1.Serialization.getInstance();class AVMAPI extends jrpcapi_1.JRPCAPI{constructor(core,baseURL="/ext/bc/X",blockchainID=""){super(core,baseURL),this.keychain=new keychain_1.KeyChain("",""),this.blockchainID="",this.blockchainAlias=void 0,this.AVAXAssetID=void 0,this.txFee=void 0,this.creationTxFee=void 0,this.mintTxFee=void 0,this.getBlockchainAlias=()=>{if(void 0===this.blockchainAlias){const netid=this.core.getNetworkID();return netid in constants_2.Defaults.network&&this.blockchainID in constants_2.Defaults.network[`${netid}`]?(this.blockchainAlias=constants_2.Defaults.network[`${netid}`][this.blockchainID].alias,this.blockchainAlias):void 0}return this.blockchainAlias},this.setBlockchainAlias=alias=>{this.blockchainAlias=alias},this.getBlockchainID=()=>this.blockchainID,this.refreshBlockchainID=blockchainID=>{const netid=this.core.getNetworkID();return void 0===blockchainID&&void 0!==constants_2.Defaults.network[`${netid}`]?(this.blockchainID=constants_2.Defaults.network[`${netid}`].X.blockchainID,!0):"string"==typeof blockchainID&&(this.blockchainID=blockchainID,!0)},this.parseAddress=addr=>{const alias=this.getBlockchainAlias(),blockchainID=this.getBlockchainID();return bintools.parseAddress(addr,blockchainID,alias,constants_1.AVMConstants.ADDRESSLENGTH)},this.addressFromBuffer=address=>{const chainID=this.getBlockchainAlias()?this.getBlockchainAlias():this.getBlockchainID(),hrp=this.core.getHRP();return serialization.bufferToType(address,"bech32",hrp,chainID)},this.getAVAXAssetID=(refresh=!1)=>__awaiter(this,void 0,void 0,(function*(){if(void 0===this.AVAXAssetID||refresh){const asset=yield this.getAssetDescription(constants_2.PrimaryAssetAlias);this.AVAXAssetID=asset.assetID}return this.AVAXAssetID})),this.setAVAXAssetID=avaxAssetID=>{"string"==typeof avaxAssetID&&(avaxAssetID=bintools.cb58Decode(avaxAssetID)),this.AVAXAssetID=avaxAssetID},this.getDefaultTxFee=()=>this.core.getNetworkID()in constants_2.Defaults.network?new bn_js_1.default(constants_2.Defaults.network[this.core.getNetworkID()].X.txFee):new bn_js_1.default(0),this.getTxFee=()=>(void 0===this.txFee&&(this.txFee=this.getDefaultTxFee()),this.txFee),this.setTxFee=fee=>{this.txFee=fee},this.getDefaultCreationTxFee=()=>this.core.getNetworkID()in constants_2.Defaults.network?new bn_js_1.default(constants_2.Defaults.network[this.core.getNetworkID()].X.creationTxFee):new bn_js_1.default(0),this.getDefaultMintTxFee=()=>this.core.getNetworkID()in constants_2.Defaults.network?new bn_js_1.default(constants_2.Defaults.network[this.core.getNetworkID()].X.mintTxFee):new bn_js_1.default(0),this.getMintTxFee=()=>(void 0===this.mintTxFee&&(this.mintTxFee=this.getDefaultMintTxFee()),this.mintTxFee),this.getCreationTxFee=()=>(void 0===this.creationTxFee&&(this.creationTxFee=this.getDefaultCreationTxFee()),this.creationTxFee),this.setMintTxFee=fee=>{this.mintTxFee=fee},this.setCreationTxFee=fee=>{this.creationTxFee=fee},this.keyChain=()=>this.keychain,this.newKeyChain=()=>{const alias=this.getBlockchainAlias();return this.keychain=alias?new keychain_1.KeyChain(this.core.getHRP(),alias):new keychain_1.KeyChain(this.core.getHRP(),this.blockchainID),this.keychain},this.checkGooseEgg=(utx,outTotal=new bn_js_1.default(0))=>__awaiter(this,void 0,void 0,(function*(){const avaxAssetID=yield this.getAVAXAssetID(),outputTotal=outTotal.gt(new bn_js_1.default(0))?outTotal:utx.getOutputTotal(avaxAssetID),fee=utx.getBurn(avaxAssetID);return!(!fee.lte(constants_2.ONEAVAX.mul(new bn_js_1.default(10)))&&!fee.lte(outputTotal))})),this.getBalance=(address,assetID,includePartial=!1)=>__awaiter(this,void 0,void 0,(function*(){if(void 0===this.parseAddress(address))throw new errors_1.AddressError("Error - AVMAPI.getBalance: Invalid address format");const params={address,assetID,includePartial};return(yield this.callMethod("avm.getBalance",params)).data.result})),this.createAddress=(username,password)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password};return(yield this.callMethod("avm.createAddress",params)).data.result.address})),this.createFixedCapAsset=(username,password,name,symbol,denomination,initialHolders)=>__awaiter(this,void 0,void 0,(function*(){const params={name,symbol,denomination,username,password,initialHolders};return(yield this.callMethod("avm.createFixedCapAsset",params)).data.result.assetID})),this.createVariableCapAsset=(username,password,name,symbol,denomination,minterSets)=>__awaiter(this,void 0,void 0,(function*(){const params={name,symbol,denomination,username,password,minterSets};return(yield this.callMethod("avm.createVariableCapAsset",params)).data.result.assetID})),this.createNFTAsset=(username,password,from,changeAddr,name,symbol,minterSet)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password,name,symbol,minterSet};if(void 0!==(from=this._cleanAddressArray(from,"createNFTAsset"))&&(params.from=from),void 0!==changeAddr){if(void 0===this.parseAddress(changeAddr))throw new errors_1.AddressError("Error - AVMAPI.createNFTAsset: Invalid address format");params.changeAddr=changeAddr}return(yield this.callMethod("avm.createNFTAsset",params)).data.result.assetID})),this.mint=(username,password,amount,assetID,to,minters)=>__awaiter(this,void 0,void 0,(function*(){let asset,amnt;asset="string"!=typeof assetID?bintools.cb58Encode(assetID):assetID,amnt="number"==typeof amount?new bn_js_1.default(amount):amount;const params={username,password,amount:amnt,assetID:asset,to,minters};return(yield this.callMethod("avm.mint",params)).data.result.txID})),this.mintNFT=(username,password,from,changeAddr,payload,assetID,to,encoding="hex")=>__awaiter(this,void 0,void 0,(function*(){let asset;if(void 0===this.parseAddress(to))throw new errors_1.AddressError("Error - AVMAPI.mintNFT: Invalid address format");asset="string"!=typeof assetID?bintools.cb58Encode(assetID):assetID;const params={username,password,assetID:asset,payload,to,encoding};if(void 0!==(from=this._cleanAddressArray(from,"mintNFT"))&&(params.from=from),void 0!==changeAddr){if(void 0===this.parseAddress(changeAddr))throw new errors_1.AddressError("Error - AVMAPI.mintNFT: Invalid address format");params.changeAddr=changeAddr}return(yield this.callMethod("avm.mintNFT",params)).data.result.txID})),this.sendNFT=(username,password,from,changeAddr,assetID,groupID,to)=>__awaiter(this,void 0,void 0,(function*(){let asset;if(void 0===this.parseAddress(to))throw new errors_1.AddressError("Error - AVMAPI.sendNFT: Invalid address format");asset="string"!=typeof assetID?bintools.cb58Encode(assetID):assetID;const params={username,password,assetID:asset,groupID,to};if(void 0!==(from=this._cleanAddressArray(from,"sendNFT"))&&(params.from=from),void 0!==changeAddr){if(void 0===this.parseAddress(changeAddr))throw new errors_1.AddressError("Error - AVMAPI.sendNFT: Invalid address format");params.changeAddr=changeAddr}return(yield this.callMethod("avm.sendNFT",params)).data.result.txID})),this.exportKey=(username,password,address)=>__awaiter(this,void 0,void 0,(function*(){if(void 0===this.parseAddress(address))throw new errors_1.AddressError("Error - AVMAPI.exportKey: Invalid address format");const params={username,password,address};return(yield this.callMethod("avm.exportKey",params)).data.result.privateKey})),this.importKey=(username,password,privateKey)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password,privateKey};return(yield this.callMethod("avm.importKey",params)).data.result.address})),this.export=(username,password,to,amount,assetID)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password,to,amount,assetID};return(yield this.callMethod("avm.export",params)).data.result.txID})),this.import=(username,password,to,sourceChain)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password,to,sourceChain};return(yield this.callMethod("avm.import",params)).data.result.txID})),this.listAddresses=(username,password)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password};return(yield this.callMethod("avm.listAddresses",params)).data.result.addresses})),this.getAllBalances=address=>__awaiter(this,void 0,void 0,(function*(){if(void 0===this.parseAddress(address))throw new errors_1.AddressError("Error - AVMAPI.getAllBalances: Invalid address format");const params={address};return(yield this.callMethod("avm.getAllBalances",params)).data.result.balances})),this.getAssetDescription=assetID=>__awaiter(this,void 0,void 0,(function*(){let asset;asset="string"!=typeof assetID?bintools.cb58Encode(assetID):assetID;const params={assetID:asset},response=yield this.callMethod("avm.getAssetDescription",params);return{name:response.data.result.name,symbol:response.data.result.symbol,assetID:bintools.cb58Decode(response.data.result.assetID),denomination:parseInt(response.data.result.denomination,10)}})),this.getTx=(txID,encoding="hex")=>__awaiter(this,void 0,void 0,(function*(){const params={txID,encoding};return(yield this.callMethod("avm.getTx",params)).data.result.tx})),this.getTxStatus=txID=>__awaiter(this,void 0,void 0,(function*(){const params={txID};return(yield this.callMethod("avm.getTxStatus",params)).data.result.status})),this.getUTXOs=(addresses,sourceChain,limit=0,startIndex,persistOpts,encoding="hex")=>__awaiter(this,void 0,void 0,(function*(){"string"==typeof addresses&&(addresses=[addresses]);const params={addresses,limit,encoding};void 0!==startIndex&&startIndex&&(params.startIndex=startIndex),void 0!==sourceChain&&(params.sourceChain=sourceChain);const response=yield this.callMethod("avm.getUTXOs",params),utxos=new utxos_1.UTXOSet;let data=response.data.result.utxos;if(persistOpts&&"object"==typeof persistOpts){if(this.db.has(persistOpts.getName())){const selfArray=this.db.get(persistOpts.getName());if(Array.isArray(selfArray)){utxos.addArray(data);const utxoSet=new utxos_1.UTXOSet;utxoSet.addArray(selfArray),utxoSet.mergeByRule(utxos,persistOpts.getMergeRule()),data=utxoSet.getAllUTXOStrings()}}this.db.set(persistOpts.getName(),data,persistOpts.getOverwrite())}if(data.length>0&&"0x"===data[0].substring(0,2)){const cb58Strs=[];data.forEach((str=>{cb58Strs.push(bintools.cb58Encode(new buffer_1.Buffer(str.slice(2),"hex")))})),utxos.addArray(cb58Strs,!1)}else utxos.addArray(data,!1);return response.data.result.utxos=utxos,response.data.result})),this.buildBaseTx=(utxoset,amount,assetID,toAddresses,fromAddresses,changeAddresses,memo,asOf=(0,helperfunctions_1.UnixNow)(),locktime=new bn_js_1.default(0),threshold=1)=>__awaiter(this,void 0,void 0,(function*(){const to=this._cleanAddressArray(toAddresses,"buildBaseTx").map((a=>bintools.stringToAddress(a))),from=this._cleanAddressArray(fromAddresses,"buildBaseTx").map((a=>bintools.stringToAddress(a))),change=this._cleanAddressArray(changeAddresses,"buildBaseTx").map((a=>bintools.stringToAddress(a)));"string"==typeof assetID&&(assetID=bintools.cb58Decode(assetID)),memo instanceof payload_1.PayloadBase&&(memo=memo.getPayload());const networkID=this.core.getNetworkID(),blockchainIDBuf=bintools.cb58Decode(this.blockchainID),fee=this.getTxFee(),feeAssetID=yield this.getAVAXAssetID(),builtUnsignedTx=utxoset.buildBaseTx(networkID,blockchainIDBuf,amount,assetID,to,from,change,fee,feeAssetID,memo,asOf,locktime,threshold);if(!(yield this.checkGooseEgg(builtUnsignedTx)))throw new errors_1.GooseEggCheckError("Error - AVMAPI.buildBaseTx:Failed Goose Egg Check");return builtUnsignedTx})),this.buildNFTTransferTx=(utxoset,toAddresses,fromAddresses,changeAddresses,utxoid,memo,asOf=(0,helperfunctions_1.UnixNow)(),locktime=new bn_js_1.default(0),threshold=1)=>__awaiter(this,void 0,void 0,(function*(){const caller="buildNFTTransferTx",to=this._cleanAddressArray(toAddresses,caller).map((a=>bintools.stringToAddress(a))),from=this._cleanAddressArray(fromAddresses,caller).map((a=>bintools.stringToAddress(a))),change=this._cleanAddressArray(changeAddresses,caller).map((a=>bintools.stringToAddress(a)));memo instanceof payload_1.PayloadBase&&(memo=memo.getPayload());const avaxAssetID=yield this.getAVAXAssetID();let utxoidArray=[];"string"==typeof utxoid?utxoidArray=[utxoid]:Array.isArray(utxoid)&&(utxoidArray=utxoid);const builtUnsignedTx=utxoset.buildNFTTransferTx(this.core.getNetworkID(),bintools.cb58Decode(this.blockchainID),to,from,change,utxoidArray,this.getTxFee(),avaxAssetID,memo,asOf,locktime,threshold);if(!(yield this.checkGooseEgg(builtUnsignedTx)))throw new errors_1.GooseEggCheckError("Error - AVMAPI.buildNFTTransferTx:Failed Goose Egg Check");return builtUnsignedTx})),this.buildImportTx=(utxoset,ownerAddresses,sourceChain,toAddresses,fromAddresses,changeAddresses,memo,asOf=(0,helperfunctions_1.UnixNow)(),locktime=new bn_js_1.default(0),threshold=1)=>__awaiter(this,void 0,void 0,(function*(){const caller="buildImportTx",to=this._cleanAddressArray(toAddresses,caller).map((a=>bintools.stringToAddress(a))),from=this._cleanAddressArray(fromAddresses,caller).map((a=>bintools.stringToAddress(a))),change=this._cleanAddressArray(changeAddresses,caller).map((a=>bintools.stringToAddress(a)));let srcChain;if(void 0===sourceChain)throw new errors_1.ChainIdError("Error - AVMAPI.buildImportTx: Source ChainID is undefined.");if("string"==typeof sourceChain)srcChain=sourceChain,sourceChain=bintools.cb58Decode(sourceChain);else if(!(sourceChain instanceof buffer_1.Buffer))throw new errors_1.ChainIdError("Error - AVMAPI.buildImportTx: Invalid destinationChain type: "+typeof sourceChain);const atomicUTXOs=(yield this.getUTXOs(ownerAddresses,srcChain,0,void 0)).utxos,avaxAssetID=yield this.getAVAXAssetID(),atomics=atomicUTXOs.getAllUTXOs();if(0===atomics.length)throw new errors_1.NoAtomicUTXOsError("Error - AVMAPI.buildImportTx: No atomic UTXOs to import from "+srcChain+" using addresses: "+ownerAddresses.join(", "));memo instanceof payload_1.PayloadBase&&(memo=memo.getPayload());const builtUnsignedTx=utxoset.buildImportTx(this.core.getNetworkID(),bintools.cb58Decode(this.blockchainID),to,from,change,atomics,sourceChain,this.getTxFee(),avaxAssetID,memo,asOf,locktime,threshold);if(!(yield this.checkGooseEgg(builtUnsignedTx)))throw new errors_1.GooseEggCheckError("Error - AVMAPI.buildImportTx:Failed Goose Egg Check");return builtUnsignedTx})),this.buildExportTx=(utxoset,amount,destinationChain,toAddresses,fromAddresses,changeAddresses,memo,asOf=(0,helperfunctions_1.UnixNow)(),locktime=new bn_js_1.default(0),threshold=1,assetID)=>__awaiter(this,void 0,void 0,(function*(){const prefixes={};if(toAddresses.map((a=>{prefixes[a.split("-")[0]]=!0})),1!==Object.keys(prefixes).length)throw new errors_1.AddressError("Error - AVMAPI.buildExportTx: To addresses must have the same chainID prefix.");if(void 0===destinationChain)throw new errors_1.ChainIdError("Error - AVMAPI.buildExportTx: Destination ChainID is undefined.");if("string"==typeof destinationChain)destinationChain=bintools.cb58Decode(destinationChain);else if(!(destinationChain instanceof buffer_1.Buffer))throw new errors_1.ChainIdError("Error - AVMAPI.buildExportTx: Invalid destinationChain type: "+typeof destinationChain);if(32!==destinationChain.length)throw new errors_1.ChainIdError("Error - AVMAPI.buildExportTx: Destination ChainID must be 32 bytes in length.");const to=[];toAddresses.map((a=>{to.push(bintools.stringToAddress(a))}));const from=this._cleanAddressArray(fromAddresses,"buildExportTx").map((a=>bintools.stringToAddress(a))),change=this._cleanAddressArray(changeAddresses,"buildExportTx").map((a=>bintools.stringToAddress(a)));memo instanceof payload_1.PayloadBase&&(memo=memo.getPayload());const avaxAssetID=yield this.getAVAXAssetID();void 0===assetID&&(assetID=bintools.cb58Encode(avaxAssetID));const networkID=this.core.getNetworkID(),blockchainID=bintools.cb58Decode(this.blockchainID),assetIDBuf=bintools.cb58Decode(assetID),fee=this.getTxFee(),builtUnsignedTx=utxoset.buildExportTx(networkID,blockchainID,amount,assetIDBuf,to,from,change,destinationChain,fee,avaxAssetID,memo,asOf,locktime,threshold);if(!(yield this.checkGooseEgg(builtUnsignedTx)))throw new errors_1.GooseEggCheckError("Error - AVMAPI.buildExportTx:Failed Goose Egg Check");return builtUnsignedTx})),this.buildCreateAssetTx=(utxoset,fromAddresses,changeAddresses,initialStates,name,symbol,denomination,mintOutputs,memo,asOf=(0,helperfunctions_1.UnixNow)())=>__awaiter(this,void 0,void 0,(function*(){const from=this._cleanAddressArray(fromAddresses,"buildCreateAssetTx").map((a=>bintools.stringToAddress(a))),change=this._cleanAddressArray(changeAddresses,"buildCreateAssetTx").map((a=>bintools.stringToAddress(a)));if(memo instanceof payload_1.PayloadBase&&(memo=memo.getPayload()),symbol.length>constants_1.AVMConstants.SYMBOLMAXLEN)throw new errors_1.SymbolError("Error - AVMAPI.buildCreateAssetTx: Symbols may not exceed length of "+constants_1.AVMConstants.SYMBOLMAXLEN);if(name.length>constants_1.AVMConstants.ASSETNAMELEN)throw new errors_1.NameError("Error - AVMAPI.buildCreateAssetTx: Names may not exceed length of "+constants_1.AVMConstants.ASSETNAMELEN);const networkID=this.core.getNetworkID(),blockchainID=bintools.cb58Decode(this.blockchainID),avaxAssetID=yield this.getAVAXAssetID(),fee=this.getDefaultCreationTxFee(),builtUnsignedTx=utxoset.buildCreateAssetTx(networkID,blockchainID,from,change,initialStates,name,symbol,denomination,mintOutputs,fee,avaxAssetID,memo,asOf);if(!(yield this.checkGooseEgg(builtUnsignedTx,fee)))throw new errors_1.GooseEggCheckError("Error - AVMAPI.buildCreateAssetTx:Failed Goose Egg Check");return builtUnsignedTx})),this.buildSECPMintTx=(utxoset,mintOwner,transferOwner,fromAddresses,changeAddresses,mintUTXOID,memo,asOf=(0,helperfunctions_1.UnixNow)())=>__awaiter(this,void 0,void 0,(function*(){const from=this._cleanAddressArray(fromAddresses,"buildSECPMintTx").map((a=>bintools.stringToAddress(a))),change=this._cleanAddressArray(changeAddresses,"buildSECPMintTx").map((a=>bintools.stringToAddress(a)));memo instanceof payload_1.PayloadBase&&(memo=memo.getPayload());const networkID=this.core.getNetworkID(),blockchainID=bintools.cb58Decode(this.blockchainID),avaxAssetID=yield this.getAVAXAssetID(),fee=this.getMintTxFee(),builtUnsignedTx=utxoset.buildSECPMintTx(networkID,blockchainID,mintOwner,transferOwner,from,change,mintUTXOID,fee,avaxAssetID,memo,asOf);if(!(yield this.checkGooseEgg(builtUnsignedTx)))throw new errors_1.GooseEggCheckError("Error - AVMAPI.buildSECPMintTx:Failed Goose Egg Check");return builtUnsignedTx})),this.buildCreateNFTAssetTx=(utxoset,fromAddresses,changeAddresses,minterSets,name,symbol,memo,asOf=(0,helperfunctions_1.UnixNow)(),locktime=new bn_js_1.default(0))=>__awaiter(this,void 0,void 0,(function*(){const caller="buildCreateNFTAssetTx",from=this._cleanAddressArray(fromAddresses,caller).map((a=>bintools.stringToAddress(a))),change=this._cleanAddressArray(changeAddresses,caller).map((a=>bintools.stringToAddress(a)));if(memo instanceof payload_1.PayloadBase&&(memo=memo.getPayload()),name.length>constants_1.AVMConstants.ASSETNAMELEN)throw new errors_1.NameError("Error - AVMAPI.buildCreateNFTAssetTx: Names may not exceed length of "+constants_1.AVMConstants.ASSETNAMELEN);if(symbol.length>constants_1.AVMConstants.SYMBOLMAXLEN)throw new errors_1.SymbolError("Error - AVMAPI.buildCreateNFTAssetTx: Symbols may not exceed length of "+constants_1.AVMConstants.SYMBOLMAXLEN);const networkID=this.core.getNetworkID(),blockchainID=bintools.cb58Decode(this.blockchainID),creationTxFee=this.getCreationTxFee(),avaxAssetID=yield this.getAVAXAssetID(),builtUnsignedTx=utxoset.buildCreateNFTAssetTx(networkID,blockchainID,from,change,minterSets,name,symbol,creationTxFee,avaxAssetID,memo,asOf,locktime);if(!(yield this.checkGooseEgg(builtUnsignedTx,creationTxFee)))throw new errors_1.GooseEggCheckError("Error - AVMAPI.buildCreateNFTAssetTx:Failed Goose Egg Check");return builtUnsignedTx})),this.buildCreateNFTMintTx=(utxoset,owners,fromAddresses,changeAddresses,utxoid,groupID=0,payload,memo,asOf=(0,helperfunctions_1.UnixNow)())=>__awaiter(this,void 0,void 0,(function*(){const caller="buildCreateNFTMintTx",from=this._cleanAddressArray(fromAddresses,caller).map((a=>bintools.stringToAddress(a))),change=this._cleanAddressArray(changeAddresses,caller).map((a=>bintools.stringToAddress(a)));memo instanceof payload_1.PayloadBase&&(memo=memo.getPayload()),payload instanceof payload_1.PayloadBase&&(payload=payload.getPayload()),"string"==typeof utxoid&&(utxoid=[utxoid]);const avaxAssetID=yield this.getAVAXAssetID();owners instanceof output_1.OutputOwners&&(owners=[owners]);const networkID=this.core.getNetworkID(),blockchainID=bintools.cb58Decode(this.blockchainID),txFee=this.getTxFee(),builtUnsignedTx=utxoset.buildCreateNFTMintTx(networkID,blockchainID,owners,from,change,utxoid,groupID,payload,txFee,avaxAssetID,memo,asOf);if(!(yield this.checkGooseEgg(builtUnsignedTx)))throw new errors_1.GooseEggCheckError("Error - AVMAPI.buildCreateNFTMintTx:Failed Goose Egg Check");return builtUnsignedTx})),this.signTx=utx=>utx.sign(this.keychain),this.issueTx=tx=>__awaiter(this,void 0,void 0,(function*(){let Transaction="";if("string"==typeof tx)Transaction=tx;else if(tx instanceof buffer_1.Buffer){const txobj=new tx_1.Tx;txobj.fromBuffer(tx),Transaction=txobj.toStringHex()}else{if(!(tx instanceof tx_1.Tx))throw new errors_1.TransactionError("Error - AVMAPI.issueTx: provided tx is not expected type of string, Buffer, or Tx");Transaction=tx.toStringHex()}const params={tx:Transaction.toString(),encoding:"hex"};return(yield this.callMethod("avm.issueTx",params)).data.result.txID})),this.getAddressTxs=(address,cursor,pageSize,assetID)=>__awaiter(this,void 0,void 0,(function*(){let asset,pageSizeNum;asset="string"!=typeof assetID?bintools.cb58Encode(assetID):assetID,pageSizeNum="number"!=typeof pageSize?0:pageSize;const params={address,cursor,pageSize:pageSizeNum,assetID:asset};return(yield this.callMethod("avm.getAddressTxs",params)).data.result})),this.send=(username,password,assetID,amount,to,from,changeAddr,memo)=>__awaiter(this,void 0,void 0,(function*(){let asset,amnt;if(void 0===this.parseAddress(to))throw new errors_1.AddressError("Error - AVMAPI.send: Invalid address format");asset="string"!=typeof assetID?bintools.cb58Encode(assetID):assetID,amnt="number"==typeof amount?new bn_js_1.default(amount):amount;const params={username,password,assetID:asset,amount:amnt.toString(10),to};if(void 0!==(from=this._cleanAddressArray(from,"send"))&&(params.from=from),void 0!==changeAddr){if(void 0===this.parseAddress(changeAddr))throw new errors_1.AddressError("Error - AVMAPI.send: Invalid address format");params.changeAddr=changeAddr}void 0!==memo&&(params.memo="string"!=typeof memo?bintools.cb58Encode(memo):memo);return(yield this.callMethod("avm.send",params)).data.result})),this.sendMultiple=(username,password,sendOutputs,from,changeAddr,memo)=>__awaiter(this,void 0,void 0,(function*(){let asset,amnt;const sOutputs=[];sendOutputs.forEach((output=>{if(void 0===this.parseAddress(output.to))throw new errors_1.AddressError("Error - AVMAPI.sendMultiple: Invalid address format");asset="string"!=typeof output.assetID?bintools.cb58Encode(output.assetID):output.assetID,amnt="number"==typeof output.amount?new bn_js_1.default(output.amount):output.amount,sOutputs.push({to:output.to,assetID:asset,amount:amnt.toString(10)})}));const params={username,password,outputs:sOutputs};if(void 0!==(from=this._cleanAddressArray(from,"send"))&&(params.from=from),void 0!==changeAddr){if(void 0===this.parseAddress(changeAddr))throw new errors_1.AddressError("Error - AVMAPI.send: Invalid address format");params.changeAddr=changeAddr}void 0!==memo&&(params.memo="string"!=typeof memo?bintools.cb58Encode(memo):memo);return(yield this.callMethod("avm.sendMultiple",params)).data.result})),this.buildGenesis=genesisData=>__awaiter(this,void 0,void 0,(function*(){const params={genesisData};return(yield this.callMethod("avm.buildGenesis",params)).data.result.bytes})),this.blockchainID=blockchainID;const netID=core.getNetworkID();if(netID in constants_2.Defaults.network&&blockchainID in constants_2.Defaults.network[`${netID}`]){const alias=constants_2.Defaults.network[`${netID}`][`${blockchainID}`].alias;this.keychain=new keychain_1.KeyChain(this.core.getHRP(),alias)}else this.keychain=new keychain_1.KeyChain(this.core.getHRP(),blockchainID)}_cleanAddressArray(addresses,caller){const addrs=[],chainID=this.getBlockchainAlias()?this.getBlockchainAlias():this.getBlockchainID();if(addresses&&addresses.length>0)for(let i=0;i{let newOut=new outputs_1.TransferableOutput;return newOut.deserialize(o,encoding),newOut})),this.ins=fields.ins.map((i=>{let newIn=new inputs_1.TransferableInput;return newIn.deserialize(i,encoding),newIn})),this.numouts=serialization.decoder(this.outs.length.toString(),"display","decimalString","Buffer",4),this.numins=serialization.decoder(this.ins.length.toString(),"display","decimalString","Buffer",4)}getOuts(){return this.outs}getIns(){return this.ins}getTotalOuts(){return this.getOuts()}setCodecID(codecID){if(0!==codecID&&1!==codecID)throw new errors_1.CodecIdError("Error - BaseTx.setCodecID: invalid codecID. Valid codecIDs are 0 and 1.");this._codecID=codecID,this._typeID=0===this._codecID?constants_1.AVMConstants.BASETX:constants_1.AVMConstants.BASETX_CODECONE}getTxType(){return this._typeID}fromBuffer(bytes,offset=0){this.networkID=bintools.copyFrom(bytes,offset,offset+4),offset+=4,this.blockchainID=bintools.copyFrom(bytes,offset,offset+32),offset+=32,this.numouts=bintools.copyFrom(bytes,offset,offset+4),offset+=4;const outcount=this.numouts.readUInt32BE(0);this.outs=[];for(let i=0;i{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AVMConstants=void 0;class AVMConstants{}exports.AVMConstants=AVMConstants,AVMConstants.LATESTCODEC=0,AVMConstants.SECPFXID=0,AVMConstants.NFTFXID=1,AVMConstants.SECPMINTOUTPUTID=6,AVMConstants.SECPMINTOUTPUTID_CODECONE=65537,AVMConstants.SECPXFEROUTPUTID=7,AVMConstants.SECPXFEROUTPUTID_CODECONE=65538,AVMConstants.NFTXFEROUTPUTID=11,AVMConstants.NFTXFEROUTPUTID_CODECONE=131073,AVMConstants.NFTMINTOUTPUTID=10,AVMConstants.NFTMINTOUTPUTID_CODECONE=131072,AVMConstants.SECPINPUTID=5,AVMConstants.SECPINPUTID_CODECONE=65536,AVMConstants.SECPMINTOPID=8,AVMConstants.SECPMINTOPID_CODECONE=65539,AVMConstants.NFTMINTOPID=12,AVMConstants.NFTMINTOPID_CODECONE=131074,AVMConstants.NFTXFEROPID=13,AVMConstants.NFTXFEROPID_CODECONE=131075,AVMConstants.VERTEX=0,AVMConstants.VERTEX_CODECONE=0,AVMConstants.BASETX=0,AVMConstants.BASETX_CODECONE=0,AVMConstants.CREATEASSETTX=1,AVMConstants.CREATEASSETTX_CODECONE=1,AVMConstants.OPERATIONTX=2,AVMConstants.OPERATIONTX_CODECONE=2,AVMConstants.IMPORTTX=3,AVMConstants.IMPORTTX_CODECONE=3,AVMConstants.EXPORTTX=4,AVMConstants.EXPORTTX_CODECONE=4,AVMConstants.SECPCREDENTIAL=9,AVMConstants.SECPCREDENTIAL_CODECONE=65540,AVMConstants.NFTCREDENTIAL=14,AVMConstants.NFTCREDENTIAL_CODECONE=131076,AVMConstants.ASSETIDLEN=32,AVMConstants.BLOCKCHAINIDLEN=32,AVMConstants.SYMBOLMAXLEN=4,AVMConstants.ASSETNAMELEN=128,AVMConstants.ADDRESSLENGTH=20},1926:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.CreateAssetTx=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),constants_1=__webpack_require__(6667),initialstates_1=__webpack_require__(2951),basetx_1=__webpack_require__(5662),constants_2=__webpack_require__(8779),serialization_1=__webpack_require__(555),errors_1=__webpack_require__(611),bintools=bintools_1.default.getInstance(),serialization=serialization_1.Serialization.getInstance(),utf8="utf8";class CreateAssetTx extends basetx_1.BaseTx{constructor(networkID=constants_2.DefaultNetworkID,blockchainID=buffer_1.Buffer.alloc(32,16),outs,ins,memo,name,symbol,denomination,initialState){super(networkID,blockchainID,outs,ins,memo),this._typeName="CreateAssetTx",this._codecID=constants_1.AVMConstants.LATESTCODEC,this._typeID=0===this._codecID?constants_1.AVMConstants.CREATEASSETTX:constants_1.AVMConstants.CREATEASSETTX_CODECONE,this.name="",this.symbol="",this.denomination=buffer_1.Buffer.alloc(1),this.initialState=new initialstates_1.InitialStates,"string"==typeof name&&"string"==typeof symbol&&"number"==typeof denomination&&denomination>=0&&denomination<=32&&void 0!==initialState&&(this.initialState=initialState,this.name=name,this.symbol=symbol,this.denomination.writeUInt8(denomination,0))}serialize(encoding="hex"){const fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{name:serialization.encoder(this.name,encoding,utf8,utf8),symbol:serialization.encoder(this.symbol,encoding,utf8,utf8),denomination:serialization.encoder(this.denomination,encoding,"Buffer","decimalString",1),initialState:this.initialState.serialize(encoding)})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.name=serialization.decoder(fields.name,encoding,utf8,utf8),this.symbol=serialization.decoder(fields.symbol,encoding,utf8,utf8),this.denomination=serialization.decoder(fields.denomination,encoding,"decimalString","Buffer",1),this.initialState=new initialstates_1.InitialStates,this.initialState.deserialize(fields.initialState,encoding)}setCodecID(codecID){if(0!==codecID&&1!==codecID)throw new errors_1.CodecIdError("Error - CreateAssetTx.setCodecID: invalid codecID. Valid codecIDs are 0 and 1.");this._codecID=codecID,this._typeID=0===this._codecID?constants_1.AVMConstants.CREATEASSETTX:constants_1.AVMConstants.CREATEASSETTX_CODECONE}getTxType(){return this._typeID}getInitialStates(){return this.initialState}getName(){return this.name}getSymbol(){return this.symbol}getDenomination(){return this.denomination.readUInt8(0)}getDenominationBuffer(){return this.denomination}fromBuffer(bytes,offset=0){offset=super.fromBuffer(bytes,offset);const namesize=bintools.copyFrom(bytes,offset,offset+2).readUInt16BE(0);offset+=2,this.name=bintools.copyFrom(bytes,offset,offset+namesize).toString("utf8"),offset+=namesize;const symsize=bintools.copyFrom(bytes,offset,offset+2).readUInt16BE(0);offset+=2,this.symbol=bintools.copyFrom(bytes,offset,offset+symsize).toString("utf8"),offset+=symsize,this.denomination=bintools.copyFrom(bytes,offset,offset+1),offset+=1;const inits=new initialstates_1.InitialStates;return offset=inits.fromBuffer(bytes,offset),this.initialState=inits,offset}toBuffer(){const superbuff=super.toBuffer(),initstatebuff=this.initialState.toBuffer(),namebuff=buffer_1.Buffer.alloc(this.name.length);namebuff.write(this.name,0,this.name.length,utf8);const namesize=buffer_1.Buffer.alloc(2);namesize.writeUInt16BE(this.name.length,0);const symbuff=buffer_1.Buffer.alloc(this.symbol.length);symbuff.write(this.symbol,0,this.symbol.length,utf8);const symsize=buffer_1.Buffer.alloc(2);symsize.writeUInt16BE(this.symbol.length,0);const bsize=superbuff.length+namesize.length+namebuff.length+symsize.length+symbuff.length+this.denomination.length+initstatebuff.length,barr=[superbuff,namesize,namebuff,symsize,symbuff,this.denomination,initstatebuff];return buffer_1.Buffer.concat(barr,bsize)}clone(){let newbase=new CreateAssetTx;return newbase.fromBuffer(this.toBuffer()),newbase}create(...args){return new CreateAssetTx(...args)}}exports.CreateAssetTx=CreateAssetTx},2819:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.NFTCredential=exports.SECPCredential=exports.SelectCredentialClass=void 0;const constants_1=__webpack_require__(6667),credentials_1=__webpack_require__(5375),errors_1=__webpack_require__(611);exports.SelectCredentialClass=(credid,...args)=>{if(credid===constants_1.AVMConstants.SECPCREDENTIAL||credid===constants_1.AVMConstants.SECPCREDENTIAL_CODECONE)return new SECPCredential(...args);if(credid===constants_1.AVMConstants.NFTCREDENTIAL||credid===constants_1.AVMConstants.NFTCREDENTIAL_CODECONE)return new NFTCredential(...args);throw new errors_1.CredIdError("Error - SelectCredentialClass: unknown credid")};class SECPCredential extends credentials_1.Credential{constructor(){super(...arguments),this._typeName="SECPCredential",this._codecID=constants_1.AVMConstants.LATESTCODEC,this._typeID=0===this._codecID?constants_1.AVMConstants.SECPCREDENTIAL:constants_1.AVMConstants.SECPCREDENTIAL_CODECONE}setCodecID(codecID){if(0!==codecID&&1!==codecID)throw new errors_1.CodecIdError("Error - SECPCredential.setCodecID: invalid codecID. Valid codecIDs are 0 and 1.");this._codecID=codecID,this._typeID=0===this._codecID?constants_1.AVMConstants.SECPCREDENTIAL:constants_1.AVMConstants.SECPCREDENTIAL_CODECONE}getCredentialID(){return this._typeID}clone(){let newbase=new SECPCredential;return newbase.fromBuffer(this.toBuffer()),newbase}create(...args){return new SECPCredential(...args)}select(id,...args){return(0,exports.SelectCredentialClass)(id,...args)}}exports.SECPCredential=SECPCredential;class NFTCredential extends credentials_1.Credential{constructor(){super(...arguments),this._typeName="NFTCredential",this._codecID=constants_1.AVMConstants.LATESTCODEC,this._typeID=0===this._codecID?constants_1.AVMConstants.NFTCREDENTIAL:constants_1.AVMConstants.NFTCREDENTIAL_CODECONE}setCodecID(codecID){if(0!==codecID&&1!==codecID)throw new errors_1.CodecIdError("Error - NFTCredential.setCodecID: invalid codecID. Valid codecIDs are 0 and 1.");this._codecID=codecID,this._typeID=0===this._codecID?constants_1.AVMConstants.NFTCREDENTIAL:constants_1.AVMConstants.NFTCREDENTIAL_CODECONE}getCredentialID(){return this._typeID}clone(){let newbase=new NFTCredential;return newbase.fromBuffer(this.toBuffer()),newbase}create(...args){return new NFTCredential(...args)}select(id,...args){return(0,exports.SelectCredentialClass)(id,...args)}}exports.NFTCredential=NFTCredential},1239:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.ExportTx=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),constants_1=__webpack_require__(6667),outputs_1=__webpack_require__(6578),basetx_1=__webpack_require__(5662),constants_2=__webpack_require__(8779),bn_js_1=__importDefault(__webpack_require__(3550)),serialization_1=__webpack_require__(555),errors_1=__webpack_require__(611),bintools=bintools_1.default.getInstance(),serialization=serialization_1.Serialization.getInstance();class ExportTx extends basetx_1.BaseTx{constructor(networkID=constants_2.DefaultNetworkID,blockchainID=buffer_1.Buffer.alloc(32,16),outs,ins,memo,destinationChain,exportOuts){if(super(networkID,blockchainID,outs,ins,memo),this._typeName="ExportTx",this._codecID=constants_1.AVMConstants.LATESTCODEC,this._typeID=0===this._codecID?constants_1.AVMConstants.EXPORTTX:constants_1.AVMConstants.EXPORTTX_CODECONE,this.destinationChain=void 0,this.numOuts=buffer_1.Buffer.alloc(4),this.exportOuts=[],this.destinationChain=destinationChain,void 0!==exportOuts&&Array.isArray(exportOuts)){for(let i=0;ie.serialize(encoding)))})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.destinationChain=serialization.decoder(fields.destinationChain,encoding,"cb58","Buffer",32),this.exportOuts=fields.exportOuts.map((e=>{let eo=new outputs_1.TransferableOutput;return eo.deserialize(e,encoding),eo})),this.numOuts=buffer_1.Buffer.alloc(4),this.numOuts.writeUInt32BE(this.exportOuts.length,0)}setCodecID(codecID){if(0!==codecID&&1!==codecID)throw new errors_1.CodecIdError("Error - ExportTx.setCodecID: invalid codecID. Valid codecIDs are 0 and 1.");this._codecID=codecID,this._typeID=0===this._codecID?constants_1.AVMConstants.EXPORTTX:constants_1.AVMConstants.EXPORTTX_CODECONE}getTxType(){return this._typeID}getExportOutputs(){return this.exportOuts}getExportTotal(){let val=new bn_js_1.default(0);for(let i=0;ithis.assetAlias,"string"==typeof assetAlias&&"string"==typeof name&&"string"==typeof symbol&&"number"==typeof denomination&&denomination>=0&&denomination<=32&&void 0!==initialState&&(this.assetAlias=assetAlias,this.name=name,this.symbol=symbol,this.denomination.writeUInt8(denomination,0),this.initialState=initialState)}serialize(encoding="hex"){const fields=super.serialize(encoding);return delete fields.blockchainID,delete fields.outs,delete fields.ins,Object.assign(Object.assign({},fields),{assetAlias:serialization.encoder(this.assetAlias,encoding,utf8,utf8),name:serialization.encoder(this.name,encoding,utf8,utf8),symbol:serialization.encoder(this.symbol,encoding,utf8,utf8),denomination:serialization.encoder(this.denomination,encoding,"Buffer","decimalString",1),initialState:this.initialState.serialize(encoding)})}deserialize(fields,encoding="hex"){fields.blockchainID=buffer_1.Buffer.alloc(32,16).toString("hex"),fields.outs=[],fields.ins=[],super.deserialize(fields,encoding),this.assetAlias=serialization.decoder(fields.assetAlias,encoding,utf8,utf8),this.name=serialization.decoder(fields.name,encoding,utf8,utf8),this.symbol=serialization.decoder(fields.symbol,encoding,utf8,utf8),this.denomination=serialization.decoder(fields.denomination,encoding,"decimalString","Buffer",1),this.initialState=new initialstates_1.InitialStates,this.initialState.deserialize(fields.initialState,encoding)}fromBuffer(bytes,offset=0){const assetAliasSize=bintools.copyFrom(bytes,offset,offset+2).readUInt16BE(0);return offset+=2,this.assetAlias=bintools.copyFrom(bytes,offset,offset+assetAliasSize).toString("utf8"),offset+=assetAliasSize,offset+=super.fromBuffer(bytes,offset)}toBuffer(networkID=constants_1.DefaultNetworkID){const assetAlias=this.getAssetAlias(),assetAliasbuffSize=buffer_1.Buffer.alloc(2);assetAliasbuffSize.writeUInt16BE(assetAlias.length,0);let bsize=assetAliasbuffSize.length,barr=[assetAliasbuffSize];const assetAliasbuff=buffer_1.Buffer.alloc(assetAlias.length);assetAliasbuff.write(assetAlias,0,assetAlias.length,utf8),bsize+=assetAliasbuff.length,barr.push(assetAliasbuff);const networkIDBuff=buffer_1.Buffer.alloc(4);networkIDBuff.writeUInt32BE(new bn_js_1.default(networkID).toNumber(),0),bsize+=networkIDBuff.length,barr.push(networkIDBuff),bsize+=32,barr.push(buffer_1.Buffer.alloc(32)),bsize+=4,barr.push(buffer_1.Buffer.alloc(4)),bsize+=4,barr.push(buffer_1.Buffer.alloc(4));const memo=this.getMemo(),memobuffSize=buffer_1.Buffer.alloc(4);memobuffSize.writeUInt32BE(memo.length,0),bsize+=memobuffSize.length,barr.push(memobuffSize),bsize+=memo.length,barr.push(memo);const name=this.getName(),namebuffSize=buffer_1.Buffer.alloc(2);namebuffSize.writeUInt16BE(name.length,0),bsize+=namebuffSize.length,barr.push(namebuffSize);const namebuff=buffer_1.Buffer.alloc(name.length);namebuff.write(name,0,name.length,utf8),bsize+=namebuff.length,barr.push(namebuff);const symbol=this.getSymbol(),symbolbuffSize=buffer_1.Buffer.alloc(2);symbolbuffSize.writeUInt16BE(symbol.length,0),bsize+=symbolbuffSize.length,barr.push(symbolbuffSize);const symbolbuff=buffer_1.Buffer.alloc(symbol.length);symbolbuff.write(symbol,0,symbol.length,utf8),bsize+=symbolbuff.length,barr.push(symbolbuff);const denomination=this.getDenomination(),denominationbuffSize=buffer_1.Buffer.alloc(1);return denominationbuffSize.writeUInt8(denomination,0),bsize+=denominationbuffSize.length,barr.push(denominationbuffSize),bsize+=this.initialState.toBuffer().length,barr.push(this.initialState.toBuffer()),buffer_1.Buffer.concat(barr,bsize)}}exports.GenesisAsset=GenesisAsset},6418:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.GenesisData=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),serialization_1=__webpack_require__(555),constants_1=__webpack_require__(6667),_1=__webpack_require__(7996),utils_1=__webpack_require__(338),serialization=serialization_1.Serialization.getInstance(),bintools=bintools_1.default.getInstance();class GenesisData extends serialization_1.Serializable{constructor(genesisAssets=[],networkID=utils_1.DefaultNetworkID){super(),this._typeName="GenesisData",this._codecID=constants_1.AVMConstants.LATESTCODEC,this.networkID=buffer_1.Buffer.alloc(4),this.getGenesisAssets=()=>this.genesisAssets,this.getNetworkID=()=>this.networkID.readUInt32BE(0),this.genesisAssets=genesisAssets,this.networkID.writeUInt32BE(networkID,0)}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{genesisAssets:this.genesisAssets.map((genesisAsset=>genesisAsset.serialize(encoding))),networkID:serialization.encoder(this.networkID,encoding,"Buffer","decimalString")})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.genesisAssets=fields.genesisAssets.map((genesisAsset=>{let g=new _1.GenesisAsset;return g.deserialize(genesisAsset,encoding),g})),this.networkID=serialization.decoder(fields.networkID,encoding,"decimalString","Buffer",4)}fromBuffer(bytes,offset=0){this._codecID=bintools.copyFrom(bytes,offset,offset+2).readUInt16BE(0),offset+=2;const numGenesisAssets=bintools.copyFrom(bytes,offset,offset+4);offset+=4;const assetCount=numGenesisAssets.readUInt32BE(0);this.genesisAssets=[];for(let i=0;i{const b=genesisAsset.toBuffer(this.getNetworkID());bsize+=b.length,barr.push(b)})),buffer_1.Buffer.concat(barr,bsize)}}exports.GenesisData=GenesisData},1952:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.ImportTx=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),constants_1=__webpack_require__(6667),inputs_1=__webpack_require__(4935),basetx_1=__webpack_require__(5662),credentials_1=__webpack_require__(2819),credentials_2=__webpack_require__(5375),constants_2=__webpack_require__(8779),serialization_1=__webpack_require__(555),errors_1=__webpack_require__(611),bintools=bintools_1.default.getInstance(),serialization=serialization_1.Serialization.getInstance();class ImportTx extends basetx_1.BaseTx{constructor(networkID=constants_2.DefaultNetworkID,blockchainID=buffer_1.Buffer.alloc(32,16),outs,ins,memo,sourceChain,importIns){if(super(networkID,blockchainID,outs,ins,memo),this._typeName="ImportTx",this._codecID=constants_1.AVMConstants.LATESTCODEC,this._typeID=0===this._codecID?constants_1.AVMConstants.IMPORTTX:constants_1.AVMConstants.IMPORTTX_CODECONE,this.sourceChain=buffer_1.Buffer.alloc(32),this.numIns=buffer_1.Buffer.alloc(4),this.importIns=[],this.sourceChain=sourceChain,void 0!==importIns&&Array.isArray(importIns)){for(let i=0;ii.serialize(encoding)))})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.sourceChain=serialization.decoder(fields.sourceChain,encoding,"cb58","Buffer",32),this.importIns=fields.importIns.map((i=>{let ii=new inputs_1.TransferableInput;return ii.deserialize(i,encoding),ii})),this.numIns=buffer_1.Buffer.alloc(4),this.numIns.writeUInt32BE(this.importIns.length,0)}setCodecID(codecID){if(0!==codecID&&1!==codecID)throw new errors_1.CodecIdError("Error - ImportTx.setCodecID: invalid codecID. Valid codecIDs are 0 and 1.");this._codecID=codecID,this._typeID=0===this._codecID?constants_1.AVMConstants.IMPORTTX:constants_1.AVMConstants.IMPORTTX_CODECONE}getTxType(){return this._typeID}getSourceChain(){return this.sourceChain}fromBuffer(bytes,offset=0){offset=super.fromBuffer(bytes,offset),this.sourceChain=bintools.copyFrom(bytes,offset,offset+32),offset+=32,this.numIns=bintools.copyFrom(bytes,offset,offset+4),offset+=4;const numIns=this.numIns.readUInt32BE(0);for(let i=0;io.serialize(encoding)));return Object.assign(Object.assign({},fields),{fxs:flatfxs})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding);const unflat={};for(let fxid in fields.fxs)unflat[`${fxid}`]=fields.fxs[`${fxid}`].map((o=>{const out=(0,outputs_1.SelectOutputClass)(o._typeID);return out.deserialize(o,encoding),out}));this.fxs=unflat}addOutput(out,fxid=constants_1.AVMConstants.SECPFXID){fxid in this.fxs||(this.fxs[`${fxid}`]=[]),this.fxs[`${fxid}`].push(out)}fromBuffer(bytes,offset=0){const result=[],klen=bintools.copyFrom(bytes,offset,offset+4);offset+=4;const klennum=klen.readUInt32BE(0);for(let i=0;iparseInt(k,10))).sort(),klen=buffer_1.Buffer.alloc(4);klen.writeUInt32BE(keys.length,0),buff.push(klen);for(let i=0;i{if(inputid===constants_1.AVMConstants.SECPINPUTID||inputid===constants_1.AVMConstants.SECPINPUTID_CODECONE)return new SECPTransferInput(...args);throw new errors_1.InputIdError("Error - SelectInputClass: unknown inputid")};class TransferableInput extends input_1.StandardTransferableInput{constructor(){super(...arguments),this._typeName="TransferableInput",this._typeID=void 0}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.input=(0,exports.SelectInputClass)(fields.input._typeID),this.input.deserialize(fields.input,encoding)}fromBuffer(bytes,offset=0){this.txid=bintools.copyFrom(bytes,offset,offset+32),offset+=32,this.outputidx=bintools.copyFrom(bytes,offset,offset+4),offset+=4,this.assetID=bintools.copyFrom(bytes,offset,offset+constants_1.AVMConstants.ASSETIDLEN),offset+=32;const inputid=bintools.copyFrom(bytes,offset,offset+4).readUInt32BE(0);return offset+=4,this.input=(0,exports.SelectInputClass)(inputid),this.input.fromBuffer(bytes,offset)}}exports.TransferableInput=TransferableInput;class AmountInput extends input_1.StandardAmountInput{constructor(){super(...arguments),this._typeName="AmountInput",this._typeID=void 0}select(id,...args){return(0,exports.SelectInputClass)(id,...args)}}exports.AmountInput=AmountInput;class SECPTransferInput extends AmountInput{constructor(){super(...arguments),this._typeName="SECPTransferInput",this._codecID=constants_1.AVMConstants.LATESTCODEC,this._typeID=0===this._codecID?constants_1.AVMConstants.SECPINPUTID:constants_1.AVMConstants.SECPINPUTID_CODECONE}setCodecID(codecID){if(0!==codecID&&1!==codecID)throw new errors_1.CodecIdError("Error - SECPTransferInput.setCodecID: invalid codecID. Valid codecIDs are 0 and 1.");this._codecID=codecID,this._typeID=0===this._codecID?constants_1.AVMConstants.SECPINPUTID:constants_1.AVMConstants.SECPINPUTID_CODECONE}getInputID(){return this._typeID}getCredentialID(){return 0===this._codecID?constants_1.AVMConstants.SECPCREDENTIAL:1===this._codecID?constants_1.AVMConstants.SECPCREDENTIAL_CODECONE:void 0}create(...args){return new SECPTransferInput(...args)}clone(){const newout=this.create();return newout.fromBuffer(this.toBuffer()),newout}}exports.SECPTransferInput=SECPTransferInput},3101:(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0})},2209:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.KeyChain=exports.KeyPair=void 0;const bintools_1=__importDefault(__webpack_require__(903)),secp256k1_1=__webpack_require__(181),utils_1=__webpack_require__(338),bintools=bintools_1.default.getInstance();utils_1.Serialization.getInstance();class KeyPair extends secp256k1_1.SECP256k1KeyPair{clone(){const newkp=new KeyPair(this.hrp,this.chainID);return newkp.importKey(bintools.copyFrom(this.getPrivateKey())),newkp}create(...args){return 2==args.length?new KeyPair(args[0],args[1]):new KeyPair(this.hrp,this.chainID)}}exports.KeyPair=KeyPair;class KeyChain extends secp256k1_1.SECP256k1KeyChain{constructor(hrp,chainid){super(),this.hrp="",this.chainid="",this.makeKey=()=>{let keypair=new KeyPair(this.hrp,this.chainid);return this.addKey(keypair),keypair},this.addKey=newKey=>{newKey.setChainID(this.chainid),super.addKey(newKey)},this.importKey=privk=>{let pk,keypair=new KeyPair(this.hrp,this.chainid);return pk="string"==typeof privk?bintools.cb58Decode(privk.split("-")[1]):bintools.copyFrom(privk),keypair.importKey(pk),keypair.getAddress().toString("hex")in this.keys||this.addKey(keypair),keypair},this.hrp=hrp,this.chainid=chainid}create(...args){return 2==args.length?new KeyChain(args[0],args[1]):new KeyChain(this.hrp,this.chainid)}clone(){const newkc=new KeyChain(this.hrp,this.chainid);for(let k in this.keys)newkc.addKey(this.keys[`${k}`].clone());return newkc}union(kc){let newkc=kc.clone();for(let k in this.keys)newkc.addKey(this.keys[`${k}`].clone());return newkc}}exports.KeyChain=KeyChain},9609:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.MinterSet=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),serialization_1=__webpack_require__(555),bintools=bintools_1.default.getInstance(),serialization=serialization_1.Serialization.getInstance();class MinterSet extends serialization_1.Serializable{constructor(threshold=1,minters=[]){super(),this._typeName="MinterSet",this._typeID=void 0,this.minters=[],this.getThreshold=()=>this.threshold,this.getMinters=()=>this.minters,this._cleanAddresses=addresses=>{let addrs=[];for(let i=0;iserialization.encoder(m,encoding,"Buffer","cb58",20)))})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.threshold=serialization.decoder(fields.threshold,encoding,"decimalString","number",4),this.minters=fields.minters.map((m=>serialization.decoder(m,encoding,"cb58","Buffer",20)))}}exports.MinterSet=MinterSet},2710:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.OperationTx=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),constants_1=__webpack_require__(6667),ops_1=__webpack_require__(4726),credentials_1=__webpack_require__(2819),credentials_2=__webpack_require__(5375),basetx_1=__webpack_require__(5662),constants_2=__webpack_require__(8779),errors_1=__webpack_require__(611),bintools=bintools_1.default.getInstance();class OperationTx extends basetx_1.BaseTx{constructor(networkID=constants_2.DefaultNetworkID,blockchainID=buffer_1.Buffer.alloc(32,16),outs,ins,memo,ops){if(super(networkID,blockchainID,outs,ins,memo),this._typeName="OperationTx",this._codecID=constants_1.AVMConstants.LATESTCODEC,this._typeID=0===this._codecID?constants_1.AVMConstants.OPERATIONTX:constants_1.AVMConstants.OPERATIONTX_CODECONE,this.numOps=buffer_1.Buffer.alloc(4),this.ops=[],void 0!==ops&&Array.isArray(ops)){for(let i=0;io.serialize(encoding)))})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.ops=fields.ops.map((o=>{let op=new ops_1.TransferableOperation;return op.deserialize(o,encoding),op})),this.numOps=buffer_1.Buffer.alloc(4),this.numOps.writeUInt32BE(this.ops.length,0)}setCodecID(codecID){if(0!==codecID&&1!==codecID)throw new errors_1.CodecIdError("Error - OperationTx.setCodecID: invalid codecID. Valid codecIDs are 0 and 1.");this._codecID=codecID,this._typeID=0===this._codecID?constants_1.AVMConstants.OPERATIONTX:constants_1.AVMConstants.OPERATIONTX_CODECONE}getTxType(){return this._typeID}fromBuffer(bytes,offset=0){offset=super.fromBuffer(bytes,offset),this.numOps=bintools.copyFrom(bytes,offset,offset+4),offset+=4;const numOps=this.numOps.readUInt32BE(0);for(let i=0;i{if(opid===constants_1.AVMConstants.SECPMINTOPID||opid===constants_1.AVMConstants.SECPMINTOPID_CODECONE)return new SECPMintOperation(...args);if(opid===constants_1.AVMConstants.NFTMINTOPID||opid===constants_1.AVMConstants.NFTMINTOPID_CODECONE)return new NFTMintOperation(...args);if(opid===constants_1.AVMConstants.NFTXFEROPID||opid===constants_1.AVMConstants.NFTXFEROPID_CODECONE)return new NFTTransferOperation(...args);throw new errors_1.InvalidOperationIdError(`Error - SelectOperationClass: unknown opid ${opid}`)};class Operation extends serialization_1.Serializable{constructor(){super(...arguments),this._typeName="Operation",this._typeID=void 0,this.sigCount=buffer_1.Buffer.alloc(4),this.sigIdxs=[],this.getSigIdxs=()=>this.sigIdxs,this.addSignatureIdx=(addressIdx,address)=>{const sigidx=new credentials_1.SigIdx,b=buffer_1.Buffer.alloc(4);b.writeUInt32BE(addressIdx,0),sigidx.fromBuffer(b),sigidx.setSource(address),this.sigIdxs.push(sigidx),this.sigCount.writeUInt32BE(this.sigIdxs.length,0)}}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{sigIdxs:this.sigIdxs.map((s=>s.serialize(encoding)))})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.sigIdxs=fields.sigIdxs.map((s=>{let sidx=new credentials_1.SigIdx;return sidx.deserialize(s,encoding),sidx})),this.sigCount.writeUInt32BE(this.sigIdxs.length,0)}fromBuffer(bytes,offset=0){this.sigCount=bintools.copyFrom(bytes,offset,offset+4),offset+=4;const sigCount=this.sigCount.readUInt32BE(0);this.sigIdxs=[];for(let i=0;i(a,b)=>{const aoutid=buffer_1.Buffer.alloc(4);aoutid.writeUInt32BE(a.getOperationID(),0);const abuff=a.toBuffer(),boutid=buffer_1.Buffer.alloc(4);boutid.writeUInt32BE(b.getOperationID(),0);const bbuff=b.toBuffer(),asort=buffer_1.Buffer.concat([aoutid,abuff],aoutid.length+abuff.length),bsort=buffer_1.Buffer.concat([boutid,bbuff],boutid.length+bbuff.length);return buffer_1.Buffer.compare(asort,bsort)};class TransferableOperation extends serialization_1.Serializable{constructor(assetID,utxoids,operation){if(super(),this._typeName="TransferableOperation",this._typeID=void 0,this.assetID=buffer_1.Buffer.alloc(32),this.utxoIDs=[],this.getAssetID=()=>this.assetID,this.getUTXOIDs=()=>this.utxoIDs,this.getOperation=()=>this.operation,void 0!==assetID&&assetID.length===constants_1.AVMConstants.ASSETIDLEN&&operation instanceof Operation&&void 0!==utxoids&&Array.isArray(utxoids)){this.assetID=assetID,this.operation=operation;for(let i=0;iu.serialize(encoding))),operation:this.operation.serialize(encoding)})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.assetID=serialization.decoder(fields.assetID,encoding,"cb58","Buffer",32),this.utxoIDs=fields.utxoIDs.map((u=>{let utxoid=new UTXOID;return utxoid.deserialize(u,encoding),utxoid})),this.operation=(0,exports.SelectOperationClass)(fields.operation._typeID),this.operation.deserialize(fields.operation,encoding)}fromBuffer(bytes,offset=0){this.assetID=bintools.copyFrom(bytes,offset,offset+32),offset+=32;const numutxoIDs=bintools.copyFrom(bytes,offset,offset+4).readUInt32BE(0);offset+=4,this.utxoIDs=[];for(let i=0;ifunction(a,b){return buffer_1.Buffer.compare(a.toBuffer(),b.toBuffer())};class SECPMintOperation extends Operation{constructor(mintOutput,transferOutput){super(),this._typeName="SECPMintOperation",this._codecID=constants_1.AVMConstants.LATESTCODEC,this._typeID=0===this._codecID?constants_1.AVMConstants.SECPMINTOPID:constants_1.AVMConstants.SECPMINTOPID_CODECONE,this.mintOutput=void 0,this.transferOutput=void 0,void 0!==mintOutput&&(this.mintOutput=mintOutput),void 0!==transferOutput&&(this.transferOutput=transferOutput)}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{mintOutput:this.mintOutput.serialize(encoding),transferOutputs:this.transferOutput.serialize(encoding)})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.mintOutput=new outputs_1.SECPMintOutput,this.mintOutput.deserialize(fields.mintOutput,encoding),this.transferOutput=new outputs_1.SECPTransferOutput,this.transferOutput.deserialize(fields.transferOutputs,encoding)}setCodecID(codecID){if(0!==codecID&&1!==codecID)throw new errors_1.CodecIdError("Error - SECPMintOperation.setCodecID: invalid codecID. Valid codecIDs are 0 and 1.");this._codecID=codecID,this._typeID=0===this._codecID?constants_1.AVMConstants.SECPMINTOPID:constants_1.AVMConstants.SECPMINTOPID_CODECONE}getOperationID(){return this._typeID}getCredentialID(){return 0===this._codecID?constants_1.AVMConstants.SECPCREDENTIAL:1===this._codecID?constants_1.AVMConstants.SECPCREDENTIAL_CODECONE:void 0}getMintOutput(){return this.mintOutput}getTransferOutput(){return this.transferOutput}fromBuffer(bytes,offset=0){return offset=super.fromBuffer(bytes,offset),this.mintOutput=new outputs_1.SECPMintOutput,offset=this.mintOutput.fromBuffer(bytes,offset),this.transferOutput=new outputs_1.SECPTransferOutput,offset=this.transferOutput.fromBuffer(bytes,offset)}toBuffer(){const superbuff=super.toBuffer(),mintoutBuff=this.mintOutput.toBuffer(),transferOutBuff=this.transferOutput.toBuffer(),bsize=superbuff.length+mintoutBuff.length+transferOutBuff.length,barr=[superbuff,mintoutBuff,transferOutBuff];return buffer_1.Buffer.concat(barr,bsize)}}exports.SECPMintOperation=SECPMintOperation;class NFTMintOperation extends Operation{constructor(groupID,payload,outputOwners){super(),this._typeName="NFTMintOperation",this._codecID=constants_1.AVMConstants.LATESTCODEC,this._typeID=0===this._codecID?constants_1.AVMConstants.NFTMINTOPID:constants_1.AVMConstants.NFTMINTOPID_CODECONE,this.groupID=buffer_1.Buffer.alloc(4),this.outputOwners=[],this.getCredentialID=()=>0===this._codecID?constants_1.AVMConstants.NFTCREDENTIAL:1===this._codecID?constants_1.AVMConstants.NFTCREDENTIAL_CODECONE:void 0,this.getGroupID=()=>bintools.copyFrom(this.groupID,0),this.getPayload=()=>bintools.copyFrom(this.payload,0),this.getPayloadBuffer=()=>{let payloadlen=buffer_1.Buffer.alloc(4);return payloadlen.writeUInt32BE(this.payload.length,0),buffer_1.Buffer.concat([payloadlen,bintools.copyFrom(this.payload,0)])},this.getOutputOwners=()=>this.outputOwners,void 0!==groupID&&void 0!==payload&&outputOwners.length&&(this.groupID.writeUInt32BE(groupID||0,0),this.payload=payload,this.outputOwners=outputOwners)}serialize(encoding="hex"){const fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{groupID:serialization.encoder(this.groupID,encoding,"Buffer","decimalString",4),payload:serialization.encoder(this.payload,encoding,"Buffer","hex"),outputOwners:this.outputOwners.map((o=>o.serialize(encoding)))})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.groupID=serialization.decoder(fields.groupID,encoding,"decimalString","Buffer",4),this.payload=serialization.decoder(fields.payload,encoding,"hex","Buffer"),this.outputOwners=fields.outputOwners.map((o=>{let oo=new output_1.OutputOwners;return oo.deserialize(o,encoding),oo}))}setCodecID(codecID){if(0!==codecID&&1!==codecID)throw new errors_1.CodecIdError("Error - NFTMintOperation.setCodecID: invalid codecID. Valid codecIDs are 0 and 1.");this._codecID=codecID,this._typeID=0===this._codecID?constants_1.AVMConstants.NFTMINTOPID:constants_1.AVMConstants.NFTMINTOPID_CODECONE}getOperationID(){return this._typeID}fromBuffer(bytes,offset=0){offset=super.fromBuffer(bytes,offset),this.groupID=bintools.copyFrom(bytes,offset,offset+4),offset+=4;let payloadLen=bintools.copyFrom(bytes,offset,offset+4).readUInt32BE(0);offset+=4,this.payload=bintools.copyFrom(bytes,offset,offset+payloadLen),offset+=payloadLen;let numoutputs=bintools.copyFrom(bytes,offset,offset+4).readUInt32BE(0);offset+=4,this.outputOwners=[];for(let i=0;ithis.output,void 0!==output&&(this.output=output)}serialize(encoding="hex"){const fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{output:this.output.serialize(encoding)})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.output=new outputs_1.NFTTransferOutput,this.output.deserialize(fields.output,encoding)}setCodecID(codecID){if(0!==codecID&&1!==codecID)throw new errors_1.CodecIdError("Error - NFTTransferOperation.setCodecID: invalid codecID. Valid codecIDs are 0 and 1.");this._codecID=codecID,this._typeID=0===this._codecID?constants_1.AVMConstants.NFTXFEROPID:constants_1.AVMConstants.NFTXFEROPID_CODECONE}getOperationID(){return this._typeID}getCredentialID(){return 0===this._codecID?constants_1.AVMConstants.NFTCREDENTIAL:1===this._codecID?constants_1.AVMConstants.NFTCREDENTIAL_CODECONE:void 0}fromBuffer(bytes,offset=0){return offset=super.fromBuffer(bytes,offset),this.output=new outputs_1.NFTTransferOutput,this.output.fromBuffer(bytes,offset)}toBuffer(){const superbuff=super.toBuffer(),outbuff=this.output.toBuffer(),bsize=superbuff.length+outbuff.length,barr=[superbuff,outbuff];return buffer_1.Buffer.concat(barr,bsize)}toString(){return bintools.bufferToB58(this.toBuffer())}}exports.NFTTransferOperation=NFTTransferOperation;class UTXOID extends nbytes_1.NBytes{constructor(){super(),this._typeName="UTXOID",this._typeID=void 0,this.bytes=buffer_1.Buffer.alloc(36),this.bsize=36}toString(){return bintools.cb58Encode(this.toBuffer())}fromString(utxoid){const utxoidbuff=bintools.b58ToBuffer(utxoid);if(40===utxoidbuff.length&&bintools.validateChecksum(utxoidbuff)){const newbuff=bintools.copyFrom(utxoidbuff,0,utxoidbuff.length-4);36===newbuff.length&&(this.bytes=newbuff)}else{if(40===utxoidbuff.length)throw new errors_1.ChecksumError("Error - UTXOID.fromString: invalid checksum on address");if(36!==utxoidbuff.length)throw new errors_1.AddressError("Error - UTXOID.fromString: invalid address");this.bytes=utxoidbuff}return this.getSize()}clone(){const newbase=new UTXOID;return newbase.fromBuffer(this.toBuffer()),newbase}create(...args){return new UTXOID}}exports.UTXOID=UTXOID,UTXOID.comparator=()=>(a,b)=>buffer_1.Buffer.compare(a.toBuffer(),b.toBuffer())},6578:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.NFTTransferOutput=exports.NFTMintOutput=exports.SECPMintOutput=exports.SECPTransferOutput=exports.NFTOutput=exports.AmountOutput=exports.TransferableOutput=exports.SelectOutputClass=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),constants_1=__webpack_require__(6667),output_1=__webpack_require__(8556),serialization_1=__webpack_require__(555),errors_1=__webpack_require__(611),bintools=bintools_1.default.getInstance(),serialization=serialization_1.Serialization.getInstance();exports.SelectOutputClass=(outputid,...args)=>{if(outputid===constants_1.AVMConstants.SECPXFEROUTPUTID||outputid===constants_1.AVMConstants.SECPXFEROUTPUTID_CODECONE)return new SECPTransferOutput(...args);if(outputid===constants_1.AVMConstants.SECPMINTOUTPUTID||outputid===constants_1.AVMConstants.SECPMINTOUTPUTID_CODECONE)return new SECPMintOutput(...args);if(outputid===constants_1.AVMConstants.NFTMINTOUTPUTID||outputid===constants_1.AVMConstants.NFTMINTOUTPUTID_CODECONE)return new NFTMintOutput(...args);if(outputid===constants_1.AVMConstants.NFTXFEROUTPUTID||outputid===constants_1.AVMConstants.NFTXFEROUTPUTID_CODECONE)return new NFTTransferOutput(...args);throw new errors_1.OutputIdError("Error - SelectOutputClass: unknown outputid "+outputid)};class TransferableOutput extends output_1.StandardTransferableOutput{constructor(){super(...arguments),this._typeName="TransferableOutput",this._typeID=void 0}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.output=(0,exports.SelectOutputClass)(fields.output._typeID),this.output.deserialize(fields.output,encoding)}fromBuffer(bytes,offset=0){this.assetID=bintools.copyFrom(bytes,offset,offset+constants_1.AVMConstants.ASSETIDLEN),offset+=constants_1.AVMConstants.ASSETIDLEN;const outputid=bintools.copyFrom(bytes,offset,offset+4).readUInt32BE(0);return offset+=4,this.output=(0,exports.SelectOutputClass)(outputid),this.output.fromBuffer(bytes,offset)}}exports.TransferableOutput=TransferableOutput;class AmountOutput extends output_1.StandardAmountOutput{constructor(){super(...arguments),this._typeName="AmountOutput",this._typeID=void 0}makeTransferable(assetID){return new TransferableOutput(assetID,this)}select(id,...args){return(0,exports.SelectOutputClass)(id,...args)}}exports.AmountOutput=AmountOutput;class NFTOutput extends output_1.BaseNFTOutput{constructor(){super(...arguments),this._typeName="NFTOutput",this._typeID=void 0}makeTransferable(assetID){return new TransferableOutput(assetID,this)}select(id,...args){return(0,exports.SelectOutputClass)(id,...args)}}exports.NFTOutput=NFTOutput;class SECPTransferOutput extends AmountOutput{constructor(){super(...arguments),this._typeName="SECPTransferOutput",this._codecID=constants_1.AVMConstants.LATESTCODEC,this._typeID=0===this._codecID?constants_1.AVMConstants.SECPXFEROUTPUTID:constants_1.AVMConstants.SECPXFEROUTPUTID_CODECONE}setCodecID(codecID){if(0!==codecID&&1!==codecID)throw new errors_1.CodecIdError("Error - SECPTransferOutput.setCodecID: invalid codecID. Valid codecIDs are 0 and 1.");this._codecID=codecID,this._typeID=0===this._codecID?constants_1.AVMConstants.SECPXFEROUTPUTID:constants_1.AVMConstants.SECPXFEROUTPUTID_CODECONE}getOutputID(){return this._typeID}create(...args){return new SECPTransferOutput(...args)}clone(){const newout=this.create();return newout.fromBuffer(this.toBuffer()),newout}}exports.SECPTransferOutput=SECPTransferOutput;class SECPMintOutput extends output_1.Output{constructor(){super(...arguments),this._typeName="SECPMintOutput",this._codecID=constants_1.AVMConstants.LATESTCODEC,this._typeID=0===this._codecID?constants_1.AVMConstants.SECPMINTOUTPUTID:constants_1.AVMConstants.SECPMINTOUTPUTID_CODECONE}setCodecID(codecID){if(0!==codecID&&1!==codecID)throw new errors_1.CodecIdError("Error - SECPMintOutput.setCodecID: invalid codecID. Valid codecIDs are 0 and 1.");this._codecID=codecID,this._typeID=0===this._codecID?constants_1.AVMConstants.SECPMINTOUTPUTID:constants_1.AVMConstants.SECPMINTOUTPUTID_CODECONE}getOutputID(){return this._typeID}makeTransferable(assetID){return new TransferableOutput(assetID,this)}create(...args){return new SECPMintOutput(...args)}clone(){const newout=this.create();return newout.fromBuffer(this.toBuffer()),newout}select(id,...args){return(0,exports.SelectOutputClass)(id,...args)}}exports.SECPMintOutput=SECPMintOutput;class NFTMintOutput extends NFTOutput{constructor(groupID,addresses,locktime,threshold){super(addresses,locktime,threshold),this._typeName="NFTMintOutput",this._codecID=constants_1.AVMConstants.LATESTCODEC,this._typeID=0===this._codecID?constants_1.AVMConstants.NFTMINTOUTPUTID:constants_1.AVMConstants.NFTMINTOUTPUTID_CODECONE,void 0!==groupID&&this.groupID.writeUInt32BE(groupID,0)}setCodecID(codecID){if(0!==codecID&&1!==codecID)throw new errors_1.CodecIdError("Error - NFTMintOutput.setCodecID: invalid codecID. Valid codecIDs are 0 and 1.");this._codecID=codecID,this._typeID=0===this._codecID?constants_1.AVMConstants.NFTMINTOUTPUTID:constants_1.AVMConstants.NFTMINTOUTPUTID_CODECONE}getOutputID(){return this._typeID}fromBuffer(utxobuff,offset=0){return this.groupID=bintools.copyFrom(utxobuff,offset,offset+4),offset+=4,super.fromBuffer(utxobuff,offset)}toBuffer(){let superbuff=super.toBuffer(),bsize=this.groupID.length+superbuff.length,barr=[this.groupID,superbuff];return buffer_1.Buffer.concat(barr,bsize)}create(...args){return new NFTMintOutput(...args)}clone(){const newout=this.create();return newout.fromBuffer(this.toBuffer()),newout}}exports.NFTMintOutput=NFTMintOutput;class NFTTransferOutput extends NFTOutput{constructor(groupID,payload,addresses,locktime,threshold){super(addresses,locktime,threshold),this._typeName="NFTTransferOutput",this._codecID=constants_1.AVMConstants.LATESTCODEC,this._typeID=0===this._codecID?constants_1.AVMConstants.NFTXFEROUTPUTID:constants_1.AVMConstants.NFTXFEROUTPUTID_CODECONE,this.sizePayload=buffer_1.Buffer.alloc(4),this.getPayload=()=>bintools.copyFrom(this.payload),this.getPayloadBuffer=()=>buffer_1.Buffer.concat([bintools.copyFrom(this.sizePayload),bintools.copyFrom(this.payload)]),void 0!==groupID&&void 0!==payload&&(this.groupID.writeUInt32BE(groupID,0),this.sizePayload.writeUInt32BE(payload.length,0),this.payload=bintools.copyFrom(payload,0,payload.length))}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{payload:serialization.encoder(this.payload,encoding,"Buffer","hex",this.payload.length)})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.payload=serialization.decoder(fields.payload,encoding,"hex","Buffer"),this.sizePayload=buffer_1.Buffer.alloc(4),this.sizePayload.writeUInt32BE(this.payload.length,0)}setCodecID(codecID){if(0!==codecID&&1!==codecID)throw new errors_1.CodecIdError("Error - NFTTransferOutput.setCodecID: invalid codecID. Valid codecIDs are 0 and 1.");this._codecID=codecID,this._typeID=0===this._codecID?constants_1.AVMConstants.NFTXFEROUTPUTID:constants_1.AVMConstants.NFTXFEROUTPUTID_CODECONE}getOutputID(){return this._typeID}fromBuffer(utxobuff,offset=0){this.groupID=bintools.copyFrom(utxobuff,offset,offset+4),offset+=4,this.sizePayload=bintools.copyFrom(utxobuff,offset,offset+4);let psize=this.sizePayload.readUInt32BE(0);return offset+=4,this.payload=bintools.copyFrom(utxobuff,offset,offset+psize),offset+=psize,super.fromBuffer(utxobuff,offset)}toBuffer(){const superbuff=super.toBuffer(),bsize=this.groupID.length+this.sizePayload.length+this.payload.length+superbuff.length;this.sizePayload.writeUInt32BE(this.payload.length,0);const barr=[this.groupID,this.sizePayload,this.payload,superbuff];return buffer_1.Buffer.concat(barr,bsize)}create(...args){return new NFTTransferOutput(...args)}clone(){const newout=this.create();return newout.fromBuffer(this.toBuffer()),newout}}exports.NFTTransferOutput=NFTTransferOutput},2577:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.Tx=exports.UnsignedTx=exports.SelectTxClass=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),constants_1=__webpack_require__(6667),credentials_1=__webpack_require__(2819),tx_1=__webpack_require__(613),create_hash_1=__importDefault(__webpack_require__(3482)),basetx_1=__webpack_require__(5662),createassettx_1=__webpack_require__(1926),operationtx_1=__webpack_require__(2710),importtx_1=__webpack_require__(1952),exporttx_1=__webpack_require__(1239),errors_1=__webpack_require__(611),bintools=bintools_1.default.getInstance();exports.SelectTxClass=(txtype,...args)=>{if(txtype===constants_1.AVMConstants.BASETX)return new basetx_1.BaseTx(...args);if(txtype===constants_1.AVMConstants.CREATEASSETTX)return new createassettx_1.CreateAssetTx(...args);if(txtype===constants_1.AVMConstants.OPERATIONTX)return new operationtx_1.OperationTx(...args);if(txtype===constants_1.AVMConstants.IMPORTTX)return new importtx_1.ImportTx(...args);if(txtype===constants_1.AVMConstants.EXPORTTX)return new exporttx_1.ExportTx(...args);throw new errors_1.TransactionError("Error - SelectTxClass: unknown txtype")};class UnsignedTx extends tx_1.StandardUnsignedTx{constructor(){super(...arguments),this._typeName="UnsignedTx",this._typeID=void 0}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.transaction=(0,exports.SelectTxClass)(fields.transaction._typeID),this.transaction.deserialize(fields.transaction,encoding)}getTransaction(){return this.transaction}fromBuffer(bytes,offset=0){this.codecID=bintools.copyFrom(bytes,offset,offset+2).readUInt16BE(0),offset+=2;const txtype=bintools.copyFrom(bytes,offset,offset+4).readUInt32BE(0);return offset+=4,this.transaction=(0,exports.SelectTxClass)(txtype),this.transaction.fromBuffer(bytes,offset)}sign(kc){const txbuff=this.toBuffer(),msg=buffer_1.Buffer.from((0,create_hash_1.default)("sha256").update(txbuff).digest()),creds=this.transaction.sign(msg,kc);return new Tx(this,creds)}}exports.UnsignedTx=UnsignedTx;class Tx extends tx_1.StandardTx{constructor(){super(...arguments),this._typeName="Tx",this._typeID=void 0}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.unsignedTx=new UnsignedTx,this.unsignedTx.deserialize(fields.unsignedTx,encoding),this.credentials=[];for(let i=0;i{const utxoArray=this.getAllUTXOs(),outids={};for(let i=0;i{if(threshold>toAddresses.length)throw new errors_1.ThresholdError("Error - UTXOSet.buildBaseTx: threshold is greater than number of addresses");void 0===changeAddresses&&(changeAddresses=toAddresses),void 0===feeAssetID&&(feeAssetID=assetID);const zero=new bn_js_1.default(0);if(amount.eq(zero))return;const aad=new AssetAmountDestination(toAddresses,fromAddresses,changeAddresses);assetID.toString("hex")===feeAssetID.toString("hex")?aad.addAssetAmount(assetID,amount,fee):(aad.addAssetAmount(assetID,amount,zero),this._feeCheck(fee,feeAssetID)&&aad.addAssetAmount(feeAssetID,zero,fee));let ins=[],outs=[];const success=this.getMinimumSpendable(aad,asOf,locktime,threshold);if(void 0!==success)throw success;ins=aad.getInputs(),outs=aad.getAllOutputs();const baseTx=new basetx_1.BaseTx(networkID,blockchainID,outs,ins,memo);return new tx_1.UnsignedTx(baseTx)},this.buildCreateAssetTx=(networkID,blockchainID,fromAddresses,changeAddresses,initialState,name,symbol,denomination,mintOutputs,fee,feeAssetID,memo,asOf=(0,helperfunctions_1.UnixNow)())=>{const zero=new bn_js_1.default(0);let ins=[],outs=[];if(this._feeCheck(fee,feeAssetID)){const aad=new AssetAmountDestination(fromAddresses,fromAddresses,changeAddresses);aad.addAssetAmount(feeAssetID,zero,fee);const success=this.getMinimumSpendable(aad,asOf);if(void 0!==success)throw success;ins=aad.getInputs(),outs=aad.getAllOutputs()}if(void 0!==mintOutputs)for(let i=0;i{const zero=new bn_js_1.default(0);let ins=[],outs=[];if(this._feeCheck(fee,feeAssetID)){const aad=new AssetAmountDestination(fromAddresses,fromAddresses,changeAddresses);aad.addAssetAmount(feeAssetID,zero,fee);const success=this.getMinimumSpendable(aad,asOf);if(void 0!==success)throw success;ins=aad.getInputs(),outs=aad.getAllOutputs()}let ops=[],mintOp=new ops_1.SECPMintOperation(mintOwner,transferOwner),utxo=this.getUTXO(mintUTXOID);if(void 0===utxo)throw new errors_1.UTXOError("Error - UTXOSet.buildSECPMintTx: UTXOID not found");if(utxo.getOutput().getOutputID()!==constants_1.AVMConstants.SECPMINTOUTPUTID)throw new errors_1.SECPMintOutputError("Error - UTXOSet.buildSECPMintTx: UTXO is not a SECPMINTOUTPUTID");let out=utxo.getOutput(),spenders=out.getSpenders(fromAddresses,asOf);for(let j=0;j{const zero=new bn_js_1.default(0);let ins=[],outs=[];if(this._feeCheck(fee,feeAssetID)){const aad=new AssetAmountDestination(fromAddresses,fromAddresses,changeAddresses);aad.addAssetAmount(feeAssetID,zero,fee);const success=this.getMinimumSpendable(aad,asOf);if(void 0!==success)throw success;ins=aad.getInputs(),outs=aad.getAllOutputs()}let initialState=new initialstates_1.InitialStates;for(let i=0;i{const zero=new bn_js_1.default(0);let ins=[],outs=[];if(this._feeCheck(fee,feeAssetID)){const aad=new AssetAmountDestination(fromAddresses,fromAddresses,changeAddresses);aad.addAssetAmount(feeAssetID,zero,fee);const success=this.getMinimumSpendable(aad,asOf);if(void 0!==success)throw success;ins=aad.getInputs(),outs=aad.getAllOutputs()}let ops=[],nftMintOperation=new ops_1.NFTMintOperation(groupID,payload,owners);for(let i=0;i{const zero=new bn_js_1.default(0);let ins=[],outs=[];if(this._feeCheck(fee,feeAssetID)){const aad=new AssetAmountDestination(fromAddresses,fromAddresses,changeAddresses);aad.addAssetAmount(feeAssetID,zero,fee);const success=this.getMinimumSpendable(aad,asOf);if(void 0!==success)throw success;ins=aad.getInputs(),outs=aad.getAllOutputs()}const ops=[];for(let i=0;i{const zero=new bn_js_1.default(0);let ins=[],outs=[];void 0===fee&&(fee=zero.clone());const importIns=[];let feepaid=new bn_js_1.default(0),feeAssetStr=feeAssetID.toString("hex");for(let i=0;i{let ins=[],outs=[],exportouts=[];void 0===changeAddresses&&(changeAddresses=toAddresses);const zero=new bn_js_1.default(0);if(amount.eq(zero))return;void 0===feeAssetID&&(feeAssetID=assetID),void 0===destinationChain&&(destinationChain=bintools.cb58Decode(constants_2.PlatformChainID));const aad=new AssetAmountDestination(toAddresses,fromAddresses,changeAddresses);assetID.toString("hex")===feeAssetID.toString("hex")?aad.addAssetAmount(assetID,amount,fee):(aad.addAssetAmount(assetID,amount,zero),this._feeCheck(fee,feeAssetID)&&aad.addAssetAmount(feeAssetID,zero,fee));const success=this.getMinimumSpendable(aad,asOf,locktime,threshold);if(void 0!==success)throw success;ins=aad.getInputs(),outs=aad.getChangeOutputs(),exportouts=aad.getOutputs();const exportTx=new exporttx_1.ExportTx(networkID,blockchainID,outs,ins,memo,destinationChain,exportouts);return new tx_1.UnsignedTx(exportTx)}}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding);let utxos={};for(let utxoid in fields.utxos){let utxoidCleaned=serialization.decoder(utxoid,encoding,"base58","base58");utxos[`${utxoidCleaned}`]=new UTXO,utxos[`${utxoidCleaned}`].deserialize(fields.utxos[`${utxoid}`],encoding)}let addressUTXOs={};for(let address in fields.addressUTXOs){let addressCleaned=serialization.decoder(address,encoding,"cb58","hex"),utxobalance={};for(let utxoid in fields.addressUTXOs[`${address}`]){utxobalance[`${serialization.decoder(utxoid,encoding,"base58","base58")}`]=serialization.decoder(fields.addressUTXOs[`${address}`][`${utxoid}`],encoding,"decimalString","BN")}addressUTXOs[`${addressCleaned}`]=utxobalance}this.utxos=utxos,this.addressUTXOs=addressUTXOs}parseUTXO(utxo){const utxovar=new UTXO;if("string"==typeof utxo)utxovar.fromBuffer(bintools.cb58Decode(utxo));else{if(!(utxo instanceof UTXO))throw new errors_1.UTXOError("Error - UTXO.parseUTXO: utxo parameter is not a UTXO or string");utxovar.fromBuffer(utxo.toBuffer())}return utxovar}create(...args){return new UTXOSet}clone(){const newset=this.create(),allUTXOs=this.getAllUTXOs();return newset.addArray(allUTXOs),newset}_feeCheck(fee,feeAssetID){return void 0!==fee&&void 0!==feeAssetID&&fee.gt(new bn_js_1.default(0))&&feeAssetID instanceof buffer_1.Buffer}}exports.UTXOSet=UTXOSet},1485:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.Vertex=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),constants_1=__webpack_require__(6667),tx_1=__webpack_require__(2577),utils_1=__webpack_require__(338),bn_js_1=__importDefault(__webpack_require__(3550)),bintools=bintools_1.default.getInstance();class Vertex extends utils_1.Serializable{constructor(networkID=utils_1.DefaultNetworkID,blockchainID="2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM",height=new bn_js_1.default(0),epoch=0,parentIDs=[],txs=[],restrictions=[]){super(),this._typeName="Vertex",this._codecID=constants_1.AVMConstants.LATESTCODEC,this.networkID=networkID,this.blockchainID=bintools.cb58Decode(blockchainID),this.height=height,this.epoch=epoch,this.parentIDs=parentIDs,this.numParentIDs=parentIDs.length,this.txs=txs,this.numTxs=txs.length,this.restrictions=restrictions,this.numRestrictions=restrictions.length}getNetworkID(){return this.networkID}getBlockchainID(){return bintools.cb58Encode(this.blockchainID)}getHeight(){return this.height}getEpoch(){return this.epoch}getParentIDs(){return this.parentIDs}getTxs(){return this.txs}getRestrictions(){return this.restrictions}setCodecID(codecID){if(0!==codecID&&1!==codecID)throw new utils_1.CodecIdError("Error - Vertex.setCodecID: invalid codecID. Valid codecIDs are 0 and 1.");this._codecID=codecID,this._typeID=0===this._codecID?constants_1.AVMConstants.VERTEX:constants_1.AVMConstants.VERTEX_CODECONE}fromBuffer(bytes,offset=0){offset+=2,this.blockchainID=bintools.copyFrom(bytes,offset,offset+32),offset+=32;const h=bintools.copyFrom(bytes,offset,offset+8);this.height=bintools.fromBufferToBN(h),offset+=8;const e=bintools.copyFrom(bytes,offset,offset+4);this.epoch=e.readInt32BE(0),offset+=4;const nPIDs=bintools.copyFrom(bytes,offset,offset+4);this.numParentIDs=nPIDs.readInt32BE(0),offset+=4;for(let i=0;ioffset&&bytes.byteLength-offset>4){const nRs=bintools.copyFrom(bytes,offset,offset+4);this.numRestrictions=nRs.readInt32BE(0),offset+=4;for(let i=0;i{barr.push(parentID)}));const txs=this.getTxs(),numTxs=buffer_1.Buffer.alloc(4);numTxs.writeUInt32BE(txs.length,0),barr.push(numTxs);let size=0;const txSize=buffer_1.Buffer.alloc(4);return txs.forEach((tx=>{const b=tx.toBuffer();size+=b.byteLength})),txSize.writeUInt32BE(size,0),barr.push(txSize),txs.forEach((tx=>{const b=tx.toBuffer();barr.push(b)})),buffer_1.Buffer.concat(barr)}clone(){let vertex=new Vertex;return vertex.fromBuffer(this.toBuffer()),vertex}}exports.Vertex=Vertex},9084:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))},__importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.EVMAPI=void 0;const buffer_1=__webpack_require__(8764),bn_js_1=__importDefault(__webpack_require__(3550)),jrpcapi_1=__webpack_require__(5912),bintools_1=__importDefault(__webpack_require__(903)),utxos_1=__webpack_require__(8643),keychain_1=__webpack_require__(1398),constants_1=__webpack_require__(8779),tx_1=__webpack_require__(5544),constants_2=__webpack_require__(6736),inputs_1=__webpack_require__(452),outputs_1=__webpack_require__(1179),exporttx_1=__webpack_require__(72),errors_1=__webpack_require__(611),utils_1=__webpack_require__(338),bintools=bintools_1.default.getInstance(),serialization=utils_1.Serialization.getInstance();class EVMAPI extends jrpcapi_1.JRPCAPI{constructor(core,baseURL="/ext/bc/C/avax",blockchainID=""){super(core,baseURL),this.keychain=new keychain_1.KeyChain("",""),this.blockchainID="",this.blockchainAlias=void 0,this.AVAXAssetID=void 0,this.txFee=void 0,this.getBlockchainAlias=()=>{if(void 0===this.blockchainAlias){const netID=this.core.getNetworkID();return netID in constants_1.Defaults.network&&this.blockchainID in constants_1.Defaults.network[`${netID}`]?(this.blockchainAlias=constants_1.Defaults.network[`${netID}`][this.blockchainID].alias,this.blockchainAlias):void 0}return this.blockchainAlias},this.setBlockchainAlias=alias=>{this.blockchainAlias=alias},this.getBlockchainID=()=>this.blockchainID,this.refreshBlockchainID=blockchainID=>{const netID=this.core.getNetworkID();return void 0===blockchainID&&void 0!==constants_1.Defaults.network[`${netID}`]?(this.blockchainID=constants_1.Defaults.network[`${netID}`].C.blockchainID,!0):"string"==typeof blockchainID&&(this.blockchainID=blockchainID,!0)},this.parseAddress=addr=>{const alias=this.getBlockchainAlias(),blockchainID=this.getBlockchainID();return bintools.parseAddress(addr,blockchainID,alias,constants_2.EVMConstants.ADDRESSLENGTH)},this.addressFromBuffer=address=>{const chainID=this.getBlockchainAlias()?this.getBlockchainAlias():this.getBlockchainID();return serialization.bufferToType(address,"bech32",this.core.getHRP(),chainID)},this.getAssetDescription=assetID=>__awaiter(this,void 0,void 0,(function*(){let asset;asset="string"!=typeof assetID?bintools.cb58Encode(assetID):assetID;const params={assetID:asset},tmpBaseURL=this.getBaseURL();this.setBaseURL("/ext/bc/X");const response=yield this.callMethod("avm.getAssetDescription",params);return this.setBaseURL(tmpBaseURL),{name:response.data.result.name,symbol:response.data.result.symbol,assetID:bintools.cb58Decode(response.data.result.assetID),denomination:parseInt(response.data.result.denomination,10)}})),this.getAVAXAssetID=(refresh=!1)=>__awaiter(this,void 0,void 0,(function*(){if(void 0===this.AVAXAssetID||refresh){const asset=yield this.getAssetDescription(constants_1.PrimaryAssetAlias);this.AVAXAssetID=asset.assetID}return this.AVAXAssetID})),this.setAVAXAssetID=avaxAssetID=>{"string"==typeof avaxAssetID&&(avaxAssetID=bintools.cb58Decode(avaxAssetID)),this.AVAXAssetID=avaxAssetID},this.getDefaultTxFee=()=>this.core.getNetworkID()in constants_1.Defaults.network?new bn_js_1.default(constants_1.Defaults.network[this.core.getNetworkID()].C.txFee):new bn_js_1.default(0),this.getAssetBalance=(hexAddress,blockHeight,assetID)=>__awaiter(this,void 0,void 0,(function*(){const params=[hexAddress,blockHeight,assetID];return(yield this.callMethod("eth_getAssetBalance",params,"ext/bc/C/rpc")).data})),this.getAtomicTxStatus=txID=>__awaiter(this,void 0,void 0,(function*(){const params={txID},response=yield this.callMethod("avax.getAtomicTxStatus",params);return response.data.result.status?response.data.result.status:response.data.result})),this.getAtomicTx=txID=>__awaiter(this,void 0,void 0,(function*(){const params={txID};return(yield this.callMethod("avax.getAtomicTx",params)).data.result.tx})),this.getTxFee=()=>(void 0===this.txFee&&(this.txFee=this.getDefaultTxFee()),this.txFee),this.export=(username,password,to,amount,assetID)=>__awaiter(this,void 0,void 0,(function*(){const params={to,amount:amount.toString(10),username,password,assetID},response=yield this.callMethod("avax.export",params);return response.data.result.txID?response.data.result.txID:response.data.result})),this.exportAVAX=(username,password,to,amount)=>__awaiter(this,void 0,void 0,(function*(){const params={to,amount:amount.toString(10),username,password},response=yield this.callMethod("avax.exportAVAX",params);return response.data.result.txID?response.data.result.txID:response.data.result})),this.getUTXOs=(addresses,sourceChain,limit=0,startIndex,encoding="hex")=>__awaiter(this,void 0,void 0,(function*(){"string"==typeof addresses&&(addresses=[addresses]);const params={addresses,limit,encoding};void 0!==startIndex&&startIndex&&(params.startIndex=startIndex),void 0!==sourceChain&&(params.sourceChain=sourceChain);const response=yield this.callMethod("avax.getUTXOs",params),utxos=new utxos_1.UTXOSet,data=response.data.result.utxos;if(data.length>0&&"0x"===data[0].substring(0,2)){const cb58Strs=[];data.forEach((str=>{cb58Strs.push(bintools.cb58Encode(new buffer_1.Buffer(str.slice(2),"hex")))})),utxos.addArray(cb58Strs,!1)}else utxos.addArray(data,!1);return response.data.result.utxos=utxos,response.data.result})),this.import=(username,password,to,sourceChain)=>__awaiter(this,void 0,void 0,(function*(){const params={to,sourceChain,username,password},response=yield this.callMethod("avax.import",params);return response.data.result.txID?response.data.result.txID:response.data.result})),this.importAVAX=(username,password,to,sourceChain)=>__awaiter(this,void 0,void 0,(function*(){const params={to,sourceChain,username,password},response=yield this.callMethod("avax.importAVAX",params);return response.data.result.txID?response.data.result.txID:response.data.result})),this.importKey=(username,password,privateKey)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password,privateKey},response=yield this.callMethod("avax.importKey",params);return response.data.result.address?response.data.result.address:response.data.result})),this.issueTx=tx=>__awaiter(this,void 0,void 0,(function*(){let Transaction="";if("string"==typeof tx)Transaction=tx;else if(tx instanceof buffer_1.Buffer){const txobj=new tx_1.Tx;txobj.fromBuffer(tx),Transaction=txobj.toStringHex()}else{if(!(tx instanceof tx_1.Tx))throw new errors_1.TransactionError("Error - avax.issueTx: provided tx is not expected type of string, Buffer, or Tx");Transaction=tx.toStringHex()}const params={tx:Transaction.toString(),encoding:"hex"},response=yield this.callMethod("avax.issueTx",params);return response.data.result.txID?response.data.result.txID:response.data.result})),this.exportKey=(username,password,address)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password,address};return(yield this.callMethod("avax.exportKey",params)).data.result})),this.buildImportTx=(utxoset,toAddress,ownerAddresses,sourceChain,fromAddresses,fee=new bn_js_1.default(0))=>__awaiter(this,void 0,void 0,(function*(){this._cleanAddressArray(fromAddresses,"buildImportTx").map((a=>bintools.stringToAddress(a)));let srcChain;if("string"==typeof sourceChain)srcChain=sourceChain,sourceChain=bintools.cb58Decode(sourceChain);else if(void 0===sourceChain||!(sourceChain instanceof buffer_1.Buffer))throw new errors_1.ChainIdError("Error - EVMAPI.buildImportTx: sourceChain is undefined or invalid sourceChain type.");const atomicUTXOs=(yield this.getUTXOs(ownerAddresses,srcChain,0,void 0)).utxos,networkID=this.core.getNetworkID(),avaxAssetID=constants_1.Defaults.network[`${networkID}`].X.avaxAssetID,avaxAssetIDBuf=bintools.cb58Decode(avaxAssetID),atomics=atomicUTXOs.getAllUTXOs();if(0===atomics.length)throw new errors_1.NoAtomicUTXOsError("Error - EVMAPI.buildImportTx: no atomic utxos to import");return utxoset.buildImportTx(networkID,bintools.cb58Decode(this.blockchainID),toAddress,atomics,sourceChain,fee,avaxAssetIDBuf)})),this.buildExportTx=(amount,assetID,destinationChain,fromAddressHex,fromAddressBech,toAddresses,nonce=0,locktime=new bn_js_1.default(0),threshold=1,fee=new bn_js_1.default(0))=>__awaiter(this,void 0,void 0,(function*(){const prefixes={};if(toAddresses.map((address=>{prefixes[address.split("-")[0]]=!0})),1!==Object.keys(prefixes).length)throw new errors_1.AddressError("Error - EVMAPI.buildExportTx: To addresses must have the same chainID prefix.");if(void 0===destinationChain)throw new errors_1.ChainIdError("Error - EVMAPI.buildExportTx: Destination ChainID is undefined.");if("string"==typeof destinationChain)destinationChain=bintools.cb58Decode(destinationChain);else if(!(destinationChain instanceof buffer_1.Buffer))throw new errors_1.ChainIdError("Error - EVMAPI.buildExportTx: Invalid destinationChain type");if(32!==destinationChain.length)throw new errors_1.ChainIdError("Error - EVMAPI.buildExportTx: Destination ChainID must be 32 bytes in length.");const assetDescription=yield this.getAssetDescription("AVAX");let evmInputs=[];if(bintools.cb58Encode(assetDescription.assetID)===assetID){const evmInput=new inputs_1.EVMInput(fromAddressHex,amount.add(fee),assetID,nonce);evmInput.addSignatureIdx(0,bintools.stringToAddress(fromAddressBech)),evmInputs.push(evmInput)}else{const evmAVAXInput=new inputs_1.EVMInput(fromAddressHex,fee,assetDescription.assetID,nonce);evmAVAXInput.addSignatureIdx(0,bintools.stringToAddress(fromAddressBech)),evmInputs.push(evmAVAXInput);const evmANTInput=new inputs_1.EVMInput(fromAddressHex,amount,assetID,nonce);evmANTInput.addSignatureIdx(0,bintools.stringToAddress(fromAddressBech)),evmInputs.push(evmANTInput)}const to=[];toAddresses.map((address=>{to.push(bintools.stringToAddress(address))}));let exportedOuts=[];const secpTransferOutput=new outputs_1.SECPTransferOutput(amount,to,locktime,threshold),transferableOutput=new outputs_1.TransferableOutput(bintools.cb58Decode(assetID),secpTransferOutput);exportedOuts.push(transferableOutput),evmInputs=evmInputs.sort(inputs_1.EVMInput.comparator()),exportedOuts=exportedOuts.sort(outputs_1.TransferableOutput.comparator());const exportTx=new exporttx_1.ExportTx(this.core.getNetworkID(),bintools.cb58Decode(this.blockchainID),destinationChain,evmInputs,exportedOuts);return new tx_1.UnsignedTx(exportTx)})),this.keyChain=()=>this.keychain,this.newKeyChain=()=>{const alias=this.getBlockchainAlias();return this.keychain=alias?new keychain_1.KeyChain(this.core.getHRP(),alias):new keychain_1.KeyChain(this.core.getHRP(),this.blockchainID),this.keychain},this.getBaseFee=()=>__awaiter(this,void 0,void 0,(function*(){return(yield this.callMethod("eth_baseFee",[],"ext/bc/C/rpc")).data.result})),this.getMaxPriorityFeePerGas=()=>__awaiter(this,void 0,void 0,(function*(){return(yield this.callMethod("eth_maxPriorityFeePerGas",[],"ext/bc/C/rpc")).data.result})),this.blockchainID=blockchainID;const netID=core.getNetworkID();if(netID in constants_1.Defaults.network&&blockchainID in constants_1.Defaults.network[`${netID}`]){const alias=constants_1.Defaults.network[`${netID}`][`${blockchainID}`].alias;this.keychain=new keychain_1.KeyChain(this.core.getHRP(),alias)}else this.keychain=new keychain_1.KeyChain(this.core.getHRP(),blockchainID)}_cleanAddressArray(addresses,caller){const addrs=[],chainid=this.getBlockchainAlias()?this.getBlockchainAlias():this.getBlockchainID();return addresses&&addresses.length>0&&addresses.forEach((address=>{if("string"==typeof address){if(void 0===this.parseAddress(address))throw new errors_1.AddressError("Error - Invalid address format");addrs.push(address)}else{const type="bech32";addrs.push(serialization.bufferToType(address,type,this.core.getHRP(),chainid))}})),addrs}}exports.EVMAPI=EVMAPI},5674:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.EVMBaseTx=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),evmtx_1=__webpack_require__(7965),constants_1=__webpack_require__(8779),tx_1=__webpack_require__(5544),bintools=bintools_1.default.getInstance();class EVMBaseTx extends evmtx_1.EVMStandardBaseTx{constructor(networkID=constants_1.DefaultNetworkID,blockchainID=buffer_1.Buffer.alloc(32,16)){super(networkID,blockchainID),this._typeName="BaseTx",this._typeID=void 0}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding)}getTxType(){return this._typeID}fromBuffer(bytes,offset=0){return this.networkID=bintools.copyFrom(bytes,offset,offset+4),offset+=4,this.blockchainID=bintools.copyFrom(bytes,offset,offset+32),offset+=32}sign(msg,kc){return[]}clone(){const newEVMBaseTx=new EVMBaseTx;return newEVMBaseTx.fromBuffer(this.toBuffer()),newEVMBaseTx}create(...args){return new EVMBaseTx(...args)}select(id,...args){return(0,tx_1.SelectTxClass)(id,...args)}}exports.EVMBaseTx=EVMBaseTx},6736:(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.EVMConstants=void 0;class EVMConstants{}exports.EVMConstants=EVMConstants,EVMConstants.SECPCREDENTIAL=9,EVMConstants.IMPORTTX=0,EVMConstants.EXPORTTX=1,EVMConstants.SECPINPUTID=5,EVMConstants.ASSETIDLEN=32,EVMConstants.SECPXFEROUTPUTID=7,EVMConstants.LATESTCODEC=0,EVMConstants.ADDRESSLENGTH=20},2501:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SECPCredential=exports.SelectCredentialClass=void 0;const constants_1=__webpack_require__(6736),credentials_1=__webpack_require__(5375),errors_1=__webpack_require__(611);exports.SelectCredentialClass=(credid,...args)=>{if(credid===constants_1.EVMConstants.SECPCREDENTIAL)return new SECPCredential(...args);throw new errors_1.CredIdError("Error - SelectCredentialClass: unknown credid")};class SECPCredential extends credentials_1.Credential{constructor(){super(...arguments),this._typeName="SECPCredential",this._typeID=constants_1.EVMConstants.SECPCREDENTIAL}getCredentialID(){return this._typeID}clone(){let newbase=new SECPCredential;return newbase.fromBuffer(this.toBuffer()),newbase}create(...args){return new SECPCredential(...args)}select(id,...args){return(0,exports.SelectCredentialClass)(id,...args)}}exports.SECPCredential=SECPCredential},72:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.ExportTx=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),constants_1=__webpack_require__(6736),basetx_1=__webpack_require__(5674),credentials_1=__webpack_require__(2501),credentials_2=__webpack_require__(5375),inputs_1=__webpack_require__(452),serialization_1=__webpack_require__(555),outputs_1=__webpack_require__(1179),errors_1=__webpack_require__(611),bintools=bintools_1.default.getInstance(),serializer=serialization_1.Serialization.getInstance();class ExportTx extends basetx_1.EVMBaseTx{constructor(networkID,blockchainID=buffer_1.Buffer.alloc(32,16),destinationChain=buffer_1.Buffer.alloc(32,16),inputs,exportedOutputs){super(networkID,blockchainID),this._typeName="ExportTx",this._typeID=constants_1.EVMConstants.EXPORTTX,this.destinationChain=buffer_1.Buffer.alloc(32),this.numInputs=buffer_1.Buffer.alloc(4),this.inputs=[],this.numExportedOutputs=buffer_1.Buffer.alloc(4),this.exportedOutputs=[],this.destinationChain=destinationChain,void 0!==inputs&&Array.isArray(inputs)&&(inputs.forEach((input=>{if(!(input instanceof inputs_1.EVMInput))throw new errors_1.EVMInputError("Error - ExportTx.constructor: invalid EVMInput in array parameter 'inputs'")})),inputs.length>1&&(inputs=inputs.sort(inputs_1.EVMInput.comparator())),this.inputs=inputs),void 0!==exportedOutputs&&Array.isArray(exportedOutputs)&&(exportedOutputs.forEach((exportedOutput=>{if(!(exportedOutput instanceof outputs_1.TransferableOutput))throw new errors_1.TransferableOutputError("Error - ExportTx.constructor: TransferableOutput EVMInput in array parameter 'exportedOutputs'")})),this.exportedOutputs=exportedOutputs)}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{destinationChain:serializer.encoder(this.destinationChain,encoding,"Buffer","cb58"),exportedOutputs:this.exportedOutputs.map((i=>i.serialize(encoding)))})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.destinationChain=serializer.decoder(fields.destinationChain,encoding,"cb58","Buffer",32),this.exportedOutputs=fields.exportedOutputs.map((i=>{let eo=new outputs_1.TransferableOutput;return eo.deserialize(i,encoding),eo})),this.numExportedOutputs=buffer_1.Buffer.alloc(4),this.numExportedOutputs.writeUInt32BE(this.exportedOutputs.length,0)}getDestinationChain(){return this.destinationChain}getInputs(){return this.inputs}getExportedOutputs(){return this.exportedOutputs}toBuffer(){if(void 0===this.destinationChain)throw new errors_1.ChainIdError("ExportTx.toBuffer -- this.destinationChain is undefined");this.numInputs.writeUInt32BE(this.inputs.length,0),this.numExportedOutputs.writeUInt32BE(this.exportedOutputs.length,0);let barr=[super.toBuffer(),this.destinationChain,this.numInputs],bsize=super.toBuffer().length+this.destinationChain.length+this.numInputs.length;return this.inputs.forEach((importIn=>{bsize+=importIn.toBuffer().length,barr.push(importIn.toBuffer())})),bsize+=this.numExportedOutputs.length,barr.push(this.numExportedOutputs),this.exportedOutputs.forEach((out=>{bsize+=out.toBuffer().length,barr.push(out.toBuffer())})),buffer_1.Buffer.concat(barr,bsize)}fromBuffer(bytes,offset=0){offset=super.fromBuffer(bytes,offset),this.destinationChain=bintools.copyFrom(bytes,offset,offset+32),offset+=32,this.numInputs=bintools.copyFrom(bytes,offset,offset+4),offset+=4;const numInputs=this.numInputs.readUInt32BE(0);for(let i=0;i{const cred=(0,credentials_1.SelectCredentialClass)(input.getCredentialID());input.getSigIdxs().forEach((sigidx=>{const signval=kc.getKey(sigidx.getSource()).sign(msg),sig=new credentials_2.Signature;sig.fromBuffer(signval),cred.addSignature(sig)})),creds.push(cred)})),creds}}exports.ExportTx=ExportTx},6419:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.ImportTx=void 0;const buffer_1=__webpack_require__(8764),bn_js_1=__importDefault(__webpack_require__(3550)),bintools_1=__importDefault(__webpack_require__(903)),constants_1=__webpack_require__(6736),outputs_1=__webpack_require__(1179),inputs_1=__webpack_require__(452),basetx_1=__webpack_require__(5674),credentials_1=__webpack_require__(2501),credentials_2=__webpack_require__(5375),input_1=__webpack_require__(1149),constants_2=__webpack_require__(8779),serialization_1=__webpack_require__(555),errors_1=__webpack_require__(611),bintools=bintools_1.default.getInstance(),serializer=serialization_1.Serialization.getInstance();class ImportTx extends basetx_1.EVMBaseTx{constructor(networkID=constants_2.DefaultNetworkID,blockchainID=buffer_1.Buffer.alloc(32,16),sourceChainID=buffer_1.Buffer.alloc(32,16),importIns,outs,fee=new bn_js_1.default(0)){super(networkID,blockchainID),this._typeName="ImportTx",this._typeID=constants_1.EVMConstants.IMPORTTX,this.sourceChain=buffer_1.Buffer.alloc(32),this.numIns=buffer_1.Buffer.alloc(4),this.importIns=[],this.numOuts=buffer_1.Buffer.alloc(4),this.outs=[],this.sourceChain=sourceChainID;let inputsPassed=!1,outputsPassed=!1;void 0!==importIns&&Array.isArray(importIns)&&importIns.length>0&&(importIns.forEach((importIn=>{if(!(importIn instanceof inputs_1.TransferableInput))throw new errors_1.TransferableInputError("Error - ImportTx.constructor: invalid TransferableInput in array parameter 'importIns'")})),inputsPassed=!0,this.importIns=importIns),void 0!==outs&&Array.isArray(outs)&&outs.length>0&&(outs.forEach((out=>{if(!(out instanceof outputs_1.EVMOutput))throw new errors_1.EVMOutputError("Error - ImportTx.constructor: invalid EVMOutput in array parameter 'outs'")})),outs.length>1&&(outs=outs.sort(outputs_1.EVMOutput.comparator())),outputsPassed=!0,this.outs=outs),inputsPassed&&outputsPassed&&this.validateOuts(fee)}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{sourceChain:serializer.encoder(this.sourceChain,encoding,"Buffer","cb58"),importIns:this.importIns.map((i=>i.serialize(encoding)))})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.sourceChain=serializer.decoder(fields.sourceChain,encoding,"cb58","Buffer",32),this.importIns=fields.importIns.map((i=>{let ii=new inputs_1.TransferableInput;return ii.deserialize(i,encoding),ii})),this.numIns=buffer_1.Buffer.alloc(4),this.numIns.writeUInt32BE(this.importIns.length,0)}getTxType(){return this._typeID}getSourceChain(){return this.sourceChain}fromBuffer(bytes,offset=0){offset=super.fromBuffer(bytes,offset),this.sourceChain=bintools.copyFrom(bytes,offset,offset+32),offset+=32,this.numIns=bintools.copyFrom(bytes,offset,offset+4),offset+=4;const numIns=this.numIns.readUInt32BE(0);for(let i=0;i{bsize+=importIn.toBuffer().length,barr.push(importIn.toBuffer())})),bsize+=this.numOuts.length,barr.push(this.numOuts),this.outs.forEach((out=>{bsize+=out.toBuffer().length,barr.push(out.toBuffer())})),buffer_1.Buffer.concat(barr,bsize)}getImportInputs(){return this.importIns}getOuts(){return this.outs}clone(){let newImportTx=new ImportTx;return newImportTx.fromBuffer(this.toBuffer()),newImportTx}create(...args){return new ImportTx(...args)}sign(msg,kc){const creds=super.sign(msg,kc);return this.importIns.forEach((importIn=>{const cred=(0,credentials_1.SelectCredentialClass)(importIn.getInput().getCredentialID());importIn.getInput().getSigIdxs().forEach((sigidx=>{const signval=kc.getKey(sigidx.getSource()).sign(msg),sig=new credentials_2.Signature;sig.fromBuffer(signval),cred.addSignature(sig)})),creds.push(cred)})),creds}validateOuts(fee){const seenAssetSends=new Map;this.outs.forEach((evmOutput=>{const address=evmOutput.getAddressString(),assetId=bintools.cb58Encode(evmOutput.getAssetID());if(seenAssetSends.has(address)){const assetsSentToAddress=seenAssetSends.get(address);if(assetsSentToAddress.includes(assetId)){const errorMessage=`Error - ImportTx: duplicate (address, assetId) pair found in outputs: (0x${address}, ${assetId})`;throw new errors_1.EVMOutputError(errorMessage)}assetsSentToAddress.push(assetId)}else seenAssetSends.set(address,[assetId])}));const selectedNetwork=this.getNetworkID(),feeDiff=new bn_js_1.default(0),avaxAssetID=constants_2.Defaults.network[`${selectedNetwork}`].X.avaxAssetID;if(this.importIns.forEach((input=>{if(input.getInput()instanceof input_1.StandardAmountInput&&avaxAssetID===bintools.cb58Encode(input.getAssetID())){const i=input.getInput();feeDiff.iadd(i.getAmount())}})),this.outs.forEach((evmOutput=>{avaxAssetID===bintools.cb58Encode(evmOutput.getAssetID())&&feeDiff.isub(evmOutput.getAmount())})),feeDiff.lt(fee)){const errorMessage=`Error - ${fee} nAVAX required for fee and only ${feeDiff} nAVAX provided`;throw new errors_1.EVMFeeError(errorMessage)}}}exports.ImportTx=ImportTx},5743:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)"default"===p||Object.prototype.hasOwnProperty.call(exports,p)||__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:!0}),__exportStar(__webpack_require__(9084),exports),__exportStar(__webpack_require__(5674),exports),__exportStar(__webpack_require__(6736),exports),__exportStar(__webpack_require__(2501),exports),__exportStar(__webpack_require__(452),exports),__exportStar(__webpack_require__(4119),exports),__exportStar(__webpack_require__(72),exports),__exportStar(__webpack_require__(6419),exports),__exportStar(__webpack_require__(1398),exports),__exportStar(__webpack_require__(1179),exports),__exportStar(__webpack_require__(5544),exports),__exportStar(__webpack_require__(8643),exports)},452:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.EVMInput=exports.SECPTransferInput=exports.AmountInput=exports.TransferableInput=exports.SelectInputClass=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),constants_1=__webpack_require__(6736),input_1=__webpack_require__(1149),outputs_1=__webpack_require__(1179),bn_js_1=__importDefault(__webpack_require__(3550)),credentials_1=__webpack_require__(5375),errors_1=__webpack_require__(611),utils_1=__webpack_require__(338),bintools=bintools_1.default.getInstance();exports.SelectInputClass=(inputID,...args)=>{if(inputID===constants_1.EVMConstants.SECPINPUTID)return new SECPTransferInput(...args);throw new errors_1.InputIdError("Error - SelectInputClass: unknown inputID")};class TransferableInput extends input_1.StandardTransferableInput{constructor(){super(...arguments),this._typeName="TransferableInput",this._typeID=void 0,this.getCost=()=>this.getInput().getSigIdxs().length*utils_1.Defaults.network[1].C.costPerSignature}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.input=(0,exports.SelectInputClass)(fields.input._typeID),this.input.deserialize(fields.input,encoding)}fromBuffer(bytes,offset=0){this.txid=bintools.copyFrom(bytes,offset,offset+32),offset+=32,this.outputidx=bintools.copyFrom(bytes,offset,offset+4),offset+=4,this.assetID=bintools.copyFrom(bytes,offset,offset+constants_1.EVMConstants.ASSETIDLEN),offset+=32;const inputid=bintools.copyFrom(bytes,offset,offset+4).readUInt32BE(0);return offset+=4,this.input=(0,exports.SelectInputClass)(inputid),this.input.fromBuffer(bytes,offset)}}exports.TransferableInput=TransferableInput;class AmountInput extends input_1.StandardAmountInput{constructor(){super(...arguments),this._typeName="AmountInput",this._typeID=void 0}select(id,...args){return(0,exports.SelectInputClass)(id,...args)}}exports.AmountInput=AmountInput;class SECPTransferInput extends AmountInput{constructor(){super(...arguments),this._typeName="SECPTransferInput",this._typeID=constants_1.EVMConstants.SECPINPUTID,this.getCredentialID=()=>constants_1.EVMConstants.SECPCREDENTIAL}getInputID(){return constants_1.EVMConstants.SECPINPUTID}create(...args){return new SECPTransferInput(...args)}clone(){const newout=this.create();return newout.fromBuffer(this.toBuffer()),newout}}exports.SECPTransferInput=SECPTransferInput;class EVMInput extends outputs_1.EVMOutput{constructor(address,amount,assetID,nonce){if(super(address,amount,assetID),this.nonce=buffer_1.Buffer.alloc(8),this.nonceValue=new bn_js_1.default(0),this.sigCount=buffer_1.Buffer.alloc(4),this.sigIdxs=[],this.getSigIdxs=()=>this.sigIdxs,this.addSignatureIdx=(addressIdx,address)=>{const sigidx=new credentials_1.SigIdx,b=buffer_1.Buffer.alloc(4);b.writeUInt32BE(addressIdx,0),sigidx.fromBuffer(b),sigidx.setSource(address),this.sigIdxs.push(sigidx),this.sigCount.writeUInt32BE(this.sigIdxs.length,0)},this.getNonce=()=>this.nonceValue.clone(),this.getCredentialID=()=>constants_1.EVMConstants.SECPCREDENTIAL,void 0!==nonce){let n;n="number"==typeof nonce?new bn_js_1.default(nonce):nonce,this.nonceValue=n.clone(),this.nonce=bintools.fromBNToBuffer(n,8)}}toBuffer(){let superbuff=super.toBuffer(),bsize=superbuff.length+this.nonce.length,barr=[superbuff,this.nonce];return buffer_1.Buffer.concat(barr,bsize)}fromBuffer(bytes,offset=0){return offset=super.fromBuffer(bytes,offset),this.nonce=bintools.copyFrom(bytes,offset,offset+8),offset+=8}toString(){return bintools.bufferToB58(this.toBuffer())}create(...args){return new EVMInput(...args)}clone(){const newEVMInput=this.create();return newEVMInput.fromBuffer(this.toBuffer()),newEVMInput}}exports.EVMInput=EVMInput},4119:(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0})},1398:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.KeyChain=exports.KeyPair=void 0;const bintools_1=__importDefault(__webpack_require__(903)),secp256k1_1=__webpack_require__(181),utils_1=__webpack_require__(338),bintools=bintools_1.default.getInstance();utils_1.Serialization.getInstance();class KeyPair extends secp256k1_1.SECP256k1KeyPair{clone(){const newkp=new KeyPair(this.hrp,this.chainID);return newkp.importKey(bintools.copyFrom(this.getPrivateKey())),newkp}create(...args){return 2==args.length?new KeyPair(args[0],args[1]):new KeyPair(this.hrp,this.chainID)}}exports.KeyPair=KeyPair;class KeyChain extends secp256k1_1.SECP256k1KeyChain{constructor(hrp,chainID){super(),this.hrp="",this.chainID="",this.makeKey=()=>{const keypair=new KeyPair(this.hrp,this.chainID);return this.addKey(keypair),keypair},this.addKey=newKey=>{newKey.setChainID(this.chainID),super.addKey(newKey)},this.importKey=privk=>{const keypair=new KeyPair(this.hrp,this.chainID);let pk;return pk="string"==typeof privk?bintools.cb58Decode(privk.split("-")[1]):bintools.copyFrom(privk),keypair.importKey(pk),keypair.getAddress().toString("hex")in this.keys||this.addKey(keypair),keypair},this.hrp=hrp,this.chainID=chainID}create(...args){return 2==args.length?new KeyChain(args[0],args[1]):new KeyChain(this.hrp,this.chainID)}clone(){const newkc=new KeyChain(this.hrp,this.chainID);for(let k in this.keys)newkc.addKey(this.keys[`${k}`].clone());return newkc}union(kc){const newkc=kc.clone();for(let k in this.keys)newkc.addKey(this.keys[`${k}`].clone());return newkc}}exports.KeyChain=KeyChain},1179:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.EVMOutput=exports.SECPTransferOutput=exports.AmountOutput=exports.TransferableOutput=exports.SelectOutputClass=void 0;const buffer_1=__webpack_require__(8764),bn_js_1=__importDefault(__webpack_require__(3550)),bintools_1=__importDefault(__webpack_require__(903)),constants_1=__webpack_require__(6736),output_1=__webpack_require__(8556),errors_1=__webpack_require__(611),bintools=bintools_1.default.getInstance();exports.SelectOutputClass=(outputID,...args)=>{if(outputID==constants_1.EVMConstants.SECPXFEROUTPUTID)return new SECPTransferOutput(...args);throw new errors_1.OutputIdError("Error - SelectOutputClass: unknown outputID")};class TransferableOutput extends output_1.StandardTransferableOutput{constructor(){super(...arguments),this._typeName="TransferableOutput",this._typeID=void 0}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.output=(0,exports.SelectOutputClass)(fields.output._typeID),this.output.deserialize(fields.output,encoding)}fromBuffer(bytes,offset=0){this.assetID=bintools.copyFrom(bytes,offset,offset+constants_1.EVMConstants.ASSETIDLEN),offset+=constants_1.EVMConstants.ASSETIDLEN;const outputid=bintools.copyFrom(bytes,offset,offset+4).readUInt32BE(0);return offset+=4,this.output=(0,exports.SelectOutputClass)(outputid),this.output.fromBuffer(bytes,offset)}}exports.TransferableOutput=TransferableOutput;class AmountOutput extends output_1.StandardAmountOutput{constructor(){super(...arguments),this._typeName="AmountOutput",this._typeID=void 0}makeTransferable(assetID){return new TransferableOutput(assetID,this)}select(id,...args){return(0,exports.SelectOutputClass)(id,...args)}}exports.AmountOutput=AmountOutput;class SECPTransferOutput extends AmountOutput{constructor(){super(...arguments),this._typeName="SECPTransferOutput",this._typeID=constants_1.EVMConstants.SECPXFEROUTPUTID}getOutputID(){return this._typeID}create(...args){return new SECPTransferOutput(...args)}clone(){const newout=this.create();return newout.fromBuffer(this.toBuffer()),newout}}exports.SECPTransferOutput=SECPTransferOutput;class EVMOutput{constructor(address,amount,assetID){if(this.address=buffer_1.Buffer.alloc(20),this.amount=buffer_1.Buffer.alloc(8),this.amountValue=new bn_js_1.default(0),this.assetID=buffer_1.Buffer.alloc(32),this.getAddress=()=>this.address,this.getAddressString=()=>this.address.toString("hex"),this.getAmount=()=>this.amountValue.clone(),this.getAssetID=()=>this.assetID,void 0!==address&&void 0!==amount&&void 0!==assetID){if("string"==typeof address){"0x"===address.substring(0,2)&&(address=address.split("x")[1]),address=buffer_1.Buffer.from(address,"hex")}let amnt;amnt="number"==typeof amount?new bn_js_1.default(amount):amount,assetID instanceof buffer_1.Buffer||(assetID=bintools.cb58Decode(assetID)),this.address=address,this.amountValue=amnt.clone(),this.amount=bintools.fromBNToBuffer(amnt,8),this.assetID=assetID}}toBuffer(){const bsize=this.address.length+this.amount.length+this.assetID.length,barr=[this.address,this.amount,this.assetID];return buffer_1.Buffer.concat(barr,bsize)}fromBuffer(bytes,offset=0){return this.address=bintools.copyFrom(bytes,offset,offset+20),offset+=20,this.amount=bintools.copyFrom(bytes,offset,offset+8),offset+=8,this.assetID=bintools.copyFrom(bytes,offset,offset+32),offset+=32,this.amountValue=new bn_js_1.default(this.amount),offset}toString(){return bintools.bufferToB58(this.toBuffer())}create(...args){return new EVMOutput(...args)}clone(){const newEVMOutput=this.create();return newEVMOutput.fromBuffer(this.toBuffer()),newEVMOutput}}exports.EVMOutput=EVMOutput,EVMOutput.comparator=()=>(a,b)=>{let sorta=a.getAddress(),sortb=b.getAddress();return sorta.equals(sortb)&&(sorta=a.getAssetID(),sortb=b.getAssetID()),buffer_1.Buffer.compare(sorta,sortb)}},5544:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.Tx=exports.UnsignedTx=exports.SelectTxClass=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),constants_1=__webpack_require__(6736),credentials_1=__webpack_require__(2501),evmtx_1=__webpack_require__(7965),create_hash_1=__importDefault(__webpack_require__(3482)),importtx_1=__webpack_require__(6419),exporttx_1=__webpack_require__(72),bintools=bintools_1.default.getInstance();exports.SelectTxClass=(txTypeID,...args)=>{if(txTypeID===constants_1.EVMConstants.IMPORTTX)return new importtx_1.ImportTx(...args);if(txTypeID===constants_1.EVMConstants.EXPORTTX)return new exporttx_1.ExportTx(...args);throw new Error("TransactionError - SelectTxClass: unknown txType")};class UnsignedTx extends evmtx_1.EVMStandardUnsignedTx{constructor(){super(...arguments),this._typeName="UnsignedTx",this._typeID=void 0}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.transaction=(0,exports.SelectTxClass)(fields.transaction._typeID),this.transaction.deserialize(fields.transaction,encoding)}getTransaction(){return this.transaction}fromBuffer(bytes,offset=0){this.codecID=bintools.copyFrom(bytes,offset,offset+2).readUInt16BE(0),offset+=2;const txtype=bintools.copyFrom(bytes,offset,offset+4).readUInt32BE(0);return offset+=4,this.transaction=(0,exports.SelectTxClass)(txtype),this.transaction.fromBuffer(bytes,offset)}sign(kc){const txbuff=this.toBuffer(),msg=buffer_1.Buffer.from((0,create_hash_1.default)("sha256").update(txbuff).digest()),creds=this.transaction.sign(msg,kc);return new Tx(this,creds)}}exports.UnsignedTx=UnsignedTx;class Tx extends evmtx_1.EVMStandardTx{constructor(){super(...arguments),this._typeName="Tx",this._typeID=void 0}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.unsignedTx=new UnsignedTx,this.unsignedTx.deserialize(fields.unsignedTx,encoding),this.credentials=[];for(let i=0;i{const utxoArray=this.getAllUTXOs(),outids={};for(let i=0;i{const idx=uout.getAddressIdx(spender);if(-1===idx)throw new errors_1.AddressError("Error - UTXOSet.getMinimumSpendable: no such address in output");xferin.getInput().addSignatureIdx(idx,spender)})),aad.addInput(xferin)}}}if(!aad.canComplete())return new errors_1.InsufficientFundsError("Error - UTXOSet.getMinimumSpendable: insufficient funds to create the transaction");const amounts=aad.getAmounts(),zero=new bn_js_1.default(0);for(let i=0;i{const zero=new bn_js_1.default(0),map=new Map;let ins=[],outs=[],feepaid=new bn_js_1.default(0);void 0===fee&&(fee=zero.clone()),atomics.forEach((atomic=>{const assetIDBuf=atomic.getAssetID(),assetID=bintools.cb58Encode(atomic.getAssetID()),output=atomic.getOutput(),amount=output.getAmount().clone();let infeeamount=amount.clone();void 0!==feeAssetID&&fee.gt(zero)&&feepaid.lt(fee)&&0===buffer_1.Buffer.compare(feeAssetID,assetIDBuf)&&(feepaid=feepaid.add(infeeamount),feepaid.gt(fee)?(infeeamount=feepaid.sub(fee),feepaid=fee.clone()):infeeamount=zero.clone());const txid=atomic.getTxID(),outputidx=atomic.getOutputIdx(),input=new inputs_1.SECPTransferInput(amount),xferin=new inputs_1.TransferableInput(txid,outputidx,assetIDBuf,input),from=output.getAddresses();output.getSpenders(from).forEach((spender=>{const idx=output.getAddressIdx(spender);if(-1===idx)throw new errors_1.AddressError("Error - UTXOSet.buildImportTx: no such address in output");xferin.getInput().addSignatureIdx(idx,spender)})),ins.push(xferin),map.has(assetID)&&(infeeamount=infeeamount.add(new bn_js_1.default(map.get(assetID)))),map.set(assetID,infeeamount.toString())}));for(let[assetID,amount]of map){const evmOutput=new outputs_1.EVMOutput(toAddress,new bn_js_1.default(amount),bintools.cb58Decode(assetID));outs.push(evmOutput)}ins=ins.sort(inputs_1.TransferableInput.comparator()),outs=outs.sort(outputs_1.EVMOutput.comparator());const importTx=new importtx_1.ImportTx(networkID,blockchainID,sourceChain,ins,outs,fee);return new tx_1.UnsignedTx(importTx)},this.buildExportTx=(networkID,blockchainID,amount,avaxAssetID,toAddresses,fromAddresses,changeAddresses,destinationChain,fee,feeAssetID,asOf=(0,helperfunctions_1.UnixNow)(),locktime=new bn_js_1.default(0),threshold=1)=>{let exportouts=[];void 0===changeAddresses&&(changeAddresses=toAddresses);const zero=new bn_js_1.default(0);if(amount.eq(zero))return;if(void 0===feeAssetID)feeAssetID=avaxAssetID;else if(feeAssetID.toString("hex")!==avaxAssetID.toString("hex"))throw new errors_1.FeeAssetError("Error - UTXOSet.buildExportTx: feeAssetID must match avaxAssetID");void 0===destinationChain&&(destinationChain=bintools.cb58Decode(constants_2.PlatformChainID));const aad=new AssetAmountDestination(toAddresses,fromAddresses,changeAddresses);avaxAssetID.toString("hex")===feeAssetID.toString("hex")?aad.addAssetAmount(avaxAssetID,amount,fee):(aad.addAssetAmount(avaxAssetID,amount,zero),this._feeCheck(fee,feeAssetID)&&aad.addAssetAmount(feeAssetID,zero,fee));const success=this.getMinimumSpendable(aad,asOf,locktime,threshold);if(void 0!==success)throw success;exportouts=aad.getOutputs();const exportTx=new exporttx_1.ExportTx(networkID,blockchainID,destinationChain,[],exportouts);return new tx_1.UnsignedTx(exportTx)}}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding);const utxos={};for(let utxoid in fields.utxos){let utxoidCleaned=serializer.decoder(utxoid,encoding,"base58","base58");utxos[`${utxoidCleaned}`]=new UTXO,utxos[`${utxoidCleaned}`].deserialize(fields.utxos[`${utxoid}`],encoding)}let addressUTXOs={};for(let address in fields.addressUTXOs){let addressCleaned=serializer.decoder(address,encoding,"cb58","hex"),utxobalance={};for(let utxoid in fields.addressUTXOs[`${address}`]){utxobalance[`${serializer.decoder(utxoid,encoding,"base58","base58")}`]=serializer.decoder(fields.addressUTXOs[`${address}`][`${utxoid}`],encoding,"decimalString","BN")}addressUTXOs[`${addressCleaned}`]=utxobalance}this.utxos=utxos,this.addressUTXOs=addressUTXOs}parseUTXO(utxo){const utxovar=new UTXO;if("string"==typeof utxo)utxovar.fromBuffer(bintools.cb58Decode(utxo));else{if(!(utxo instanceof UTXO))throw new errors_1.UTXOError("Error - UTXO.parseUTXO: utxo parameter is not a UTXO or string");utxovar.fromBuffer(utxo.toBuffer())}return utxovar}create(){return new UTXOSet}clone(){const newset=this.create(),allUTXOs=this.getAllUTXOs();return newset.addArray(allUTXOs),newset}_feeCheck(fee,feeAssetID){return void 0!==fee&&void 0!==feeAssetID&&fee.gt(new bn_js_1.default(0))&&feeAssetID instanceof buffer_1.Buffer}}exports.UTXOSet=UTXOSet},6778:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.HealthAPI=void 0;const jrpcapi_1=__webpack_require__(5912);class HealthAPI extends jrpcapi_1.JRPCAPI{constructor(core,baseURL="/ext/health"){super(core,baseURL),this.health=()=>__awaiter(this,void 0,void 0,(function*(){return(yield this.callMethod("health.health")).data.result}))}}exports.HealthAPI=HealthAPI},1996:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)"default"===p||Object.prototype.hasOwnProperty.call(exports,p)||__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:!0}),__exportStar(__webpack_require__(6778),exports)},1229:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.IndexAPI=void 0;const jrpcapi_1=__webpack_require__(5912);class IndexAPI extends jrpcapi_1.JRPCAPI{constructor(core,baseURL="/ext/index/X/tx"){super(core,baseURL),this.getLastAccepted=(encoding="hex",baseURL=this.getBaseURL())=>__awaiter(this,void 0,void 0,(function*(){this.setBaseURL(baseURL);const params={encoding};try{return(yield this.callMethod("index.getLastAccepted",params)).data.result}catch(error){console.log(error)}})),this.getContainerByIndex=(index="0",encoding="hex",baseURL=this.getBaseURL())=>__awaiter(this,void 0,void 0,(function*(){this.setBaseURL(baseURL);const params={index,encoding};try{return(yield this.callMethod("index.getContainerByIndex",params)).data.result}catch(error){console.log(error)}})),this.getContainerByID=(id="0",encoding="hex",baseURL=this.getBaseURL())=>__awaiter(this,void 0,void 0,(function*(){this.setBaseURL(baseURL);const params={id,encoding};try{return(yield this.callMethod("index.getContainerByID",params)).data.result}catch(error){console.log(error)}})),this.getContainerRange=(startIndex=0,numToFetch=100,encoding="hex",baseURL=this.getBaseURL())=>__awaiter(this,void 0,void 0,(function*(){this.setBaseURL(baseURL);const params={startIndex,numToFetch,encoding};try{return(yield this.callMethod("index.getContainerRange",params)).data.result}catch(error){console.log(error)}})),this.getIndex=(id="",encoding="hex",baseURL=this.getBaseURL())=>__awaiter(this,void 0,void 0,(function*(){this.setBaseURL(baseURL);const params={id,encoding};try{return(yield this.callMethod("index.getIndex",params)).data.result.index}catch(error){console.log(error)}})),this.isAccepted=(id="",encoding="hex",baseURL=this.getBaseURL())=>__awaiter(this,void 0,void 0,(function*(){this.setBaseURL(baseURL);const params={id,encoding};try{return(yield this.callMethod("index.isAccepted",params)).data.result}catch(error){console.log(error)}}))}}exports.IndexAPI=IndexAPI},6119:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)"default"===p||Object.prototype.hasOwnProperty.call(exports,p)||__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:!0}),__exportStar(__webpack_require__(1229),exports)},8224:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))},__importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.InfoAPI=void 0;const jrpcapi_1=__webpack_require__(5912),bn_js_1=__importDefault(__webpack_require__(3550));class InfoAPI extends jrpcapi_1.JRPCAPI{constructor(core,baseURL="/ext/info"){super(core,baseURL),this.getBlockchainID=alias=>__awaiter(this,void 0,void 0,(function*(){const params={alias};return(yield this.callMethod("info.getBlockchainID",params)).data.result.blockchainID})),this.getNodeIP=()=>__awaiter(this,void 0,void 0,(function*(){return(yield this.callMethod("info.getBlockchainID")).data.result.ip})),this.getNetworkID=()=>__awaiter(this,void 0,void 0,(function*(){return(yield this.callMethod("info.getNetworkID")).data.result.networkID})),this.getNetworkName=()=>__awaiter(this,void 0,void 0,(function*(){return(yield this.callMethod("info.getNetworkName")).data.result.networkName})),this.getNodeID=()=>__awaiter(this,void 0,void 0,(function*(){return(yield this.callMethod("info.getNodeID")).data.result.nodeID})),this.getNodeVersion=()=>__awaiter(this,void 0,void 0,(function*(){return(yield this.callMethod("info.getNodeVersion")).data.result.version})),this.getTxFee=()=>__awaiter(this,void 0,void 0,(function*(){const response=yield this.callMethod("info.getTxFee");return{txFee:new bn_js_1.default(response.data.result.txFee,10),creationTxFee:new bn_js_1.default(response.data.result.creationTxFee,10)}})),this.isBootstrapped=chain=>__awaiter(this,void 0,void 0,(function*(){const params={chain};return(yield this.callMethod("info.isBootstrapped",params)).data.result.isBootstrapped})),this.peers=(nodeIDs=[])=>__awaiter(this,void 0,void 0,(function*(){const params={nodeIDs};return(yield this.callMethod("info.peers",params)).data.result.peers})),this.uptime=()=>__awaiter(this,void 0,void 0,(function*(){return(yield this.callMethod("info.uptime")).data.result}))}}exports.InfoAPI=InfoAPI},8379:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)"default"===p||Object.prototype.hasOwnProperty.call(exports,p)||__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:!0}),__exportStar(__webpack_require__(8224),exports)},7345:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.KeystoreAPI=void 0;const jrpcapi_1=__webpack_require__(5912);class KeystoreAPI extends jrpcapi_1.JRPCAPI{constructor(core,baseURL="/ext/keystore"){super(core,baseURL),this.createUser=(username,password)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password},response=yield this.callMethod("keystore.createUser",params);return response.data.result.success?response.data.result.success:response.data.result})),this.exportUser=(username,password)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password},response=yield this.callMethod("keystore.exportUser",params);return response.data.result.user?response.data.result.user:response.data.result})),this.importUser=(username,user,password)=>__awaiter(this,void 0,void 0,(function*(){const params={username,user,password},response=yield this.callMethod("keystore.importUser",params);return response.data.result.success?response.data.result.success:response.data.result})),this.listUsers=()=>__awaiter(this,void 0,void 0,(function*(){return(yield this.callMethod("keystore.listUsers")).data.result.users})),this.deleteUser=(username,password)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password},response=yield this.callMethod("keystore.deleteUser",params);return response.data.result.success?response.data.result.success:response.data.result}))}}exports.KeystoreAPI=KeystoreAPI},913:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)"default"===p||Object.prototype.hasOwnProperty.call(exports,p)||__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:!0}),__exportStar(__webpack_require__(7345),exports)},130:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.MetricsAPI=void 0;const restapi_1=__webpack_require__(5534);class MetricsAPI extends restapi_1.RESTAPI{constructor(core,baseURL="/ext/metrics"){super(core,baseURL),this.axConf=()=>({baseURL:`${this.core.getProtocol()}://${this.core.getHost()}:${this.core.getPort()}`,responseType:"text"}),this.getMetrics=()=>__awaiter(this,void 0,void 0,(function*(){return(yield this.post("")).data}))}}exports.MetricsAPI=MetricsAPI},6413:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)"default"===p||Object.prototype.hasOwnProperty.call(exports,p)||__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:!0}),__exportStar(__webpack_require__(130),exports)},1726:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.AddSubnetValidatorTx=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),constants_1=__webpack_require__(7080),credentials_1=__webpack_require__(5375),basetx_1=__webpack_require__(9660),constants_2=__webpack_require__(8779),serialization_1=__webpack_require__(555),_1=__webpack_require__(7679),utils_1=__webpack_require__(338),bintools=bintools_1.default.getInstance(),serialization=serialization_1.Serialization.getInstance();class AddSubnetValidatorTx extends basetx_1.BaseTx{constructor(networkID=constants_2.DefaultNetworkID,blockchainID=buffer_1.Buffer.alloc(32,16),outs,ins,memo,nodeID,startTime,endTime,weight,subnetID){super(networkID,blockchainID,outs,ins,memo),this._typeName="AddSubnetValidatorTx",this._typeID=constants_1.PlatformVMConstants.ADDSUBNETVALIDATORTX,this.nodeID=buffer_1.Buffer.alloc(20),this.startTime=buffer_1.Buffer.alloc(8),this.endTime=buffer_1.Buffer.alloc(8),this.weight=buffer_1.Buffer.alloc(8),this.subnetID=buffer_1.Buffer.alloc(32),this.sigCount=buffer_1.Buffer.alloc(4),this.sigIdxs=[],void 0!==subnetID&&(this.subnetID="string"==typeof subnetID?bintools.cb58Decode(subnetID):subnetID),void 0!==nodeID&&(this.nodeID=nodeID),void 0!==startTime&&(this.startTime=bintools.fromBNToBuffer(startTime,8)),void 0!==endTime&&(this.endTime=bintools.fromBNToBuffer(endTime,8)),void 0!==weight&&(this.weight=bintools.fromBNToBuffer(weight,8));const subnetAuth=new _1.SubnetAuth;this.subnetAuth=subnetAuth}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{subnetID:serialization.encoder(this.subnetID,encoding,"Buffer","cb58")})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.subnetID=serialization.decoder(fields.subnetID,encoding,"cb58","Buffer",32)}getTxType(){return constants_1.PlatformVMConstants.ADDSUBNETVALIDATORTX}getNodeID(){return this.nodeID}getNodeIDString(){return(0,utils_1.bufferToNodeIDString)(this.nodeID)}getStartTime(){return bintools.fromBufferToBN(this.startTime)}getEndTime(){return bintools.fromBufferToBN(this.endTime)}getWeight(){return bintools.fromBufferToBN(this.weight)}getSubnetID(){return bintools.cb58Encode(this.subnetID)}getSubnetAuth(){return this.subnetAuth}fromBuffer(bytes,offset=0){offset=super.fromBuffer(bytes,offset),this.nodeID=bintools.copyFrom(bytes,offset,offset+20),offset+=20,this.startTime=bintools.copyFrom(bytes,offset,offset+8),offset+=8,this.endTime=bintools.copyFrom(bytes,offset,offset+8),offset+=8,this.weight=bintools.copyFrom(bytes,offset,offset+8),offset+=8,this.subnetID=bintools.copyFrom(bytes,offset,offset+32),offset+=32;const sa=new _1.SubnetAuth;return offset+=sa.fromBuffer(bintools.copyFrom(bytes,offset)),this.subnetAuth=sa,offset}toBuffer(){const superbuff=super.toBuffer(),bsize=superbuff.length+this.nodeID.length+this.startTime.length+this.endTime.length+this.weight.length+this.subnetID.length+this.subnetAuth.toBuffer().length,barr=[superbuff,this.nodeID,this.startTime,this.endTime,this.weight,this.subnetID,this.subnetAuth.toBuffer()];return buffer_1.Buffer.concat(barr,bsize)}clone(){const newAddSubnetValidatorTx=new AddSubnetValidatorTx;return newAddSubnetValidatorTx.fromBuffer(this.toBuffer()),newAddSubnetValidatorTx}create(...args){return new AddSubnetValidatorTx(...args)}addSignatureIdx(addressIdx,address){const addressIndex=buffer_1.Buffer.alloc(4);addressIndex.writeUIntBE(addressIdx,0,4),this.subnetAuth.addAddressIndex(addressIndex);const sigidx=new credentials_1.SigIdx,b=buffer_1.Buffer.alloc(4);b.writeUInt32BE(addressIdx,0),sigidx.fromBuffer(b),sigidx.setSource(address),this.sigIdxs.push(sigidx),this.sigCount.writeUInt32BE(this.sigIdxs.length,0)}getSigIdxs(){return this.sigIdxs}getCredentialID(){return constants_1.PlatformVMConstants.SECPCREDENTIAL}sign(msg,kc){const creds=super.sign(msg,kc),sigidxs=this.getSigIdxs(),cred=(0,_1.SelectCredentialClass)(this.getCredentialID());for(let i=0;i{if(void 0===this.blockchainAlias){const netid=this.core.getNetworkID();return netid in constants_1.Defaults.network&&this.blockchainID in constants_1.Defaults.network[`${netid}`]?(this.blockchainAlias=constants_1.Defaults.network[`${netid}`][this.blockchainID].alias,this.blockchainAlias):void 0}return this.blockchainAlias},this.setBlockchainAlias=alias=>{this.blockchainAlias=alias},this.getBlockchainID=()=>this.blockchainID,this.refreshBlockchainID=blockchainID=>{const netid=this.core.getNetworkID();return void 0===blockchainID&&void 0!==constants_1.Defaults.network[`${netid}`]?(this.blockchainID=constants_1.PlatformChainID,!0):"string"==typeof blockchainID&&(this.blockchainID=blockchainID,!0)},this.parseAddress=addr=>{const alias=this.getBlockchainAlias(),blockchainID=this.getBlockchainID();return bintools.parseAddress(addr,blockchainID,alias,constants_2.PlatformVMConstants.ADDRESSLENGTH)},this.addressFromBuffer=address=>{const chainid=this.getBlockchainAlias()?this.getBlockchainAlias():this.getBlockchainID();return serialization.bufferToType(address,"bech32",this.core.getHRP(),chainid)},this.getAVAXAssetID=(refresh=!1)=>__awaiter(this,void 0,void 0,(function*(){if(void 0===this.AVAXAssetID||refresh){const assetID=yield this.getStakingAssetID();this.AVAXAssetID=bintools.cb58Decode(assetID)}return this.AVAXAssetID})),this.setAVAXAssetID=avaxAssetID=>{"string"==typeof avaxAssetID&&(avaxAssetID=bintools.cb58Decode(avaxAssetID)),this.AVAXAssetID=avaxAssetID},this.getDefaultTxFee=()=>this.core.getNetworkID()in constants_1.Defaults.network?new bn_js_1.default(constants_1.Defaults.network[this.core.getNetworkID()].P.txFee):new bn_js_1.default(0),this.getTxFee=()=>(void 0===this.txFee&&(this.txFee=this.getDefaultTxFee()),this.txFee),this.getCreateSubnetTxFee=()=>this.core.getNetworkID()in constants_1.Defaults.network?new bn_js_1.default(constants_1.Defaults.network[this.core.getNetworkID()].P.createSubnetTx):new bn_js_1.default(0),this.getCreateChainTxFee=()=>this.core.getNetworkID()in constants_1.Defaults.network?new bn_js_1.default(constants_1.Defaults.network[this.core.getNetworkID()].P.createChainTx):new bn_js_1.default(0),this.setTxFee=fee=>{this.txFee=fee},this.getDefaultCreationTxFee=()=>this.core.getNetworkID()in constants_1.Defaults.network?new bn_js_1.default(constants_1.Defaults.network[this.core.getNetworkID()].P.creationTxFee):new bn_js_1.default(0),this.getCreationTxFee=()=>(void 0===this.creationTxFee&&(this.creationTxFee=this.getDefaultCreationTxFee()),this.creationTxFee),this.setCreationTxFee=fee=>{this.creationTxFee=fee},this.keyChain=()=>this.keychain,this.newKeyChain=()=>{const alias=this.getBlockchainAlias();return this.keychain=alias?new keychain_1.KeyChain(this.core.getHRP(),alias):new keychain_1.KeyChain(this.core.getHRP(),this.blockchainID),this.keychain},this.checkGooseEgg=(utx,outTotal=new bn_js_1.default(0))=>__awaiter(this,void 0,void 0,(function*(){const avaxAssetID=yield this.getAVAXAssetID();let outputTotal=outTotal.gt(new bn_js_1.default(0))?outTotal:utx.getOutputTotal(avaxAssetID);const fee=utx.getBurn(avaxAssetID);return!(!fee.lte(constants_1.ONEAVAX.mul(new bn_js_1.default(10)))&&!fee.lte(outputTotal))})),this.getStakingAssetID=()=>__awaiter(this,void 0,void 0,(function*(){return(yield this.callMethod("platform.getStakingAssetID")).data.result.assetID})),this.createBlockchain=(username,password,subnetID,vmID,fxIDs,name,genesis)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password,fxIDs,vmID,name,genesisData:genesis};"string"==typeof subnetID?params.subnetID=subnetID:void 0!==subnetID&&(params.subnetID=bintools.cb58Encode(subnetID));return(yield this.callMethod("platform.createBlockchain",params)).data.result.txID})),this.getBlockchainStatus=blockchainID=>__awaiter(this,void 0,void 0,(function*(){const params={blockchainID};return(yield this.callMethod("platform.getBlockchainStatus",params)).data.result.status})),this.getValidatorsAt=(height,subnetID)=>__awaiter(this,void 0,void 0,(function*(){const params={height};void 0!==subnetID&&(params.subnetID=subnetID);return(yield this.callMethod("platform.getValidatorsAt",params)).data.result})),this.createAddress=(username,password)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password};return(yield this.callMethod("platform.createAddress",params)).data.result.address})),this.getBalance=address=>__awaiter(this,void 0,void 0,(function*(){if(void 0===this.parseAddress(address))throw new errors_1.AddressError("Error - PlatformVMAPI.getBalance: Invalid address format");const params={address};return(yield this.callMethod("platform.getBalance",params)).data.result})),this.listAddresses=(username,password)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password};return(yield this.callMethod("platform.listAddresses",params)).data.result.addresses})),this.getCurrentValidators=(subnetID,nodeIDs)=>__awaiter(this,void 0,void 0,(function*(){const params={};"string"==typeof subnetID?params.subnetID=subnetID:void 0!==subnetID&&(params.subnetID=bintools.cb58Encode(subnetID)),void 0!==nodeIDs&&nodeIDs.length>0&&(params.nodeIDs=nodeIDs);return(yield this.callMethod("platform.getCurrentValidators",params)).data.result})),this.getPendingValidators=(subnetID,nodeIDs)=>__awaiter(this,void 0,void 0,(function*(){const params={};"string"==typeof subnetID?params.subnetID=subnetID:void 0!==subnetID&&(params.subnetID=bintools.cb58Encode(subnetID)),void 0!==nodeIDs&&nodeIDs.length>0&&(params.nodeIDs=nodeIDs);return(yield this.callMethod("platform.getPendingValidators",params)).data.result})),this.sampleValidators=(sampleSize,subnetID)=>__awaiter(this,void 0,void 0,(function*(){const params={size:sampleSize.toString()};"string"==typeof subnetID?params.subnetID=subnetID:void 0!==subnetID&&(params.subnetID=bintools.cb58Encode(subnetID));return(yield this.callMethod("platform.sampleValidators",params)).data.result.validators})),this.addValidator=(username,password,nodeID,startTime,endTime,stakeAmount,rewardAddress,delegationFeeRate)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password,nodeID,startTime:startTime.getTime()/1e3,endTime:endTime.getTime()/1e3,stakeAmount:stakeAmount.toString(10),rewardAddress};void 0!==delegationFeeRate&&(params.delegationFeeRate=delegationFeeRate.toString(10));return(yield this.callMethod("platform.addValidator",params)).data.result.txID})),this.addSubnetValidator=(username,password,nodeID,subnetID,startTime,endTime,weight)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password,nodeID,startTime:startTime.getTime()/1e3,endTime:endTime.getTime()/1e3,weight};"string"==typeof subnetID?params.subnetID=subnetID:void 0!==subnetID&&(params.subnetID=bintools.cb58Encode(subnetID));return(yield this.callMethod("platform.addSubnetValidator",params)).data.result.txID})),this.addDelegator=(username,password,nodeID,startTime,endTime,stakeAmount,rewardAddress)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password,nodeID,startTime:startTime.getTime()/1e3,endTime:endTime.getTime()/1e3,stakeAmount:stakeAmount.toString(10),rewardAddress};return(yield this.callMethod("platform.addDelegator",params)).data.result.txID})),this.createSubnet=(username,password,controlKeys,threshold)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password,controlKeys,threshold},response=yield this.callMethod("platform.createSubnet",params);return response.data.result.txID?response.data.result.txID:response.data.result})),this.validatedBy=blockchainID=>__awaiter(this,void 0,void 0,(function*(){const params={blockchainID};return(yield this.callMethod("platform.validatedBy",params)).data.result.subnetID})),this.validates=subnetID=>__awaiter(this,void 0,void 0,(function*(){const params={subnetID};"string"==typeof subnetID?params.subnetID=subnetID:void 0!==subnetID&&(params.subnetID=bintools.cb58Encode(subnetID));return(yield this.callMethod("platform.validates",params)).data.result.blockchainIDs})),this.getBlockchains=()=>__awaiter(this,void 0,void 0,(function*(){return(yield this.callMethod("platform.getBlockchains")).data.result.blockchains})),this.exportAVAX=(username,password,amount,to)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password,to,amount:amount.toString(10)},response=yield this.callMethod("platform.exportAVAX",params);return response.data.result.txID?response.data.result.txID:response.data.result})),this.importAVAX=(username,password,to,sourceChain)=>__awaiter(this,void 0,void 0,(function*(){const params={to,sourceChain,username,password},response=yield this.callMethod("platform.importAVAX",params);return response.data.result.txID?response.data.result.txID:response.data.result})),this.issueTx=tx=>__awaiter(this,void 0,void 0,(function*(){let Transaction="";if("string"==typeof tx)Transaction=tx;else if(tx instanceof buffer_1.Buffer){const txobj=new tx_1.Tx;txobj.fromBuffer(tx),Transaction=txobj.toStringHex()}else{if(!(tx instanceof tx_1.Tx))throw new errors_1.TransactionError("Error - platform.issueTx: provided tx is not expected type of string, Buffer, or Tx");Transaction=tx.toStringHex()}const params={tx:Transaction.toString(),encoding:"hex"};return(yield this.callMethod("platform.issueTx",params)).data.result.txID})),this.getCurrentSupply=()=>__awaiter(this,void 0,void 0,(function*(){const response=yield this.callMethod("platform.getCurrentSupply");return new bn_js_1.default(response.data.result.supply,10)})),this.getHeight=()=>__awaiter(this,void 0,void 0,(function*(){const response=yield this.callMethod("platform.getHeight");return new bn_js_1.default(response.data.result.height,10)})),this.getMinStake=(refresh=!1)=>__awaiter(this,void 0,void 0,(function*(){if(!0!==refresh&&void 0!==this.minValidatorStake&&void 0!==this.minDelegatorStake)return{minValidatorStake:this.minValidatorStake,minDelegatorStake:this.minDelegatorStake};const response=yield this.callMethod("platform.getMinStake");return this.minValidatorStake=new bn_js_1.default(response.data.result.minValidatorStake,10),this.minDelegatorStake=new bn_js_1.default(response.data.result.minDelegatorStake,10),{minValidatorStake:this.minValidatorStake,minDelegatorStake:this.minDelegatorStake}})),this.getTotalStake=()=>__awaiter(this,void 0,void 0,(function*(){const response=yield this.callMethod("platform.getTotalStake");return new bn_js_1.default(response.data.result.stake,10)})),this.getMaxStakeAmount=(subnetID,nodeID,startTime,endTime)=>__awaiter(this,void 0,void 0,(function*(){const now=(0,helperfunctions_1.UnixNow)();if(startTime.gt(now)||endTime.lte(startTime))throw new errors_1.TimeError("PlatformVMAPI.getMaxStakeAmount -- startTime must be in the past and endTime must come after startTime");const params={nodeID,startTime,endTime};"string"==typeof subnetID?params.subnetID=subnetID:void 0!==subnetID&&(params.subnetID=bintools.cb58Encode(subnetID));const response=yield this.callMethod("platform.getMaxStakeAmount",params);return new bn_js_1.default(response.data.result.amount,10)})),this.setMinStake=(minValidatorStake,minDelegatorStake)=>{void 0!==minValidatorStake&&(this.minValidatorStake=minValidatorStake),void 0!==minDelegatorStake&&(this.minDelegatorStake=minDelegatorStake)},this.getStake=(addresses,encoding="hex")=>__awaiter(this,void 0,void 0,(function*(){const params={addresses,encoding},response=yield this.callMethod("platform.getStake",params);return{staked:new bn_js_1.default(response.data.result.staked,10),stakedOutputs:response.data.result.stakedOutputs.map((stakedOutput=>{const transferableOutput=new outputs_1.TransferableOutput;let buf;return buf="cb58"===encoding?bintools.cb58Decode(stakedOutput):buffer_1.Buffer.from(stakedOutput.replace(/0x/g,""),"hex"),transferableOutput.fromBuffer(buf,2),transferableOutput}))}})),this.getSubnets=ids=>__awaiter(this,void 0,void 0,(function*(){const params={};void 0!==typeof ids&&(params.ids=ids);return(yield this.callMethod("platform.getSubnets",params)).data.result.subnets})),this.exportKey=(username,password,address)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password,address},response=yield this.callMethod("platform.exportKey",params);return response.data.result.privateKey?response.data.result.privateKey:response.data.result})),this.importKey=(username,password,privateKey)=>__awaiter(this,void 0,void 0,(function*(){const params={username,password,privateKey},response=yield this.callMethod("platform.importKey",params);return response.data.result.address?response.data.result.address:response.data.result})),this.getTx=(txID,encoding="hex")=>__awaiter(this,void 0,void 0,(function*(){const params={txID,encoding},response=yield this.callMethod("platform.getTx",params);return response.data.result.tx?response.data.result.tx:response.data.result})),this.getTxStatus=(txid,includeReason=!0)=>__awaiter(this,void 0,void 0,(function*(){const params={txID:txid,includeReason};return(yield this.callMethod("platform.getTxStatus",params)).data.result})),this.getUTXOs=(addresses,sourceChain,limit=0,startIndex,persistOpts,encoding="hex")=>__awaiter(this,void 0,void 0,(function*(){"string"==typeof addresses&&(addresses=[addresses]);const params={addresses,limit,encoding};void 0!==startIndex&&startIndex&&(params.startIndex=startIndex),void 0!==sourceChain&&(params.sourceChain=sourceChain);const response=yield this.callMethod("platform.getUTXOs",params),utxos=new utxos_1.UTXOSet;let data=response.data.result.utxos;if(persistOpts&&"object"==typeof persistOpts){if(this.db.has(persistOpts.getName())){const selfArray=this.db.get(persistOpts.getName());if(Array.isArray(selfArray)){utxos.addArray(data);const self=new utxos_1.UTXOSet;self.addArray(selfArray),self.mergeByRule(utxos,persistOpts.getMergeRule()),data=self.getAllUTXOStrings()}}this.db.set(persistOpts.getName(),data,persistOpts.getOverwrite())}if(data.length>0&&"0x"===data[0].substring(0,2)){const cb58Strs=[];data.forEach((str=>{cb58Strs.push(bintools.cb58Encode(new buffer_1.Buffer(str.slice(2),"hex")))})),utxos.addArray(cb58Strs,!1)}else utxos.addArray(data,!1);return response.data.result.utxos=utxos,response.data.result.numFetched=parseInt(response.data.result.numFetched),response.data.result})),this.buildImportTx=(utxoset,ownerAddresses,sourceChain,toAddresses,fromAddresses,changeAddresses,memo,asOf=(0,helperfunctions_1.UnixNow)(),locktime=new bn_js_1.default(0),threshold=1)=>__awaiter(this,void 0,void 0,(function*(){const to=this._cleanAddressArray(toAddresses,"buildImportTx").map((a=>bintools.stringToAddress(a))),from=this._cleanAddressArray(fromAddresses,"buildImportTx").map((a=>bintools.stringToAddress(a))),change=this._cleanAddressArray(changeAddresses,"buildImportTx").map((a=>bintools.stringToAddress(a)));let srcChain;if(void 0===sourceChain)throw new errors_1.ChainIdError("Error - PlatformVMAPI.buildImportTx: Source ChainID is undefined.");if("string"==typeof sourceChain)srcChain=sourceChain,sourceChain=bintools.cb58Decode(sourceChain);else if(!(sourceChain instanceof buffer_1.Buffer))throw new errors_1.ChainIdError("Error - PlatformVMAPI.buildImportTx: Invalid destinationChain type: "+typeof sourceChain);const atomicUTXOs=yield(yield this.getUTXOs(ownerAddresses,srcChain,0,void 0)).utxos,avaxAssetID=yield this.getAVAXAssetID();memo instanceof payload_1.PayloadBase&&(memo=memo.getPayload());const atomics=atomicUTXOs.getAllUTXOs(),builtUnsignedTx=utxoset.buildImportTx(this.core.getNetworkID(),bintools.cb58Decode(this.blockchainID),to,from,change,atomics,sourceChain,this.getTxFee(),avaxAssetID,memo,asOf,locktime,threshold);if(!(yield this.checkGooseEgg(builtUnsignedTx)))throw new errors_1.GooseEggCheckError("Failed Goose Egg Check");return builtUnsignedTx})),this.buildExportTx=(utxoset,amount,destinationChain,toAddresses,fromAddresses,changeAddresses,memo,asOf=(0,helperfunctions_1.UnixNow)(),locktime=new bn_js_1.default(0),threshold=1)=>__awaiter(this,void 0,void 0,(function*(){let prefixes={};if(toAddresses.map((a=>{prefixes[a.split("-")[0]]=!0})),1!==Object.keys(prefixes).length)throw new errors_1.AddressError("Error - PlatformVMAPI.buildExportTx: To addresses must have the same chainID prefix.");if(void 0===destinationChain)throw new errors_1.ChainIdError("Error - PlatformVMAPI.buildExportTx: Destination ChainID is undefined.");if("string"==typeof destinationChain)destinationChain=bintools.cb58Decode(destinationChain);else if(!(destinationChain instanceof buffer_1.Buffer))throw new errors_1.ChainIdError("Error - PlatformVMAPI.buildExportTx: Invalid destinationChain type: "+typeof destinationChain);if(32!==destinationChain.length)throw new errors_1.ChainIdError("Error - PlatformVMAPI.buildExportTx: Destination ChainID must be 32 bytes in length.");let to=[];toAddresses.map((a=>{to.push(bintools.stringToAddress(a))}));const from=this._cleanAddressArray(fromAddresses,"buildExportTx").map((a=>bintools.stringToAddress(a))),change=this._cleanAddressArray(changeAddresses,"buildExportTx").map((a=>bintools.stringToAddress(a)));memo instanceof payload_1.PayloadBase&&(memo=memo.getPayload());const avaxAssetID=yield this.getAVAXAssetID(),builtUnsignedTx=utxoset.buildExportTx(this.core.getNetworkID(),bintools.cb58Decode(this.blockchainID),amount,avaxAssetID,to,from,change,destinationChain,this.getTxFee(),avaxAssetID,memo,asOf,locktime,threshold);if(!(yield this.checkGooseEgg(builtUnsignedTx)))throw new errors_1.GooseEggCheckError("Failed Goose Egg Check");return builtUnsignedTx})),this.buildAddSubnetValidatorTx=(utxoset,fromAddresses,changeAddresses,nodeID,startTime,endTime,weight,subnetID,memo,asOf=(0,helperfunctions_1.UnixNow)(),subnetAuthCredentials=[])=>__awaiter(this,void 0,void 0,(function*(){const from=this._cleanAddressArray(fromAddresses,"buildAddSubnetValidatorTx").map((a=>bintools.stringToAddress(a))),change=this._cleanAddressArray(changeAddresses,"buildAddSubnetValidatorTx").map((a=>bintools.stringToAddress(a)));memo instanceof payload_1.PayloadBase&&(memo=memo.getPayload());const avaxAssetID=yield this.getAVAXAssetID(),now=(0,helperfunctions_1.UnixNow)();if(startTime.lt(now)||endTime.lte(startTime))throw new Error("PlatformVMAPI.buildAddSubnetValidatorTx -- startTime must be in the future and endTime must come after startTime");const builtUnsignedTx=utxoset.buildAddSubnetValidatorTx(this.core.getNetworkID(),bintools.cb58Decode(this.blockchainID),from,change,(0,helperfunctions_1.NodeIDStringToBuffer)(nodeID),startTime,endTime,weight,subnetID,this.getDefaultTxFee(),avaxAssetID,memo,asOf,subnetAuthCredentials);if(!(yield this.checkGooseEgg(builtUnsignedTx)))throw new Error("Failed Goose Egg Check");return builtUnsignedTx})),this.buildAddDelegatorTx=(utxoset,toAddresses,fromAddresses,changeAddresses,nodeID,startTime,endTime,stakeAmount,rewardAddresses,rewardLocktime=new bn_js_1.default(0),rewardThreshold=1,memo,asOf=(0,helperfunctions_1.UnixNow)())=>__awaiter(this,void 0,void 0,(function*(){const to=this._cleanAddressArray(toAddresses,"buildAddDelegatorTx").map((a=>bintools.stringToAddress(a))),from=this._cleanAddressArray(fromAddresses,"buildAddDelegatorTx").map((a=>bintools.stringToAddress(a))),change=this._cleanAddressArray(changeAddresses,"buildAddDelegatorTx").map((a=>bintools.stringToAddress(a))),rewards=this._cleanAddressArray(rewardAddresses,"buildAddDelegatorTx").map((a=>bintools.stringToAddress(a)));memo instanceof payload_1.PayloadBase&&(memo=memo.getPayload());const minStake=(yield this.getMinStake()).minDelegatorStake;if(stakeAmount.lt(minStake))throw new errors_1.StakeError("PlatformVMAPI.buildAddDelegatorTx -- stake amount must be at least "+minStake.toString(10));const avaxAssetID=yield this.getAVAXAssetID(),now=(0,helperfunctions_1.UnixNow)();if(startTime.lt(now)||endTime.lte(startTime))throw new errors_1.TimeError("PlatformVMAPI.buildAddDelegatorTx -- startTime must be in the future and endTime must come after startTime");const builtUnsignedTx=utxoset.buildAddDelegatorTx(this.core.getNetworkID(),bintools.cb58Decode(this.blockchainID),avaxAssetID,to,from,change,(0,helperfunctions_1.NodeIDStringToBuffer)(nodeID),startTime,endTime,stakeAmount,rewardLocktime,rewardThreshold,rewards,new bn_js_1.default(0),avaxAssetID,memo,asOf);if(!(yield this.checkGooseEgg(builtUnsignedTx)))throw new errors_1.GooseEggCheckError("Failed Goose Egg Check");return builtUnsignedTx})),this.buildAddValidatorTx=(utxoset,toAddresses,fromAddresses,changeAddresses,nodeID,startTime,endTime,stakeAmount,rewardAddresses,delegationFee,rewardLocktime=new bn_js_1.default(0),rewardThreshold=1,memo,asOf=(0,helperfunctions_1.UnixNow)())=>__awaiter(this,void 0,void 0,(function*(){const to=this._cleanAddressArray(toAddresses,"buildAddValidatorTx").map((a=>bintools.stringToAddress(a))),from=this._cleanAddressArray(fromAddresses,"buildAddValidatorTx").map((a=>bintools.stringToAddress(a))),change=this._cleanAddressArray(changeAddresses,"buildAddValidatorTx").map((a=>bintools.stringToAddress(a))),rewards=this._cleanAddressArray(rewardAddresses,"buildAddValidatorTx").map((a=>bintools.stringToAddress(a)));memo instanceof payload_1.PayloadBase&&(memo=memo.getPayload());const minStake=(yield this.getMinStake()).minValidatorStake;if(stakeAmount.lt(minStake))throw new errors_1.StakeError("PlatformVMAPI.buildAddValidatorTx -- stake amount must be at least "+minStake.toString(10));if("number"!=typeof delegationFee||delegationFee>100||delegationFee<0)throw new errors_1.DelegationFeeError("PlatformVMAPI.buildAddValidatorTx -- delegationFee must be a number between 0 and 100");const avaxAssetID=yield this.getAVAXAssetID(),now=(0,helperfunctions_1.UnixNow)();if(startTime.lt(now)||endTime.lte(startTime))throw new errors_1.TimeError("PlatformVMAPI.buildAddValidatorTx -- startTime must be in the future and endTime must come after startTime");const builtUnsignedTx=utxoset.buildAddValidatorTx(this.core.getNetworkID(),bintools.cb58Decode(this.blockchainID),avaxAssetID,to,from,change,(0,helperfunctions_1.NodeIDStringToBuffer)(nodeID),startTime,endTime,stakeAmount,rewardLocktime,rewardThreshold,rewards,delegationFee,new bn_js_1.default(0),avaxAssetID,memo,asOf);if(!(yield this.checkGooseEgg(builtUnsignedTx)))throw new errors_1.GooseEggCheckError("Failed Goose Egg Check");return builtUnsignedTx})),this.buildCreateSubnetTx=(utxoset,fromAddresses,changeAddresses,subnetOwnerAddresses,subnetOwnerThreshold,memo,asOf=(0,helperfunctions_1.UnixNow)())=>__awaiter(this,void 0,void 0,(function*(){const from=this._cleanAddressArray(fromAddresses,"buildCreateSubnetTx").map((a=>bintools.stringToAddress(a))),change=this._cleanAddressArray(changeAddresses,"buildCreateSubnetTx").map((a=>bintools.stringToAddress(a))),owners=this._cleanAddressArray(subnetOwnerAddresses,"buildCreateSubnetTx").map((a=>bintools.stringToAddress(a)));memo instanceof payload_1.PayloadBase&&(memo=memo.getPayload());const avaxAssetID=yield this.getAVAXAssetID(),networkID=this.core.getNetworkID(),blockchainID=bintools.cb58Decode(this.blockchainID),fee=this.getCreateSubnetTxFee(),builtUnsignedTx=utxoset.buildCreateSubnetTx(networkID,blockchainID,from,change,owners,subnetOwnerThreshold,fee,avaxAssetID,memo,asOf);if(!(yield this.checkGooseEgg(builtUnsignedTx,this.getCreationTxFee())))throw new errors_1.GooseEggCheckError("Failed Goose Egg Check");return builtUnsignedTx})),this.buildCreateChainTx=(utxoset,fromAddresses,changeAddresses,subnetID,chainName,vmID,fxIDs,genesisData,memo,asOf=(0,helperfunctions_1.UnixNow)(),subnetAuthCredentials=[])=>__awaiter(this,void 0,void 0,(function*(){const from=this._cleanAddressArray(fromAddresses,"buildCreateChainTx").map((a=>bintools.stringToAddress(a))),change=this._cleanAddressArray(changeAddresses,"buildCreateChainTx").map((a=>bintools.stringToAddress(a)));memo instanceof payload_1.PayloadBase&&(memo=memo.getPayload());const avaxAssetID=yield this.getAVAXAssetID();fxIDs=fxIDs.sort();const networkID=this.core.getNetworkID(),blockchainID=bintools.cb58Decode(this.blockchainID),fee=this.getCreateChainTxFee(),builtUnsignedTx=utxoset.buildCreateChainTx(networkID,blockchainID,from,change,subnetID,chainName,vmID,fxIDs,genesisData,fee,avaxAssetID,memo,asOf,subnetAuthCredentials);if(!(yield this.checkGooseEgg(builtUnsignedTx,this.getCreationTxFee())))throw new errors_1.GooseEggCheckError("Failed Goose Egg Check");return builtUnsignedTx})),this.getTimestamp=()=>__awaiter(this,void 0,void 0,(function*(){return(yield this.callMethod("platform.getTimestamp")).data.result.timestamp})),this.getRewardUTXOs=(txID,encoding)=>__awaiter(this,void 0,void 0,(function*(){const params={txID,encoding};return(yield this.callMethod("platform.getRewardUTXOs",params)).data.result})),this.blockchainID=constants_1.PlatformChainID;const netID=core.getNetworkID();if(netID in constants_1.Defaults.network&&this.blockchainID in constants_1.Defaults.network[`${netID}`]){const alias=constants_1.Defaults.network[`${netID}`][this.blockchainID].alias;this.keychain=new keychain_1.KeyChain(this.core.getHRP(),alias)}else this.keychain=new keychain_1.KeyChain(this.core.getHRP(),this.blockchainID)}_cleanAddressArray(addresses,caller){const addrs=[],chainid=this.getBlockchainAlias()?this.getBlockchainAlias():this.getBlockchainID();if(addresses&&addresses.length>0)for(let i=0;i{let newOut=new outputs_1.TransferableOutput;return newOut.deserialize(o,encoding),newOut})),this.ins=fields.ins.map((i=>{let newIn=new inputs_1.TransferableInput;return newIn.deserialize(i,encoding),newIn})),this.numouts=buffer_1.Buffer.alloc(4),this.numouts.writeUInt32BE(this.outs.length,0),this.numins=buffer_1.Buffer.alloc(4),this.numins.writeUInt32BE(this.ins.length,0)}getOuts(){return this.outs}getIns(){return this.ins}getTotalOuts(){return this.getOuts()}getTxType(){return constants_1.PlatformVMConstants.BASETX}fromBuffer(bytes,offset=0){this.networkID=bintools.copyFrom(bytes,offset,offset+4),offset+=4,this.blockchainID=bintools.copyFrom(bytes,offset,offset+32),offset+=32,this.numouts=bintools.copyFrom(bytes,offset,offset+4),offset+=4;const outcount=this.numouts.readUInt32BE(0);this.outs=[];for(let i=0;i{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PlatformVMConstants=void 0;class PlatformVMConstants{}exports.PlatformVMConstants=PlatformVMConstants,PlatformVMConstants.LATESTCODEC=0,PlatformVMConstants.SECPFXID=0,PlatformVMConstants.SECPXFEROUTPUTID=7,PlatformVMConstants.SUBNETAUTHID=10,PlatformVMConstants.SECPOWNEROUTPUTID=11,PlatformVMConstants.STAKEABLELOCKOUTID=22,PlatformVMConstants.SECPINPUTID=5,PlatformVMConstants.STAKEABLELOCKINID=21,PlatformVMConstants.LOCKEDSTAKEABLES=[PlatformVMConstants.STAKEABLELOCKINID,PlatformVMConstants.STAKEABLELOCKOUTID],PlatformVMConstants.BASETX=0,PlatformVMConstants.SUBNETAUTH=10,PlatformVMConstants.ADDVALIDATORTX=12,PlatformVMConstants.ADDSUBNETVALIDATORTX=13,PlatformVMConstants.ADDDELEGATORTX=14,PlatformVMConstants.CREATECHAINTX=15,PlatformVMConstants.CREATESUBNETTX=16,PlatformVMConstants.IMPORTTX=17,PlatformVMConstants.EXPORTTX=18,PlatformVMConstants.ADVANCETIMETX=19,PlatformVMConstants.REWARDVALIDATORTX=20,PlatformVMConstants.SECPCREDENTIAL=9,PlatformVMConstants.ASSETIDLEN=32,PlatformVMConstants.BLOCKCHAINIDLEN=32,PlatformVMConstants.SYMBOLMAXLEN=4,PlatformVMConstants.ASSETNAMELEN=128,PlatformVMConstants.ADDRESSLENGTH=20},9115:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.CreateChainTx=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),constants_1=__webpack_require__(7080),credentials_1=__webpack_require__(5375),basetx_1=__webpack_require__(9660),constants_2=__webpack_require__(8779),serialization_1=__webpack_require__(555),_1=__webpack_require__(7679),bintools=bintools_1.default.getInstance(),serialization=serialization_1.Serialization.getInstance();class CreateChainTx extends basetx_1.BaseTx{constructor(networkID=constants_2.DefaultNetworkID,blockchainID=buffer_1.Buffer.alloc(32,16),outs,ins,memo,subnetID,chainName,vmID,fxIDs,genesisData){if(super(networkID,blockchainID,outs,ins,memo),this._typeName="CreateChainTx",this._typeID=constants_1.PlatformVMConstants.CREATECHAINTX,this.subnetID=buffer_1.Buffer.alloc(32),this.chainName="",this.vmID=buffer_1.Buffer.alloc(32),this.numFXIDs=buffer_1.Buffer.alloc(4),this.fxIDs=[],this.genesisData=buffer_1.Buffer.alloc(32),this.sigCount=buffer_1.Buffer.alloc(4),this.sigIdxs=[],void 0!==subnetID&&(this.subnetID="string"==typeof subnetID?bintools.cb58Decode(subnetID):subnetID),void 0!==chainName&&(this.chainName=chainName),void 0!==vmID){const buf=buffer_1.Buffer.alloc(32);buf.write(vmID,0,vmID.length),this.vmID=buf}if(void 0!==fxIDs){this.numFXIDs.writeUInt32BE(fxIDs.length,0);const fxIDBufs=[];fxIDs.forEach((fxID=>{const buf=buffer_1.Buffer.alloc(32);buf.write(fxID,0,fxID.length,"utf8"),fxIDBufs.push(buf)})),this.fxIDs=fxIDBufs}void 0!==genesisData&&"string"!=typeof genesisData?this.genesisData=genesisData.toBuffer():"string"==typeof genesisData&&(this.genesisData=buffer_1.Buffer.from(genesisData));const subnetAuth=new _1.SubnetAuth;this.subnetAuth=subnetAuth}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{subnetID:serialization.encoder(this.subnetID,encoding,"Buffer","cb58")})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.subnetID=serialization.decoder(fields.subnetID,encoding,"cb58","Buffer",32)}getTxType(){return constants_1.PlatformVMConstants.CREATECHAINTX}getSubnetAuth(){return this.subnetAuth}getSubnetID(){return bintools.cb58Encode(this.subnetID)}getChainName(){return this.chainName}getVMID(){return this.vmID}getFXIDs(){return this.fxIDs}getGenesisData(){return bintools.cb58Encode(this.genesisData)}fromBuffer(bytes,offset=0){offset=super.fromBuffer(bytes,offset),this.subnetID=bintools.copyFrom(bytes,offset,offset+32),offset+=32;const chainNameSize=bintools.copyFrom(bytes,offset,offset+2).readUInt16BE(0);offset+=2,this.chainName=bintools.copyFrom(bytes,offset,offset+chainNameSize).toString("utf8"),offset+=chainNameSize,this.vmID=bintools.copyFrom(bytes,offset,offset+32),offset+=32,this.numFXIDs=bintools.copyFrom(bytes,offset,offset+4),offset+=4;const nfxids=parseInt(this.numFXIDs.toString("hex"),10);for(let i=0;i{bsize+=fxID.length,barr.push(fxID)})),bsize+=4,bsize+=this.genesisData.length;const gdLength=buffer_1.Buffer.alloc(4);return gdLength.writeUIntBE(this.genesisData.length,0,4),barr.push(gdLength),barr.push(this.genesisData),bsize+=this.subnetAuth.toBuffer().length,barr.push(this.subnetAuth.toBuffer()),buffer_1.Buffer.concat(barr,bsize)}clone(){const newCreateChainTx=new CreateChainTx;return newCreateChainTx.fromBuffer(this.toBuffer()),newCreateChainTx}create(...args){return new CreateChainTx(...args)}addSignatureIdx(addressIdx,address){const addressIndex=buffer_1.Buffer.alloc(4);addressIndex.writeUIntBE(addressIdx,0,4),this.subnetAuth.addAddressIndex(addressIndex);const sigidx=new credentials_1.SigIdx,b=buffer_1.Buffer.alloc(4);b.writeUInt32BE(addressIdx,0),sigidx.fromBuffer(b),sigidx.setSource(address),this.sigIdxs.push(sigidx),this.sigCount.writeUInt32BE(this.sigIdxs.length,0)}getSigIdxs(){return this.sigIdxs}getCredentialID(){return constants_1.PlatformVMConstants.SECPCREDENTIAL}sign(msg,kc){const creds=super.sign(msg,kc),sigidxs=this.getSigIdxs(),cred=(0,_1.SelectCredentialClass)(this.getCredentialID());for(let i=0;i{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CreateSubnetTx=void 0;const buffer_1=__webpack_require__(8764),basetx_1=__webpack_require__(9660),constants_1=__webpack_require__(7080),constants_2=__webpack_require__(8779),outputs_1=__webpack_require__(5168),errors_1=__webpack_require__(611);class CreateSubnetTx extends basetx_1.BaseTx{constructor(networkID=constants_2.DefaultNetworkID,blockchainID=buffer_1.Buffer.alloc(32,16),outs,ins,memo,subnetOwners){super(networkID,blockchainID,outs,ins,memo),this._typeName="CreateSubnetTx",this._typeID=constants_1.PlatformVMConstants.CREATESUBNETTX,this.subnetOwners=void 0,this.subnetOwners=subnetOwners}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{subnetOwners:this.subnetOwners.serialize(encoding)})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.subnetOwners=new outputs_1.SECPOwnerOutput,this.subnetOwners.deserialize(fields.subnetOwners,encoding)}getTxType(){return this._typeID}getSubnetOwners(){return this.subnetOwners}fromBuffer(bytes,offset=0){return offset=super.fromBuffer(bytes,offset),offset+=4,this.subnetOwners=new outputs_1.SECPOwnerOutput,offset=this.subnetOwners.fromBuffer(bytes,offset)}toBuffer(){if(void 0===this.subnetOwners||!(this.subnetOwners instanceof outputs_1.SECPOwnerOutput))throw new errors_1.SubnetOwnerError("CreateSubnetTx.toBuffer -- this.subnetOwners is not a SECPOwnerOutput");let typeID=buffer_1.Buffer.alloc(4);typeID.writeUInt32BE(this.subnetOwners.getOutputID(),0);let barr=[super.toBuffer(),typeID,this.subnetOwners.toBuffer()];return buffer_1.Buffer.concat(barr)}}exports.CreateSubnetTx=CreateSubnetTx},6525:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SECPCredential=exports.SelectCredentialClass=void 0;const constants_1=__webpack_require__(7080),credentials_1=__webpack_require__(5375),errors_1=__webpack_require__(611);exports.SelectCredentialClass=(credid,...args)=>{if(credid===constants_1.PlatformVMConstants.SECPCREDENTIAL)return new SECPCredential(...args);throw new errors_1.CredIdError("Error - SelectCredentialClass: unknown credid")};class SECPCredential extends credentials_1.Credential{constructor(){super(...arguments),this._typeName="SECPCredential",this._typeID=constants_1.PlatformVMConstants.SECPCREDENTIAL}getCredentialID(){return this._typeID}clone(){let newbase=new SECPCredential;return newbase.fromBuffer(this.toBuffer()),newbase}create(...args){return new SECPCredential(...args)}select(id,...args){return(0,exports.SelectCredentialClass)(id,...args)}}exports.SECPCredential=SECPCredential},5619:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.ExportTx=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),constants_1=__webpack_require__(7080),outputs_1=__webpack_require__(5168),basetx_1=__webpack_require__(9660),constants_2=__webpack_require__(8779),bn_js_1=__importDefault(__webpack_require__(3550)),serialization_1=__webpack_require__(555),errors_1=__webpack_require__(611),bintools=bintools_1.default.getInstance(),serialization=serialization_1.Serialization.getInstance();class ExportTx extends basetx_1.BaseTx{constructor(networkID=constants_2.DefaultNetworkID,blockchainID=buffer_1.Buffer.alloc(32,16),outs,ins,memo,destinationChain,exportOuts){if(super(networkID,blockchainID,outs,ins,memo),this._typeName="ExportTx",this._typeID=constants_1.PlatformVMConstants.EXPORTTX,this.destinationChain=buffer_1.Buffer.alloc(32),this.numOuts=buffer_1.Buffer.alloc(4),this.exportOuts=[],this.destinationChain=destinationChain,void 0!==exportOuts&&Array.isArray(exportOuts)){for(let i=0;ie.serialize(encoding)))})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.destinationChain=serialization.decoder(fields.destinationChain,encoding,"cb58","Buffer",32),this.exportOuts=fields.exportOuts.map((e=>{let eo=new outputs_1.TransferableOutput;return eo.deserialize(e,encoding),eo})),this.numOuts=buffer_1.Buffer.alloc(4),this.numOuts.writeUInt32BE(this.exportOuts.length,0)}getTxType(){return constants_1.PlatformVMConstants.EXPORTTX}getExportOutputs(){return this.exportOuts}getExportTotal(){let val=new bn_js_1.default(0);for(let i=0;ii.serialize(encoding)))})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.sourceChain=serialization.decoder(fields.sourceChain,encoding,"cb58","Buffer",32),this.importIns=fields.importIns.map((i=>{let ii=new inputs_1.TransferableInput;return ii.deserialize(i,encoding),ii})),this.numIns=buffer_1.Buffer.alloc(4),this.numIns.writeUInt32BE(this.importIns.length,0)}getTxType(){return this._typeID}fromBuffer(bytes,offset=0){offset=super.fromBuffer(bytes,offset),this.sourceChain=bintools.copyFrom(bytes,offset,offset+32),offset+=32,this.numIns=bintools.copyFrom(bytes,offset,offset+4),offset+=4;const numIns=this.numIns.readUInt32BE(0);for(let i=0;i{if(inputid===constants_1.PlatformVMConstants.SECPINPUTID)return new SECPTransferInput(...args);if(inputid===constants_1.PlatformVMConstants.STAKEABLELOCKINID)return new StakeableLockIn(...args);throw new errors_1.InputIdError("Error - SelectInputClass: unknown inputid")};class ParseableInput extends input_1.StandardParseableInput{constructor(){super(...arguments),this._typeName="ParseableInput",this._typeID=void 0}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.input=(0,exports.SelectInputClass)(fields.input._typeID),this.input.deserialize(fields.input,encoding)}fromBuffer(bytes,offset=0){const inputid=bintools.copyFrom(bytes,offset,offset+4).readUInt32BE(0);return offset+=4,this.input=(0,exports.SelectInputClass)(inputid),this.input.fromBuffer(bytes,offset)}}exports.ParseableInput=ParseableInput;class TransferableInput extends input_1.StandardTransferableInput{constructor(){super(...arguments),this._typeName="TransferableInput",this._typeID=void 0}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.input=(0,exports.SelectInputClass)(fields.input._typeID),this.input.deserialize(fields.input,encoding)}fromBuffer(bytes,offset=0){this.txid=bintools.copyFrom(bytes,offset,offset+32),offset+=32,this.outputidx=bintools.copyFrom(bytes,offset,offset+4),offset+=4,this.assetID=bintools.copyFrom(bytes,offset,offset+constants_1.PlatformVMConstants.ASSETIDLEN),offset+=32;const inputid=bintools.copyFrom(bytes,offset,offset+4).readUInt32BE(0);return offset+=4,this.input=(0,exports.SelectInputClass)(inputid),this.input.fromBuffer(bytes,offset)}}exports.TransferableInput=TransferableInput;class AmountInput extends input_1.StandardAmountInput{constructor(){super(...arguments),this._typeName="AmountInput",this._typeID=void 0}select(id,...args){return(0,exports.SelectInputClass)(id,...args)}}exports.AmountInput=AmountInput;class SECPTransferInput extends AmountInput{constructor(){super(...arguments),this._typeName="SECPTransferInput",this._typeID=constants_1.PlatformVMConstants.SECPINPUTID,this.getCredentialID=()=>constants_1.PlatformVMConstants.SECPCREDENTIAL}getInputID(){return this._typeID}create(...args){return new SECPTransferInput(...args)}clone(){const newout=this.create();return newout.fromBuffer(this.toBuffer()),newout}}exports.SECPTransferInput=SECPTransferInput;class StakeableLockIn extends AmountInput{constructor(amount,stakeableLocktime,transferableInput){super(amount),this._typeName="StakeableLockIn",this._typeID=constants_1.PlatformVMConstants.STAKEABLELOCKINID,this.getCredentialID=()=>constants_1.PlatformVMConstants.SECPCREDENTIAL,void 0!==stakeableLocktime&&(this.stakeableLocktime=bintools.fromBNToBuffer(stakeableLocktime,8)),void 0!==transferableInput&&(this.transferableInput=transferableInput,this.synchronize())}serialize(encoding="hex"){let fields=super.serialize(encoding),outobj=Object.assign(Object.assign({},fields),{stakeableLocktime:serialization.encoder(this.stakeableLocktime,encoding,"Buffer","decimalString",8),transferableInput:this.transferableInput.serialize(encoding)});return delete outobj.sigIdxs,delete outobj.sigCount,delete outobj.amount,outobj}deserialize(fields,encoding="hex"){fields.sigIdxs=[],fields.sigCount="0",fields.amount="98",super.deserialize(fields,encoding),this.stakeableLocktime=serialization.decoder(fields.stakeableLocktime,encoding,"decimalString","Buffer",8),this.transferableInput=new ParseableInput,this.transferableInput.deserialize(fields.transferableInput,encoding),this.synchronize()}synchronize(){let input=this.transferableInput.getInput();this.sigIdxs=input.getSigIdxs(),this.sigCount=buffer_1.Buffer.alloc(4),this.sigCount.writeUInt32BE(this.sigIdxs.length,0),this.amount=bintools.fromBNToBuffer(input.getAmount(),8),this.amountValue=input.getAmount()}getStakeableLocktime(){return bintools.fromBufferToBN(this.stakeableLocktime)}getTransferablInput(){return this.transferableInput}getInputID(){return this._typeID}fromBuffer(bytes,offset=0){return this.stakeableLocktime=bintools.copyFrom(bytes,offset,offset+8),offset+=8,this.transferableInput=new ParseableInput,offset=this.transferableInput.fromBuffer(bytes,offset),this.synchronize(),offset}toBuffer(){const xferinBuff=this.transferableInput.toBuffer(),bsize=this.stakeableLocktime.length+xferinBuff.length,barr=[this.stakeableLocktime,xferinBuff];return buffer_1.Buffer.concat(barr,bsize)}create(...args){return new StakeableLockIn(...args)}clone(){const newout=this.create();return newout.fromBuffer(this.toBuffer()),newout}select(id,...args){return(0,exports.SelectInputClass)(id,...args)}}exports.StakeableLockIn=StakeableLockIn},6333:(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0})},2372:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.KeyChain=exports.KeyPair=void 0;const bintools_1=__importDefault(__webpack_require__(903)),secp256k1_1=__webpack_require__(181),utils_1=__webpack_require__(338),bintools=bintools_1.default.getInstance();utils_1.Serialization.getInstance();class KeyPair extends secp256k1_1.SECP256k1KeyPair{clone(){let newkp=new KeyPair(this.hrp,this.chainID);return newkp.importKey(bintools.copyFrom(this.getPrivateKey())),newkp}create(...args){return 2==args.length?new KeyPair(args[0],args[1]):new KeyPair(this.hrp,this.chainID)}}exports.KeyPair=KeyPair;class KeyChain extends secp256k1_1.SECP256k1KeyChain{constructor(hrp,chainID){super(),this.hrp="",this.chainID="",this.makeKey=()=>{let keypair=new KeyPair(this.hrp,this.chainID);return this.addKey(keypair),keypair},this.addKey=newKey=>{newKey.setChainID(this.chainID),super.addKey(newKey)},this.importKey=privk=>{let pk,keypair=new KeyPair(this.hrp,this.chainID);return pk="string"==typeof privk?bintools.cb58Decode(privk.split("-")[1]):bintools.copyFrom(privk),keypair.importKey(pk),keypair.getAddress().toString("hex")in this.keys||this.addKey(keypair),keypair},this.hrp=hrp,this.chainID=chainID}create(...args){return 2==args.length?new KeyChain(args[0],args[1]):new KeyChain(this.hrp,this.chainID)}clone(){const newkc=new KeyChain(this.hrp,this.chainID);for(let k in this.keys)newkc.addKey(this.keys[`${k}`].clone());return newkc}union(kc){let newkc=kc.clone();for(let k in this.keys)newkc.addKey(this.keys[`${k}`].clone());return newkc}}exports.KeyChain=KeyChain},5168:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.SECPOwnerOutput=exports.StakeableLockOut=exports.SECPTransferOutput=exports.AmountOutput=exports.ParseableOutput=exports.TransferableOutput=exports.SelectOutputClass=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),constants_1=__webpack_require__(7080),output_1=__webpack_require__(8556),serialization_1=__webpack_require__(555),errors_1=__webpack_require__(611),bintools=bintools_1.default.getInstance(),serialization=serialization_1.Serialization.getInstance();exports.SelectOutputClass=(outputid,...args)=>{if(outputid==constants_1.PlatformVMConstants.SECPXFEROUTPUTID)return new SECPTransferOutput(...args);if(outputid==constants_1.PlatformVMConstants.SECPOWNEROUTPUTID)return new SECPOwnerOutput(...args);if(outputid==constants_1.PlatformVMConstants.STAKEABLELOCKOUTID)return new StakeableLockOut(...args);throw new errors_1.OutputIdError("Error - SelectOutputClass: unknown outputid "+outputid)};class TransferableOutput extends output_1.StandardTransferableOutput{constructor(){super(...arguments),this._typeName="TransferableOutput",this._typeID=void 0}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.output=(0,exports.SelectOutputClass)(fields.output._typeID),this.output.deserialize(fields.output,encoding)}fromBuffer(bytes,offset=0){this.assetID=bintools.copyFrom(bytes,offset,offset+constants_1.PlatformVMConstants.ASSETIDLEN),offset+=constants_1.PlatformVMConstants.ASSETIDLEN;const outputid=bintools.copyFrom(bytes,offset,offset+4).readUInt32BE(0);return offset+=4,this.output=(0,exports.SelectOutputClass)(outputid),this.output.fromBuffer(bytes,offset)}}exports.TransferableOutput=TransferableOutput;class ParseableOutput extends output_1.StandardParseableOutput{constructor(){super(...arguments),this._typeName="ParseableOutput",this._typeID=void 0}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.output=(0,exports.SelectOutputClass)(fields.output._typeID),this.output.deserialize(fields.output,encoding)}fromBuffer(bytes,offset=0){const outputid=bintools.copyFrom(bytes,offset,offset+4).readUInt32BE(0);return offset+=4,this.output=(0,exports.SelectOutputClass)(outputid),this.output.fromBuffer(bytes,offset)}}exports.ParseableOutput=ParseableOutput;class AmountOutput extends output_1.StandardAmountOutput{constructor(){super(...arguments),this._typeName="AmountOutput",this._typeID=void 0}makeTransferable(assetID){return new TransferableOutput(assetID,this)}select(id,...args){return(0,exports.SelectOutputClass)(id,...args)}}exports.AmountOutput=AmountOutput;class SECPTransferOutput extends AmountOutput{constructor(){super(...arguments),this._typeName="SECPTransferOutput",this._typeID=constants_1.PlatformVMConstants.SECPXFEROUTPUTID}getOutputID(){return this._typeID}create(...args){return new SECPTransferOutput(...args)}clone(){const newout=this.create();return newout.fromBuffer(this.toBuffer()),newout}}exports.SECPTransferOutput=SECPTransferOutput;class StakeableLockOut extends AmountOutput{constructor(amount,addresses,locktime,threshold,stakeableLocktime,transferableOutput){super(amount,addresses,locktime,threshold),this._typeName="StakeableLockOut",this._typeID=constants_1.PlatformVMConstants.STAKEABLELOCKOUTID,void 0!==stakeableLocktime&&(this.stakeableLocktime=bintools.fromBNToBuffer(stakeableLocktime,8)),void 0!==transferableOutput&&(this.transferableOutput=transferableOutput,this.synchronize())}serialize(encoding="hex"){let fields=super.serialize(encoding),outobj=Object.assign(Object.assign({},fields),{stakeableLocktime:serialization.encoder(this.stakeableLocktime,encoding,"Buffer","decimalString",8),transferableOutput:this.transferableOutput.serialize(encoding)});return delete outobj.addresses,delete outobj.locktime,delete outobj.threshold,delete outobj.amount,outobj}deserialize(fields,encoding="hex"){fields.addresses=[],fields.locktime="0",fields.threshold="1",fields.amount="99",super.deserialize(fields,encoding),this.stakeableLocktime=serialization.decoder(fields.stakeableLocktime,encoding,"decimalString","Buffer",8),this.transferableOutput=new ParseableOutput,this.transferableOutput.deserialize(fields.transferableOutput,encoding),this.synchronize()}synchronize(){let output=this.transferableOutput.getOutput();this.addresses=output.getAddresses().map((a=>{let addr=new output_1.Address;return addr.fromBuffer(a),addr})),this.numaddrs=buffer_1.Buffer.alloc(4),this.numaddrs.writeUInt32BE(this.addresses.length,0),this.locktime=bintools.fromBNToBuffer(output.getLocktime(),8),this.threshold=buffer_1.Buffer.alloc(4),this.threshold.writeUInt32BE(output.getThreshold(),0),this.amount=bintools.fromBNToBuffer(output.getAmount(),8),this.amountValue=output.getAmount()}getStakeableLocktime(){return bintools.fromBufferToBN(this.stakeableLocktime)}getTransferableOutput(){return this.transferableOutput}makeTransferable(assetID){return new TransferableOutput(assetID,this)}select(id,...args){return(0,exports.SelectOutputClass)(id,...args)}fromBuffer(outbuff,offset=0){return this.stakeableLocktime=bintools.copyFrom(outbuff,offset,offset+8),offset+=8,this.transferableOutput=new ParseableOutput,offset=this.transferableOutput.fromBuffer(outbuff,offset),this.synchronize(),offset}toBuffer(){let xferoutBuff=this.transferableOutput.toBuffer();const bsize=this.stakeableLocktime.length+xferoutBuff.length,barr=[this.stakeableLocktime,xferoutBuff];return buffer_1.Buffer.concat(barr,bsize)}getOutputID(){return this._typeID}create(...args){return new StakeableLockOut(...args)}clone(){const newout=this.create();return newout.fromBuffer(this.toBuffer()),newout}}exports.StakeableLockOut=StakeableLockOut;class SECPOwnerOutput extends output_1.Output{constructor(){super(...arguments),this._typeName="SECPOwnerOutput",this._typeID=constants_1.PlatformVMConstants.SECPOWNEROUTPUTID}getOutputID(){return this._typeID}makeTransferable(assetID){return new TransferableOutput(assetID,this)}create(...args){return new SECPOwnerOutput(...args)}clone(){const newout=this.create();return newout.fromBuffer(this.toBuffer()),newout}select(id,...args){return(0,exports.SelectOutputClass)(id,...args)}}exports.SECPOwnerOutput=SECPOwnerOutput},9968:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.SubnetAuth=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),utils_1=__webpack_require__(338),_1=__webpack_require__(7679),bintools=bintools_1.default.getInstance();class SubnetAuth extends utils_1.Serializable{constructor(){super(...arguments),this._typeName="SubnetAuth",this._typeID=_1.PlatformVMConstants.SUBNETAUTH,this.addressIndices=[],this.numAddressIndices=buffer_1.Buffer.alloc(4)}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign({},fields)}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding)}addAddressIndex(index){const numAddrIndices=this.getNumAddressIndices();this.numAddressIndices.writeUIntBE(numAddrIndices+1,0,4),this.addressIndices.push(index)}getNumAddressIndices(){return this.numAddressIndices.readUIntBE(0,4)}getAddressIndices(){return this.addressIndices}fromBuffer(bytes,offset=0){offset+=4,this.numAddressIndices=bintools.copyFrom(bytes,offset,offset+4),offset+=4;for(let i=0;i{bsize+=4,barr.push(this.addressIndices[`${i}`])})),buffer_1.Buffer.concat(barr,bsize)}}exports.SubnetAuth=SubnetAuth},8508:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.Tx=exports.UnsignedTx=exports.SelectTxClass=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),constants_1=__webpack_require__(7080),credentials_1=__webpack_require__(6525),tx_1=__webpack_require__(613),create_hash_1=__importDefault(__webpack_require__(3482)),basetx_1=__webpack_require__(9660),importtx_1=__webpack_require__(5416),exporttx_1=__webpack_require__(5619),validationtx_1=__webpack_require__(6237),createsubnettx_1=__webpack_require__(6547),errors_1=__webpack_require__(611),bintools=bintools_1.default.getInstance();exports.SelectTxClass=(txtype,...args)=>{if(txtype===constants_1.PlatformVMConstants.BASETX)return new basetx_1.BaseTx(...args);if(txtype===constants_1.PlatformVMConstants.IMPORTTX)return new importtx_1.ImportTx(...args);if(txtype===constants_1.PlatformVMConstants.EXPORTTX)return new exporttx_1.ExportTx(...args);if(txtype===constants_1.PlatformVMConstants.ADDDELEGATORTX)return new validationtx_1.AddDelegatorTx(...args);if(txtype===constants_1.PlatformVMConstants.ADDVALIDATORTX)return new validationtx_1.AddValidatorTx(...args);if(txtype===constants_1.PlatformVMConstants.CREATESUBNETTX)return new createsubnettx_1.CreateSubnetTx(...args);throw new errors_1.TransactionError("Error - SelectTxClass: unknown txtype")};class UnsignedTx extends tx_1.StandardUnsignedTx{constructor(){super(...arguments),this._typeName="UnsignedTx",this._typeID=void 0}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.transaction=(0,exports.SelectTxClass)(fields.transaction._typeID),this.transaction.deserialize(fields.transaction,encoding)}getTransaction(){return this.transaction}fromBuffer(bytes,offset=0){this.codecID=bintools.copyFrom(bytes,offset,offset+2).readUInt16BE(0),offset+=2;const txtype=bintools.copyFrom(bytes,offset,offset+4).readUInt32BE(0);return offset+=4,this.transaction=(0,exports.SelectTxClass)(txtype),this.transaction.fromBuffer(bytes,offset)}sign(kc){const txbuff=this.toBuffer(),msg=buffer_1.Buffer.from((0,create_hash_1.default)("sha256").update(txbuff).digest()),creds=this.transaction.sign(msg,kc);return new Tx(this,creds)}}exports.UnsignedTx=UnsignedTx;class Tx extends tx_1.StandardTx{constructor(){super(...arguments),this._typeName="Tx",this._typeID=void 0}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.unsignedTx=new UnsignedTx,this.unsignedTx.deserialize(fields.unsignedTx,encoding),this.credentials=[];for(let i=0;ithis.getAllUTXOs().filter((utxo=>{if(stakeable)return!0;const output=utxo.getOutput();if(!(output instanceof outputs_1.StakeableLockOut))return!0;return!!output.getStakeableLocktime().lt(asOf)})),this.getMinimumSpendable=(aad,asOf=(0,helperfunctions_1.UnixNow)(),locktime=new bn_js_1.default(0),threshold=1,stakeable=!1)=>{let utxoArray=this.getConsumableUXTO(asOf,stakeable),tmpUTXOArray=[];stakeable&&(utxoArray.forEach((utxo=>{22===utxo.getOutput().getTypeID()&&tmpUTXOArray.push(utxo)})),tmpUTXOArray.sort(((a,b)=>{let stakeableLockOut1=a.getOutput();return b.getOutput().getStakeableLocktime().toNumber()-stakeableLockOut1.getStakeableLocktime().toNumber()})),utxoArray.forEach((utxo=>{7===utxo.getOutput().getTypeID()&&tmpUTXOArray.push(utxo)})),utxoArray=tmpUTXOArray);const outs={};if(utxoArray.forEach(((utxo,index)=>{const assetID=utxo.getAssetID(),assetKey=assetID.toString("hex"),fromAddresses=aad.getSenders(),output=utxo.getOutput();if(!(output instanceof outputs_1.AmountOutput&&aad.assetExists(assetKey)&&output.meetsThreshold(fromAddresses,asOf)))return;const assetAmount=aad.getAssetAmount(assetKey);if(assetAmount.isFinished())return;assetKey in outs||(outs[`${assetKey}`]={lockedStakeable:[],unlocked:[]});const amountOutput=output,amount=amountOutput.getAmount();let input=new inputs_1.SECPTransferInput(amount),locked=!1;if(amountOutput instanceof outputs_1.StakeableLockOut){const stakeableLocktime=amountOutput.getStakeableLocktime();stakeableLocktime.gt(asOf)&&(input=new inputs_1.StakeableLockIn(amount,stakeableLocktime,new inputs_1.ParseableInput(input)),locked=!0)}assetAmount.spendAmount(amount,locked),locked?outs[`${assetKey}`].lockedStakeable.push(amountOutput):outs[`${assetKey}`].unlocked.push(amountOutput);amountOutput.getSpenders(fromAddresses,asOf).forEach((spender=>{const idx=amountOutput.getAddressIdx(spender);if(-1===idx)throw new errors_1.AddressError(`Error - UTXOSet.getMinimumSpendable: no such address in output: ${spender}`);input.addSignatureIdx(idx,spender)}));const txID=utxo.getTxID(),outputIdx=utxo.getOutputIdx(),transferInput=new inputs_1.TransferableInput(txID,outputIdx,assetID,input);aad.addInput(transferInput)})),!aad.canComplete())return new errors_1.InsufficientFundsError("Error - UTXOSet.getMinimumSpendable: insufficient funds to create the transaction");const zero=new bn_js_1.default(0);aad.getAmounts().forEach((assetAmount=>{const change=assetAmount.getChange(),isStakeableLockChange=assetAmount.getStakeableLockChange(),lockedChange=isStakeableLockChange?change:zero.clone(),assetID=assetAmount.getAssetID(),assetKey=assetAmount.getAssetIDString(),lockedOutputs=outs[`${assetKey}`].lockedStakeable;lockedOutputs.forEach(((lockedOutput,i)=>{const stakeableLocktime=lockedOutput.getStakeableLocktime(),output=lockedOutput.getTransferableOutput().getOutput();let outputAmountRemaining=output.getAmount();if(i==lockedOutputs.length-1&&lockedChange.gt(zero)){outputAmountRemaining=outputAmountRemaining.sub(lockedChange);const newChangeOutput=(0,outputs_1.SelectOutputClass)(output.getOutputID(),lockedChange,output.getAddresses(),output.getLocktime(),output.getThreshold());let newLockedChangeOutput=(0,outputs_1.SelectOutputClass)(lockedOutput.getOutputID(),lockedChange,output.getAddresses(),output.getLocktime(),output.getThreshold(),stakeableLocktime,new outputs_1.ParseableOutput(newChangeOutput));const transferOutput=new outputs_1.TransferableOutput(assetID,newLockedChangeOutput);aad.addChange(transferOutput)}const newOutput=(0,outputs_1.SelectOutputClass)(output.getOutputID(),outputAmountRemaining,output.getAddresses(),output.getLocktime(),output.getThreshold()),newLockedOutput=(0,outputs_1.SelectOutputClass)(lockedOutput.getOutputID(),outputAmountRemaining,output.getAddresses(),output.getLocktime(),output.getThreshold(),stakeableLocktime,new outputs_1.ParseableOutput(newOutput)),transferOutput=new outputs_1.TransferableOutput(assetID,newLockedOutput);aad.addOutput(transferOutput)}));const unlockedChange=isStakeableLockChange?zero.clone():change;if(unlockedChange.gt(zero)){const newChangeOutput=new outputs_1.SECPTransferOutput(unlockedChange,aad.getChangeAddresses(),zero.clone(),threshold),transferOutput=new outputs_1.TransferableOutput(assetID,newChangeOutput);aad.addChange(transferOutput)}const totalAmountSpent=assetAmount.getSpent(),stakeableLockedAmount=assetAmount.getStakeableLockSpent(),totalUnlockedSpent=totalAmountSpent.sub(stakeableLockedAmount),amountBurnt=assetAmount.getBurn(),unlockedAmount=totalUnlockedSpent.sub(amountBurnt).sub(unlockedChange);if(unlockedAmount.gt(zero)){const newOutput=new outputs_1.SECPTransferOutput(unlockedAmount,aad.getDestinations(),locktime,threshold),transferOutput=new outputs_1.TransferableOutput(assetID,newOutput);aad.addOutput(transferOutput)}}))},this.buildBaseTx=(networkID,blockchainID,amount,assetID,toAddresses,fromAddresses,changeAddresses,fee,feeAssetID,memo,asOf=(0,helperfunctions_1.UnixNow)(),locktime=new bn_js_1.default(0),threshold=1)=>{if(threshold>toAddresses.length)throw new errors_1.ThresholdError("Error - UTXOSet.buildBaseTx: threshold is greater than number of addresses");void 0===changeAddresses&&(changeAddresses=toAddresses),void 0===feeAssetID&&(feeAssetID=assetID);const zero=new bn_js_1.default(0);if(amount.eq(zero))return;const aad=new AssetAmountDestination(toAddresses,fromAddresses,changeAddresses);assetID.toString("hex")===feeAssetID.toString("hex")?aad.addAssetAmount(assetID,amount,fee):(aad.addAssetAmount(assetID,amount,zero),this._feeCheck(fee,feeAssetID)&&aad.addAssetAmount(feeAssetID,zero,fee));let ins=[],outs=[];const minSpendableErr=this.getMinimumSpendable(aad,asOf,locktime,threshold);if(void 0!==minSpendableErr)throw minSpendableErr;ins=aad.getInputs(),outs=aad.getAllOutputs();const baseTx=new basetx_1.BaseTx(networkID,blockchainID,outs,ins,memo);return new tx_1.UnsignedTx(baseTx)},this.buildImportTx=(networkID,blockchainID,toAddresses,fromAddresses,changeAddresses,atomics,sourceChain,fee,feeAssetID,memo,asOf=(0,helperfunctions_1.UnixNow)(),locktime=new bn_js_1.default(0),threshold=1)=>{const zero=new bn_js_1.default(0);let ins=[],outs=[];void 0===fee&&(fee=zero.clone());const importIns=[];let feepaid=new bn_js_1.default(0),feeAssetStr=feeAssetID.toString("hex");for(let i=0;i{let ins=[],outs=[],exportouts=[];void 0===changeAddresses&&(changeAddresses=toAddresses);const zero=new bn_js_1.default(0);if(amount.eq(zero))return;if(void 0===feeAssetID)feeAssetID=avaxAssetID;else if(feeAssetID.toString("hex")!==avaxAssetID.toString("hex"))throw new errors_1.FeeAssetError("Error - UTXOSet.buildExportTx: feeAssetID must match avaxAssetID");void 0===destinationChain&&(destinationChain=bintools.cb58Decode(constants_2.Defaults.network[`${networkID}`].X.blockchainID));const aad=new AssetAmountDestination(toAddresses,fromAddresses,changeAddresses);avaxAssetID.toString("hex")===feeAssetID.toString("hex")?aad.addAssetAmount(avaxAssetID,amount,fee):(aad.addAssetAmount(avaxAssetID,amount,zero),this._feeCheck(fee,feeAssetID)&&aad.addAssetAmount(feeAssetID,zero,fee));const minSpendableErr=this.getMinimumSpendable(aad,asOf,locktime,threshold);if(void 0!==minSpendableErr)throw minSpendableErr;ins=aad.getInputs(),outs=aad.getChangeOutputs(),exportouts=aad.getOutputs();const exportTx=new exporttx_1.ExportTx(networkID,blockchainID,outs,ins,memo,destinationChain,exportouts);return new tx_1.UnsignedTx(exportTx)},this.buildAddSubnetValidatorTx=(networkID=constants_2.DefaultNetworkID,blockchainID,fromAddresses,changeAddresses,nodeID,startTime,endTime,weight,subnetID,fee,feeAssetID,memo,asOf=(0,helperfunctions_1.UnixNow)(),subnetAuthCredentials=[])=>{let ins=[],outs=[];const zero=new bn_js_1.default(0),now=(0,helperfunctions_1.UnixNow)();if(startTime.lt(now)||endTime.lte(startTime))throw new Error("UTXOSet.buildAddSubnetValidatorTx -- startTime must be in the future and endTime must come after startTime");if(this._feeCheck(fee,feeAssetID)){const aad=new AssetAmountDestination(fromAddresses,fromAddresses,changeAddresses);aad.addAssetAmount(feeAssetID,zero,fee);const success=this.getMinimumSpendable(aad,asOf);if(void 0!==success)throw success;ins=aad.getInputs(),outs=aad.getAllOutputs()}const addSubnetValidatorTx=new addsubnetvalidatortx_1.AddSubnetValidatorTx(networkID,blockchainID,outs,ins,memo,nodeID,startTime,endTime,weight,subnetID);return subnetAuthCredentials.forEach((subnetAuthCredential=>{addSubnetValidatorTx.addSignatureIdx(subnetAuthCredential[0],subnetAuthCredential[1])})),new tx_1.UnsignedTx(addSubnetValidatorTx)},this.buildAddDelegatorTx=(networkID=constants_2.DefaultNetworkID,blockchainID,avaxAssetID,toAddresses,fromAddresses,changeAddresses,nodeID,startTime,endTime,stakeAmount,rewardLocktime,rewardThreshold,rewardAddresses,fee,feeAssetID,memo,asOf=(0,helperfunctions_1.UnixNow)(),changeThreshold=1)=>{if(rewardThreshold>rewardAddresses.length)throw new errors_1.ThresholdError("Error - UTXOSet.buildAddDelegatorTx: reward threshold is greater than number of addresses");void 0===changeAddresses&&(changeAddresses=toAddresses);let ins=[],outs=[],stakeOuts=[];const zero=new bn_js_1.default(0),now=(0,helperfunctions_1.UnixNow)();if(startTime.lt(now)||endTime.lte(startTime))throw new errors_1.TimeError("UTXOSet.buildAddDelegatorTx -- startTime must be in the future and endTime must come after startTime");const aad=new AssetAmountDestination(toAddresses,fromAddresses,changeAddresses);avaxAssetID.toString("hex")===feeAssetID.toString("hex")?aad.addAssetAmount(avaxAssetID,stakeAmount,fee):(aad.addAssetAmount(avaxAssetID,stakeAmount,zero),this._feeCheck(fee,feeAssetID)&&aad.addAssetAmount(feeAssetID,zero,fee));const minSpendableErr=this.getMinimumSpendable(aad,asOf,void 0,changeThreshold,!0);if(void 0!==minSpendableErr)throw minSpendableErr;ins=aad.getInputs(),outs=aad.getChangeOutputs(),stakeOuts=aad.getOutputs();const rewardOutputOwners=new outputs_1.SECPOwnerOutput(rewardAddresses,rewardLocktime,rewardThreshold),UTx=new validationtx_1.AddDelegatorTx(networkID,blockchainID,outs,ins,memo,nodeID,startTime,endTime,stakeAmount,stakeOuts,new outputs_1.ParseableOutput(rewardOutputOwners));return new tx_1.UnsignedTx(UTx)},this.buildAddValidatorTx=(networkID=constants_2.DefaultNetworkID,blockchainID,avaxAssetID,toAddresses,fromAddresses,changeAddresses,nodeID,startTime,endTime,stakeAmount,rewardLocktime,rewardThreshold,rewardAddresses,delegationFee,fee,feeAssetID,memo,asOf=(0,helperfunctions_1.UnixNow)())=>{let ins=[],outs=[],stakeOuts=[];const zero=new bn_js_1.default(0),now=(0,helperfunctions_1.UnixNow)();if(startTime.lt(now)||endTime.lte(startTime))throw new errors_1.TimeError("UTXOSet.buildAddValidatorTx -- startTime must be in the future and endTime must come after startTime");if(delegationFee>100||delegationFee<0)throw new errors_1.TimeError("UTXOSet.buildAddValidatorTx -- startTime must be in the range of 0 to 100, inclusively");const aad=new AssetAmountDestination(toAddresses,fromAddresses,changeAddresses);avaxAssetID.toString("hex")===feeAssetID.toString("hex")?aad.addAssetAmount(avaxAssetID,stakeAmount,fee):(aad.addAssetAmount(avaxAssetID,stakeAmount,zero),this._feeCheck(fee,feeAssetID)&&aad.addAssetAmount(feeAssetID,zero,fee));const minSpendableErr=this.getMinimumSpendable(aad,asOf,void 0,void 0,!0);if(void 0!==minSpendableErr)throw minSpendableErr;ins=aad.getInputs(),outs=aad.getChangeOutputs(),stakeOuts=aad.getOutputs();const rewardOutputOwners=new outputs_1.SECPOwnerOutput(rewardAddresses,rewardLocktime,rewardThreshold),UTx=new validationtx_1.AddValidatorTx(networkID,blockchainID,outs,ins,memo,nodeID,startTime,endTime,stakeAmount,stakeOuts,new outputs_1.ParseableOutput(rewardOutputOwners),delegationFee);return new tx_1.UnsignedTx(UTx)},this.buildCreateSubnetTx=(networkID=constants_2.DefaultNetworkID,blockchainID,fromAddresses,changeAddresses,subnetOwnerAddresses,subnetOwnerThreshold,fee,feeAssetID,memo,asOf=(0,helperfunctions_1.UnixNow)())=>{const zero=new bn_js_1.default(0);let ins=[],outs=[];if(this._feeCheck(fee,feeAssetID)){const aad=new AssetAmountDestination(fromAddresses,fromAddresses,changeAddresses);aad.addAssetAmount(feeAssetID,zero,fee);const minSpendableErr=this.getMinimumSpendable(aad,asOf,void 0,void 0);if(void 0!==minSpendableErr)throw minSpendableErr;ins=aad.getInputs(),outs=aad.getAllOutputs()}const locktime=new bn_js_1.default(0),subnetOwners=new outputs_1.SECPOwnerOutput(subnetOwnerAddresses,locktime,subnetOwnerThreshold),createSubnetTx=new createsubnettx_1.CreateSubnetTx(networkID,blockchainID,outs,ins,memo,subnetOwners);return new tx_1.UnsignedTx(createSubnetTx)},this.buildCreateChainTx=(networkID=constants_2.DefaultNetworkID,blockchainID,fromAddresses,changeAddresses,subnetID,chainName,vmID,fxIDs,genesisData,fee,feeAssetID,memo,asOf=(0,helperfunctions_1.UnixNow)(),subnetAuthCredentials=[])=>{const zero=new bn_js_1.default(0);let ins=[],outs=[];if(this._feeCheck(fee,feeAssetID)){const aad=new AssetAmountDestination(fromAddresses,fromAddresses,changeAddresses);aad.addAssetAmount(feeAssetID,zero,fee);const minSpendableErr=this.getMinimumSpendable(aad,asOf,void 0,void 0);if(void 0!==minSpendableErr)throw minSpendableErr;ins=aad.getInputs(),outs=aad.getAllOutputs()}const createChainTx=new _1.CreateChainTx(networkID,blockchainID,outs,ins,memo,subnetID,chainName,vmID,fxIDs,genesisData);return subnetAuthCredentials.forEach((subnetAuthCredential=>{createChainTx.addSignatureIdx(subnetAuthCredential[0],subnetAuthCredential[1])})),new tx_1.UnsignedTx(createChainTx)}}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding);let utxos={};for(let utxoid in fields.utxos){let utxoidCleaned=serialization.decoder(utxoid,encoding,"base58","base58");utxos[`${utxoidCleaned}`]=new UTXO,utxos[`${utxoidCleaned}`].deserialize(fields.utxos[`${utxoid}`],encoding)}let addressUTXOs={};for(let address in fields.addressUTXOs){let addressCleaned=serialization.decoder(address,encoding,"cb58","hex"),utxobalance={};for(let utxoid in fields.addressUTXOs[`${address}`]){utxobalance[`${serialization.decoder(utxoid,encoding,"base58","base58")}`]=serialization.decoder(fields.addressUTXOs[`${address}`][`${utxoid}`],encoding,"decimalString","BN")}addressUTXOs[`${addressCleaned}`]=utxobalance}this.utxos=utxos,this.addressUTXOs=addressUTXOs}parseUTXO(utxo){const utxovar=new UTXO;if("string"==typeof utxo)utxovar.fromBuffer(bintools.cb58Decode(utxo));else{if(!(utxo instanceof utxos_1.StandardUTXO))throw new errors_1.UTXOError("Error - UTXO.parseUTXO: utxo parameter is not a UTXO or string");utxovar.fromBuffer(utxo.toBuffer())}return utxovar}create(...args){return new UTXOSet}clone(){const newset=this.create(),allUTXOs=this.getAllUTXOs();return newset.addArray(allUTXOs),newset}_feeCheck(fee,feeAssetID){return void 0!==fee&&void 0!==feeAssetID&&fee.gt(new bn_js_1.default(0))&&feeAssetID instanceof buffer_1.Buffer}}exports.UTXOSet=UTXOSet},6237:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.AddValidatorTx=exports.AddDelegatorTx=exports.WeightedValidatorTx=exports.ValidatorTx=void 0;const bn_js_1=__importDefault(__webpack_require__(3550)),bintools_1=__importDefault(__webpack_require__(903)),basetx_1=__webpack_require__(9660),outputs_1=__webpack_require__(5168),buffer_1=__webpack_require__(8764),constants_1=__webpack_require__(7080),constants_2=__webpack_require__(8779),helperfunctions_1=__webpack_require__(5554),outputs_2=__webpack_require__(5168),serialization_1=__webpack_require__(555),errors_1=__webpack_require__(611),bintools=bintools_1.default.getInstance(),serialization=serialization_1.Serialization.getInstance();class ValidatorTx extends basetx_1.BaseTx{constructor(networkID,blockchainID,outs,ins,memo,nodeID,startTime,endTime){super(networkID,blockchainID,outs,ins,memo),this._typeName="ValidatorTx",this._typeID=void 0,this.nodeID=buffer_1.Buffer.alloc(20),this.startTime=buffer_1.Buffer.alloc(8),this.endTime=buffer_1.Buffer.alloc(8),this.nodeID=nodeID,this.startTime=bintools.fromBNToBuffer(startTime,8),this.endTime=bintools.fromBNToBuffer(endTime,8)}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{nodeID:serialization.encoder(this.nodeID,encoding,"Buffer","nodeID"),startTime:serialization.encoder(this.startTime,encoding,"Buffer","decimalString"),endTime:serialization.encoder(this.endTime,encoding,"Buffer","decimalString")})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.nodeID=serialization.decoder(fields.nodeID,encoding,"nodeID","Buffer",20),this.startTime=serialization.decoder(fields.startTime,encoding,"decimalString","Buffer",8),this.endTime=serialization.decoder(fields.endTime,encoding,"decimalString","Buffer",8)}getNodeID(){return this.nodeID}getNodeIDString(){return(0,helperfunctions_1.bufferToNodeIDString)(this.nodeID)}getStartTime(){return bintools.fromBufferToBN(this.startTime)}getEndTime(){return bintools.fromBufferToBN(this.endTime)}fromBuffer(bytes,offset=0){return offset=super.fromBuffer(bytes,offset),this.nodeID=bintools.copyFrom(bytes,offset,offset+20),offset+=20,this.startTime=bintools.copyFrom(bytes,offset,offset+8),offset+=8,this.endTime=bintools.copyFrom(bytes,offset,offset+8),offset+=8}toBuffer(){const superbuff=super.toBuffer(),bsize=superbuff.length+this.nodeID.length+this.startTime.length+this.endTime.length;return buffer_1.Buffer.concat([superbuff,this.nodeID,this.startTime,this.endTime],bsize)}}exports.ValidatorTx=ValidatorTx;class WeightedValidatorTx extends ValidatorTx{constructor(networkID=constants_2.DefaultNetworkID,blockchainID=buffer_1.Buffer.alloc(32,16),outs,ins,memo,nodeID,startTime,endTime,weight){super(networkID,blockchainID,outs,ins,memo,nodeID,startTime,endTime),this._typeName="WeightedValidatorTx",this._typeID=void 0,this.weight=buffer_1.Buffer.alloc(8),void 0!==typeof weight&&(this.weight=bintools.fromBNToBuffer(weight,8))}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{weight:serialization.encoder(this.weight,encoding,"Buffer","decimalString")})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.weight=serialization.decoder(fields.weight,encoding,"decimalString","Buffer",8)}getWeight(){return bintools.fromBufferToBN(this.weight)}getWeightBuffer(){return this.weight}fromBuffer(bytes,offset=0){return offset=super.fromBuffer(bytes,offset),this.weight=bintools.copyFrom(bytes,offset,offset+8),offset+=8}toBuffer(){const superbuff=super.toBuffer();return buffer_1.Buffer.concat([superbuff,this.weight])}}exports.WeightedValidatorTx=WeightedValidatorTx;class AddDelegatorTx extends WeightedValidatorTx{constructor(networkID=constants_2.DefaultNetworkID,blockchainID=buffer_1.Buffer.alloc(32,16),outs,ins,memo,nodeID,startTime,endTime,stakeAmount,stakeOuts,rewardOwners){super(networkID,blockchainID,outs,ins,memo,nodeID,startTime,endTime,stakeAmount),this._typeName="AddDelegatorTx",this._typeID=constants_1.PlatformVMConstants.ADDDELEGATORTX,this.stakeOuts=[],this.rewardOwners=void 0,void 0!==typeof stakeOuts&&(this.stakeOuts=stakeOuts),this.rewardOwners=rewardOwners}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{stakeOuts:this.stakeOuts.map((s=>s.serialize(encoding))),rewardOwners:this.rewardOwners.serialize(encoding)})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.stakeOuts=fields.stakeOuts.map((s=>{let xferout=new outputs_1.TransferableOutput;return xferout.deserialize(s,encoding),xferout})),this.rewardOwners=new outputs_2.ParseableOutput,this.rewardOwners.deserialize(fields.rewardOwners,encoding)}getTxType(){return this._typeID}getStakeAmount(){return this.getWeight()}getStakeAmountBuffer(){return this.weight}getStakeOuts(){return this.stakeOuts}getStakeOutsTotal(){let val=new bn_js_1.default(0);for(let i=0;i=0&&delegationFee<=100))throw new errors_1.DelegationFeeError("AddValidatorTx.constructor -- delegationFee must be in the range of 0 and 100, inclusively.");this.delegationFee=parseFloat(delegationFee.toFixed(4))}}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{delegationFee:serialization.encoder(this.getDelegationFeeBuffer(),encoding,"Buffer","decimalString",4)})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding);let dbuff=serialization.decoder(fields.delegationFee,encoding,"decimalString","Buffer",4);this.delegationFee=dbuff.readUInt32BE(0)/AddValidatorTx.delegatorMultiplier}getTxType(){return this._typeID}getDelegationFee(){return this.delegationFee}getDelegationFeeBuffer(){let dBuff=buffer_1.Buffer.alloc(4),buffnum=parseFloat(this.delegationFee.toFixed(4))*AddValidatorTx.delegatorMultiplier;return dBuff.writeUInt32BE(buffnum,0),dBuff}fromBuffer(bytes,offset=0){offset=super.fromBuffer(bytes,offset);let dbuff=bintools.copyFrom(bytes,offset,offset+4);return offset+=4,this.delegationFee=dbuff.readUInt32BE(0)/AddValidatorTx.delegatorMultiplier,offset}toBuffer(){let superBuff=super.toBuffer(),feeBuff=this.getDelegationFeeBuffer();return buffer_1.Buffer.concat([superBuff,feeBuff])}}exports.AddValidatorTx=AddValidatorTx,AddValidatorTx.delegatorMultiplier=1e4},4115:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.Socket=void 0;const isomorphic_ws_1=__importDefault(__webpack_require__(6792)),utils_1=__webpack_require__(338);class Socket extends isomorphic_ws_1.default{constructor(url=`wss://${utils_1.MainnetAPI}:443/ext/bc/X/events`,options){super(url,options)}send(data,cb){super.send(data,cb)}close(mcode,data){super.close(mcode,data)}}exports.Socket=Socket},9837:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))},__importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});const axios_1=__importDefault(__webpack_require__(9669)),apibase_1=__webpack_require__(17),errors_1=__webpack_require__(611),fetchadapter_1=__webpack_require__(3064),helperfunctions_1=__webpack_require__(5554);exports.default=class AvalancheCore{constructor(host,port,protocol="http"){this.networkID=0,this.hrp="",this.auth=void 0,this.headers={},this.requestConfig={},this.apis={},this.setAddress=(host,port,protocol="http",baseEndpoint="")=>{host=host.replace(/[&#,@+()$~%'":*?<>{}]/g,""),protocol=protocol.replace(/[&#,@+()$~%'":*?<>{}]/g,"");if(!["http","https"].includes(protocol))throw new errors_1.ProtocolError("Error - AvalancheCore.setAddress: Invalid protocol");this.host=host,this.port=port,this.protocol=protocol,this.baseEndpoint=baseEndpoint;let url=`${protocol}://${host}`;null!=port&&"number"==typeof port&&port>=0&&(url=`${url}:${port}`),null!=baseEndpoint&&"string"==typeof baseEndpoint&&baseEndpoint.length>0&&("/"!=baseEndpoint[0]&&(baseEndpoint=`/${baseEndpoint}`),url=`${url}${baseEndpoint}`),this.url=url},this.getProtocol=()=>this.protocol,this.getHost=()=>this.host,this.getIP=()=>this.host,this.getPort=()=>this.port,this.getBaseEndpoint=()=>this.baseEndpoint,this.getURL=()=>this.url,this.getHeaders=()=>this.headers,this.getRequestConfig=()=>this.requestConfig,this.getNetworkID=()=>this.networkID,this.setNetworkID=netID=>{this.networkID=netID,this.hrp=(0,helperfunctions_1.getPreferredHRP)(this.networkID)},this.getHRP=()=>this.hrp,this.setHRP=hrp=>{this.hrp=hrp},this.setHeader=(key,value)=>{this.headers[`${key}`]=value},this.removeHeader=key=>{delete this.headers[`${key}`]},this.removeAllHeaders=()=>{for(const prop in this.headers)Object.prototype.hasOwnProperty.call(this.headers,prop)&&delete this.headers[`${prop}`]},this.setRequestConfig=(key,value)=>{this.requestConfig[`${key}`]=value},this.removeRequestConfig=key=>{delete this.requestConfig[`${key}`]},this.removeAllRequestConfigs=()=>{for(const prop in this.requestConfig)Object.prototype.hasOwnProperty.call(this.requestConfig,prop)&&delete this.requestConfig[`${prop}`]},this.setAuthToken=auth=>{this.auth=auth},this._setHeaders=headers=>{if("object"==typeof this.headers)for(const[key,value]of Object.entries(this.headers))headers[`${key}`]=value;return"string"==typeof this.auth&&(headers.Authorization=`Bearer ${this.auth}`),headers},this.addAPI=(apiName,ConstructorFN,baseurl,...args)=>{this.apis[`${apiName}`]=void 0===baseurl?new ConstructorFN(this,void 0,...args):new ConstructorFN(this,baseurl,...args)},this.api=apiName=>this.apis[`${apiName}`],this._request=(xhrmethod,baseurl,getdata,postdata,headers={},axiosConfig)=>__awaiter(this,void 0,void 0,(function*(){let config;config=axiosConfig?Object.assign(Object.assign({},axiosConfig),this.requestConfig):Object.assign({baseURL:this.url,responseType:"text"},this.requestConfig),config.url=baseurl,config.method=xhrmethod,config.headers=headers,config.data=postdata,config.params=getdata,"undefined"!=typeof fetch&&(config.adapter=fetchadapter_1.fetchAdapter);const resp=yield axios_1.default.request(config);return new apibase_1.RequestResponseData(resp.data,resp.headers,resp.status,resp.statusText,resp.request)})),this.get=(baseurl,getdata,headers={},axiosConfig)=>this._request("GET",baseurl,getdata,{},this._setHeaders(headers),axiosConfig),this.delete=(baseurl,getdata,headers={},axiosConfig)=>this._request("DELETE",baseurl,getdata,{},this._setHeaders(headers),axiosConfig),this.post=(baseurl,getdata,postdata,headers={},axiosConfig)=>this._request("POST",baseurl,getdata,postdata,this._setHeaders(headers),axiosConfig),this.put=(baseurl,getdata,postdata,headers={},axiosConfig)=>this._request("PUT",baseurl,getdata,postdata,this._setHeaders(headers),axiosConfig),this.patch=(baseurl,getdata,postdata,headers={},axiosConfig)=>this._request("PATCH",baseurl,getdata,postdata,this._setHeaders(headers),axiosConfig),null!=host&&this.setAddress(host,port,protocol)}}},17:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.APIBase=exports.RequestResponseData=void 0;const db_1=__importDefault(__webpack_require__(7911));exports.RequestResponseData=class RequestResponseData{constructor(data,headers,status,statusText,request){this.data=data,this.headers=headers,this.status=status,this.statusText=statusText,this.request=request}};exports.APIBase=class APIBase{constructor(core,baseURL){this.setBaseURL=baseURL=>{if(this.db&&this.baseURL!==baseURL){const backup=this.db.getAll();this.db.clearAll(),this.baseURL=baseURL,this.db=db_1.default.getNamespace(baseURL),this.db.setAll(backup,!0)}else this.baseURL=baseURL,this.db=db_1.default.getNamespace(baseURL)},this.getBaseURL=()=>this.baseURL,this.getDB=()=>this.db,this.core=core,this.setBaseURL(baseURL)}}},6305:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.StandardAssetAmountDestination=exports.AssetAmount=void 0;const buffer_1=__webpack_require__(8764),bn_js_1=__importDefault(__webpack_require__(3550)),errors_1=__webpack_require__(611);class AssetAmount{constructor(assetID,amount,burn){this.assetID=buffer_1.Buffer.alloc(32),this.amount=new bn_js_1.default(0),this.burn=new bn_js_1.default(0),this.spent=new bn_js_1.default(0),this.stakeableLockSpent=new bn_js_1.default(0),this.change=new bn_js_1.default(0),this.stakeableLockChange=!1,this.finished=!1,this.getAssetID=()=>this.assetID,this.getAssetIDString=()=>this.assetID.toString("hex"),this.getAmount=()=>this.amount,this.getSpent=()=>this.spent,this.getBurn=()=>this.burn,this.getChange=()=>this.change,this.getStakeableLockSpent=()=>this.stakeableLockSpent,this.getStakeableLockChange=()=>this.stakeableLockChange,this.isFinished=()=>this.finished,this.spendAmount=(amt,stakeableLocked=!1)=>{if(this.finished)throw new errors_1.InsufficientFundsError("Error - AssetAmount.spendAmount: attempted to spend excess funds");this.spent=this.spent.add(amt),stakeableLocked&&(this.stakeableLockSpent=this.stakeableLockSpent.add(amt));const total=this.amount.add(this.burn);return this.spent.gte(total)&&(this.change=this.spent.sub(total),stakeableLocked&&(this.stakeableLockChange=!0),this.finished=!0),this.finished},this.assetID=assetID,this.amount=void 0===amount?new bn_js_1.default(0):amount,this.burn=void 0===burn?new bn_js_1.default(0):burn,this.spent=new bn_js_1.default(0),this.stakeableLockSpent=new bn_js_1.default(0),this.stakeableLockChange=!1}}exports.AssetAmount=AssetAmount;exports.StandardAssetAmountDestination=class StandardAssetAmountDestination{constructor(destinations,senders,changeAddresses){this.amounts=[],this.destinations=[],this.senders=[],this.changeAddresses=[],this.amountkey={},this.inputs=[],this.outputs=[],this.change=[],this.addAssetAmount=(assetID,amount,burn)=>{let aa=new AssetAmount(assetID,amount,burn);this.amounts.push(aa),this.amountkey[aa.getAssetIDString()]=aa},this.addInput=input=>{this.inputs.push(input)},this.addOutput=output=>{this.outputs.push(output)},this.addChange=output=>{this.change.push(output)},this.getAmounts=()=>this.amounts,this.getDestinations=()=>this.destinations,this.getSenders=()=>this.senders,this.getChangeAddresses=()=>this.changeAddresses,this.getAssetAmount=assetHexStr=>this.amountkey[`${assetHexStr}`],this.assetExists=assetHexStr=>assetHexStr in this.amountkey,this.getInputs=()=>this.inputs,this.getOutputs=()=>this.outputs,this.getChangeOutputs=()=>this.change,this.getAllOutputs=()=>this.outputs.concat(this.change),this.canComplete=()=>{for(let i=0;i{this.source=address},this.getSource=()=>this.source}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{source:serialization.encoder(this.source,encoding,"Buffer","hex")})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.source=serialization.decoder(fields.source,encoding,"hex","Buffer")}clone(){let newbase=new SigIdx;return newbase.fromBuffer(this.toBuffer()),newbase}create(...args){return new SigIdx}}exports.SigIdx=SigIdx;class Signature extends nbytes_1.NBytes{constructor(){super(),this._typeName="Signature",this._typeID=void 0,this.bytes=buffer_1.Buffer.alloc(65),this.bsize=65}clone(){let newbase=new Signature;return newbase.fromBuffer(this.toBuffer()),newbase}create(...args){return new Signature}}exports.Signature=Signature;class Credential extends serialization_1.Serializable{constructor(sigarray){super(),this._typeName="Credential",this._typeID=void 0,this.sigArray=[],this.addSignature=sig=>(this.sigArray.push(sig),this.sigArray.length-1),void 0!==sigarray&&(this.sigArray=sigarray)}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{sigArray:this.sigArray.map((s=>s.serialize(encoding)))})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.sigArray=fields.sigArray.map((s=>{let sig=new Signature;return sig.deserialize(s,encoding),sig}))}setCodecID(codecID){}fromBuffer(bytes,offset=0){const siglen=bintools.copyFrom(bytes,offset,offset+4).readUInt32BE(0);offset+=4,this.sigArray=[];for(let i=0;i{if(input.getInput()instanceof input_1.StandardAmountInput&&aIDHex===input.getAssetID().toString("hex")){const i=input.getInput();total=total.add(i.getAmount())}})),total}getOutputTotal(assetID){const aIDHex=assetID.toString("hex");let total=new bn_js_1.default(0);return[].forEach((out=>{if(out.getOutput()instanceof output_1.StandardAmountOutput&&aIDHex===out.getAssetID().toString("hex")){const output=out.getOutput();total=total.add(output.getAmount())}})),total}getBurn(assetID){return this.getInputTotal(assetID).sub(this.getOutputTotal(assetID))}toBuffer(){const codecID=this.getCodecIDBuffer(),txtype=buffer_1.Buffer.alloc(4);txtype.writeUInt32BE(this.transaction.getTxType(),0);const basebuff=this.transaction.toBuffer();return buffer_1.Buffer.concat([codecID,txtype,basebuff],codecID.length+txtype.length+basebuff.length)}}exports.EVMStandardUnsignedTx=EVMStandardUnsignedTx;class EVMStandardTx extends serialization_1.Serializable{constructor(unsignedTx,credentials){super(),this._typeName="StandardTx",this._typeID=void 0,this.unsignedTx=void 0,this.credentials=[],void 0!==unsignedTx&&(this.unsignedTx=unsignedTx,void 0!==credentials&&(this.credentials=credentials))}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{unsignedTx:this.unsignedTx.serialize(encoding),credentials:this.credentials.map((c=>c.serialize(encoding)))})}getUnsignedTx(){return this.unsignedTx}toBuffer(){const txbuff=this.unsignedTx.toBuffer();let bsize=txbuff.length;const credlen=buffer_1.Buffer.alloc(4);credlen.writeUInt32BE(this.credentials.length,0);const barr=[txbuff,credlen];bsize+=credlen.length,this.credentials.forEach((credential=>{const credid=buffer_1.Buffer.alloc(4);credid.writeUInt32BE(credential.getCredentialID(),0),barr.push(credid),bsize+=credid.length;const credbuff=credential.toBuffer();bsize+=credbuff.length,barr.push(credbuff)}));return buffer_1.Buffer.concat(barr,bsize)}fromString(serialized){return this.fromBuffer(bintools.cb58Decode(serialized))}toString(){return bintools.cb58Encode(this.toBuffer())}toStringHex(){return`0x${bintools.addChecksum(this.toBuffer()).toString("hex")}`}}exports.EVMStandardTx=EVMStandardTx},999:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)"default"===p||Object.prototype.hasOwnProperty.call(exports,p)||__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:!0}),__exportStar(__webpack_require__(17),exports),__exportStar(__webpack_require__(6305),exports),__exportStar(__webpack_require__(5375),exports),__exportStar(__webpack_require__(7965),exports),__exportStar(__webpack_require__(1149),exports),__exportStar(__webpack_require__(5277),exports),__exportStar(__webpack_require__(5912),exports),__exportStar(__webpack_require__(62),exports),__exportStar(__webpack_require__(4263),exports),__exportStar(__webpack_require__(8556),exports),__exportStar(__webpack_require__(5534),exports),__exportStar(__webpack_require__(181),exports),__exportStar(__webpack_require__(613),exports),__exportStar(__webpack_require__(7612),exports)},1149:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.StandardAmountInput=exports.StandardTransferableInput=exports.StandardParseableInput=exports.Input=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),bn_js_1=__importDefault(__webpack_require__(3550)),credentials_1=__webpack_require__(5375),serialization_1=__webpack_require__(555),bintools=bintools_1.default.getInstance(),serialization=serialization_1.Serialization.getInstance();class Input extends serialization_1.Serializable{constructor(){super(...arguments),this._typeName="Input",this._typeID=void 0,this.sigCount=buffer_1.Buffer.alloc(4),this.sigIdxs=[],this.getSigIdxs=()=>this.sigIdxs,this.addSignatureIdx=(addressIdx,address)=>{const sigidx=new credentials_1.SigIdx,b=buffer_1.Buffer.alloc(4);b.writeUInt32BE(addressIdx,0),sigidx.fromBuffer(b),sigidx.setSource(address),this.sigIdxs.push(sigidx),this.sigCount.writeUInt32BE(this.sigIdxs.length,0)}}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{sigIdxs:this.sigIdxs.map((s=>s.serialize(encoding)))})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.sigIdxs=fields.sigIdxs.map((s=>{let sidx=new credentials_1.SigIdx;return sidx.deserialize(s,encoding),sidx})),this.sigCount.writeUInt32BE(this.sigIdxs.length,0)}fromBuffer(bytes,offset=0){this.sigCount=bintools.copyFrom(bytes,offset,offset+4),offset+=4;const sigCount=this.sigCount.readUInt32BE(0);this.sigIdxs=[];for(let i=0;i(a,b)=>{const aoutid=buffer_1.Buffer.alloc(4);aoutid.writeUInt32BE(a.getInputID(),0);const abuff=a.toBuffer(),boutid=buffer_1.Buffer.alloc(4);boutid.writeUInt32BE(b.getInputID(),0);const bbuff=b.toBuffer(),asort=buffer_1.Buffer.concat([aoutid,abuff],aoutid.length+abuff.length),bsort=buffer_1.Buffer.concat([boutid,bbuff],boutid.length+bbuff.length);return buffer_1.Buffer.compare(asort,bsort)};class StandardParseableInput extends serialization_1.Serializable{constructor(input){super(),this._typeName="StandardParseableInput",this._typeID=void 0,this.getInput=()=>this.input,input instanceof Input&&(this.input=input)}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{input:this.input.serialize(encoding)})}toBuffer(){const inbuff=this.input.toBuffer(),inid=buffer_1.Buffer.alloc(4);inid.writeUInt32BE(this.input.getInputID(),0);const barr=[inid,inbuff];return buffer_1.Buffer.concat(barr,inid.length+inbuff.length)}}exports.StandardParseableInput=StandardParseableInput,StandardParseableInput.comparator=()=>(a,b)=>{const sorta=a.toBuffer(),sortb=b.toBuffer();return buffer_1.Buffer.compare(sorta,sortb)};exports.StandardTransferableInput=class StandardTransferableInput extends StandardParseableInput{constructor(txid,outputidx,assetID,input){super(),this._typeName="StandardTransferableInput",this._typeID=void 0,this.txid=buffer_1.Buffer.alloc(32),this.outputidx=buffer_1.Buffer.alloc(4),this.assetID=buffer_1.Buffer.alloc(32),this.getTxID=()=>this.txid,this.getOutputIdx=()=>this.outputidx,this.getUTXOID=()=>bintools.bufferToB58(buffer_1.Buffer.concat([this.txid,this.outputidx])),this.getInput=()=>this.input,this.getAssetID=()=>this.assetID,void 0!==txid&&void 0!==outputidx&&void 0!==assetID&&input instanceof Input&&(this.input=input,this.txid=txid,this.outputidx=outputidx,this.assetID=assetID)}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{txid:serialization.encoder(this.txid,encoding,"Buffer","cb58"),outputidx:serialization.encoder(this.outputidx,encoding,"Buffer","decimalString"),assetID:serialization.encoder(this.assetID,encoding,"Buffer","cb58")})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.txid=serialization.decoder(fields.txid,encoding,"cb58","Buffer",32),this.outputidx=serialization.decoder(fields.outputidx,encoding,"decimalString","Buffer",4),this.assetID=serialization.decoder(fields.assetID,encoding,"cb58","Buffer",32)}toBuffer(){const parseableBuff=super.toBuffer(),bsize=this.txid.length+this.outputidx.length+this.assetID.length+parseableBuff.length,barr=[this.txid,this.outputidx,this.assetID,parseableBuff];return buffer_1.Buffer.concat(barr,bsize)}toString(){return bintools.bufferToB58(this.toBuffer())}};exports.StandardAmountInput=class StandardAmountInput extends Input{constructor(amount){super(),this._typeName="StandardAmountInput",this._typeID=void 0,this.amount=buffer_1.Buffer.alloc(8),this.amountValue=new bn_js_1.default(0),this.getAmount=()=>this.amountValue.clone(),amount&&(this.amountValue=amount.clone(),this.amount=bintools.fromBNToBuffer(amount,8))}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{amount:serialization.encoder(this.amount,encoding,"Buffer","decimalString",8)})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.amount=serialization.decoder(fields.amount,encoding,"decimalString","Buffer",8),this.amountValue=bintools.fromBufferToBN(this.amount)}fromBuffer(bytes,offset=0){return this.amount=bintools.copyFrom(bytes,offset,offset+8),this.amountValue=bintools.fromBufferToBN(this.amount),offset+=8,super.fromBuffer(bytes,offset)}toBuffer(){const superbuff=super.toBuffer(),bsize=this.amount.length+superbuff.length,barr=[this.amount,superbuff];return buffer_1.Buffer.concat(barr,bsize)}}},5277:(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0})},5912:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.JRPCAPI=void 0;const utils_1=__webpack_require__(338),apibase_1=__webpack_require__(17);class JRPCAPI extends apibase_1.APIBase{constructor(core,baseURL,jrpcVersion="2.0"){super(core,baseURL),this.jrpcVersion="2.0",this.rpcID=1,this.callMethod=(method,params,baseURL,headers)=>__awaiter(this,void 0,void 0,(function*(){const ep=baseURL||this.baseURL,rpc={};rpc.id=this.rpcID,rpc.method=method,params?rpc.params=params:"1.0"===this.jrpcVersion&&(rpc.params=[]),"1.0"!==this.jrpcVersion&&(rpc.jsonrpc=this.jrpcVersion);let headrs={"Content-Type":"application/json;charset=UTF-8"};headers&&(headrs=Object.assign(Object.assign({},headrs),headers));const axConf={baseURL:baseURL=this.core.getURL(),responseType:"json",adapter:"undefined"!=typeof fetch?utils_1.fetchAdapter:void 0},resp=yield this.core.post(ep,{},JSON.stringify(rpc),headrs,axConf);if(resp.status>=200&&resp.status<300&&(this.rpcID+=1,"string"==typeof resp.data&&(resp.data=JSON.parse(resp.data)),"object"==typeof resp.data&&(null===resp.data||"error"in resp.data)))throw new Error(resp.data.error.message);return resp})),this.getRPCID=()=>this.rpcID,this.jrpcVersion=jrpcVersion,this.rpcID=1}}exports.JRPCAPI=JRPCAPI},62:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.StandardKeyChain=exports.StandardKeyPair=void 0;const buffer_1=__webpack_require__(8764);exports.StandardKeyPair=class StandardKeyPair{getPrivateKey(){return this.privk}getPublicKey(){return this.pubk}};exports.StandardKeyChain=class StandardKeyChain{constructor(){this.keys={},this.getAddresses=()=>Object.values(this.keys).map((kp=>kp.getAddress())),this.getAddressStrings=()=>Object.values(this.keys).map((kp=>kp.getAddressString())),this.removeKey=key=>{let kaddr;return kaddr=key instanceof buffer_1.Buffer?key.toString("hex"):key.getAddress().toString("hex"),kaddr in this.keys&&(delete this.keys[`${kaddr}`],!0)},this.hasKey=address=>address.toString("hex")in this.keys,this.getKey=address=>this.keys[address.toString("hex")]}addKey(newKey){this.keys[newKey.getAddress().toString("hex")]=newKey}}},4263:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.NBytes=void 0;const bintools_1=__importDefault(__webpack_require__(903)),serialization_1=__webpack_require__(555),errors_1=__webpack_require__(611),bintools=bintools_1.default.getInstance(),serialization=serialization_1.Serialization.getInstance();class NBytes extends serialization_1.Serializable{constructor(){super(...arguments),this._typeName="NBytes",this._typeID=void 0,this.getSize=()=>this.bsize}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{bsize:serialization.encoder(this.bsize,encoding,"number","decimalString",4),bytes:serialization.encoder(this.bytes,encoding,"Buffer","hex",this.bsize)})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.bsize=serialization.decoder(fields.bsize,encoding,"decimalString","number",4),this.bytes=serialization.decoder(fields.bytes,encoding,"hex","Buffer",this.bsize)}fromString(b58str){try{this.fromBuffer(bintools.b58ToBuffer(b58str))}catch(e){throw new Error(`Error - NBytes.fromString: ${e}`)}return this.bsize}fromBuffer(buff,offset=0){try{if(buff.length-offset(a,b)=>buffer_1.Buffer.compare(a.toBuffer(),b.toBuffer());class OutputOwners extends serialization_1.Serializable{constructor(addresses,locktime,threshold){if(super(),this._typeName="OutputOwners",this._typeID=void 0,this.locktime=buffer_1.Buffer.alloc(8),this.threshold=buffer_1.Buffer.alloc(4),this.numaddrs=buffer_1.Buffer.alloc(4),this.addresses=[],this.getThreshold=()=>this.threshold.readUInt32BE(0),this.getLocktime=()=>bintools.fromBufferToBN(this.locktime),this.getAddresses=()=>{const result=[];for(let i=0;i{for(let i=0;i{if(idx{let now;now=void 0===asOf?(0,helperfunctions_1.UnixNow)():asOf;const qualified=this.getSpenders(addresses,now),threshold=this.threshold.readUInt32BE(0);return qualified.length>=threshold},this.getSpenders=(addresses,asOf)=>{const qualified=[];let now;now=void 0===asOf?(0,helperfunctions_1.UnixNow)():asOf;const locktime=bintools.fromBufferToBN(this.locktime);if(now.lte(locktime))return qualified;const threshold=this.threshold.readUInt32BE(0);for(let i=0;ia.serialize(encoding)))})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.locktime=serialization.decoder(fields.locktime,encoding,"decimalString","Buffer",8),this.threshold=serialization.decoder(fields.threshold,encoding,"decimalString","Buffer",4),this.addresses=fields.addresses.map((a=>{let addr=new Address;return addr.deserialize(a,encoding),addr})),this.numaddrs=buffer_1.Buffer.alloc(4),this.numaddrs.writeUInt32BE(this.addresses.length,0)}fromBuffer(bytes,offset=0){this.locktime=bintools.copyFrom(bytes,offset,offset+8),offset+=8,this.threshold=bintools.copyFrom(bytes,offset,offset+4),offset+=4,this.numaddrs=bintools.copyFrom(bytes,offset,offset+4),offset+=4;const numaddrs=this.numaddrs.readUInt32BE(0);this.addresses=[];for(let i=0;i(a,b)=>{const aoutid=buffer_1.Buffer.alloc(4);aoutid.writeUInt32BE(a.getOutputID(),0);const abuff=a.toBuffer(),boutid=buffer_1.Buffer.alloc(4);boutid.writeUInt32BE(b.getOutputID(),0);const bbuff=b.toBuffer(),asort=buffer_1.Buffer.concat([aoutid,abuff],aoutid.length+abuff.length),bsort=buffer_1.Buffer.concat([boutid,bbuff],boutid.length+bbuff.length);return buffer_1.Buffer.compare(asort,bsort)};class Output extends OutputOwners{constructor(){super(...arguments),this._typeName="Output",this._typeID=void 0}}exports.Output=Output;class StandardParseableOutput extends serialization_1.Serializable{constructor(output){super(),this._typeName="StandardParseableOutput",this._typeID=void 0,this.getOutput=()=>this.output,output instanceof Output&&(this.output=output)}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{output:this.output.serialize(encoding)})}toBuffer(){const outbuff=this.output.toBuffer(),outid=buffer_1.Buffer.alloc(4);outid.writeUInt32BE(this.output.getOutputID(),0);const barr=[outid,outbuff];return buffer_1.Buffer.concat(barr,outid.length+outbuff.length)}}exports.StandardParseableOutput=StandardParseableOutput,StandardParseableOutput.comparator=()=>(a,b)=>{const sorta=a.toBuffer(),sortb=b.toBuffer();return buffer_1.Buffer.compare(sorta,sortb)};exports.StandardTransferableOutput=class StandardTransferableOutput extends StandardParseableOutput{constructor(assetID,output){super(output),this._typeName="StandardTransferableOutput",this._typeID=void 0,this.assetID=void 0,this.getAssetID=()=>this.assetID,void 0!==assetID&&(this.assetID=assetID)}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{assetID:serialization.encoder(this.assetID,encoding,"Buffer","cb58")})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.assetID=serialization.decoder(fields.assetID,encoding,"cb58","Buffer",32)}toBuffer(){const parseableBuff=super.toBuffer(),barr=[this.assetID,parseableBuff];return buffer_1.Buffer.concat(barr,this.assetID.length+parseableBuff.length)}};exports.StandardAmountOutput=class StandardAmountOutput extends Output{constructor(amount,addresses,locktime,threshold){super(addresses,locktime,threshold),this._typeName="StandardAmountOutput",this._typeID=void 0,this.amount=buffer_1.Buffer.alloc(8),this.amountValue=new bn_js_1.default(0),void 0!==amount&&(this.amountValue=amount.clone(),this.amount=bintools.fromBNToBuffer(amount,8))}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{amount:serialization.encoder(this.amount,encoding,"Buffer","decimalString",8)})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.amount=serialization.decoder(fields.amount,encoding,"decimalString","Buffer",8),this.amountValue=bintools.fromBufferToBN(this.amount)}getAmount(){return this.amountValue.clone()}fromBuffer(outbuff,offset=0){return this.amount=bintools.copyFrom(outbuff,offset,offset+8),this.amountValue=bintools.fromBufferToBN(this.amount),offset+=8,super.fromBuffer(outbuff,offset)}toBuffer(){const superbuff=super.toBuffer(),bsize=this.amount.length+superbuff.length;this.numaddrs.writeUInt32BE(this.addresses.length,0);const barr=[this.amount,superbuff];return buffer_1.Buffer.concat(barr,bsize)}};exports.BaseNFTOutput=class BaseNFTOutput extends Output{constructor(){super(...arguments),this._typeName="BaseNFTOutput",this._typeID=void 0,this.groupID=buffer_1.Buffer.alloc(4),this.getGroupID=()=>this.groupID.readUInt32BE(0)}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{groupID:serialization.encoder(this.groupID,encoding,"Buffer","decimalString",4)})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.groupID=serialization.decoder(fields.groupID,encoding,"decimalString","Buffer",4)}}},5534:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0}),exports.RESTAPI=void 0;const apibase_1=__webpack_require__(17);class RESTAPI extends apibase_1.APIBase{constructor(core,baseURL,contentType="application/json;charset=UTF-8",acceptType){super(core,baseURL),this.prepHeaders=(contentType,acceptType)=>{const headers={};return headers["Content-Type"]=void 0!==contentType?contentType:this.contentType,void 0!==acceptType?headers.Accept=acceptType:void 0!==this.acceptType&&(headers.Accept=this.acceptType),headers},this.axConf=()=>({baseURL:this.core.getURL(),responseType:"json"}),this.get=(baseURL,contentType,acceptType)=>__awaiter(this,void 0,void 0,(function*(){const ep=baseURL||this.baseURL,headers=this.prepHeaders(contentType,acceptType);return yield this.core.get(ep,{},headers,this.axConf())})),this.post=(method,params,baseURL,contentType,acceptType)=>__awaiter(this,void 0,void 0,(function*(){const ep=baseURL||this.baseURL,rpc={};rpc.method=method,params&&(rpc.params=params);const headers=this.prepHeaders(contentType,acceptType);return yield this.core.post(ep,{},JSON.stringify(rpc),headers,this.axConf())})),this.put=(method,params,baseURL,contentType,acceptType)=>__awaiter(this,void 0,void 0,(function*(){const ep=baseURL||this.baseURL,rpc={};rpc.method=method,params&&(rpc.params=params);const headers=this.prepHeaders(contentType,acceptType);return yield this.core.put(ep,{},JSON.stringify(rpc),headers,this.axConf())})),this.delete=(method,params,baseURL,contentType,acceptType)=>__awaiter(this,void 0,void 0,(function*(){const ep=baseURL||this.baseURL,rpc={};rpc.method=method,params&&(rpc.params=params);const headers=this.prepHeaders(contentType,acceptType);return yield this.core.delete(ep,{},headers,this.axConf())})),this.patch=(method,params,baseURL,contentType,acceptType)=>__awaiter(this,void 0,void 0,(function*(){const ep=baseURL||this.baseURL,rpc={};rpc.method=method,params&&(rpc.params=params);const headers=this.prepHeaders(contentType,acceptType);return yield this.core.patch(ep,{},JSON.stringify(rpc),headers,this.axConf())})),this.getContentType=()=>this.contentType,this.getAcceptType=()=>this.acceptType,this.contentType=contentType,this.acceptType=acceptType}}exports.RESTAPI=RESTAPI},181:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=this&&this.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(null!=mod)for(var k in mod)"default"!==k&&Object.prototype.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.SECP256k1KeyChain=exports.SECP256k1KeyPair=void 0;const buffer_1=__webpack_require__(8764),elliptic=__importStar(__webpack_require__(6266)),create_hash_1=__importDefault(__webpack_require__(3482)),bintools_1=__importDefault(__webpack_require__(903)),keychain_1=__webpack_require__(62),errors_1=__webpack_require__(611),utils_1=__webpack_require__(338),ec=new(0,elliptic.ec)("secp256k1"),BN=ec.curve.n.constructor,bintools=bintools_1.default.getInstance(),serialization=utils_1.Serialization.getInstance();class SECP256k1KeyPair extends keychain_1.StandardKeyPair{constructor(hrp,chainID){super(),this.chainID="",this.hrp="",this.chainID=chainID,this.hrp=hrp,this.generateKey()}_sigFromSigBuffer(sig){return{r:new BN(bintools.copyFrom(sig,0,32)),s:new BN(bintools.copyFrom(sig,32,64)),recoveryParam:bintools.copyFrom(sig,64,65).readUIntBE(0,1)}}generateKey(){this.keypair=ec.genKeyPair(),this.privk=buffer_1.Buffer.from(this.keypair.getPrivate("hex").padStart(64,"0"),"hex"),this.pubk=buffer_1.Buffer.from(this.keypair.getPublic(!0,"hex").padStart(66,"0"),"hex")}importKey(privk){this.keypair=ec.keyFromPrivate(privk.toString("hex"),"hex");try{return this.privk=buffer_1.Buffer.from(this.keypair.getPrivate("hex").padStart(64,"0"),"hex"),this.pubk=buffer_1.Buffer.from(this.keypair.getPublic(!0,"hex").padStart(66,"0"),"hex"),!0}catch(error){return!1}}getAddress(){return SECP256k1KeyPair.addressFromPublicKey(this.pubk)}getAddressString(){const addr=SECP256k1KeyPair.addressFromPublicKey(this.pubk);return serialization.bufferToType(addr,"bech32",this.hrp,this.chainID)}static addressFromPublicKey(pubk){if(65===pubk.length&&(pubk=buffer_1.Buffer.from(ec.keyFromPublic(pubk).getPublic(!0,"hex").padStart(66,"0"),"hex")),33===pubk.length){const sha256=buffer_1.Buffer.from((0,create_hash_1.default)("sha256").update(pubk).digest());return buffer_1.Buffer.from((0,create_hash_1.default)("ripemd160").update(sha256).digest())}throw new errors_1.PublicKeyError("Unable to make address.")}getPrivateKeyString(){return`PrivateKey-${bintools.cb58Encode(this.privk)}`}getPublicKeyString(){return bintools.cb58Encode(this.pubk)}sign(msg){const sigObj=this.keypair.sign(msg,void 0,{canonical:!0}),recovery=buffer_1.Buffer.alloc(1);recovery.writeUInt8(sigObj.recoveryParam,0);const r=buffer_1.Buffer.from(sigObj.r.toArray("be",32)),s=buffer_1.Buffer.from(sigObj.s.toArray("be",32));return buffer_1.Buffer.concat([r,s,recovery],65)}verify(msg,sig){const sigObj=this._sigFromSigBuffer(sig);return ec.verify(msg,sigObj,this.keypair)}recover(msg,sig){const sigObj=this._sigFromSigBuffer(sig),pubk=ec.recoverPubKey(msg,sigObj,sigObj.recoveryParam);return buffer_1.Buffer.from(pubk.encodeCompressed())}getChainID(){return this.chainID}setChainID(chainID){this.chainID=chainID}getHRP(){return this.hrp}setHRP(hrp){this.hrp=hrp}}exports.SECP256k1KeyPair=SECP256k1KeyPair;class SECP256k1KeyChain extends keychain_1.StandardKeyChain{addKey(newKey){super.addKey(newKey)}}exports.SECP256k1KeyChain=SECP256k1KeyChain},613:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.StandardTx=exports.StandardUnsignedTx=exports.StandardBaseTx=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),bn_js_1=__importDefault(__webpack_require__(3550)),input_1=__webpack_require__(1149),output_1=__webpack_require__(8556),constants_1=__webpack_require__(8779),serialization_1=__webpack_require__(555),bintools=bintools_1.default.getInstance(),serialization=serialization_1.Serialization.getInstance();class StandardBaseTx extends serialization_1.Serializable{constructor(networkID=constants_1.DefaultNetworkID,blockchainID=buffer_1.Buffer.alloc(32,16),outs,ins,memo){super(),this._typeName="StandardBaseTx",this._typeID=void 0,this.networkID=buffer_1.Buffer.alloc(4),this.blockchainID=buffer_1.Buffer.alloc(32),this.numouts=buffer_1.Buffer.alloc(4),this.numins=buffer_1.Buffer.alloc(4),this.memo=buffer_1.Buffer.alloc(0),this.networkID.writeUInt32BE(networkID,0),this.blockchainID=blockchainID,void 0!==memo&&(this.memo=memo),void 0!==ins&&void 0!==outs&&(this.numouts.writeUInt32BE(outs.length,0),this.outs=outs.sort(output_1.StandardTransferableOutput.comparator()),this.numins.writeUInt32BE(ins.length,0),this.ins=ins.sort(input_1.StandardTransferableInput.comparator()))}serialize(encoding="hex"){const fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{networkID:serialization.encoder(this.networkID,encoding,"Buffer","decimalString"),blockchainID:serialization.encoder(this.blockchainID,encoding,"Buffer","cb58"),outs:this.outs.map((o=>o.serialize(encoding))),ins:this.ins.map((i=>i.serialize(encoding))),memo:serialization.encoder(this.memo,encoding,"Buffer","hex")})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.networkID=serialization.decoder(fields.networkID,encoding,"decimalString","Buffer",4),this.blockchainID=serialization.decoder(fields.blockchainID,encoding,"cb58","Buffer",32),this.memo=serialization.decoder(fields.memo,encoding,"hex","Buffer")}getNetworkID(){return this.networkID.readUInt32BE(0)}getBlockchainID(){return this.blockchainID}getMemo(){return this.memo}toBuffer(){this.outs.sort(output_1.StandardTransferableOutput.comparator()),this.ins.sort(input_1.StandardTransferableInput.comparator()),this.numouts.writeUInt32BE(this.outs.length,0),this.numins.writeUInt32BE(this.ins.length,0);let bsize=this.networkID.length+this.blockchainID.length+this.numouts.length;const barr=[this.networkID,this.blockchainID,this.numouts];for(let i=0;ic.serialize(encoding)))})}getCredentials(){return this.credentials}getUnsignedTx(){return this.unsignedTx}toBuffer(){const codecID=this.unsignedTx.getTransaction().getCodecID(),txbuff=this.unsignedTx.toBuffer();let bsize=txbuff.length;const credlen=buffer_1.Buffer.alloc(4);credlen.writeUInt32BE(this.credentials.length,0);const barr=[txbuff,credlen];bsize+=credlen.length;for(let i=0;ithis.codecID.readUInt8(0),this.getCodecIDBuffer=()=>this.codecID,this.getTxID=()=>this.txid,this.getOutputIdx=()=>this.outputidx,this.getAssetID=()=>this.assetID,this.getUTXOID=()=>bintools.bufferToB58(buffer_1.Buffer.concat([this.getTxID(),this.getOutputIdx()])),this.getOutput=()=>this.output,void 0!==codecID&&this.codecID.writeUInt8(codecID,0),void 0!==txID&&(this.txid=txID),"number"==typeof outputidx?this.outputidx.writeUInt32BE(outputidx,0):outputidx instanceof buffer_1.Buffer&&(this.outputidx=outputidx),void 0!==assetID&&(this.assetID=assetID),void 0!==output&&(this.output=output)}serialize(encoding="hex"){let fields=super.serialize(encoding);return Object.assign(Object.assign({},fields),{codecID:serialization.encoder(this.codecID,encoding,"Buffer","decimalString"),txid:serialization.encoder(this.txid,encoding,"Buffer","cb58"),outputidx:serialization.encoder(this.outputidx,encoding,"Buffer","decimalString"),assetID:serialization.encoder(this.assetID,encoding,"Buffer","cb58"),output:this.output.serialize(encoding)})}deserialize(fields,encoding="hex"){super.deserialize(fields,encoding),this.codecID=serialization.decoder(fields.codecID,encoding,"decimalString","Buffer",2),this.txid=serialization.decoder(fields.txid,encoding,"cb58","Buffer",32),this.outputidx=serialization.decoder(fields.outputidx,encoding,"decimalString","Buffer",4),this.assetID=serialization.decoder(fields.assetID,encoding,"cb58","Buffer",32)}toBuffer(){const outbuff=this.output.toBuffer(),outputidbuffer=buffer_1.Buffer.alloc(4);outputidbuffer.writeUInt32BE(this.output.getOutputID(),0);const barr=[this.codecID,this.txid,this.outputidx,this.assetID,outputidbuffer,outbuff];return buffer_1.Buffer.concat(barr,this.codecID.length+this.txid.length+this.outputidx.length+this.assetID.length+outputidbuffer.length+outbuff.length)}}exports.StandardUTXO=StandardUTXO;class StandardUTXOSet extends serialization_1.Serializable{constructor(){super(...arguments),this._typeName="StandardUTXOSet",this._typeID=void 0,this.utxos={},this.addressUTXOs={},this.includes=utxo=>{let utxoX,utxoid;try{utxoX=this.parseUTXO(utxo),utxoid=utxoX.getUTXOID()}catch(e){return e instanceof Error?console.log(e.message):console.log(e),!1}return utxoid in this.utxos},this.remove=utxo=>{let utxovar;try{utxovar=this.parseUTXO(utxo)}catch(e){return void(e instanceof Error?console.log(e.message):console.log(e))}const utxoid=utxovar.getUTXOID();if(!(utxoid in this.utxos))return;delete this.utxos[`${utxoid}`];const addresses=Object.keys(this.addressUTXOs);for(let i=0;i{const removed=[];for(let i=0;ithis.utxos[`${utxoid}`],this.getAllUTXOs=utxoids=>{let results=[];return results=void 0!==utxoids&&Array.isArray(utxoids)?utxoids.filter((utxoid=>this.utxos[`${utxoid}`])).map((utxoid=>this.utxos[`${utxoid}`])):Object.values(this.utxos),results},this.getAllUTXOStrings=utxoids=>{const results=[],utxos=Object.keys(this.utxos);if(void 0!==utxoids&&Array.isArray(utxoids))for(let i=0;i{if(void 0!==addresses){const results=[],now=(0,helperfunctions_1.UnixNow)();for(let i=0;iObject.keys(this.addressUTXOs).map((k=>buffer_1.Buffer.from(k,"hex"))),this.getBalance=(addresses,assetID,asOf)=>{const utxoids=this.getUTXOIDs(addresses),utxos=this.getAllUTXOs(utxoids);let asset,spend=new bn_js_1.default(0);asset="string"==typeof assetID?bintools.cb58Decode(assetID):assetID;for(let i=0;i{const results=new Set;let utxoids=[];utxoids=void 0!==addresses?this.getUTXOIDs(addresses):this.getUTXOIDs();for(let i=0;i{const results=this.create(),utxos1=this.getAllUTXOs(hasUTXOIDs),utxos2=utxoset.getAllUTXOs(hasUTXOIDs),process=utxo=>{results.add(utxo)};return utxos1.forEach(process),utxos2.forEach(process),results},this.intersection=utxoset=>{const us1=this.getUTXOIDs(),us2=utxoset.getUTXOIDs(),results=us1.filter((utxoid=>us2.includes(utxoid)));return this.merge(utxoset,results)},this.difference=utxoset=>{const us1=this.getUTXOIDs(),us2=utxoset.getUTXOIDs(),results=us1.filter((utxoid=>!us2.includes(utxoid)));return this.merge(utxoset,results)},this.symDifference=utxoset=>{const us1=this.getUTXOIDs(),us2=utxoset.getUTXOIDs(),results=us1.filter((utxoid=>!us2.includes(utxoid))).concat(us2.filter((utxoid=>!us1.includes(utxoid))));return this.merge(utxoset,results)},this.union=utxoset=>this.merge(utxoset),this.mergeByRule=(utxoset,mergeRule)=>{let uSet;switch(mergeRule){case"intersection":return this.intersection(utxoset);case"differenceSelf":return this.difference(utxoset);case"differenceNew":return utxoset.difference(this);case"symDifference":return this.symDifference(utxoset);case"union":return this.union(utxoset);case"unionMinusNew":return uSet=this.union(utxoset),uSet.difference(utxoset);case"unionMinusSelf":return uSet=this.union(utxoset),uSet.difference(this);default:throw new errors_1.MergeRuleError("Error - StandardUTXOSet.mergeByRule: bad MergeRule")}}}serialize(encoding="hex"){let fields=super.serialize(encoding),utxos={};for(let utxoid in this.utxos){utxos[`${serialization.encoder(utxoid,encoding,"base58","base58")}`]=this.utxos[`${utxoid}`].serialize(encoding)}let addressUTXOs={};for(let address in this.addressUTXOs){let addressCleaned=serialization.encoder(address,encoding,"hex","cb58"),utxobalance={};for(let utxoid in this.addressUTXOs[`${address}`]){utxobalance[`${serialization.encoder(utxoid,encoding,"base58","base58")}`]=serialization.encoder(this.addressUTXOs[`${address}`][`${utxoid}`],encoding,"BN","decimalString")}addressUTXOs[`${addressCleaned}`]=utxobalance}return Object.assign(Object.assign({},fields),{utxos,addressUTXOs})}add(utxo,overwrite=!1){let utxovar;try{utxovar=this.parseUTXO(utxo)}catch(e){return void(e instanceof Error?console.log(e.message):console.log(e))}const utxoid=utxovar.getUTXOID();if(!(utxoid in this.utxos)||!0===overwrite){this.utxos[`${utxoid}`]=utxovar;const addresses=utxovar.getOutput().getAddresses(),locktime=utxovar.getOutput().getLocktime();for(let i=0;ithis.apis.admin,this.Auth=()=>this.apis.auth,this.CChain=()=>this.apis.cchain,this.XChain=()=>this.apis.xchain,this.Health=()=>this.apis.health,this.Index=()=>this.apis.index,this.Info=()=>this.apis.info,this.Metrics=()=>this.apis.metrics,this.NodeKeys=()=>this.apis.keystore,this.PChain=()=>this.apis.pchain;let xchainid=XChainID,cchainid=CChainID;void 0!==XChainID&&XChainID&&"x"!==XChainID.toLowerCase()||(xchainid=networkID.toString()in constants_1.Defaults.network?constants_1.Defaults.network[`${networkID}`].X.blockchainID:constants_1.Defaults.network[12345].X.blockchainID),void 0!==CChainID&&CChainID&&"c"!==CChainID.toLowerCase()||(cchainid=networkID.toString()in constants_1.Defaults.network?constants_1.Defaults.network[`${networkID}`].C.blockchainID:constants_1.Defaults.network[12345].C.blockchainID),"number"==typeof networkID&&networkID>=0?this.networkID=networkID:void 0===networkID&&(networkID=constants_1.DefaultNetworkID),this.hrp=void 0!==hrp?hrp:(0,helperfunctions_1.getPreferredHRP)(this.networkID),skipinit||(this.addAPI("admin",api_1.AdminAPI),this.addAPI("auth",api_2.AuthAPI),this.addAPI("xchain",api_3.AVMAPI,"/ext/bc/X",xchainid),this.addAPI("cchain",api_4.EVMAPI,"/ext/bc/C/avax",cchainid),this.addAPI("health",api_5.HealthAPI),this.addAPI("info",api_7.InfoAPI),this.addAPI("index",api_6.IndexAPI),this.addAPI("keystore",api_8.KeystoreAPI),this.addAPI("metrics",api_9.MetricsAPI),this.addAPI("pchain",api_10.PlatformVMAPI))}}exports.default=Avalanche,exports.Avalanche=Avalanche,exports.admin=__importStar(__webpack_require__(7458)),exports.auth=__importStar(__webpack_require__(7843)),exports.avm=__importStar(__webpack_require__(7996)),exports.common=__importStar(__webpack_require__(999)),exports.evm=__importStar(__webpack_require__(5743)),exports.health=__importStar(__webpack_require__(1996)),exports.index=__importStar(__webpack_require__(6119)),exports.info=__importStar(__webpack_require__(8379)),exports.keystore=__importStar(__webpack_require__(913)),exports.metrics=__importStar(__webpack_require__(6413)),exports.platformvm=__importStar(__webpack_require__(7679)),exports.utils=__importStar(__webpack_require__(338))},978:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.Base58=void 0;const bn_js_1=__importDefault(__webpack_require__(3550)),buffer_1=__webpack_require__(8764),errors_1=__webpack_require__(611);class Base58{constructor(){this.b58alphabet="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",this.alphabetIdx0="1",this.b58=[255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,1,2,3,4,5,6,7,8,255,255,255,255,255,255,255,9,10,11,12,13,14,15,16,255,17,18,19,20,21,255,22,23,24,25,26,27,28,29,30,31,32,255,255,255,255,255,255,33,34,35,36,37,38,39,40,41,42,43,255,44,45,46,47,48,49,50,51,52,53,54,55,56,57,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255],this.big58Radix=new bn_js_1.default(58),this.bigZero=new bn_js_1.default(0),this.encode=buff=>{let x=new bn_js_1.default(buff.toString("hex"),"hex","be"),answer="";for(;x.cmp(this.bigZero)>0;){const mod=x.mod(this.big58Radix);x=x.div(this.big58Radix),answer+=this.b58alphabet[mod.toNumber()]}for(let i=0;i{const answer=new bn_js_1.default(0),j=new bn_js_1.default(1);for(let i=b.length-1;i>=0;i--){const tmp=this.b58[b.charCodeAt(i)];if(255===tmp)throw new errors_1.Base58Error("Error - Base58.decode: not a valid base58 string");const scratch=new bn_js_1.default(tmp);scratch.imul(j),answer.iadd(scratch),j.imul(this.big58Radix)}let anshex=answer.toString("hex");anshex=anshex.length%2?`0${anshex}`:anshex;const tmpval=buffer_1.Buffer.from(anshex,"hex");let numZeros;for(numZeros=0;numZeros{const parts=address.trim().split("-");if(2!==parts.length)return!1;try{bech32.bech32.fromWords(bech32.bech32.decode(parts[1]).words)}catch(err){return!1}return!0},this.bufferToString=buff=>this.copyFrom(buff,2).toString("utf8"),this.stringToBuffer=str=>{const buff=buffer_1.Buffer.alloc(2+str.length);return buff.writeUInt16BE(str.length,0),buff.write(str,2,str.length,"utf8"),buff},this.copyFrom=(buff,start=0,end)=>(void 0===end&&(end=buff.length),buffer_1.Buffer.from(Uint8Array.prototype.slice.call(buff.slice(start,end)))),this.bufferToB58=buff=>this.b58.encode(buff),this.b58ToBuffer=b58str=>this.b58.decode(b58str),this.fromBufferToArrayBuffer=buff=>{const ab=new ArrayBuffer(buff.length),view=new Uint8Array(ab);for(let i=0;i{const buf=buffer_1.Buffer.alloc(ab.byteLength);for(let i=0;i{if(void 0!==buff)return new bn_js_1.default(buff.toString("hex"),16,"be")},this.fromBNToBuffer=(bn,length)=>{if(void 0===bn)return;const newarr=bn.toArray("be");if(length){const x=length-newarr.length;for(let i=0;i{const hashslice=buffer_1.Buffer.from((0,create_hash_1.default)("sha256").update(buff).digest().slice(28));return buffer_1.Buffer.concat([buff,hashslice])},this.validateChecksum=buff=>{const checkslice=buff.slice(buff.length-4),hashslice=buffer_1.Buffer.from((0,create_hash_1.default)("sha256").update(buff.slice(0,buff.length-4)).digest().slice(28));return checkslice.toString("hex")===hashslice.toString("hex")},this.cb58Encode=bytes=>{const x=this.addChecksum(bytes);return this.bufferToB58(x)},this.cb58Decode=bytes=>{if("string"==typeof bytes&&(bytes=this.b58ToBuffer(bytes)),this.validateChecksum(bytes))return this.copyFrom(bytes,0,bytes.length-4);throw new errors_1.ChecksumError("Error - BinTools.cb58Decode: invalid checksum")},this.cb58DecodeWithChecksum=bytes=>{if("string"==typeof bytes&&(bytes=this.b58ToBuffer(bytes)),this.validateChecksum(bytes))return`0x${this.copyFrom(bytes,0,bytes.length).toString("hex")}`;throw new errors_1.ChecksumError("Error - BinTools.cb58Decode: invalid checksum")},this.addressToString=(hrp,chainid,bytes)=>`${chainid}-${bech32.bech32.encode(hrp,bech32.bech32.toWords(bytes))}`,this.stringToAddress=(address,hrp)=>{if("0x"===address.substring(0,2)){if(ethers_1.utils.isAddress(address))return buffer_1.Buffer.from(address.substring(2),"hex");throw new errors_1.HexError("Error - Invalid address")}const parts=address.trim().split("-");if(parts.length<2)throw new errors_1.Bech32Error("Error - Valid address should include -");if(parts[0].length<1)throw new errors_1.Bech32Error("Error - Valid address must have prefix before -");const split=parts[1].lastIndexOf("1");if(split<0)throw new errors_1.Bech32Error("Error - Valid address must include separator (1)");const humanReadablePart=parts[1].slice(0,split);if(humanReadablePart.length<1)throw new errors_1.Bech32Error("Error - HRP should be at least 1 character");if("avax"!==humanReadablePart&&"fuji"!==humanReadablePart&&"local"!=humanReadablePart&&"custom"!=humanReadablePart&&humanReadablePart!=hrp)throw new errors_1.Bech32Error("Error - Invalid HRP");return buffer_1.Buffer.from(bech32.bech32.fromWords(bech32.bech32.decode(parts[1]).words))},this.parseAddress=(addr,blockchainID,alias,addrlen=20)=>{const abc=addr.split("-");if(2===abc.length&&(alias&&abc[0]===alias||blockchainID&&abc[0]===blockchainID)){const addrbuff=this.stringToAddress(addr);if(addrlen&&addrbuff.length===addrlen||!addrlen)return addrbuff}},this.b58=base58_1.Base58.getInstance()}static getInstance(){return BinTools.instance||(BinTools.instance=new BinTools),BinTools.instance}isBase64(str){if(""===str||""===str.trim())return!1;try{return buffer_1.Buffer.from(str,"base64").toString("base64")===str}catch(err){return!1}}isCB58(cb58){return this.isBase58(cb58)}isBase58(base58){if(""===base58||""===base58.trim())return!1;try{return this.b58.encode(this.b58.decode(base58))===base58}catch(err){return!1}}isHex(hex){if(""===hex||""===hex.trim())return!1;const startsWith0x=hex.startsWith("0x"),matchResult=startsWith0x?hex.slice(2).match(/[0-9A-Fa-f]/g):hex.match(/[0-9A-Fa-f]/g);return!!(startsWith0x&&hex.length-2==matchResult.length||hex.length==matchResult.length)}isDecimal(str){if(""===str||""===str.trim())return!1;try{return new bn_js_1.default(str,10).toString(10)===str.trim()}catch(err){return!1}}}exports.default=BinTools},8779:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.Defaults=exports.AVAXSTAKECAP=exports.AVAXGWEI=exports.GWEI=exports.WEI=exports.NANOAVAX=exports.MICROAVAX=exports.MILLIAVAX=exports.CENTIAVAX=exports.DECIAVAX=exports.ONEAVAX=exports.mnemonic=exports.DefaultEVMLocalGenesisAddress=exports.DefaultEVMLocalGenesisPrivateKey=exports.DefaultLocalGenesisPrivateKey=exports.PChainVMName=exports.CChainVMName=exports.XChainVMName=exports.PChainAlias=exports.CChainAlias=exports.XChainAlias=exports.PrimaryNetworkID=exports.PlatformChainID=exports.DefaultNetworkID=exports.FallbackEVMChainID=exports.FallbackNetworkName=exports.FallbackHRP=exports.NetworkNameToNetworkID=exports.NetworkIDToNetworkNames=exports.HRPToNetworkID=exports.NetworkIDToHRP=exports.FujiAPI=exports.MainnetAPI=exports.PrimaryAssetAlias=exports.NodeIDPrefix=exports.PrivateKeyPrefix=void 0;const bn_js_1=__importDefault(__webpack_require__(3550));exports.PrivateKeyPrefix="PrivateKey-",exports.NodeIDPrefix="NodeID-",exports.PrimaryAssetAlias="AVAX",exports.MainnetAPI="api.avax.network",exports.FujiAPI="api.avax-test.network",exports.NetworkIDToHRP={0:"custom",1:"avax",2:"cascade",3:"denali",4:"everest",5:"fuji",1337:"custom",12345:"local"},exports.HRPToNetworkID={manhattan:0,avax:1,cascade:2,denali:3,everest:4,fuji:5,custom:1337,local:12345},exports.NetworkIDToNetworkNames={0:["Manhattan"],1:["Avalanche","Mainnet"],2:["Cascade"],3:["Denali"],4:["Everest"],5:["Fuji","Testnet"],1337:["Custom Network"],12345:["Local Network"]},exports.NetworkNameToNetworkID={Manhattan:0,Avalanche:1,Mainnet:1,Cascade:2,Denali:3,Everest:4,Fuji:5,Testnet:5,Custom:1337,"Custom Network":1337,Local:12345,"Local Network":12345},exports.FallbackHRP="custom",exports.FallbackNetworkName="Custom Network",exports.FallbackEVMChainID=43112,exports.DefaultNetworkID=1,exports.PlatformChainID="11111111111111111111111111111111LpoYY",exports.PrimaryNetworkID="11111111111111111111111111111111LpoYY",exports.XChainAlias="X",exports.CChainAlias="C",exports.PChainAlias="P",exports.XChainVMName="avm",exports.CChainVMName="evm",exports.PChainVMName="platformvm",exports.DefaultLocalGenesisPrivateKey="ewoqjP7PxY4yr3iLTpLisriqt94hdyDFNgchSxGGztUrTXtNN",exports.DefaultEVMLocalGenesisPrivateKey="0x56289e99c94b6912bfc12adc093c9b51124f0dc54ac7a766b2bc5ccf558d8027",exports.DefaultEVMLocalGenesisAddress="0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC",exports.mnemonic="output tooth keep tooth bracket fox city sustain blood raise install pond stem reject long scene clap gloom purpose mean music piece unknown light",exports.ONEAVAX=new bn_js_1.default(1e9),exports.DECIAVAX=exports.ONEAVAX.div(new bn_js_1.default(10)),exports.CENTIAVAX=exports.ONEAVAX.div(new bn_js_1.default(100)),exports.MILLIAVAX=exports.ONEAVAX.div(new bn_js_1.default(1e3)),exports.MICROAVAX=exports.ONEAVAX.div(new bn_js_1.default(1e6)),exports.NANOAVAX=exports.ONEAVAX.div(new bn_js_1.default(1e9)),exports.WEI=new bn_js_1.default(1),exports.GWEI=exports.WEI.mul(new bn_js_1.default(1e9)),exports.AVAXGWEI=exports.NANOAVAX.clone(),exports.AVAXSTAKECAP=exports.ONEAVAX.mul(new bn_js_1.default(3e6));const n0X={blockchainID:"2vrXWHgGxh5n3YsLHMV16YVVJTpT4z45Fmb4y3bL6si8kLCyg9",alias:exports.XChainAlias,vm:exports.XChainVMName,fee:exports.MILLIAVAX,creationTxFee:exports.CENTIAVAX,mintTxFee:exports.MILLIAVAX},n0P={blockchainID:exports.PlatformChainID,alias:exports.PChainAlias,vm:exports.PChainVMName,fee:exports.MILLIAVAX,creationTxFee:exports.CENTIAVAX,createSubnetTx:exports.ONEAVAX,createChainTx:exports.ONEAVAX,minConsumption:.1,maxConsumption:.12,maxStakingDuration:new bn_js_1.default(31536e3),maxSupply:new bn_js_1.default(72e7).mul(exports.ONEAVAX),minStake:exports.ONEAVAX.mul(new bn_js_1.default(2e3)),minStakeDuration:1209600,maxStakeDuration:31536e3,minDelegationStake:exports.ONEAVAX.mul(new bn_js_1.default(25)),minDelegationFee:new bn_js_1.default(2)},n0C={blockchainID:"2fFZQibQXcd6LTE4rpBPBAkLVXFE91Kit8pgxaBG1mRnh5xqbb",alias:exports.CChainAlias,vm:exports.CChainVMName,fee:exports.MILLIAVAX,gasPrice:exports.GWEI.mul(new bn_js_1.default(470)),chainID:43111};let avaxAssetID="FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z";const n1X={blockchainID:"2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM",avaxAssetID,alias:exports.XChainAlias,vm:exports.XChainVMName,txFee:exports.MILLIAVAX,creationTxFee:exports.CENTIAVAX,mintTxFee:exports.MILLIAVAX},n1P={blockchainID:exports.PlatformChainID,avaxAssetID,alias:exports.PChainAlias,vm:exports.PChainVMName,txFee:exports.MILLIAVAX,createSubnetTx:exports.ONEAVAX,createChainTx:exports.ONEAVAX,creationTxFee:exports.CENTIAVAX,minConsumption:.1,maxConsumption:.12,maxStakingDuration:new bn_js_1.default(31536e3),maxSupply:new bn_js_1.default(72e7).mul(exports.ONEAVAX),minStake:exports.ONEAVAX.mul(new bn_js_1.default(2e3)),minStakeDuration:1209600,maxStakeDuration:31536e3,minDelegationStake:exports.ONEAVAX.mul(new bn_js_1.default(25)),minDelegationFee:new bn_js_1.default(2)},n1C={blockchainID:"2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5",alias:exports.CChainAlias,vm:exports.CChainVMName,txBytesGas:1,costPerSignature:1e3,txFee:exports.MILLIAVAX,gasPrice:exports.GWEI.mul(new bn_js_1.default(225)),minGasPrice:exports.GWEI.mul(new bn_js_1.default(25)),maxGasPrice:exports.GWEI.mul(new bn_js_1.default(1e3)),chainID:43114},n2X={blockchainID:"4ktRjsAKxgMr2aEzv9SWmrU7Xk5FniHUrVCX4P1TZSfTLZWFM",alias:exports.XChainAlias,vm:exports.XChainVMName,txFee:0,creationTxFee:0,mintTxFee:new bn_js_1.default(0)},n2P={blockchainID:exports.PlatformChainID,alias:exports.PChainAlias,vm:exports.PChainVMName,txFee:0,creationTxFee:0,createSubnetTx:exports.ONEAVAX,createChainTx:exports.ONEAVAX,minConsumption:.1,maxConsumption:.12,maxStakingDuration:new bn_js_1.default(31536e3),maxSupply:new bn_js_1.default(72e7).mul(exports.ONEAVAX),minStake:exports.ONEAVAX.mul(new bn_js_1.default(2e3)),minStakeDuration:1209600,maxStakeDuration:31536e3,minDelegationStake:exports.ONEAVAX.mul(new bn_js_1.default(25)),minDelegationFee:new bn_js_1.default(2)},n2C={blockchainID:"2mUYSXfLrDtigwbzj1LxKVsHwELghc5sisoXrzJwLqAAQHF4i",alias:exports.CChainAlias,vm:exports.CChainVMName,gasPrice:0},n3X={blockchainID:"rrEWX7gc7D9mwcdrdBxBTdqh1a7WDVsMuadhTZgyXfFcRz45L",alias:exports.XChainAlias,vm:exports.XChainVMName,txFee:0,creationTxFee:0,mintTxFee:new bn_js_1.default(0)},n3P={blockchainID:"",alias:exports.PChainAlias,vm:exports.PChainVMName,txFee:0,creationTxFee:0,createSubnetTx:exports.ONEAVAX,createChainTx:exports.ONEAVAX,minConsumption:.1,maxConsumption:.12,maxStakingDuration:new bn_js_1.default(31536e3),maxSupply:new bn_js_1.default(72e7).mul(exports.ONEAVAX),minStake:exports.ONEAVAX.mul(new bn_js_1.default(2e3)),minStakeDuration:1209600,maxStakeDuration:31536e3,minDelegationStake:exports.ONEAVAX.mul(new bn_js_1.default(25)),minDelegationFee:new bn_js_1.default(2)},n3C={blockchainID:"zJytnh96Pc8rM337bBrtMvJDbEdDNjcXG3WkTNCiLp18ergm9",alias:exports.CChainAlias,vm:exports.CChainVMName,gasPrice:0},n4X={blockchainID:"jnUjZSRt16TcRnZzmh5aMhavwVHz3zBrSN8GfFMTQkzUnoBxC",alias:exports.XChainAlias,vm:exports.XChainVMName,txFee:exports.MILLIAVAX,creationTxFee:exports.CENTIAVAX,mintTxFee:exports.MILLIAVAX},n4P={blockchainID:exports.PlatformChainID,alias:exports.PChainAlias,vm:exports.PChainVMName,txFee:exports.MILLIAVAX,creationTxFee:exports.CENTIAVAX,createSubnetTx:exports.ONEAVAX,createChainTx:exports.ONEAVAX,minConsumption:.1,maxConsumption:.12,maxStakingDuration:new bn_js_1.default(31536e3),maxSupply:new bn_js_1.default(72e7).mul(exports.ONEAVAX),minStake:exports.ONEAVAX.mul(new bn_js_1.default(2e3)),minStakeDuration:1209600,maxStakeDuration:31536e3,minDelegationStake:exports.ONEAVAX.mul(new bn_js_1.default(25)),minDelegationFee:new bn_js_1.default(2)},n4C={blockchainID:"saMG5YgNsFxzjz4NMkEkt3bAH6hVxWdZkWcEnGB3Z15pcAmsK",alias:exports.CChainAlias,vm:exports.CChainVMName,gasPrice:exports.GWEI.mul(new bn_js_1.default(470)),chainID:43110};avaxAssetID="U8iRqJoiJm8xZHAacmvYyZVwqQx6uDNtQeP3CQ6fcgQk3JqnK";const n5X={blockchainID:"2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm",avaxAssetID,alias:exports.XChainAlias,vm:exports.XChainVMName,txFee:exports.MILLIAVAX,creationTxFee:exports.CENTIAVAX,mintTxFee:exports.MILLIAVAX},n5P={blockchainID:exports.PlatformChainID,avaxAssetID,alias:exports.PChainAlias,vm:exports.PChainVMName,txFee:exports.MILLIAVAX,creationTxFee:exports.CENTIAVAX,createSubnetTx:exports.ONEAVAX,createChainTx:exports.ONEAVAX,minConsumption:.1,maxConsumption:.12,maxStakingDuration:new bn_js_1.default(31536e3),maxSupply:new bn_js_1.default(72e7).mul(exports.ONEAVAX),minStake:exports.ONEAVAX,minStakeDuration:86400,maxStakeDuration:31536e3,minDelegationStake:exports.ONEAVAX,minDelegationFee:new bn_js_1.default(2)},n5C={blockchainID:"yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp",alias:exports.CChainAlias,vm:exports.CChainVMName,txBytesGas:1,costPerSignature:1e3,txFee:exports.MILLIAVAX,gasPrice:exports.GWEI.mul(new bn_js_1.default(225)),minGasPrice:exports.GWEI.mul(new bn_js_1.default(25)),maxGasPrice:exports.GWEI.mul(new bn_js_1.default(1e3)),chainID:43113};avaxAssetID="BUuypiq2wyuLMvyhzFXcPyxPMCgSp7eeDohhQRqTChoBjKziC";const n1337X=Object.assign({},n5X);n1337X.blockchainID="qzfF3A11KzpcHkkqznEyQgupQrCNS6WV6fTUTwZpEKqhj1QE7",n1337X.avaxAssetID=avaxAssetID;const n1337P=Object.assign({},n5P);n1337P.blockchainID=exports.PlatformChainID;const n1337C=Object.assign({},n5C);n1337C.blockchainID="BR28ypgLATNS6PbtHMiJ7NQ61vfpT27Hj8tAcZ1AHsfU5cz88",n1337C.avaxAssetID=avaxAssetID,n1337C.chainID=43112,avaxAssetID="2fombhL7aGPwj3KH4bfrmJwW6PVnMobf9Y2fn9GwxiAAJyFDbe";const n12345X=Object.assign({},n5X);n12345X.blockchainID="2eNy1mUFdmaxXNj1eQHUe7Np4gju9sJsEtWQ4MX3ToiNKuADed",n12345X.avaxAssetID=avaxAssetID;const n12345P=Object.assign({},n5P);n12345P.blockchainID=exports.PlatformChainID;const n12345C=Object.assign({},n5C);n12345C.blockchainID="2CA6j5zYzasynPsFeNoqWkmTCt3VScMvXUZHbfDJ8k3oGzAPtU",n12345C.avaxAssetID=avaxAssetID,n12345C.chainID=43112;class Defaults{}exports.Defaults=Defaults,Defaults.network={0:{hrp:exports.NetworkIDToHRP[0],X:n0X,"2vrXWHgGxh5n3YsLHMV16YVVJTpT4z45Fmb4y3bL6si8kLCyg9":n0X,P:n0P,"11111111111111111111111111111111LpoYY":n0P,C:n0C,"2fFZQibQXcd6LTE4rpBPBAkLVXFE91Kit8pgxaBG1mRnh5xqbb":n0C},1:{hrp:exports.NetworkIDToHRP[1],X:n1X,"2oYMBNV4eNHyqk2fjjV5nVQLDbtmNJzq5s3qs3Lo6ftnC6FByM":n1X,P:n1P,"11111111111111111111111111111111LpoYY":n1P,C:n1C,"2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5":n1C},2:{hrp:exports.NetworkIDToHRP[2],X:n2X,"4ktRjsAKxgMr2aEzv9SWmrU7Xk5FniHUrVCX4P1TZSfTLZWFM":n2X,P:n2P,"11111111111111111111111111111111LpoYY":n2P,C:n2C,"2mUYSXfLrDtigwbzj1LxKVsHwELghc5sisoXrzJwLqAAQHF4i":n2C},3:{hrp:exports.NetworkIDToHRP[3],X:n3X,rrEWX7gc7D9mwcdrdBxBTdqh1a7WDVsMuadhTZgyXfFcRz45L:n3X,P:n3P,"11111111111111111111111111111111LpoYY":n3P,C:n3C,zJytnh96Pc8rM337bBrtMvJDbEdDNjcXG3WkTNCiLp18ergm9:n3C},4:{hrp:exports.NetworkIDToHRP[4],X:n4X,jnUjZSRt16TcRnZzmh5aMhavwVHz3zBrSN8GfFMTQkzUnoBxC:n4X,P:n4P,"11111111111111111111111111111111LpoYY":n4P,C:n4C,saMG5YgNsFxzjz4NMkEkt3bAH6hVxWdZkWcEnGB3Z15pcAmsK:n4C},5:{hrp:exports.NetworkIDToHRP[5],X:n5X,"2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm":n5X,P:n5P,"11111111111111111111111111111111LpoYY":n5P,C:n5C,yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp:n5C},1337:{hrp:exports.NetworkIDToHRP[1337],X:n1337X,qzfF3A11KzpcHkkqznEyQgupQrCNS6WV6fTUTwZpEKqhj1QE7:n1337X,P:n1337P,"11111111111111111111111111111111LpoYY":n1337P,C:n1337C,BR28ypgLATNS6PbtHMiJ7NQ61vfpT27Hj8tAcZ1AHsfU5cz88:n1337C},12345:{hrp:exports.NetworkIDToHRP[12345],X:n12345X,"2eNy1mUFdmaxXNj1eQHUe7Np4gju9sJsEtWQ4MX3ToiNKuADed":n12345X,P:n12345P,"11111111111111111111111111111111LpoYY":n12345P,C:n12345C,"2CA6j5zYzasynPsFeNoqWkmTCt3VScMvXUZHbfDJ8k3oGzAPtU":n12345C}}},7911:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});const store2_1=__importDefault(__webpack_require__(1860));class DB{constructor(){}static getInstance(){return DB.instance||(DB.instance=new DB),DB.instance}static getNamespace(ns){return this.store.namespace(ns)}}exports.default=DB,DB.store=store2_1.default},611:(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SubnetAddressError=exports.SubnetThresholdError=exports.SubnetIdError=exports.ProtocolError=exports.InvalidEntropy=exports.EVMFeeError=exports.Bech32Error=exports.UnknownTypeError=exports.TypeNameError=exports.TypeIdError=exports.HexError=exports.NodeIdError=exports.PrivateKeyError=exports.Base58Error=exports.MergeRuleError=exports.PublicKeyError=exports.AddressIndexError=exports.BufferSizeError=exports.SubnetOwnerError=exports.DelegationFeeError=exports.TimeError=exports.StakeError=exports.FeeAssetError=exports.EVMOutputError=exports.EVMInputError=exports.SECPMintOutputError=exports.ThresholdError=exports.InsufficientFundsError=exports.UTXOError=exports.OutputIdError=exports.ChecksumError=exports.InvalidOperationIdError=exports.OperationError=exports.InputIdError=exports.TransferableInputError=exports.TransferableOutputError=exports.CredIdError=exports.CodecIdError=exports.TransactionError=exports.NameError=exports.SymbolError=exports.NoAtomicUTXOsError=exports.ChainIdError=exports.GooseEggCheckError=exports.AddressError=exports.AvalancheError=void 0;class AvalancheError extends Error{constructor(m,code){super(m),Object.setPrototypeOf(this,AvalancheError.prototype),this.errorCode=code}getCode(){return this.errorCode}}exports.AvalancheError=AvalancheError;class AddressError extends AvalancheError{constructor(m){super(m,"1000"),Object.setPrototypeOf(this,AddressError.prototype)}}exports.AddressError=AddressError;class GooseEggCheckError extends AvalancheError{constructor(m){super(m,"1001"),Object.setPrototypeOf(this,GooseEggCheckError.prototype)}}exports.GooseEggCheckError=GooseEggCheckError;class ChainIdError extends AvalancheError{constructor(m){super(m,"1002"),Object.setPrototypeOf(this,ChainIdError.prototype)}}exports.ChainIdError=ChainIdError;class NoAtomicUTXOsError extends AvalancheError{constructor(m){super(m,"1003"),Object.setPrototypeOf(this,NoAtomicUTXOsError.prototype)}}exports.NoAtomicUTXOsError=NoAtomicUTXOsError;class SymbolError extends AvalancheError{constructor(m){super(m,"1004"),Object.setPrototypeOf(this,SymbolError.prototype)}}exports.SymbolError=SymbolError;class NameError extends AvalancheError{constructor(m){super(m,"1005"),Object.setPrototypeOf(this,NameError.prototype)}}exports.NameError=NameError;class TransactionError extends AvalancheError{constructor(m){super(m,"1006"),Object.setPrototypeOf(this,TransactionError.prototype)}}exports.TransactionError=TransactionError;class CodecIdError extends AvalancheError{constructor(m){super(m,"1007"),Object.setPrototypeOf(this,CodecIdError.prototype)}}exports.CodecIdError=CodecIdError;class CredIdError extends AvalancheError{constructor(m){super(m,"1008"),Object.setPrototypeOf(this,CredIdError.prototype)}}exports.CredIdError=CredIdError;class TransferableOutputError extends AvalancheError{constructor(m){super(m,"1009"),Object.setPrototypeOf(this,TransferableOutputError.prototype)}}exports.TransferableOutputError=TransferableOutputError;class TransferableInputError extends AvalancheError{constructor(m){super(m,"1010"),Object.setPrototypeOf(this,TransferableInputError.prototype)}}exports.TransferableInputError=TransferableInputError;class InputIdError extends AvalancheError{constructor(m){super(m,"1011"),Object.setPrototypeOf(this,InputIdError.prototype)}}exports.InputIdError=InputIdError;class OperationError extends AvalancheError{constructor(m){super(m,"1012"),Object.setPrototypeOf(this,OperationError.prototype)}}exports.OperationError=OperationError;class InvalidOperationIdError extends AvalancheError{constructor(m){super(m,"1013"),Object.setPrototypeOf(this,InvalidOperationIdError.prototype)}}exports.InvalidOperationIdError=InvalidOperationIdError;class ChecksumError extends AvalancheError{constructor(m){super(m,"1014"),Object.setPrototypeOf(this,ChecksumError.prototype)}}exports.ChecksumError=ChecksumError;class OutputIdError extends AvalancheError{constructor(m){super(m,"1015"),Object.setPrototypeOf(this,OutputIdError.prototype)}}exports.OutputIdError=OutputIdError;class UTXOError extends AvalancheError{constructor(m){super(m,"1016"),Object.setPrototypeOf(this,UTXOError.prototype)}}exports.UTXOError=UTXOError;class InsufficientFundsError extends AvalancheError{constructor(m){super(m,"1017"),Object.setPrototypeOf(this,InsufficientFundsError.prototype)}}exports.InsufficientFundsError=InsufficientFundsError;class ThresholdError extends AvalancheError{constructor(m){super(m,"1018"),Object.setPrototypeOf(this,ThresholdError.prototype)}}exports.ThresholdError=ThresholdError;class SECPMintOutputError extends AvalancheError{constructor(m){super(m,"1019"),Object.setPrototypeOf(this,SECPMintOutputError.prototype)}}exports.SECPMintOutputError=SECPMintOutputError;class EVMInputError extends AvalancheError{constructor(m){super(m,"1020"),Object.setPrototypeOf(this,EVMInputError.prototype)}}exports.EVMInputError=EVMInputError;class EVMOutputError extends AvalancheError{constructor(m){super(m,"1021"),Object.setPrototypeOf(this,EVMOutputError.prototype)}}exports.EVMOutputError=EVMOutputError;class FeeAssetError extends AvalancheError{constructor(m){super(m,"1022"),Object.setPrototypeOf(this,FeeAssetError.prototype)}}exports.FeeAssetError=FeeAssetError;class StakeError extends AvalancheError{constructor(m){super(m,"1023"),Object.setPrototypeOf(this,StakeError.prototype)}}exports.StakeError=StakeError;class TimeError extends AvalancheError{constructor(m){super(m,"1024"),Object.setPrototypeOf(this,TimeError.prototype)}}exports.TimeError=TimeError;class DelegationFeeError extends AvalancheError{constructor(m){super(m,"1025"),Object.setPrototypeOf(this,DelegationFeeError.prototype)}}exports.DelegationFeeError=DelegationFeeError;class SubnetOwnerError extends AvalancheError{constructor(m){super(m,"1026"),Object.setPrototypeOf(this,SubnetOwnerError.prototype)}}exports.SubnetOwnerError=SubnetOwnerError;class BufferSizeError extends AvalancheError{constructor(m){super(m,"1027"),Object.setPrototypeOf(this,BufferSizeError.prototype)}}exports.BufferSizeError=BufferSizeError;class AddressIndexError extends AvalancheError{constructor(m){super(m,"1028"),Object.setPrototypeOf(this,AddressIndexError.prototype)}}exports.AddressIndexError=AddressIndexError;class PublicKeyError extends AvalancheError{constructor(m){super(m,"1029"),Object.setPrototypeOf(this,PublicKeyError.prototype)}}exports.PublicKeyError=PublicKeyError;class MergeRuleError extends AvalancheError{constructor(m){super(m,"1030"),Object.setPrototypeOf(this,MergeRuleError.prototype)}}exports.MergeRuleError=MergeRuleError;class Base58Error extends AvalancheError{constructor(m){super(m,"1031"),Object.setPrototypeOf(this,Base58Error.prototype)}}exports.Base58Error=Base58Error;class PrivateKeyError extends AvalancheError{constructor(m){super(m,"1032"),Object.setPrototypeOf(this,PrivateKeyError.prototype)}}exports.PrivateKeyError=PrivateKeyError;class NodeIdError extends AvalancheError{constructor(m){super(m,"1033"),Object.setPrototypeOf(this,NodeIdError.prototype)}}exports.NodeIdError=NodeIdError;class HexError extends AvalancheError{constructor(m){super(m,"1034"),Object.setPrototypeOf(this,HexError.prototype)}}exports.HexError=HexError;class TypeIdError extends AvalancheError{constructor(m){super(m,"1035"),Object.setPrototypeOf(this,TypeIdError.prototype)}}exports.TypeIdError=TypeIdError;class TypeNameError extends AvalancheError{constructor(m){super(m,"1042"),Object.setPrototypeOf(this,TypeNameError.prototype)}}exports.TypeNameError=TypeNameError;class UnknownTypeError extends AvalancheError{constructor(m){super(m,"1036"),Object.setPrototypeOf(this,UnknownTypeError.prototype)}}exports.UnknownTypeError=UnknownTypeError;class Bech32Error extends AvalancheError{constructor(m){super(m,"1037"),Object.setPrototypeOf(this,Bech32Error.prototype)}}exports.Bech32Error=Bech32Error;class EVMFeeError extends AvalancheError{constructor(m){super(m,"1038"),Object.setPrototypeOf(this,EVMFeeError.prototype)}}exports.EVMFeeError=EVMFeeError;class InvalidEntropy extends AvalancheError{constructor(m){super(m,"1039"),Object.setPrototypeOf(this,InvalidEntropy.prototype)}}exports.InvalidEntropy=InvalidEntropy;class ProtocolError extends AvalancheError{constructor(m){super(m,"1040"),Object.setPrototypeOf(this,ProtocolError.prototype)}}exports.ProtocolError=ProtocolError;class SubnetIdError extends AvalancheError{constructor(m){super(m,"1041"),Object.setPrototypeOf(this,SubnetIdError.prototype)}}exports.SubnetIdError=SubnetIdError;class SubnetThresholdError extends AvalancheError{constructor(m){super(m,"1043"),Object.setPrototypeOf(this,SubnetThresholdError.prototype)}}exports.SubnetThresholdError=SubnetThresholdError;class SubnetAddressError extends AvalancheError{constructor(m){super(m,"1044"),Object.setPrototypeOf(this,SubnetAddressError.prototype)}}exports.SubnetAddressError=SubnetAddressError},3064:function(__unused_webpack_module,exports){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};function getResponse(request,config){return __awaiter(this,void 0,void 0,(function*(){let stageOne;try{stageOne=yield fetch(request)}catch(e){const error=Object.assign(Object.assign({},new Error("Network Error")),{config,request,isAxiosError:!0,toJSON:()=>error});return Promise.reject(error)}const response={status:stageOne.status,statusText:stageOne.statusText,headers:Object.assign({},stageOne.headers),config,request,data:void 0};if(stageOne.status>=200&&204!==stageOne.status)switch(config.responseType){case"arraybuffer":response.data=yield stageOne.arrayBuffer();break;case"blob":response.data=yield stageOne.blob();break;case"json":response.data=yield stageOne.json();break;case"formData":response.data=yield stageOne.formData();break;default:response.data=yield stageOne.text()}return Promise.resolve(response)}))}Object.defineProperty(exports,"__esModule",{value:!0}),exports.fetchAdapter=void 0,exports.fetchAdapter=function fetchAdapter(config){return __awaiter(this,void 0,void 0,(function*(){const request=function createRequest(config){const headers=new Headers(config.headers);if(config.auth){const username=config.auth.username||"",password=config.auth.password?encodeURIComponent(config.auth.password):"";headers.set("Authorization",`Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`)}const method=config.method.toUpperCase(),options={headers,method};"GET"!==method&&"HEAD"!==method&&(options.body=config.data),config.withCredentials&&(options.credentials=config.withCredentials?"include":"omit");const fullPath=new URL(config.url,config.baseURL),params=new URLSearchParams(config.params);return new Request(`${fullPath}${params}`,options)}(config),promiseChain=[getResponse(request,config)];config.timeout&&config.timeout>0&&promiseChain.push(new Promise(((res,reject)=>{setTimeout((()=>{const message=config.timeoutErrorMessage?config.timeoutErrorMessage:"timeout of "+config.timeout+"ms exceeded",error=Object.assign(Object.assign({},new Error(message)),{config,request,code:"ECONNABORTED",isAxiosError:!0,toJSON:()=>error});reject(error)}),config.timeout)})));const response=yield Promise.race(promiseChain);return new Promise(((resolve,reject)=>{if(response instanceof Error)reject(response);else if(response.status&&response.config.validateStatus&&!response.config.validateStatus(response.status)){const error=Object.assign(Object.assign({},new Error("Request failed with status code "+response.status)),{config,request,code:response.status>=500?"ERR_BAD_RESPONSE":"ERR_BAD_REQUEST",isAxiosError:!0,toJSON:()=>error});reject(error)}else resolve(response)}))}))}},59:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});const buffer_1=__webpack_require__(8764),hdkey_1=__importDefault(__webpack_require__(9840)),bintools=__importDefault(__webpack_require__(903)).default.getInstance();class HDNode{constructor(from){"string"==typeof from&&"xp"===from.substring(0,2)?this.hdkey=hdkey_1.default.fromExtendedKey(from):buffer_1.Buffer.isBuffer(from)?this.hdkey=hdkey_1.default.fromMasterSeed(from):this.hdkey=hdkey_1.default.fromMasterSeed(buffer_1.Buffer.from(from)),this.publicKey=this.hdkey.publicKey,this.privateKey=this.hdkey.privateKey,this.privateKey?this.privateKeyCB58=`PrivateKey-${bintools.cb58Encode(this.privateKey)}`:this.privateExtendedKey=null,this.chainCode=this.hdkey.chainCode,this.privateExtendedKey=this.hdkey.privateExtendedKey,this.publicExtendedKey=this.hdkey.publicExtendedKey}derive(path){const hdKey=this.hdkey.derive(path);let hdNode;return hdNode=null!=hdKey.privateExtendedKey?new HDNode(hdKey.privateExtendedKey):new HDNode(hdKey.publicExtendedKey),hdNode}sign(hash){const sig=this.hdkey.sign(hash);return buffer_1.Buffer.from(sig)}verify(hash,signature){return this.hdkey.verify(hash,signature)}wipePrivateData(){this.privateKey=null,this.privateExtendedKey=null,this.privateKeyCB58=null,this.hdkey.wipePrivateData()}}exports.default=HDNode},5554:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.costExportTx=exports.calcBytesCost=exports.costImportTx=exports.NodeIDStringToBuffer=exports.bufferToNodeIDString=exports.privateKeyStringToBuffer=exports.bufferToPrivateKeyString=exports.UnixNow=exports.MaxWeightFormula=exports.getPreferredHRP=void 0;const constants_1=__webpack_require__(8779),bn_js_1=__importDefault(__webpack_require__(3550)),bintools_1=__importDefault(__webpack_require__(903)),errors_1=__webpack_require__(611),bintools=bintools_1.default.getInstance();function calcBytesCost(len){return len*constants_1.Defaults.network[1].C.txBytesGas}exports.getPreferredHRP=function getPreferredHRP(networkID){return networkID in constants_1.NetworkIDToHRP?constants_1.NetworkIDToHRP[`${networkID}`]:void 0===networkID?constants_1.NetworkIDToHRP[`${constants_1.DefaultNetworkID}`]:constants_1.FallbackHRP},exports.MaxWeightFormula=function MaxWeightFormula(staked,cap){return bn_js_1.default.min(staked.mul(new bn_js_1.default(5)),cap)},exports.UnixNow=function UnixNow(){return new bn_js_1.default(Math.round((new Date).getTime()/1e3))},exports.bufferToPrivateKeyString=function bufferToPrivateKeyString(pk){return`PrivateKey-${bintools.cb58Encode(pk)}`},exports.privateKeyStringToBuffer=function privateKeyStringToBuffer(pk){if(!pk.startsWith("PrivateKey-"))throw new errors_1.PrivateKeyError("Error - privateKeyStringToBuffer: private keys must start with 'PrivateKey-'");const pksplit=pk.split("-");return bintools.cb58Decode(pksplit[pksplit.length-1])},exports.bufferToNodeIDString=function bufferToNodeIDString(pk){return`NodeID-${bintools.cb58Encode(pk)}`},exports.NodeIDStringToBuffer=function NodeIDStringToBuffer(pk){if(!pk.startsWith("NodeID-"))throw new errors_1.NodeIdError("Error - privateNodeIDToBuffer: nodeID must start with 'NodeID-'");const pksplit=pk.split("-");return bintools.cb58Decode(pksplit[pksplit.length-1])},exports.costImportTx=function costImportTx(tx){let bytesCost=calcBytesCost(tx.toBuffer().byteLength);return tx.getTransaction().getImportInputs().forEach((input=>{const inCost=input.getCost();bytesCost+=inCost})),bytesCost+1e4},exports.calcBytesCost=calcBytesCost,exports.costExportTx=function costExportTx(tx){return calcBytesCost(tx.toBuffer().byteLength)+tx.getTransaction().getInputs().length*constants_1.Defaults.network[1].C.costPerSignature+1e4}},338:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&!("get"in desc?!m.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){void 0===k2&&(k2=k),o[k2]=m[k]}),__exportStar=this&&this.__exportStar||function(m,exports){for(var p in m)"default"===p||Object.prototype.hasOwnProperty.call(exports,p)||__createBinding(exports,m,p)};Object.defineProperty(exports,"__esModule",{value:!0}),__exportStar(__webpack_require__(978),exports),__exportStar(__webpack_require__(903),exports),__exportStar(__webpack_require__(8309),exports),__exportStar(__webpack_require__(8779),exports),__exportStar(__webpack_require__(7911),exports),__exportStar(__webpack_require__(611),exports),__exportStar(__webpack_require__(3064),exports),__exportStar(__webpack_require__(59),exports),__exportStar(__webpack_require__(5554),exports),__exportStar(__webpack_require__(9836),exports),__exportStar(__webpack_require__(2272),exports),__exportStar(__webpack_require__(2216),exports),__exportStar(__webpack_require__(555),exports)},8309:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};Object.defineProperty(exports,"__esModule",{value:!0});const buffer_1=__webpack_require__(8764),errors_1=__webpack_require__(611),bip39=__webpack_require__(2153),randomBytes=__webpack_require__(1798);class Mnemonic{constructor(){this.wordlists=bip39.wordlists}static getInstance(){return Mnemonic.instance||(Mnemonic.instance=new Mnemonic),Mnemonic.instance}getWordlists(language){return void 0!==language?this.wordlists[`${language}`]:this.wordlists}mnemonicToSeedSync(mnemonic,password=""){const seed=bip39.mnemonicToSeedSync(mnemonic,password);return buffer_1.Buffer.from(seed)}mnemonicToSeed(mnemonic,password=""){return __awaiter(this,void 0,void 0,(function*(){const seed=yield bip39.mnemonicToSeed(mnemonic,password);return buffer_1.Buffer.from(seed)}))}mnemonicToEntropy(mnemonic,wordlist){return bip39.mnemonicToEntropy(mnemonic,wordlist)}entropyToMnemonic(entropy,wordlist){return bip39.entropyToMnemonic(entropy,wordlist)}validateMnemonic(mnemonic,wordlist){return bip39.validateMnemonic(mnemonic,wordlist)}setDefaultWordlist(language){bip39.setDefaultWordlist(language)}getDefaultWordlist(){return bip39.getDefaultWordlist()}generateMnemonic(strength,rng,wordlist){if((strength=strength||256)%32!=0)throw new errors_1.InvalidEntropy("Error - Invalid entropy");return rng=rng||randomBytes,bip39.generateMnemonic(strength,rng,wordlist)}}exports.default=Mnemonic},9836:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.MAGNETPayload=exports.ONIONPayload=exports.IPFSPayload=exports.URLPayload=exports.EMAILPayload=exports.YAMLPayload=exports.JSONPayload=exports.CSVPayload=exports.SVGPayload=exports.ICOPayload=exports.BMPPayload=exports.PNGPayload=exports.JPEGPayload=exports.SECPENCPayload=exports.SECPSIGPayload=exports.NODEIDPayload=exports.CHAINIDPayload=exports.SUBNETIDPayload=exports.NFTIDPayload=exports.UTXOIDPayload=exports.ASSETIDPayload=exports.TXIDPayload=exports.cb58EncodedPayload=exports.CCHAINADDRPayload=exports.PCHAINADDRPayload=exports.XCHAINADDRPayload=exports.ChainAddressPayload=exports.BIGNUMPayload=exports.B64STRPayload=exports.B58STRPayload=exports.HEXSTRPayload=exports.UTF8Payload=exports.BINPayload=exports.PayloadBase=exports.PayloadTypes=void 0;const buffer_1=__webpack_require__(8764),bintools_1=__importDefault(__webpack_require__(903)),bn_js_1=__importDefault(__webpack_require__(3550)),errors_1=__webpack_require__(611),serialization_1=__webpack_require__(555),bintools=bintools_1.default.getInstance(),serialization=serialization_1.Serialization.getInstance();class PayloadTypes{constructor(){this.types=[],this.types=["BIN","UTF8","HEXSTR","B58STR","B64STR","BIGNUM","XCHAINADDR","PCHAINADDR","CCHAINADDR","TXID","ASSETID","UTXOID","NFTID","SUBNETID","CHAINID","NODEID","SECPSIG","SECPENC","JPEG","PNG","BMP","ICO","SVG","CSV","JSON","YAML","EMAIL","URL","IPFS","ONION","MAGNET"]}getContent(payload){return bintools.copyFrom(payload,5)}getPayload(payload){return bintools.copyFrom(payload,4)}getTypeID(payload){return bintools.copyFrom(payload,4,5).readUInt8(0)}lookupID(typestr){return this.types.indexOf(typestr)}lookupType(value){return this.types[`${value}`]}select(typeID,...args){switch(typeID){case 0:return new BINPayload(...args);case 1:return new UTF8Payload(...args);case 2:return new HEXSTRPayload(...args);case 3:return new B58STRPayload(...args);case 4:return new B64STRPayload(...args);case 5:return new BIGNUMPayload(...args);case 6:return new XCHAINADDRPayload(...args);case 7:return new PCHAINADDRPayload(...args);case 8:return new CCHAINADDRPayload(...args);case 9:return new TXIDPayload(...args);case 10:return new ASSETIDPayload(...args);case 11:return new UTXOIDPayload(...args);case 12:return new NFTIDPayload(...args);case 13:return new SUBNETIDPayload(...args);case 14:return new CHAINIDPayload(...args);case 15:return new NODEIDPayload(...args);case 16:return new SECPSIGPayload(...args);case 17:return new SECPENCPayload(...args);case 18:return new JPEGPayload(...args);case 19:return new PNGPayload(...args);case 20:return new BMPPayload(...args);case 21:return new ICOPayload(...args);case 22:return new SVGPayload(...args);case 23:return new CSVPayload(...args);case 24:return new JSONPayload(...args);case 25:return new YAMLPayload(...args);case 26:return new EMAILPayload(...args);case 27:return new URLPayload(...args);case 28:return new IPFSPayload(...args);case 29:return new ONIONPayload(...args);case 30:return new MAGNETPayload(...args)}throw new errors_1.TypeIdError(`Error - PayloadTypes.select: unknown typeid ${typeID}`)}recast(unknowPayload){return this.select(unknowPayload.typeID(),unknowPayload.returnType())}static getInstance(){return PayloadTypes.instance||(PayloadTypes.instance=new PayloadTypes),PayloadTypes.instance}}exports.PayloadTypes=PayloadTypes;class PayloadBase{constructor(){this.payload=buffer_1.Buffer.alloc(0),this.typeid=void 0}typeID(){return this.typeid}typeName(){return PayloadTypes.getInstance().lookupType(this.typeid)}getContent(){return bintools.copyFrom(this.payload)}getPayload(){const typeID=buffer_1.Buffer.alloc(1);typeID.writeUInt8(this.typeid,0);return buffer_1.Buffer.concat([typeID,bintools.copyFrom(this.payload)])}fromBuffer(bytes,offset=0){const size=bintools.copyFrom(bytes,offset,offset+4).readUInt32BE(0);return offset+=4,this.typeid=bintools.copyFrom(bytes,offset,offset+1).readUInt8(0),offset+=1,this.payload=bintools.copyFrom(bytes,offset,offset+size-1),offset+=size-1}toBuffer(){const sizebuff=buffer_1.Buffer.alloc(4);sizebuff.writeUInt32BE(this.payload.length+1,0);const typebuff=buffer_1.Buffer.alloc(1);return typebuff.writeUInt8(this.typeid,0),buffer_1.Buffer.concat([sizebuff,typebuff,this.payload])}}exports.PayloadBase=PayloadBase;class BINPayload extends PayloadBase{constructor(payload){super(),this.typeid=0,payload instanceof buffer_1.Buffer?this.payload=payload:"string"==typeof payload&&(this.payload=bintools.b58ToBuffer(payload))}returnType(){return this.payload}}exports.BINPayload=BINPayload;class UTF8Payload extends PayloadBase{constructor(payload){super(),this.typeid=1,payload instanceof buffer_1.Buffer?this.payload=payload:"string"==typeof payload&&(this.payload=buffer_1.Buffer.from(payload,"utf8"))}returnType(){return this.payload.toString("utf8")}}exports.UTF8Payload=UTF8Payload;class HEXSTRPayload extends PayloadBase{constructor(payload){if(super(),this.typeid=2,payload instanceof buffer_1.Buffer)this.payload=payload;else if("string"==typeof payload){if(payload.startsWith("0x")||!payload.match(/^[0-9A-Fa-f]+$/))throw new errors_1.HexError("HEXSTRPayload.constructor -- hex string may not start with 0x and must be in /^[0-9A-Fa-f]+$/: "+payload);this.payload=buffer_1.Buffer.from(payload,"hex")}}returnType(){return this.payload.toString("hex")}}exports.HEXSTRPayload=HEXSTRPayload;class B58STRPayload extends PayloadBase{constructor(payload){super(),this.typeid=3,payload instanceof buffer_1.Buffer?this.payload=payload:"string"==typeof payload&&(this.payload=bintools.b58ToBuffer(payload))}returnType(){return bintools.bufferToB58(this.payload)}}exports.B58STRPayload=B58STRPayload;class B64STRPayload extends PayloadBase{constructor(payload){super(),this.typeid=4,payload instanceof buffer_1.Buffer?this.payload=payload:"string"==typeof payload&&(this.payload=buffer_1.Buffer.from(payload,"base64"))}returnType(){return this.payload.toString("base64")}}exports.B64STRPayload=B64STRPayload;class BIGNUMPayload extends PayloadBase{constructor(payload){super(),this.typeid=5,payload instanceof buffer_1.Buffer?this.payload=payload:payload instanceof bn_js_1.default?this.payload=bintools.fromBNToBuffer(payload):"string"==typeof payload&&(this.payload=buffer_1.Buffer.from(payload,"hex"))}returnType(){return bintools.fromBufferToBN(this.payload)}}exports.BIGNUMPayload=BIGNUMPayload;class ChainAddressPayload extends PayloadBase{constructor(payload,hrp){super(),this.typeid=6,this.chainid="",payload instanceof buffer_1.Buffer?this.payload=payload:"string"==typeof payload&&(this.payload=null!=hrp?bintools.stringToAddress(payload,hrp):bintools.stringToAddress(payload))}returnChainID(){return this.chainid}returnType(hrp){return serialization.bufferToType(this.payload,"bech32",hrp,this.chainid)}}exports.ChainAddressPayload=ChainAddressPayload;class XCHAINADDRPayload extends ChainAddressPayload{constructor(){super(...arguments),this.typeid=6,this.chainid="X"}}exports.XCHAINADDRPayload=XCHAINADDRPayload;class PCHAINADDRPayload extends ChainAddressPayload{constructor(){super(...arguments),this.typeid=7,this.chainid="P"}}exports.PCHAINADDRPayload=PCHAINADDRPayload;class CCHAINADDRPayload extends ChainAddressPayload{constructor(){super(...arguments),this.typeid=8,this.chainid="C"}}exports.CCHAINADDRPayload=CCHAINADDRPayload;class cb58EncodedPayload extends PayloadBase{returnType(){return bintools.cb58Encode(this.payload)}constructor(payload){super(),payload instanceof buffer_1.Buffer?this.payload=payload:"string"==typeof payload&&(this.payload=bintools.cb58Decode(payload))}}exports.cb58EncodedPayload=cb58EncodedPayload;class TXIDPayload extends cb58EncodedPayload{constructor(){super(...arguments),this.typeid=9}}exports.TXIDPayload=TXIDPayload;class ASSETIDPayload extends cb58EncodedPayload{constructor(){super(...arguments),this.typeid=10}}exports.ASSETIDPayload=ASSETIDPayload;class UTXOIDPayload extends cb58EncodedPayload{constructor(){super(...arguments),this.typeid=11}}exports.UTXOIDPayload=UTXOIDPayload;class NFTIDPayload extends UTXOIDPayload{constructor(){super(...arguments),this.typeid=12}}exports.NFTIDPayload=NFTIDPayload;class SUBNETIDPayload extends cb58EncodedPayload{constructor(){super(...arguments),this.typeid=13}}exports.SUBNETIDPayload=SUBNETIDPayload;class CHAINIDPayload extends cb58EncodedPayload{constructor(){super(...arguments),this.typeid=14}}exports.CHAINIDPayload=CHAINIDPayload;class NODEIDPayload extends cb58EncodedPayload{constructor(){super(...arguments),this.typeid=15}}exports.NODEIDPayload=NODEIDPayload;class SECPSIGPayload extends B58STRPayload{constructor(){super(...arguments),this.typeid=16}}exports.SECPSIGPayload=SECPSIGPayload;class SECPENCPayload extends B58STRPayload{constructor(){super(...arguments),this.typeid=17}}exports.SECPENCPayload=SECPENCPayload;class JPEGPayload extends BINPayload{constructor(){super(...arguments),this.typeid=18}}exports.JPEGPayload=JPEGPayload;class PNGPayload extends BINPayload{constructor(){super(...arguments),this.typeid=19}}exports.PNGPayload=PNGPayload;class BMPPayload extends BINPayload{constructor(){super(...arguments),this.typeid=20}}exports.BMPPayload=BMPPayload;class ICOPayload extends BINPayload{constructor(){super(...arguments),this.typeid=21}}exports.ICOPayload=ICOPayload;class SVGPayload extends UTF8Payload{constructor(){super(...arguments),this.typeid=22}}exports.SVGPayload=SVGPayload;class CSVPayload extends UTF8Payload{constructor(){super(...arguments),this.typeid=23}}exports.CSVPayload=CSVPayload;class JSONPayload extends PayloadBase{constructor(payload){if(super(),this.typeid=24,payload instanceof buffer_1.Buffer)this.payload=payload;else if("string"==typeof payload)this.payload=buffer_1.Buffer.from(payload,"utf8");else if(payload){let jsonstr=JSON.stringify(payload);this.payload=buffer_1.Buffer.from(jsonstr,"utf8")}}returnType(){return JSON.parse(this.payload.toString("utf8"))}}exports.JSONPayload=JSONPayload;class YAMLPayload extends UTF8Payload{constructor(){super(...arguments),this.typeid=25}}exports.YAMLPayload=YAMLPayload;class EMAILPayload extends UTF8Payload{constructor(){super(...arguments),this.typeid=26}}exports.EMAILPayload=EMAILPayload;class URLPayload extends UTF8Payload{constructor(){super(...arguments),this.typeid=27}}exports.URLPayload=URLPayload;class IPFSPayload extends B58STRPayload{constructor(){super(...arguments),this.typeid=28}}exports.IPFSPayload=IPFSPayload;class ONIONPayload extends UTF8Payload{constructor(){super(...arguments),this.typeid=29}}exports.ONIONPayload=ONIONPayload;class MAGNETPayload extends UTF8Payload{constructor(){super(...arguments),this.typeid=30}}exports.MAGNETPayload=MAGNETPayload},2272:(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PersistanceOptions=void 0;exports.PersistanceOptions=class PersistanceOptions{constructor(name,overwrite=!1,mergeRule){this.name=void 0,this.overwrite=!1,this.mergeRule="union",this.getName=()=>this.name,this.getOverwrite=()=>this.overwrite,this.getMergeRule=()=>this.mergeRule,this.name=name,this.overwrite=overwrite,this.mergeRule=mergeRule}}},2216:(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.default=class PubSub{newSet(){return JSON.stringify({newSet:{}})}newBloom(maxElements=1e3,collisionProb=.01){return JSON.stringify({newBloom:{maxElements,collisionProb}})}addAddresses(addresses){return JSON.stringify({addAddresses:{addresses}})}}},555:function(__unused_webpack_module,exports,__webpack_require__){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.Serialization=exports.Serializable=exports.SERIALIZATIONVERSION=void 0;const bintools_1=__importDefault(__webpack_require__(903)),bn_js_1=__importDefault(__webpack_require__(3550)),buffer_1=__webpack_require__(8764),xss_1=__importDefault(__webpack_require__(8924)),helperfunctions_1=__webpack_require__(5554),errors_1=__webpack_require__(611);exports.SERIALIZATIONVERSION=0;exports.Serializable=class Serializable{constructor(){this._typeName=void 0,this._typeID=void 0,this._codecID=void 0}getTypeName(){return this._typeName}getTypeID(){return this._typeID}getCodecID(){return this._codecID}sanitizeObject(obj){for(const k in obj)"object"==typeof obj[`${k}`]&&null!==obj[`${k}`]?this.sanitizeObject(obj[`${k}`]):"string"==typeof obj[`${k}`]&&(obj[`${k}`]=(0,xss_1.default)(obj[`${k}`]));return obj}serialize(encoding){return{_typeName:(0,xss_1.default)(this._typeName),_typeID:void 0===this._typeID?null:this._typeID,_codecID:void 0===this._codecID?null:this._codecID}}deserialize(fields,encoding){if("string"!=typeof(fields=this.sanitizeObject(fields))._typeName)throw new errors_1.TypeNameError("Error - Serializable.deserialize: _typeName must be a string, found: "+typeof fields._typeName);if(fields._typeName!==this._typeName)throw new errors_1.TypeNameError("Error - Serializable.deserialize: _typeName mismatch -- expected: "+this._typeName+" -- received: "+fields._typeName);if(void 0!==fields._typeID&&null!==fields._typeID){if("number"!=typeof fields._typeID)throw new errors_1.TypeIdError("Error - Serializable.deserialize: _typeID must be a number, found: "+typeof fields._typeID);if(fields._typeID!==this._typeID)throw new errors_1.TypeIdError("Error - Serializable.deserialize: _typeID mismatch -- expected: "+this._typeID+" -- received: "+fields._typeID)}if(void 0!==fields._codecID&&null!==fields._codecID){if("number"!=typeof fields._codecID)throw new errors_1.CodecIdError("Error - Serializable.deserialize: _codecID must be a number, found: "+typeof fields._codecID);if(fields._codecID!==this._codecID)throw new errors_1.CodecIdError("Error - Serializable.deserialize: _codecID mismatch -- expected: "+this._codecID+" -- received: "+fields._codecID)}}};class Serialization{constructor(){this.bintools=bintools_1.default.getInstance()}static getInstance(){return Serialization.instance||(Serialization.instance=new Serialization),Serialization.instance}bufferToType(vb,type,...args){return"BN"===type?new bn_js_1.default(vb.toString("hex"),"hex"):"Buffer"===type?(1==args.length&&"number"==typeof args[0]&&(vb=buffer_1.Buffer.from(vb.toString("hex").padStart(2*args[0],"0"),"hex")),vb):"bech32"===type?this.bintools.addressToString(args[0],args[1],vb):"nodeID"===type?(0,helperfunctions_1.bufferToNodeIDString)(vb):"privateKey"===type?(0,helperfunctions_1.bufferToPrivateKeyString)(vb):"cb58"===type?this.bintools.cb58Encode(vb):"base58"===type?this.bintools.bufferToB58(vb):"base64"===type?vb.toString("base64"):"hex"===type?vb.toString("hex"):"decimalString"===type?new bn_js_1.default(vb.toString("hex"),"hex").toString(10):"number"===type?new bn_js_1.default(vb.toString("hex"),"hex").toNumber():"utf8"===type?vb.toString("utf8"):void 0}typeToBuffer(v,type,...args){if("BN"===type){let str=v.toString("hex");return 1==args.length&&"number"==typeof args[0]?buffer_1.Buffer.from(str.padStart(2*args[0],"0"),"hex"):buffer_1.Buffer.from(str,"hex")}if("Buffer"===type)return v;if("bech32"===type)return this.bintools.stringToAddress(v,...args);if("nodeID"===type)return(0,helperfunctions_1.NodeIDStringToBuffer)(v);if("privateKey"===type)return(0,helperfunctions_1.privateKeyStringToBuffer)(v);if("cb58"===type)return this.bintools.cb58Decode(v);if("base58"===type)return this.bintools.b58ToBuffer(v);if("base64"===type)return buffer_1.Buffer.from(v,"base64");if("hex"===type)return v.startsWith("0x")&&(v=v.slice(2)),buffer_1.Buffer.from(v,"hex");if("decimalString"===type){let str=new bn_js_1.default(v,10).toString("hex");return 1==args.length&&"number"==typeof args[0]?buffer_1.Buffer.from(str.padStart(2*args[0],"0"),"hex"):buffer_1.Buffer.from(str,"hex")}if("number"===type){let str=new bn_js_1.default(v,10).toString("hex");return 1==args.length&&"number"==typeof args[0]?buffer_1.Buffer.from(str.padStart(2*args[0],"0"),"hex"):buffer_1.Buffer.from(str,"hex")}if("utf8"===type){if(1==args.length&&"number"==typeof args[0]){let b=buffer_1.Buffer.alloc(args[0]);return b.write(v),b}return buffer_1.Buffer.from(v,"utf8")}}encoder(value,encoding,intype,outtype,...args){if(void 0===value)throw new errors_1.UnknownTypeError("Error - Serializable.encoder: value passed is undefined");"display"!==encoding&&(outtype=encoding);const vb=this.typeToBuffer(value,intype,...args);return this.bufferToType(vb,outtype,...args)}decoder(value,encoding,intype,outtype,...args){if(void 0===value)throw new errors_1.UnknownTypeError("Error - Serializable.decoder: value passed is undefined");"display"!==encoding&&(intype=encoding);const vb=this.typeToBuffer(value,intype,...args);return this.bufferToType(vb,outtype,...args)}serialize(serialize,vm,encoding="display",notes){return void 0===notes&&(notes=serialize.getTypeName()),{vm,encoding,version:exports.SERIALIZATIONVERSION,notes,fields:serialize.serialize(encoding)}}deserialize(input,output){output.deserialize(input.fields,input.encoding)}}exports.Serialization=Serialization},5751:module=>{"use strict";for(var ALPHABET="qpzry9x8gf2tvdw0s3jn54khce6mua7l",ALPHABET_MAP={},z=0;z>25;return(33554431&pre)<<5^996825010&-(b>>0&1)^642813549&-(b>>1&1)^513874426&-(b>>2&1)^1027748829&-(b>>3&1)^705979059&-(b>>4&1)}function prefixChk(prefix){for(var chk=1,i=0;i126)return"Invalid prefix ("+prefix+")";chk=polymodStep(chk)^c>>5}for(chk=polymodStep(chk),i=0;iLIMIT)return"Exceeds length limit";var lowered=str.toLowerCase(),uppered=str.toUpperCase();if(str!==lowered&&str!==uppered)return"Mixed-case string "+str;var split=(str=lowered).lastIndexOf("1");if(-1===split)return"No separator character for "+str;if(0===split)return"Missing prefix for "+str;var prefix=str.slice(0,split),wordChars=str.slice(split+1);if(wordChars.length<6)return"Data too short";var chk=prefixChk(prefix);if("string"==typeof chk)return chk;for(var words=[],i=0;i=wordChars.length||words.push(v)}return 1!==chk?"Invalid checksum for "+str:{prefix,words}}function convert(data,inBits,outBits,pad){for(var value=0,bits=0,maxV=(1<=outBits;)bits-=outBits,result.push(value>>bits&maxV);if(pad)bits>0&&result.push(value<=inBits)return"Excess padding";if(value<LIMIT)throw new TypeError("Exceeds length limit");var chk=prefixChk(prefix=prefix.toLowerCase());if("string"==typeof chk)throw new Error(chk);for(var result=prefix+"1",i=0;i>5!=0)throw new Error("Non 5-bit word");chk=polymodStep(chk)^x,result+=ALPHABET.charAt(x)}for(i=0;i<6;++i)chk=polymodStep(chk);for(chk^=1,i=0;i<6;++i){result+=ALPHABET.charAt(chk>>5*(5-i)&31)}return result},toWordsUnsafe:function toWordsUnsafe(bytes){var res=convert(bytes,8,5,!0);if(Array.isArray(res))return res},toWords:function toWords(bytes){var res=convert(bytes,8,5,!0);if(Array.isArray(res))return res;throw new Error(res)},fromWordsUnsafe:function fromWordsUnsafe(words){var res=convert(words,5,8,!1);if(Array.isArray(res))return res},fromWords:function fromWords(words){var res=convert(words,5,8,!1);if(Array.isArray(res))return res;throw new Error(res)}}},8826:function(module){"use strict";!function(root){function checkInt(value){return parseInt(value)===value}function checkInts(arrayish){if(!checkInt(arrayish.length))return!1;for(var i=0;i255)return!1;return!0}function coerceArray(arg,copy){if(arg.buffer&&ArrayBuffer.isView(arg)&&"Uint8Array"===arg.name)return copy&&(arg=arg.slice?arg.slice():Array.prototype.slice.call(arg)),arg;if(Array.isArray(arg)){if(!checkInts(arg))throw new Error("Array contains invalid value: "+arg);return new Uint8Array(arg)}if(checkInt(arg.length)&&checkInts(arg))return new Uint8Array(arg);throw new Error("unsupported array-like object")}function createArray(length){return new Uint8Array(length)}function copyArray(sourceArray,targetArray,targetStart,sourceStart,sourceEnd){null==sourceStart&&null==sourceEnd||(sourceArray=sourceArray.slice?sourceArray.slice(sourceStart,sourceEnd):Array.prototype.slice.call(sourceArray,sourceStart,sourceEnd)),targetArray.set(sourceArray,targetStart)}var Hex,convertUtf8={toBytes:function toBytes(text){var result=[],i=0;for(text=encodeURI(text);i191&&c<224?(result.push(String.fromCharCode((31&c)<<6|63&bytes[i+1])),i+=2):(result.push(String.fromCharCode((15&c)<<12|(63&bytes[i+1])<<6|63&bytes[i+2])),i+=3)}return result.join("")}},convertHex=(Hex="0123456789abcdef",{toBytes:function toBytes(text){for(var result=[],i=0;i>4]+Hex[15&v])}return result.join("")}}),numberOfRounds={16:10,24:12,32:14},rcon=[1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145],S=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],Si=[82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125],T1=[3328402341,4168907908,4000806809,4135287693,4294111757,3597364157,3731845041,2445657428,1613770832,33620227,3462883241,1445669757,3892248089,3050821474,1303096294,3967186586,2412431941,528646813,2311702848,4202528135,4026202645,2992200171,2387036105,4226871307,1101901292,3017069671,1604494077,1169141738,597466303,1403299063,3832705686,2613100635,1974974402,3791519004,1033081774,1277568618,1815492186,2118074177,4126668546,2211236943,1748251740,1369810420,3521504564,4193382664,3799085459,2883115123,1647391059,706024767,134480908,2512897874,1176707941,2646852446,806885416,932615841,168101135,798661301,235341577,605164086,461406363,3756188221,3454790438,1311188841,2142417613,3933566367,302582043,495158174,1479289972,874125870,907746093,3698224818,3025820398,1537253627,2756858614,1983593293,3084310113,2108928974,1378429307,3722699582,1580150641,327451799,2790478837,3117535592,0,3253595436,1075847264,3825007647,2041688520,3059440621,3563743934,2378943302,1740553945,1916352843,2487896798,2555137236,2958579944,2244988746,3151024235,3320835882,1336584933,3992714006,2252555205,2588757463,1714631509,293963156,2319795663,3925473552,67240454,4269768577,2689618160,2017213508,631218106,1269344483,2723238387,1571005438,2151694528,93294474,1066570413,563977660,1882732616,4059428100,1673313503,2008463041,2950355573,1109467491,537923632,3858759450,4260623118,3218264685,2177748300,403442708,638784309,3287084079,3193921505,899127202,2286175436,773265209,2479146071,1437050866,4236148354,2050833735,3362022572,3126681063,840505643,3866325909,3227541664,427917720,2655997905,2749160575,1143087718,1412049534,999329963,193497219,2353415882,3354324521,1807268051,672404540,2816401017,3160301282,369822493,2916866934,3688947771,1681011286,1949973070,336202270,2454276571,201721354,1210328172,3093060836,2680341085,3184776046,1135389935,3294782118,965841320,831886756,3554993207,4068047243,3588745010,2345191491,1849112409,3664604599,26054028,2983581028,2622377682,1235855840,3630984372,2891339514,4092916743,3488279077,3395642799,4101667470,1202630377,268961816,1874508501,4034427016,1243948399,1546530418,941366308,1470539505,1941222599,2546386513,3421038627,2715671932,3899946140,1042226977,2521517021,1639824860,227249030,260737669,3765465232,2084453954,1907733956,3429263018,2420656344,100860677,4160157185,470683154,3261161891,1781871967,2924959737,1773779408,394692241,2579611992,974986535,664706745,3655459128,3958962195,731420851,571543859,3530123707,2849626480,126783113,865375399,765172662,1008606754,361203602,3387549984,2278477385,2857719295,1344809080,2782912378,59542671,1503764984,160008576,437062935,1707065306,3622233649,2218934982,3496503480,2185314755,697932208,1512910199,504303377,2075177163,2824099068,1841019862,739644986],T2=[2781242211,2230877308,2582542199,2381740923,234877682,3184946027,2984144751,1418839493,1348481072,50462977,2848876391,2102799147,434634494,1656084439,3863849899,2599188086,1167051466,2636087938,1082771913,2281340285,368048890,3954334041,3381544775,201060592,3963727277,1739838676,4250903202,3930435503,3206782108,4149453988,2531553906,1536934080,3262494647,484572669,2923271059,1783375398,1517041206,1098792767,49674231,1334037708,1550332980,4098991525,886171109,150598129,2481090929,1940642008,1398944049,1059722517,201851908,1385547719,1699095331,1587397571,674240536,2704774806,252314885,3039795866,151914247,908333586,2602270848,1038082786,651029483,1766729511,3447698098,2682942837,454166793,2652734339,1951935532,775166490,758520603,3000790638,4004797018,4217086112,4137964114,1299594043,1639438038,3464344499,2068982057,1054729187,1901997871,2534638724,4121318227,1757008337,0,750906861,1614815264,535035132,3363418545,3988151131,3201591914,1183697867,3647454910,1265776953,3734260298,3566750796,3903871064,1250283471,1807470800,717615087,3847203498,384695291,3313910595,3617213773,1432761139,2484176261,3481945413,283769337,100925954,2180939647,4037038160,1148730428,3123027871,3813386408,4087501137,4267549603,3229630528,2315620239,2906624658,3156319645,1215313976,82966005,3747855548,3245848246,1974459098,1665278241,807407632,451280895,251524083,1841287890,1283575245,337120268,891687699,801369324,3787349855,2721421207,3431482436,959321879,1469301956,4065699751,2197585534,1199193405,2898814052,3887750493,724703513,2514908019,2696962144,2551808385,3516813135,2141445340,1715741218,2119445034,2872807568,2198571144,3398190662,700968686,3547052216,1009259540,2041044702,3803995742,487983883,1991105499,1004265696,1449407026,1316239930,504629770,3683797321,168560134,1816667172,3837287516,1570751170,1857934291,4014189740,2797888098,2822345105,2754712981,936633572,2347923833,852879335,1133234376,1500395319,3084545389,2348912013,1689376213,3533459022,3762923945,3034082412,4205598294,133428468,634383082,2949277029,2398386810,3913789102,403703816,3580869306,2297460856,1867130149,1918643758,607656988,4049053350,3346248884,1368901318,600565992,2090982877,2632479860,557719327,3717614411,3697393085,2249034635,2232388234,2430627952,1115438654,3295786421,2865522278,3633334344,84280067,33027830,303828494,2747425121,1600795957,4188952407,3496589753,2434238086,1486471617,658119965,3106381470,953803233,334231800,3005978776,857870609,3151128937,1890179545,2298973838,2805175444,3056442267,574365214,2450884487,550103529,1233637070,4289353045,2018519080,2057691103,2399374476,4166623649,2148108681,387583245,3664101311,836232934,3330556482,3100665960,3280093505,2955516313,2002398509,287182607,3413881008,4238890068,3597515707,975967766],T3=[1671808611,2089089148,2006576759,2072901243,4061003762,1807603307,1873927791,3310653893,810573872,16974337,1739181671,729634347,4263110654,3613570519,2883997099,1989864566,3393556426,2191335298,3376449993,2106063485,4195741690,1508618841,1204391495,4027317232,2917941677,3563566036,2734514082,2951366063,2629772188,2767672228,1922491506,3227229120,3082974647,4246528509,2477669779,644500518,911895606,1061256767,4144166391,3427763148,878471220,2784252325,3845444069,4043897329,1905517169,3631459288,827548209,356461077,67897348,3344078279,593839651,3277757891,405286936,2527147926,84871685,2595565466,118033927,305538066,2157648768,3795705826,3945188843,661212711,2999812018,1973414517,152769033,2208177539,745822252,439235610,455947803,1857215598,1525593178,2700827552,1391895634,994932283,3596728278,3016654259,695947817,3812548067,795958831,2224493444,1408607827,3513301457,0,3979133421,543178784,4229948412,2982705585,1542305371,1790891114,3410398667,3201918910,961245753,1256100938,1289001036,1491644504,3477767631,3496721360,4012557807,2867154858,4212583931,1137018435,1305975373,861234739,2241073541,1171229253,4178635257,33948674,2139225727,1357946960,1011120188,2679776671,2833468328,1374921297,2751356323,1086357568,2408187279,2460827538,2646352285,944271416,4110742005,3168756668,3066132406,3665145818,560153121,271589392,4279952895,4077846003,3530407890,3444343245,202643468,322250259,3962553324,1608629855,2543990167,1154254916,389623319,3294073796,2817676711,2122513534,1028094525,1689045092,1575467613,422261273,1939203699,1621147744,2174228865,1339137615,3699352540,577127458,712922154,2427141008,2290289544,1187679302,3995715566,3100863416,339486740,3732514782,1591917662,186455563,3681988059,3762019296,844522546,978220090,169743370,1239126601,101321734,611076132,1558493276,3260915650,3547250131,2901361580,1655096418,2443721105,2510565781,3828863972,2039214713,3878868455,3359869896,928607799,1840765549,2374762893,3580146133,1322425422,2850048425,1823791212,1459268694,4094161908,3928346602,1706019429,2056189050,2934523822,135794696,3134549946,2022240376,628050469,779246638,472135708,2800834470,3032970164,3327236038,3894660072,3715932637,1956440180,522272287,1272813131,3185336765,2340818315,2323976074,1888542832,1044544574,3049550261,1722469478,1222152264,50660867,4127324150,236067854,1638122081,895445557,1475980887,3117443513,2257655686,3243809217,489110045,2662934430,3778599393,4162055160,2561878936,288563729,1773916777,3648039385,2391345038,2493985684,2612407707,505560094,2274497927,3911240169,3460925390,1442818645,678973480,3749357023,2358182796,2717407649,2306869641,219617805,3218761151,3862026214,1120306242,1756942440,1103331905,2578459033,762796589,252780047,2966125488,1425844308,3151392187,372911126],T4=[1667474886,2088535288,2004326894,2071694838,4075949567,1802223062,1869591006,3318043793,808472672,16843522,1734846926,724270422,4278065639,3621216949,2880169549,1987484396,3402253711,2189597983,3385409673,2105378810,4210693615,1499065266,1195886990,4042263547,2913856577,3570689971,2728590687,2947541573,2627518243,2762274643,1920112356,3233831835,3082273397,4261223649,2475929149,640051788,909531756,1061110142,4160160501,3435941763,875846760,2779116625,3857003729,4059105529,1903268834,3638064043,825316194,353713962,67374088,3351728789,589522246,3284360861,404236336,2526454071,84217610,2593830191,117901582,303183396,2155911963,3806477791,3958056653,656894286,2998062463,1970642922,151591698,2206440989,741110872,437923380,454765878,1852748508,1515908788,2694904667,1381168804,993742198,3604373943,3014905469,690584402,3823320797,791638366,2223281939,1398011302,3520161977,0,3991743681,538992704,4244381667,2981218425,1532751286,1785380564,3419096717,3200178535,960056178,1246420628,1280103576,1482221744,3486468741,3503319995,4025428677,2863326543,4227536621,1128514950,1296947098,859002214,2240123921,1162203018,4193849577,33687044,2139062782,1347481760,1010582648,2678045221,2829640523,1364325282,2745433693,1077985408,2408548869,2459086143,2644360225,943212656,4126475505,3166494563,3065430391,3671750063,555836226,269496352,4294908645,4092792573,3537006015,3452783745,202118168,320025894,3974901699,1600119230,2543297077,1145359496,387397934,3301201811,2812801621,2122220284,1027426170,1684319432,1566435258,421079858,1936954854,1616945344,2172753945,1330631070,3705438115,572679748,707427924,2425400123,2290647819,1179044492,4008585671,3099120491,336870440,3739122087,1583276732,185277718,3688593069,3772791771,842159716,976899700,168435220,1229577106,101059084,606366792,1549591736,3267517855,3553849021,2897014595,1650632388,2442242105,2509612081,3840161747,2038008818,3890688725,3368567691,926374254,1835907034,2374863873,3587531953,1313788572,2846482505,1819063512,1448540844,4109633523,3941213647,1701162954,2054852340,2930698567,134748176,3132806511,2021165296,623210314,774795868,471606328,2795958615,3031746419,3334885783,3907527627,3722280097,1953799400,522133822,1263263126,3183336545,2341176845,2324333839,1886425312,1044267644,3048588401,1718004428,1212733584,50529542,4143317495,235803164,1633788866,892690282,1465383342,3115962473,2256965911,3250673817,488449850,2661202215,3789633753,4177007595,2560144171,286339874,1768537042,3654906025,2391705863,2492770099,2610673197,505291324,2273808917,3924369609,3469625735,1431699370,673740880,3755965093,2358021891,2711746649,2307489801,218961690,3217021541,3873845719,1111672452,1751693520,1094828930,2576986153,757954394,252645662,2964376443,1414855848,3149649517,370555436],T5=[1374988112,2118214995,437757123,975658646,1001089995,530400753,2902087851,1273168787,540080725,2910219766,2295101073,4110568485,1340463100,3307916247,641025152,3043140495,3736164937,632953703,1172967064,1576976609,3274667266,2169303058,2370213795,1809054150,59727847,361929877,3211623147,2505202138,3569255213,1484005843,1239443753,2395588676,1975683434,4102977912,2572697195,666464733,3202437046,4035489047,3374361702,2110667444,1675577880,3843699074,2538681184,1649639237,2976151520,3144396420,4269907996,4178062228,1883793496,2403728665,2497604743,1383856311,2876494627,1917518562,3810496343,1716890410,3001755655,800440835,2261089178,3543599269,807962610,599762354,33778362,3977675356,2328828971,2809771154,4077384432,1315562145,1708848333,101039829,3509871135,3299278474,875451293,2733856160,92987698,2767645557,193195065,1080094634,1584504582,3178106961,1042385657,2531067453,3711829422,1306967366,2438237621,1908694277,67556463,1615861247,429456164,3602770327,2302690252,1742315127,2968011453,126454664,3877198648,2043211483,2709260871,2084704233,4169408201,0,159417987,841739592,504459436,1817866830,4245618683,260388950,1034867998,908933415,168810852,1750902305,2606453969,607530554,202008497,2472011535,3035535058,463180190,2160117071,1641816226,1517767529,470948374,3801332234,3231722213,1008918595,303765277,235474187,4069246893,766945465,337553864,1475418501,2943682380,4003061179,2743034109,4144047775,1551037884,1147550661,1543208500,2336434550,3408119516,3069049960,3102011747,3610369226,1113818384,328671808,2227573024,2236228733,3535486456,2935566865,3341394285,496906059,3702665459,226906860,2009195472,733156972,2842737049,294930682,1206477858,2835123396,2700099354,1451044056,573804783,2269728455,3644379585,2362090238,2564033334,2801107407,2776292904,3669462566,1068351396,742039012,1350078989,1784663195,1417561698,4136440770,2430122216,775550814,2193862645,2673705150,1775276924,1876241833,3475313331,3366754619,270040487,3902563182,3678124923,3441850377,1851332852,3969562369,2203032232,3868552805,2868897406,566021896,4011190502,3135740889,1248802510,3936291284,699432150,832877231,708780849,3332740144,899835584,1951317047,4236429990,3767586992,866637845,4043610186,1106041591,2144161806,395441711,1984812685,1139781709,3433712980,3835036895,2664543715,1282050075,3240894392,1181045119,2640243204,25965917,4203181171,4211818798,3009879386,2463879762,3910161971,1842759443,2597806476,933301370,1509430414,3943906441,3467192302,3076639029,3776767469,2051518780,2631065433,1441952575,404016761,1942435775,1408749034,1610459739,3745345300,2017778566,3400528769,3110650942,941896748,3265478751,371049330,3168937228,675039627,4279080257,967311729,135050206,3635733660,1683407248,2076935265,3576870512,1215061108,3501741890],T6=[1347548327,1400783205,3273267108,2520393566,3409685355,4045380933,2880240216,2471224067,1428173050,4138563181,2441661558,636813900,4233094615,3620022987,2149987652,2411029155,1239331162,1730525723,2554718734,3781033664,46346101,310463728,2743944855,3328955385,3875770207,2501218972,3955191162,3667219033,768917123,3545789473,692707433,1150208456,1786102409,2029293177,1805211710,3710368113,3065962831,401639597,1724457132,3028143674,409198410,2196052529,1620529459,1164071807,3769721975,2226875310,486441376,2499348523,1483753576,428819965,2274680428,3075636216,598438867,3799141122,1474502543,711349675,129166120,53458370,2592523643,2782082824,4063242375,2988687269,3120694122,1559041666,730517276,2460449204,4042459122,2706270690,3446004468,3573941694,533804130,2328143614,2637442643,2695033685,839224033,1973745387,957055980,2856345839,106852767,1371368976,4181598602,1033297158,2933734917,1179510461,3046200461,91341917,1862534868,4284502037,605657339,2547432937,3431546947,2003294622,3182487618,2282195339,954669403,3682191598,1201765386,3917234703,3388507166,0,2198438022,1211247597,2887651696,1315723890,4227665663,1443857720,507358933,657861945,1678381017,560487590,3516619604,975451694,2970356327,261314535,3535072918,2652609425,1333838021,2724322336,1767536459,370938394,182621114,3854606378,1128014560,487725847,185469197,2918353863,3106780840,3356761769,2237133081,1286567175,3152976349,4255350624,2683765030,3160175349,3309594171,878443390,1988838185,3704300486,1756818940,1673061617,3403100636,272786309,1075025698,545572369,2105887268,4174560061,296679730,1841768865,1260232239,4091327024,3960309330,3497509347,1814803222,2578018489,4195456072,575138148,3299409036,446754879,3629546796,4011996048,3347532110,3252238545,4270639778,915985419,3483825537,681933534,651868046,2755636671,3828103837,223377554,2607439820,1649704518,3270937875,3901806776,1580087799,4118987695,3198115200,2087309459,2842678573,3016697106,1003007129,2802849917,1860738147,2077965243,164439672,4100872472,32283319,2827177882,1709610350,2125135846,136428751,3874428392,3652904859,3460984630,3572145929,3593056380,2939266226,824852259,818324884,3224740454,930369212,2801566410,2967507152,355706840,1257309336,4148292826,243256656,790073846,2373340630,1296297904,1422699085,3756299780,3818836405,457992840,3099667487,2135319889,77422314,1560382517,1945798516,788204353,1521706781,1385356242,870912086,325965383,2358957921,2050466060,2388260884,2313884476,4006521127,901210569,3990953189,1014646705,1503449823,1062597235,2031621326,3212035895,3931371469,1533017514,350174575,2256028891,2177544179,1052338372,741876788,1606591296,1914052035,213705253,2334669897,1107234197,1899603969,3725069491,2631447780,2422494913,1635502980,1893020342,1950903388,1120974935],T7=[2807058932,1699970625,2764249623,1586903591,1808481195,1173430173,1487645946,59984867,4199882800,1844882806,1989249228,1277555970,3623636965,3419915562,1149249077,2744104290,1514790577,459744698,244860394,3235995134,1963115311,4027744588,2544078150,4190530515,1608975247,2627016082,2062270317,1507497298,2200818878,567498868,1764313568,3359936201,2305455554,2037970062,1047239e3,1910319033,1337376481,2904027272,2892417312,984907214,1243112415,830661914,861968209,2135253587,2011214180,2927934315,2686254721,731183368,1750626376,4246310725,1820824798,4172763771,3542330227,48394827,2404901663,2871682645,671593195,3254988725,2073724613,145085239,2280796200,2779915199,1790575107,2187128086,472615631,3029510009,4075877127,3802222185,4107101658,3201631749,1646252340,4270507174,1402811438,1436590835,3778151818,3950355702,3963161475,4020912224,2667994737,273792366,2331590177,104699613,95345982,3175501286,2377486676,1560637892,3564045318,369057872,4213447064,3919042237,1137477952,2658625497,1119727848,2340947849,1530455833,4007360968,172466556,266959938,516552836,0,2256734592,3980931627,1890328081,1917742170,4294704398,945164165,3575528878,958871085,3647212047,2787207260,1423022939,775562294,1739656202,3876557655,2530391278,2443058075,3310321856,547512796,1265195639,437656594,3121275539,719700128,3762502690,387781147,218828297,3350065803,2830708150,2848461854,428169201,122466165,3720081049,1627235199,648017665,4122762354,1002783846,2117360635,695634755,3336358691,4234721005,4049844452,3704280881,2232435299,574624663,287343814,612205898,1039717051,840019705,2708326185,793451934,821288114,1391201670,3822090177,376187827,3113855344,1224348052,1679968233,2361698556,1058709744,752375421,2431590963,1321699145,3519142200,2734591178,188127444,2177869557,3727205754,2384911031,3215212461,2648976442,2450346104,3432737375,1180849278,331544205,3102249176,4150144569,2952102595,2159976285,2474404304,766078933,313773861,2570832044,2108100632,1668212892,3145456443,2013908262,418672217,3070356634,2594734927,1852171925,3867060991,3473416636,3907448597,2614737639,919489135,164948639,2094410160,2997825956,590424639,2486224549,1723872674,3157750862,3399941250,3501252752,3625268135,2555048196,3673637356,1343127501,4130281361,3599595085,2957853679,1297403050,81781910,3051593425,2283490410,532201772,1367295589,3926170974,895287692,1953757831,1093597963,492483431,3528626907,1446242576,1192455638,1636604631,209336225,344873464,1015671571,669961897,3375740769,3857572124,2973530695,3747192018,1933530610,3464042516,935293895,3454686199,2858115069,1863638845,3683022916,4085369519,3292445032,875313188,1080017571,3279033885,621591778,1233856572,2504130317,24197544,3017672716,3835484340,3247465558,2220981195,3060847922,1551124588,1463996600],T8=[4104605777,1097159550,396673818,660510266,2875968315,2638606623,4200115116,3808662347,821712160,1986918061,3430322568,38544885,3856137295,718002117,893681702,1654886325,2975484382,3122358053,3926825029,4274053469,796197571,1290801793,1184342925,3556361835,2405426947,2459735317,1836772287,1381620373,3196267988,1948373848,3764988233,3385345166,3263785589,2390325492,1480485785,3111247143,3780097726,2293045232,548169417,3459953789,3746175075,439452389,1362321559,1400849762,1685577905,1806599355,2174754046,137073913,1214797936,1174215055,3731654548,2079897426,1943217067,1258480242,529487843,1437280870,3945269170,3049390895,3313212038,923313619,679998e3,3215307299,57326082,377642221,3474729866,2041877159,133361907,1776460110,3673476453,96392454,878845905,2801699524,777231668,4082475170,2330014213,4142626212,2213296395,1626319424,1906247262,1846563261,562755902,3708173718,1040559837,3871163981,1418573201,3294430577,114585348,1343618912,2566595609,3186202582,1078185097,3651041127,3896688048,2307622919,425408743,3371096953,2081048481,1108339068,2216610296,0,2156299017,736970802,292596766,1517440620,251657213,2235061775,2933202493,758720310,265905162,1554391400,1532285339,908999204,174567692,1474760595,4002861748,2610011675,3234156416,3693126241,2001430874,303699484,2478443234,2687165888,585122620,454499602,151849742,2345119218,3064510765,514443284,4044981591,1963412655,2581445614,2137062819,19308535,1928707164,1715193156,4219352155,1126790795,600235211,3992742070,3841024952,836553431,1669664834,2535604243,3323011204,1243905413,3141400786,4180808110,698445255,2653899549,2989552604,2253581325,3252932727,3004591147,1891211689,2487810577,3915653703,4237083816,4030667424,2100090966,865136418,1229899655,953270745,3399679628,3557504664,4118925222,2061379749,3079546586,2915017791,983426092,2022837584,1607244650,2118541908,2366882550,3635996816,972512814,3283088770,1568718495,3499326569,3576539503,621982671,2895723464,410887952,2623762152,1002142683,645401037,1494807662,2595684844,1335535747,2507040230,4293295786,3167684641,367585007,3885750714,1865862730,2668221674,2960971305,2763173681,1059270954,2777952454,2724642869,1320957812,2194319100,2429595872,2815956275,77089521,3973773121,3444575871,2448830231,1305906550,4021308739,2857194700,2516901860,3518358430,1787304780,740276417,1699839814,1592394909,2352307457,2272556026,188821243,1729977011,3687994002,274084841,3594982253,3613494426,2701949495,4162096729,322734571,2837966542,1640576439,484830689,1202797690,3537852828,4067639125,349075736,3342319475,4157467219,4255800159,1030690015,1155237496,2951971274,1757691577,607398968,2738905026,499347990,3794078908,1011452712,227885567,2818666809,213114376,3034881240,1455525988,3414450555,850817237,1817998408,3092726480],U1=[0,235474187,470948374,303765277,941896748,908933415,607530554,708780849,1883793496,2118214995,1817866830,1649639237,1215061108,1181045119,1417561698,1517767529,3767586992,4003061179,4236429990,4069246893,3635733660,3602770327,3299278474,3400528769,2430122216,2664543715,2362090238,2193862645,2835123396,2801107407,3035535058,3135740889,3678124923,3576870512,3341394285,3374361702,3810496343,3977675356,4279080257,4043610186,2876494627,2776292904,3076639029,3110650942,2472011535,2640243204,2403728665,2169303058,1001089995,899835584,666464733,699432150,59727847,226906860,530400753,294930682,1273168787,1172967064,1475418501,1509430414,1942435775,2110667444,1876241833,1641816226,2910219766,2743034109,2976151520,3211623147,2505202138,2606453969,2302690252,2269728455,3711829422,3543599269,3240894392,3475313331,3843699074,3943906441,4178062228,4144047775,1306967366,1139781709,1374988112,1610459739,1975683434,2076935265,1775276924,1742315127,1034867998,866637845,566021896,800440835,92987698,193195065,429456164,395441711,1984812685,2017778566,1784663195,1683407248,1315562145,1080094634,1383856311,1551037884,101039829,135050206,437757123,337553864,1042385657,807962610,573804783,742039012,2531067453,2564033334,2328828971,2227573024,2935566865,2700099354,3001755655,3168937228,3868552805,3902563182,4203181171,4102977912,3736164937,3501741890,3265478751,3433712980,1106041591,1340463100,1576976609,1408749034,2043211483,2009195472,1708848333,1809054150,832877231,1068351396,766945465,599762354,159417987,126454664,361929877,463180190,2709260871,2943682380,3178106961,3009879386,2572697195,2538681184,2236228733,2336434550,3509871135,3745345300,3441850377,3274667266,3910161971,3877198648,4110568485,4211818798,2597806476,2497604743,2261089178,2295101073,2733856160,2902087851,3202437046,2968011453,3936291284,3835036895,4136440770,4169408201,3535486456,3702665459,3467192302,3231722213,2051518780,1951317047,1716890410,1750902305,1113818384,1282050075,1584504582,1350078989,168810852,67556463,371049330,404016761,841739592,1008918595,775550814,540080725,3969562369,3801332234,4035489047,4269907996,3569255213,3669462566,3366754619,3332740144,2631065433,2463879762,2160117071,2395588676,2767645557,2868897406,3102011747,3069049960,202008497,33778362,270040487,504459436,875451293,975658646,675039627,641025152,2084704233,1917518562,1615861247,1851332852,1147550661,1248802510,1484005843,1451044056,933301370,967311729,733156972,632953703,260388950,25965917,328671808,496906059,1206477858,1239443753,1543208500,1441952575,2144161806,1908694277,1675577880,1842759443,3610369226,3644379585,3408119516,3307916247,4011190502,3776767469,4077384432,4245618683,2809771154,2842737049,3144396420,3043140495,2673705150,2438237621,2203032232,2370213795],U2=[0,185469197,370938394,487725847,741876788,657861945,975451694,824852259,1483753576,1400783205,1315723890,1164071807,1950903388,2135319889,1649704518,1767536459,2967507152,3152976349,2801566410,2918353863,2631447780,2547432937,2328143614,2177544179,3901806776,3818836405,4270639778,4118987695,3299409036,3483825537,3535072918,3652904859,2077965243,1893020342,1841768865,1724457132,1474502543,1559041666,1107234197,1257309336,598438867,681933534,901210569,1052338372,261314535,77422314,428819965,310463728,3409685355,3224740454,3710368113,3593056380,3875770207,3960309330,4045380933,4195456072,2471224067,2554718734,2237133081,2388260884,3212035895,3028143674,2842678573,2724322336,4138563181,4255350624,3769721975,3955191162,3667219033,3516619604,3431546947,3347532110,2933734917,2782082824,3099667487,3016697106,2196052529,2313884476,2499348523,2683765030,1179510461,1296297904,1347548327,1533017514,1786102409,1635502980,2087309459,2003294622,507358933,355706840,136428751,53458370,839224033,957055980,605657339,790073846,2373340630,2256028891,2607439820,2422494913,2706270690,2856345839,3075636216,3160175349,3573941694,3725069491,3273267108,3356761769,4181598602,4063242375,4011996048,3828103837,1033297158,915985419,730517276,545572369,296679730,446754879,129166120,213705253,1709610350,1860738147,1945798516,2029293177,1239331162,1120974935,1606591296,1422699085,4148292826,4233094615,3781033664,3931371469,3682191598,3497509347,3446004468,3328955385,2939266226,2755636671,3106780840,2988687269,2198438022,2282195339,2501218972,2652609425,1201765386,1286567175,1371368976,1521706781,1805211710,1620529459,2105887268,1988838185,533804130,350174575,164439672,46346101,870912086,954669403,636813900,788204353,2358957921,2274680428,2592523643,2441661558,2695033685,2880240216,3065962831,3182487618,3572145929,3756299780,3270937875,3388507166,4174560061,4091327024,4006521127,3854606378,1014646705,930369212,711349675,560487590,272786309,457992840,106852767,223377554,1678381017,1862534868,1914052035,2031621326,1211247597,1128014560,1580087799,1428173050,32283319,182621114,401639597,486441376,768917123,651868046,1003007129,818324884,1503449823,1385356242,1333838021,1150208456,1973745387,2125135846,1673061617,1756818940,2970356327,3120694122,2802849917,2887651696,2637442643,2520393566,2334669897,2149987652,3917234703,3799141122,4284502037,4100872472,3309594171,3460984630,3545789473,3629546796,2050466060,1899603969,1814803222,1730525723,1443857720,1560382517,1075025698,1260232239,575138148,692707433,878443390,1062597235,243256656,91341917,409198410,325965383,3403100636,3252238545,3704300486,3620022987,3874428392,3990953189,4042459122,4227665663,2460449204,2578018489,2226875310,2411029155,3198115200,3046200461,2827177882,2743944855],U3=[0,218828297,437656594,387781147,875313188,958871085,775562294,590424639,1750626376,1699970625,1917742170,2135253587,1551124588,1367295589,1180849278,1265195639,3501252752,3720081049,3399941250,3350065803,3835484340,3919042237,4270507174,4085369519,3102249176,3051593425,2734591178,2952102595,2361698556,2177869557,2530391278,2614737639,3145456443,3060847922,2708326185,2892417312,2404901663,2187128086,2504130317,2555048196,3542330227,3727205754,3375740769,3292445032,3876557655,3926170974,4246310725,4027744588,1808481195,1723872674,1910319033,2094410160,1608975247,1391201670,1173430173,1224348052,59984867,244860394,428169201,344873464,935293895,984907214,766078933,547512796,1844882806,1627235199,2011214180,2062270317,1507497298,1423022939,1137477952,1321699145,95345982,145085239,532201772,313773861,830661914,1015671571,731183368,648017665,3175501286,2957853679,2807058932,2858115069,2305455554,2220981195,2474404304,2658625497,3575528878,3625268135,3473416636,3254988725,3778151818,3963161475,4213447064,4130281361,3599595085,3683022916,3432737375,3247465558,3802222185,4020912224,4172763771,4122762354,3201631749,3017672716,2764249623,2848461854,2331590177,2280796200,2431590963,2648976442,104699613,188127444,472615631,287343814,840019705,1058709744,671593195,621591778,1852171925,1668212892,1953757831,2037970062,1514790577,1463996600,1080017571,1297403050,3673637356,3623636965,3235995134,3454686199,4007360968,3822090177,4107101658,4190530515,2997825956,3215212461,2830708150,2779915199,2256734592,2340947849,2627016082,2443058075,172466556,122466165,273792366,492483431,1047239e3,861968209,612205898,695634755,1646252340,1863638845,2013908262,1963115311,1446242576,1530455833,1277555970,1093597963,1636604631,1820824798,2073724613,1989249228,1436590835,1487645946,1337376481,1119727848,164948639,81781910,331544205,516552836,1039717051,821288114,669961897,719700128,2973530695,3157750862,2871682645,2787207260,2232435299,2283490410,2667994737,2450346104,3647212047,3564045318,3279033885,3464042516,3980931627,3762502690,4150144569,4199882800,3070356634,3121275539,2904027272,2686254721,2200818878,2384911031,2570832044,2486224549,3747192018,3528626907,3310321856,3359936201,3950355702,3867060991,4049844452,4234721005,1739656202,1790575107,2108100632,1890328081,1402811438,1586903591,1233856572,1149249077,266959938,48394827,369057872,418672217,1002783846,919489135,567498868,752375421,209336225,24197544,376187827,459744698,945164165,895287692,574624663,793451934,1679968233,1764313568,2117360635,1933530610,1343127501,1560637892,1243112415,1192455638,3704280881,3519142200,3336358691,3419915562,3907448597,3857572124,4075877127,4294704398,3029510009,3113855344,2927934315,2744104290,2159976285,2377486676,2594734927,2544078150],U4=[0,151849742,303699484,454499602,607398968,758720310,908999204,1059270954,1214797936,1097159550,1517440620,1400849762,1817998408,1699839814,2118541908,2001430874,2429595872,2581445614,2194319100,2345119218,3034881240,3186202582,2801699524,2951971274,3635996816,3518358430,3399679628,3283088770,4237083816,4118925222,4002861748,3885750714,1002142683,850817237,698445255,548169417,529487843,377642221,227885567,77089521,1943217067,2061379749,1640576439,1757691577,1474760595,1592394909,1174215055,1290801793,2875968315,2724642869,3111247143,2960971305,2405426947,2253581325,2638606623,2487810577,3808662347,3926825029,4044981591,4162096729,3342319475,3459953789,3576539503,3693126241,1986918061,2137062819,1685577905,1836772287,1381620373,1532285339,1078185097,1229899655,1040559837,923313619,740276417,621982671,439452389,322734571,137073913,19308535,3871163981,4021308739,4104605777,4255800159,3263785589,3414450555,3499326569,3651041127,2933202493,2815956275,3167684641,3049390895,2330014213,2213296395,2566595609,2448830231,1305906550,1155237496,1607244650,1455525988,1776460110,1626319424,2079897426,1928707164,96392454,213114376,396673818,514443284,562755902,679998e3,865136418,983426092,3708173718,3557504664,3474729866,3323011204,4180808110,4030667424,3945269170,3794078908,2507040230,2623762152,2272556026,2390325492,2975484382,3092726480,2738905026,2857194700,3973773121,3856137295,4274053469,4157467219,3371096953,3252932727,3673476453,3556361835,2763173681,2915017791,3064510765,3215307299,2156299017,2307622919,2459735317,2610011675,2081048481,1963412655,1846563261,1729977011,1480485785,1362321559,1243905413,1126790795,878845905,1030690015,645401037,796197571,274084841,425408743,38544885,188821243,3613494426,3731654548,3313212038,3430322568,4082475170,4200115116,3780097726,3896688048,2668221674,2516901860,2366882550,2216610296,3141400786,2989552604,2837966542,2687165888,1202797690,1320957812,1437280870,1554391400,1669664834,1787304780,1906247262,2022837584,265905162,114585348,499347990,349075736,736970802,585122620,972512814,821712160,2595684844,2478443234,2293045232,2174754046,3196267988,3079546586,2895723464,2777952454,3537852828,3687994002,3234156416,3385345166,4142626212,4293295786,3841024952,3992742070,174567692,57326082,410887952,292596766,777231668,660510266,1011452712,893681702,1108339068,1258480242,1343618912,1494807662,1715193156,1865862730,1948373848,2100090966,2701949495,2818666809,3004591147,3122358053,2235061775,2352307457,2535604243,2653899549,3915653703,3764988233,4219352155,4067639125,3444575871,3294430577,3746175075,3594982253,836553431,953270745,600235211,718002117,367585007,484830689,133361907,251657213,2041877159,1891211689,1806599355,1654886325,1568718495,1418573201,1335535747,1184342925];function convertToInt32(bytes){for(var result=[],i=0;i>2,this._Ke[index][i%4]=tk[i],this._Kd[rounds-index][i%4]=tk[i];for(var tt,rconpointer=0,t=KC;t>16&255]<<24^S[tt>>8&255]<<16^S[255&tt]<<8^S[tt>>24&255]^rcon[rconpointer]<<24,rconpointer+=1,8!=KC)for(i=1;i>8&255]<<8^S[tt>>16&255]<<16^S[tt>>24&255]<<24;for(i=KC/2+1;i>2,c=t%4,this._Ke[r][c]=tk[i],this._Kd[rounds-r][c]=tk[i++],t++}for(var r=1;r>24&255]^U2[tt>>16&255]^U3[tt>>8&255]^U4[255&tt]},AES.prototype.encrypt=function(plaintext){if(16!=plaintext.length)throw new Error("invalid plaintext size (must be 16 bytes)");for(var rounds=this._Ke.length-1,a=[0,0,0,0],t=convertToInt32(plaintext),i=0;i<4;i++)t[i]^=this._Ke[0][i];for(var r=1;r>24&255]^T2[t[(i+1)%4]>>16&255]^T3[t[(i+2)%4]>>8&255]^T4[255&t[(i+3)%4]]^this._Ke[r][i];t=a.slice()}var tt,result=createArray(16);for(i=0;i<4;i++)tt=this._Ke[rounds][i],result[4*i]=255&(S[t[i]>>24&255]^tt>>24),result[4*i+1]=255&(S[t[(i+1)%4]>>16&255]^tt>>16),result[4*i+2]=255&(S[t[(i+2)%4]>>8&255]^tt>>8),result[4*i+3]=255&(S[255&t[(i+3)%4]]^tt);return result},AES.prototype.decrypt=function(ciphertext){if(16!=ciphertext.length)throw new Error("invalid ciphertext size (must be 16 bytes)");for(var rounds=this._Kd.length-1,a=[0,0,0,0],t=convertToInt32(ciphertext),i=0;i<4;i++)t[i]^=this._Kd[0][i];for(var r=1;r>24&255]^T6[t[(i+3)%4]>>16&255]^T7[t[(i+2)%4]>>8&255]^T8[255&t[(i+1)%4]]^this._Kd[r][i];t=a.slice()}var tt,result=createArray(16);for(i=0;i<4;i++)tt=this._Kd[rounds][i],result[4*i]=255&(Si[t[i]>>24&255]^tt>>24),result[4*i+1]=255&(Si[t[(i+3)%4]>>16&255]^tt>>16),result[4*i+2]=255&(Si[t[(i+2)%4]>>8&255]^tt>>8),result[4*i+3]=255&(Si[255&t[(i+1)%4]]^tt);return result};var ModeOfOperationECB=function(key){if(!(this instanceof ModeOfOperationECB))throw Error("AES must be instanitated with `new`");this.description="Electronic Code Block",this.name="ecb",this._aes=new AES(key)};ModeOfOperationECB.prototype.encrypt=function(plaintext){if((plaintext=coerceArray(plaintext)).length%16!=0)throw new Error("invalid plaintext size (must be multiple of 16 bytes)");for(var ciphertext=createArray(plaintext.length),block=createArray(16),i=0;i=0;--index)this._counter[index]=value%256,value>>=8},Counter.prototype.setBytes=function(bytes){if(16!=(bytes=coerceArray(bytes,!0)).length)throw new Error("invalid counter bytes size (must be 16 bytes)");this._counter=bytes},Counter.prototype.increment=function(){for(var i=15;i>=0;i--){if(255!==this._counter[i]){this._counter[i]++;break}this._counter[i]=0}};var ModeOfOperationCTR=function(key,counter){if(!(this instanceof ModeOfOperationCTR))throw Error("AES must be instanitated with `new`");this.description="Counter",this.name="ctr",counter instanceof Counter||(counter=new Counter(counter)),this._counter=counter,this._remainingCounter=null,this._remainingCounterIndex=16,this._aes=new AES(key)};ModeOfOperationCTR.prototype.encrypt=function(plaintext){for(var encrypted=coerceArray(plaintext,!0),i=0;i16)throw new Error("PKCS#7 padding byte out of range");for(var length=data.length-padder,i=0;i{"use strict";const asn1=exports;asn1.bignum=__webpack_require__(4590),asn1.define=__webpack_require__(2500).define,asn1.base=__webpack_require__(1979),asn1.constants=__webpack_require__(6826),asn1.decoders=__webpack_require__(8307),asn1.encoders=__webpack_require__(6579)},2500:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";const encoders=__webpack_require__(6579),decoders=__webpack_require__(8307),inherits=__webpack_require__(5717);function Entity(name,body){this.name=name,this.body=body,this.decoders={},this.encoders={}}exports.define=function define(name,body){return new Entity(name,body)},Entity.prototype._createNamed=function createNamed(Base){const name=this.name;function Generated(entity){this._initNamed(entity,name)}return inherits(Generated,Base),Generated.prototype._initNamed=function _initNamed(entity,name){Base.call(this,entity,name)},new Generated(this)},Entity.prototype._getDecoder=function _getDecoder(enc){return enc=enc||"der",this.decoders.hasOwnProperty(enc)||(this.decoders[enc]=this._createNamed(decoders[enc])),this.decoders[enc]},Entity.prototype.decode=function decode(data,enc,options){return this._getDecoder(enc).decode(data,options)},Entity.prototype._getEncoder=function _getEncoder(enc){return enc=enc||"der",this.encoders.hasOwnProperty(enc)||(this.encoders[enc]=this._createNamed(encoders[enc])),this.encoders[enc]},Entity.prototype.encode=function encode(data,enc,reporter){return this._getEncoder(enc).encode(data,reporter)}},6625:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";const inherits=__webpack_require__(5717),Reporter=__webpack_require__(8465).b,Buffer=__webpack_require__(2399).Buffer;function DecoderBuffer(base,options){Reporter.call(this,options),Buffer.isBuffer(base)?(this.base=base,this.offset=0,this.length=base.length):this.error("Input not Buffer")}function EncoderBuffer(value,reporter){if(Array.isArray(value))this.length=0,this.value=value.map((function(item){return EncoderBuffer.isEncoderBuffer(item)||(item=new EncoderBuffer(item,reporter)),this.length+=item.length,item}),this);else if("number"==typeof value){if(!(0<=value&&value<=255))return reporter.error("non-byte EncoderBuffer value");this.value=value,this.length=1}else if("string"==typeof value)this.value=value,this.length=Buffer.byteLength(value);else{if(!Buffer.isBuffer(value))return reporter.error("Unsupported type: "+typeof value);this.value=value,this.length=value.length}}inherits(DecoderBuffer,Reporter),exports.C=DecoderBuffer,DecoderBuffer.isDecoderBuffer=function isDecoderBuffer(data){if(data instanceof DecoderBuffer)return!0;return"object"==typeof data&&Buffer.isBuffer(data.base)&&"DecoderBuffer"===data.constructor.name&&"number"==typeof data.offset&&"number"==typeof data.length&&"function"==typeof data.save&&"function"==typeof data.restore&&"function"==typeof data.isEmpty&&"function"==typeof data.readUInt8&&"function"==typeof data.skip&&"function"==typeof data.raw},DecoderBuffer.prototype.save=function save(){return{offset:this.offset,reporter:Reporter.prototype.save.call(this)}},DecoderBuffer.prototype.restore=function restore(save){const res=new DecoderBuffer(this.base);return res.offset=save.offset,res.length=this.offset,this.offset=save.offset,Reporter.prototype.restore.call(this,save.reporter),res},DecoderBuffer.prototype.isEmpty=function isEmpty(){return this.offset===this.length},DecoderBuffer.prototype.readUInt8=function readUInt8(fail){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(fail||"DecoderBuffer overrun")},DecoderBuffer.prototype.skip=function skip(bytes,fail){if(!(this.offset+bytes<=this.length))return this.error(fail||"DecoderBuffer overrun");const res=new DecoderBuffer(this.base);return res._reporterState=this._reporterState,res.offset=this.offset,res.length=this.offset+bytes,this.offset+=bytes,res},DecoderBuffer.prototype.raw=function raw(save){return this.base.slice(save?save.offset:this.offset,this.length)},exports.R=EncoderBuffer,EncoderBuffer.isEncoderBuffer=function isEncoderBuffer(data){if(data instanceof EncoderBuffer)return!0;return"object"==typeof data&&"EncoderBuffer"===data.constructor.name&&"number"==typeof data.length&&"function"==typeof data.join},EncoderBuffer.prototype.join=function join(out,offset){return out||(out=Buffer.alloc(this.length)),offset||(offset=0),0===this.length||(Array.isArray(this.value)?this.value.forEach((function(item){item.join(out,offset),offset+=item.length})):("number"==typeof this.value?out[offset]=this.value:"string"==typeof this.value?out.write(this.value,offset):Buffer.isBuffer(this.value)&&this.value.copy(out,offset),offset+=this.length)),out}},1979:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";const base=exports;base.Reporter=__webpack_require__(8465).b,base.DecoderBuffer=__webpack_require__(6625).C,base.EncoderBuffer=__webpack_require__(6625).R,base.Node=__webpack_require__(1949)},1949:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";const Reporter=__webpack_require__(8465).b,EncoderBuffer=__webpack_require__(6625).R,DecoderBuffer=__webpack_require__(6625).C,assert=__webpack_require__(9746),tags=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],methods=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(tags);function Node(enc,parent,name){const state={};this._baseState=state,state.name=name,state.enc=enc,state.parent=parent||null,state.children=null,state.tag=null,state.args=null,state.reverseArgs=null,state.choice=null,state.optional=!1,state.any=!1,state.obj=!1,state.use=null,state.useDecoder=null,state.key=null,state.default=null,state.explicit=null,state.implicit=null,state.contains=null,state.parent||(state.children=[],this._wrap())}module.exports=Node;const stateProps=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];Node.prototype.clone=function clone(){const state=this._baseState,cstate={};stateProps.forEach((function(prop){cstate[prop]=state[prop]}));const res=new this.constructor(cstate.parent);return res._baseState=cstate,res},Node.prototype._wrap=function wrap(){const state=this._baseState;methods.forEach((function(method){this[method]=function _wrappedMethod(){const clone=new this.constructor(this);return state.children.push(clone),clone[method].apply(clone,arguments)}}),this)},Node.prototype._init=function init(body){const state=this._baseState;assert(null===state.parent),body.call(this),state.children=state.children.filter((function(child){return child._baseState.parent===this}),this),assert.equal(state.children.length,1,"Root node can have only one child")},Node.prototype._useArgs=function useArgs(args){const state=this._baseState,children=args.filter((function(arg){return arg instanceof this.constructor}),this);args=args.filter((function(arg){return!(arg instanceof this.constructor)}),this),0!==children.length&&(assert(null===state.children),state.children=children,children.forEach((function(child){child._baseState.parent=this}),this)),0!==args.length&&(assert(null===state.args),state.args=args,state.reverseArgs=args.map((function(arg){if("object"!=typeof arg||arg.constructor!==Object)return arg;const res={};return Object.keys(arg).forEach((function(key){key==(0|key)&&(key|=0);const value=arg[key];res[value]=key})),res})))},["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"].forEach((function(method){Node.prototype[method]=function _overrided(){const state=this._baseState;throw new Error(method+" not implemented for encoding: "+state.enc)}})),tags.forEach((function(tag){Node.prototype[tag]=function _tagMethod(){const state=this._baseState,args=Array.prototype.slice.call(arguments);return assert(null===state.tag),state.tag=tag,this._useArgs(args),this}})),Node.prototype.use=function use(item){assert(item);const state=this._baseState;return assert(null===state.use),state.use=item,this},Node.prototype.optional=function optional(){return this._baseState.optional=!0,this},Node.prototype.def=function def(val){const state=this._baseState;return assert(null===state.default),state.default=val,state.optional=!0,this},Node.prototype.explicit=function explicit(num){const state=this._baseState;return assert(null===state.explicit&&null===state.implicit),state.explicit=num,this},Node.prototype.implicit=function implicit(num){const state=this._baseState;return assert(null===state.explicit&&null===state.implicit),state.implicit=num,this},Node.prototype.obj=function obj(){const state=this._baseState,args=Array.prototype.slice.call(arguments);return state.obj=!0,0!==args.length&&this._useArgs(args),this},Node.prototype.key=function key(newKey){const state=this._baseState;return assert(null===state.key),state.key=newKey,this},Node.prototype.any=function any(){return this._baseState.any=!0,this},Node.prototype.choice=function choice(obj){const state=this._baseState;return assert(null===state.choice),state.choice=obj,this._useArgs(Object.keys(obj).map((function(key){return obj[key]}))),this},Node.prototype.contains=function contains(item){const state=this._baseState;return assert(null===state.use),state.contains=item,this},Node.prototype._decode=function decode(input,options){const state=this._baseState;if(null===state.parent)return input.wrapResult(state.children[0]._decode(input,options));let prevObj,result=state.default,present=!0,prevKey=null;if(null!==state.key&&(prevKey=input.enterKey(state.key)),state.optional){let tag=null;if(null!==state.explicit?tag=state.explicit:null!==state.implicit?tag=state.implicit:null!==state.tag&&(tag=state.tag),null!==tag||state.any){if(present=this._peekTag(input,tag,state.any),input.isError(present))return present}else{const save=input.save();try{null===state.choice?this._decodeGeneric(state.tag,input,options):this._decodeChoice(input,options),present=!0}catch(e){present=!1}input.restore(save)}}if(state.obj&&present&&(prevObj=input.enterObject()),present){if(null!==state.explicit){const explicit=this._decodeTag(input,state.explicit);if(input.isError(explicit))return explicit;input=explicit}const start=input.offset;if(null===state.use&&null===state.choice){let save;state.any&&(save=input.save());const body=this._decodeTag(input,null!==state.implicit?state.implicit:state.tag,state.any);if(input.isError(body))return body;state.any?result=input.raw(save):input=body}if(options&&options.track&&null!==state.tag&&options.track(input.path(),start,input.length,"tagged"),options&&options.track&&null!==state.tag&&options.track(input.path(),input.offset,input.length,"content"),state.any||(result=null===state.choice?this._decodeGeneric(state.tag,input,options):this._decodeChoice(input,options)),input.isError(result))return result;if(state.any||null!==state.choice||null===state.children||state.children.forEach((function decodeChildren(child){child._decode(input,options)})),state.contains&&("octstr"===state.tag||"bitstr"===state.tag)){const data=new DecoderBuffer(result);result=this._getUse(state.contains,input._reporterState.obj)._decode(data,options)}}return state.obj&&present&&(result=input.leaveObject(prevObj)),null===state.key||null===result&&!0!==present?null!==prevKey&&input.exitKey(prevKey):input.leaveKey(prevKey,state.key,result),result},Node.prototype._decodeGeneric=function decodeGeneric(tag,input,options){const state=this._baseState;return"seq"===tag||"set"===tag?null:"seqof"===tag||"setof"===tag?this._decodeList(input,tag,state.args[0],options):/str$/.test(tag)?this._decodeStr(input,tag,options):"objid"===tag&&state.args?this._decodeObjid(input,state.args[0],state.args[1],options):"objid"===tag?this._decodeObjid(input,null,null,options):"gentime"===tag||"utctime"===tag?this._decodeTime(input,tag,options):"null_"===tag?this._decodeNull(input,options):"bool"===tag?this._decodeBool(input,options):"objDesc"===tag?this._decodeStr(input,tag,options):"int"===tag||"enum"===tag?this._decodeInt(input,state.args&&state.args[0],options):null!==state.use?this._getUse(state.use,input._reporterState.obj)._decode(input,options):input.error("unknown tag: "+tag)},Node.prototype._getUse=function _getUse(entity,obj){const state=this._baseState;return state.useDecoder=this._use(entity,obj),assert(null===state.useDecoder._baseState.parent),state.useDecoder=state.useDecoder._baseState.children[0],state.implicit!==state.useDecoder._baseState.implicit&&(state.useDecoder=state.useDecoder.clone(),state.useDecoder._baseState.implicit=state.implicit),state.useDecoder},Node.prototype._decodeChoice=function decodeChoice(input,options){const state=this._baseState;let result=null,match=!1;return Object.keys(state.choice).some((function(key){const save=input.save(),node=state.choice[key];try{const value=node._decode(input,options);if(input.isError(value))return!1;result={type:key,value},match=!0}catch(e){return input.restore(save),!1}return!0}),this),match?result:input.error("Choice not matched")},Node.prototype._createEncoderBuffer=function createEncoderBuffer(data){return new EncoderBuffer(data,this.reporter)},Node.prototype._encode=function encode(data,reporter,parent){const state=this._baseState;if(null!==state.default&&state.default===data)return;const result=this._encodeValue(data,reporter,parent);return void 0===result||this._skipDefault(result,reporter,parent)?void 0:result},Node.prototype._encodeValue=function encode(data,reporter,parent){const state=this._baseState;if(null===state.parent)return state.children[0]._encode(data,reporter||new Reporter);let result=null;if(this.reporter=reporter,state.optional&&void 0===data){if(null===state.default)return;data=state.default}let content=null,primitive=!1;if(state.any)result=this._createEncoderBuffer(data);else if(state.choice)result=this._encodeChoice(data,reporter);else if(state.contains)content=this._getUse(state.contains,parent)._encode(data,reporter),primitive=!0;else if(state.children)content=state.children.map((function(child){if("null_"===child._baseState.tag)return child._encode(null,reporter,data);if(null===child._baseState.key)return reporter.error("Child should have a key");const prevKey=reporter.enterKey(child._baseState.key);if("object"!=typeof data)return reporter.error("Child expected, but input is not object");const res=child._encode(data[child._baseState.key],reporter,data);return reporter.leaveKey(prevKey),res}),this).filter((function(child){return child})),content=this._createEncoderBuffer(content);else if("seqof"===state.tag||"setof"===state.tag){if(!state.args||1!==state.args.length)return reporter.error("Too many args for : "+state.tag);if(!Array.isArray(data))return reporter.error("seqof/setof, but data is not Array");const child=this.clone();child._baseState.implicit=null,content=this._createEncoderBuffer(data.map((function(item){const state=this._baseState;return this._getUse(state.args[0],data)._encode(item,reporter)}),child))}else null!==state.use?result=this._getUse(state.use,parent)._encode(data,reporter):(content=this._encodePrimitive(state.tag,data),primitive=!0);if(!state.any&&null===state.choice){const tag=null!==state.implicit?state.implicit:state.tag,cls=null===state.implicit?"universal":"context";null===tag?null===state.use&&reporter.error("Tag could be omitted only for .use()"):null===state.use&&(result=this._encodeComposite(tag,primitive,cls,content))}return null!==state.explicit&&(result=this._encodeComposite(state.explicit,!1,"context",result)),result},Node.prototype._encodeChoice=function encodeChoice(data,reporter){const state=this._baseState,node=state.choice[data.type];return node||assert(!1,data.type+" not found in "+JSON.stringify(Object.keys(state.choice))),node._encode(data.value,reporter)},Node.prototype._encodePrimitive=function encodePrimitive(tag,data){const state=this._baseState;if(/str$/.test(tag))return this._encodeStr(data,tag);if("objid"===tag&&state.args)return this._encodeObjid(data,state.reverseArgs[0],state.args[1]);if("objid"===tag)return this._encodeObjid(data,null,null);if("gentime"===tag||"utctime"===tag)return this._encodeTime(data,tag);if("null_"===tag)return this._encodeNull();if("int"===tag||"enum"===tag)return this._encodeInt(data,state.args&&state.reverseArgs[0]);if("bool"===tag)return this._encodeBool(data);if("objDesc"===tag)return this._encodeStr(data,tag);throw new Error("Unsupported tag: "+tag)},Node.prototype._isNumstr=function isNumstr(str){return/^[0-9 ]*$/.test(str)},Node.prototype._isPrintstr=function isPrintstr(str){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(str)}},8465:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";const inherits=__webpack_require__(5717);function Reporter(options){this._reporterState={obj:null,path:[],options:options||{},errors:[]}}function ReporterError(path,msg){this.path=path,this.rethrow(msg)}exports.b=Reporter,Reporter.prototype.isError=function isError(obj){return obj instanceof ReporterError},Reporter.prototype.save=function save(){const state=this._reporterState;return{obj:state.obj,pathLen:state.path.length}},Reporter.prototype.restore=function restore(data){const state=this._reporterState;state.obj=data.obj,state.path=state.path.slice(0,data.pathLen)},Reporter.prototype.enterKey=function enterKey(key){return this._reporterState.path.push(key)},Reporter.prototype.exitKey=function exitKey(index){const state=this._reporterState;state.path=state.path.slice(0,index-1)},Reporter.prototype.leaveKey=function leaveKey(index,key,value){const state=this._reporterState;this.exitKey(index),null!==state.obj&&(state.obj[key]=value)},Reporter.prototype.path=function path(){return this._reporterState.path.join("/")},Reporter.prototype.enterObject=function enterObject(){const state=this._reporterState,prev=state.obj;return state.obj={},prev},Reporter.prototype.leaveObject=function leaveObject(prev){const state=this._reporterState,now=state.obj;return state.obj=prev,now},Reporter.prototype.error=function error(msg){let err;const state=this._reporterState,inherited=msg instanceof ReporterError;if(err=inherited?msg:new ReporterError(state.path.map((function(elem){return"["+JSON.stringify(elem)+"]"})).join(""),msg.message||msg,msg.stack),!state.options.partial)throw err;return inherited||state.errors.push(err),err},Reporter.prototype.wrapResult=function wrapResult(result){const state=this._reporterState;return state.options.partial?{result:this.isError(result)?null:result,errors:state.errors}:result},inherits(ReporterError,Error),ReporterError.prototype.rethrow=function rethrow(msg){if(this.message=msg+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,ReporterError),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}},160:(__unused_webpack_module,exports)=>{"use strict";function reverse(map){const res={};return Object.keys(map).forEach((function(key){(0|key)==key&&(key|=0);const value=map[key];res[value]=key})),res}exports.tagClass={0:"universal",1:"application",2:"context",3:"private"},exports.tagClassByName=reverse(exports.tagClass),exports.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},exports.tagByName=reverse(exports.tag)},6826:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";const constants=exports;constants._reverse=function reverse(map){const res={};return Object.keys(map).forEach((function(key){(0|key)==key&&(key|=0);const value=map[key];res[value]=key})),res},constants.der=__webpack_require__(160)},1671:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";const inherits=__webpack_require__(5717),bignum=__webpack_require__(4590),DecoderBuffer=__webpack_require__(6625).C,Node=__webpack_require__(1949),der=__webpack_require__(160);function DERDecoder(entity){this.enc="der",this.name=entity.name,this.entity=entity,this.tree=new DERNode,this.tree._init(entity.body)}function DERNode(parent){Node.call(this,"der",parent)}function derDecodeTag(buf,fail){let tag=buf.readUInt8(fail);if(buf.isError(tag))return tag;const cls=der.tagClass[tag>>6],primitive=0==(32&tag);if(31==(31&tag)){let oct=tag;for(tag=0;128==(128&oct);){if(oct=buf.readUInt8(fail),buf.isError(oct))return oct;tag<<=7,tag|=127&oct}}else tag&=31;return{cls,primitive,tag,tagStr:der.tag[tag]}}function derDecodeLen(buf,primitive,fail){let len=buf.readUInt8(fail);if(buf.isError(len))return len;if(!primitive&&128===len)return null;if(0==(128&len))return len;const num=127&len;if(num>4)return buf.error("length octect is too long");len=0;for(let i=0;i{"use strict";const decoders=exports;decoders.der=__webpack_require__(1671),decoders.pem=__webpack_require__(9631)},9631:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";const inherits=__webpack_require__(5717),Buffer=__webpack_require__(2399).Buffer,DERDecoder=__webpack_require__(1671);function PEMDecoder(entity){DERDecoder.call(this,entity),this.enc="pem"}inherits(PEMDecoder,DERDecoder),module.exports=PEMDecoder,PEMDecoder.prototype.decode=function decode(data,options){const lines=data.toString().split(/[\r\n]+/g),label=options.label.toUpperCase(),re=/^-----(BEGIN|END) ([^-]+)-----$/;let start=-1,end=-1;for(let i=0;i{"use strict";const inherits=__webpack_require__(5717),Buffer=__webpack_require__(2399).Buffer,Node=__webpack_require__(1949),der=__webpack_require__(160);function DEREncoder(entity){this.enc="der",this.name=entity.name,this.entity=entity,this.tree=new DERNode,this.tree._init(entity.body)}function DERNode(parent){Node.call(this,"der",parent)}function two(num){return num<10?"0"+num:num}module.exports=DEREncoder,DEREncoder.prototype.encode=function encode(data,reporter){return this.tree._encode(data,reporter).join()},inherits(DERNode,Node),DERNode.prototype._encodeComposite=function encodeComposite(tag,primitive,cls,content){const encodedTag=function encodeTag(tag,primitive,cls,reporter){let res;"seqof"===tag?tag="seq":"setof"===tag&&(tag="set");if(der.tagByName.hasOwnProperty(tag))res=der.tagByName[tag];else{if("number"!=typeof tag||(0|tag)!==tag)return reporter.error("Unknown tag: "+tag);res=tag}if(res>=31)return reporter.error("Multi-octet tag encoding unsupported");primitive||(res|=32);return res|=der.tagClassByName[cls||"universal"]<<6,res}(tag,primitive,cls,this.reporter);if(content.length<128){const header=Buffer.alloc(2);return header[0]=encodedTag,header[1]=content.length,this._createEncoderBuffer([header,content])}let lenOctets=1;for(let i=content.length;i>=256;i>>=8)lenOctets++;const header=Buffer.alloc(2+lenOctets);header[0]=encodedTag,header[1]=128|lenOctets;for(let i=1+lenOctets,j=content.length;j>0;i--,j>>=8)header[i]=255&j;return this._createEncoderBuffer([header,content])},DERNode.prototype._encodeStr=function encodeStr(str,tag){if("bitstr"===tag)return this._createEncoderBuffer([0|str.unused,str.data]);if("bmpstr"===tag){const buf=Buffer.alloc(2*str.length);for(let i=0;i=40)return this.reporter.error("Second objid identifier OOB");id.splice(0,2,40*id[0]+id[1])}let size=0;for(let i=0;i=128;ident>>=7)size++}const objid=Buffer.alloc(size);let offset=objid.length-1;for(let i=id.length-1;i>=0;i--){let ident=id[i];for(objid[offset--]=127&ident;(ident>>=7)>0;)objid[offset--]=128|127&ident}return this._createEncoderBuffer(objid)},DERNode.prototype._encodeTime=function encodeTime(time,tag){let str;const date=new Date(time);return"gentime"===tag?str=[two(date.getUTCFullYear()),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),"Z"].join(""):"utctime"===tag?str=[two(date.getUTCFullYear()%100),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+tag+" time is not supported yet"),this._encodeStr(str,"octstr")},DERNode.prototype._encodeNull=function encodeNull(){return this._createEncoderBuffer("")},DERNode.prototype._encodeInt=function encodeInt(num,values){if("string"==typeof num){if(!values)return this.reporter.error("String int or enum given, but no values map");if(!values.hasOwnProperty(num))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(num));num=values[num]}if("number"!=typeof num&&!Buffer.isBuffer(num)){const numArray=num.toArray();!num.sign&&128&numArray[0]&&numArray.unshift(0),num=Buffer.from(numArray)}if(Buffer.isBuffer(num)){let size=num.length;0===num.length&&size++;const out=Buffer.alloc(size);return num.copy(out),0===num.length&&(out[0]=0),this._createEncoderBuffer(out)}if(num<128)return this._createEncoderBuffer(num);if(num<256)return this._createEncoderBuffer([0,num]);let size=1;for(let i=num;i>=256;i>>=8)size++;const out=new Array(size);for(let i=out.length-1;i>=0;i--)out[i]=255&num,num>>=8;return 128&out[0]&&out.unshift(0),this._createEncoderBuffer(Buffer.from(out))},DERNode.prototype._encodeBool=function encodeBool(value){return this._createEncoderBuffer(value?255:0)},DERNode.prototype._use=function use(entity,obj){return"function"==typeof entity&&(entity=entity(obj)),entity._getEncoder("der").tree},DERNode.prototype._skipDefault=function skipDefault(dataBuffer,reporter,parent){const state=this._baseState;let i;if(null===state.default)return!1;const data=dataBuffer.join();if(void 0===state.defaultBuffer&&(state.defaultBuffer=this._encodeValue(state.default,reporter,parent).join()),data.length!==state.defaultBuffer.length)return!1;for(i=0;i{"use strict";const encoders=exports;encoders.der=__webpack_require__(6984),encoders.pem=__webpack_require__(2883)},2883:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";const inherits=__webpack_require__(5717),DEREncoder=__webpack_require__(6984);function PEMEncoder(entity){DEREncoder.call(this,entity),this.enc="pem"}inherits(PEMEncoder,DEREncoder),module.exports=PEMEncoder,PEMEncoder.prototype.encode=function encode(data,options){const p=DEREncoder.prototype.encode.call(this,data).toString("base64"),out=["-----BEGIN "+options.label+"-----"];for(let i=0;i=65&&c<=70?c-55:c>=97&&c<=102?c-87:c-48&15}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return index-1>=lowerBound&&(r|=parseHex4Bits(string,index-1)<<4),r}function parseBase(str,start,end,mul){for(var r=0,len=Math.min(str.length,end),i=start;i=49?c-49+10:c>=17?c-17+10:c}return r}BN.isBN=function isBN(num){return num instanceof BN||null!==num&&"object"==typeof num&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words)},BN.max=function max(left,right){return left.cmp(right)>0?left:right},BN.min=function min(left,right){return left.cmp(right)<0?left:right},BN.prototype._init=function init(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&base>=2&&base<=36);var start=0;"-"===(number=number.toString().replace(/\s+/g,""))[0]&&(start++,this.negative=1),start=0;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=w<>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);return this.strip()},BN.prototype._parseHex=function _parseHex(number,start,endian){this.length=Math.ceil((number.length-start)/6),this.words=new Array(this.length);for(var i=0;i=start;i-=2)w=parseHexByte(number,start,i)<=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;else for(i=(number.length-start)%2==0?start+1:start;i=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;this.strip()},BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;limbPow*=base)limbLen++;limbLen--,limbPow=limbPow/base|0;for(var total=number.length-start,mod=total%limbLen,end=Math.min(total,total-mod)+start,word=0,i=start;i1&&0===this.words[this.length-1];)this.length--;return this._normSign()},BN.prototype._normSign=function _normSign(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},BN.prototype.inspect=function inspect(){return(this.red?""};var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=self.length+num.length|0;out.length=len,len=len-1|0;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=r/67108864|0;out.words[0]=lo;for(var k=1;k>>26,rword=67108863&carry,maxJ=Math.min(k,num.length-1),j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j|0;ncarry+=(r=(a=0|self.words[i])*(b=0|num.words[j])+rword)/67108864|0,rword=67108863&r}out.words[k]=0|rword,carry=0|ncarry}return 0!==carry?out.words[k]=0|carry:out.length--,out.strip()}BN.prototype.toString=function toString(base,padding){var out;if(padding=0|padding||1,16===(base=base||10)||"hex"===base){out="";for(var off=0,carry=0,i=0;i>>24-off&16777215)||i!==this.length-1?zeros[6-word.length]+word+out:word+out,(off+=2)>=26&&(off-=26,i--)}for(0!==carry&&(out=carry.toString(16)+out);out.length%padding!=0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&base>=2&&base<=36){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modn(groupBase).toString(base);out=(c=c.idivn(groupBase)).isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);out.length%padding!=0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function toNumber(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:this.length>2&&assert(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-ret:ret},BN.prototype.toJSON=function toJSON(){return this.toString(16)},BN.prototype.toBuffer=function toBuffer(endian,length){return assert(void 0!==Buffer),this.toArrayLike(Buffer,endian,length)},BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)},BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){var byteLength=this.byteLength(),reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length"),assert(reqLength>0,"Requested array length <= 0"),this.strip();var b,i,littleEndian="le"===endian,res=new ArrayType(reqLength),q=this.clone();if(littleEndian){for(i=0;!q.isZero();i++)b=q.andln(255),q.iushrn(8),res[i]=b;for(;i=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function _zeroBits(w){if(0===w)return 26;var t=w,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;for(var r=0,i=0;inum.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function uor(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function iuand(num){var b;b=this.length>num.length?num:this;for(var i=0;inum.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function uand(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function iuxor(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;inum.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function uxor(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function inotn(width){assert("number"==typeof width&&width>=0);var bytesNeeded=0|Math.ceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),bitsLeft>0&&bytesNeeded--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this.strip()},BN.prototype.notn=function notn(width){return this.clone().inotn(width)},BN.prototype.setn=function setn(bit,val){assert("number"==typeof bit&&bit>=0);var off=bit/26|0,wbit=bit%26;return this._expand(off+1),this.words[off]=val?this.words[off]|1<num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>>26;for(;0!==carry&&i>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;inum.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function isub(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var a,b,cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;cmp>0?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>26,this.words[i]=67108863&r;for(;0!==carry&&i>26,this.words[i]=67108863&r;if(0===carry&&i>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13;out.negative=self.negative^num.negative,out.length=19;var w0=(c+(lo=Math.imul(al0,bl0))|0)+((8191&(mid=(mid=Math.imul(al0,bh0))+Math.imul(ah0,bl0)|0))<<13)|0;c=((hi=Math.imul(ah0,bh0))+(mid>>>13)|0)+(w0>>>26)|0,w0&=67108863,lo=Math.imul(al1,bl0),mid=(mid=Math.imul(al1,bh0))+Math.imul(ah1,bl0)|0,hi=Math.imul(ah1,bh0);var w1=(c+(lo=lo+Math.imul(al0,bl1)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh1)|0)+Math.imul(ah0,bl1)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh1)|0)+(mid>>>13)|0)+(w1>>>26)|0,w1&=67108863,lo=Math.imul(al2,bl0),mid=(mid=Math.imul(al2,bh0))+Math.imul(ah2,bl0)|0,hi=Math.imul(ah2,bh0),lo=lo+Math.imul(al1,bl1)|0,mid=(mid=mid+Math.imul(al1,bh1)|0)+Math.imul(ah1,bl1)|0,hi=hi+Math.imul(ah1,bh1)|0;var w2=(c+(lo=lo+Math.imul(al0,bl2)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh2)|0)+Math.imul(ah0,bl2)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh2)|0)+(mid>>>13)|0)+(w2>>>26)|0,w2&=67108863,lo=Math.imul(al3,bl0),mid=(mid=Math.imul(al3,bh0))+Math.imul(ah3,bl0)|0,hi=Math.imul(ah3,bh0),lo=lo+Math.imul(al2,bl1)|0,mid=(mid=mid+Math.imul(al2,bh1)|0)+Math.imul(ah2,bl1)|0,hi=hi+Math.imul(ah2,bh1)|0,lo=lo+Math.imul(al1,bl2)|0,mid=(mid=mid+Math.imul(al1,bh2)|0)+Math.imul(ah1,bl2)|0,hi=hi+Math.imul(ah1,bh2)|0;var w3=(c+(lo=lo+Math.imul(al0,bl3)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh3)|0)+Math.imul(ah0,bl3)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh3)|0)+(mid>>>13)|0)+(w3>>>26)|0,w3&=67108863,lo=Math.imul(al4,bl0),mid=(mid=Math.imul(al4,bh0))+Math.imul(ah4,bl0)|0,hi=Math.imul(ah4,bh0),lo=lo+Math.imul(al3,bl1)|0,mid=(mid=mid+Math.imul(al3,bh1)|0)+Math.imul(ah3,bl1)|0,hi=hi+Math.imul(ah3,bh1)|0,lo=lo+Math.imul(al2,bl2)|0,mid=(mid=mid+Math.imul(al2,bh2)|0)+Math.imul(ah2,bl2)|0,hi=hi+Math.imul(ah2,bh2)|0,lo=lo+Math.imul(al1,bl3)|0,mid=(mid=mid+Math.imul(al1,bh3)|0)+Math.imul(ah1,bl3)|0,hi=hi+Math.imul(ah1,bh3)|0;var w4=(c+(lo=lo+Math.imul(al0,bl4)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh4)|0)+Math.imul(ah0,bl4)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh4)|0)+(mid>>>13)|0)+(w4>>>26)|0,w4&=67108863,lo=Math.imul(al5,bl0),mid=(mid=Math.imul(al5,bh0))+Math.imul(ah5,bl0)|0,hi=Math.imul(ah5,bh0),lo=lo+Math.imul(al4,bl1)|0,mid=(mid=mid+Math.imul(al4,bh1)|0)+Math.imul(ah4,bl1)|0,hi=hi+Math.imul(ah4,bh1)|0,lo=lo+Math.imul(al3,bl2)|0,mid=(mid=mid+Math.imul(al3,bh2)|0)+Math.imul(ah3,bl2)|0,hi=hi+Math.imul(ah3,bh2)|0,lo=lo+Math.imul(al2,bl3)|0,mid=(mid=mid+Math.imul(al2,bh3)|0)+Math.imul(ah2,bl3)|0,hi=hi+Math.imul(ah2,bh3)|0,lo=lo+Math.imul(al1,bl4)|0,mid=(mid=mid+Math.imul(al1,bh4)|0)+Math.imul(ah1,bl4)|0,hi=hi+Math.imul(ah1,bh4)|0;var w5=(c+(lo=lo+Math.imul(al0,bl5)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh5)|0)+Math.imul(ah0,bl5)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh5)|0)+(mid>>>13)|0)+(w5>>>26)|0,w5&=67108863,lo=Math.imul(al6,bl0),mid=(mid=Math.imul(al6,bh0))+Math.imul(ah6,bl0)|0,hi=Math.imul(ah6,bh0),lo=lo+Math.imul(al5,bl1)|0,mid=(mid=mid+Math.imul(al5,bh1)|0)+Math.imul(ah5,bl1)|0,hi=hi+Math.imul(ah5,bh1)|0,lo=lo+Math.imul(al4,bl2)|0,mid=(mid=mid+Math.imul(al4,bh2)|0)+Math.imul(ah4,bl2)|0,hi=hi+Math.imul(ah4,bh2)|0,lo=lo+Math.imul(al3,bl3)|0,mid=(mid=mid+Math.imul(al3,bh3)|0)+Math.imul(ah3,bl3)|0,hi=hi+Math.imul(ah3,bh3)|0,lo=lo+Math.imul(al2,bl4)|0,mid=(mid=mid+Math.imul(al2,bh4)|0)+Math.imul(ah2,bl4)|0,hi=hi+Math.imul(ah2,bh4)|0,lo=lo+Math.imul(al1,bl5)|0,mid=(mid=mid+Math.imul(al1,bh5)|0)+Math.imul(ah1,bl5)|0,hi=hi+Math.imul(ah1,bh5)|0;var w6=(c+(lo=lo+Math.imul(al0,bl6)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh6)|0)+Math.imul(ah0,bl6)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh6)|0)+(mid>>>13)|0)+(w6>>>26)|0,w6&=67108863,lo=Math.imul(al7,bl0),mid=(mid=Math.imul(al7,bh0))+Math.imul(ah7,bl0)|0,hi=Math.imul(ah7,bh0),lo=lo+Math.imul(al6,bl1)|0,mid=(mid=mid+Math.imul(al6,bh1)|0)+Math.imul(ah6,bl1)|0,hi=hi+Math.imul(ah6,bh1)|0,lo=lo+Math.imul(al5,bl2)|0,mid=(mid=mid+Math.imul(al5,bh2)|0)+Math.imul(ah5,bl2)|0,hi=hi+Math.imul(ah5,bh2)|0,lo=lo+Math.imul(al4,bl3)|0,mid=(mid=mid+Math.imul(al4,bh3)|0)+Math.imul(ah4,bl3)|0,hi=hi+Math.imul(ah4,bh3)|0,lo=lo+Math.imul(al3,bl4)|0,mid=(mid=mid+Math.imul(al3,bh4)|0)+Math.imul(ah3,bl4)|0,hi=hi+Math.imul(ah3,bh4)|0,lo=lo+Math.imul(al2,bl5)|0,mid=(mid=mid+Math.imul(al2,bh5)|0)+Math.imul(ah2,bl5)|0,hi=hi+Math.imul(ah2,bh5)|0,lo=lo+Math.imul(al1,bl6)|0,mid=(mid=mid+Math.imul(al1,bh6)|0)+Math.imul(ah1,bl6)|0,hi=hi+Math.imul(ah1,bh6)|0;var w7=(c+(lo=lo+Math.imul(al0,bl7)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh7)|0)+Math.imul(ah0,bl7)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh7)|0)+(mid>>>13)|0)+(w7>>>26)|0,w7&=67108863,lo=Math.imul(al8,bl0),mid=(mid=Math.imul(al8,bh0))+Math.imul(ah8,bl0)|0,hi=Math.imul(ah8,bh0),lo=lo+Math.imul(al7,bl1)|0,mid=(mid=mid+Math.imul(al7,bh1)|0)+Math.imul(ah7,bl1)|0,hi=hi+Math.imul(ah7,bh1)|0,lo=lo+Math.imul(al6,bl2)|0,mid=(mid=mid+Math.imul(al6,bh2)|0)+Math.imul(ah6,bl2)|0,hi=hi+Math.imul(ah6,bh2)|0,lo=lo+Math.imul(al5,bl3)|0,mid=(mid=mid+Math.imul(al5,bh3)|0)+Math.imul(ah5,bl3)|0,hi=hi+Math.imul(ah5,bh3)|0,lo=lo+Math.imul(al4,bl4)|0,mid=(mid=mid+Math.imul(al4,bh4)|0)+Math.imul(ah4,bl4)|0,hi=hi+Math.imul(ah4,bh4)|0,lo=lo+Math.imul(al3,bl5)|0,mid=(mid=mid+Math.imul(al3,bh5)|0)+Math.imul(ah3,bl5)|0,hi=hi+Math.imul(ah3,bh5)|0,lo=lo+Math.imul(al2,bl6)|0,mid=(mid=mid+Math.imul(al2,bh6)|0)+Math.imul(ah2,bl6)|0,hi=hi+Math.imul(ah2,bh6)|0,lo=lo+Math.imul(al1,bl7)|0,mid=(mid=mid+Math.imul(al1,bh7)|0)+Math.imul(ah1,bl7)|0,hi=hi+Math.imul(ah1,bh7)|0;var w8=(c+(lo=lo+Math.imul(al0,bl8)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh8)|0)+Math.imul(ah0,bl8)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh8)|0)+(mid>>>13)|0)+(w8>>>26)|0,w8&=67108863,lo=Math.imul(al9,bl0),mid=(mid=Math.imul(al9,bh0))+Math.imul(ah9,bl0)|0,hi=Math.imul(ah9,bh0),lo=lo+Math.imul(al8,bl1)|0,mid=(mid=mid+Math.imul(al8,bh1)|0)+Math.imul(ah8,bl1)|0,hi=hi+Math.imul(ah8,bh1)|0,lo=lo+Math.imul(al7,bl2)|0,mid=(mid=mid+Math.imul(al7,bh2)|0)+Math.imul(ah7,bl2)|0,hi=hi+Math.imul(ah7,bh2)|0,lo=lo+Math.imul(al6,bl3)|0,mid=(mid=mid+Math.imul(al6,bh3)|0)+Math.imul(ah6,bl3)|0,hi=hi+Math.imul(ah6,bh3)|0,lo=lo+Math.imul(al5,bl4)|0,mid=(mid=mid+Math.imul(al5,bh4)|0)+Math.imul(ah5,bl4)|0,hi=hi+Math.imul(ah5,bh4)|0,lo=lo+Math.imul(al4,bl5)|0,mid=(mid=mid+Math.imul(al4,bh5)|0)+Math.imul(ah4,bl5)|0,hi=hi+Math.imul(ah4,bh5)|0,lo=lo+Math.imul(al3,bl6)|0,mid=(mid=mid+Math.imul(al3,bh6)|0)+Math.imul(ah3,bl6)|0,hi=hi+Math.imul(ah3,bh6)|0,lo=lo+Math.imul(al2,bl7)|0,mid=(mid=mid+Math.imul(al2,bh7)|0)+Math.imul(ah2,bl7)|0,hi=hi+Math.imul(ah2,bh7)|0,lo=lo+Math.imul(al1,bl8)|0,mid=(mid=mid+Math.imul(al1,bh8)|0)+Math.imul(ah1,bl8)|0,hi=hi+Math.imul(ah1,bh8)|0;var w9=(c+(lo=lo+Math.imul(al0,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh9)|0)+Math.imul(ah0,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh9)|0)+(mid>>>13)|0)+(w9>>>26)|0,w9&=67108863,lo=Math.imul(al9,bl1),mid=(mid=Math.imul(al9,bh1))+Math.imul(ah9,bl1)|0,hi=Math.imul(ah9,bh1),lo=lo+Math.imul(al8,bl2)|0,mid=(mid=mid+Math.imul(al8,bh2)|0)+Math.imul(ah8,bl2)|0,hi=hi+Math.imul(ah8,bh2)|0,lo=lo+Math.imul(al7,bl3)|0,mid=(mid=mid+Math.imul(al7,bh3)|0)+Math.imul(ah7,bl3)|0,hi=hi+Math.imul(ah7,bh3)|0,lo=lo+Math.imul(al6,bl4)|0,mid=(mid=mid+Math.imul(al6,bh4)|0)+Math.imul(ah6,bl4)|0,hi=hi+Math.imul(ah6,bh4)|0,lo=lo+Math.imul(al5,bl5)|0,mid=(mid=mid+Math.imul(al5,bh5)|0)+Math.imul(ah5,bl5)|0,hi=hi+Math.imul(ah5,bh5)|0,lo=lo+Math.imul(al4,bl6)|0,mid=(mid=mid+Math.imul(al4,bh6)|0)+Math.imul(ah4,bl6)|0,hi=hi+Math.imul(ah4,bh6)|0,lo=lo+Math.imul(al3,bl7)|0,mid=(mid=mid+Math.imul(al3,bh7)|0)+Math.imul(ah3,bl7)|0,hi=hi+Math.imul(ah3,bh7)|0,lo=lo+Math.imul(al2,bl8)|0,mid=(mid=mid+Math.imul(al2,bh8)|0)+Math.imul(ah2,bl8)|0,hi=hi+Math.imul(ah2,bh8)|0;var w10=(c+(lo=lo+Math.imul(al1,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al1,bh9)|0)+Math.imul(ah1,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah1,bh9)|0)+(mid>>>13)|0)+(w10>>>26)|0,w10&=67108863,lo=Math.imul(al9,bl2),mid=(mid=Math.imul(al9,bh2))+Math.imul(ah9,bl2)|0,hi=Math.imul(ah9,bh2),lo=lo+Math.imul(al8,bl3)|0,mid=(mid=mid+Math.imul(al8,bh3)|0)+Math.imul(ah8,bl3)|0,hi=hi+Math.imul(ah8,bh3)|0,lo=lo+Math.imul(al7,bl4)|0,mid=(mid=mid+Math.imul(al7,bh4)|0)+Math.imul(ah7,bl4)|0,hi=hi+Math.imul(ah7,bh4)|0,lo=lo+Math.imul(al6,bl5)|0,mid=(mid=mid+Math.imul(al6,bh5)|0)+Math.imul(ah6,bl5)|0,hi=hi+Math.imul(ah6,bh5)|0,lo=lo+Math.imul(al5,bl6)|0,mid=(mid=mid+Math.imul(al5,bh6)|0)+Math.imul(ah5,bl6)|0,hi=hi+Math.imul(ah5,bh6)|0,lo=lo+Math.imul(al4,bl7)|0,mid=(mid=mid+Math.imul(al4,bh7)|0)+Math.imul(ah4,bl7)|0,hi=hi+Math.imul(ah4,bh7)|0,lo=lo+Math.imul(al3,bl8)|0,mid=(mid=mid+Math.imul(al3,bh8)|0)+Math.imul(ah3,bl8)|0,hi=hi+Math.imul(ah3,bh8)|0;var w11=(c+(lo=lo+Math.imul(al2,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al2,bh9)|0)+Math.imul(ah2,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah2,bh9)|0)+(mid>>>13)|0)+(w11>>>26)|0,w11&=67108863,lo=Math.imul(al9,bl3),mid=(mid=Math.imul(al9,bh3))+Math.imul(ah9,bl3)|0,hi=Math.imul(ah9,bh3),lo=lo+Math.imul(al8,bl4)|0,mid=(mid=mid+Math.imul(al8,bh4)|0)+Math.imul(ah8,bl4)|0,hi=hi+Math.imul(ah8,bh4)|0,lo=lo+Math.imul(al7,bl5)|0,mid=(mid=mid+Math.imul(al7,bh5)|0)+Math.imul(ah7,bl5)|0,hi=hi+Math.imul(ah7,bh5)|0,lo=lo+Math.imul(al6,bl6)|0,mid=(mid=mid+Math.imul(al6,bh6)|0)+Math.imul(ah6,bl6)|0,hi=hi+Math.imul(ah6,bh6)|0,lo=lo+Math.imul(al5,bl7)|0,mid=(mid=mid+Math.imul(al5,bh7)|0)+Math.imul(ah5,bl7)|0,hi=hi+Math.imul(ah5,bh7)|0,lo=lo+Math.imul(al4,bl8)|0,mid=(mid=mid+Math.imul(al4,bh8)|0)+Math.imul(ah4,bl8)|0,hi=hi+Math.imul(ah4,bh8)|0;var w12=(c+(lo=lo+Math.imul(al3,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al3,bh9)|0)+Math.imul(ah3,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah3,bh9)|0)+(mid>>>13)|0)+(w12>>>26)|0,w12&=67108863,lo=Math.imul(al9,bl4),mid=(mid=Math.imul(al9,bh4))+Math.imul(ah9,bl4)|0,hi=Math.imul(ah9,bh4),lo=lo+Math.imul(al8,bl5)|0,mid=(mid=mid+Math.imul(al8,bh5)|0)+Math.imul(ah8,bl5)|0,hi=hi+Math.imul(ah8,bh5)|0,lo=lo+Math.imul(al7,bl6)|0,mid=(mid=mid+Math.imul(al7,bh6)|0)+Math.imul(ah7,bl6)|0,hi=hi+Math.imul(ah7,bh6)|0,lo=lo+Math.imul(al6,bl7)|0,mid=(mid=mid+Math.imul(al6,bh7)|0)+Math.imul(ah6,bl7)|0,hi=hi+Math.imul(ah6,bh7)|0,lo=lo+Math.imul(al5,bl8)|0,mid=(mid=mid+Math.imul(al5,bh8)|0)+Math.imul(ah5,bl8)|0,hi=hi+Math.imul(ah5,bh8)|0;var w13=(c+(lo=lo+Math.imul(al4,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al4,bh9)|0)+Math.imul(ah4,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah4,bh9)|0)+(mid>>>13)|0)+(w13>>>26)|0,w13&=67108863,lo=Math.imul(al9,bl5),mid=(mid=Math.imul(al9,bh5))+Math.imul(ah9,bl5)|0,hi=Math.imul(ah9,bh5),lo=lo+Math.imul(al8,bl6)|0,mid=(mid=mid+Math.imul(al8,bh6)|0)+Math.imul(ah8,bl6)|0,hi=hi+Math.imul(ah8,bh6)|0,lo=lo+Math.imul(al7,bl7)|0,mid=(mid=mid+Math.imul(al7,bh7)|0)+Math.imul(ah7,bl7)|0,hi=hi+Math.imul(ah7,bh7)|0,lo=lo+Math.imul(al6,bl8)|0,mid=(mid=mid+Math.imul(al6,bh8)|0)+Math.imul(ah6,bl8)|0,hi=hi+Math.imul(ah6,bh8)|0;var w14=(c+(lo=lo+Math.imul(al5,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al5,bh9)|0)+Math.imul(ah5,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah5,bh9)|0)+(mid>>>13)|0)+(w14>>>26)|0,w14&=67108863,lo=Math.imul(al9,bl6),mid=(mid=Math.imul(al9,bh6))+Math.imul(ah9,bl6)|0,hi=Math.imul(ah9,bh6),lo=lo+Math.imul(al8,bl7)|0,mid=(mid=mid+Math.imul(al8,bh7)|0)+Math.imul(ah8,bl7)|0,hi=hi+Math.imul(ah8,bh7)|0,lo=lo+Math.imul(al7,bl8)|0,mid=(mid=mid+Math.imul(al7,bh8)|0)+Math.imul(ah7,bl8)|0,hi=hi+Math.imul(ah7,bh8)|0;var w15=(c+(lo=lo+Math.imul(al6,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al6,bh9)|0)+Math.imul(ah6,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah6,bh9)|0)+(mid>>>13)|0)+(w15>>>26)|0,w15&=67108863,lo=Math.imul(al9,bl7),mid=(mid=Math.imul(al9,bh7))+Math.imul(ah9,bl7)|0,hi=Math.imul(ah9,bh7),lo=lo+Math.imul(al8,bl8)|0,mid=(mid=mid+Math.imul(al8,bh8)|0)+Math.imul(ah8,bl8)|0,hi=hi+Math.imul(ah8,bh8)|0;var w16=(c+(lo=lo+Math.imul(al7,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al7,bh9)|0)+Math.imul(ah7,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah7,bh9)|0)+(mid>>>13)|0)+(w16>>>26)|0,w16&=67108863,lo=Math.imul(al9,bl8),mid=(mid=Math.imul(al9,bh8))+Math.imul(ah9,bl8)|0,hi=Math.imul(ah9,bh8);var w17=(c+(lo=lo+Math.imul(al8,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al8,bh9)|0)+Math.imul(ah8,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah8,bh9)|0)+(mid>>>13)|0)+(w17>>>26)|0,w17&=67108863;var w18=(c+(lo=Math.imul(al9,bl9))|0)+((8191&(mid=(mid=Math.imul(al9,bh9))+Math.imul(ah9,bl9)|0))<<13)|0;return c=((hi=Math.imul(ah9,bh9))+(mid>>>13)|0)+(w18>>>26)|0,w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,0!==c&&(o[19]=c,out.length++),out};function jumboMulTo(self,num,out){return(new FFTM).mulp(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}Math.imul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function mulTo(num,out){var res,len=this.length+num.length;return res=10===this.length&&10===num.length?comb10MulTo(this,num,out):len<63?smallMulTo(this,num,out):len<1024?function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0;k>>26)|0)>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0!==carry?out.words[k]=carry:out.length--,out.strip()}(this,num,out):jumboMulTo(this,num,out),res},FFTM.prototype.makeRBT=function makeRBT(N){for(var t=new Array(N),l=BN.prototype._countBits(N)-1,i=0;i>=1;return rb},FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>=1)i++;return 1<>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;i>=26,carry+=w/67108864|0,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.muln=function muln(num){return this.clone().imuln(num)},BN.prototype.sqr=function sqr(){return this.mul(this)},BN.prototype.isqr=function isqr(){return this.imul(this.clone())},BN.prototype.pow=function pow(num){var w=function toBitArray(num){for(var w=new Array(num.bitLength()),bit=0;bit>>wbit}return w}(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i=0);var i,r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r;if(0!==r){var carry=0;for(i=0;i>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;i>=0;i--)this.words[i+s]=this.words[i];for(i=0;i=0),h=hint?(hint-hint%26)/26:0;var r=bits%26,s=Math.min((bits-r)/26,this.length),mask=67108863^67108863>>>r<s)for(this.length-=s,i=0;i=0&&(0!==carry||i>=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&0!==carry&&(maskedWords.words[maskedWords.length++]=carry),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},BN.prototype.ishrn=function ishrn(bits,hint,extended){return assert(0===this.negative),this.iushrn(bits,hint,extended)},BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function testn(bit){assert("number"==typeof bit&&bit>=0);var r=bit%26,s=(bit-r)/26,q=1<=0);var r=bits%26,s=(bits-r)/26;if(assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!==r&&s++,this.length=Math.min(s,this.length),0!==r){var mask=67108863^67108863>>>r<=67108864;i++)this.words[i]-=67108864,i===this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=Math.max(this.length,i+1),this},BN.prototype.isubn=function isubn(num){if(assert("number"==typeof num),assert(num<67108864),num<0)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i>26)-(right/67108864|0),this.words[i+shift]=67108863&w}for(;i>26,this.words[i+shift]=67108863&w;if(0===carry)return this.strip();for(assert(-1===carry),carry=0,i=0;i>26,this.words[i]=67108863&w;return this.negative=1,this.strip()},BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=(this.length,num.length),a=this.clone(),b=num,bhi=0|b.words[b.length-1];0!==(shift=26-this._countBits(bhi))&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var q,m=a.length-b.length;if("mod"!==mode){(q=new BN(null)).length=m+1,q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=67108864*(0|a.words[b.length+j])+(0|a.words[b.length+j-1]);for(qj=Math.min(qj/bhi|0,67108863),a._ishlnsubmul(b,qj,j);0!==a.negative;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q.strip(),a.strip(),"div"!==mode&&0!==shift&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function divmod(num,mode,positive){return assert(!num.isZero()),this.isZero()?{div:new BN(0),mod:new BN(0)}:0!==this.negative&&0===num.negative?(res=this.neg().divmod(num,mode),"mod"!==mode&&(div=res.div.neg()),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.iadd(num)),{div,mod}):0===this.negative&&0!==num.negative?(res=this.divmod(num.neg(),mode),"mod"!==mode&&(div=res.div.neg()),{div,mod:res.mod}):0!=(this.negative&num.negative)?(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod}):num.length>this.length||this.cmp(num)<0?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modn(num.words[0]))}:this._wordDiv(num,mode);var div,mod,res},BN.prototype.div=function div(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function mod(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function umod(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0!==dm.div.negative?dm.mod.isub(num):dm.mod,half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return cmp<0||1===r2&&0===cmp?dm.div:0!==dm.div.negative?dm.div.isubn(1):dm.div.iaddn(1)},BN.prototype.modn=function modn(num){assert(num<=67108863);for(var p=(1<<26)%num,acc=0,i=this.length-1;i>=0;i--)acc=(p*acc+(0|this.words[i]))%num;return acc},BN.prototype.idivn=function idivn(num){assert(num<=67108863);for(var carry=0,i=this.length-1;i>=0;i--){var w=(0|this.words[i])+67108864*carry;this.words[i]=w/num|0,carry=w%num}return this.strip()},BN.prototype.divn=function divn(num){return this.clone().idivn(num)},BN.prototype.egcd=function egcd(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0!==x.negative?x.umod(p):x.clone();for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0==(x.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(x.iushrn(i);i-- >0;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;0==(y.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(y.iushrn(j);j-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);x.cmp(y)>=0?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function _invmp(p){assert(0===p.negative),assert(!p.isZero());var a=this,b=p.clone();a=0!==a.negative?a.umod(p):a.clone();for(var res,x1=new BN(1),x2=new BN(0),delta=b.clone();a.cmpn(1)>0&&b.cmpn(1)>0;){for(var i=0,im=1;0==(a.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(a.iushrn(i);i-- >0;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;0==(b.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(b.iushrn(j);j-- >0;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);a.cmp(b)>=0?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}return(res=0===a.cmpn(1)?x1:x2).cmpn(0)<0&&res.iadd(p),res},BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);for(;;){for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(r<0){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}return b.iushln(shift)},BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function isEven(){return 0==(1&this.words[0])},BN.prototype.isOdd=function isOdd(){return 1==(1&this.words[0])},BN.prototype.andln=function andln(num){return this.words[0]&num},BN.prototype.bincn=function bincn(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<>>26,w&=67108863,this.words[i]=w}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function isZero(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function cmpn(num){var res,negative=num<0;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;if(this.strip(),this.length>1)res=1;else{negative&&(num=-num),assert(num<=67108863,"Number is too big");var w=0|this.words[0];res=w===num?0:wnum.length)return 1;if(this.length=0;i--){var a=0|this.words[i],b=0|num.words[i];if(a!==b){ab&&(res=1);break}}return res},BN.prototype.gtn=function gtn(num){return 1===this.cmpn(num)},BN.prototype.gt=function gt(num){return 1===this.cmp(num)},BN.prototype.gten=function gten(num){return this.cmpn(num)>=0},BN.prototype.gte=function gte(num){return this.cmp(num)>=0},BN.prototype.ltn=function ltn(num){return-1===this.cmpn(num)},BN.prototype.lt=function lt(num){return-1===this.cmp(num)},BN.prototype.lten=function lten(num){return this.cmpn(num)<=0},BN.prototype.lte=function lte(num){return this.cmp(num)<=0},BN.prototype.eqn=function eqn(num){return 0===this.cmpn(num)},BN.prototype.eq=function eq(num){return 0===this.cmp(num)},BN.red=function red(num){return new Red(num)},BN.prototype.toRed=function toRed(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function fromRed(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function _forceRed(ctx){return this.red=ctx,this},BN.prototype.forceRed=function forceRed(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function redAdd(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function redIAdd(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function redSub(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function redISub(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function redShl(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function redMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function redIMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function redSqr(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function redISqr(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function redSqrt(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function redInvm(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function redNeg(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function redPow(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);return tmp.words=new Array(Math.ceil(this.n/13)),tmp},MPrime.prototype.ireduce=function ireduce(num){var rlen,r=num;do{this.split(r,this.tmp),rlen=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(rlen>this.n);var cmp=rlen0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)},inherits(K256,MPrime),K256.prototype.split=function split(input,output){for(var outLen=Math.min(input.length,9),i=0;i>>22,prev=next}prev>>>=22,input.words[i-10]=prev,0===prev&&input.length>10?input.length-=10:input.length-=9},K256.prototype.imulK=function imulK(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0;i>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else{if("p25519"!==name)throw new Error("Unknown prime "+name);prime=new P25519}return primes[name]=prime,prime},Red.prototype._verify1=function _verify1(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function _verify2(a,b){assert(0==(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function imod(a){return this.prime?this.prime.ireduce(a)._forceRed(this):a.umod(this.m)._forceRed(this)},Red.prototype.neg=function neg(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);return res.cmp(this.m)>=0&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);return res.cmp(this.m)>=0&&res.isub(this.m),res},Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);return res.cmpn(0)<0&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);return res.cmpn(0)<0&&res.iadd(this.m),res},Red.prototype.shl=function shl(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function imul(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function mul(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())},Red.prototype.sqr=function sqr(a){return this.mul(a,a)},Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(mod3%2==1),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i=0;i--){for(var word=num.words[i],j=start-1;j>=0;j--){var bit=word>>j&1;res!==wnd[0]&&(res=this.sqr(res)),0!==bit||0!==current?(current<<=1,current|=bit,(4===++currentLen||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)):currentLen=0}start=26}return res},Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();return res.red=null,res},BN.mont=function mont(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function invm(a){return this.imod(a._invmp(this.m).mul(this.r2))._forceRed(this)}}(module=__webpack_require__.nmd(module),this)},9282:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";function _typeof(obj){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function _typeof(obj){return typeof obj}:function _typeof(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_typeof(obj)}var isDeepEqual,isDeepStrictEqual,_require$codes=__webpack_require__(2136).codes,ERR_AMBIGUOUS_ARGUMENT=_require$codes.ERR_AMBIGUOUS_ARGUMENT,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_INVALID_ARG_VALUE=_require$codes.ERR_INVALID_ARG_VALUE,ERR_INVALID_RETURN_VALUE=_require$codes.ERR_INVALID_RETURN_VALUE,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,AssertionError=__webpack_require__(5961),inspect=__webpack_require__(9539).inspect,_require$types=__webpack_require__(9539).types,isPromise=_require$types.isPromise,isRegExp=_require$types.isRegExp,objectAssign=Object.assign?Object.assign:__webpack_require__(8091).assign,objectIs=Object.is?Object.is:__webpack_require__(609);new Map;function lazyLoadComparison(){var comparison=__webpack_require__(9158);isDeepEqual=comparison.isDeepEqual,isDeepStrictEqual=comparison.isDeepStrictEqual}var warned=!1,assert=module.exports=ok,NO_EXCEPTION_SENTINEL={};function innerFail(obj){if(obj.message instanceof Error)throw obj.message;throw new AssertionError(obj)}function innerOk(fn,argLen,value,message){if(!value){var generatedMessage=!1;if(0===argLen)generatedMessage=!0,message="No value argument passed to `assert.ok()`";else if(message instanceof Error)throw message;var err=new AssertionError({actual:value,expected:!0,message,operator:"==",stackStartFn:fn});throw err.generatedMessage=generatedMessage,err}}function ok(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];innerOk.apply(void 0,[ok,args.length].concat(args))}assert.fail=function fail(actual,expected,message,operator,stackStartFn){var internalMessage,argsLen=arguments.length;if(0===argsLen)internalMessage="Failed";else if(1===argsLen)message=actual,actual=void 0;else{if(!1===warned){warned=!0;var warn=process.emitWarning?process.emitWarning:console.warn.bind(console);warn("assert.fail() with more than one argument is deprecated. Please use assert.strictEqual() instead or only pass a message.","DeprecationWarning","DEP0094")}2===argsLen&&(operator="!=")}if(message instanceof Error)throw message;var errArgs={actual,expected,operator:void 0===operator?"fail":operator,stackStartFn:stackStartFn||fail};void 0!==message&&(errArgs.message=message);var err=new AssertionError(errArgs);throw internalMessage&&(err.message=internalMessage,err.generatedMessage=!0),err},assert.AssertionError=AssertionError,assert.ok=ok,assert.equal=function equal(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS("actual","expected");actual!=expected&&innerFail({actual,expected,message,operator:"==",stackStartFn:equal})},assert.notEqual=function notEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS("actual","expected");actual==expected&&innerFail({actual,expected,message,operator:"!=",stackStartFn:notEqual})},assert.deepEqual=function deepEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS("actual","expected");void 0===isDeepEqual&&lazyLoadComparison(),isDeepEqual(actual,expected)||innerFail({actual,expected,message,operator:"deepEqual",stackStartFn:deepEqual})},assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS("actual","expected");void 0===isDeepEqual&&lazyLoadComparison(),isDeepEqual(actual,expected)&&innerFail({actual,expected,message,operator:"notDeepEqual",stackStartFn:notDeepEqual})},assert.deepStrictEqual=function deepStrictEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS("actual","expected");void 0===isDeepEqual&&lazyLoadComparison(),isDeepStrictEqual(actual,expected)||innerFail({actual,expected,message,operator:"deepStrictEqual",stackStartFn:deepStrictEqual})},assert.notDeepStrictEqual=function notDeepStrictEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS("actual","expected");void 0===isDeepEqual&&lazyLoadComparison();isDeepStrictEqual(actual,expected)&&innerFail({actual,expected,message,operator:"notDeepStrictEqual",stackStartFn:notDeepStrictEqual})},assert.strictEqual=function strictEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS("actual","expected");objectIs(actual,expected)||innerFail({actual,expected,message,operator:"strictEqual",stackStartFn:strictEqual})},assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(arguments.length<2)throw new ERR_MISSING_ARGS("actual","expected");objectIs(actual,expected)&&innerFail({actual,expected,message,operator:"notStrictEqual",stackStartFn:notStrictEqual})};var Comparison=function Comparison(obj,keys,actual){var _this=this;!function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}(this,Comparison),keys.forEach((function(key){key in obj&&(void 0!==actual&&"string"==typeof actual[key]&&isRegExp(obj[key])&&obj[key].test(actual[key])?_this[key]=actual[key]:_this[key]=obj[key])}))};function compareExceptionKey(actual,expected,key,message,keys,fn){if(!(key in actual)||!isDeepStrictEqual(actual[key],expected[key])){if(!message){var a=new Comparison(actual,keys),b=new Comparison(expected,keys,actual),err=new AssertionError({actual:a,expected:b,operator:"deepStrictEqual",stackStartFn:fn});throw err.actual=actual,err.expected=expected,err.operator=fn.name,err}innerFail({actual,expected,message,operator:fn.name,stackStartFn:fn})}}function expectedException(actual,expected,msg,fn){if("function"!=typeof expected){if(isRegExp(expected))return expected.test(actual);if(2===arguments.length)throw new ERR_INVALID_ARG_TYPE("expected",["Function","RegExp"],expected);if("object"!==_typeof(actual)||null===actual){var err=new AssertionError({actual,expected,message:msg,operator:"deepStrictEqual",stackStartFn:fn});throw err.operator=fn.name,err}var keys=Object.keys(expected);if(expected instanceof Error)keys.push("name","message");else if(0===keys.length)throw new ERR_INVALID_ARG_VALUE("error",expected,"may not be an empty object");return void 0===isDeepEqual&&lazyLoadComparison(),keys.forEach((function(key){"string"==typeof actual[key]&&isRegExp(expected[key])&&expected[key].test(actual[key])||compareExceptionKey(actual,expected,key,msg,keys,fn)})),!0}return void 0!==expected.prototype&&actual instanceof expected||!Error.isPrototypeOf(expected)&&!0===expected.call({},actual)}function getActual(fn){if("function"!=typeof fn)throw new ERR_INVALID_ARG_TYPE("fn","Function",fn);try{fn()}catch(e){return e}return NO_EXCEPTION_SENTINEL}function checkIsPromise(obj){return isPromise(obj)||null!==obj&&"object"===_typeof(obj)&&"function"==typeof obj.then&&"function"==typeof obj.catch}function waitForActual(promiseFn){return Promise.resolve().then((function(){var resultPromise;if("function"==typeof promiseFn){if(!checkIsPromise(resultPromise=promiseFn()))throw new ERR_INVALID_RETURN_VALUE("instance of Promise","promiseFn",resultPromise)}else{if(!checkIsPromise(promiseFn))throw new ERR_INVALID_ARG_TYPE("promiseFn",["Function","Promise"],promiseFn);resultPromise=promiseFn}return Promise.resolve().then((function(){return resultPromise})).then((function(){return NO_EXCEPTION_SENTINEL})).catch((function(e){return e}))}))}function expectsError(stackStartFn,actual,error,message){if("string"==typeof error){if(4===arguments.length)throw new ERR_INVALID_ARG_TYPE("error",["Object","Error","Function","RegExp"],error);if("object"===_typeof(actual)&&null!==actual){if(actual.message===error)throw new ERR_AMBIGUOUS_ARGUMENT("error/message",'The error message "'.concat(actual.message,'" is identical to the message.'))}else if(actual===error)throw new ERR_AMBIGUOUS_ARGUMENT("error/message",'The error "'.concat(actual,'" is identical to the message.'));message=error,error=void 0}else if(null!=error&&"object"!==_typeof(error)&&"function"!=typeof error)throw new ERR_INVALID_ARG_TYPE("error",["Object","Error","Function","RegExp"],error);if(actual===NO_EXCEPTION_SENTINEL){var details="";error&&error.name&&(details+=" (".concat(error.name,")")),details+=message?": ".concat(message):".";var fnType="rejects"===stackStartFn.name?"rejection":"exception";innerFail({actual:void 0,expected:error,operator:stackStartFn.name,message:"Missing expected ".concat(fnType).concat(details),stackStartFn})}if(error&&!expectedException(actual,error,message,stackStartFn))throw actual}function expectsNoError(stackStartFn,actual,error,message){if(actual!==NO_EXCEPTION_SENTINEL){if("string"==typeof error&&(message=error,error=void 0),!error||expectedException(actual,error)){var details=message?": ".concat(message):".",fnType="doesNotReject"===stackStartFn.name?"rejection":"exception";innerFail({actual,expected:error,operator:stackStartFn.name,message:"Got unwanted ".concat(fnType).concat(details,"\n")+'Actual message: "'.concat(actual&&actual.message,'"'),stackStartFn})}throw actual}}function strict(){for(var _len6=arguments.length,args=new Array(_len6),_key6=0;_key6<_len6;_key6++)args[_key6]=arguments[_key6];innerOk.apply(void 0,[strict,args.length].concat(args))}assert.throws=function throws(promiseFn){for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++)args[_key2-1]=arguments[_key2];expectsError.apply(void 0,[throws,getActual(promiseFn)].concat(args))},assert.rejects=function rejects(promiseFn){for(var _len3=arguments.length,args=new Array(_len3>1?_len3-1:0),_key3=1;_key3<_len3;_key3++)args[_key3-1]=arguments[_key3];return waitForActual(promiseFn).then((function(result){return expectsError.apply(void 0,[rejects,result].concat(args))}))},assert.doesNotThrow=function doesNotThrow(fn){for(var _len4=arguments.length,args=new Array(_len4>1?_len4-1:0),_key4=1;_key4<_len4;_key4++)args[_key4-1]=arguments[_key4];expectsNoError.apply(void 0,[doesNotThrow,getActual(fn)].concat(args))},assert.doesNotReject=function doesNotReject(fn){for(var _len5=arguments.length,args=new Array(_len5>1?_len5-1:0),_key5=1;_key5<_len5;_key5++)args[_key5-1]=arguments[_key5];return waitForActual(fn).then((function(result){return expectsNoError.apply(void 0,[doesNotReject,result].concat(args))}))},assert.ifError=function ifError(err){if(null!=err){var message="ifError got unwanted exception: ";"object"===_typeof(err)&&"string"==typeof err.message?0===err.message.length&&err.constructor?message+=err.constructor.name:message+=err.message:message+=inspect(err);var newErr=new AssertionError({actual:err,expected:null,operator:"ifError",message,stackStartFn:ifError}),origStack=err.stack;if("string"==typeof origStack){var tmp2=origStack.split("\n");tmp2.shift();for(var tmp1=newErr.stack.split("\n"),i=0;i{"use strict";function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function _defineProperties(target,props){for(var i=0;istr.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}var blue="",green="",red="",white="",kReadableOperator={deepStrictEqual:"Expected values to be strictly deep-equal:",strictEqual:"Expected values to be strictly equal:",strictEqualObject:'Expected "actual" to be reference-equal to "expected":',deepEqual:"Expected values to be loosely deep-equal:",equal:"Expected values to be loosely equal:",notDeepStrictEqual:'Expected "actual" not to be strictly deep-equal to:',notStrictEqual:'Expected "actual" to be strictly unequal to:',notStrictEqualObject:'Expected "actual" not to be reference-equal to "expected":',notDeepEqual:'Expected "actual" not to be loosely deep-equal to:',notEqual:'Expected "actual" to be loosely unequal to:',notIdentical:"Values identical but not reference-equal:"};function copyError(source){var keys=Object.keys(source),target=Object.create(Object.getPrototypeOf(source));return keys.forEach((function(key){target[key]=source[key]})),Object.defineProperty(target,"message",{value:source.message}),target}function inspectValue(val){return inspect(val,{compact:!1,customInspect:!1,depth:1e3,maxArrayLength:1/0,showHidden:!1,breakLength:1/0,showProxy:!1,sorted:!0,getters:!0})}function createErrDiff(actual,expected,operator){var other="",res="",lastPos=0,end="",skipped=!1,actualInspected=inspectValue(actual),actualLines=actualInspected.split("\n"),expectedLines=inspectValue(expected).split("\n"),i=0,indicator="";if("strictEqual"===operator&&"object"===_typeof(actual)&&"object"===_typeof(expected)&&null!==actual&&null!==expected&&(operator="strictEqualObject"),1===actualLines.length&&1===expectedLines.length&&actualLines[0]!==expectedLines[0]){var inputLength=actualLines[0].length+expectedLines[0].length;if(inputLength<=10){if(!("object"===_typeof(actual)&&null!==actual||"object"===_typeof(expected)&&null!==expected||0===actual&&0===expected))return"".concat(kReadableOperator[operator],"\n\n")+"".concat(actualLines[0]," !== ").concat(expectedLines[0],"\n")}else if("strictEqualObject"!==operator){if(inputLength<(process.stderr&&process.stderr.isTTY?process.stderr.columns:80)){for(;actualLines[0][i]===expectedLines[0][i];)i++;i>2&&(indicator="\n ".concat(function repeat(str,count){if(count=Math.floor(count),0==str.length||0==count)return"";var maxCount=str.length*count;for(count=Math.floor(Math.log(count)/Math.log(2));count;)str+=str,count--;return str+str.substring(0,maxCount-str.length)}(" ",i),"^"),i=0)}}}for(var a=actualLines[actualLines.length-1],b=expectedLines[expectedLines.length-1];a===b&&(i++<2?end="\n ".concat(a).concat(end):other=a,actualLines.pop(),expectedLines.pop(),0!==actualLines.length&&0!==expectedLines.length);)a=actualLines[actualLines.length-1],b=expectedLines[expectedLines.length-1];var maxLines=Math.max(actualLines.length,expectedLines.length);if(0===maxLines){var _actualLines=actualInspected.split("\n");if(_actualLines.length>30)for(_actualLines[26]="".concat(blue,"...").concat(white);_actualLines.length>27;)_actualLines.pop();return"".concat(kReadableOperator.notIdentical,"\n\n").concat(_actualLines.join("\n"),"\n")}i>3&&(end="\n".concat(blue,"...").concat(white).concat(end),skipped=!0),""!==other&&(end="\n ".concat(other).concat(end),other="");var printedLines=0,msg=kReadableOperator[operator]+"\n".concat(green,"+ actual").concat(white," ").concat(red,"- expected").concat(white),skippedMsg=" ".concat(blue,"...").concat(white," Lines skipped");for(i=0;i1&&i>2&&(cur>4?(res+="\n".concat(blue,"...").concat(white),skipped=!0):cur>3&&(res+="\n ".concat(expectedLines[i-2]),printedLines++),res+="\n ".concat(expectedLines[i-1]),printedLines++),lastPos=i,other+="\n".concat(red,"-").concat(white," ").concat(expectedLines[i]),printedLines++;else if(expectedLines.length1&&i>2&&(cur>4?(res+="\n".concat(blue,"...").concat(white),skipped=!0):cur>3&&(res+="\n ".concat(actualLines[i-2]),printedLines++),res+="\n ".concat(actualLines[i-1]),printedLines++),lastPos=i,res+="\n".concat(green,"+").concat(white," ").concat(actualLines[i]),printedLines++;else{var expectedLine=expectedLines[i],actualLine=actualLines[i],divergingLines=actualLine!==expectedLine&&(!endsWith(actualLine,",")||actualLine.slice(0,-1)!==expectedLine);divergingLines&&endsWith(expectedLine,",")&&expectedLine.slice(0,-1)===actualLine&&(divergingLines=!1,actualLine+=","),divergingLines?(cur>1&&i>2&&(cur>4?(res+="\n".concat(blue,"...").concat(white),skipped=!0):cur>3&&(res+="\n ".concat(actualLines[i-2]),printedLines++),res+="\n ".concat(actualLines[i-1]),printedLines++),lastPos=i,res+="\n".concat(green,"+").concat(white," ").concat(actualLine),other+="\n".concat(red,"-").concat(white," ").concat(expectedLine),printedLines+=2):(res+=other,other="",1!==cur&&0!==i||(res+="\n ".concat(actualLine),printedLines++))}if(printedLines>20&&i30)for(res[26]="".concat(blue,"...").concat(white);res.length>27;)res.pop();_this=1===res.length?_possibleConstructorReturn(this,_getPrototypeOf(AssertionError).call(this,"".concat(base," ").concat(res[0]))):_possibleConstructorReturn(this,_getPrototypeOf(AssertionError).call(this,"".concat(base,"\n\n").concat(res.join("\n"),"\n")))}else{var _res=inspectValue(actual),other="",knownOperators=kReadableOperator[operator];"notDeepEqual"===operator||"notEqual"===operator?(_res="".concat(kReadableOperator[operator],"\n\n").concat(_res)).length>1024&&(_res="".concat(_res.slice(0,1021),"...")):(other="".concat(inspectValue(expected)),_res.length>512&&(_res="".concat(_res.slice(0,509),"...")),other.length>512&&(other="".concat(other.slice(0,509),"...")),"deepEqual"===operator||"equal"===operator?_res="".concat(knownOperators,"\n\n").concat(_res,"\n\nshould equal\n\n"):other=" ".concat(operator," ").concat(other)),_this=_possibleConstructorReturn(this,_getPrototypeOf(AssertionError).call(this,"".concat(_res).concat(other)))}return Error.stackTraceLimit=limit,_this.generatedMessage=!message,Object.defineProperty(_assertThisInitialized(_this),"name",{value:"AssertionError [ERR_ASSERTION]",enumerable:!1,writable:!0,configurable:!0}),_this.code="ERR_ASSERTION",_this.actual=actual,_this.expected=expected,_this.operator=operator,Error.captureStackTrace&&Error.captureStackTrace(_assertThisInitialized(_this),stackStartFn),_this.stack,_this.name="AssertionError",_possibleConstructorReturn(_this)}return function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function");subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:!0,configurable:!0}}),superClass&&_setPrototypeOf(subClass,superClass)}(AssertionError,_Error),function _createClass(Constructor,protoProps,staticProps){return protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Constructor}(AssertionError,[{key:"toString",value:function toString(){return"".concat(this.name," [").concat(this.code,"]: ").concat(this.message)}},{key:inspect.custom,value:function value(recurseTimes,ctx){return inspect(this,function _objectSpread(target){for(var i=1;i{"use strict";function _typeof(obj){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function _typeof(obj){return typeof obj}:function _typeof(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_typeof(obj)}function _possibleConstructorReturn(self,call){return!call||"object"!==_typeof(call)&&"function"!=typeof call?function _assertThisInitialized(self){if(void 0===self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return self}(self):call}function _getPrototypeOf(o){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o)},_getPrototypeOf(o)}function _setPrototypeOf(o,p){return _setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){return o.__proto__=p,o},_setPrototypeOf(o,p)}var assert,util,codes={};function createErrorType(code,message,Base){Base||(Base=Error);var NodeError=function(_Base){function NodeError(arg1,arg2,arg3){var _this;return function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}(this,NodeError),_this=_possibleConstructorReturn(this,_getPrototypeOf(NodeError).call(this,function getMessage(arg1,arg2,arg3){return"string"==typeof message?message:message(arg1,arg2,arg3)}(arg1,arg2,arg3))),_this.code=code,_this}return function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function");subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:!0,configurable:!0}}),superClass&&_setPrototypeOf(subClass,superClass)}(NodeError,_Base),NodeError}(Base);codes[code]=NodeError}function oneOf(expected,thing){if(Array.isArray(expected)){var len=expected.length;return expected=expected.map((function(i){return String(i)})),len>2?"one of ".concat(thing," ").concat(expected.slice(0,len-1).join(", "),", or ")+expected[len-1]:2===len?"one of ".concat(thing," ").concat(expected[0]," or ").concat(expected[1]):"of ".concat(thing," ").concat(expected[0])}return"of ".concat(thing," ").concat(String(expected))}createErrorType("ERR_AMBIGUOUS_ARGUMENT",'The "%s" argument is ambiguous. %s',TypeError),createErrorType("ERR_INVALID_ARG_TYPE",(function(name,expected,actual){var determiner,msg;if(void 0===assert&&(assert=__webpack_require__(9282)),assert("string"==typeof name,"'name' must be a string"),"string"==typeof expected&&function startsWith(str,search,pos){return str.substr(!pos||pos<0?0:+pos,search.length)===search}(expected,"not ")?(determiner="must not be",expected=expected.replace(/^not /,"")):determiner="must be",function endsWith(str,search,this_len){return(void 0===this_len||this_len>str.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}(name," argument"))msg="The ".concat(name," ").concat(determiner," ").concat(oneOf(expected,"type"));else{var type=function includes(str,search,start){return"number"!=typeof start&&(start=0),!(start+search.length>str.length)&&-1!==str.indexOf(search,start)}(name,".")?"property":"argument";msg='The "'.concat(name,'" ').concat(type," ").concat(determiner," ").concat(oneOf(expected,"type"))}return msg+=". Received type ".concat(_typeof(actual))}),TypeError),createErrorType("ERR_INVALID_ARG_VALUE",(function(name,value){var reason=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"is invalid";void 0===util&&(util=__webpack_require__(9539));var inspected=util.inspect(value);return inspected.length>128&&(inspected="".concat(inspected.slice(0,128),"...")),"The argument '".concat(name,"' ").concat(reason,". Received ").concat(inspected)}),TypeError,RangeError),createErrorType("ERR_INVALID_RETURN_VALUE",(function(input,name,value){var type;return type=value&&value.constructor&&value.constructor.name?"instance of ".concat(value.constructor.name):"type ".concat(_typeof(value)),"Expected ".concat(input,' to be returned from the "').concat(name,'"')+" function but got ".concat(type,".")}),TypeError),createErrorType("ERR_MISSING_ARGS",(function(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];void 0===assert&&(assert=__webpack_require__(9282)),assert(args.length>0,"At least one arg needs to be specified");var msg="The ",len=args.length;switch(args=args.map((function(a){return'"'.concat(a,'"')})),len){case 1:msg+="".concat(args[0]," argument");break;case 2:msg+="".concat(args[0]," and ").concat(args[1]," arguments");break;default:msg+=args.slice(0,len-1).join(", "),msg+=", and ".concat(args[len-1]," arguments")}return"".concat(msg," must be specified")}),TypeError),module.exports.codes=codes},9158:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";function _slicedToArray(arr,i){return function _arrayWithHoles(arr){if(Array.isArray(arr))return arr}(arr)||function _iterableToArrayLimit(arr,i){var _arr=[],_n=!0,_d=!1,_e=void 0;try{for(var _s,_i=arr[Symbol.iterator]();!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{_n||null==_i.return||_i.return()}finally{if(_d)throw _e}}return _arr}(arr,i)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function _typeof(obj){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function _typeof(obj){return typeof obj}:function _typeof(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_typeof(obj)}var regexFlagsSupported=void 0!==/a/g.flags,arrayFromSet=function arrayFromSet(set){var array=[];return set.forEach((function(value){return array.push(value)})),array},arrayFromMap=function arrayFromMap(map){var array=[];return map.forEach((function(value,key){return array.push([key,value])})),array},objectIs=Object.is?Object.is:__webpack_require__(609),objectGetOwnPropertySymbols=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols:function(){return[]},numberIsNaN=Number.isNaN?Number.isNaN:__webpack_require__(360);function uncurryThis(f){return f.call.bind(f)}var hasOwnProperty=uncurryThis(Object.prototype.hasOwnProperty),propertyIsEnumerable=uncurryThis(Object.prototype.propertyIsEnumerable),objectToString=uncurryThis(Object.prototype.toString),_require$types=__webpack_require__(9539).types,isAnyArrayBuffer=_require$types.isAnyArrayBuffer,isArrayBufferView=_require$types.isArrayBufferView,isDate=_require$types.isDate,isMap=_require$types.isMap,isRegExp=_require$types.isRegExp,isSet=_require$types.isSet,isNativeError=_require$types.isNativeError,isBoxedPrimitive=_require$types.isBoxedPrimitive,isNumberObject=_require$types.isNumberObject,isStringObject=_require$types.isStringObject,isBooleanObject=_require$types.isBooleanObject,isBigIntObject=_require$types.isBigIntObject,isSymbolObject=_require$types.isSymbolObject,isFloat32Array=_require$types.isFloat32Array,isFloat64Array=_require$types.isFloat64Array;function isNonIndex(key){if(0===key.length||key.length>10)return!0;for(var i=0;i57)return!0}return 10===key.length&&key>=Math.pow(2,32)}function getOwnNonIndexProperties(value){return Object.keys(value).filter(isNonIndex).concat(objectGetOwnPropertySymbols(value).filter(Object.prototype.propertyIsEnumerable.bind(value)))}function compare(a,b){if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);i{module.exports=__webpack_require__(1609)},5448:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(4867),settle=__webpack_require__(6026),cookies=__webpack_require__(4372),buildURL=__webpack_require__(5327),buildFullPath=__webpack_require__(4097),parseHeaders=__webpack_require__(4109),isURLSameOrigin=__webpack_require__(7985),transitionalDefaults=__webpack_require__(7874),AxiosError=__webpack_require__(2648),CanceledError=__webpack_require__(644),parseProtocol=__webpack_require__(205);module.exports=function xhrAdapter(config){return new Promise((function dispatchXhrRequest(resolve,reject){var onCanceled,requestData=config.data,requestHeaders=config.headers,responseType=config.responseType;function done(){config.cancelToken&&config.cancelToken.unsubscribe(onCanceled),config.signal&&config.signal.removeEventListener("abort",onCanceled)}utils.isFormData(requestData)&&utils.isStandardBrowserEnv()&&delete requestHeaders["Content-Type"];var request=new XMLHttpRequest;if(config.auth){var username=config.auth.username||"",password=config.auth.password?unescape(encodeURIComponent(config.auth.password)):"";requestHeaders.Authorization="Basic "+btoa(username+":"+password)}var fullPath=buildFullPath(config.baseURL,config.url);function onloadend(){if(request){var responseHeaders="getAllResponseHeaders"in request?parseHeaders(request.getAllResponseHeaders()):null,response={data:responseType&&"text"!==responseType&&"json"!==responseType?request.response:request.responseText,status:request.status,statusText:request.statusText,headers:responseHeaders,config,request};settle((function _resolve(value){resolve(value),done()}),(function _reject(err){reject(err),done()}),response),request=null}}if(request.open(config.method.toUpperCase(),buildURL(fullPath,config.params,config.paramsSerializer),!0),request.timeout=config.timeout,"onloadend"in request?request.onloadend=onloadend:request.onreadystatechange=function handleLoad(){request&&4===request.readyState&&(0!==request.status||request.responseURL&&0===request.responseURL.indexOf("file:"))&&setTimeout(onloadend)},request.onabort=function handleAbort(){request&&(reject(new AxiosError("Request aborted",AxiosError.ECONNABORTED,config,request)),request=null)},request.onerror=function handleError(){reject(new AxiosError("Network Error",AxiosError.ERR_NETWORK,config,request,request)),request=null},request.ontimeout=function handleTimeout(){var timeoutErrorMessage=config.timeout?"timeout of "+config.timeout+"ms exceeded":"timeout exceeded",transitional=config.transitional||transitionalDefaults;config.timeoutErrorMessage&&(timeoutErrorMessage=config.timeoutErrorMessage),reject(new AxiosError(timeoutErrorMessage,transitional.clarifyTimeoutError?AxiosError.ETIMEDOUT:AxiosError.ECONNABORTED,config,request)),request=null},utils.isStandardBrowserEnv()){var xsrfValue=(config.withCredentials||isURLSameOrigin(fullPath))&&config.xsrfCookieName?cookies.read(config.xsrfCookieName):void 0;xsrfValue&&(requestHeaders[config.xsrfHeaderName]=xsrfValue)}"setRequestHeader"in request&&utils.forEach(requestHeaders,(function setRequestHeader(val,key){void 0===requestData&&"content-type"===key.toLowerCase()?delete requestHeaders[key]:request.setRequestHeader(key,val)})),utils.isUndefined(config.withCredentials)||(request.withCredentials=!!config.withCredentials),responseType&&"json"!==responseType&&(request.responseType=config.responseType),"function"==typeof config.onDownloadProgress&&request.addEventListener("progress",config.onDownloadProgress),"function"==typeof config.onUploadProgress&&request.upload&&request.upload.addEventListener("progress",config.onUploadProgress),(config.cancelToken||config.signal)&&(onCanceled=function(cancel){request&&(reject(!cancel||cancel&&cancel.type?new CanceledError:cancel),request.abort(),request=null)},config.cancelToken&&config.cancelToken.subscribe(onCanceled),config.signal&&(config.signal.aborted?onCanceled():config.signal.addEventListener("abort",onCanceled))),requestData||(requestData=null);var protocol=parseProtocol(fullPath);protocol&&-1===["http","https","file"].indexOf(protocol)?reject(new AxiosError("Unsupported protocol "+protocol+":",AxiosError.ERR_BAD_REQUEST,config)):request.send(requestData)}))}},1609:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(4867),bind=__webpack_require__(1849),Axios=__webpack_require__(321),mergeConfig=__webpack_require__(7185);var axios=function createInstance(defaultConfig){var context=new Axios(defaultConfig),instance=bind(Axios.prototype.request,context);return utils.extend(instance,Axios.prototype,context),utils.extend(instance,context),instance.create=function create(instanceConfig){return createInstance(mergeConfig(defaultConfig,instanceConfig))},instance}(__webpack_require__(5546));axios.Axios=Axios,axios.CanceledError=__webpack_require__(644),axios.CancelToken=__webpack_require__(4972),axios.isCancel=__webpack_require__(6502),axios.VERSION=__webpack_require__(7288).version,axios.toFormData=__webpack_require__(7675),axios.AxiosError=__webpack_require__(2648),axios.Cancel=axios.CanceledError,axios.all=function all(promises){return Promise.all(promises)},axios.spread=__webpack_require__(8713),axios.isAxiosError=__webpack_require__(6268),module.exports=axios,module.exports.default=axios},4972:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var CanceledError=__webpack_require__(644);function CancelToken(executor){if("function"!=typeof executor)throw new TypeError("executor must be a function.");var resolvePromise;this.promise=new Promise((function promiseExecutor(resolve){resolvePromise=resolve}));var token=this;this.promise.then((function(cancel){if(token._listeners){var i,l=token._listeners.length;for(i=0;i{"use strict";var AxiosError=__webpack_require__(2648);function CanceledError(message){AxiosError.call(this,null==message?"canceled":message,AxiosError.ERR_CANCELED),this.name="CanceledError"}__webpack_require__(4867).inherits(CanceledError,AxiosError,{__CANCEL__:!0}),module.exports=CanceledError},6502:module=>{"use strict";module.exports=function isCancel(value){return!(!value||!value.__CANCEL__)}},321:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(4867),buildURL=__webpack_require__(5327),InterceptorManager=__webpack_require__(782),dispatchRequest=__webpack_require__(3572),mergeConfig=__webpack_require__(7185),buildFullPath=__webpack_require__(4097),validator=__webpack_require__(4875),validators=validator.validators;function Axios(instanceConfig){this.defaults=instanceConfig,this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}Axios.prototype.request=function request(configOrUrl,config){"string"==typeof configOrUrl?(config=config||{}).url=configOrUrl:config=configOrUrl||{},(config=mergeConfig(this.defaults,config)).method?config.method=config.method.toLowerCase():this.defaults.method?config.method=this.defaults.method.toLowerCase():config.method="get";var transitional=config.transitional;void 0!==transitional&&validator.assertOptions(transitional,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean)},!1);var requestInterceptorChain=[],synchronousRequestInterceptors=!0;this.interceptors.request.forEach((function unshiftRequestInterceptors(interceptor){"function"==typeof interceptor.runWhen&&!1===interceptor.runWhen(config)||(synchronousRequestInterceptors=synchronousRequestInterceptors&&interceptor.synchronous,requestInterceptorChain.unshift(interceptor.fulfilled,interceptor.rejected))}));var promise,responseInterceptorChain=[];if(this.interceptors.response.forEach((function pushResponseInterceptors(interceptor){responseInterceptorChain.push(interceptor.fulfilled,interceptor.rejected)})),!synchronousRequestInterceptors){var chain=[dispatchRequest,void 0];for(Array.prototype.unshift.apply(chain,requestInterceptorChain),chain=chain.concat(responseInterceptorChain),promise=Promise.resolve(config);chain.length;)promise=promise.then(chain.shift(),chain.shift());return promise}for(var newConfig=config;requestInterceptorChain.length;){var onFulfilled=requestInterceptorChain.shift(),onRejected=requestInterceptorChain.shift();try{newConfig=onFulfilled(newConfig)}catch(error){onRejected(error);break}}try{promise=dispatchRequest(newConfig)}catch(error){return Promise.reject(error)}for(;responseInterceptorChain.length;)promise=promise.then(responseInterceptorChain.shift(),responseInterceptorChain.shift());return promise},Axios.prototype.getUri=function getUri(config){config=mergeConfig(this.defaults,config);var fullPath=buildFullPath(config.baseURL,config.url);return buildURL(fullPath,config.params,config.paramsSerializer)},utils.forEach(["delete","get","head","options"],(function forEachMethodNoData(method){Axios.prototype[method]=function(url,config){return this.request(mergeConfig(config||{},{method,url,data:(config||{}).data}))}})),utils.forEach(["post","put","patch"],(function forEachMethodWithData(method){function generateHTTPMethod(isForm){return function httpMethod(url,data,config){return this.request(mergeConfig(config||{},{method,headers:isForm?{"Content-Type":"multipart/form-data"}:{},url,data}))}}Axios.prototype[method]=generateHTTPMethod(),Axios.prototype[method+"Form"]=generateHTTPMethod(!0)})),module.exports=Axios},2648:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(4867);function AxiosError(message,code,config,request,response){Error.call(this),this.message=message,this.name="AxiosError",code&&(this.code=code),config&&(this.config=config),request&&(this.request=request),response&&(this.response=response)}utils.inherits(AxiosError,Error,{toJSON:function toJSON(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var prototype=AxiosError.prototype,descriptors={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED"].forEach((function(code){descriptors[code]={value:code}})),Object.defineProperties(AxiosError,descriptors),Object.defineProperty(prototype,"isAxiosError",{value:!0}),AxiosError.from=function(error,code,config,request,response,customProps){var axiosError=Object.create(prototype);return utils.toFlatObject(error,axiosError,(function filter(obj){return obj!==Error.prototype})),AxiosError.call(axiosError,error.message,code,config,request,response),axiosError.name=error.name,customProps&&Object.assign(axiosError,customProps),axiosError},module.exports=AxiosError},782:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(4867);function InterceptorManager(){this.handlers=[]}InterceptorManager.prototype.use=function use(fulfilled,rejected,options){return this.handlers.push({fulfilled,rejected,synchronous:!!options&&options.synchronous,runWhen:options?options.runWhen:null}),this.handlers.length-1},InterceptorManager.prototype.eject=function eject(id){this.handlers[id]&&(this.handlers[id]=null)},InterceptorManager.prototype.forEach=function forEach(fn){utils.forEach(this.handlers,(function forEachHandler(h){null!==h&&fn(h)}))},module.exports=InterceptorManager},4097:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var isAbsoluteURL=__webpack_require__(1793),combineURLs=__webpack_require__(7303);module.exports=function buildFullPath(baseURL,requestedURL){return baseURL&&!isAbsoluteURL(requestedURL)?combineURLs(baseURL,requestedURL):requestedURL}},3572:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(4867),transformData=__webpack_require__(8527),isCancel=__webpack_require__(6502),defaults=__webpack_require__(5546),CanceledError=__webpack_require__(644);function throwIfCancellationRequested(config){if(config.cancelToken&&config.cancelToken.throwIfRequested(),config.signal&&config.signal.aborted)throw new CanceledError}module.exports=function dispatchRequest(config){return throwIfCancellationRequested(config),config.headers=config.headers||{},config.data=transformData.call(config,config.data,config.headers,config.transformRequest),config.headers=utils.merge(config.headers.common||{},config.headers[config.method]||{},config.headers),utils.forEach(["delete","get","head","post","put","patch","common"],(function cleanHeaderConfig(method){delete config.headers[method]})),(config.adapter||defaults.adapter)(config).then((function onAdapterResolution(response){return throwIfCancellationRequested(config),response.data=transformData.call(config,response.data,response.headers,config.transformResponse),response}),(function onAdapterRejection(reason){return isCancel(reason)||(throwIfCancellationRequested(config),reason&&reason.response&&(reason.response.data=transformData.call(config,reason.response.data,reason.response.headers,config.transformResponse))),Promise.reject(reason)}))}},7185:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(4867);module.exports=function mergeConfig(config1,config2){config2=config2||{};var config={};function getMergedValue(target,source){return utils.isPlainObject(target)&&utils.isPlainObject(source)?utils.merge(target,source):utils.isPlainObject(source)?utils.merge({},source):utils.isArray(source)?source.slice():source}function mergeDeepProperties(prop){return utils.isUndefined(config2[prop])?utils.isUndefined(config1[prop])?void 0:getMergedValue(void 0,config1[prop]):getMergedValue(config1[prop],config2[prop])}function valueFromConfig2(prop){if(!utils.isUndefined(config2[prop]))return getMergedValue(void 0,config2[prop])}function defaultToConfig2(prop){return utils.isUndefined(config2[prop])?utils.isUndefined(config1[prop])?void 0:getMergedValue(void 0,config1[prop]):getMergedValue(void 0,config2[prop])}function mergeDirectKeys(prop){return prop in config2?getMergedValue(config1[prop],config2[prop]):prop in config1?getMergedValue(void 0,config1[prop]):void 0}var mergeMap={url:valueFromConfig2,method:valueFromConfig2,data:valueFromConfig2,baseURL:defaultToConfig2,transformRequest:defaultToConfig2,transformResponse:defaultToConfig2,paramsSerializer:defaultToConfig2,timeout:defaultToConfig2,timeoutMessage:defaultToConfig2,withCredentials:defaultToConfig2,adapter:defaultToConfig2,responseType:defaultToConfig2,xsrfCookieName:defaultToConfig2,xsrfHeaderName:defaultToConfig2,onUploadProgress:defaultToConfig2,onDownloadProgress:defaultToConfig2,decompress:defaultToConfig2,maxContentLength:defaultToConfig2,maxBodyLength:defaultToConfig2,beforeRedirect:defaultToConfig2,transport:defaultToConfig2,httpAgent:defaultToConfig2,httpsAgent:defaultToConfig2,cancelToken:defaultToConfig2,socketPath:defaultToConfig2,responseEncoding:defaultToConfig2,validateStatus:mergeDirectKeys};return utils.forEach(Object.keys(config1).concat(Object.keys(config2)),(function computeConfigValue(prop){var merge=mergeMap[prop]||mergeDeepProperties,configValue=merge(prop);utils.isUndefined(configValue)&&merge!==mergeDirectKeys||(config[prop]=configValue)})),config}},6026:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var AxiosError=__webpack_require__(2648);module.exports=function settle(resolve,reject,response){var validateStatus=response.config.validateStatus;response.status&&validateStatus&&!validateStatus(response.status)?reject(new AxiosError("Request failed with status code "+response.status,[AxiosError.ERR_BAD_REQUEST,AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status/100)-4],response.config,response.request,response)):resolve(response)}},8527:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(4867),defaults=__webpack_require__(5546);module.exports=function transformData(data,headers,fns){var context=this||defaults;return utils.forEach(fns,(function transform(fn){data=fn.call(context,data,headers)})),data}},5546:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(4867),normalizeHeaderName=__webpack_require__(6016),AxiosError=__webpack_require__(2648),transitionalDefaults=__webpack_require__(7874),toFormData=__webpack_require__(7675),DEFAULT_CONTENT_TYPE={"Content-Type":"application/x-www-form-urlencoded"};function setContentTypeIfUnset(headers,value){!utils.isUndefined(headers)&&utils.isUndefined(headers["Content-Type"])&&(headers["Content-Type"]=value)}var defaults={transitional:transitionalDefaults,adapter:function getDefaultAdapter(){var adapter;return("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(adapter=__webpack_require__(5448)),adapter}(),transformRequest:[function transformRequest(data,headers){if(normalizeHeaderName(headers,"Accept"),normalizeHeaderName(headers,"Content-Type"),utils.isFormData(data)||utils.isArrayBuffer(data)||utils.isBuffer(data)||utils.isStream(data)||utils.isFile(data)||utils.isBlob(data))return data;if(utils.isArrayBufferView(data))return data.buffer;if(utils.isURLSearchParams(data))return setContentTypeIfUnset(headers,"application/x-www-form-urlencoded;charset=utf-8"),data.toString();var isFileList,isObjectPayload=utils.isObject(data),contentType=headers&&headers["Content-Type"];if((isFileList=utils.isFileList(data))||isObjectPayload&&"multipart/form-data"===contentType){var _FormData=this.env&&this.env.FormData;return toFormData(isFileList?{"files[]":data}:data,_FormData&&new _FormData)}return isObjectPayload||"application/json"===contentType?(setContentTypeIfUnset(headers,"application/json"),function stringifySafely(rawValue,parser,encoder){if(utils.isString(rawValue))try{return(parser||JSON.parse)(rawValue),utils.trim(rawValue)}catch(e){if("SyntaxError"!==e.name)throw e}return(encoder||JSON.stringify)(rawValue)}(data)):data}],transformResponse:[function transformResponse(data){var transitional=this.transitional||defaults.transitional,silentJSONParsing=transitional&&transitional.silentJSONParsing,forcedJSONParsing=transitional&&transitional.forcedJSONParsing,strictJSONParsing=!silentJSONParsing&&"json"===this.responseType;if(strictJSONParsing||forcedJSONParsing&&utils.isString(data)&&data.length)try{return JSON.parse(data)}catch(e){if(strictJSONParsing){if("SyntaxError"===e.name)throw AxiosError.from(e,AxiosError.ERR_BAD_RESPONSE,this,null,this.response);throw e}}return data}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:__webpack_require__(1623)},validateStatus:function validateStatus(status){return status>=200&&status<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};utils.forEach(["delete","get","head"],(function forEachMethodNoData(method){defaults.headers[method]={}})),utils.forEach(["post","put","patch"],(function forEachMethodWithData(method){defaults.headers[method]=utils.merge(DEFAULT_CONTENT_TYPE)})),module.exports=defaults},7874:module=>{"use strict";module.exports={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1}},7288:module=>{module.exports={version:"0.27.2"}},1849:module=>{"use strict";module.exports=function bind(fn,thisArg){return function wrap(){for(var args=new Array(arguments.length),i=0;i{"use strict";var utils=__webpack_require__(4867);function encode(val){return encodeURIComponent(val).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}module.exports=function buildURL(url,params,paramsSerializer){if(!params)return url;var serializedParams;if(paramsSerializer)serializedParams=paramsSerializer(params);else if(utils.isURLSearchParams(params))serializedParams=params.toString();else{var parts=[];utils.forEach(params,(function serialize(val,key){null!=val&&(utils.isArray(val)?key+="[]":val=[val],utils.forEach(val,(function parseValue(v){utils.isDate(v)?v=v.toISOString():utils.isObject(v)&&(v=JSON.stringify(v)),parts.push(encode(key)+"="+encode(v))})))})),serializedParams=parts.join("&")}if(serializedParams){var hashmarkIndex=url.indexOf("#");-1!==hashmarkIndex&&(url=url.slice(0,hashmarkIndex)),url+=(-1===url.indexOf("?")?"?":"&")+serializedParams}return url}},7303:module=>{"use strict";module.exports=function combineURLs(baseURL,relativeURL){return relativeURL?baseURL.replace(/\/+$/,"")+"/"+relativeURL.replace(/^\/+/,""):baseURL}},4372:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(4867);module.exports=utils.isStandardBrowserEnv()?function standardBrowserEnv(){return{write:function write(name,value,expires,path,domain,secure){var cookie=[];cookie.push(name+"="+encodeURIComponent(value)),utils.isNumber(expires)&&cookie.push("expires="+new Date(expires).toGMTString()),utils.isString(path)&&cookie.push("path="+path),utils.isString(domain)&&cookie.push("domain="+domain),!0===secure&&cookie.push("secure"),document.cookie=cookie.join("; ")},read:function read(name){var match=document.cookie.match(new RegExp("(^|;\\s*)("+name+")=([^;]*)"));return match?decodeURIComponent(match[3]):null},remove:function remove(name){this.write(name,"",Date.now()-864e5)}}}():{write:function write(){},read:function read(){return null},remove:function remove(){}}},1793:module=>{"use strict";module.exports=function isAbsoluteURL(url){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(url)}},6268:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(4867);module.exports=function isAxiosError(payload){return utils.isObject(payload)&&!0===payload.isAxiosError}},7985:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(4867);module.exports=utils.isStandardBrowserEnv()?function standardBrowserEnv(){var originURL,msie=/(msie|trident)/i.test(navigator.userAgent),urlParsingNode=document.createElement("a");function resolveURL(url){var href=url;return msie&&(urlParsingNode.setAttribute("href",href),href=urlParsingNode.href),urlParsingNode.setAttribute("href",href),{href:urlParsingNode.href,protocol:urlParsingNode.protocol?urlParsingNode.protocol.replace(/:$/,""):"",host:urlParsingNode.host,search:urlParsingNode.search?urlParsingNode.search.replace(/^\?/,""):"",hash:urlParsingNode.hash?urlParsingNode.hash.replace(/^#/,""):"",hostname:urlParsingNode.hostname,port:urlParsingNode.port,pathname:"/"===urlParsingNode.pathname.charAt(0)?urlParsingNode.pathname:"/"+urlParsingNode.pathname}}return originURL=resolveURL(window.location.href),function isURLSameOrigin(requestURL){var parsed=utils.isString(requestURL)?resolveURL(requestURL):requestURL;return parsed.protocol===originURL.protocol&&parsed.host===originURL.host}}():function isURLSameOrigin(){return!0}},6016:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(4867);module.exports=function normalizeHeaderName(headers,normalizedName){utils.forEach(headers,(function processHeader(value,name){name!==normalizedName&&name.toUpperCase()===normalizedName.toUpperCase()&&(headers[normalizedName]=value,delete headers[name])}))}},1623:module=>{module.exports=null},4109:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(4867),ignoreDuplicateOf=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];module.exports=function parseHeaders(headers){var key,val,i,parsed={};return headers?(utils.forEach(headers.split("\n"),(function parser(line){if(i=line.indexOf(":"),key=utils.trim(line.substr(0,i)).toLowerCase(),val=utils.trim(line.substr(i+1)),key){if(parsed[key]&&ignoreDuplicateOf.indexOf(key)>=0)return;parsed[key]="set-cookie"===key?(parsed[key]?parsed[key]:[]).concat([val]):parsed[key]?parsed[key]+", "+val:val}})),parsed):parsed}},205:module=>{"use strict";module.exports=function parseProtocol(url){var match=/^([-+\w]{1,25})(:?\/\/|:)/.exec(url);return match&&match[1]||""}},8713:module=>{"use strict";module.exports=function spread(callback){return function wrap(arr){return callback.apply(null,arr)}}},7675:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(4867);module.exports=function toFormData(obj,formData){formData=formData||new FormData;var stack=[];function convertValue(value){return null===value?"":utils.isDate(value)?value.toISOString():utils.isArrayBuffer(value)||utils.isTypedArray(value)?"function"==typeof Blob?new Blob([value]):Buffer.from(value):value}return function build(data,parentKey){if(utils.isPlainObject(data)||utils.isArray(data)){if(-1!==stack.indexOf(data))throw Error("Circular reference detected in "+parentKey);stack.push(data),utils.forEach(data,(function each(value,key){if(!utils.isUndefined(value)){var arr,fullKey=parentKey?parentKey+"."+key:key;if(value&&!parentKey&&"object"==typeof value)if(utils.endsWith(key,"{}"))value=JSON.stringify(value);else if(utils.endsWith(key,"[]")&&(arr=utils.toArray(value)))return void arr.forEach((function(el){!utils.isUndefined(el)&&formData.append(fullKey,convertValue(el))}));build(value,fullKey)}})),stack.pop()}else formData.append(parentKey,convertValue(data))}(obj),formData}},4875:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var VERSION=__webpack_require__(7288).version,AxiosError=__webpack_require__(2648),validators={};["object","boolean","number","function","string","symbol"].forEach((function(type,i){validators[type]=function validator(thing){return typeof thing===type||"a"+(i<1?"n ":" ")+type}}));var deprecatedWarnings={};validators.transitional=function transitional(validator,version,message){function formatMessage(opt,desc){return"[Axios v"+VERSION+"] Transitional option '"+opt+"'"+desc+(message?". "+message:"")}return function(value,opt,opts){if(!1===validator)throw new AxiosError(formatMessage(opt," has been removed"+(version?" in "+version:"")),AxiosError.ERR_DEPRECATED);return version&&!deprecatedWarnings[opt]&&(deprecatedWarnings[opt]=!0,console.warn(formatMessage(opt," has been deprecated since v"+version+" and will be removed in the near future"))),!validator||validator(value,opt,opts)}},module.exports={assertOptions:function assertOptions(options,schema,allowUnknown){if("object"!=typeof options)throw new AxiosError("options must be an object",AxiosError.ERR_BAD_OPTION_VALUE);for(var keys=Object.keys(options),i=keys.length;i-- >0;){var opt=keys[i],validator=schema[opt];if(validator){var value=options[opt],result=void 0===value||validator(value,opt,options);if(!0!==result)throw new AxiosError("option "+opt+" must be "+result,AxiosError.ERR_BAD_OPTION_VALUE)}else if(!0!==allowUnknown)throw new AxiosError("Unknown option "+opt,AxiosError.ERR_BAD_OPTION)}},validators}},4867:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var cache,bind=__webpack_require__(1849),toString=Object.prototype.toString,kindOf=(cache=Object.create(null),function(thing){var str=toString.call(thing);return cache[str]||(cache[str]=str.slice(8,-1).toLowerCase())});function kindOfTest(type){return type=type.toLowerCase(),function isKindOf(thing){return kindOf(thing)===type}}function isArray(val){return Array.isArray(val)}function isUndefined(val){return void 0===val}var isArrayBuffer=kindOfTest("ArrayBuffer");function isObject(val){return null!==val&&"object"==typeof val}function isPlainObject(val){if("object"!==kindOf(val))return!1;var prototype=Object.getPrototypeOf(val);return null===prototype||prototype===Object.prototype}var isDate=kindOfTest("Date"),isFile=kindOfTest("File"),isBlob=kindOfTest("Blob"),isFileList=kindOfTest("FileList");function isFunction(val){return"[object Function]"===toString.call(val)}var isURLSearchParams=kindOfTest("URLSearchParams");function forEach(obj,fn){if(null!=obj)if("object"!=typeof obj&&(obj=[obj]),isArray(obj))for(var i=0,l=obj.length;i0;)merged[prop=props[i]]||(destObj[prop]=sourceObj[prop],merged[prop]=!0);sourceObj=Object.getPrototypeOf(sourceObj)}while(sourceObj&&(!filter||filter(sourceObj,destObj))&&sourceObj!==Object.prototype);return destObj},kindOf,kindOfTest,endsWith:function endsWith(str,searchString,position){str=String(str),(void 0===position||position>str.length)&&(position=str.length),position-=searchString.length;var lastIndex=str.indexOf(searchString,position);return-1!==lastIndex&&lastIndex===position},toArray:function toArray(thing){if(!thing)return null;var i=thing.length;if(isUndefined(i))return null;for(var arr=new Array(i);i-- >0;)arr[i]=thing[i];return arr},isTypedArray,isFileList}},8162:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var _Buffer=__webpack_require__(9509).Buffer;module.exports=function base(ALPHABET){if(ALPHABET.length>=255)throw new TypeError("Alphabet too long");for(var BASE_MAP=new Uint8Array(256),j=0;j>>0,b256=new Uint8Array(size);source[psz];){var carry=BASE_MAP[source.charCodeAt(psz)];if(255===carry)return;for(var i=0,it3=size-1;(0!==carry||i>>0,b256[it3]=carry%256>>>0,carry=carry/256>>>0;if(0!==carry)throw new Error("Non-zero carry");length=i,psz++}for(var it4=size-length;it4!==size&&0===b256[it4];)it4++;var vch=_Buffer.allocUnsafe(zeroes+(size-it4));vch.fill(0,0,zeroes);for(var j=zeroes;it4!==size;)vch[j++]=b256[it4++];return vch}return{encode:function encode(source){if((Array.isArray(source)||source instanceof Uint8Array)&&(source=_Buffer.from(source)),!_Buffer.isBuffer(source))throw new TypeError("Expected Buffer");if(0===source.length)return"";for(var zeroes=0,length=0,pbegin=0,pend=source.length;pbegin!==pend&&0===source[pbegin];)pbegin++,zeroes++;for(var size=(pend-pbegin)*iFACTOR+1>>>0,b58=new Uint8Array(size);pbegin!==pend;){for(var carry=source[pbegin],i=0,it1=size-1;(0!==carry||i>>0,b58[it1]=carry%BASE>>>0,carry=carry/BASE>>>0;if(0!==carry)throw new Error("Non-zero carry");length=i,pbegin++}for(var it2=size-length;it2!==size&&0===b58[it2];)it2++;for(var str=LEADER.repeat(zeroes);it2{"use strict";exports.byteLength=function byteLength(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1];return 3*(validLen+placeHoldersLen)/4-placeHoldersLen},exports.toByteArray=function toByteArray(b64){var tmp,i,lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1],arr=new Arr(function _byteLength(b64,validLen,placeHoldersLen){return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}(0,validLen,placeHoldersLen)),curByte=0,len=placeHoldersLen>0?validLen-4:validLen;for(i=0;i>16&255,arr[curByte++]=tmp>>8&255,arr[curByte++]=255&tmp;2===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[curByte++]=255&tmp);1===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[curByte++]=tmp>>8&255,arr[curByte++]=255&tmp);return arr},exports.fromByteArray=function fromByteArray(uint8){for(var tmp,len=uint8.length,extraBytes=len%3,parts=[],i=0,len2=len-extraBytes;ilen2?len2:i+16383));1===extraBytes?(tmp=uint8[len-1],parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"="));return parts.join("")};for(var lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i0)throw new Error("Invalid string. Length must be a multiple of 4");var validLen=b64.indexOf("=");return-1===validLen&&(validLen=len),[validLen,validLen===len?0:4-validLen%4]}function encodeChunk(uint8,start,end){for(var tmp,num,output=[],i=start;i>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[63&num]);return output.join("")}revLookup["-".charCodeAt(0)]=62,revLookup["_".charCodeAt(0)]=63},7715:(__unused_webpack_module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.bech32m=exports.bech32=void 0;const ALPHABET="qpzry9x8gf2tvdw0s3jn54khce6mua7l",ALPHABET_MAP={};for(let z=0;z>25;return(33554431&pre)<<5^996825010&-(b>>0&1)^642813549&-(b>>1&1)^513874426&-(b>>2&1)^1027748829&-(b>>3&1)^705979059&-(b>>4&1)}function prefixChk(prefix){let chk=1;for(let i=0;i126)return"Invalid prefix ("+prefix+")";chk=polymodStep(chk)^c>>5}chk=polymodStep(chk);for(let i=0;i=outBits;)bits-=outBits,result.push(value>>bits&maxV);if(pad)bits>0&&result.push(value<=inBits)return"Excess padding";if(value<LIMIT)return"Exceeds length limit";const lowered=str.toLowerCase(),uppered=str.toUpperCase();if(str!==lowered&&str!==uppered)return"Mixed-case string "+str;const split=(str=lowered).lastIndexOf("1");if(-1===split)return"No separator character for "+str;if(0===split)return"Missing prefix for "+str;const prefix=str.slice(0,split),wordChars=str.slice(split+1);if(wordChars.length<6)return"Data too short";let chk=prefixChk(prefix);if("string"==typeof chk)return chk;const words=[];for(let i=0;i=wordChars.length||words.push(v)}return chk!==ENCODING_CONST?"Invalid checksum for "+str:{prefix,words}}return ENCODING_CONST="bech32"===encoding?1:734539939,{decodeUnsafe:function decodeUnsafe(str,LIMIT){const res=__decode(str,LIMIT);if("object"==typeof res)return res},decode:function decode(str,LIMIT){const res=__decode(str,LIMIT);if("object"==typeof res)return res;throw new Error(res)},encode:function encode(prefix,words,LIMIT){if(LIMIT=LIMIT||90,prefix.length+7+words.length>LIMIT)throw new TypeError("Exceeds length limit");let chk=prefixChk(prefix=prefix.toLowerCase());if("string"==typeof chk)throw new Error(chk);let result=prefix+"1";for(let i=0;i>5!=0)throw new Error("Non 5-bit word");chk=polymodStep(chk)^x,result+=ALPHABET.charAt(x)}for(let i=0;i<6;++i)chk=polymodStep(chk);chk^=ENCODING_CONST;for(let i=0;i<6;++i){result+=ALPHABET.charAt(chk>>5*(5-i)&31)}return result},toWords,fromWordsUnsafe,fromWords}}exports.bech32=getLibraryFromEncoding("bech32"),exports.bech32m=getLibraryFromEncoding("bech32m")},2314:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const wordlists={};let _default;exports.wordlists=wordlists,exports._default=_default;try{exports._default=_default=__webpack_require__(32),wordlists.czech=_default}catch(err){}try{exports._default=_default=__webpack_require__(6996),wordlists.chinese_simplified=_default}catch(err){}try{exports._default=_default=__webpack_require__(4262),wordlists.chinese_traditional=_default}catch(err){}try{exports._default=_default=__webpack_require__(8013),wordlists.korean=_default}catch(err){}try{exports._default=_default=__webpack_require__(1848),wordlists.french=_default}catch(err){}try{exports._default=_default=__webpack_require__(2841),wordlists.italian=_default}catch(err){}try{exports._default=_default=__webpack_require__(659),wordlists.spanish=_default}catch(err){}try{exports._default=_default=__webpack_require__(4472),wordlists.japanese=_default,wordlists.JA=_default}catch(err){}try{exports._default=_default=__webpack_require__(1945),wordlists.portuguese=_default}catch(err){}try{exports._default=_default=__webpack_require__(4573),wordlists.english=_default,wordlists.EN=_default}catch(err){}},2153:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const createHash=__webpack_require__(3482),pbkdf2_1=__webpack_require__(5632),randomBytes=__webpack_require__(1798),_wordlists_1=__webpack_require__(2314);let DEFAULT_WORDLIST=_wordlists_1._default;const WORDLIST_REQUIRED="A wordlist is required but a default could not be found.\nPlease pass a 2048 word array explicitly.";function normalize(str){return(str||"").normalize("NFKD")}function lpad(str,padString,length){for(;str.lengthlpad(x.toString(2),"0",8))).join("")}function deriveChecksumBits(entropyBuffer){const CS=8*entropyBuffer.length/32,hash=createHash("sha256").update(entropyBuffer).digest();return bytesToBinary(Array.from(hash)).slice(0,CS)}function salt(password){return"mnemonic"+(password||"")}function mnemonicToEntropy(mnemonic,wordlist){if(!(wordlist=wordlist||DEFAULT_WORDLIST))throw new Error(WORDLIST_REQUIRED);const words=normalize(mnemonic).split(" ");if(words.length%3!=0)throw new Error("Invalid mnemonic");const bits=words.map((word=>{const index=wordlist.indexOf(word);if(-1===index)throw new Error("Invalid mnemonic");return lpad(index.toString(2),"0",11)})).join(""),dividerIndex=32*Math.floor(bits.length/33),entropyBits=bits.slice(0,dividerIndex),checksumBits=bits.slice(dividerIndex),entropyBytes=entropyBits.match(/(.{1,8})/g).map(binaryToByte);if(entropyBytes.length<16)throw new Error("Invalid entropy");if(entropyBytes.length>32)throw new Error("Invalid entropy");if(entropyBytes.length%4!=0)throw new Error("Invalid entropy");const entropy=Buffer.from(entropyBytes);if(deriveChecksumBits(entropy)!==checksumBits)throw new Error("Invalid mnemonic checksum");return entropy.toString("hex")}function entropyToMnemonic(entropy,wordlist){if(Buffer.isBuffer(entropy)||(entropy=Buffer.from(entropy,"hex")),!(wordlist=wordlist||DEFAULT_WORDLIST))throw new Error(WORDLIST_REQUIRED);if(entropy.length<16)throw new TypeError("Invalid entropy");if(entropy.length>32)throw new TypeError("Invalid entropy");if(entropy.length%4!=0)throw new TypeError("Invalid entropy");const words=(bytesToBinary(Array.from(entropy))+deriveChecksumBits(entropy)).match(/(.{1,11})/g).map((binary=>{const index=binaryToByte(binary);return wordlist[index]}));return"あいこくしん"===wordlist[0]?words.join(" "):words.join(" ")}exports.mnemonicToSeedSync=function mnemonicToSeedSync(mnemonic,password){const mnemonicBuffer=Buffer.from(normalize(mnemonic),"utf8"),saltBuffer=Buffer.from(salt(normalize(password)),"utf8");return pbkdf2_1.pbkdf2Sync(mnemonicBuffer,saltBuffer,2048,64,"sha512")},exports.mnemonicToSeed=function mnemonicToSeed(mnemonic,password){return Promise.resolve().then((()=>function pbkdf2Promise(password,saltMixin,iterations,keylen,digest){return Promise.resolve().then((()=>new Promise(((resolve,reject)=>{pbkdf2_1.pbkdf2(password,saltMixin,iterations,keylen,digest,((err,derivedKey)=>err?reject(err):resolve(derivedKey)))}))))}(Buffer.from(normalize(mnemonic),"utf8"),Buffer.from(salt(normalize(password)),"utf8"),2048,64,"sha512")))},exports.mnemonicToEntropy=mnemonicToEntropy,exports.entropyToMnemonic=entropyToMnemonic,exports.generateMnemonic=function generateMnemonic(strength,rng,wordlist){if((strength=strength||128)%32!=0)throw new TypeError("Invalid entropy");return entropyToMnemonic((rng=rng||randomBytes)(strength/8),wordlist)},exports.validateMnemonic=function validateMnemonic(mnemonic,wordlist){try{mnemonicToEntropy(mnemonic,wordlist)}catch(e){return!1}return!0},exports.setDefaultWordlist=function setDefaultWordlist(language){const result=_wordlists_1.wordlists[language];if(!result)throw new Error('Could not find wordlist for language "'+language+'"');DEFAULT_WORDLIST=result},exports.getDefaultWordlist=function getDefaultWordlist(){if(!DEFAULT_WORDLIST)throw new Error("No Default Wordlist set");return Object.keys(_wordlists_1.wordlists).filter((lang=>"JA"!==lang&&"EN"!==lang&&_wordlists_1.wordlists[lang].every(((word,index)=>word===DEFAULT_WORDLIST[index]))))[0]};var _wordlists_2=__webpack_require__(2314);exports.wordlists=_wordlists_2.wordlists},3550:function(module,__unused_webpack_exports,__webpack_require__){!function(module,exports){"use strict";function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}function BN(number,base,endian){if(BN.isBN(number))return number;this.negative=0,this.words=null,this.length=0,this.red=null,null!==number&&("le"!==base&&"be"!==base||(endian=base,base=10),this._init(number||0,base||10,endian||"be"))}var Buffer;"object"==typeof module?module.exports=BN:exports.BN=BN,BN.BN=BN,BN.wordSize=26;try{Buffer="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:__webpack_require__(6601).Buffer}catch(e){}function parseHex4Bits(string,index){var c=string.charCodeAt(index);return c>=48&&c<=57?c-48:c>=65&&c<=70?c-55:c>=97&&c<=102?c-87:void assert(!1,"Invalid character in "+string)}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return index-1>=lowerBound&&(r|=parseHex4Bits(string,index-1)<<4),r}function parseBase(str,start,end,mul){for(var r=0,b=0,len=Math.min(str.length,end),i=start;i=49?c-49+10:c>=17?c-17+10:c,assert(c>=0&&b0?left:right},BN.min=function min(left,right){return left.cmp(right)<0?left:right},BN.prototype._init=function init(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&base>=2&&base<=36);var start=0;"-"===(number=number.toString().replace(/\s+/g,""))[0]&&(start++,this.negative=1),start=0;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=w<>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);return this._strip()},BN.prototype._parseHex=function _parseHex(number,start,endian){this.length=Math.ceil((number.length-start)/6),this.words=new Array(this.length);for(var i=0;i=start;i-=2)w=parseHexByte(number,start,i)<=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;else for(i=(number.length-start)%2==0?start+1:start;i=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;this._strip()},BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;limbPow*=base)limbLen++;limbLen--,limbPow=limbPow/base|0;for(var total=number.length-start,mod=total%limbLen,end=Math.min(total,total-mod)+start,word=0,i=start;i1&&0===this.words[this.length-1];)this.length--;return this._normSign()},BN.prototype._normSign=function _normSign(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{BN.prototype[Symbol.for("nodejs.util.inspect.custom")]=inspect}catch(e){BN.prototype.inspect=inspect}else BN.prototype.inspect=inspect;function inspect(){return(this.red?""}var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function toString(base,padding){var out;if(padding=0|padding||1,16===(base=base||10)||"hex"===base){out="";for(var off=0,carry=0,i=0;i>>24-off&16777215,(off+=2)>=26&&(off-=26,i--),out=0!==carry||i!==this.length-1?zeros[6-word.length]+word+out:word+out}for(0!==carry&&(out=carry.toString(16)+out);out.length%padding!=0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&base>=2&&base<=36){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modrn(groupBase).toString(base);out=(c=c.idivn(groupBase)).isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);out.length%padding!=0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function toNumber(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:this.length>2&&assert(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-ret:ret},BN.prototype.toJSON=function toJSON(){return this.toString(16,2)},Buffer&&(BN.prototype.toBuffer=function toBuffer(endian,length){return this.toArrayLike(Buffer,endian,length)}),BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)};function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=self.length+num.length|0;out.length=len,len=len-1|0;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=r/67108864|0;out.words[0]=lo;for(var k=1;k>>26,rword=67108863&carry,maxJ=Math.min(k,num.length-1),j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j|0;ncarry+=(r=(a=0|self.words[i])*(b=0|num.words[j])+rword)/67108864|0,rword=67108863&r}out.words[k]=0|rword,carry=0|ncarry}return 0!==carry?out.words[k]=0|carry:out.length--,out._strip()}BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){this._strip();var byteLength=this.byteLength(),reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length"),assert(reqLength>0,"Requested array length <= 0");var res=function allocate(ArrayType,size){return ArrayType.allocUnsafe?ArrayType.allocUnsafe(size):new ArrayType(size)}(ArrayType,reqLength);return this["_toArrayLike"+("le"===endian?"LE":"BE")](res,byteLength),res},BN.prototype._toArrayLikeLE=function _toArrayLikeLE(res,byteLength){for(var position=0,carry=0,i=0,shift=0;i>8&255),position>16&255),6===shift?(position>24&255),carry=0,shift=0):(carry=word>>>24,shift+=2)}if(position=0&&(res[position--]=word>>8&255),position>=0&&(res[position--]=word>>16&255),6===shift?(position>=0&&(res[position--]=word>>24&255),carry=0,shift=0):(carry=word>>>24,shift+=2)}if(position>=0)for(res[position--]=carry;position>=0;)res[position--]=0},Math.clz32?BN.prototype._countBits=function _countBits(w){return 32-Math.clz32(w)}:BN.prototype._countBits=function _countBits(w){var t=w,r=0;return t>=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function _zeroBits(w){if(0===w)return 26;var t=w,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;for(var r=0,i=0;inum.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function uor(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function iuand(num){var b;b=this.length>num.length?num:this;for(var i=0;inum.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function uand(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function iuxor(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;inum.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function uxor(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function inotn(width){assert("number"==typeof width&&width>=0);var bytesNeeded=0|Math.ceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),bitsLeft>0&&bytesNeeded--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this._strip()},BN.prototype.notn=function notn(width){return this.clone().inotn(width)},BN.prototype.setn=function setn(bit,val){assert("number"==typeof bit&&bit>=0);var off=bit/26|0,wbit=bit%26;return this._expand(off+1),this.words[off]=val?this.words[off]|1<num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>>26;for(;0!==carry&&i>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;inum.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function isub(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var a,b,cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;cmp>0?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>26,this.words[i]=67108863&r;for(;0!==carry&&i>26,this.words[i]=67108863&r;if(0===carry&&i>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13;out.negative=self.negative^num.negative,out.length=19;var w0=(c+(lo=Math.imul(al0,bl0))|0)+((8191&(mid=(mid=Math.imul(al0,bh0))+Math.imul(ah0,bl0)|0))<<13)|0;c=((hi=Math.imul(ah0,bh0))+(mid>>>13)|0)+(w0>>>26)|0,w0&=67108863,lo=Math.imul(al1,bl0),mid=(mid=Math.imul(al1,bh0))+Math.imul(ah1,bl0)|0,hi=Math.imul(ah1,bh0);var w1=(c+(lo=lo+Math.imul(al0,bl1)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh1)|0)+Math.imul(ah0,bl1)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh1)|0)+(mid>>>13)|0)+(w1>>>26)|0,w1&=67108863,lo=Math.imul(al2,bl0),mid=(mid=Math.imul(al2,bh0))+Math.imul(ah2,bl0)|0,hi=Math.imul(ah2,bh0),lo=lo+Math.imul(al1,bl1)|0,mid=(mid=mid+Math.imul(al1,bh1)|0)+Math.imul(ah1,bl1)|0,hi=hi+Math.imul(ah1,bh1)|0;var w2=(c+(lo=lo+Math.imul(al0,bl2)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh2)|0)+Math.imul(ah0,bl2)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh2)|0)+(mid>>>13)|0)+(w2>>>26)|0,w2&=67108863,lo=Math.imul(al3,bl0),mid=(mid=Math.imul(al3,bh0))+Math.imul(ah3,bl0)|0,hi=Math.imul(ah3,bh0),lo=lo+Math.imul(al2,bl1)|0,mid=(mid=mid+Math.imul(al2,bh1)|0)+Math.imul(ah2,bl1)|0,hi=hi+Math.imul(ah2,bh1)|0,lo=lo+Math.imul(al1,bl2)|0,mid=(mid=mid+Math.imul(al1,bh2)|0)+Math.imul(ah1,bl2)|0,hi=hi+Math.imul(ah1,bh2)|0;var w3=(c+(lo=lo+Math.imul(al0,bl3)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh3)|0)+Math.imul(ah0,bl3)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh3)|0)+(mid>>>13)|0)+(w3>>>26)|0,w3&=67108863,lo=Math.imul(al4,bl0),mid=(mid=Math.imul(al4,bh0))+Math.imul(ah4,bl0)|0,hi=Math.imul(ah4,bh0),lo=lo+Math.imul(al3,bl1)|0,mid=(mid=mid+Math.imul(al3,bh1)|0)+Math.imul(ah3,bl1)|0,hi=hi+Math.imul(ah3,bh1)|0,lo=lo+Math.imul(al2,bl2)|0,mid=(mid=mid+Math.imul(al2,bh2)|0)+Math.imul(ah2,bl2)|0,hi=hi+Math.imul(ah2,bh2)|0,lo=lo+Math.imul(al1,bl3)|0,mid=(mid=mid+Math.imul(al1,bh3)|0)+Math.imul(ah1,bl3)|0,hi=hi+Math.imul(ah1,bh3)|0;var w4=(c+(lo=lo+Math.imul(al0,bl4)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh4)|0)+Math.imul(ah0,bl4)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh4)|0)+(mid>>>13)|0)+(w4>>>26)|0,w4&=67108863,lo=Math.imul(al5,bl0),mid=(mid=Math.imul(al5,bh0))+Math.imul(ah5,bl0)|0,hi=Math.imul(ah5,bh0),lo=lo+Math.imul(al4,bl1)|0,mid=(mid=mid+Math.imul(al4,bh1)|0)+Math.imul(ah4,bl1)|0,hi=hi+Math.imul(ah4,bh1)|0,lo=lo+Math.imul(al3,bl2)|0,mid=(mid=mid+Math.imul(al3,bh2)|0)+Math.imul(ah3,bl2)|0,hi=hi+Math.imul(ah3,bh2)|0,lo=lo+Math.imul(al2,bl3)|0,mid=(mid=mid+Math.imul(al2,bh3)|0)+Math.imul(ah2,bl3)|0,hi=hi+Math.imul(ah2,bh3)|0,lo=lo+Math.imul(al1,bl4)|0,mid=(mid=mid+Math.imul(al1,bh4)|0)+Math.imul(ah1,bl4)|0,hi=hi+Math.imul(ah1,bh4)|0;var w5=(c+(lo=lo+Math.imul(al0,bl5)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh5)|0)+Math.imul(ah0,bl5)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh5)|0)+(mid>>>13)|0)+(w5>>>26)|0,w5&=67108863,lo=Math.imul(al6,bl0),mid=(mid=Math.imul(al6,bh0))+Math.imul(ah6,bl0)|0,hi=Math.imul(ah6,bh0),lo=lo+Math.imul(al5,bl1)|0,mid=(mid=mid+Math.imul(al5,bh1)|0)+Math.imul(ah5,bl1)|0,hi=hi+Math.imul(ah5,bh1)|0,lo=lo+Math.imul(al4,bl2)|0,mid=(mid=mid+Math.imul(al4,bh2)|0)+Math.imul(ah4,bl2)|0,hi=hi+Math.imul(ah4,bh2)|0,lo=lo+Math.imul(al3,bl3)|0,mid=(mid=mid+Math.imul(al3,bh3)|0)+Math.imul(ah3,bl3)|0,hi=hi+Math.imul(ah3,bh3)|0,lo=lo+Math.imul(al2,bl4)|0,mid=(mid=mid+Math.imul(al2,bh4)|0)+Math.imul(ah2,bl4)|0,hi=hi+Math.imul(ah2,bh4)|0,lo=lo+Math.imul(al1,bl5)|0,mid=(mid=mid+Math.imul(al1,bh5)|0)+Math.imul(ah1,bl5)|0,hi=hi+Math.imul(ah1,bh5)|0;var w6=(c+(lo=lo+Math.imul(al0,bl6)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh6)|0)+Math.imul(ah0,bl6)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh6)|0)+(mid>>>13)|0)+(w6>>>26)|0,w6&=67108863,lo=Math.imul(al7,bl0),mid=(mid=Math.imul(al7,bh0))+Math.imul(ah7,bl0)|0,hi=Math.imul(ah7,bh0),lo=lo+Math.imul(al6,bl1)|0,mid=(mid=mid+Math.imul(al6,bh1)|0)+Math.imul(ah6,bl1)|0,hi=hi+Math.imul(ah6,bh1)|0,lo=lo+Math.imul(al5,bl2)|0,mid=(mid=mid+Math.imul(al5,bh2)|0)+Math.imul(ah5,bl2)|0,hi=hi+Math.imul(ah5,bh2)|0,lo=lo+Math.imul(al4,bl3)|0,mid=(mid=mid+Math.imul(al4,bh3)|0)+Math.imul(ah4,bl3)|0,hi=hi+Math.imul(ah4,bh3)|0,lo=lo+Math.imul(al3,bl4)|0,mid=(mid=mid+Math.imul(al3,bh4)|0)+Math.imul(ah3,bl4)|0,hi=hi+Math.imul(ah3,bh4)|0,lo=lo+Math.imul(al2,bl5)|0,mid=(mid=mid+Math.imul(al2,bh5)|0)+Math.imul(ah2,bl5)|0,hi=hi+Math.imul(ah2,bh5)|0,lo=lo+Math.imul(al1,bl6)|0,mid=(mid=mid+Math.imul(al1,bh6)|0)+Math.imul(ah1,bl6)|0,hi=hi+Math.imul(ah1,bh6)|0;var w7=(c+(lo=lo+Math.imul(al0,bl7)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh7)|0)+Math.imul(ah0,bl7)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh7)|0)+(mid>>>13)|0)+(w7>>>26)|0,w7&=67108863,lo=Math.imul(al8,bl0),mid=(mid=Math.imul(al8,bh0))+Math.imul(ah8,bl0)|0,hi=Math.imul(ah8,bh0),lo=lo+Math.imul(al7,bl1)|0,mid=(mid=mid+Math.imul(al7,bh1)|0)+Math.imul(ah7,bl1)|0,hi=hi+Math.imul(ah7,bh1)|0,lo=lo+Math.imul(al6,bl2)|0,mid=(mid=mid+Math.imul(al6,bh2)|0)+Math.imul(ah6,bl2)|0,hi=hi+Math.imul(ah6,bh2)|0,lo=lo+Math.imul(al5,bl3)|0,mid=(mid=mid+Math.imul(al5,bh3)|0)+Math.imul(ah5,bl3)|0,hi=hi+Math.imul(ah5,bh3)|0,lo=lo+Math.imul(al4,bl4)|0,mid=(mid=mid+Math.imul(al4,bh4)|0)+Math.imul(ah4,bl4)|0,hi=hi+Math.imul(ah4,bh4)|0,lo=lo+Math.imul(al3,bl5)|0,mid=(mid=mid+Math.imul(al3,bh5)|0)+Math.imul(ah3,bl5)|0,hi=hi+Math.imul(ah3,bh5)|0,lo=lo+Math.imul(al2,bl6)|0,mid=(mid=mid+Math.imul(al2,bh6)|0)+Math.imul(ah2,bl6)|0,hi=hi+Math.imul(ah2,bh6)|0,lo=lo+Math.imul(al1,bl7)|0,mid=(mid=mid+Math.imul(al1,bh7)|0)+Math.imul(ah1,bl7)|0,hi=hi+Math.imul(ah1,bh7)|0;var w8=(c+(lo=lo+Math.imul(al0,bl8)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh8)|0)+Math.imul(ah0,bl8)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh8)|0)+(mid>>>13)|0)+(w8>>>26)|0,w8&=67108863,lo=Math.imul(al9,bl0),mid=(mid=Math.imul(al9,bh0))+Math.imul(ah9,bl0)|0,hi=Math.imul(ah9,bh0),lo=lo+Math.imul(al8,bl1)|0,mid=(mid=mid+Math.imul(al8,bh1)|0)+Math.imul(ah8,bl1)|0,hi=hi+Math.imul(ah8,bh1)|0,lo=lo+Math.imul(al7,bl2)|0,mid=(mid=mid+Math.imul(al7,bh2)|0)+Math.imul(ah7,bl2)|0,hi=hi+Math.imul(ah7,bh2)|0,lo=lo+Math.imul(al6,bl3)|0,mid=(mid=mid+Math.imul(al6,bh3)|0)+Math.imul(ah6,bl3)|0,hi=hi+Math.imul(ah6,bh3)|0,lo=lo+Math.imul(al5,bl4)|0,mid=(mid=mid+Math.imul(al5,bh4)|0)+Math.imul(ah5,bl4)|0,hi=hi+Math.imul(ah5,bh4)|0,lo=lo+Math.imul(al4,bl5)|0,mid=(mid=mid+Math.imul(al4,bh5)|0)+Math.imul(ah4,bl5)|0,hi=hi+Math.imul(ah4,bh5)|0,lo=lo+Math.imul(al3,bl6)|0,mid=(mid=mid+Math.imul(al3,bh6)|0)+Math.imul(ah3,bl6)|0,hi=hi+Math.imul(ah3,bh6)|0,lo=lo+Math.imul(al2,bl7)|0,mid=(mid=mid+Math.imul(al2,bh7)|0)+Math.imul(ah2,bl7)|0,hi=hi+Math.imul(ah2,bh7)|0,lo=lo+Math.imul(al1,bl8)|0,mid=(mid=mid+Math.imul(al1,bh8)|0)+Math.imul(ah1,bl8)|0,hi=hi+Math.imul(ah1,bh8)|0;var w9=(c+(lo=lo+Math.imul(al0,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh9)|0)+Math.imul(ah0,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh9)|0)+(mid>>>13)|0)+(w9>>>26)|0,w9&=67108863,lo=Math.imul(al9,bl1),mid=(mid=Math.imul(al9,bh1))+Math.imul(ah9,bl1)|0,hi=Math.imul(ah9,bh1),lo=lo+Math.imul(al8,bl2)|0,mid=(mid=mid+Math.imul(al8,bh2)|0)+Math.imul(ah8,bl2)|0,hi=hi+Math.imul(ah8,bh2)|0,lo=lo+Math.imul(al7,bl3)|0,mid=(mid=mid+Math.imul(al7,bh3)|0)+Math.imul(ah7,bl3)|0,hi=hi+Math.imul(ah7,bh3)|0,lo=lo+Math.imul(al6,bl4)|0,mid=(mid=mid+Math.imul(al6,bh4)|0)+Math.imul(ah6,bl4)|0,hi=hi+Math.imul(ah6,bh4)|0,lo=lo+Math.imul(al5,bl5)|0,mid=(mid=mid+Math.imul(al5,bh5)|0)+Math.imul(ah5,bl5)|0,hi=hi+Math.imul(ah5,bh5)|0,lo=lo+Math.imul(al4,bl6)|0,mid=(mid=mid+Math.imul(al4,bh6)|0)+Math.imul(ah4,bl6)|0,hi=hi+Math.imul(ah4,bh6)|0,lo=lo+Math.imul(al3,bl7)|0,mid=(mid=mid+Math.imul(al3,bh7)|0)+Math.imul(ah3,bl7)|0,hi=hi+Math.imul(ah3,bh7)|0,lo=lo+Math.imul(al2,bl8)|0,mid=(mid=mid+Math.imul(al2,bh8)|0)+Math.imul(ah2,bl8)|0,hi=hi+Math.imul(ah2,bh8)|0;var w10=(c+(lo=lo+Math.imul(al1,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al1,bh9)|0)+Math.imul(ah1,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah1,bh9)|0)+(mid>>>13)|0)+(w10>>>26)|0,w10&=67108863,lo=Math.imul(al9,bl2),mid=(mid=Math.imul(al9,bh2))+Math.imul(ah9,bl2)|0,hi=Math.imul(ah9,bh2),lo=lo+Math.imul(al8,bl3)|0,mid=(mid=mid+Math.imul(al8,bh3)|0)+Math.imul(ah8,bl3)|0,hi=hi+Math.imul(ah8,bh3)|0,lo=lo+Math.imul(al7,bl4)|0,mid=(mid=mid+Math.imul(al7,bh4)|0)+Math.imul(ah7,bl4)|0,hi=hi+Math.imul(ah7,bh4)|0,lo=lo+Math.imul(al6,bl5)|0,mid=(mid=mid+Math.imul(al6,bh5)|0)+Math.imul(ah6,bl5)|0,hi=hi+Math.imul(ah6,bh5)|0,lo=lo+Math.imul(al5,bl6)|0,mid=(mid=mid+Math.imul(al5,bh6)|0)+Math.imul(ah5,bl6)|0,hi=hi+Math.imul(ah5,bh6)|0,lo=lo+Math.imul(al4,bl7)|0,mid=(mid=mid+Math.imul(al4,bh7)|0)+Math.imul(ah4,bl7)|0,hi=hi+Math.imul(ah4,bh7)|0,lo=lo+Math.imul(al3,bl8)|0,mid=(mid=mid+Math.imul(al3,bh8)|0)+Math.imul(ah3,bl8)|0,hi=hi+Math.imul(ah3,bh8)|0;var w11=(c+(lo=lo+Math.imul(al2,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al2,bh9)|0)+Math.imul(ah2,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah2,bh9)|0)+(mid>>>13)|0)+(w11>>>26)|0,w11&=67108863,lo=Math.imul(al9,bl3),mid=(mid=Math.imul(al9,bh3))+Math.imul(ah9,bl3)|0,hi=Math.imul(ah9,bh3),lo=lo+Math.imul(al8,bl4)|0,mid=(mid=mid+Math.imul(al8,bh4)|0)+Math.imul(ah8,bl4)|0,hi=hi+Math.imul(ah8,bh4)|0,lo=lo+Math.imul(al7,bl5)|0,mid=(mid=mid+Math.imul(al7,bh5)|0)+Math.imul(ah7,bl5)|0,hi=hi+Math.imul(ah7,bh5)|0,lo=lo+Math.imul(al6,bl6)|0,mid=(mid=mid+Math.imul(al6,bh6)|0)+Math.imul(ah6,bl6)|0,hi=hi+Math.imul(ah6,bh6)|0,lo=lo+Math.imul(al5,bl7)|0,mid=(mid=mid+Math.imul(al5,bh7)|0)+Math.imul(ah5,bl7)|0,hi=hi+Math.imul(ah5,bh7)|0,lo=lo+Math.imul(al4,bl8)|0,mid=(mid=mid+Math.imul(al4,bh8)|0)+Math.imul(ah4,bl8)|0,hi=hi+Math.imul(ah4,bh8)|0;var w12=(c+(lo=lo+Math.imul(al3,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al3,bh9)|0)+Math.imul(ah3,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah3,bh9)|0)+(mid>>>13)|0)+(w12>>>26)|0,w12&=67108863,lo=Math.imul(al9,bl4),mid=(mid=Math.imul(al9,bh4))+Math.imul(ah9,bl4)|0,hi=Math.imul(ah9,bh4),lo=lo+Math.imul(al8,bl5)|0,mid=(mid=mid+Math.imul(al8,bh5)|0)+Math.imul(ah8,bl5)|0,hi=hi+Math.imul(ah8,bh5)|0,lo=lo+Math.imul(al7,bl6)|0,mid=(mid=mid+Math.imul(al7,bh6)|0)+Math.imul(ah7,bl6)|0,hi=hi+Math.imul(ah7,bh6)|0,lo=lo+Math.imul(al6,bl7)|0,mid=(mid=mid+Math.imul(al6,bh7)|0)+Math.imul(ah6,bl7)|0,hi=hi+Math.imul(ah6,bh7)|0,lo=lo+Math.imul(al5,bl8)|0,mid=(mid=mid+Math.imul(al5,bh8)|0)+Math.imul(ah5,bl8)|0,hi=hi+Math.imul(ah5,bh8)|0;var w13=(c+(lo=lo+Math.imul(al4,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al4,bh9)|0)+Math.imul(ah4,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah4,bh9)|0)+(mid>>>13)|0)+(w13>>>26)|0,w13&=67108863,lo=Math.imul(al9,bl5),mid=(mid=Math.imul(al9,bh5))+Math.imul(ah9,bl5)|0,hi=Math.imul(ah9,bh5),lo=lo+Math.imul(al8,bl6)|0,mid=(mid=mid+Math.imul(al8,bh6)|0)+Math.imul(ah8,bl6)|0,hi=hi+Math.imul(ah8,bh6)|0,lo=lo+Math.imul(al7,bl7)|0,mid=(mid=mid+Math.imul(al7,bh7)|0)+Math.imul(ah7,bl7)|0,hi=hi+Math.imul(ah7,bh7)|0,lo=lo+Math.imul(al6,bl8)|0,mid=(mid=mid+Math.imul(al6,bh8)|0)+Math.imul(ah6,bl8)|0,hi=hi+Math.imul(ah6,bh8)|0;var w14=(c+(lo=lo+Math.imul(al5,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al5,bh9)|0)+Math.imul(ah5,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah5,bh9)|0)+(mid>>>13)|0)+(w14>>>26)|0,w14&=67108863,lo=Math.imul(al9,bl6),mid=(mid=Math.imul(al9,bh6))+Math.imul(ah9,bl6)|0,hi=Math.imul(ah9,bh6),lo=lo+Math.imul(al8,bl7)|0,mid=(mid=mid+Math.imul(al8,bh7)|0)+Math.imul(ah8,bl7)|0,hi=hi+Math.imul(ah8,bh7)|0,lo=lo+Math.imul(al7,bl8)|0,mid=(mid=mid+Math.imul(al7,bh8)|0)+Math.imul(ah7,bl8)|0,hi=hi+Math.imul(ah7,bh8)|0;var w15=(c+(lo=lo+Math.imul(al6,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al6,bh9)|0)+Math.imul(ah6,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah6,bh9)|0)+(mid>>>13)|0)+(w15>>>26)|0,w15&=67108863,lo=Math.imul(al9,bl7),mid=(mid=Math.imul(al9,bh7))+Math.imul(ah9,bl7)|0,hi=Math.imul(ah9,bh7),lo=lo+Math.imul(al8,bl8)|0,mid=(mid=mid+Math.imul(al8,bh8)|0)+Math.imul(ah8,bl8)|0,hi=hi+Math.imul(ah8,bh8)|0;var w16=(c+(lo=lo+Math.imul(al7,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al7,bh9)|0)+Math.imul(ah7,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah7,bh9)|0)+(mid>>>13)|0)+(w16>>>26)|0,w16&=67108863,lo=Math.imul(al9,bl8),mid=(mid=Math.imul(al9,bh8))+Math.imul(ah9,bl8)|0,hi=Math.imul(ah9,bh8);var w17=(c+(lo=lo+Math.imul(al8,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al8,bh9)|0)+Math.imul(ah8,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah8,bh9)|0)+(mid>>>13)|0)+(w17>>>26)|0,w17&=67108863;var w18=(c+(lo=Math.imul(al9,bl9))|0)+((8191&(mid=(mid=Math.imul(al9,bh9))+Math.imul(ah9,bl9)|0))<<13)|0;return c=((hi=Math.imul(ah9,bh9))+(mid>>>13)|0)+(w18>>>26)|0,w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,0!==c&&(o[19]=c,out.length++),out};function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0;k>>26)|0)>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0!==carry?out.words[k]=carry:out.length--,out._strip()}function jumboMulTo(self,num,out){return bigMulTo(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}Math.imul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function mulTo(num,out){var len=this.length+num.length;return 10===this.length&&10===num.length?comb10MulTo(this,num,out):len<63?smallMulTo(this,num,out):len<1024?bigMulTo(this,num,out):jumboMulTo(this,num,out)},FFTM.prototype.makeRBT=function makeRBT(N){for(var t=new Array(N),l=BN.prototype._countBits(N)-1,i=0;i>=1;return rb},FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>=1)i++;return 1<>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;i>=26,carry+=w/67108864|0,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),isNegNum?this.ineg():this},BN.prototype.muln=function muln(num){return this.clone().imuln(num)},BN.prototype.sqr=function sqr(){return this.mul(this)},BN.prototype.isqr=function isqr(){return this.imul(this.clone())},BN.prototype.pow=function pow(num){var w=function toBitArray(num){for(var w=new Array(num.bitLength()),bit=0;bit>>wbit&1}return w}(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i=0);var i,r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r;if(0!==r){var carry=0;for(i=0;i>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;i>=0;i--)this.words[i+s]=this.words[i];for(i=0;i=0),h=hint?(hint-hint%26)/26:0;var r=bits%26,s=Math.min((bits-r)/26,this.length),mask=67108863^67108863>>>r<s)for(this.length-=s,i=0;i=0&&(0!==carry||i>=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&0!==carry&&(maskedWords.words[maskedWords.length++]=carry),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},BN.prototype.ishrn=function ishrn(bits,hint,extended){return assert(0===this.negative),this.iushrn(bits,hint,extended)},BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function testn(bit){assert("number"==typeof bit&&bit>=0);var r=bit%26,s=(bit-r)/26,q=1<=0);var r=bits%26,s=(bits-r)/26;if(assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!==r&&s++,this.length=Math.min(s,this.length),0!==r){var mask=67108863^67108863>>>r<=67108864;i++)this.words[i]-=67108864,i===this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=Math.max(this.length,i+1),this},BN.prototype.isubn=function isubn(num){if(assert("number"==typeof num),assert(num<67108864),num<0)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i>26)-(right/67108864|0),this.words[i+shift]=67108863&w}for(;i>26,this.words[i+shift]=67108863&w;if(0===carry)return this._strip();for(assert(-1===carry),carry=0,i=0;i>26,this.words[i]=67108863&w;return this.negative=1,this._strip()},BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=(this.length,num.length),a=this.clone(),b=num,bhi=0|b.words[b.length-1];0!==(shift=26-this._countBits(bhi))&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var q,m=a.length-b.length;if("mod"!==mode){(q=new BN(null)).length=m+1,q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=67108864*(0|a.words[b.length+j])+(0|a.words[b.length+j-1]);for(qj=Math.min(qj/bhi|0,67108863),a._ishlnsubmul(b,qj,j);0!==a.negative;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q._strip(),a._strip(),"div"!==mode&&0!==shift&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function divmod(num,mode,positive){return assert(!num.isZero()),this.isZero()?{div:new BN(0),mod:new BN(0)}:0!==this.negative&&0===num.negative?(res=this.neg().divmod(num,mode),"mod"!==mode&&(div=res.div.neg()),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.iadd(num)),{div,mod}):0===this.negative&&0!==num.negative?(res=this.divmod(num.neg(),mode),"mod"!==mode&&(div=res.div.neg()),{div,mod:res.mod}):0!=(this.negative&num.negative)?(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod}):num.length>this.length||this.cmp(num)<0?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modrn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modrn(num.words[0]))}:this._wordDiv(num,mode);var div,mod,res},BN.prototype.div=function div(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function mod(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function umod(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0!==dm.div.negative?dm.mod.isub(num):dm.mod,half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return cmp<0||1===r2&&0===cmp?dm.div:0!==dm.div.negative?dm.div.isubn(1):dm.div.iaddn(1)},BN.prototype.modrn=function modrn(num){var isNegNum=num<0;isNegNum&&(num=-num),assert(num<=67108863);for(var p=(1<<26)%num,acc=0,i=this.length-1;i>=0;i--)acc=(p*acc+(0|this.words[i]))%num;return isNegNum?-acc:acc},BN.prototype.modn=function modn(num){return this.modrn(num)},BN.prototype.idivn=function idivn(num){var isNegNum=num<0;isNegNum&&(num=-num),assert(num<=67108863);for(var carry=0,i=this.length-1;i>=0;i--){var w=(0|this.words[i])+67108864*carry;this.words[i]=w/num|0,carry=w%num}return this._strip(),isNegNum?this.ineg():this},BN.prototype.divn=function divn(num){return this.clone().idivn(num)},BN.prototype.egcd=function egcd(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0!==x.negative?x.umod(p):x.clone();for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0==(x.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(x.iushrn(i);i-- >0;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;0==(y.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(y.iushrn(j);j-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);x.cmp(y)>=0?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function _invmp(p){assert(0===p.negative),assert(!p.isZero());var a=this,b=p.clone();a=0!==a.negative?a.umod(p):a.clone();for(var res,x1=new BN(1),x2=new BN(0),delta=b.clone();a.cmpn(1)>0&&b.cmpn(1)>0;){for(var i=0,im=1;0==(a.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(a.iushrn(i);i-- >0;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;0==(b.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(b.iushrn(j);j-- >0;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);a.cmp(b)>=0?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}return(res=0===a.cmpn(1)?x1:x2).cmpn(0)<0&&res.iadd(p),res},BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);for(;;){for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(r<0){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}return b.iushln(shift)},BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function isEven(){return 0==(1&this.words[0])},BN.prototype.isOdd=function isOdd(){return 1==(1&this.words[0])},BN.prototype.andln=function andln(num){return this.words[0]&num},BN.prototype.bincn=function bincn(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<>>26,w&=67108863,this.words[i]=w}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function isZero(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function cmpn(num){var res,negative=num<0;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;if(this._strip(),this.length>1)res=1;else{negative&&(num=-num),assert(num<=67108863,"Number is too big");var w=0|this.words[0];res=w===num?0:wnum.length)return 1;if(this.length=0;i--){var a=0|this.words[i],b=0|num.words[i];if(a!==b){ab&&(res=1);break}}return res},BN.prototype.gtn=function gtn(num){return 1===this.cmpn(num)},BN.prototype.gt=function gt(num){return 1===this.cmp(num)},BN.prototype.gten=function gten(num){return this.cmpn(num)>=0},BN.prototype.gte=function gte(num){return this.cmp(num)>=0},BN.prototype.ltn=function ltn(num){return-1===this.cmpn(num)},BN.prototype.lt=function lt(num){return-1===this.cmp(num)},BN.prototype.lten=function lten(num){return this.cmpn(num)<=0},BN.prototype.lte=function lte(num){return this.cmp(num)<=0},BN.prototype.eqn=function eqn(num){return 0===this.cmpn(num)},BN.prototype.eq=function eq(num){return 0===this.cmp(num)},BN.red=function red(num){return new Red(num)},BN.prototype.toRed=function toRed(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function fromRed(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function _forceRed(ctx){return this.red=ctx,this},BN.prototype.forceRed=function forceRed(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function redAdd(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function redIAdd(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function redSub(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function redISub(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function redShl(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function redMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function redIMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function redSqr(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function redISqr(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function redSqrt(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function redInvm(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function redNeg(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function redPow(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);return tmp.words=new Array(Math.ceil(this.n/13)),tmp},MPrime.prototype.ireduce=function ireduce(num){var rlen,r=num;do{this.split(r,this.tmp),rlen=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(rlen>this.n);var cmp=rlen0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)},inherits(K256,MPrime),K256.prototype.split=function split(input,output){for(var outLen=Math.min(input.length,9),i=0;i>>22,prev=next}prev>>>=22,input.words[i-10]=prev,0===prev&&input.length>10?input.length-=10:input.length-=9},K256.prototype.imulK=function imulK(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0;i>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else{if("p25519"!==name)throw new Error("Unknown prime "+name);prime=new P25519}return primes[name]=prime,prime},Red.prototype._verify1=function _verify1(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function _verify2(a,b){assert(0==(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function imod(a){return this.prime?this.prime.ireduce(a)._forceRed(this):(move(a,a.umod(this.m)._forceRed(this)),a)},Red.prototype.neg=function neg(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);return res.cmp(this.m)>=0&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);return res.cmp(this.m)>=0&&res.isub(this.m),res},Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);return res.cmpn(0)<0&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);return res.cmpn(0)<0&&res.iadd(this.m),res},Red.prototype.shl=function shl(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function imul(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function mul(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())},Red.prototype.sqr=function sqr(a){return this.mul(a,a)},Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(mod3%2==1),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i=0;i--){for(var word=num.words[i],j=start-1;j>=0;j--){var bit=word>>j&1;res!==wnd[0]&&(res=this.sqr(res)),0!==bit||0!==current?(current<<=1,current|=bit,(4===++currentLen||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)):currentLen=0}start=26}return res},Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();return res.red=null,res},BN.mont=function mont(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function invm(a){return this.imod(a._invmp(this.m).mul(this.r2))._forceRed(this)}}(module=__webpack_require__.nmd(module),this)},9931:(module,__unused_webpack_exports,__webpack_require__)=>{var r;function Rand(rand){this.rand=rand}if(module.exports=function rand(len){return r||(r=new Rand(null)),r.generate(len)},module.exports.Rand=Rand,Rand.prototype.generate=function generate(len){return this._rand(len)},Rand.prototype._rand=function _rand(n){if(this.rand.getBytes)return this.rand.getBytes(n);for(var res=new Uint8Array(n),i=0;i{var Buffer=__webpack_require__(9509).Buffer;function asUInt32Array(buf){Buffer.isBuffer(buf)||(buf=Buffer.from(buf));for(var len=buf.length/4|0,out=new Array(len),i=0;i>>24]^SUB_MIX1[s1>>>16&255]^SUB_MIX2[s2>>>8&255]^SUB_MIX3[255&s3]^keySchedule[ksRow++],t1=SUB_MIX0[s1>>>24]^SUB_MIX1[s2>>>16&255]^SUB_MIX2[s3>>>8&255]^SUB_MIX3[255&s0]^keySchedule[ksRow++],t2=SUB_MIX0[s2>>>24]^SUB_MIX1[s3>>>16&255]^SUB_MIX2[s0>>>8&255]^SUB_MIX3[255&s1]^keySchedule[ksRow++],t3=SUB_MIX0[s3>>>24]^SUB_MIX1[s0>>>16&255]^SUB_MIX2[s1>>>8&255]^SUB_MIX3[255&s2]^keySchedule[ksRow++],s0=t0,s1=t1,s2=t2,s3=t3;return t0=(SBOX[s0>>>24]<<24|SBOX[s1>>>16&255]<<16|SBOX[s2>>>8&255]<<8|SBOX[255&s3])^keySchedule[ksRow++],t1=(SBOX[s1>>>24]<<24|SBOX[s2>>>16&255]<<16|SBOX[s3>>>8&255]<<8|SBOX[255&s0])^keySchedule[ksRow++],t2=(SBOX[s2>>>24]<<24|SBOX[s3>>>16&255]<<16|SBOX[s0>>>8&255]<<8|SBOX[255&s1])^keySchedule[ksRow++],t3=(SBOX[s3>>>24]<<24|SBOX[s0>>>16&255]<<16|SBOX[s1>>>8&255]<<8|SBOX[255&s2])^keySchedule[ksRow++],[t0>>>=0,t1>>>=0,t2>>>=0,t3>>>=0]}var RCON=[0,1,2,4,8,16,32,64,128,27,54],G=function(){for(var d=new Array(256),j=0;j<256;j++)d[j]=j<128?j<<1:j<<1^283;for(var SBOX=[],INV_SBOX=[],SUB_MIX=[[],[],[],[]],INV_SUB_MIX=[[],[],[],[]],x=0,xi=0,i=0;i<256;++i){var sx=xi^xi<<1^xi<<2^xi<<3^xi<<4;sx=sx>>>8^255&sx^99,SBOX[x]=sx,INV_SBOX[sx]=x;var x2=d[x],x4=d[x2],x8=d[x4],t=257*d[sx]^16843008*sx;SUB_MIX[0][x]=t<<24|t>>>8,SUB_MIX[1][x]=t<<16|t>>>16,SUB_MIX[2][x]=t<<8|t>>>24,SUB_MIX[3][x]=t,t=16843009*x8^65537*x4^257*x2^16843008*x,INV_SUB_MIX[0][sx]=t<<24|t>>>8,INV_SUB_MIX[1][sx]=t<<16|t>>>16,INV_SUB_MIX[2][sx]=t<<8|t>>>24,INV_SUB_MIX[3][sx]=t,0===x?x=xi=1:(x=x2^d[d[d[x8^x2]]],xi^=d[d[xi]])}return{SBOX,INV_SBOX,SUB_MIX,INV_SUB_MIX}}();function AES(key){this._key=asUInt32Array(key),this._reset()}AES.blockSize=16,AES.keySize=32,AES.prototype.blockSize=AES.blockSize,AES.prototype.keySize=AES.keySize,AES.prototype._reset=function(){for(var keyWords=this._key,keySize=keyWords.length,nRounds=keySize+6,ksRows=4*(nRounds+1),keySchedule=[],k=0;k>>24,t=G.SBOX[t>>>24]<<24|G.SBOX[t>>>16&255]<<16|G.SBOX[t>>>8&255]<<8|G.SBOX[255&t],t^=RCON[k/keySize|0]<<24):keySize>6&&k%keySize==4&&(t=G.SBOX[t>>>24]<<24|G.SBOX[t>>>16&255]<<16|G.SBOX[t>>>8&255]<<8|G.SBOX[255&t]),keySchedule[k]=keySchedule[k-keySize]^t}for(var invKeySchedule=[],ik=0;ik>>24]]^G.INV_SUB_MIX[1][G.SBOX[tt>>>16&255]]^G.INV_SUB_MIX[2][G.SBOX[tt>>>8&255]]^G.INV_SUB_MIX[3][G.SBOX[255&tt]]}this._nRounds=nRounds,this._keySchedule=keySchedule,this._invKeySchedule=invKeySchedule},AES.prototype.encryptBlockRaw=function(M){return cryptBlock(M=asUInt32Array(M),this._keySchedule,G.SUB_MIX,G.SBOX,this._nRounds)},AES.prototype.encryptBlock=function(M){var out=this.encryptBlockRaw(M),buf=Buffer.allocUnsafe(16);return buf.writeUInt32BE(out[0],0),buf.writeUInt32BE(out[1],4),buf.writeUInt32BE(out[2],8),buf.writeUInt32BE(out[3],12),buf},AES.prototype.decryptBlock=function(M){var m1=(M=asUInt32Array(M))[1];M[1]=M[3],M[3]=m1;var out=cryptBlock(M,this._invKeySchedule,G.INV_SUB_MIX,G.INV_SBOX,this._nRounds),buf=Buffer.allocUnsafe(16);return buf.writeUInt32BE(out[0],0),buf.writeUInt32BE(out[3],4),buf.writeUInt32BE(out[2],8),buf.writeUInt32BE(out[1],12),buf},AES.prototype.scrub=function(){scrubVec(this._keySchedule),scrubVec(this._invKeySchedule),scrubVec(this._key)},module.exports.AES=AES},2422:(module,__unused_webpack_exports,__webpack_require__)=>{var aes=__webpack_require__(4497),Buffer=__webpack_require__(9509).Buffer,Transform=__webpack_require__(1027),inherits=__webpack_require__(5717),GHASH=__webpack_require__(3288),xor=__webpack_require__(7295),incr32=__webpack_require__(685);function StreamCipher(mode,key,iv,decrypt){Transform.call(this);var h=Buffer.alloc(4,0);this._cipher=new aes.AES(key);var ck=this._cipher.encryptBlock(h);this._ghash=new GHASH(ck),iv=function calcIv(self,iv,ck){if(12===iv.length)return self._finID=Buffer.concat([iv,Buffer.from([0,0,0,1])]),Buffer.concat([iv,Buffer.from([0,0,0,2])]);var ghash=new GHASH(ck),len=iv.length,toPad=len%16;ghash.update(iv),toPad&&(toPad=16-toPad,ghash.update(Buffer.alloc(toPad,0))),ghash.update(Buffer.alloc(8,0));var ivBits=8*len,tail=Buffer.alloc(8);tail.writeUIntBE(ivBits,0,8),ghash.update(tail),self._finID=ghash.state;var out=Buffer.from(self._finID);return incr32(out),out}(this,iv,ck),this._prev=Buffer.from(iv),this._cache=Buffer.allocUnsafe(0),this._secCache=Buffer.allocUnsafe(0),this._decrypt=decrypt,this._alen=0,this._len=0,this._mode=mode,this._authTag=null,this._called=!1}inherits(StreamCipher,Transform),StreamCipher.prototype._update=function(chunk){if(!this._called&&this._alen){var rump=16-this._alen%16;rump<16&&(rump=Buffer.alloc(rump,0),this._ghash.update(rump))}this._called=!0;var out=this._mode.encrypt(this,chunk);return this._decrypt?this._ghash.update(chunk):this._ghash.update(out),this._len+=chunk.length,out},StreamCipher.prototype._final=function(){if(this._decrypt&&!this._authTag)throw new Error("Unsupported state or unable to authenticate data");var tag=xor(this._ghash.final(8*this._alen,8*this._len),this._cipher.encryptBlock(this._finID));if(this._decrypt&&function xorTest(a,b){var out=0;a.length!==b.length&&out++;for(var len=Math.min(a.length,b.length),i=0;i{var ciphers=__webpack_require__(1494),deciphers=__webpack_require__(6193),modes=__webpack_require__(4946);exports.createCipher=exports.Cipher=ciphers.createCipher,exports.createCipheriv=exports.Cipheriv=ciphers.createCipheriv,exports.createDecipher=exports.Decipher=deciphers.createDecipher,exports.createDecipheriv=exports.Decipheriv=deciphers.createDecipheriv,exports.listCiphers=exports.getCiphers=function getCiphers(){return Object.keys(modes)}},6193:(__unused_webpack_module,exports,__webpack_require__)=>{var AuthCipher=__webpack_require__(2422),Buffer=__webpack_require__(9509).Buffer,MODES=__webpack_require__(45),StreamCipher=__webpack_require__(5969),Transform=__webpack_require__(1027),aes=__webpack_require__(4497),ebtk=__webpack_require__(3048);function Decipher(mode,key,iv){Transform.call(this),this._cache=new Splitter,this._last=void 0,this._cipher=new aes.AES(key),this._prev=Buffer.from(iv),this._mode=mode,this._autopadding=!0}function Splitter(){this.cache=Buffer.allocUnsafe(0)}function createDecipheriv(suite,password,iv){var config=MODES[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");if("string"==typeof iv&&(iv=Buffer.from(iv)),"GCM"!==config.mode&&iv.length!==config.iv)throw new TypeError("invalid iv length "+iv.length);if("string"==typeof password&&(password=Buffer.from(password)),password.length!==config.key/8)throw new TypeError("invalid key length "+password.length);return"stream"===config.type?new StreamCipher(config.module,password,iv,!0):"auth"===config.type?new AuthCipher(config.module,password,iv,!0):new Decipher(config.module,password,iv)}__webpack_require__(5717)(Decipher,Transform),Decipher.prototype._update=function(data){var chunk,thing;this._cache.add(data);for(var out=[];chunk=this._cache.get(this._autopadding);)thing=this._mode.decrypt(this,chunk),out.push(thing);return Buffer.concat(out)},Decipher.prototype._final=function(){var chunk=this._cache.flush();if(this._autopadding)return function unpad(last){var padded=last[15];if(padded<1||padded>16)throw new Error("unable to decrypt data");var i=-1;for(;++i16)return out=this.cache.slice(0,16),this.cache=this.cache.slice(16),out}else if(this.cache.length>=16)return out=this.cache.slice(0,16),this.cache=this.cache.slice(16),out;return null},Splitter.prototype.flush=function(){if(this.cache.length)return this.cache},exports.createDecipher=function createDecipher(suite,password){var config=MODES[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");var keys=ebtk(password,!1,config.key,config.iv);return createDecipheriv(suite,keys.key,keys.iv)},exports.createDecipheriv=createDecipheriv},1494:(__unused_webpack_module,exports,__webpack_require__)=>{var MODES=__webpack_require__(45),AuthCipher=__webpack_require__(2422),Buffer=__webpack_require__(9509).Buffer,StreamCipher=__webpack_require__(5969),Transform=__webpack_require__(1027),aes=__webpack_require__(4497),ebtk=__webpack_require__(3048);function Cipher(mode,key,iv){Transform.call(this),this._cache=new Splitter,this._cipher=new aes.AES(key),this._prev=Buffer.from(iv),this._mode=mode,this._autopadding=!0}__webpack_require__(5717)(Cipher,Transform),Cipher.prototype._update=function(data){var chunk,thing;this._cache.add(data);for(var out=[];chunk=this._cache.get();)thing=this._mode.encrypt(this,chunk),out.push(thing);return Buffer.concat(out)};var PADDING=Buffer.alloc(16,16);function Splitter(){this.cache=Buffer.allocUnsafe(0)}function createCipheriv(suite,password,iv){var config=MODES[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");if("string"==typeof password&&(password=Buffer.from(password)),password.length!==config.key/8)throw new TypeError("invalid key length "+password.length);if("string"==typeof iv&&(iv=Buffer.from(iv)),"GCM"!==config.mode&&iv.length!==config.iv)throw new TypeError("invalid iv length "+iv.length);return"stream"===config.type?new StreamCipher(config.module,password,iv):"auth"===config.type?new AuthCipher(config.module,password,iv):new Cipher(config.module,password,iv)}Cipher.prototype._final=function(){var chunk=this._cache.flush();if(this._autopadding)return chunk=this._mode.encrypt(this,chunk),this._cipher.scrub(),chunk;if(!chunk.equals(PADDING))throw this._cipher.scrub(),new Error("data not multiple of block length")},Cipher.prototype.setAutoPadding=function(setTo){return this._autopadding=!!setTo,this},Splitter.prototype.add=function(data){this.cache=Buffer.concat([this.cache,data])},Splitter.prototype.get=function(){if(this.cache.length>15){var out=this.cache.slice(0,16);return this.cache=this.cache.slice(16),out}return null},Splitter.prototype.flush=function(){for(var len=16-this.cache.length,padBuff=Buffer.allocUnsafe(len),i=-1;++i{var Buffer=__webpack_require__(9509).Buffer,ZEROES=Buffer.alloc(16,0);function fromArray(out){var buf=Buffer.allocUnsafe(16);return buf.writeUInt32BE(out[0]>>>0,0),buf.writeUInt32BE(out[1]>>>0,4),buf.writeUInt32BE(out[2]>>>0,8),buf.writeUInt32BE(out[3]>>>0,12),buf}function GHASH(key){this.h=key,this.state=Buffer.alloc(16,0),this.cache=Buffer.allocUnsafe(0)}GHASH.prototype.ghash=function(block){for(var i=-1;++i0;j--)Vi[j]=Vi[j]>>>1|(1&Vi[j-1])<<31;Vi[0]=Vi[0]>>>1,lsbVi&&(Vi[0]=Vi[0]^225<<24)}this.state=fromArray(Zi)},GHASH.prototype.update=function(buf){var chunk;for(this.cache=Buffer.concat([this.cache,buf]);this.cache.length>=16;)chunk=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(chunk)},GHASH.prototype.final=function(abl,bl){return this.cache.length&&this.ghash(Buffer.concat([this.cache,ZEROES],16)),this.ghash(fromArray([0,abl,0,bl])),this.state},module.exports=GHASH},685:module=>{module.exports=function incr32(iv){for(var item,len=iv.length;len--;){if(255!==(item=iv.readUInt8(len))){item++,iv.writeUInt8(item,len);break}iv.writeUInt8(0,len)}}},5292:(__unused_webpack_module,exports,__webpack_require__)=>{var xor=__webpack_require__(7295);exports.encrypt=function(self,block){var data=xor(block,self._prev);return self._prev=self._cipher.encryptBlock(data),self._prev},exports.decrypt=function(self,block){var pad=self._prev;self._prev=block;var out=self._cipher.decryptBlock(block);return xor(out,pad)}},6311:(__unused_webpack_module,exports,__webpack_require__)=>{var Buffer=__webpack_require__(9509).Buffer,xor=__webpack_require__(7295);function encryptStart(self,data,decrypt){var len=data.length,out=xor(data,self._cache);return self._cache=self._cache.slice(len),self._prev=Buffer.concat([self._prev,decrypt?data:out]),out}exports.encrypt=function(self,data,decrypt){for(var len,out=Buffer.allocUnsafe(0);data.length;){if(0===self._cache.length&&(self._cache=self._cipher.encryptBlock(self._prev),self._prev=Buffer.allocUnsafe(0)),!(self._cache.length<=data.length)){out=Buffer.concat([out,encryptStart(self,data,decrypt)]);break}len=self._cache.length,out=Buffer.concat([out,encryptStart(self,data.slice(0,len),decrypt)]),data=data.slice(len)}return out}},1510:(__unused_webpack_module,exports,__webpack_require__)=>{var Buffer=__webpack_require__(9509).Buffer;function encryptByte(self,byteParam,decrypt){for(var bit,value,i=-1,out=0;++i<8;)bit=byteParam&1<<7-i?128:0,out+=(128&(value=self._cipher.encryptBlock(self._prev)[0]^bit))>>i%8,self._prev=shiftIn(self._prev,decrypt?bit:value);return out}function shiftIn(buffer,value){var len=buffer.length,i=-1,out=Buffer.allocUnsafe(buffer.length);for(buffer=Buffer.concat([buffer,Buffer.from([value])]);++i>7;return out}exports.encrypt=function(self,chunk,decrypt){for(var len=chunk.length,out=Buffer.allocUnsafe(len),i=-1;++i{var Buffer=__webpack_require__(9509).Buffer;function encryptByte(self,byteParam,decrypt){var out=self._cipher.encryptBlock(self._prev)[0]^byteParam;return self._prev=Buffer.concat([self._prev.slice(1),Buffer.from([decrypt?byteParam:out])]),out}exports.encrypt=function(self,chunk,decrypt){for(var len=chunk.length,out=Buffer.allocUnsafe(len),i=-1;++i{var xor=__webpack_require__(7295),Buffer=__webpack_require__(9509).Buffer,incr32=__webpack_require__(685);function getBlock(self){var out=self._cipher.encryptBlockRaw(self._prev);return incr32(self._prev),out}exports.encrypt=function(self,chunk){var chunkNum=Math.ceil(chunk.length/16),start=self._cache.length;self._cache=Buffer.concat([self._cache,Buffer.allocUnsafe(16*chunkNum)]);for(var i=0;i{exports.encrypt=function(self,block){return self._cipher.encryptBlock(block)},exports.decrypt=function(self,block){return self._cipher.decryptBlock(block)}},45:(module,__unused_webpack_exports,__webpack_require__)=>{var modeModules={ECB:__webpack_require__(1084),CBC:__webpack_require__(5292),CFB:__webpack_require__(6311),CFB8:__webpack_require__(1964),CFB1:__webpack_require__(1510),OFB:__webpack_require__(8861),CTR:__webpack_require__(6009),GCM:__webpack_require__(6009)},modes=__webpack_require__(4946);for(var key in modes)modes[key].module=modeModules[modes[key].mode];module.exports=modes},8861:(__unused_webpack_module,exports,__webpack_require__)=>{var xor=__webpack_require__(7295);function getBlock(self){return self._prev=self._cipher.encryptBlock(self._prev),self._prev}exports.encrypt=function(self,chunk){for(;self._cache.length{var aes=__webpack_require__(4497),Buffer=__webpack_require__(9509).Buffer,Transform=__webpack_require__(1027);function StreamCipher(mode,key,iv,decrypt){Transform.call(this),this._cipher=new aes.AES(key),this._prev=Buffer.from(iv),this._cache=Buffer.allocUnsafe(0),this._secCache=Buffer.allocUnsafe(0),this._decrypt=decrypt,this._mode=mode}__webpack_require__(5717)(StreamCipher,Transform),StreamCipher.prototype._update=function(chunk){return this._mode.encrypt(this,chunk,this._decrypt)},StreamCipher.prototype._final=function(){this._cipher.scrub()},module.exports=StreamCipher},3614:(__unused_webpack_module,exports,__webpack_require__)=>{var DES=__webpack_require__(7667),aes=__webpack_require__(4696),aesModes=__webpack_require__(45),desModes=__webpack_require__(9715),ebtk=__webpack_require__(3048);function createCipheriv(suite,key,iv){if(suite=suite.toLowerCase(),aesModes[suite])return aes.createCipheriv(suite,key,iv);if(desModes[suite])return new DES({key,iv,mode:suite});throw new TypeError("invalid suite type")}function createDecipheriv(suite,key,iv){if(suite=suite.toLowerCase(),aesModes[suite])return aes.createDecipheriv(suite,key,iv);if(desModes[suite])return new DES({key,iv,mode:suite,decrypt:!0});throw new TypeError("invalid suite type")}exports.createCipher=exports.Cipher=function createCipher(suite,password){var keyLen,ivLen;if(suite=suite.toLowerCase(),aesModes[suite])keyLen=aesModes[suite].key,ivLen=aesModes[suite].iv;else{if(!desModes[suite])throw new TypeError("invalid suite type");keyLen=8*desModes[suite].key,ivLen=desModes[suite].iv}var keys=ebtk(password,!1,keyLen,ivLen);return createCipheriv(suite,keys.key,keys.iv)},exports.createCipheriv=exports.Cipheriv=createCipheriv,exports.createDecipher=exports.Decipher=function createDecipher(suite,password){var keyLen,ivLen;if(suite=suite.toLowerCase(),aesModes[suite])keyLen=aesModes[suite].key,ivLen=aesModes[suite].iv;else{if(!desModes[suite])throw new TypeError("invalid suite type");keyLen=8*desModes[suite].key,ivLen=desModes[suite].iv}var keys=ebtk(password,!1,keyLen,ivLen);return createDecipheriv(suite,keys.key,keys.iv)},exports.createDecipheriv=exports.Decipheriv=createDecipheriv,exports.listCiphers=exports.getCiphers=function getCiphers(){return Object.keys(desModes).concat(aes.getCiphers())}},7667:(module,__unused_webpack_exports,__webpack_require__)=>{var CipherBase=__webpack_require__(1027),des=__webpack_require__(5251),inherits=__webpack_require__(5717),Buffer=__webpack_require__(9509).Buffer,modes={"des-ede3-cbc":des.CBC.instantiate(des.EDE),"des-ede3":des.EDE,"des-ede-cbc":des.CBC.instantiate(des.EDE),"des-ede":des.EDE,"des-cbc":des.CBC.instantiate(des.DES),"des-ecb":des.DES};function DES(opts){CipherBase.call(this);var type,modeName=opts.mode.toLowerCase(),mode=modes[modeName];type=opts.decrypt?"decrypt":"encrypt";var key=opts.key;Buffer.isBuffer(key)||(key=Buffer.from(key)),"des-ede"!==modeName&&"des-ede-cbc"!==modeName||(key=Buffer.concat([key,key.slice(0,8)]));var iv=opts.iv;Buffer.isBuffer(iv)||(iv=Buffer.from(iv)),this._des=mode.create({key,iv,type})}modes.des=modes["des-cbc"],modes.des3=modes["des-ede3-cbc"],module.exports=DES,inherits(DES,CipherBase),DES.prototype._update=function(data){return Buffer.from(this._des.update(data))},DES.prototype._final=function(){return Buffer.from(this._des.final())}},9715:(__unused_webpack_module,exports)=>{exports["des-ecb"]={key:8,iv:0},exports["des-cbc"]=exports.des={key:8,iv:8},exports["des-ede3-cbc"]=exports.des3={key:24,iv:8},exports["des-ede3"]={key:24,iv:0},exports["des-ede-cbc"]={key:16,iv:8},exports["des-ede"]={key:16,iv:0}},3663:(module,__unused_webpack_exports,__webpack_require__)=>{var BN=__webpack_require__(3982),randomBytes=__webpack_require__(1798);function getr(priv){var r,len=priv.modulus.byteLength();do{r=new BN(randomBytes(len))}while(r.cmp(priv.modulus)>=0||!r.umod(priv.prime1)||!r.umod(priv.prime2));return r}function crt(msg,priv){var blinds=function blind(priv){var r=getr(priv);return{blinder:r.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed(),unblinder:r.invm(priv.modulus)}}(priv),len=priv.modulus.byteLength(),blinded=new BN(msg).mul(blinds.blinder).umod(priv.modulus),c1=blinded.toRed(BN.mont(priv.prime1)),c2=blinded.toRed(BN.mont(priv.prime2)),qinv=priv.coefficient,p=priv.prime1,q=priv.prime2,m1=c1.redPow(priv.exponent1).fromRed(),m2=c2.redPow(priv.exponent2).fromRed(),h=m1.isub(m2).imul(qinv).umod(p).imul(q);return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer,"be",len)}crt.getr=getr,module.exports=crt},3982:function(module,__unused_webpack_exports,__webpack_require__){!function(module,exports){"use strict";function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}function BN(number,base,endian){if(BN.isBN(number))return number;this.negative=0,this.words=null,this.length=0,this.red=null,null!==number&&("le"!==base&&"be"!==base||(endian=base,base=10),this._init(number||0,base||10,endian||"be"))}var Buffer;"object"==typeof module?module.exports=BN:exports.BN=BN,BN.BN=BN,BN.wordSize=26;try{Buffer="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:__webpack_require__(1922).Buffer}catch(e){}function parseHex4Bits(string,index){var c=string.charCodeAt(index);return c>=48&&c<=57?c-48:c>=65&&c<=70?c-55:c>=97&&c<=102?c-87:void assert(!1,"Invalid character in "+string)}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return index-1>=lowerBound&&(r|=parseHex4Bits(string,index-1)<<4),r}function parseBase(str,start,end,mul){for(var r=0,b=0,len=Math.min(str.length,end),i=start;i=49?c-49+10:c>=17?c-17+10:c,assert(c>=0&&b0?left:right},BN.min=function min(left,right){return left.cmp(right)<0?left:right},BN.prototype._init=function init(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&base>=2&&base<=36);var start=0;"-"===(number=number.toString().replace(/\s+/g,""))[0]&&(start++,this.negative=1),start=0;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=w<>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);return this._strip()},BN.prototype._parseHex=function _parseHex(number,start,endian){this.length=Math.ceil((number.length-start)/6),this.words=new Array(this.length);for(var i=0;i=start;i-=2)w=parseHexByte(number,start,i)<=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;else for(i=(number.length-start)%2==0?start+1:start;i=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;this._strip()},BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;limbPow*=base)limbLen++;limbLen--,limbPow=limbPow/base|0;for(var total=number.length-start,mod=total%limbLen,end=Math.min(total,total-mod)+start,word=0,i=start;i1&&0===this.words[this.length-1];)this.length--;return this._normSign()},BN.prototype._normSign=function _normSign(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{BN.prototype[Symbol.for("nodejs.util.inspect.custom")]=inspect}catch(e){BN.prototype.inspect=inspect}else BN.prototype.inspect=inspect;function inspect(){return(this.red?""}var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function toString(base,padding){var out;if(padding=0|padding||1,16===(base=base||10)||"hex"===base){out="";for(var off=0,carry=0,i=0;i>>24-off&16777215)||i!==this.length-1?zeros[6-word.length]+word+out:word+out,(off+=2)>=26&&(off-=26,i--)}for(0!==carry&&(out=carry.toString(16)+out);out.length%padding!=0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&base>=2&&base<=36){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modrn(groupBase).toString(base);out=(c=c.idivn(groupBase)).isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);out.length%padding!=0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function toNumber(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:this.length>2&&assert(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-ret:ret},BN.prototype.toJSON=function toJSON(){return this.toString(16,2)},Buffer&&(BN.prototype.toBuffer=function toBuffer(endian,length){return this.toArrayLike(Buffer,endian,length)}),BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)};function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=self.length+num.length|0;out.length=len,len=len-1|0;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=r/67108864|0;out.words[0]=lo;for(var k=1;k>>26,rword=67108863&carry,maxJ=Math.min(k,num.length-1),j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j|0;ncarry+=(r=(a=0|self.words[i])*(b=0|num.words[j])+rword)/67108864|0,rword=67108863&r}out.words[k]=0|rword,carry=0|ncarry}return 0!==carry?out.words[k]=0|carry:out.length--,out._strip()}BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){this._strip();var byteLength=this.byteLength(),reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length"),assert(reqLength>0,"Requested array length <= 0");var res=function allocate(ArrayType,size){return ArrayType.allocUnsafe?ArrayType.allocUnsafe(size):new ArrayType(size)}(ArrayType,reqLength);return this["_toArrayLike"+("le"===endian?"LE":"BE")](res,byteLength),res},BN.prototype._toArrayLikeLE=function _toArrayLikeLE(res,byteLength){for(var position=0,carry=0,i=0,shift=0;i>8&255),position>16&255),6===shift?(position>24&255),carry=0,shift=0):(carry=word>>>24,shift+=2)}if(position=0&&(res[position--]=word>>8&255),position>=0&&(res[position--]=word>>16&255),6===shift?(position>=0&&(res[position--]=word>>24&255),carry=0,shift=0):(carry=word>>>24,shift+=2)}if(position>=0)for(res[position--]=carry;position>=0;)res[position--]=0},Math.clz32?BN.prototype._countBits=function _countBits(w){return 32-Math.clz32(w)}:BN.prototype._countBits=function _countBits(w){var t=w,r=0;return t>=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function _zeroBits(w){if(0===w)return 26;var t=w,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;for(var r=0,i=0;inum.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function uor(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function iuand(num){var b;b=this.length>num.length?num:this;for(var i=0;inum.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function uand(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function iuxor(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;inum.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function uxor(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function inotn(width){assert("number"==typeof width&&width>=0);var bytesNeeded=0|Math.ceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),bitsLeft>0&&bytesNeeded--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this._strip()},BN.prototype.notn=function notn(width){return this.clone().inotn(width)},BN.prototype.setn=function setn(bit,val){assert("number"==typeof bit&&bit>=0);var off=bit/26|0,wbit=bit%26;return this._expand(off+1),this.words[off]=val?this.words[off]|1<num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>>26;for(;0!==carry&&i>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;inum.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function isub(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var a,b,cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;cmp>0?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>26,this.words[i]=67108863&r;for(;0!==carry&&i>26,this.words[i]=67108863&r;if(0===carry&&i>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13;out.negative=self.negative^num.negative,out.length=19;var w0=(c+(lo=Math.imul(al0,bl0))|0)+((8191&(mid=(mid=Math.imul(al0,bh0))+Math.imul(ah0,bl0)|0))<<13)|0;c=((hi=Math.imul(ah0,bh0))+(mid>>>13)|0)+(w0>>>26)|0,w0&=67108863,lo=Math.imul(al1,bl0),mid=(mid=Math.imul(al1,bh0))+Math.imul(ah1,bl0)|0,hi=Math.imul(ah1,bh0);var w1=(c+(lo=lo+Math.imul(al0,bl1)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh1)|0)+Math.imul(ah0,bl1)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh1)|0)+(mid>>>13)|0)+(w1>>>26)|0,w1&=67108863,lo=Math.imul(al2,bl0),mid=(mid=Math.imul(al2,bh0))+Math.imul(ah2,bl0)|0,hi=Math.imul(ah2,bh0),lo=lo+Math.imul(al1,bl1)|0,mid=(mid=mid+Math.imul(al1,bh1)|0)+Math.imul(ah1,bl1)|0,hi=hi+Math.imul(ah1,bh1)|0;var w2=(c+(lo=lo+Math.imul(al0,bl2)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh2)|0)+Math.imul(ah0,bl2)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh2)|0)+(mid>>>13)|0)+(w2>>>26)|0,w2&=67108863,lo=Math.imul(al3,bl0),mid=(mid=Math.imul(al3,bh0))+Math.imul(ah3,bl0)|0,hi=Math.imul(ah3,bh0),lo=lo+Math.imul(al2,bl1)|0,mid=(mid=mid+Math.imul(al2,bh1)|0)+Math.imul(ah2,bl1)|0,hi=hi+Math.imul(ah2,bh1)|0,lo=lo+Math.imul(al1,bl2)|0,mid=(mid=mid+Math.imul(al1,bh2)|0)+Math.imul(ah1,bl2)|0,hi=hi+Math.imul(ah1,bh2)|0;var w3=(c+(lo=lo+Math.imul(al0,bl3)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh3)|0)+Math.imul(ah0,bl3)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh3)|0)+(mid>>>13)|0)+(w3>>>26)|0,w3&=67108863,lo=Math.imul(al4,bl0),mid=(mid=Math.imul(al4,bh0))+Math.imul(ah4,bl0)|0,hi=Math.imul(ah4,bh0),lo=lo+Math.imul(al3,bl1)|0,mid=(mid=mid+Math.imul(al3,bh1)|0)+Math.imul(ah3,bl1)|0,hi=hi+Math.imul(ah3,bh1)|0,lo=lo+Math.imul(al2,bl2)|0,mid=(mid=mid+Math.imul(al2,bh2)|0)+Math.imul(ah2,bl2)|0,hi=hi+Math.imul(ah2,bh2)|0,lo=lo+Math.imul(al1,bl3)|0,mid=(mid=mid+Math.imul(al1,bh3)|0)+Math.imul(ah1,bl3)|0,hi=hi+Math.imul(ah1,bh3)|0;var w4=(c+(lo=lo+Math.imul(al0,bl4)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh4)|0)+Math.imul(ah0,bl4)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh4)|0)+(mid>>>13)|0)+(w4>>>26)|0,w4&=67108863,lo=Math.imul(al5,bl0),mid=(mid=Math.imul(al5,bh0))+Math.imul(ah5,bl0)|0,hi=Math.imul(ah5,bh0),lo=lo+Math.imul(al4,bl1)|0,mid=(mid=mid+Math.imul(al4,bh1)|0)+Math.imul(ah4,bl1)|0,hi=hi+Math.imul(ah4,bh1)|0,lo=lo+Math.imul(al3,bl2)|0,mid=(mid=mid+Math.imul(al3,bh2)|0)+Math.imul(ah3,bl2)|0,hi=hi+Math.imul(ah3,bh2)|0,lo=lo+Math.imul(al2,bl3)|0,mid=(mid=mid+Math.imul(al2,bh3)|0)+Math.imul(ah2,bl3)|0,hi=hi+Math.imul(ah2,bh3)|0,lo=lo+Math.imul(al1,bl4)|0,mid=(mid=mid+Math.imul(al1,bh4)|0)+Math.imul(ah1,bl4)|0,hi=hi+Math.imul(ah1,bh4)|0;var w5=(c+(lo=lo+Math.imul(al0,bl5)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh5)|0)+Math.imul(ah0,bl5)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh5)|0)+(mid>>>13)|0)+(w5>>>26)|0,w5&=67108863,lo=Math.imul(al6,bl0),mid=(mid=Math.imul(al6,bh0))+Math.imul(ah6,bl0)|0,hi=Math.imul(ah6,bh0),lo=lo+Math.imul(al5,bl1)|0,mid=(mid=mid+Math.imul(al5,bh1)|0)+Math.imul(ah5,bl1)|0,hi=hi+Math.imul(ah5,bh1)|0,lo=lo+Math.imul(al4,bl2)|0,mid=(mid=mid+Math.imul(al4,bh2)|0)+Math.imul(ah4,bl2)|0,hi=hi+Math.imul(ah4,bh2)|0,lo=lo+Math.imul(al3,bl3)|0,mid=(mid=mid+Math.imul(al3,bh3)|0)+Math.imul(ah3,bl3)|0,hi=hi+Math.imul(ah3,bh3)|0,lo=lo+Math.imul(al2,bl4)|0,mid=(mid=mid+Math.imul(al2,bh4)|0)+Math.imul(ah2,bl4)|0,hi=hi+Math.imul(ah2,bh4)|0,lo=lo+Math.imul(al1,bl5)|0,mid=(mid=mid+Math.imul(al1,bh5)|0)+Math.imul(ah1,bl5)|0,hi=hi+Math.imul(ah1,bh5)|0;var w6=(c+(lo=lo+Math.imul(al0,bl6)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh6)|0)+Math.imul(ah0,bl6)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh6)|0)+(mid>>>13)|0)+(w6>>>26)|0,w6&=67108863,lo=Math.imul(al7,bl0),mid=(mid=Math.imul(al7,bh0))+Math.imul(ah7,bl0)|0,hi=Math.imul(ah7,bh0),lo=lo+Math.imul(al6,bl1)|0,mid=(mid=mid+Math.imul(al6,bh1)|0)+Math.imul(ah6,bl1)|0,hi=hi+Math.imul(ah6,bh1)|0,lo=lo+Math.imul(al5,bl2)|0,mid=(mid=mid+Math.imul(al5,bh2)|0)+Math.imul(ah5,bl2)|0,hi=hi+Math.imul(ah5,bh2)|0,lo=lo+Math.imul(al4,bl3)|0,mid=(mid=mid+Math.imul(al4,bh3)|0)+Math.imul(ah4,bl3)|0,hi=hi+Math.imul(ah4,bh3)|0,lo=lo+Math.imul(al3,bl4)|0,mid=(mid=mid+Math.imul(al3,bh4)|0)+Math.imul(ah3,bl4)|0,hi=hi+Math.imul(ah3,bh4)|0,lo=lo+Math.imul(al2,bl5)|0,mid=(mid=mid+Math.imul(al2,bh5)|0)+Math.imul(ah2,bl5)|0,hi=hi+Math.imul(ah2,bh5)|0,lo=lo+Math.imul(al1,bl6)|0,mid=(mid=mid+Math.imul(al1,bh6)|0)+Math.imul(ah1,bl6)|0,hi=hi+Math.imul(ah1,bh6)|0;var w7=(c+(lo=lo+Math.imul(al0,bl7)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh7)|0)+Math.imul(ah0,bl7)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh7)|0)+(mid>>>13)|0)+(w7>>>26)|0,w7&=67108863,lo=Math.imul(al8,bl0),mid=(mid=Math.imul(al8,bh0))+Math.imul(ah8,bl0)|0,hi=Math.imul(ah8,bh0),lo=lo+Math.imul(al7,bl1)|0,mid=(mid=mid+Math.imul(al7,bh1)|0)+Math.imul(ah7,bl1)|0,hi=hi+Math.imul(ah7,bh1)|0,lo=lo+Math.imul(al6,bl2)|0,mid=(mid=mid+Math.imul(al6,bh2)|0)+Math.imul(ah6,bl2)|0,hi=hi+Math.imul(ah6,bh2)|0,lo=lo+Math.imul(al5,bl3)|0,mid=(mid=mid+Math.imul(al5,bh3)|0)+Math.imul(ah5,bl3)|0,hi=hi+Math.imul(ah5,bh3)|0,lo=lo+Math.imul(al4,bl4)|0,mid=(mid=mid+Math.imul(al4,bh4)|0)+Math.imul(ah4,bl4)|0,hi=hi+Math.imul(ah4,bh4)|0,lo=lo+Math.imul(al3,bl5)|0,mid=(mid=mid+Math.imul(al3,bh5)|0)+Math.imul(ah3,bl5)|0,hi=hi+Math.imul(ah3,bh5)|0,lo=lo+Math.imul(al2,bl6)|0,mid=(mid=mid+Math.imul(al2,bh6)|0)+Math.imul(ah2,bl6)|0,hi=hi+Math.imul(ah2,bh6)|0,lo=lo+Math.imul(al1,bl7)|0,mid=(mid=mid+Math.imul(al1,bh7)|0)+Math.imul(ah1,bl7)|0,hi=hi+Math.imul(ah1,bh7)|0;var w8=(c+(lo=lo+Math.imul(al0,bl8)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh8)|0)+Math.imul(ah0,bl8)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh8)|0)+(mid>>>13)|0)+(w8>>>26)|0,w8&=67108863,lo=Math.imul(al9,bl0),mid=(mid=Math.imul(al9,bh0))+Math.imul(ah9,bl0)|0,hi=Math.imul(ah9,bh0),lo=lo+Math.imul(al8,bl1)|0,mid=(mid=mid+Math.imul(al8,bh1)|0)+Math.imul(ah8,bl1)|0,hi=hi+Math.imul(ah8,bh1)|0,lo=lo+Math.imul(al7,bl2)|0,mid=(mid=mid+Math.imul(al7,bh2)|0)+Math.imul(ah7,bl2)|0,hi=hi+Math.imul(ah7,bh2)|0,lo=lo+Math.imul(al6,bl3)|0,mid=(mid=mid+Math.imul(al6,bh3)|0)+Math.imul(ah6,bl3)|0,hi=hi+Math.imul(ah6,bh3)|0,lo=lo+Math.imul(al5,bl4)|0,mid=(mid=mid+Math.imul(al5,bh4)|0)+Math.imul(ah5,bl4)|0,hi=hi+Math.imul(ah5,bh4)|0,lo=lo+Math.imul(al4,bl5)|0,mid=(mid=mid+Math.imul(al4,bh5)|0)+Math.imul(ah4,bl5)|0,hi=hi+Math.imul(ah4,bh5)|0,lo=lo+Math.imul(al3,bl6)|0,mid=(mid=mid+Math.imul(al3,bh6)|0)+Math.imul(ah3,bl6)|0,hi=hi+Math.imul(ah3,bh6)|0,lo=lo+Math.imul(al2,bl7)|0,mid=(mid=mid+Math.imul(al2,bh7)|0)+Math.imul(ah2,bl7)|0,hi=hi+Math.imul(ah2,bh7)|0,lo=lo+Math.imul(al1,bl8)|0,mid=(mid=mid+Math.imul(al1,bh8)|0)+Math.imul(ah1,bl8)|0,hi=hi+Math.imul(ah1,bh8)|0;var w9=(c+(lo=lo+Math.imul(al0,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh9)|0)+Math.imul(ah0,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh9)|0)+(mid>>>13)|0)+(w9>>>26)|0,w9&=67108863,lo=Math.imul(al9,bl1),mid=(mid=Math.imul(al9,bh1))+Math.imul(ah9,bl1)|0,hi=Math.imul(ah9,bh1),lo=lo+Math.imul(al8,bl2)|0,mid=(mid=mid+Math.imul(al8,bh2)|0)+Math.imul(ah8,bl2)|0,hi=hi+Math.imul(ah8,bh2)|0,lo=lo+Math.imul(al7,bl3)|0,mid=(mid=mid+Math.imul(al7,bh3)|0)+Math.imul(ah7,bl3)|0,hi=hi+Math.imul(ah7,bh3)|0,lo=lo+Math.imul(al6,bl4)|0,mid=(mid=mid+Math.imul(al6,bh4)|0)+Math.imul(ah6,bl4)|0,hi=hi+Math.imul(ah6,bh4)|0,lo=lo+Math.imul(al5,bl5)|0,mid=(mid=mid+Math.imul(al5,bh5)|0)+Math.imul(ah5,bl5)|0,hi=hi+Math.imul(ah5,bh5)|0,lo=lo+Math.imul(al4,bl6)|0,mid=(mid=mid+Math.imul(al4,bh6)|0)+Math.imul(ah4,bl6)|0,hi=hi+Math.imul(ah4,bh6)|0,lo=lo+Math.imul(al3,bl7)|0,mid=(mid=mid+Math.imul(al3,bh7)|0)+Math.imul(ah3,bl7)|0,hi=hi+Math.imul(ah3,bh7)|0,lo=lo+Math.imul(al2,bl8)|0,mid=(mid=mid+Math.imul(al2,bh8)|0)+Math.imul(ah2,bl8)|0,hi=hi+Math.imul(ah2,bh8)|0;var w10=(c+(lo=lo+Math.imul(al1,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al1,bh9)|0)+Math.imul(ah1,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah1,bh9)|0)+(mid>>>13)|0)+(w10>>>26)|0,w10&=67108863,lo=Math.imul(al9,bl2),mid=(mid=Math.imul(al9,bh2))+Math.imul(ah9,bl2)|0,hi=Math.imul(ah9,bh2),lo=lo+Math.imul(al8,bl3)|0,mid=(mid=mid+Math.imul(al8,bh3)|0)+Math.imul(ah8,bl3)|0,hi=hi+Math.imul(ah8,bh3)|0,lo=lo+Math.imul(al7,bl4)|0,mid=(mid=mid+Math.imul(al7,bh4)|0)+Math.imul(ah7,bl4)|0,hi=hi+Math.imul(ah7,bh4)|0,lo=lo+Math.imul(al6,bl5)|0,mid=(mid=mid+Math.imul(al6,bh5)|0)+Math.imul(ah6,bl5)|0,hi=hi+Math.imul(ah6,bh5)|0,lo=lo+Math.imul(al5,bl6)|0,mid=(mid=mid+Math.imul(al5,bh6)|0)+Math.imul(ah5,bl6)|0,hi=hi+Math.imul(ah5,bh6)|0,lo=lo+Math.imul(al4,bl7)|0,mid=(mid=mid+Math.imul(al4,bh7)|0)+Math.imul(ah4,bl7)|0,hi=hi+Math.imul(ah4,bh7)|0,lo=lo+Math.imul(al3,bl8)|0,mid=(mid=mid+Math.imul(al3,bh8)|0)+Math.imul(ah3,bl8)|0,hi=hi+Math.imul(ah3,bh8)|0;var w11=(c+(lo=lo+Math.imul(al2,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al2,bh9)|0)+Math.imul(ah2,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah2,bh9)|0)+(mid>>>13)|0)+(w11>>>26)|0,w11&=67108863,lo=Math.imul(al9,bl3),mid=(mid=Math.imul(al9,bh3))+Math.imul(ah9,bl3)|0,hi=Math.imul(ah9,bh3),lo=lo+Math.imul(al8,bl4)|0,mid=(mid=mid+Math.imul(al8,bh4)|0)+Math.imul(ah8,bl4)|0,hi=hi+Math.imul(ah8,bh4)|0,lo=lo+Math.imul(al7,bl5)|0,mid=(mid=mid+Math.imul(al7,bh5)|0)+Math.imul(ah7,bl5)|0,hi=hi+Math.imul(ah7,bh5)|0,lo=lo+Math.imul(al6,bl6)|0,mid=(mid=mid+Math.imul(al6,bh6)|0)+Math.imul(ah6,bl6)|0,hi=hi+Math.imul(ah6,bh6)|0,lo=lo+Math.imul(al5,bl7)|0,mid=(mid=mid+Math.imul(al5,bh7)|0)+Math.imul(ah5,bl7)|0,hi=hi+Math.imul(ah5,bh7)|0,lo=lo+Math.imul(al4,bl8)|0,mid=(mid=mid+Math.imul(al4,bh8)|0)+Math.imul(ah4,bl8)|0,hi=hi+Math.imul(ah4,bh8)|0;var w12=(c+(lo=lo+Math.imul(al3,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al3,bh9)|0)+Math.imul(ah3,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah3,bh9)|0)+(mid>>>13)|0)+(w12>>>26)|0,w12&=67108863,lo=Math.imul(al9,bl4),mid=(mid=Math.imul(al9,bh4))+Math.imul(ah9,bl4)|0,hi=Math.imul(ah9,bh4),lo=lo+Math.imul(al8,bl5)|0,mid=(mid=mid+Math.imul(al8,bh5)|0)+Math.imul(ah8,bl5)|0,hi=hi+Math.imul(ah8,bh5)|0,lo=lo+Math.imul(al7,bl6)|0,mid=(mid=mid+Math.imul(al7,bh6)|0)+Math.imul(ah7,bl6)|0,hi=hi+Math.imul(ah7,bh6)|0,lo=lo+Math.imul(al6,bl7)|0,mid=(mid=mid+Math.imul(al6,bh7)|0)+Math.imul(ah6,bl7)|0,hi=hi+Math.imul(ah6,bh7)|0,lo=lo+Math.imul(al5,bl8)|0,mid=(mid=mid+Math.imul(al5,bh8)|0)+Math.imul(ah5,bl8)|0,hi=hi+Math.imul(ah5,bh8)|0;var w13=(c+(lo=lo+Math.imul(al4,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al4,bh9)|0)+Math.imul(ah4,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah4,bh9)|0)+(mid>>>13)|0)+(w13>>>26)|0,w13&=67108863,lo=Math.imul(al9,bl5),mid=(mid=Math.imul(al9,bh5))+Math.imul(ah9,bl5)|0,hi=Math.imul(ah9,bh5),lo=lo+Math.imul(al8,bl6)|0,mid=(mid=mid+Math.imul(al8,bh6)|0)+Math.imul(ah8,bl6)|0,hi=hi+Math.imul(ah8,bh6)|0,lo=lo+Math.imul(al7,bl7)|0,mid=(mid=mid+Math.imul(al7,bh7)|0)+Math.imul(ah7,bl7)|0,hi=hi+Math.imul(ah7,bh7)|0,lo=lo+Math.imul(al6,bl8)|0,mid=(mid=mid+Math.imul(al6,bh8)|0)+Math.imul(ah6,bl8)|0,hi=hi+Math.imul(ah6,bh8)|0;var w14=(c+(lo=lo+Math.imul(al5,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al5,bh9)|0)+Math.imul(ah5,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah5,bh9)|0)+(mid>>>13)|0)+(w14>>>26)|0,w14&=67108863,lo=Math.imul(al9,bl6),mid=(mid=Math.imul(al9,bh6))+Math.imul(ah9,bl6)|0,hi=Math.imul(ah9,bh6),lo=lo+Math.imul(al8,bl7)|0,mid=(mid=mid+Math.imul(al8,bh7)|0)+Math.imul(ah8,bl7)|0,hi=hi+Math.imul(ah8,bh7)|0,lo=lo+Math.imul(al7,bl8)|0,mid=(mid=mid+Math.imul(al7,bh8)|0)+Math.imul(ah7,bl8)|0,hi=hi+Math.imul(ah7,bh8)|0;var w15=(c+(lo=lo+Math.imul(al6,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al6,bh9)|0)+Math.imul(ah6,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah6,bh9)|0)+(mid>>>13)|0)+(w15>>>26)|0,w15&=67108863,lo=Math.imul(al9,bl7),mid=(mid=Math.imul(al9,bh7))+Math.imul(ah9,bl7)|0,hi=Math.imul(ah9,bh7),lo=lo+Math.imul(al8,bl8)|0,mid=(mid=mid+Math.imul(al8,bh8)|0)+Math.imul(ah8,bl8)|0,hi=hi+Math.imul(ah8,bh8)|0;var w16=(c+(lo=lo+Math.imul(al7,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al7,bh9)|0)+Math.imul(ah7,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah7,bh9)|0)+(mid>>>13)|0)+(w16>>>26)|0,w16&=67108863,lo=Math.imul(al9,bl8),mid=(mid=Math.imul(al9,bh8))+Math.imul(ah9,bl8)|0,hi=Math.imul(ah9,bh8);var w17=(c+(lo=lo+Math.imul(al8,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al8,bh9)|0)+Math.imul(ah8,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah8,bh9)|0)+(mid>>>13)|0)+(w17>>>26)|0,w17&=67108863;var w18=(c+(lo=Math.imul(al9,bl9))|0)+((8191&(mid=(mid=Math.imul(al9,bh9))+Math.imul(ah9,bl9)|0))<<13)|0;return c=((hi=Math.imul(ah9,bh9))+(mid>>>13)|0)+(w18>>>26)|0,w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,0!==c&&(o[19]=c,out.length++),out};function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0;k>>26)|0)>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0!==carry?out.words[k]=carry:out.length--,out._strip()}function jumboMulTo(self,num,out){return bigMulTo(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}Math.imul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function mulTo(num,out){var len=this.length+num.length;return 10===this.length&&10===num.length?comb10MulTo(this,num,out):len<63?smallMulTo(this,num,out):len<1024?bigMulTo(this,num,out):jumboMulTo(this,num,out)},FFTM.prototype.makeRBT=function makeRBT(N){for(var t=new Array(N),l=BN.prototype._countBits(N)-1,i=0;i>=1;return rb},FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>=1)i++;return 1<>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;i>=26,carry+=w/67108864|0,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),isNegNum?this.ineg():this},BN.prototype.muln=function muln(num){return this.clone().imuln(num)},BN.prototype.sqr=function sqr(){return this.mul(this)},BN.prototype.isqr=function isqr(){return this.imul(this.clone())},BN.prototype.pow=function pow(num){var w=function toBitArray(num){for(var w=new Array(num.bitLength()),bit=0;bit>>wbit&1}return w}(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i=0);var i,r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r;if(0!==r){var carry=0;for(i=0;i>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;i>=0;i--)this.words[i+s]=this.words[i];for(i=0;i=0),h=hint?(hint-hint%26)/26:0;var r=bits%26,s=Math.min((bits-r)/26,this.length),mask=67108863^67108863>>>r<s)for(this.length-=s,i=0;i=0&&(0!==carry||i>=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&0!==carry&&(maskedWords.words[maskedWords.length++]=carry),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},BN.prototype.ishrn=function ishrn(bits,hint,extended){return assert(0===this.negative),this.iushrn(bits,hint,extended)},BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function testn(bit){assert("number"==typeof bit&&bit>=0);var r=bit%26,s=(bit-r)/26,q=1<=0);var r=bits%26,s=(bits-r)/26;if(assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!==r&&s++,this.length=Math.min(s,this.length),0!==r){var mask=67108863^67108863>>>r<=67108864;i++)this.words[i]-=67108864,i===this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=Math.max(this.length,i+1),this},BN.prototype.isubn=function isubn(num){if(assert("number"==typeof num),assert(num<67108864),num<0)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i>26)-(right/67108864|0),this.words[i+shift]=67108863&w}for(;i>26,this.words[i+shift]=67108863&w;if(0===carry)return this._strip();for(assert(-1===carry),carry=0,i=0;i>26,this.words[i]=67108863&w;return this.negative=1,this._strip()},BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=(this.length,num.length),a=this.clone(),b=num,bhi=0|b.words[b.length-1];0!==(shift=26-this._countBits(bhi))&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var q,m=a.length-b.length;if("mod"!==mode){(q=new BN(null)).length=m+1,q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=67108864*(0|a.words[b.length+j])+(0|a.words[b.length+j-1]);for(qj=Math.min(qj/bhi|0,67108863),a._ishlnsubmul(b,qj,j);0!==a.negative;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q._strip(),a._strip(),"div"!==mode&&0!==shift&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function divmod(num,mode,positive){return assert(!num.isZero()),this.isZero()?{div:new BN(0),mod:new BN(0)}:0!==this.negative&&0===num.negative?(res=this.neg().divmod(num,mode),"mod"!==mode&&(div=res.div.neg()),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.iadd(num)),{div,mod}):0===this.negative&&0!==num.negative?(res=this.divmod(num.neg(),mode),"mod"!==mode&&(div=res.div.neg()),{div,mod:res.mod}):0!=(this.negative&num.negative)?(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod}):num.length>this.length||this.cmp(num)<0?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modrn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modrn(num.words[0]))}:this._wordDiv(num,mode);var div,mod,res},BN.prototype.div=function div(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function mod(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function umod(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0!==dm.div.negative?dm.mod.isub(num):dm.mod,half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return cmp<0||1===r2&&0===cmp?dm.div:0!==dm.div.negative?dm.div.isubn(1):dm.div.iaddn(1)},BN.prototype.modrn=function modrn(num){var isNegNum=num<0;isNegNum&&(num=-num),assert(num<=67108863);for(var p=(1<<26)%num,acc=0,i=this.length-1;i>=0;i--)acc=(p*acc+(0|this.words[i]))%num;return isNegNum?-acc:acc},BN.prototype.modn=function modn(num){return this.modrn(num)},BN.prototype.idivn=function idivn(num){var isNegNum=num<0;isNegNum&&(num=-num),assert(num<=67108863);for(var carry=0,i=this.length-1;i>=0;i--){var w=(0|this.words[i])+67108864*carry;this.words[i]=w/num|0,carry=w%num}return this._strip(),isNegNum?this.ineg():this},BN.prototype.divn=function divn(num){return this.clone().idivn(num)},BN.prototype.egcd=function egcd(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0!==x.negative?x.umod(p):x.clone();for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0==(x.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(x.iushrn(i);i-- >0;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;0==(y.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(y.iushrn(j);j-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);x.cmp(y)>=0?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function _invmp(p){assert(0===p.negative),assert(!p.isZero());var a=this,b=p.clone();a=0!==a.negative?a.umod(p):a.clone();for(var res,x1=new BN(1),x2=new BN(0),delta=b.clone();a.cmpn(1)>0&&b.cmpn(1)>0;){for(var i=0,im=1;0==(a.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(a.iushrn(i);i-- >0;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;0==(b.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(b.iushrn(j);j-- >0;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);a.cmp(b)>=0?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}return(res=0===a.cmpn(1)?x1:x2).cmpn(0)<0&&res.iadd(p),res},BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);for(;;){for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(r<0){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}return b.iushln(shift)},BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function isEven(){return 0==(1&this.words[0])},BN.prototype.isOdd=function isOdd(){return 1==(1&this.words[0])},BN.prototype.andln=function andln(num){return this.words[0]&num},BN.prototype.bincn=function bincn(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<>>26,w&=67108863,this.words[i]=w}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function isZero(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function cmpn(num){var res,negative=num<0;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;if(this._strip(),this.length>1)res=1;else{negative&&(num=-num),assert(num<=67108863,"Number is too big");var w=0|this.words[0];res=w===num?0:wnum.length)return 1;if(this.length=0;i--){var a=0|this.words[i],b=0|num.words[i];if(a!==b){ab&&(res=1);break}}return res},BN.prototype.gtn=function gtn(num){return 1===this.cmpn(num)},BN.prototype.gt=function gt(num){return 1===this.cmp(num)},BN.prototype.gten=function gten(num){return this.cmpn(num)>=0},BN.prototype.gte=function gte(num){return this.cmp(num)>=0},BN.prototype.ltn=function ltn(num){return-1===this.cmpn(num)},BN.prototype.lt=function lt(num){return-1===this.cmp(num)},BN.prototype.lten=function lten(num){return this.cmpn(num)<=0},BN.prototype.lte=function lte(num){return this.cmp(num)<=0},BN.prototype.eqn=function eqn(num){return 0===this.cmpn(num)},BN.prototype.eq=function eq(num){return 0===this.cmp(num)},BN.red=function red(num){return new Red(num)},BN.prototype.toRed=function toRed(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function fromRed(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function _forceRed(ctx){return this.red=ctx,this},BN.prototype.forceRed=function forceRed(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function redAdd(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function redIAdd(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function redSub(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function redISub(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function redShl(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function redMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function redIMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function redSqr(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function redISqr(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function redSqrt(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function redInvm(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function redNeg(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function redPow(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);return tmp.words=new Array(Math.ceil(this.n/13)),tmp},MPrime.prototype.ireduce=function ireduce(num){var rlen,r=num;do{this.split(r,this.tmp),rlen=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(rlen>this.n);var cmp=rlen0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)},inherits(K256,MPrime),K256.prototype.split=function split(input,output){for(var outLen=Math.min(input.length,9),i=0;i>>22,prev=next}prev>>>=22,input.words[i-10]=prev,0===prev&&input.length>10?input.length-=10:input.length-=9},K256.prototype.imulK=function imulK(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0;i>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else{if("p25519"!==name)throw new Error("Unknown prime "+name);prime=new P25519}return primes[name]=prime,prime},Red.prototype._verify1=function _verify1(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function _verify2(a,b){assert(0==(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function imod(a){return this.prime?this.prime.ireduce(a)._forceRed(this):(move(a,a.umod(this.m)._forceRed(this)),a)},Red.prototype.neg=function neg(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);return res.cmp(this.m)>=0&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);return res.cmp(this.m)>=0&&res.isub(this.m),res},Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);return res.cmpn(0)<0&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);return res.cmpn(0)<0&&res.iadd(this.m),res},Red.prototype.shl=function shl(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function imul(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function mul(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())},Red.prototype.sqr=function sqr(a){return this.mul(a,a)},Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(mod3%2==1),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i=0;i--){for(var word=num.words[i],j=start-1;j>=0;j--){var bit=word>>j&1;res!==wnd[0]&&(res=this.sqr(res)),0!==bit||0!==current?(current<<=1,current|=bit,(4===++currentLen||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)):currentLen=0}start=26}return res},Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();return res.red=null,res},BN.mont=function mont(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function invm(a){return this.imod(a._invmp(this.m).mul(this.r2))._forceRed(this)}}(module=__webpack_require__.nmd(module),this)},6042:(module,__unused_webpack_exports,__webpack_require__)=>{module.exports=__webpack_require__(5207)},4743:(module,__unused_webpack_exports,__webpack_require__)=>{var Buffer=__webpack_require__(9509).Buffer,createHash=__webpack_require__(3482),stream=__webpack_require__(8473),inherits=__webpack_require__(5717),sign=__webpack_require__(2957),verify=__webpack_require__(7753),algorithms=__webpack_require__(5207);function Sign(algorithm){stream.Writable.call(this);var data=algorithms[algorithm];if(!data)throw new Error("Unknown message digest");this._hashType=data.hash,this._hash=createHash(data.hash),this._tag=data.id,this._signType=data.sign}function Verify(algorithm){stream.Writable.call(this);var data=algorithms[algorithm];if(!data)throw new Error("Unknown message digest");this._hash=createHash(data.hash),this._tag=data.id,this._signType=data.sign}function createSign(algorithm){return new Sign(algorithm)}function createVerify(algorithm){return new Verify(algorithm)}Object.keys(algorithms).forEach((function(key){algorithms[key].id=Buffer.from(algorithms[key].id,"hex"),algorithms[key.toLowerCase()]=algorithms[key]})),inherits(Sign,stream.Writable),Sign.prototype._write=function _write(data,_,done){this._hash.update(data),done()},Sign.prototype.update=function update(data,enc){return"string"==typeof data&&(data=Buffer.from(data,enc)),this._hash.update(data),this},Sign.prototype.sign=function signMethod(key,enc){this.end();var hash=this._hash.digest(),sig=sign(hash,key,this._hashType,this._signType,this._tag);return enc?sig.toString(enc):sig},inherits(Verify,stream.Writable),Verify.prototype._write=function _write(data,_,done){this._hash.update(data),done()},Verify.prototype.update=function update(data,enc){return"string"==typeof data&&(data=Buffer.from(data,enc)),this._hash.update(data),this},Verify.prototype.verify=function verifyMethod(key,sig,enc){"string"==typeof sig&&(sig=Buffer.from(sig,enc)),this.end();var hash=this._hash.digest();return verify(sig,hash,key,this._signType,this._tag)},module.exports={Sign:createSign,Verify:createVerify,createSign,createVerify}},2957:(module,__unused_webpack_exports,__webpack_require__)=>{var Buffer=__webpack_require__(9509).Buffer,createHmac=__webpack_require__(8355),crt=__webpack_require__(3663),EC=__webpack_require__(6266).ec,BN=__webpack_require__(8815),parseKeys=__webpack_require__(980),curves=__webpack_require__(1308);function getKey(x,q,hash,algo){if((x=Buffer.from(x.toArray())).length0&&bits.ishrn(shift),bits}function makeKey(q,kv,algo){var t,k;do{for(t=Buffer.alloc(0);8*t.length{var Buffer=__webpack_require__(9509).Buffer,BN=__webpack_require__(8815),EC=__webpack_require__(6266).ec,parseKeys=__webpack_require__(980),curves=__webpack_require__(1308);function checkValue(b,q){if(b.cmpn(0)<=0)throw new Error("invalid sig");if(b.cmp(q)>=q)throw new Error("invalid sig")}module.exports=function verify(sig,hash,key,signType,tag){var pub=parseKeys(key);if("ec"===pub.type){if("ecdsa"!==signType&&"ecdsa/rsa"!==signType)throw new Error("wrong public key type");return function ecVerify(sig,hash,pub){var curveId=curves[pub.data.algorithm.curve.join(".")];if(!curveId)throw new Error("unknown curve "+pub.data.algorithm.curve.join("."));var curve=new EC(curveId),pubkey=pub.data.subjectPrivateKey.data;return curve.verify(hash,sig,pubkey)}(sig,hash,pub)}if("dsa"===pub.type){if("dsa"!==signType)throw new Error("wrong public key type");return function dsaVerify(sig,hash,pub){var p=pub.data.p,q=pub.data.q,g=pub.data.g,y=pub.data.pub_key,unpacked=parseKeys.signature.decode(sig,"der"),s=unpacked.s,r=unpacked.r;checkValue(s,q),checkValue(r,q);var montp=BN.mont(p),w=s.invm(q);return 0===g.toRed(montp).redPow(new BN(hash).mul(w).mod(q)).fromRed().mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()).mod(p).mod(q).cmp(r)}(sig,hash,pub)}if("rsa"!==signType&&"ecdsa/rsa"!==signType)throw new Error("wrong public key type");hash=Buffer.concat([tag,hash]);for(var len=pub.modulus.byteLength(),pad=[1],padNum=0;hash.length+pad.length+2=48&&c<=57?c-48:c>=65&&c<=70?c-55:c>=97&&c<=102?c-87:void assert(!1,"Invalid character in "+string)}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return index-1>=lowerBound&&(r|=parseHex4Bits(string,index-1)<<4),r}function parseBase(str,start,end,mul){for(var r=0,b=0,len=Math.min(str.length,end),i=start;i=49?c-49+10:c>=17?c-17+10:c,assert(c>=0&&b0?left:right},BN.min=function min(left,right){return left.cmp(right)<0?left:right},BN.prototype._init=function init(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&base>=2&&base<=36);var start=0;"-"===(number=number.toString().replace(/\s+/g,""))[0]&&(start++,this.negative=1),start=0;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=w<>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);return this._strip()},BN.prototype._parseHex=function _parseHex(number,start,endian){this.length=Math.ceil((number.length-start)/6),this.words=new Array(this.length);for(var i=0;i=start;i-=2)w=parseHexByte(number,start,i)<=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;else for(i=(number.length-start)%2==0?start+1:start;i=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;this._strip()},BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;limbPow*=base)limbLen++;limbLen--,limbPow=limbPow/base|0;for(var total=number.length-start,mod=total%limbLen,end=Math.min(total,total-mod)+start,word=0,i=start;i1&&0===this.words[this.length-1];)this.length--;return this._normSign()},BN.prototype._normSign=function _normSign(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{BN.prototype[Symbol.for("nodejs.util.inspect.custom")]=inspect}catch(e){BN.prototype.inspect=inspect}else BN.prototype.inspect=inspect;function inspect(){return(this.red?""}var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function toString(base,padding){var out;if(padding=0|padding||1,16===(base=base||10)||"hex"===base){out="";for(var off=0,carry=0,i=0;i>>24-off&16777215)||i!==this.length-1?zeros[6-word.length]+word+out:word+out,(off+=2)>=26&&(off-=26,i--)}for(0!==carry&&(out=carry.toString(16)+out);out.length%padding!=0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&base>=2&&base<=36){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modrn(groupBase).toString(base);out=(c=c.idivn(groupBase)).isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);out.length%padding!=0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function toNumber(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:this.length>2&&assert(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-ret:ret},BN.prototype.toJSON=function toJSON(){return this.toString(16,2)},Buffer&&(BN.prototype.toBuffer=function toBuffer(endian,length){return this.toArrayLike(Buffer,endian,length)}),BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)};function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=self.length+num.length|0;out.length=len,len=len-1|0;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=r/67108864|0;out.words[0]=lo;for(var k=1;k>>26,rword=67108863&carry,maxJ=Math.min(k,num.length-1),j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j|0;ncarry+=(r=(a=0|self.words[i])*(b=0|num.words[j])+rword)/67108864|0,rword=67108863&r}out.words[k]=0|rword,carry=0|ncarry}return 0!==carry?out.words[k]=0|carry:out.length--,out._strip()}BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){this._strip();var byteLength=this.byteLength(),reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length"),assert(reqLength>0,"Requested array length <= 0");var res=function allocate(ArrayType,size){return ArrayType.allocUnsafe?ArrayType.allocUnsafe(size):new ArrayType(size)}(ArrayType,reqLength);return this["_toArrayLike"+("le"===endian?"LE":"BE")](res,byteLength),res},BN.prototype._toArrayLikeLE=function _toArrayLikeLE(res,byteLength){for(var position=0,carry=0,i=0,shift=0;i>8&255),position>16&255),6===shift?(position>24&255),carry=0,shift=0):(carry=word>>>24,shift+=2)}if(position=0&&(res[position--]=word>>8&255),position>=0&&(res[position--]=word>>16&255),6===shift?(position>=0&&(res[position--]=word>>24&255),carry=0,shift=0):(carry=word>>>24,shift+=2)}if(position>=0)for(res[position--]=carry;position>=0;)res[position--]=0},Math.clz32?BN.prototype._countBits=function _countBits(w){return 32-Math.clz32(w)}:BN.prototype._countBits=function _countBits(w){var t=w,r=0;return t>=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function _zeroBits(w){if(0===w)return 26;var t=w,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;for(var r=0,i=0;inum.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function uor(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function iuand(num){var b;b=this.length>num.length?num:this;for(var i=0;inum.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function uand(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function iuxor(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;inum.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function uxor(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function inotn(width){assert("number"==typeof width&&width>=0);var bytesNeeded=0|Math.ceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),bitsLeft>0&&bytesNeeded--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this._strip()},BN.prototype.notn=function notn(width){return this.clone().inotn(width)},BN.prototype.setn=function setn(bit,val){assert("number"==typeof bit&&bit>=0);var off=bit/26|0,wbit=bit%26;return this._expand(off+1),this.words[off]=val?this.words[off]|1<num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>>26;for(;0!==carry&&i>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;inum.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function isub(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var a,b,cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;cmp>0?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>26,this.words[i]=67108863&r;for(;0!==carry&&i>26,this.words[i]=67108863&r;if(0===carry&&i>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13;out.negative=self.negative^num.negative,out.length=19;var w0=(c+(lo=Math.imul(al0,bl0))|0)+((8191&(mid=(mid=Math.imul(al0,bh0))+Math.imul(ah0,bl0)|0))<<13)|0;c=((hi=Math.imul(ah0,bh0))+(mid>>>13)|0)+(w0>>>26)|0,w0&=67108863,lo=Math.imul(al1,bl0),mid=(mid=Math.imul(al1,bh0))+Math.imul(ah1,bl0)|0,hi=Math.imul(ah1,bh0);var w1=(c+(lo=lo+Math.imul(al0,bl1)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh1)|0)+Math.imul(ah0,bl1)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh1)|0)+(mid>>>13)|0)+(w1>>>26)|0,w1&=67108863,lo=Math.imul(al2,bl0),mid=(mid=Math.imul(al2,bh0))+Math.imul(ah2,bl0)|0,hi=Math.imul(ah2,bh0),lo=lo+Math.imul(al1,bl1)|0,mid=(mid=mid+Math.imul(al1,bh1)|0)+Math.imul(ah1,bl1)|0,hi=hi+Math.imul(ah1,bh1)|0;var w2=(c+(lo=lo+Math.imul(al0,bl2)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh2)|0)+Math.imul(ah0,bl2)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh2)|0)+(mid>>>13)|0)+(w2>>>26)|0,w2&=67108863,lo=Math.imul(al3,bl0),mid=(mid=Math.imul(al3,bh0))+Math.imul(ah3,bl0)|0,hi=Math.imul(ah3,bh0),lo=lo+Math.imul(al2,bl1)|0,mid=(mid=mid+Math.imul(al2,bh1)|0)+Math.imul(ah2,bl1)|0,hi=hi+Math.imul(ah2,bh1)|0,lo=lo+Math.imul(al1,bl2)|0,mid=(mid=mid+Math.imul(al1,bh2)|0)+Math.imul(ah1,bl2)|0,hi=hi+Math.imul(ah1,bh2)|0;var w3=(c+(lo=lo+Math.imul(al0,bl3)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh3)|0)+Math.imul(ah0,bl3)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh3)|0)+(mid>>>13)|0)+(w3>>>26)|0,w3&=67108863,lo=Math.imul(al4,bl0),mid=(mid=Math.imul(al4,bh0))+Math.imul(ah4,bl0)|0,hi=Math.imul(ah4,bh0),lo=lo+Math.imul(al3,bl1)|0,mid=(mid=mid+Math.imul(al3,bh1)|0)+Math.imul(ah3,bl1)|0,hi=hi+Math.imul(ah3,bh1)|0,lo=lo+Math.imul(al2,bl2)|0,mid=(mid=mid+Math.imul(al2,bh2)|0)+Math.imul(ah2,bl2)|0,hi=hi+Math.imul(ah2,bh2)|0,lo=lo+Math.imul(al1,bl3)|0,mid=(mid=mid+Math.imul(al1,bh3)|0)+Math.imul(ah1,bl3)|0,hi=hi+Math.imul(ah1,bh3)|0;var w4=(c+(lo=lo+Math.imul(al0,bl4)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh4)|0)+Math.imul(ah0,bl4)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh4)|0)+(mid>>>13)|0)+(w4>>>26)|0,w4&=67108863,lo=Math.imul(al5,bl0),mid=(mid=Math.imul(al5,bh0))+Math.imul(ah5,bl0)|0,hi=Math.imul(ah5,bh0),lo=lo+Math.imul(al4,bl1)|0,mid=(mid=mid+Math.imul(al4,bh1)|0)+Math.imul(ah4,bl1)|0,hi=hi+Math.imul(ah4,bh1)|0,lo=lo+Math.imul(al3,bl2)|0,mid=(mid=mid+Math.imul(al3,bh2)|0)+Math.imul(ah3,bl2)|0,hi=hi+Math.imul(ah3,bh2)|0,lo=lo+Math.imul(al2,bl3)|0,mid=(mid=mid+Math.imul(al2,bh3)|0)+Math.imul(ah2,bl3)|0,hi=hi+Math.imul(ah2,bh3)|0,lo=lo+Math.imul(al1,bl4)|0,mid=(mid=mid+Math.imul(al1,bh4)|0)+Math.imul(ah1,bl4)|0,hi=hi+Math.imul(ah1,bh4)|0;var w5=(c+(lo=lo+Math.imul(al0,bl5)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh5)|0)+Math.imul(ah0,bl5)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh5)|0)+(mid>>>13)|0)+(w5>>>26)|0,w5&=67108863,lo=Math.imul(al6,bl0),mid=(mid=Math.imul(al6,bh0))+Math.imul(ah6,bl0)|0,hi=Math.imul(ah6,bh0),lo=lo+Math.imul(al5,bl1)|0,mid=(mid=mid+Math.imul(al5,bh1)|0)+Math.imul(ah5,bl1)|0,hi=hi+Math.imul(ah5,bh1)|0,lo=lo+Math.imul(al4,bl2)|0,mid=(mid=mid+Math.imul(al4,bh2)|0)+Math.imul(ah4,bl2)|0,hi=hi+Math.imul(ah4,bh2)|0,lo=lo+Math.imul(al3,bl3)|0,mid=(mid=mid+Math.imul(al3,bh3)|0)+Math.imul(ah3,bl3)|0,hi=hi+Math.imul(ah3,bh3)|0,lo=lo+Math.imul(al2,bl4)|0,mid=(mid=mid+Math.imul(al2,bh4)|0)+Math.imul(ah2,bl4)|0,hi=hi+Math.imul(ah2,bh4)|0,lo=lo+Math.imul(al1,bl5)|0,mid=(mid=mid+Math.imul(al1,bh5)|0)+Math.imul(ah1,bl5)|0,hi=hi+Math.imul(ah1,bh5)|0;var w6=(c+(lo=lo+Math.imul(al0,bl6)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh6)|0)+Math.imul(ah0,bl6)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh6)|0)+(mid>>>13)|0)+(w6>>>26)|0,w6&=67108863,lo=Math.imul(al7,bl0),mid=(mid=Math.imul(al7,bh0))+Math.imul(ah7,bl0)|0,hi=Math.imul(ah7,bh0),lo=lo+Math.imul(al6,bl1)|0,mid=(mid=mid+Math.imul(al6,bh1)|0)+Math.imul(ah6,bl1)|0,hi=hi+Math.imul(ah6,bh1)|0,lo=lo+Math.imul(al5,bl2)|0,mid=(mid=mid+Math.imul(al5,bh2)|0)+Math.imul(ah5,bl2)|0,hi=hi+Math.imul(ah5,bh2)|0,lo=lo+Math.imul(al4,bl3)|0,mid=(mid=mid+Math.imul(al4,bh3)|0)+Math.imul(ah4,bl3)|0,hi=hi+Math.imul(ah4,bh3)|0,lo=lo+Math.imul(al3,bl4)|0,mid=(mid=mid+Math.imul(al3,bh4)|0)+Math.imul(ah3,bl4)|0,hi=hi+Math.imul(ah3,bh4)|0,lo=lo+Math.imul(al2,bl5)|0,mid=(mid=mid+Math.imul(al2,bh5)|0)+Math.imul(ah2,bl5)|0,hi=hi+Math.imul(ah2,bh5)|0,lo=lo+Math.imul(al1,bl6)|0,mid=(mid=mid+Math.imul(al1,bh6)|0)+Math.imul(ah1,bl6)|0,hi=hi+Math.imul(ah1,bh6)|0;var w7=(c+(lo=lo+Math.imul(al0,bl7)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh7)|0)+Math.imul(ah0,bl7)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh7)|0)+(mid>>>13)|0)+(w7>>>26)|0,w7&=67108863,lo=Math.imul(al8,bl0),mid=(mid=Math.imul(al8,bh0))+Math.imul(ah8,bl0)|0,hi=Math.imul(ah8,bh0),lo=lo+Math.imul(al7,bl1)|0,mid=(mid=mid+Math.imul(al7,bh1)|0)+Math.imul(ah7,bl1)|0,hi=hi+Math.imul(ah7,bh1)|0,lo=lo+Math.imul(al6,bl2)|0,mid=(mid=mid+Math.imul(al6,bh2)|0)+Math.imul(ah6,bl2)|0,hi=hi+Math.imul(ah6,bh2)|0,lo=lo+Math.imul(al5,bl3)|0,mid=(mid=mid+Math.imul(al5,bh3)|0)+Math.imul(ah5,bl3)|0,hi=hi+Math.imul(ah5,bh3)|0,lo=lo+Math.imul(al4,bl4)|0,mid=(mid=mid+Math.imul(al4,bh4)|0)+Math.imul(ah4,bl4)|0,hi=hi+Math.imul(ah4,bh4)|0,lo=lo+Math.imul(al3,bl5)|0,mid=(mid=mid+Math.imul(al3,bh5)|0)+Math.imul(ah3,bl5)|0,hi=hi+Math.imul(ah3,bh5)|0,lo=lo+Math.imul(al2,bl6)|0,mid=(mid=mid+Math.imul(al2,bh6)|0)+Math.imul(ah2,bl6)|0,hi=hi+Math.imul(ah2,bh6)|0,lo=lo+Math.imul(al1,bl7)|0,mid=(mid=mid+Math.imul(al1,bh7)|0)+Math.imul(ah1,bl7)|0,hi=hi+Math.imul(ah1,bh7)|0;var w8=(c+(lo=lo+Math.imul(al0,bl8)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh8)|0)+Math.imul(ah0,bl8)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh8)|0)+(mid>>>13)|0)+(w8>>>26)|0,w8&=67108863,lo=Math.imul(al9,bl0),mid=(mid=Math.imul(al9,bh0))+Math.imul(ah9,bl0)|0,hi=Math.imul(ah9,bh0),lo=lo+Math.imul(al8,bl1)|0,mid=(mid=mid+Math.imul(al8,bh1)|0)+Math.imul(ah8,bl1)|0,hi=hi+Math.imul(ah8,bh1)|0,lo=lo+Math.imul(al7,bl2)|0,mid=(mid=mid+Math.imul(al7,bh2)|0)+Math.imul(ah7,bl2)|0,hi=hi+Math.imul(ah7,bh2)|0,lo=lo+Math.imul(al6,bl3)|0,mid=(mid=mid+Math.imul(al6,bh3)|0)+Math.imul(ah6,bl3)|0,hi=hi+Math.imul(ah6,bh3)|0,lo=lo+Math.imul(al5,bl4)|0,mid=(mid=mid+Math.imul(al5,bh4)|0)+Math.imul(ah5,bl4)|0,hi=hi+Math.imul(ah5,bh4)|0,lo=lo+Math.imul(al4,bl5)|0,mid=(mid=mid+Math.imul(al4,bh5)|0)+Math.imul(ah4,bl5)|0,hi=hi+Math.imul(ah4,bh5)|0,lo=lo+Math.imul(al3,bl6)|0,mid=(mid=mid+Math.imul(al3,bh6)|0)+Math.imul(ah3,bl6)|0,hi=hi+Math.imul(ah3,bh6)|0,lo=lo+Math.imul(al2,bl7)|0,mid=(mid=mid+Math.imul(al2,bh7)|0)+Math.imul(ah2,bl7)|0,hi=hi+Math.imul(ah2,bh7)|0,lo=lo+Math.imul(al1,bl8)|0,mid=(mid=mid+Math.imul(al1,bh8)|0)+Math.imul(ah1,bl8)|0,hi=hi+Math.imul(ah1,bh8)|0;var w9=(c+(lo=lo+Math.imul(al0,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh9)|0)+Math.imul(ah0,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh9)|0)+(mid>>>13)|0)+(w9>>>26)|0,w9&=67108863,lo=Math.imul(al9,bl1),mid=(mid=Math.imul(al9,bh1))+Math.imul(ah9,bl1)|0,hi=Math.imul(ah9,bh1),lo=lo+Math.imul(al8,bl2)|0,mid=(mid=mid+Math.imul(al8,bh2)|0)+Math.imul(ah8,bl2)|0,hi=hi+Math.imul(ah8,bh2)|0,lo=lo+Math.imul(al7,bl3)|0,mid=(mid=mid+Math.imul(al7,bh3)|0)+Math.imul(ah7,bl3)|0,hi=hi+Math.imul(ah7,bh3)|0,lo=lo+Math.imul(al6,bl4)|0,mid=(mid=mid+Math.imul(al6,bh4)|0)+Math.imul(ah6,bl4)|0,hi=hi+Math.imul(ah6,bh4)|0,lo=lo+Math.imul(al5,bl5)|0,mid=(mid=mid+Math.imul(al5,bh5)|0)+Math.imul(ah5,bl5)|0,hi=hi+Math.imul(ah5,bh5)|0,lo=lo+Math.imul(al4,bl6)|0,mid=(mid=mid+Math.imul(al4,bh6)|0)+Math.imul(ah4,bl6)|0,hi=hi+Math.imul(ah4,bh6)|0,lo=lo+Math.imul(al3,bl7)|0,mid=(mid=mid+Math.imul(al3,bh7)|0)+Math.imul(ah3,bl7)|0,hi=hi+Math.imul(ah3,bh7)|0,lo=lo+Math.imul(al2,bl8)|0,mid=(mid=mid+Math.imul(al2,bh8)|0)+Math.imul(ah2,bl8)|0,hi=hi+Math.imul(ah2,bh8)|0;var w10=(c+(lo=lo+Math.imul(al1,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al1,bh9)|0)+Math.imul(ah1,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah1,bh9)|0)+(mid>>>13)|0)+(w10>>>26)|0,w10&=67108863,lo=Math.imul(al9,bl2),mid=(mid=Math.imul(al9,bh2))+Math.imul(ah9,bl2)|0,hi=Math.imul(ah9,bh2),lo=lo+Math.imul(al8,bl3)|0,mid=(mid=mid+Math.imul(al8,bh3)|0)+Math.imul(ah8,bl3)|0,hi=hi+Math.imul(ah8,bh3)|0,lo=lo+Math.imul(al7,bl4)|0,mid=(mid=mid+Math.imul(al7,bh4)|0)+Math.imul(ah7,bl4)|0,hi=hi+Math.imul(ah7,bh4)|0,lo=lo+Math.imul(al6,bl5)|0,mid=(mid=mid+Math.imul(al6,bh5)|0)+Math.imul(ah6,bl5)|0,hi=hi+Math.imul(ah6,bh5)|0,lo=lo+Math.imul(al5,bl6)|0,mid=(mid=mid+Math.imul(al5,bh6)|0)+Math.imul(ah5,bl6)|0,hi=hi+Math.imul(ah5,bh6)|0,lo=lo+Math.imul(al4,bl7)|0,mid=(mid=mid+Math.imul(al4,bh7)|0)+Math.imul(ah4,bl7)|0,hi=hi+Math.imul(ah4,bh7)|0,lo=lo+Math.imul(al3,bl8)|0,mid=(mid=mid+Math.imul(al3,bh8)|0)+Math.imul(ah3,bl8)|0,hi=hi+Math.imul(ah3,bh8)|0;var w11=(c+(lo=lo+Math.imul(al2,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al2,bh9)|0)+Math.imul(ah2,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah2,bh9)|0)+(mid>>>13)|0)+(w11>>>26)|0,w11&=67108863,lo=Math.imul(al9,bl3),mid=(mid=Math.imul(al9,bh3))+Math.imul(ah9,bl3)|0,hi=Math.imul(ah9,bh3),lo=lo+Math.imul(al8,bl4)|0,mid=(mid=mid+Math.imul(al8,bh4)|0)+Math.imul(ah8,bl4)|0,hi=hi+Math.imul(ah8,bh4)|0,lo=lo+Math.imul(al7,bl5)|0,mid=(mid=mid+Math.imul(al7,bh5)|0)+Math.imul(ah7,bl5)|0,hi=hi+Math.imul(ah7,bh5)|0,lo=lo+Math.imul(al6,bl6)|0,mid=(mid=mid+Math.imul(al6,bh6)|0)+Math.imul(ah6,bl6)|0,hi=hi+Math.imul(ah6,bh6)|0,lo=lo+Math.imul(al5,bl7)|0,mid=(mid=mid+Math.imul(al5,bh7)|0)+Math.imul(ah5,bl7)|0,hi=hi+Math.imul(ah5,bh7)|0,lo=lo+Math.imul(al4,bl8)|0,mid=(mid=mid+Math.imul(al4,bh8)|0)+Math.imul(ah4,bl8)|0,hi=hi+Math.imul(ah4,bh8)|0;var w12=(c+(lo=lo+Math.imul(al3,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al3,bh9)|0)+Math.imul(ah3,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah3,bh9)|0)+(mid>>>13)|0)+(w12>>>26)|0,w12&=67108863,lo=Math.imul(al9,bl4),mid=(mid=Math.imul(al9,bh4))+Math.imul(ah9,bl4)|0,hi=Math.imul(ah9,bh4),lo=lo+Math.imul(al8,bl5)|0,mid=(mid=mid+Math.imul(al8,bh5)|0)+Math.imul(ah8,bl5)|0,hi=hi+Math.imul(ah8,bh5)|0,lo=lo+Math.imul(al7,bl6)|0,mid=(mid=mid+Math.imul(al7,bh6)|0)+Math.imul(ah7,bl6)|0,hi=hi+Math.imul(ah7,bh6)|0,lo=lo+Math.imul(al6,bl7)|0,mid=(mid=mid+Math.imul(al6,bh7)|0)+Math.imul(ah6,bl7)|0,hi=hi+Math.imul(ah6,bh7)|0,lo=lo+Math.imul(al5,bl8)|0,mid=(mid=mid+Math.imul(al5,bh8)|0)+Math.imul(ah5,bl8)|0,hi=hi+Math.imul(ah5,bh8)|0;var w13=(c+(lo=lo+Math.imul(al4,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al4,bh9)|0)+Math.imul(ah4,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah4,bh9)|0)+(mid>>>13)|0)+(w13>>>26)|0,w13&=67108863,lo=Math.imul(al9,bl5),mid=(mid=Math.imul(al9,bh5))+Math.imul(ah9,bl5)|0,hi=Math.imul(ah9,bh5),lo=lo+Math.imul(al8,bl6)|0,mid=(mid=mid+Math.imul(al8,bh6)|0)+Math.imul(ah8,bl6)|0,hi=hi+Math.imul(ah8,bh6)|0,lo=lo+Math.imul(al7,bl7)|0,mid=(mid=mid+Math.imul(al7,bh7)|0)+Math.imul(ah7,bl7)|0,hi=hi+Math.imul(ah7,bh7)|0,lo=lo+Math.imul(al6,bl8)|0,mid=(mid=mid+Math.imul(al6,bh8)|0)+Math.imul(ah6,bl8)|0,hi=hi+Math.imul(ah6,bh8)|0;var w14=(c+(lo=lo+Math.imul(al5,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al5,bh9)|0)+Math.imul(ah5,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah5,bh9)|0)+(mid>>>13)|0)+(w14>>>26)|0,w14&=67108863,lo=Math.imul(al9,bl6),mid=(mid=Math.imul(al9,bh6))+Math.imul(ah9,bl6)|0,hi=Math.imul(ah9,bh6),lo=lo+Math.imul(al8,bl7)|0,mid=(mid=mid+Math.imul(al8,bh7)|0)+Math.imul(ah8,bl7)|0,hi=hi+Math.imul(ah8,bh7)|0,lo=lo+Math.imul(al7,bl8)|0,mid=(mid=mid+Math.imul(al7,bh8)|0)+Math.imul(ah7,bl8)|0,hi=hi+Math.imul(ah7,bh8)|0;var w15=(c+(lo=lo+Math.imul(al6,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al6,bh9)|0)+Math.imul(ah6,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah6,bh9)|0)+(mid>>>13)|0)+(w15>>>26)|0,w15&=67108863,lo=Math.imul(al9,bl7),mid=(mid=Math.imul(al9,bh7))+Math.imul(ah9,bl7)|0,hi=Math.imul(ah9,bh7),lo=lo+Math.imul(al8,bl8)|0,mid=(mid=mid+Math.imul(al8,bh8)|0)+Math.imul(ah8,bl8)|0,hi=hi+Math.imul(ah8,bh8)|0;var w16=(c+(lo=lo+Math.imul(al7,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al7,bh9)|0)+Math.imul(ah7,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah7,bh9)|0)+(mid>>>13)|0)+(w16>>>26)|0,w16&=67108863,lo=Math.imul(al9,bl8),mid=(mid=Math.imul(al9,bh8))+Math.imul(ah9,bl8)|0,hi=Math.imul(ah9,bh8);var w17=(c+(lo=lo+Math.imul(al8,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al8,bh9)|0)+Math.imul(ah8,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah8,bh9)|0)+(mid>>>13)|0)+(w17>>>26)|0,w17&=67108863;var w18=(c+(lo=Math.imul(al9,bl9))|0)+((8191&(mid=(mid=Math.imul(al9,bh9))+Math.imul(ah9,bl9)|0))<<13)|0;return c=((hi=Math.imul(ah9,bh9))+(mid>>>13)|0)+(w18>>>26)|0,w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,0!==c&&(o[19]=c,out.length++),out};function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0;k>>26)|0)>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0!==carry?out.words[k]=carry:out.length--,out._strip()}function jumboMulTo(self,num,out){return bigMulTo(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}Math.imul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function mulTo(num,out){var len=this.length+num.length;return 10===this.length&&10===num.length?comb10MulTo(this,num,out):len<63?smallMulTo(this,num,out):len<1024?bigMulTo(this,num,out):jumboMulTo(this,num,out)},FFTM.prototype.makeRBT=function makeRBT(N){for(var t=new Array(N),l=BN.prototype._countBits(N)-1,i=0;i>=1;return rb},FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>=1)i++;return 1<>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;i>=26,carry+=w/67108864|0,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),isNegNum?this.ineg():this},BN.prototype.muln=function muln(num){return this.clone().imuln(num)},BN.prototype.sqr=function sqr(){return this.mul(this)},BN.prototype.isqr=function isqr(){return this.imul(this.clone())},BN.prototype.pow=function pow(num){var w=function toBitArray(num){for(var w=new Array(num.bitLength()),bit=0;bit>>wbit&1}return w}(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i=0);var i,r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r;if(0!==r){var carry=0;for(i=0;i>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;i>=0;i--)this.words[i+s]=this.words[i];for(i=0;i=0),h=hint?(hint-hint%26)/26:0;var r=bits%26,s=Math.min((bits-r)/26,this.length),mask=67108863^67108863>>>r<s)for(this.length-=s,i=0;i=0&&(0!==carry||i>=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&0!==carry&&(maskedWords.words[maskedWords.length++]=carry),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},BN.prototype.ishrn=function ishrn(bits,hint,extended){return assert(0===this.negative),this.iushrn(bits,hint,extended)},BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function testn(bit){assert("number"==typeof bit&&bit>=0);var r=bit%26,s=(bit-r)/26,q=1<=0);var r=bits%26,s=(bits-r)/26;if(assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!==r&&s++,this.length=Math.min(s,this.length),0!==r){var mask=67108863^67108863>>>r<=67108864;i++)this.words[i]-=67108864,i===this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=Math.max(this.length,i+1),this},BN.prototype.isubn=function isubn(num){if(assert("number"==typeof num),assert(num<67108864),num<0)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i>26)-(right/67108864|0),this.words[i+shift]=67108863&w}for(;i>26,this.words[i+shift]=67108863&w;if(0===carry)return this._strip();for(assert(-1===carry),carry=0,i=0;i>26,this.words[i]=67108863&w;return this.negative=1,this._strip()},BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=(this.length,num.length),a=this.clone(),b=num,bhi=0|b.words[b.length-1];0!==(shift=26-this._countBits(bhi))&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var q,m=a.length-b.length;if("mod"!==mode){(q=new BN(null)).length=m+1,q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=67108864*(0|a.words[b.length+j])+(0|a.words[b.length+j-1]);for(qj=Math.min(qj/bhi|0,67108863),a._ishlnsubmul(b,qj,j);0!==a.negative;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q._strip(),a._strip(),"div"!==mode&&0!==shift&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function divmod(num,mode,positive){return assert(!num.isZero()),this.isZero()?{div:new BN(0),mod:new BN(0)}:0!==this.negative&&0===num.negative?(res=this.neg().divmod(num,mode),"mod"!==mode&&(div=res.div.neg()),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.iadd(num)),{div,mod}):0===this.negative&&0!==num.negative?(res=this.divmod(num.neg(),mode),"mod"!==mode&&(div=res.div.neg()),{div,mod:res.mod}):0!=(this.negative&num.negative)?(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod}):num.length>this.length||this.cmp(num)<0?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modrn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modrn(num.words[0]))}:this._wordDiv(num,mode);var div,mod,res},BN.prototype.div=function div(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function mod(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function umod(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0!==dm.div.negative?dm.mod.isub(num):dm.mod,half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return cmp<0||1===r2&&0===cmp?dm.div:0!==dm.div.negative?dm.div.isubn(1):dm.div.iaddn(1)},BN.prototype.modrn=function modrn(num){var isNegNum=num<0;isNegNum&&(num=-num),assert(num<=67108863);for(var p=(1<<26)%num,acc=0,i=this.length-1;i>=0;i--)acc=(p*acc+(0|this.words[i]))%num;return isNegNum?-acc:acc},BN.prototype.modn=function modn(num){return this.modrn(num)},BN.prototype.idivn=function idivn(num){var isNegNum=num<0;isNegNum&&(num=-num),assert(num<=67108863);for(var carry=0,i=this.length-1;i>=0;i--){var w=(0|this.words[i])+67108864*carry;this.words[i]=w/num|0,carry=w%num}return this._strip(),isNegNum?this.ineg():this},BN.prototype.divn=function divn(num){return this.clone().idivn(num)},BN.prototype.egcd=function egcd(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0!==x.negative?x.umod(p):x.clone();for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0==(x.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(x.iushrn(i);i-- >0;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;0==(y.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(y.iushrn(j);j-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);x.cmp(y)>=0?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function _invmp(p){assert(0===p.negative),assert(!p.isZero());var a=this,b=p.clone();a=0!==a.negative?a.umod(p):a.clone();for(var res,x1=new BN(1),x2=new BN(0),delta=b.clone();a.cmpn(1)>0&&b.cmpn(1)>0;){for(var i=0,im=1;0==(a.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(a.iushrn(i);i-- >0;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;0==(b.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(b.iushrn(j);j-- >0;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);a.cmp(b)>=0?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}return(res=0===a.cmpn(1)?x1:x2).cmpn(0)<0&&res.iadd(p),res},BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);for(;;){for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(r<0){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}return b.iushln(shift)},BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function isEven(){return 0==(1&this.words[0])},BN.prototype.isOdd=function isOdd(){return 1==(1&this.words[0])},BN.prototype.andln=function andln(num){return this.words[0]&num},BN.prototype.bincn=function bincn(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<>>26,w&=67108863,this.words[i]=w}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function isZero(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function cmpn(num){var res,negative=num<0;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;if(this._strip(),this.length>1)res=1;else{negative&&(num=-num),assert(num<=67108863,"Number is too big");var w=0|this.words[0];res=w===num?0:wnum.length)return 1;if(this.length=0;i--){var a=0|this.words[i],b=0|num.words[i];if(a!==b){ab&&(res=1);break}}return res},BN.prototype.gtn=function gtn(num){return 1===this.cmpn(num)},BN.prototype.gt=function gt(num){return 1===this.cmp(num)},BN.prototype.gten=function gten(num){return this.cmpn(num)>=0},BN.prototype.gte=function gte(num){return this.cmp(num)>=0},BN.prototype.ltn=function ltn(num){return-1===this.cmpn(num)},BN.prototype.lt=function lt(num){return-1===this.cmp(num)},BN.prototype.lten=function lten(num){return this.cmpn(num)<=0},BN.prototype.lte=function lte(num){return this.cmp(num)<=0},BN.prototype.eqn=function eqn(num){return 0===this.cmpn(num)},BN.prototype.eq=function eq(num){return 0===this.cmp(num)},BN.red=function red(num){return new Red(num)},BN.prototype.toRed=function toRed(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function fromRed(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function _forceRed(ctx){return this.red=ctx,this},BN.prototype.forceRed=function forceRed(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function redAdd(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function redIAdd(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function redSub(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function redISub(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function redShl(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function redMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function redIMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function redSqr(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function redISqr(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function redSqrt(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function redInvm(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function redNeg(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function redPow(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);return tmp.words=new Array(Math.ceil(this.n/13)),tmp},MPrime.prototype.ireduce=function ireduce(num){var rlen,r=num;do{this.split(r,this.tmp),rlen=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(rlen>this.n);var cmp=rlen0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)},inherits(K256,MPrime),K256.prototype.split=function split(input,output){for(var outLen=Math.min(input.length,9),i=0;i>>22,prev=next}prev>>>=22,input.words[i-10]=prev,0===prev&&input.length>10?input.length-=10:input.length-=9},K256.prototype.imulK=function imulK(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0;i>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else{if("p25519"!==name)throw new Error("Unknown prime "+name);prime=new P25519}return primes[name]=prime,prime},Red.prototype._verify1=function _verify1(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function _verify2(a,b){assert(0==(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function imod(a){return this.prime?this.prime.ireduce(a)._forceRed(this):(move(a,a.umod(this.m)._forceRed(this)),a)},Red.prototype.neg=function neg(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);return res.cmp(this.m)>=0&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);return res.cmp(this.m)>=0&&res.isub(this.m),res},Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);return res.cmpn(0)<0&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);return res.cmpn(0)<0&&res.iadd(this.m),res},Red.prototype.shl=function shl(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function imul(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function mul(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())},Red.prototype.sqr=function sqr(a){return this.mul(a,a)},Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(mod3%2==1),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i=0;i--){for(var word=num.words[i],j=start-1;j>=0;j--){var bit=word>>j&1;res!==wnd[0]&&(res=this.sqr(res)),0!==bit||0!==current?(current<<=1,current|=bit,(4===++currentLen||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)):currentLen=0}start=26}return res},Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();return res.red=null,res},BN.mont=function mont(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function invm(a){return this.imod(a._invmp(this.m).mul(this.r2))._forceRed(this)}}(module=__webpack_require__.nmd(module),this)},7191:(module,__unused_webpack_exports,__webpack_require__)=>{var basex=__webpack_require__(8162);module.exports=basex("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")},3310:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var base58=__webpack_require__(7191),Buffer=__webpack_require__(9509).Buffer;module.exports=function(checksumFn){function decodeRaw(buffer){var payload=buffer.slice(0,-4),checksum=buffer.slice(-4),newChecksum=checksumFn(payload);if(!(checksum[0]^newChecksum[0]|checksum[1]^newChecksum[1]|checksum[2]^newChecksum[2]|checksum[3]^newChecksum[3]))return payload}return{encode:function encode(payload){var checksum=checksumFn(payload);return base58.encode(Buffer.concat([payload,checksum],payload.length+4))},decode:function decode(string){var payload=decodeRaw(base58.decode(string));if(!payload)throw new Error("Invalid checksum");return payload},decodeUnsafe:function decodeUnsafe(string){var buffer=base58.decodeUnsafe(string);if(buffer)return decodeRaw(buffer)}}}},8334:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var createHash=__webpack_require__(3482),bs58checkBase=__webpack_require__(3310);module.exports=bs58checkBase((function sha256x2(buffer){var tmp=createHash("sha256").update(buffer).digest();return createHash("sha256").update(tmp).digest()}))},7295:module=>{module.exports=function xor(a,b){for(var length=Math.min(a.length,b.length),buffer=new Buffer(length),i=0;i{"use strict";const base64=__webpack_require__(9742),ieee754=__webpack_require__(645),customInspectSymbol="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;exports.Buffer=Buffer,exports.SlowBuffer=function SlowBuffer(length){+length!=length&&(length=0);return Buffer.alloc(+length)},exports.INSPECT_MAX_BYTES=50;function createBuffer(length){if(length>2147483647)throw new RangeError('The value "'+length+'" is invalid for option "size"');const buf=new Uint8Array(length);return Object.setPrototypeOf(buf,Buffer.prototype),buf}function Buffer(arg,encodingOrOffset,length){if("number"==typeof arg){if("string"==typeof encodingOrOffset)throw new TypeError('The "string" argument must be of type string. Received type number');return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}function from(value,encodingOrOffset,length){if("string"==typeof value)return function fromString(string,encoding){"string"==typeof encoding&&""!==encoding||(encoding="utf8");if(!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);const length=0|byteLength(string,encoding);let buf=createBuffer(length);const actual=buf.write(string,encoding);actual!==length&&(buf=buf.slice(0,actual));return buf}(value,encodingOrOffset);if(ArrayBuffer.isView(value))return function fromArrayView(arrayView){if(isInstance(arrayView,Uint8Array)){const copy=new Uint8Array(arrayView);return fromArrayBuffer(copy.buffer,copy.byteOffset,copy.byteLength)}return fromArrayLike(arrayView)}(value);if(null==value)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value);if(isInstance(value,ArrayBuffer)||value&&isInstance(value.buffer,ArrayBuffer))return fromArrayBuffer(value,encodingOrOffset,length);if("undefined"!=typeof SharedArrayBuffer&&(isInstance(value,SharedArrayBuffer)||value&&isInstance(value.buffer,SharedArrayBuffer)))return fromArrayBuffer(value,encodingOrOffset,length);if("number"==typeof value)throw new TypeError('The "value" argument must not be of type number. Received type number');const valueOf=value.valueOf&&value.valueOf();if(null!=valueOf&&valueOf!==value)return Buffer.from(valueOf,encodingOrOffset,length);const b=function fromObject(obj){if(Buffer.isBuffer(obj)){const len=0|checked(obj.length),buf=createBuffer(len);return 0===buf.length||obj.copy(buf,0,0,len),buf}if(void 0!==obj.length)return"number"!=typeof obj.length||numberIsNaN(obj.length)?createBuffer(0):fromArrayLike(obj);if("Buffer"===obj.type&&Array.isArray(obj.data))return fromArrayLike(obj.data)}(value);if(b)return b;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof value[Symbol.toPrimitive])return Buffer.from(value[Symbol.toPrimitive]("string"),encodingOrOffset,length);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value)}function assertSize(size){if("number"!=typeof size)throw new TypeError('"size" argument must be of type number');if(size<0)throw new RangeError('The value "'+size+'" is invalid for option "size"')}function allocUnsafe(size){return assertSize(size),createBuffer(size<0?0:0|checked(size))}function fromArrayLike(array){const length=array.length<0?0:0|checked(array.length),buf=createBuffer(length);for(let i=0;i=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647..toString(16)+" bytes");return 0|length}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if(ArrayBuffer.isView(string)||isInstance(string,ArrayBuffer))return string.byteLength;if("string"!=typeof string)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof string);const len=string.length,mustMatch=arguments.length>2&&!0===arguments[2];if(!mustMatch&&0===len)return 0;let loweredCase=!1;for(;;)switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*len;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return mustMatch?-1:utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0}}function slowToString(encoding,start,end){let loweredCase=!1;if((void 0===start||start<0)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),end<=0)return"";if((end>>>=0)<=(start>>>=0))return"";for(encoding||(encoding="utf8");;)switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase(),loweredCase=!0}}function swap(b,n,m){const i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):byteOffset>2147483647?byteOffset=2147483647:byteOffset<-2147483648&&(byteOffset=-2147483648),numberIsNaN(byteOffset=+byteOffset)&&(byteOffset=dir?0:buffer.length-1),byteOffset<0&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(byteOffset<0){if(!dir)return-1;byteOffset=0}if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){let i,indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&("ucs2"===(encoding=String(encoding).toLowerCase())||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(arr.length<2||val.length<2)return-1;indexSize=2,arrLength/=2,valLength/=2,byteOffset/=2}function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}if(dir){let foundIndex=-1;for(i=byteOffset;iarrLength&&(byteOffset=arrLength-valLength),i=byteOffset;i>=0;i--){let found=!0;for(let j=0;jremaining&&(length=remaining):length=remaining;const strLen=string.length;let i;for(length>strLen/2&&(length=strLen/2),i=0;i>8,lo=c%256,byteArray.push(lo),byteArray.push(hi);return byteArray}(string,buf.length-offset),buf,offset,length)}function base64Slice(buf,start,end){return 0===start&&end===buf.length?base64.fromByteArray(buf):base64.fromByteArray(buf.slice(start,end))}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);const res=[];let i=start;for(;i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){let secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:firstByte<128&&(codePoint=firstByte);break;case 2:secondByte=buf[i+1],128==(192&secondByte)&&(tempCodePoint=(31&firstByte)<<6|63&secondByte,tempCodePoint>127&&(codePoint=tempCodePoint));break;case 3:secondByte=buf[i+1],thirdByte=buf[i+2],128==(192&secondByte)&&128==(192&thirdByte)&&(tempCodePoint=(15&firstByte)<<12|(63&secondByte)<<6|63&thirdByte,tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)&&(codePoint=tempCodePoint));break;case 4:secondByte=buf[i+1],thirdByte=buf[i+2],fourthByte=buf[i+3],128==(192&secondByte)&&128==(192&thirdByte)&&128==(192&fourthByte)&&(tempCodePoint=(15&firstByte)<<18|(63&secondByte)<<12|(63&thirdByte)<<6|63&fourthByte,tempCodePoint>65535&&tempCodePoint<1114112&&(codePoint=tempCodePoint))}}null===codePoint?(codePoint=65533,bytesPerSequence=1):codePoint>65535&&(codePoint-=65536,res.push(codePoint>>>10&1023|55296),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return function decodeCodePointsArray(codePoints){const len=codePoints.length;if(len<=4096)return String.fromCharCode.apply(String,codePoints);let res="",i=0;for(;ibuffer.length?(Buffer.isBuffer(buf)||(buf=Buffer.from(buf)),buf.copy(buffer,pos)):Uint8Array.prototype.set.call(buffer,buf,pos);else{if(!Buffer.isBuffer(buf))throw new TypeError('"list" argument must be an Array of Buffers');buf.copy(buffer,pos)}pos+=buf.length}return buffer},Buffer.byteLength=byteLength,Buffer.prototype._isBuffer=!0,Buffer.prototype.swap16=function swap16(){const len=this.length;if(len%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let i=0;imax&&(str+=" ... "),""},customInspectSymbol&&(Buffer.prototype[customInspectSymbol]=Buffer.prototype.inspect),Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)&&(target=Buffer.from(target,target.offset,target.byteLength)),!Buffer.isBuffer(target))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof target);if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),start<0||end>target.length||thisStart<0||thisEnd>this.length)throw new RangeError("out of range index");if(thisStart>=thisEnd&&start>=end)return 0;if(thisStart>=thisEnd)return-1;if(start>=end)return 1;if(this===target)return 0;let x=(thisEnd>>>=0)-(thisStart>>>=0),y=(end>>>=0)-(start>>>=0);const len=Math.min(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end);for(let i=0;i>>=0,isFinite(length)?(length>>>=0,void 0===encoding&&(encoding="utf8")):(encoding=length,length=void 0)}const remaining=this.length-offset;if((void 0===length||length>remaining)&&(length=remaining),string.length>0&&(length<0||offset<0)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");let loweredCase=!1;for(;;)switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":case"latin1":case"binary":return asciiWrite(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase(),loweredCase=!0}},Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function asciiSlice(buf,start,end){let ret="";end=Math.min(buf.length,end);for(let i=start;ilen)&&(end=len);let out="";for(let i=start;ilength)throw new RangeError("Trying to access beyond buffer length")}function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}function wrtBigUInt64LE(buf,value,offset,min,max){checkIntBI(value,min,max,buf,offset,7);let lo=Number(value&BigInt(4294967295));buf[offset++]=lo,lo>>=8,buf[offset++]=lo,lo>>=8,buf[offset++]=lo,lo>>=8,buf[offset++]=lo;let hi=Number(value>>BigInt(32)&BigInt(4294967295));return buf[offset++]=hi,hi>>=8,buf[offset++]=hi,hi>>=8,buf[offset++]=hi,hi>>=8,buf[offset++]=hi,offset}function wrtBigUInt64BE(buf,value,offset,min,max){checkIntBI(value,min,max,buf,offset,7);let lo=Number(value&BigInt(4294967295));buf[offset+7]=lo,lo>>=8,buf[offset+6]=lo,lo>>=8,buf[offset+5]=lo,lo>>=8,buf[offset+4]=lo;let hi=Number(value>>BigInt(32)&BigInt(4294967295));return buf[offset+3]=hi,hi>>=8,buf[offset+2]=hi,hi>>=8,buf[offset+1]=hi,hi>>=8,buf[offset]=hi,offset+8}function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,0,offset,4),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,0,offset,8),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}Buffer.prototype.slice=function slice(start,end){const len=this.length;(start=~~start)<0?(start+=len)<0&&(start=0):start>len&&(start=len),(end=void 0===end?len:~~end)<0?(end+=len)<0&&(end=0):end>len&&(end=len),end>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);let val=this[offset],mul=1,i=0;for(;++i>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);let val=this[offset+--byteLength],mul=1;for(;byteLength>0&&(mul*=256);)val+=this[offset+--byteLength]*mul;return val},Buffer.prototype.readUint8=Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUint16LE=Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUint16BE=Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUint32LE=Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUint32BE=Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readBigUInt64LE=defineBigIntMethod((function readBigUInt64LE(offset){validateNumber(offset>>>=0,"offset");const first=this[offset],last=this[offset+7];void 0!==first&&void 0!==last||boundsError(offset,this.length-8);const lo=first+256*this[++offset]+65536*this[++offset]+this[++offset]*2**24,hi=this[++offset]+256*this[++offset]+65536*this[++offset]+last*2**24;return BigInt(lo)+(BigInt(hi)<>>=0,"offset");const first=this[offset],last=this[offset+7];void 0!==first&&void 0!==last||boundsError(offset,this.length-8);const hi=first*2**24+65536*this[++offset]+256*this[++offset]+this[++offset],lo=this[++offset]*2**24+65536*this[++offset]+256*this[++offset]+last;return(BigInt(hi)<>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);let val=this[offset],mul=1,i=0;for(;++i=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);let i=byteLength,mul=1,val=this[offset+--i];for(;i>0&&(mul*=256);)val+=this[offset+--i]*mul;return mul*=128,val>=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readInt8=function readInt8(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,1,this.length),128&this[offset]?-1*(255-this[offset]+1):this[offset]},Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);const val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);const val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readBigInt64LE=defineBigIntMethod((function readBigInt64LE(offset){validateNumber(offset>>>=0,"offset");const first=this[offset],last=this[offset+7];void 0!==first&&void 0!==last||boundsError(offset,this.length-8);const val=this[offset+4]+256*this[offset+5]+65536*this[offset+6]+(last<<24);return(BigInt(val)<>>=0,"offset");const first=this[offset],last=this[offset+7];void 0!==first&&void 0!==last||boundsError(offset,this.length-8);const val=(first<<24)+65536*this[++offset]+256*this[++offset]+this[++offset];return(BigInt(val)<>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUintLE=Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,byteLength>>>=0,!noAssert){checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength)-1,0)}let mul=1,i=0;for(this[offset]=255&value;++i>>=0,byteLength>>>=0,!noAssert){checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength)-1,0)}let i=byteLength-1,mul=1;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)this[offset+i]=value/mul&255;return offset+byteLength},Buffer.prototype.writeUint8=Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,255,0),this[offset]=255&value,offset+1},Buffer.prototype.writeUint16LE=Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeUint16BE=Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeUint32LE=Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value,offset+4},Buffer.prototype.writeUint32BE=Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeBigUInt64LE=defineBigIntMethod((function writeBigUInt64LE(value,offset=0){return wrtBigUInt64LE(this,value,offset,BigInt(0),BigInt("0xffffffffffffffff"))})),Buffer.prototype.writeBigUInt64BE=defineBigIntMethod((function writeBigUInt64BE(value,offset=0){return wrtBigUInt64BE(this,value,offset,BigInt(0),BigInt("0xffffffffffffffff"))})),Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,!noAssert){const limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}let i=0,mul=1,sub=0;for(this[offset]=255&value;++i>0)-sub&255;return offset+byteLength},Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,!noAssert){const limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}let i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)value<0&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength},Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,127,-128),value<0&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24,offset+4},Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),value<0&&(value=4294967295+value+1),this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeBigInt64LE=defineBigIntMethod((function writeBigInt64LE(value,offset=0){return wrtBigUInt64LE(this,value,offset,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),Buffer.prototype.writeBigInt64BE=defineBigIntMethod((function writeBigInt64BE(value,offset=0){return wrtBigUInt64BE(this,value,offset,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),end>0&&end=this.length)throw new RangeError("Index out of range");if(end<0)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStart>>=0,end=void 0===end?this.length:end>>>0,val||(val=0),"number"==typeof val)for(i=start;i=start+4;i-=3)res=`_${val.slice(i-3,i)}${res}`;return`${val.slice(0,i)}${res}`}function checkIntBI(value,min,max,buf,offset,byteLength){if(value>max||value3?0===min||min===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(byteLength+1)}${n}`:`>= -(2${n} ** ${8*(byteLength+1)-1}${n}) and < 2 ** ${8*(byteLength+1)-1}${n}`:`>= ${min}${n} and <= ${max}${n}`,new errors.ERR_OUT_OF_RANGE("value",range,value)}!function checkBounds(buf,offset,byteLength){validateNumber(offset,"offset"),void 0!==buf[offset]&&void 0!==buf[offset+byteLength]||boundsError(offset,buf.length-(byteLength+1))}(buf,offset,byteLength)}function validateNumber(value,name){if("number"!=typeof value)throw new errors.ERR_INVALID_ARG_TYPE(name,"number",value)}function boundsError(value,length,type){if(Math.floor(value)!==value)throw validateNumber(value,type),new errors.ERR_OUT_OF_RANGE(type||"offset","an integer",value);if(length<0)throw new errors.ERR_BUFFER_OUT_OF_BOUNDS;throw new errors.ERR_OUT_OF_RANGE(type||"offset",`>= ${type?1:0} and <= ${length}`,value)}E("ERR_BUFFER_OUT_OF_BOUNDS",(function(name){return name?`${name} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),E("ERR_INVALID_ARG_TYPE",(function(name,actual){return`The "${name}" argument must be of type number. Received type ${typeof actual}`}),TypeError),E("ERR_OUT_OF_RANGE",(function(str,range,input){let msg=`The value of "${str}" is out of range.`,received=input;return Number.isInteger(input)&&Math.abs(input)>2**32?received=addNumericalSeparator(String(input)):"bigint"==typeof input&&(received=String(input),(input>BigInt(2)**BigInt(32)||input<-(BigInt(2)**BigInt(32)))&&(received=addNumericalSeparator(received)),received+="n"),msg+=` It must be ${range}. Received ${received}`,msg}),RangeError);const INVALID_BASE64_RE=/[^+/0-9A-Za-z-_]/g;function utf8ToBytes(string,units){let codePoint;units=units||1/0;const length=string.length;let leadSurrogate=null;const bytes=[];for(let i=0;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){(units-=3)>-1&&bytes.push(239,191,189);continue}if(i+1===length){(units-=3)>-1&&bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){(units-=3)>-1&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=65536+(leadSurrogate-55296<<10|codePoint-56320)}else leadSurrogate&&(units-=3)>-1&&bytes.push(239,191,189);if(leadSurrogate=null,codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,63&codePoint|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,63&codePoint|128)}else{if(!(codePoint<1114112))throw new Error("Invalid code point");if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,63&codePoint|128)}}return bytes}function base64ToBytes(str){return base64.toByteArray(function base64clean(str){if((str=(str=str.split("=")[0]).trim().replace(INVALID_BASE64_RE,"")).length<2)return"";for(;str.length%4!=0;)str+="=";return str}(str))}function blitBuffer(src,dst,offset,length){let i;for(i=0;i=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isInstance(obj,type){return obj instanceof type||null!=obj&&null!=obj.constructor&&null!=obj.constructor.name&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!=obj}const hexSliceLookupTable=function(){const table=new Array(256);for(let i=0;i<16;++i){const i16=16*i;for(let j=0;j<16;++j)table[i16+j]="0123456789abcdef"[i]+"0123456789abcdef"[j]}return table}();function defineBigIntMethod(fn){return"undefined"==typeof BigInt?BufferBigIntNotDefined:fn}function BufferBigIntNotDefined(){throw new Error("BigInt not supported")}},1924:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var GetIntrinsic=__webpack_require__(210),callBind=__webpack_require__(5559),$indexOf=callBind(GetIntrinsic("String.prototype.indexOf"));module.exports=function callBoundIntrinsic(name,allowMissing){var intrinsic=GetIntrinsic(name,!!allowMissing);return"function"==typeof intrinsic&&$indexOf(name,".prototype.")>-1?callBind(intrinsic):intrinsic}},5559:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var bind=__webpack_require__(8612),GetIntrinsic=__webpack_require__(210),$apply=GetIntrinsic("%Function.prototype.apply%"),$call=GetIntrinsic("%Function.prototype.call%"),$reflectApply=GetIntrinsic("%Reflect.apply%",!0)||bind.call($call,$apply),$gOPD=GetIntrinsic("%Object.getOwnPropertyDescriptor%",!0),$defineProperty=GetIntrinsic("%Object.defineProperty%",!0),$max=GetIntrinsic("%Math.max%");if($defineProperty)try{$defineProperty({},"a",{value:1})}catch(e){$defineProperty=null}module.exports=function callBind(originalFunction){var func=$reflectApply(bind,$call,arguments);if($gOPD&&$defineProperty){var desc=$gOPD(func,"length");desc.configurable&&$defineProperty(func,"length",{value:1+$max(0,originalFunction.length-(arguments.length-1))})}return func};var applyBind=function applyBind(){return $reflectApply(bind,$apply,arguments)};$defineProperty?$defineProperty(module.exports,"apply",{value:applyBind}):module.exports.apply=applyBind},1027:(module,__unused_webpack_exports,__webpack_require__)=>{var Buffer=__webpack_require__(9509).Buffer,Transform=__webpack_require__(2830).Transform,StringDecoder=__webpack_require__(2553).s;function CipherBase(hashMode){Transform.call(this),this.hashMode="string"==typeof hashMode,this.hashMode?this[hashMode]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}__webpack_require__(5717)(CipherBase,Transform),CipherBase.prototype.update=function(data,inputEnc,outputEnc){"string"==typeof data&&(data=Buffer.from(data,inputEnc));var outData=this._update(data);return this.hashMode?this:(outputEnc&&(outData=this._toString(outData,outputEnc)),outData)},CipherBase.prototype.setAutoPadding=function(){},CipherBase.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")},CipherBase.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")},CipherBase.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")},CipherBase.prototype._transform=function(data,_,next){var err;try{this.hashMode?this._update(data):this.push(this._update(data))}catch(e){err=e}finally{next(err)}},CipherBase.prototype._flush=function(done){var err;try{this.push(this.__final())}catch(e){err=e}done(err)},CipherBase.prototype._finalOrDigest=function(outputEnc){var outData=this.__final()||Buffer.alloc(0);return outputEnc&&(outData=this._toString(outData,outputEnc,!0)),outData},CipherBase.prototype._toString=function(value,enc,fin){if(this._decoder||(this._decoder=new StringDecoder(enc),this._encoding=enc),this._encoding!==enc)throw new Error("can't switch encodings");var out=this._decoder.write(value);return fin&&(out+=this._decoder.end()),out},module.exports=CipherBase},6393:(module,__unused_webpack_exports,__webpack_require__)=>{var elliptic=__webpack_require__(6266),BN=__webpack_require__(6426);module.exports=function createECDH(curve){return new ECDH(curve)};var aliases={secp256k1:{name:"secp256k1",byteLength:32},secp224r1:{name:"p224",byteLength:28},prime256v1:{name:"p256",byteLength:32},prime192v1:{name:"p192",byteLength:24},ed25519:{name:"ed25519",byteLength:32},secp384r1:{name:"p384",byteLength:48},secp521r1:{name:"p521",byteLength:66}};function ECDH(curve){this.curveType=aliases[curve],this.curveType||(this.curveType={name:curve}),this.curve=new elliptic.ec(this.curveType.name),this.keys=void 0}function formatReturnValue(bn,enc,len){Array.isArray(bn)||(bn=bn.toArray());var buf=new Buffer(bn);if(len&&buf.length=65&&c<=70?c-55:c>=97&&c<=102?c-87:c-48&15}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return index-1>=lowerBound&&(r|=parseHex4Bits(string,index-1)<<4),r}function parseBase(str,start,end,mul){for(var r=0,len=Math.min(str.length,end),i=start;i=49?c-49+10:c>=17?c-17+10:c}return r}BN.isBN=function isBN(num){return num instanceof BN||null!==num&&"object"==typeof num&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words)},BN.max=function max(left,right){return left.cmp(right)>0?left:right},BN.min=function min(left,right){return left.cmp(right)<0?left:right},BN.prototype._init=function init(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&base>=2&&base<=36);var start=0;"-"===(number=number.toString().replace(/\s+/g,""))[0]&&(start++,this.negative=1),start=0;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=w<>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);return this.strip()},BN.prototype._parseHex=function _parseHex(number,start,endian){this.length=Math.ceil((number.length-start)/6),this.words=new Array(this.length);for(var i=0;i=start;i-=2)w=parseHexByte(number,start,i)<=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;else for(i=(number.length-start)%2==0?start+1:start;i=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;this.strip()},BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;limbPow*=base)limbLen++;limbLen--,limbPow=limbPow/base|0;for(var total=number.length-start,mod=total%limbLen,end=Math.min(total,total-mod)+start,word=0,i=start;i1&&0===this.words[this.length-1];)this.length--;return this._normSign()},BN.prototype._normSign=function _normSign(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},BN.prototype.inspect=function inspect(){return(this.red?""};var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=self.length+num.length|0;out.length=len,len=len-1|0;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=r/67108864|0;out.words[0]=lo;for(var k=1;k>>26,rword=67108863&carry,maxJ=Math.min(k,num.length-1),j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j|0;ncarry+=(r=(a=0|self.words[i])*(b=0|num.words[j])+rword)/67108864|0,rword=67108863&r}out.words[k]=0|rword,carry=0|ncarry}return 0!==carry?out.words[k]=0|carry:out.length--,out.strip()}BN.prototype.toString=function toString(base,padding){var out;if(padding=0|padding||1,16===(base=base||10)||"hex"===base){out="";for(var off=0,carry=0,i=0;i>>24-off&16777215)||i!==this.length-1?zeros[6-word.length]+word+out:word+out,(off+=2)>=26&&(off-=26,i--)}for(0!==carry&&(out=carry.toString(16)+out);out.length%padding!=0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&base>=2&&base<=36){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modn(groupBase).toString(base);out=(c=c.idivn(groupBase)).isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);out.length%padding!=0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function toNumber(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:this.length>2&&assert(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-ret:ret},BN.prototype.toJSON=function toJSON(){return this.toString(16)},BN.prototype.toBuffer=function toBuffer(endian,length){return assert(void 0!==Buffer),this.toArrayLike(Buffer,endian,length)},BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)},BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){var byteLength=this.byteLength(),reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length"),assert(reqLength>0,"Requested array length <= 0"),this.strip();var b,i,littleEndian="le"===endian,res=new ArrayType(reqLength),q=this.clone();if(littleEndian){for(i=0;!q.isZero();i++)b=q.andln(255),q.iushrn(8),res[i]=b;for(;i=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function _zeroBits(w){if(0===w)return 26;var t=w,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;for(var r=0,i=0;inum.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function uor(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function iuand(num){var b;b=this.length>num.length?num:this;for(var i=0;inum.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function uand(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function iuxor(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;inum.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function uxor(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function inotn(width){assert("number"==typeof width&&width>=0);var bytesNeeded=0|Math.ceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),bitsLeft>0&&bytesNeeded--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this.strip()},BN.prototype.notn=function notn(width){return this.clone().inotn(width)},BN.prototype.setn=function setn(bit,val){assert("number"==typeof bit&&bit>=0);var off=bit/26|0,wbit=bit%26;return this._expand(off+1),this.words[off]=val?this.words[off]|1<num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>>26;for(;0!==carry&&i>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;inum.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function isub(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var a,b,cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;cmp>0?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>26,this.words[i]=67108863&r;for(;0!==carry&&i>26,this.words[i]=67108863&r;if(0===carry&&i>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13;out.negative=self.negative^num.negative,out.length=19;var w0=(c+(lo=Math.imul(al0,bl0))|0)+((8191&(mid=(mid=Math.imul(al0,bh0))+Math.imul(ah0,bl0)|0))<<13)|0;c=((hi=Math.imul(ah0,bh0))+(mid>>>13)|0)+(w0>>>26)|0,w0&=67108863,lo=Math.imul(al1,bl0),mid=(mid=Math.imul(al1,bh0))+Math.imul(ah1,bl0)|0,hi=Math.imul(ah1,bh0);var w1=(c+(lo=lo+Math.imul(al0,bl1)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh1)|0)+Math.imul(ah0,bl1)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh1)|0)+(mid>>>13)|0)+(w1>>>26)|0,w1&=67108863,lo=Math.imul(al2,bl0),mid=(mid=Math.imul(al2,bh0))+Math.imul(ah2,bl0)|0,hi=Math.imul(ah2,bh0),lo=lo+Math.imul(al1,bl1)|0,mid=(mid=mid+Math.imul(al1,bh1)|0)+Math.imul(ah1,bl1)|0,hi=hi+Math.imul(ah1,bh1)|0;var w2=(c+(lo=lo+Math.imul(al0,bl2)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh2)|0)+Math.imul(ah0,bl2)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh2)|0)+(mid>>>13)|0)+(w2>>>26)|0,w2&=67108863,lo=Math.imul(al3,bl0),mid=(mid=Math.imul(al3,bh0))+Math.imul(ah3,bl0)|0,hi=Math.imul(ah3,bh0),lo=lo+Math.imul(al2,bl1)|0,mid=(mid=mid+Math.imul(al2,bh1)|0)+Math.imul(ah2,bl1)|0,hi=hi+Math.imul(ah2,bh1)|0,lo=lo+Math.imul(al1,bl2)|0,mid=(mid=mid+Math.imul(al1,bh2)|0)+Math.imul(ah1,bl2)|0,hi=hi+Math.imul(ah1,bh2)|0;var w3=(c+(lo=lo+Math.imul(al0,bl3)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh3)|0)+Math.imul(ah0,bl3)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh3)|0)+(mid>>>13)|0)+(w3>>>26)|0,w3&=67108863,lo=Math.imul(al4,bl0),mid=(mid=Math.imul(al4,bh0))+Math.imul(ah4,bl0)|0,hi=Math.imul(ah4,bh0),lo=lo+Math.imul(al3,bl1)|0,mid=(mid=mid+Math.imul(al3,bh1)|0)+Math.imul(ah3,bl1)|0,hi=hi+Math.imul(ah3,bh1)|0,lo=lo+Math.imul(al2,bl2)|0,mid=(mid=mid+Math.imul(al2,bh2)|0)+Math.imul(ah2,bl2)|0,hi=hi+Math.imul(ah2,bh2)|0,lo=lo+Math.imul(al1,bl3)|0,mid=(mid=mid+Math.imul(al1,bh3)|0)+Math.imul(ah1,bl3)|0,hi=hi+Math.imul(ah1,bh3)|0;var w4=(c+(lo=lo+Math.imul(al0,bl4)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh4)|0)+Math.imul(ah0,bl4)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh4)|0)+(mid>>>13)|0)+(w4>>>26)|0,w4&=67108863,lo=Math.imul(al5,bl0),mid=(mid=Math.imul(al5,bh0))+Math.imul(ah5,bl0)|0,hi=Math.imul(ah5,bh0),lo=lo+Math.imul(al4,bl1)|0,mid=(mid=mid+Math.imul(al4,bh1)|0)+Math.imul(ah4,bl1)|0,hi=hi+Math.imul(ah4,bh1)|0,lo=lo+Math.imul(al3,bl2)|0,mid=(mid=mid+Math.imul(al3,bh2)|0)+Math.imul(ah3,bl2)|0,hi=hi+Math.imul(ah3,bh2)|0,lo=lo+Math.imul(al2,bl3)|0,mid=(mid=mid+Math.imul(al2,bh3)|0)+Math.imul(ah2,bl3)|0,hi=hi+Math.imul(ah2,bh3)|0,lo=lo+Math.imul(al1,bl4)|0,mid=(mid=mid+Math.imul(al1,bh4)|0)+Math.imul(ah1,bl4)|0,hi=hi+Math.imul(ah1,bh4)|0;var w5=(c+(lo=lo+Math.imul(al0,bl5)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh5)|0)+Math.imul(ah0,bl5)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh5)|0)+(mid>>>13)|0)+(w5>>>26)|0,w5&=67108863,lo=Math.imul(al6,bl0),mid=(mid=Math.imul(al6,bh0))+Math.imul(ah6,bl0)|0,hi=Math.imul(ah6,bh0),lo=lo+Math.imul(al5,bl1)|0,mid=(mid=mid+Math.imul(al5,bh1)|0)+Math.imul(ah5,bl1)|0,hi=hi+Math.imul(ah5,bh1)|0,lo=lo+Math.imul(al4,bl2)|0,mid=(mid=mid+Math.imul(al4,bh2)|0)+Math.imul(ah4,bl2)|0,hi=hi+Math.imul(ah4,bh2)|0,lo=lo+Math.imul(al3,bl3)|0,mid=(mid=mid+Math.imul(al3,bh3)|0)+Math.imul(ah3,bl3)|0,hi=hi+Math.imul(ah3,bh3)|0,lo=lo+Math.imul(al2,bl4)|0,mid=(mid=mid+Math.imul(al2,bh4)|0)+Math.imul(ah2,bl4)|0,hi=hi+Math.imul(ah2,bh4)|0,lo=lo+Math.imul(al1,bl5)|0,mid=(mid=mid+Math.imul(al1,bh5)|0)+Math.imul(ah1,bl5)|0,hi=hi+Math.imul(ah1,bh5)|0;var w6=(c+(lo=lo+Math.imul(al0,bl6)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh6)|0)+Math.imul(ah0,bl6)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh6)|0)+(mid>>>13)|0)+(w6>>>26)|0,w6&=67108863,lo=Math.imul(al7,bl0),mid=(mid=Math.imul(al7,bh0))+Math.imul(ah7,bl0)|0,hi=Math.imul(ah7,bh0),lo=lo+Math.imul(al6,bl1)|0,mid=(mid=mid+Math.imul(al6,bh1)|0)+Math.imul(ah6,bl1)|0,hi=hi+Math.imul(ah6,bh1)|0,lo=lo+Math.imul(al5,bl2)|0,mid=(mid=mid+Math.imul(al5,bh2)|0)+Math.imul(ah5,bl2)|0,hi=hi+Math.imul(ah5,bh2)|0,lo=lo+Math.imul(al4,bl3)|0,mid=(mid=mid+Math.imul(al4,bh3)|0)+Math.imul(ah4,bl3)|0,hi=hi+Math.imul(ah4,bh3)|0,lo=lo+Math.imul(al3,bl4)|0,mid=(mid=mid+Math.imul(al3,bh4)|0)+Math.imul(ah3,bl4)|0,hi=hi+Math.imul(ah3,bh4)|0,lo=lo+Math.imul(al2,bl5)|0,mid=(mid=mid+Math.imul(al2,bh5)|0)+Math.imul(ah2,bl5)|0,hi=hi+Math.imul(ah2,bh5)|0,lo=lo+Math.imul(al1,bl6)|0,mid=(mid=mid+Math.imul(al1,bh6)|0)+Math.imul(ah1,bl6)|0,hi=hi+Math.imul(ah1,bh6)|0;var w7=(c+(lo=lo+Math.imul(al0,bl7)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh7)|0)+Math.imul(ah0,bl7)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh7)|0)+(mid>>>13)|0)+(w7>>>26)|0,w7&=67108863,lo=Math.imul(al8,bl0),mid=(mid=Math.imul(al8,bh0))+Math.imul(ah8,bl0)|0,hi=Math.imul(ah8,bh0),lo=lo+Math.imul(al7,bl1)|0,mid=(mid=mid+Math.imul(al7,bh1)|0)+Math.imul(ah7,bl1)|0,hi=hi+Math.imul(ah7,bh1)|0,lo=lo+Math.imul(al6,bl2)|0,mid=(mid=mid+Math.imul(al6,bh2)|0)+Math.imul(ah6,bl2)|0,hi=hi+Math.imul(ah6,bh2)|0,lo=lo+Math.imul(al5,bl3)|0,mid=(mid=mid+Math.imul(al5,bh3)|0)+Math.imul(ah5,bl3)|0,hi=hi+Math.imul(ah5,bh3)|0,lo=lo+Math.imul(al4,bl4)|0,mid=(mid=mid+Math.imul(al4,bh4)|0)+Math.imul(ah4,bl4)|0,hi=hi+Math.imul(ah4,bh4)|0,lo=lo+Math.imul(al3,bl5)|0,mid=(mid=mid+Math.imul(al3,bh5)|0)+Math.imul(ah3,bl5)|0,hi=hi+Math.imul(ah3,bh5)|0,lo=lo+Math.imul(al2,bl6)|0,mid=(mid=mid+Math.imul(al2,bh6)|0)+Math.imul(ah2,bl6)|0,hi=hi+Math.imul(ah2,bh6)|0,lo=lo+Math.imul(al1,bl7)|0,mid=(mid=mid+Math.imul(al1,bh7)|0)+Math.imul(ah1,bl7)|0,hi=hi+Math.imul(ah1,bh7)|0;var w8=(c+(lo=lo+Math.imul(al0,bl8)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh8)|0)+Math.imul(ah0,bl8)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh8)|0)+(mid>>>13)|0)+(w8>>>26)|0,w8&=67108863,lo=Math.imul(al9,bl0),mid=(mid=Math.imul(al9,bh0))+Math.imul(ah9,bl0)|0,hi=Math.imul(ah9,bh0),lo=lo+Math.imul(al8,bl1)|0,mid=(mid=mid+Math.imul(al8,bh1)|0)+Math.imul(ah8,bl1)|0,hi=hi+Math.imul(ah8,bh1)|0,lo=lo+Math.imul(al7,bl2)|0,mid=(mid=mid+Math.imul(al7,bh2)|0)+Math.imul(ah7,bl2)|0,hi=hi+Math.imul(ah7,bh2)|0,lo=lo+Math.imul(al6,bl3)|0,mid=(mid=mid+Math.imul(al6,bh3)|0)+Math.imul(ah6,bl3)|0,hi=hi+Math.imul(ah6,bh3)|0,lo=lo+Math.imul(al5,bl4)|0,mid=(mid=mid+Math.imul(al5,bh4)|0)+Math.imul(ah5,bl4)|0,hi=hi+Math.imul(ah5,bh4)|0,lo=lo+Math.imul(al4,bl5)|0,mid=(mid=mid+Math.imul(al4,bh5)|0)+Math.imul(ah4,bl5)|0,hi=hi+Math.imul(ah4,bh5)|0,lo=lo+Math.imul(al3,bl6)|0,mid=(mid=mid+Math.imul(al3,bh6)|0)+Math.imul(ah3,bl6)|0,hi=hi+Math.imul(ah3,bh6)|0,lo=lo+Math.imul(al2,bl7)|0,mid=(mid=mid+Math.imul(al2,bh7)|0)+Math.imul(ah2,bl7)|0,hi=hi+Math.imul(ah2,bh7)|0,lo=lo+Math.imul(al1,bl8)|0,mid=(mid=mid+Math.imul(al1,bh8)|0)+Math.imul(ah1,bl8)|0,hi=hi+Math.imul(ah1,bh8)|0;var w9=(c+(lo=lo+Math.imul(al0,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh9)|0)+Math.imul(ah0,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh9)|0)+(mid>>>13)|0)+(w9>>>26)|0,w9&=67108863,lo=Math.imul(al9,bl1),mid=(mid=Math.imul(al9,bh1))+Math.imul(ah9,bl1)|0,hi=Math.imul(ah9,bh1),lo=lo+Math.imul(al8,bl2)|0,mid=(mid=mid+Math.imul(al8,bh2)|0)+Math.imul(ah8,bl2)|0,hi=hi+Math.imul(ah8,bh2)|0,lo=lo+Math.imul(al7,bl3)|0,mid=(mid=mid+Math.imul(al7,bh3)|0)+Math.imul(ah7,bl3)|0,hi=hi+Math.imul(ah7,bh3)|0,lo=lo+Math.imul(al6,bl4)|0,mid=(mid=mid+Math.imul(al6,bh4)|0)+Math.imul(ah6,bl4)|0,hi=hi+Math.imul(ah6,bh4)|0,lo=lo+Math.imul(al5,bl5)|0,mid=(mid=mid+Math.imul(al5,bh5)|0)+Math.imul(ah5,bl5)|0,hi=hi+Math.imul(ah5,bh5)|0,lo=lo+Math.imul(al4,bl6)|0,mid=(mid=mid+Math.imul(al4,bh6)|0)+Math.imul(ah4,bl6)|0,hi=hi+Math.imul(ah4,bh6)|0,lo=lo+Math.imul(al3,bl7)|0,mid=(mid=mid+Math.imul(al3,bh7)|0)+Math.imul(ah3,bl7)|0,hi=hi+Math.imul(ah3,bh7)|0,lo=lo+Math.imul(al2,bl8)|0,mid=(mid=mid+Math.imul(al2,bh8)|0)+Math.imul(ah2,bl8)|0,hi=hi+Math.imul(ah2,bh8)|0;var w10=(c+(lo=lo+Math.imul(al1,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al1,bh9)|0)+Math.imul(ah1,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah1,bh9)|0)+(mid>>>13)|0)+(w10>>>26)|0,w10&=67108863,lo=Math.imul(al9,bl2),mid=(mid=Math.imul(al9,bh2))+Math.imul(ah9,bl2)|0,hi=Math.imul(ah9,bh2),lo=lo+Math.imul(al8,bl3)|0,mid=(mid=mid+Math.imul(al8,bh3)|0)+Math.imul(ah8,bl3)|0,hi=hi+Math.imul(ah8,bh3)|0,lo=lo+Math.imul(al7,bl4)|0,mid=(mid=mid+Math.imul(al7,bh4)|0)+Math.imul(ah7,bl4)|0,hi=hi+Math.imul(ah7,bh4)|0,lo=lo+Math.imul(al6,bl5)|0,mid=(mid=mid+Math.imul(al6,bh5)|0)+Math.imul(ah6,bl5)|0,hi=hi+Math.imul(ah6,bh5)|0,lo=lo+Math.imul(al5,bl6)|0,mid=(mid=mid+Math.imul(al5,bh6)|0)+Math.imul(ah5,bl6)|0,hi=hi+Math.imul(ah5,bh6)|0,lo=lo+Math.imul(al4,bl7)|0,mid=(mid=mid+Math.imul(al4,bh7)|0)+Math.imul(ah4,bl7)|0,hi=hi+Math.imul(ah4,bh7)|0,lo=lo+Math.imul(al3,bl8)|0,mid=(mid=mid+Math.imul(al3,bh8)|0)+Math.imul(ah3,bl8)|0,hi=hi+Math.imul(ah3,bh8)|0;var w11=(c+(lo=lo+Math.imul(al2,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al2,bh9)|0)+Math.imul(ah2,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah2,bh9)|0)+(mid>>>13)|0)+(w11>>>26)|0,w11&=67108863,lo=Math.imul(al9,bl3),mid=(mid=Math.imul(al9,bh3))+Math.imul(ah9,bl3)|0,hi=Math.imul(ah9,bh3),lo=lo+Math.imul(al8,bl4)|0,mid=(mid=mid+Math.imul(al8,bh4)|0)+Math.imul(ah8,bl4)|0,hi=hi+Math.imul(ah8,bh4)|0,lo=lo+Math.imul(al7,bl5)|0,mid=(mid=mid+Math.imul(al7,bh5)|0)+Math.imul(ah7,bl5)|0,hi=hi+Math.imul(ah7,bh5)|0,lo=lo+Math.imul(al6,bl6)|0,mid=(mid=mid+Math.imul(al6,bh6)|0)+Math.imul(ah6,bl6)|0,hi=hi+Math.imul(ah6,bh6)|0,lo=lo+Math.imul(al5,bl7)|0,mid=(mid=mid+Math.imul(al5,bh7)|0)+Math.imul(ah5,bl7)|0,hi=hi+Math.imul(ah5,bh7)|0,lo=lo+Math.imul(al4,bl8)|0,mid=(mid=mid+Math.imul(al4,bh8)|0)+Math.imul(ah4,bl8)|0,hi=hi+Math.imul(ah4,bh8)|0;var w12=(c+(lo=lo+Math.imul(al3,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al3,bh9)|0)+Math.imul(ah3,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah3,bh9)|0)+(mid>>>13)|0)+(w12>>>26)|0,w12&=67108863,lo=Math.imul(al9,bl4),mid=(mid=Math.imul(al9,bh4))+Math.imul(ah9,bl4)|0,hi=Math.imul(ah9,bh4),lo=lo+Math.imul(al8,bl5)|0,mid=(mid=mid+Math.imul(al8,bh5)|0)+Math.imul(ah8,bl5)|0,hi=hi+Math.imul(ah8,bh5)|0,lo=lo+Math.imul(al7,bl6)|0,mid=(mid=mid+Math.imul(al7,bh6)|0)+Math.imul(ah7,bl6)|0,hi=hi+Math.imul(ah7,bh6)|0,lo=lo+Math.imul(al6,bl7)|0,mid=(mid=mid+Math.imul(al6,bh7)|0)+Math.imul(ah6,bl7)|0,hi=hi+Math.imul(ah6,bh7)|0,lo=lo+Math.imul(al5,bl8)|0,mid=(mid=mid+Math.imul(al5,bh8)|0)+Math.imul(ah5,bl8)|0,hi=hi+Math.imul(ah5,bh8)|0;var w13=(c+(lo=lo+Math.imul(al4,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al4,bh9)|0)+Math.imul(ah4,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah4,bh9)|0)+(mid>>>13)|0)+(w13>>>26)|0,w13&=67108863,lo=Math.imul(al9,bl5),mid=(mid=Math.imul(al9,bh5))+Math.imul(ah9,bl5)|0,hi=Math.imul(ah9,bh5),lo=lo+Math.imul(al8,bl6)|0,mid=(mid=mid+Math.imul(al8,bh6)|0)+Math.imul(ah8,bl6)|0,hi=hi+Math.imul(ah8,bh6)|0,lo=lo+Math.imul(al7,bl7)|0,mid=(mid=mid+Math.imul(al7,bh7)|0)+Math.imul(ah7,bl7)|0,hi=hi+Math.imul(ah7,bh7)|0,lo=lo+Math.imul(al6,bl8)|0,mid=(mid=mid+Math.imul(al6,bh8)|0)+Math.imul(ah6,bl8)|0,hi=hi+Math.imul(ah6,bh8)|0;var w14=(c+(lo=lo+Math.imul(al5,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al5,bh9)|0)+Math.imul(ah5,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah5,bh9)|0)+(mid>>>13)|0)+(w14>>>26)|0,w14&=67108863,lo=Math.imul(al9,bl6),mid=(mid=Math.imul(al9,bh6))+Math.imul(ah9,bl6)|0,hi=Math.imul(ah9,bh6),lo=lo+Math.imul(al8,bl7)|0,mid=(mid=mid+Math.imul(al8,bh7)|0)+Math.imul(ah8,bl7)|0,hi=hi+Math.imul(ah8,bh7)|0,lo=lo+Math.imul(al7,bl8)|0,mid=(mid=mid+Math.imul(al7,bh8)|0)+Math.imul(ah7,bl8)|0,hi=hi+Math.imul(ah7,bh8)|0;var w15=(c+(lo=lo+Math.imul(al6,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al6,bh9)|0)+Math.imul(ah6,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah6,bh9)|0)+(mid>>>13)|0)+(w15>>>26)|0,w15&=67108863,lo=Math.imul(al9,bl7),mid=(mid=Math.imul(al9,bh7))+Math.imul(ah9,bl7)|0,hi=Math.imul(ah9,bh7),lo=lo+Math.imul(al8,bl8)|0,mid=(mid=mid+Math.imul(al8,bh8)|0)+Math.imul(ah8,bl8)|0,hi=hi+Math.imul(ah8,bh8)|0;var w16=(c+(lo=lo+Math.imul(al7,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al7,bh9)|0)+Math.imul(ah7,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah7,bh9)|0)+(mid>>>13)|0)+(w16>>>26)|0,w16&=67108863,lo=Math.imul(al9,bl8),mid=(mid=Math.imul(al9,bh8))+Math.imul(ah9,bl8)|0,hi=Math.imul(ah9,bh8);var w17=(c+(lo=lo+Math.imul(al8,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al8,bh9)|0)+Math.imul(ah8,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah8,bh9)|0)+(mid>>>13)|0)+(w17>>>26)|0,w17&=67108863;var w18=(c+(lo=Math.imul(al9,bl9))|0)+((8191&(mid=(mid=Math.imul(al9,bh9))+Math.imul(ah9,bl9)|0))<<13)|0;return c=((hi=Math.imul(ah9,bh9))+(mid>>>13)|0)+(w18>>>26)|0,w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,0!==c&&(o[19]=c,out.length++),out};function jumboMulTo(self,num,out){return(new FFTM).mulp(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}Math.imul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function mulTo(num,out){var res,len=this.length+num.length;return res=10===this.length&&10===num.length?comb10MulTo(this,num,out):len<63?smallMulTo(this,num,out):len<1024?function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0;k>>26)|0)>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0!==carry?out.words[k]=carry:out.length--,out.strip()}(this,num,out):jumboMulTo(this,num,out),res},FFTM.prototype.makeRBT=function makeRBT(N){for(var t=new Array(N),l=BN.prototype._countBits(N)-1,i=0;i>=1;return rb},FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>=1)i++;return 1<>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;i>=26,carry+=w/67108864|0,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.muln=function muln(num){return this.clone().imuln(num)},BN.prototype.sqr=function sqr(){return this.mul(this)},BN.prototype.isqr=function isqr(){return this.imul(this.clone())},BN.prototype.pow=function pow(num){var w=function toBitArray(num){for(var w=new Array(num.bitLength()),bit=0;bit>>wbit}return w}(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i=0);var i,r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r;if(0!==r){var carry=0;for(i=0;i>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;i>=0;i--)this.words[i+s]=this.words[i];for(i=0;i=0),h=hint?(hint-hint%26)/26:0;var r=bits%26,s=Math.min((bits-r)/26,this.length),mask=67108863^67108863>>>r<s)for(this.length-=s,i=0;i=0&&(0!==carry||i>=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&0!==carry&&(maskedWords.words[maskedWords.length++]=carry),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},BN.prototype.ishrn=function ishrn(bits,hint,extended){return assert(0===this.negative),this.iushrn(bits,hint,extended)},BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function testn(bit){assert("number"==typeof bit&&bit>=0);var r=bit%26,s=(bit-r)/26,q=1<=0);var r=bits%26,s=(bits-r)/26;if(assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!==r&&s++,this.length=Math.min(s,this.length),0!==r){var mask=67108863^67108863>>>r<=67108864;i++)this.words[i]-=67108864,i===this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=Math.max(this.length,i+1),this},BN.prototype.isubn=function isubn(num){if(assert("number"==typeof num),assert(num<67108864),num<0)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i>26)-(right/67108864|0),this.words[i+shift]=67108863&w}for(;i>26,this.words[i+shift]=67108863&w;if(0===carry)return this.strip();for(assert(-1===carry),carry=0,i=0;i>26,this.words[i]=67108863&w;return this.negative=1,this.strip()},BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=(this.length,num.length),a=this.clone(),b=num,bhi=0|b.words[b.length-1];0!==(shift=26-this._countBits(bhi))&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var q,m=a.length-b.length;if("mod"!==mode){(q=new BN(null)).length=m+1,q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=67108864*(0|a.words[b.length+j])+(0|a.words[b.length+j-1]);for(qj=Math.min(qj/bhi|0,67108863),a._ishlnsubmul(b,qj,j);0!==a.negative;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q.strip(),a.strip(),"div"!==mode&&0!==shift&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function divmod(num,mode,positive){return assert(!num.isZero()),this.isZero()?{div:new BN(0),mod:new BN(0)}:0!==this.negative&&0===num.negative?(res=this.neg().divmod(num,mode),"mod"!==mode&&(div=res.div.neg()),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.iadd(num)),{div,mod}):0===this.negative&&0!==num.negative?(res=this.divmod(num.neg(),mode),"mod"!==mode&&(div=res.div.neg()),{div,mod:res.mod}):0!=(this.negative&num.negative)?(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod}):num.length>this.length||this.cmp(num)<0?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modn(num.words[0]))}:this._wordDiv(num,mode);var div,mod,res},BN.prototype.div=function div(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function mod(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function umod(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0!==dm.div.negative?dm.mod.isub(num):dm.mod,half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return cmp<0||1===r2&&0===cmp?dm.div:0!==dm.div.negative?dm.div.isubn(1):dm.div.iaddn(1)},BN.prototype.modn=function modn(num){assert(num<=67108863);for(var p=(1<<26)%num,acc=0,i=this.length-1;i>=0;i--)acc=(p*acc+(0|this.words[i]))%num;return acc},BN.prototype.idivn=function idivn(num){assert(num<=67108863);for(var carry=0,i=this.length-1;i>=0;i--){var w=(0|this.words[i])+67108864*carry;this.words[i]=w/num|0,carry=w%num}return this.strip()},BN.prototype.divn=function divn(num){return this.clone().idivn(num)},BN.prototype.egcd=function egcd(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0!==x.negative?x.umod(p):x.clone();for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0==(x.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(x.iushrn(i);i-- >0;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;0==(y.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(y.iushrn(j);j-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);x.cmp(y)>=0?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function _invmp(p){assert(0===p.negative),assert(!p.isZero());var a=this,b=p.clone();a=0!==a.negative?a.umod(p):a.clone();for(var res,x1=new BN(1),x2=new BN(0),delta=b.clone();a.cmpn(1)>0&&b.cmpn(1)>0;){for(var i=0,im=1;0==(a.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(a.iushrn(i);i-- >0;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;0==(b.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(b.iushrn(j);j-- >0;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);a.cmp(b)>=0?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}return(res=0===a.cmpn(1)?x1:x2).cmpn(0)<0&&res.iadd(p),res},BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);for(;;){for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(r<0){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}return b.iushln(shift)},BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function isEven(){return 0==(1&this.words[0])},BN.prototype.isOdd=function isOdd(){return 1==(1&this.words[0])},BN.prototype.andln=function andln(num){return this.words[0]&num},BN.prototype.bincn=function bincn(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<>>26,w&=67108863,this.words[i]=w}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function isZero(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function cmpn(num){var res,negative=num<0;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;if(this.strip(),this.length>1)res=1;else{negative&&(num=-num),assert(num<=67108863,"Number is too big");var w=0|this.words[0];res=w===num?0:wnum.length)return 1;if(this.length=0;i--){var a=0|this.words[i],b=0|num.words[i];if(a!==b){ab&&(res=1);break}}return res},BN.prototype.gtn=function gtn(num){return 1===this.cmpn(num)},BN.prototype.gt=function gt(num){return 1===this.cmp(num)},BN.prototype.gten=function gten(num){return this.cmpn(num)>=0},BN.prototype.gte=function gte(num){return this.cmp(num)>=0},BN.prototype.ltn=function ltn(num){return-1===this.cmpn(num)},BN.prototype.lt=function lt(num){return-1===this.cmp(num)},BN.prototype.lten=function lten(num){return this.cmpn(num)<=0},BN.prototype.lte=function lte(num){return this.cmp(num)<=0},BN.prototype.eqn=function eqn(num){return 0===this.cmpn(num)},BN.prototype.eq=function eq(num){return 0===this.cmp(num)},BN.red=function red(num){return new Red(num)},BN.prototype.toRed=function toRed(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function fromRed(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function _forceRed(ctx){return this.red=ctx,this},BN.prototype.forceRed=function forceRed(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function redAdd(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function redIAdd(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function redSub(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function redISub(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function redShl(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function redMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function redIMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function redSqr(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function redISqr(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function redSqrt(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function redInvm(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function redNeg(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function redPow(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);return tmp.words=new Array(Math.ceil(this.n/13)),tmp},MPrime.prototype.ireduce=function ireduce(num){var rlen,r=num;do{this.split(r,this.tmp),rlen=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(rlen>this.n);var cmp=rlen0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)},inherits(K256,MPrime),K256.prototype.split=function split(input,output){for(var outLen=Math.min(input.length,9),i=0;i>>22,prev=next}prev>>>=22,input.words[i-10]=prev,0===prev&&input.length>10?input.length-=10:input.length-=9},K256.prototype.imulK=function imulK(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0;i>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else{if("p25519"!==name)throw new Error("Unknown prime "+name);prime=new P25519}return primes[name]=prime,prime},Red.prototype._verify1=function _verify1(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function _verify2(a,b){assert(0==(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function imod(a){return this.prime?this.prime.ireduce(a)._forceRed(this):a.umod(this.m)._forceRed(this)},Red.prototype.neg=function neg(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);return res.cmp(this.m)>=0&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);return res.cmp(this.m)>=0&&res.isub(this.m),res},Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);return res.cmpn(0)<0&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);return res.cmpn(0)<0&&res.iadd(this.m),res},Red.prototype.shl=function shl(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function imul(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function mul(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())},Red.prototype.sqr=function sqr(a){return this.mul(a,a)},Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(mod3%2==1),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i=0;i--){for(var word=num.words[i],j=start-1;j>=0;j--){var bit=word>>j&1;res!==wnd[0]&&(res=this.sqr(res)),0!==bit||0!==current?(current<<=1,current|=bit,(4===++currentLen||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)):currentLen=0}start=26}return res},Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();return res.red=null,res},BN.mont=function mont(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function invm(a){return this.imod(a._invmp(this.m).mul(this.r2))._forceRed(this)}}(module=__webpack_require__.nmd(module),this)},3482:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var inherits=__webpack_require__(5717),MD5=__webpack_require__(2318),RIPEMD160=__webpack_require__(9785),sha=__webpack_require__(9072),Base=__webpack_require__(1027);function Hash(hash){Base.call(this,"digest"),this._hash=hash}inherits(Hash,Base),Hash.prototype._update=function(data){this._hash.update(data)},Hash.prototype._final=function(){return this._hash.digest()},module.exports=function createHash(alg){return"md5"===(alg=alg.toLowerCase())?new MD5:"rmd160"===alg||"ripemd160"===alg?new RIPEMD160:new Hash(sha(alg))}},8028:(module,__unused_webpack_exports,__webpack_require__)=>{var MD5=__webpack_require__(2318);module.exports=function(buffer){return(new MD5).update(buffer).digest()}},8355:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var inherits=__webpack_require__(5717),Legacy=__webpack_require__(1031),Base=__webpack_require__(1027),Buffer=__webpack_require__(9509).Buffer,md5=__webpack_require__(8028),RIPEMD160=__webpack_require__(9785),sha=__webpack_require__(9072),ZEROS=Buffer.alloc(128);function Hmac(alg,key){Base.call(this,"digest"),"string"==typeof key&&(key=Buffer.from(key));var blocksize="sha512"===alg||"sha384"===alg?128:64;(this._alg=alg,this._key=key,key.length>blocksize)?key=("rmd160"===alg?new RIPEMD160:sha(alg)).update(key).digest():key.length{"use strict";var inherits=__webpack_require__(5717),Buffer=__webpack_require__(9509).Buffer,Base=__webpack_require__(1027),ZEROS=Buffer.alloc(128);function Hmac(alg,key){Base.call(this,"digest"),"string"==typeof key&&(key=Buffer.from(key)),this._alg=alg,this._key=key,key.length>64?key=alg(key):key.length<64&&(key=Buffer.concat([key,ZEROS],64));for(var ipad=this._ipad=Buffer.allocUnsafe(64),opad=this._opad=Buffer.allocUnsafe(64),i=0;i<64;i++)ipad[i]=54^key[i],opad[i]=92^key[i];this._hash=[ipad]}inherits(Hmac,Base),Hmac.prototype._update=function(data){this._hash.push(data)},Hmac.prototype._final=function(){var h=this._alg(Buffer.concat(this._hash));return this._alg(Buffer.concat([this._opad,h]))},module.exports=Hmac},5835:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";exports.randomBytes=exports.rng=exports.pseudoRandomBytes=exports.prng=__webpack_require__(1798),exports.createHash=exports.Hash=__webpack_require__(3482),exports.createHmac=exports.Hmac=__webpack_require__(8355);var algos=__webpack_require__(6042),algoKeys=Object.keys(algos),hashes=["sha1","sha224","sha256","sha384","sha512","md5","rmd160"].concat(algoKeys);exports.getHashes=function(){return hashes};var p=__webpack_require__(5632);exports.pbkdf2=p.pbkdf2,exports.pbkdf2Sync=p.pbkdf2Sync;var aes=__webpack_require__(3614);exports.Cipher=aes.Cipher,exports.createCipher=aes.createCipher,exports.Cipheriv=aes.Cipheriv,exports.createCipheriv=aes.createCipheriv,exports.Decipher=aes.Decipher,exports.createDecipher=aes.createDecipher,exports.Decipheriv=aes.Decipheriv,exports.createDecipheriv=aes.createDecipheriv,exports.getCiphers=aes.getCiphers,exports.listCiphers=aes.listCiphers;var dh=__webpack_require__(2607);exports.DiffieHellmanGroup=dh.DiffieHellmanGroup,exports.createDiffieHellmanGroup=dh.createDiffieHellmanGroup,exports.getDiffieHellman=dh.getDiffieHellman,exports.createDiffieHellman=dh.createDiffieHellman,exports.DiffieHellman=dh.DiffieHellman;var sign=__webpack_require__(4743);exports.createSign=sign.createSign,exports.Sign=sign.Sign,exports.createVerify=sign.createVerify,exports.Verify=sign.Verify,exports.createECDH=__webpack_require__(6393);var publicEncrypt=__webpack_require__(7900);exports.publicEncrypt=publicEncrypt.publicEncrypt,exports.privateEncrypt=publicEncrypt.privateEncrypt,exports.publicDecrypt=publicEncrypt.publicDecrypt,exports.privateDecrypt=publicEncrypt.privateDecrypt;var rf=__webpack_require__(7963);exports.randomFill=rf.randomFill,exports.randomFillSync=rf.randomFillSync,exports.createCredentials=function(){throw new Error(["sorry, createCredentials is not implemented yet","we accept pull requests","https://github.com/crypto-browserify/crypto-browserify"].join("\n"))},exports.constants={DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,NPN_ENABLED:1,ALPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_SSLV23_PADDING:2,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6}},2667:(module,__unused_webpack_exports,__webpack_require__)=>{var DEFAULT=__webpack_require__(9950),parseStyle=__webpack_require__(6771);__webpack_require__(7381);function isNull(obj){return null==obj}function FilterCSS(options){(options=function shallowCopyObject(obj){var ret={};for(var i in obj)ret[i]=obj[i];return ret}(options||{})).whiteList=options.whiteList||DEFAULT.whiteList,options.onAttr=options.onAttr||DEFAULT.onAttr,options.onIgnoreAttr=options.onIgnoreAttr||DEFAULT.onIgnoreAttr,options.safeAttrValue=options.safeAttrValue||DEFAULT.safeAttrValue,this.options=options}FilterCSS.prototype.process=function(css){if(!(css=(css=css||"").toString()))return"";var options=this.options,whiteList=options.whiteList,onAttr=options.onAttr,onIgnoreAttr=options.onIgnoreAttr,safeAttrValue=options.safeAttrValue;return parseStyle(css,(function(sourcePosition,position,name,value,source){var check=whiteList[name],isWhite=!1;if(!0===check?isWhite=check:"function"==typeof check?isWhite=check(value):check instanceof RegExp&&(isWhite=check.test(value)),!0!==isWhite&&(isWhite=!1),value=safeAttrValue(name,value)){var ret,opts={position,sourcePosition,source,isWhite};return isWhite?isNull(ret=onAttr(name,value,opts))?name+":"+value:ret:isNull(ret=onIgnoreAttr(name,value,opts))?void 0:ret}}))},module.exports=FilterCSS},9950:(__unused_webpack_module,exports)=>{function getDefaultWhiteList(){var whiteList={"align-content":!1,"align-items":!1,"align-self":!1,"alignment-adjust":!1,"alignment-baseline":!1,all:!1,"anchor-point":!1,animation:!1,"animation-delay":!1,"animation-direction":!1,"animation-duration":!1,"animation-fill-mode":!1,"animation-iteration-count":!1,"animation-name":!1,"animation-play-state":!1,"animation-timing-function":!1,azimuth:!1,"backface-visibility":!1,background:!0,"background-attachment":!0,"background-clip":!0,"background-color":!0,"background-image":!0,"background-origin":!0,"background-position":!0,"background-repeat":!0,"background-size":!0,"baseline-shift":!1,binding:!1,bleed:!1,"bookmark-label":!1,"bookmark-level":!1,"bookmark-state":!1,border:!0,"border-bottom":!0,"border-bottom-color":!0,"border-bottom-left-radius":!0,"border-bottom-right-radius":!0,"border-bottom-style":!0,"border-bottom-width":!0,"border-collapse":!0,"border-color":!0,"border-image":!0,"border-image-outset":!0,"border-image-repeat":!0,"border-image-slice":!0,"border-image-source":!0,"border-image-width":!0,"border-left":!0,"border-left-color":!0,"border-left-style":!0,"border-left-width":!0,"border-radius":!0,"border-right":!0,"border-right-color":!0,"border-right-style":!0,"border-right-width":!0,"border-spacing":!0,"border-style":!0,"border-top":!0,"border-top-color":!0,"border-top-left-radius":!0,"border-top-right-radius":!0,"border-top-style":!0,"border-top-width":!0,"border-width":!0,bottom:!1,"box-decoration-break":!0,"box-shadow":!0,"box-sizing":!0,"box-snap":!0,"box-suppress":!0,"break-after":!0,"break-before":!0,"break-inside":!0,"caption-side":!1,chains:!1,clear:!0,clip:!1,"clip-path":!1,"clip-rule":!1,color:!0,"color-interpolation-filters":!0,"column-count":!1,"column-fill":!1,"column-gap":!1,"column-rule":!1,"column-rule-color":!1,"column-rule-style":!1,"column-rule-width":!1,"column-span":!1,"column-width":!1,columns:!1,contain:!1,content:!1,"counter-increment":!1,"counter-reset":!1,"counter-set":!1,crop:!1,cue:!1,"cue-after":!1,"cue-before":!1,cursor:!1,direction:!1,display:!0,"display-inside":!0,"display-list":!0,"display-outside":!0,"dominant-baseline":!1,elevation:!1,"empty-cells":!1,filter:!1,flex:!1,"flex-basis":!1,"flex-direction":!1,"flex-flow":!1,"flex-grow":!1,"flex-shrink":!1,"flex-wrap":!1,float:!1,"float-offset":!1,"flood-color":!1,"flood-opacity":!1,"flow-from":!1,"flow-into":!1,font:!0,"font-family":!0,"font-feature-settings":!0,"font-kerning":!0,"font-language-override":!0,"font-size":!0,"font-size-adjust":!0,"font-stretch":!0,"font-style":!0,"font-synthesis":!0,"font-variant":!0,"font-variant-alternates":!0,"font-variant-caps":!0,"font-variant-east-asian":!0,"font-variant-ligatures":!0,"font-variant-numeric":!0,"font-variant-position":!0,"font-weight":!0,grid:!1,"grid-area":!1,"grid-auto-columns":!1,"grid-auto-flow":!1,"grid-auto-rows":!1,"grid-column":!1,"grid-column-end":!1,"grid-column-start":!1,"grid-row":!1,"grid-row-end":!1,"grid-row-start":!1,"grid-template":!1,"grid-template-areas":!1,"grid-template-columns":!1,"grid-template-rows":!1,"hanging-punctuation":!1,height:!0,hyphens:!1,icon:!1,"image-orientation":!1,"image-resolution":!1,"ime-mode":!1,"initial-letters":!1,"inline-box-align":!1,"justify-content":!1,"justify-items":!1,"justify-self":!1,left:!1,"letter-spacing":!0,"lighting-color":!0,"line-box-contain":!1,"line-break":!1,"line-grid":!1,"line-height":!1,"line-snap":!1,"line-stacking":!1,"line-stacking-ruby":!1,"line-stacking-shift":!1,"line-stacking-strategy":!1,"list-style":!0,"list-style-image":!0,"list-style-position":!0,"list-style-type":!0,margin:!0,"margin-bottom":!0,"margin-left":!0,"margin-right":!0,"margin-top":!0,"marker-offset":!1,"marker-side":!1,marks:!1,mask:!1,"mask-box":!1,"mask-box-outset":!1,"mask-box-repeat":!1,"mask-box-slice":!1,"mask-box-source":!1,"mask-box-width":!1,"mask-clip":!1,"mask-image":!1,"mask-origin":!1,"mask-position":!1,"mask-repeat":!1,"mask-size":!1,"mask-source-type":!1,"mask-type":!1,"max-height":!0,"max-lines":!1,"max-width":!0,"min-height":!0,"min-width":!0,"move-to":!1,"nav-down":!1,"nav-index":!1,"nav-left":!1,"nav-right":!1,"nav-up":!1,"object-fit":!1,"object-position":!1,opacity:!1,order:!1,orphans:!1,outline:!1,"outline-color":!1,"outline-offset":!1,"outline-style":!1,"outline-width":!1,overflow:!1,"overflow-wrap":!1,"overflow-x":!1,"overflow-y":!1,padding:!0,"padding-bottom":!0,"padding-left":!0,"padding-right":!0,"padding-top":!0,page:!1,"page-break-after":!1,"page-break-before":!1,"page-break-inside":!1,"page-policy":!1,pause:!1,"pause-after":!1,"pause-before":!1,perspective:!1,"perspective-origin":!1,pitch:!1,"pitch-range":!1,"play-during":!1,position:!1,"presentation-level":!1,quotes:!1,"region-fragment":!1,resize:!1,rest:!1,"rest-after":!1,"rest-before":!1,richness:!1,right:!1,rotation:!1,"rotation-point":!1,"ruby-align":!1,"ruby-merge":!1,"ruby-position":!1,"shape-image-threshold":!1,"shape-outside":!1,"shape-margin":!1,size:!1,speak:!1,"speak-as":!1,"speak-header":!1,"speak-numeral":!1,"speak-punctuation":!1,"speech-rate":!1,stress:!1,"string-set":!1,"tab-size":!1,"table-layout":!1,"text-align":!0,"text-align-last":!0,"text-combine-upright":!0,"text-decoration":!0,"text-decoration-color":!0,"text-decoration-line":!0,"text-decoration-skip":!0,"text-decoration-style":!0,"text-emphasis":!0,"text-emphasis-color":!0,"text-emphasis-position":!0,"text-emphasis-style":!0,"text-height":!0,"text-indent":!0,"text-justify":!0,"text-orientation":!0,"text-overflow":!0,"text-shadow":!0,"text-space-collapse":!0,"text-transform":!0,"text-underline-position":!0,"text-wrap":!0,top:!1,transform:!1,"transform-origin":!1,"transform-style":!1,transition:!1,"transition-delay":!1,"transition-duration":!1,"transition-property":!1,"transition-timing-function":!1,"unicode-bidi":!1,"vertical-align":!1,visibility:!1,"voice-balance":!1,"voice-duration":!1,"voice-family":!1,"voice-pitch":!1,"voice-range":!1,"voice-rate":!1,"voice-stress":!1,"voice-volume":!1,volume:!1,"white-space":!1,widows:!1,width:!0,"will-change":!1,"word-break":!0,"word-spacing":!0,"word-wrap":!0,"wrap-flow":!1,"wrap-through":!1,"writing-mode":!1,"z-index":!1};return whiteList}var REGEXP_URL_JAVASCRIPT=/javascript\s*\:/gim;exports.whiteList=getDefaultWhiteList(),exports.getDefaultWhiteList=getDefaultWhiteList,exports.onAttr=function onAttr(name,value,options){},exports.onIgnoreAttr=function onIgnoreAttr(name,value,options){},exports.safeAttrValue=function safeAttrValue(name,value){return REGEXP_URL_JAVASCRIPT.test(value)?"":value}},9970:(module,exports,__webpack_require__)=>{var DEFAULT=__webpack_require__(9950),FilterCSS=__webpack_require__(2667);for(var i in(exports=module.exports=function filterCSS(html,options){return new FilterCSS(options).process(html)}).FilterCSS=FilterCSS,DEFAULT)exports[i]=DEFAULT[i];"undefined"!=typeof window&&(window.filterCSS=module.exports)},6771:(module,__unused_webpack_exports,__webpack_require__)=>{var _=__webpack_require__(7381);module.exports=function parseStyle(css,onAttr){";"!==(css=_.trimRight(css))[css.length-1]&&(css+=";");var cssLength=css.length,isParenthesisOpen=!1,lastPos=0,i=0,retCSS="";function addNewAttr(){if(!isParenthesisOpen){var source=_.trim(css.slice(lastPos,i)),j=source.indexOf(":");if(-1!==j){var name=_.trim(source.slice(0,j)),value=_.trim(source.slice(j+1));if(name){var ret=onAttr(lastPos,retCSS.length,name,value,source);ret&&(retCSS+=ret+"; ")}}}lastPos=i+1}for(;i{module.exports={indexOf:function(arr,item){var i,j;if(Array.prototype.indexOf)return arr.indexOf(item);for(i=0,j=arr.length;i{"use strict";var keys=__webpack_require__(2215),hasSymbols="function"==typeof Symbol&&"symbol"==typeof Symbol("foo"),toStr=Object.prototype.toString,concat=Array.prototype.concat,origDefineProperty=Object.defineProperty,hasPropertyDescriptors=__webpack_require__(1044)(),supportsDescriptors=origDefineProperty&&hasPropertyDescriptors,defineProperty=function(object,name,value,predicate){var fn;(!(name in object)||"function"==typeof(fn=predicate)&&"[object Function]"===toStr.call(fn)&&predicate())&&(supportsDescriptors?origDefineProperty(object,name,{configurable:!0,enumerable:!1,value,writable:!0}):object[name]=value)},defineProperties=function(object,map){var predicates=arguments.length>2?arguments[2]:{},props=keys(map);hasSymbols&&(props=concat.call(props,Object.getOwnPropertySymbols(map)));for(var i=0;i{"use strict";exports.utils=__webpack_require__(1278),exports.Cipher=__webpack_require__(5756),exports.DES=__webpack_require__(778),exports.CBC=__webpack_require__(9051),exports.EDE=__webpack_require__(651)},9051:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";var assert=__webpack_require__(9746),inherits=__webpack_require__(5717),proto={};function CBCState(iv){assert.equal(iv.length,8,"Invalid IV length"),this.iv=new Array(8);for(var i=0;i{"use strict";var assert=__webpack_require__(9746);function Cipher(options){this.options=options,this.type=this.options.type,this.blockSize=8,this._init(),this.buffer=new Array(this.blockSize),this.bufferOff=0}module.exports=Cipher,Cipher.prototype._init=function _init(){},Cipher.prototype.update=function update(data){return 0===data.length?[]:"decrypt"===this.type?this._updateDecrypt(data):this._updateEncrypt(data)},Cipher.prototype._buffer=function _buffer(data,off){for(var min=Math.min(this.buffer.length-this.bufferOff,data.length-off),i=0;i0;count--)inputOff+=this._buffer(data,inputOff),outputOff+=this._flushBuffer(out,outputOff);return inputOff+=this._buffer(data,inputOff),out},Cipher.prototype.final=function final(buffer){var first,last;return buffer&&(first=this.update(buffer)),last="encrypt"===this.type?this._finalEncrypt():this._finalDecrypt(),first?first.concat(last):last},Cipher.prototype._pad=function _pad(buffer,off){if(0===off)return!1;for(;off{"use strict";var assert=__webpack_require__(9746),inherits=__webpack_require__(5717),utils=__webpack_require__(1278),Cipher=__webpack_require__(5756);function DESState(){this.tmp=new Array(2),this.keys=null}function DES(options){Cipher.call(this,options);var state=new DESState;this._desState=state,this.deriveKeys(state,options.key)}inherits(DES,Cipher),module.exports=DES,DES.create=function create(options){return new DES(options)};var shiftTable=[1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1];DES.prototype.deriveKeys=function deriveKeys(state,key){state.keys=new Array(32),assert.equal(key.length,this.blockSize,"Invalid key length");var kL=utils.readUInt32BE(key,0),kR=utils.readUInt32BE(key,4);utils.pc1(kL,kR,state.tmp,0),kL=state.tmp[0],kR=state.tmp[1];for(var i=0;i>>1];kL=utils.r28shl(kL,shift),kR=utils.r28shl(kR,shift),utils.pc2(kL,kR,state.keys,i)}},DES.prototype._update=function _update(inp,inOff,out,outOff){var state=this._desState,l=utils.readUInt32BE(inp,inOff),r=utils.readUInt32BE(inp,inOff+4);utils.ip(l,r,state.tmp,0),l=state.tmp[0],r=state.tmp[1],"encrypt"===this.type?this._encrypt(state,l,r,state.tmp,0):this._decrypt(state,l,r,state.tmp,0),l=state.tmp[0],r=state.tmp[1],utils.writeUInt32BE(out,l,outOff),utils.writeUInt32BE(out,r,outOff+4)},DES.prototype._pad=function _pad(buffer,off){for(var value=buffer.length-off,i=off;i>>0,l=t}utils.rip(r,l,out,off)},DES.prototype._decrypt=function _decrypt(state,lStart,rStart,out,off){for(var l=rStart,r=lStart,i=state.keys.length-2;i>=0;i-=2){var keyL=state.keys[i],keyR=state.keys[i+1];utils.expand(l,state.tmp,0),keyL^=state.tmp[0],keyR^=state.tmp[1];var s=utils.substitute(keyL,keyR),t=l;l=(r^utils.permute(s))>>>0,r=t}utils.rip(l,r,out,off)}},651:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var assert=__webpack_require__(9746),inherits=__webpack_require__(5717),Cipher=__webpack_require__(5756),DES=__webpack_require__(778);function EDEState(type,key){assert.equal(key.length,24,"Invalid key length");var k1=key.slice(0,8),k2=key.slice(8,16),k3=key.slice(16,24);this.ciphers="encrypt"===type?[DES.create({type:"encrypt",key:k1}),DES.create({type:"decrypt",key:k2}),DES.create({type:"encrypt",key:k3})]:[DES.create({type:"decrypt",key:k3}),DES.create({type:"encrypt",key:k2}),DES.create({type:"decrypt",key:k1})]}function EDE(options){Cipher.call(this,options);var state=new EDEState(this.type,this.options.key);this._edeState=state}inherits(EDE,Cipher),module.exports=EDE,EDE.create=function create(options){return new EDE(options)},EDE.prototype._update=function _update(inp,inOff,out,outOff){var state=this._edeState;state.ciphers[0]._update(inp,inOff,out,outOff),state.ciphers[1]._update(out,outOff,out,outOff),state.ciphers[2]._update(out,outOff,out,outOff)},EDE.prototype._pad=DES.prototype._pad,EDE.prototype._unpad=DES.prototype._unpad},1278:(__unused_webpack_module,exports)=>{"use strict";exports.readUInt32BE=function readUInt32BE(bytes,off){return(bytes[0+off]<<24|bytes[1+off]<<16|bytes[2+off]<<8|bytes[3+off])>>>0},exports.writeUInt32BE=function writeUInt32BE(bytes,value,off){bytes[0+off]=value>>>24,bytes[1+off]=value>>>16&255,bytes[2+off]=value>>>8&255,bytes[3+off]=255&value},exports.ip=function ip(inL,inR,out,off){for(var outL=0,outR=0,i=6;i>=0;i-=2){for(var j=0;j<=24;j+=8)outL<<=1,outL|=inR>>>j+i&1;for(j=0;j<=24;j+=8)outL<<=1,outL|=inL>>>j+i&1}for(i=6;i>=0;i-=2){for(j=1;j<=25;j+=8)outR<<=1,outR|=inR>>>j+i&1;for(j=1;j<=25;j+=8)outR<<=1,outR|=inL>>>j+i&1}out[off+0]=outL>>>0,out[off+1]=outR>>>0},exports.rip=function rip(inL,inR,out,off){for(var outL=0,outR=0,i=0;i<4;i++)for(var j=24;j>=0;j-=8)outL<<=1,outL|=inR>>>j+i&1,outL<<=1,outL|=inL>>>j+i&1;for(i=4;i<8;i++)for(j=24;j>=0;j-=8)outR<<=1,outR|=inR>>>j+i&1,outR<<=1,outR|=inL>>>j+i&1;out[off+0]=outL>>>0,out[off+1]=outR>>>0},exports.pc1=function pc1(inL,inR,out,off){for(var outL=0,outR=0,i=7;i>=5;i--){for(var j=0;j<=24;j+=8)outL<<=1,outL|=inR>>j+i&1;for(j=0;j<=24;j+=8)outL<<=1,outL|=inL>>j+i&1}for(j=0;j<=24;j+=8)outL<<=1,outL|=inR>>j+i&1;for(i=1;i<=3;i++){for(j=0;j<=24;j+=8)outR<<=1,outR|=inR>>j+i&1;for(j=0;j<=24;j+=8)outR<<=1,outR|=inL>>j+i&1}for(j=0;j<=24;j+=8)outR<<=1,outR|=inL>>j+i&1;out[off+0]=outL>>>0,out[off+1]=outR>>>0},exports.r28shl=function r28shl(num,shift){return num<>>28-shift};var pc2table=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];exports.pc2=function pc2(inL,inR,out,off){for(var outL=0,outR=0,len=pc2table.length>>>1,i=0;i>>pc2table[i]&1;for(i=len;i>>pc2table[i]&1;out[off+0]=outL>>>0,out[off+1]=outR>>>0},exports.expand=function expand(r,out,off){var outL=0,outR=0;outL=(1&r)<<5|r>>>27;for(var i=23;i>=15;i-=4)outL<<=6,outL|=r>>>i&63;for(i=11;i>=3;i-=4)outR|=r>>>i&63,outR<<=6;outR|=(31&r)<<1|r>>>31,out[off+0]=outL>>>0,out[off+1]=outR>>>0};var sTable=[14,0,4,15,13,7,1,4,2,14,15,2,11,13,8,1,3,10,10,6,6,12,12,11,5,9,9,5,0,3,7,8,4,15,1,12,14,8,8,2,13,4,6,9,2,1,11,7,15,5,12,11,9,3,7,14,3,10,10,0,5,6,0,13,15,3,1,13,8,4,14,7,6,15,11,2,3,8,4,14,9,12,7,0,2,1,13,10,12,6,0,9,5,11,10,5,0,13,14,8,7,10,11,1,10,3,4,15,13,4,1,2,5,11,8,6,12,7,6,12,9,0,3,5,2,14,15,9,10,13,0,7,9,0,14,9,6,3,3,4,15,6,5,10,1,2,13,8,12,5,7,14,11,12,4,11,2,15,8,1,13,1,6,10,4,13,9,0,8,6,15,9,3,8,0,7,11,4,1,15,2,14,12,3,5,11,10,5,14,2,7,12,7,13,13,8,14,11,3,5,0,6,6,15,9,0,10,3,1,4,2,7,8,2,5,12,11,1,12,10,4,14,15,9,10,3,6,15,9,0,0,6,12,10,11,1,7,13,13,8,15,9,1,4,3,5,14,11,5,12,2,7,8,2,4,14,2,14,12,11,4,2,1,12,7,4,10,7,11,13,6,1,8,5,5,0,3,15,15,10,13,3,0,9,14,8,9,6,4,11,2,8,1,12,11,7,10,1,13,14,7,2,8,13,15,6,9,15,12,0,5,9,6,10,3,4,0,5,14,3,12,10,1,15,10,4,15,2,9,7,2,12,6,9,8,5,0,6,13,1,3,13,4,14,14,0,7,11,5,3,11,8,9,4,14,3,15,2,5,12,2,9,8,5,12,15,3,10,7,11,0,14,4,1,10,7,1,6,13,0,11,8,6,13,4,13,11,0,2,11,14,7,15,4,0,9,8,1,13,10,3,14,12,3,9,5,7,12,5,2,10,15,6,8,1,6,1,6,4,11,11,13,13,8,12,1,3,4,7,10,14,7,10,9,15,5,6,0,8,15,0,14,5,2,9,3,2,12,13,1,2,15,8,13,4,8,6,10,15,3,11,7,1,4,10,12,9,5,3,6,14,11,5,0,0,14,12,9,7,2,7,2,11,1,4,14,1,7,9,4,12,10,14,8,2,13,0,15,6,12,10,9,13,0,15,3,3,5,5,6,8,11];exports.substitute=function substitute(inL,inR){for(var out=0,i=0;i<4;i++){out<<=4,out|=sTable[64*i+(inL>>>18-6*i&63)]}for(i=0;i<4;i++){out<<=4,out|=sTable[256+64*i+(inR>>>18-6*i&63)]}return out>>>0};var permuteTable=[16,25,12,11,3,20,4,15,31,17,9,6,27,14,1,22,30,24,8,18,0,5,29,23,13,19,2,26,10,21,28,7];exports.permute=function permute(num){for(var out=0,i=0;i>>permuteTable[i]&1;return out>>>0},exports.padSplit=function padSplit(num,size,group){for(var str=num.toString(2);str.length{var generatePrime=__webpack_require__(3590),primes=__webpack_require__(9799),DH=__webpack_require__(7426);var ENCODINGS={binary:!0,hex:!0,base64:!0};exports.DiffieHellmanGroup=exports.createDiffieHellmanGroup=exports.getDiffieHellman=function getDiffieHellman(mod){var prime=new Buffer(primes[mod].prime,"hex"),gen=new Buffer(primes[mod].gen,"hex");return new DH(prime,gen)},exports.createDiffieHellman=exports.DiffieHellman=function createDiffieHellman(prime,enc,generator,genc){return Buffer.isBuffer(enc)||void 0===ENCODINGS[enc]?createDiffieHellman(prime,"binary",enc,generator):(enc=enc||"binary",genc=genc||"binary",generator=generator||new Buffer([2]),Buffer.isBuffer(generator)||(generator=new Buffer(generator,genc)),"number"==typeof prime?new DH(generatePrime(prime,generator),generator,!0):(Buffer.isBuffer(prime)||(prime=new Buffer(prime,enc)),new DH(prime,generator,!0)))}},7426:(module,__unused_webpack_exports,__webpack_require__)=>{var BN=__webpack_require__(3620),millerRabin=new(__webpack_require__(3047)),TWENTYFOUR=new BN(24),ELEVEN=new BN(11),TEN=new BN(10),THREE=new BN(3),SEVEN=new BN(7),primes=__webpack_require__(3590),randomBytes=__webpack_require__(1798);function setPublicKey(pub,enc){return enc=enc||"utf8",Buffer.isBuffer(pub)||(pub=new Buffer(pub,enc)),this._pub=new BN(pub),this}function setPrivateKey(priv,enc){return enc=enc||"utf8",Buffer.isBuffer(priv)||(priv=new Buffer(priv,enc)),this._priv=new BN(priv),this}module.exports=DH;var primeCache={};function DH(prime,generator,malleable){this.setGenerator(generator),this.__prime=new BN(prime),this._prime=BN.mont(this.__prime),this._primeLen=prime.length,this._pub=void 0,this._priv=void 0,this._primeCode=void 0,malleable?(this.setPublicKey=setPublicKey,this.setPrivateKey=setPrivateKey):this._primeCode=8}function formatReturnValue(bn,enc){var buf=new Buffer(bn.toArray());return enc?buf.toString(enc):buf}Object.defineProperty(DH.prototype,"verifyError",{enumerable:!0,get:function(){return"number"!=typeof this._primeCode&&(this._primeCode=function checkPrime(prime,generator){var gen=generator.toString("hex"),hex=[gen,prime.toString(16)].join("_");if(hex in primeCache)return primeCache[hex];var rem,error=0;if(prime.isEven()||!primes.simpleSieve||!primes.fermatTest(prime)||!millerRabin.test(prime))return error+=1,error+="02"===gen||"05"===gen?8:4,primeCache[hex]=error,error;switch(millerRabin.test(prime.shrn(1))||(error+=2),gen){case"02":prime.mod(TWENTYFOUR).cmp(ELEVEN)&&(error+=8);break;case"05":(rem=prime.mod(TEN)).cmp(THREE)&&rem.cmp(SEVEN)&&(error+=8);break;default:error+=4}return primeCache[hex]=error,error}(this.__prime,this.__gen)),this._primeCode}}),DH.prototype.generateKeys=function(){return this._priv||(this._priv=new BN(randomBytes(this._primeLen))),this._pub=this._gen.toRed(this._prime).redPow(this._priv).fromRed(),this.getPublicKey()},DH.prototype.computeSecret=function(other){var secret=(other=(other=new BN(other)).toRed(this._prime)).redPow(this._priv).fromRed(),out=new Buffer(secret.toArray()),prime=this.getPrime();if(out.length{var randomBytes=__webpack_require__(1798);module.exports=findPrime,findPrime.simpleSieve=simpleSieve,findPrime.fermatTest=fermatTest;var BN=__webpack_require__(3620),TWENTYFOUR=new BN(24),millerRabin=new(__webpack_require__(3047)),ONE=new BN(1),TWO=new BN(2),FIVE=new BN(5),TEN=(new BN(16),new BN(8),new BN(10)),THREE=new BN(3),ELEVEN=(new BN(7),new BN(11)),FOUR=new BN(4),primes=(new BN(12),null);function _getPrimes(){if(null!==primes)return primes;var res=[];res[0]=2;for(var i=1,k=3;k<1048576;k+=2){for(var sqrt=Math.ceil(Math.sqrt(k)),j=0;jbits;)num.ishrn(1);if(num.isEven()&&num.iadd(ONE),num.testn(1)||num.iadd(TWO),gen.cmp(TWO)){if(!gen.cmp(FIVE))for(;num.mod(TEN).cmp(THREE);)num.iadd(FOUR)}else for(;num.mod(TWENTYFOUR).cmp(ELEVEN);)num.iadd(FOUR);if(simpleSieve(n2=num.shrn(1))&&simpleSieve(num)&&fermatTest(n2)&&fermatTest(num)&&millerRabin.test(n2)&&millerRabin.test(num))return num}}},3620:function(module,__unused_webpack_exports,__webpack_require__){!function(module,exports){"use strict";function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}function BN(number,base,endian){if(BN.isBN(number))return number;this.negative=0,this.words=null,this.length=0,this.red=null,null!==number&&("le"!==base&&"be"!==base||(endian=base,base=10),this._init(number||0,base||10,endian||"be"))}var Buffer;"object"==typeof module?module.exports=BN:exports.BN=BN,BN.BN=BN,BN.wordSize=26;try{Buffer="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:__webpack_require__(7748).Buffer}catch(e){}function parseHex4Bits(string,index){var c=string.charCodeAt(index);return c>=65&&c<=70?c-55:c>=97&&c<=102?c-87:c-48&15}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return index-1>=lowerBound&&(r|=parseHex4Bits(string,index-1)<<4),r}function parseBase(str,start,end,mul){for(var r=0,len=Math.min(str.length,end),i=start;i=49?c-49+10:c>=17?c-17+10:c}return r}BN.isBN=function isBN(num){return num instanceof BN||null!==num&&"object"==typeof num&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words)},BN.max=function max(left,right){return left.cmp(right)>0?left:right},BN.min=function min(left,right){return left.cmp(right)<0?left:right},BN.prototype._init=function init(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&base>=2&&base<=36);var start=0;"-"===(number=number.toString().replace(/\s+/g,""))[0]&&(start++,this.negative=1),start=0;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=w<>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);return this.strip()},BN.prototype._parseHex=function _parseHex(number,start,endian){this.length=Math.ceil((number.length-start)/6),this.words=new Array(this.length);for(var i=0;i=start;i-=2)w=parseHexByte(number,start,i)<=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;else for(i=(number.length-start)%2==0?start+1:start;i=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;this.strip()},BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;limbPow*=base)limbLen++;limbLen--,limbPow=limbPow/base|0;for(var total=number.length-start,mod=total%limbLen,end=Math.min(total,total-mod)+start,word=0,i=start;i1&&0===this.words[this.length-1];)this.length--;return this._normSign()},BN.prototype._normSign=function _normSign(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},BN.prototype.inspect=function inspect(){return(this.red?""};var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=self.length+num.length|0;out.length=len,len=len-1|0;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=r/67108864|0;out.words[0]=lo;for(var k=1;k>>26,rword=67108863&carry,maxJ=Math.min(k,num.length-1),j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j|0;ncarry+=(r=(a=0|self.words[i])*(b=0|num.words[j])+rword)/67108864|0,rword=67108863&r}out.words[k]=0|rword,carry=0|ncarry}return 0!==carry?out.words[k]=0|carry:out.length--,out.strip()}BN.prototype.toString=function toString(base,padding){var out;if(padding=0|padding||1,16===(base=base||10)||"hex"===base){out="";for(var off=0,carry=0,i=0;i>>24-off&16777215)||i!==this.length-1?zeros[6-word.length]+word+out:word+out,(off+=2)>=26&&(off-=26,i--)}for(0!==carry&&(out=carry.toString(16)+out);out.length%padding!=0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&base>=2&&base<=36){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modn(groupBase).toString(base);out=(c=c.idivn(groupBase)).isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);out.length%padding!=0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function toNumber(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:this.length>2&&assert(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-ret:ret},BN.prototype.toJSON=function toJSON(){return this.toString(16)},BN.prototype.toBuffer=function toBuffer(endian,length){return assert(void 0!==Buffer),this.toArrayLike(Buffer,endian,length)},BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)},BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){var byteLength=this.byteLength(),reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length"),assert(reqLength>0,"Requested array length <= 0"),this.strip();var b,i,littleEndian="le"===endian,res=new ArrayType(reqLength),q=this.clone();if(littleEndian){for(i=0;!q.isZero();i++)b=q.andln(255),q.iushrn(8),res[i]=b;for(;i=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function _zeroBits(w){if(0===w)return 26;var t=w,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;for(var r=0,i=0;inum.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function uor(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function iuand(num){var b;b=this.length>num.length?num:this;for(var i=0;inum.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function uand(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function iuxor(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;inum.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function uxor(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function inotn(width){assert("number"==typeof width&&width>=0);var bytesNeeded=0|Math.ceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),bitsLeft>0&&bytesNeeded--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this.strip()},BN.prototype.notn=function notn(width){return this.clone().inotn(width)},BN.prototype.setn=function setn(bit,val){assert("number"==typeof bit&&bit>=0);var off=bit/26|0,wbit=bit%26;return this._expand(off+1),this.words[off]=val?this.words[off]|1<num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>>26;for(;0!==carry&&i>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;inum.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function isub(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var a,b,cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;cmp>0?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>26,this.words[i]=67108863&r;for(;0!==carry&&i>26,this.words[i]=67108863&r;if(0===carry&&i>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13;out.negative=self.negative^num.negative,out.length=19;var w0=(c+(lo=Math.imul(al0,bl0))|0)+((8191&(mid=(mid=Math.imul(al0,bh0))+Math.imul(ah0,bl0)|0))<<13)|0;c=((hi=Math.imul(ah0,bh0))+(mid>>>13)|0)+(w0>>>26)|0,w0&=67108863,lo=Math.imul(al1,bl0),mid=(mid=Math.imul(al1,bh0))+Math.imul(ah1,bl0)|0,hi=Math.imul(ah1,bh0);var w1=(c+(lo=lo+Math.imul(al0,bl1)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh1)|0)+Math.imul(ah0,bl1)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh1)|0)+(mid>>>13)|0)+(w1>>>26)|0,w1&=67108863,lo=Math.imul(al2,bl0),mid=(mid=Math.imul(al2,bh0))+Math.imul(ah2,bl0)|0,hi=Math.imul(ah2,bh0),lo=lo+Math.imul(al1,bl1)|0,mid=(mid=mid+Math.imul(al1,bh1)|0)+Math.imul(ah1,bl1)|0,hi=hi+Math.imul(ah1,bh1)|0;var w2=(c+(lo=lo+Math.imul(al0,bl2)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh2)|0)+Math.imul(ah0,bl2)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh2)|0)+(mid>>>13)|0)+(w2>>>26)|0,w2&=67108863,lo=Math.imul(al3,bl0),mid=(mid=Math.imul(al3,bh0))+Math.imul(ah3,bl0)|0,hi=Math.imul(ah3,bh0),lo=lo+Math.imul(al2,bl1)|0,mid=(mid=mid+Math.imul(al2,bh1)|0)+Math.imul(ah2,bl1)|0,hi=hi+Math.imul(ah2,bh1)|0,lo=lo+Math.imul(al1,bl2)|0,mid=(mid=mid+Math.imul(al1,bh2)|0)+Math.imul(ah1,bl2)|0,hi=hi+Math.imul(ah1,bh2)|0;var w3=(c+(lo=lo+Math.imul(al0,bl3)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh3)|0)+Math.imul(ah0,bl3)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh3)|0)+(mid>>>13)|0)+(w3>>>26)|0,w3&=67108863,lo=Math.imul(al4,bl0),mid=(mid=Math.imul(al4,bh0))+Math.imul(ah4,bl0)|0,hi=Math.imul(ah4,bh0),lo=lo+Math.imul(al3,bl1)|0,mid=(mid=mid+Math.imul(al3,bh1)|0)+Math.imul(ah3,bl1)|0,hi=hi+Math.imul(ah3,bh1)|0,lo=lo+Math.imul(al2,bl2)|0,mid=(mid=mid+Math.imul(al2,bh2)|0)+Math.imul(ah2,bl2)|0,hi=hi+Math.imul(ah2,bh2)|0,lo=lo+Math.imul(al1,bl3)|0,mid=(mid=mid+Math.imul(al1,bh3)|0)+Math.imul(ah1,bl3)|0,hi=hi+Math.imul(ah1,bh3)|0;var w4=(c+(lo=lo+Math.imul(al0,bl4)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh4)|0)+Math.imul(ah0,bl4)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh4)|0)+(mid>>>13)|0)+(w4>>>26)|0,w4&=67108863,lo=Math.imul(al5,bl0),mid=(mid=Math.imul(al5,bh0))+Math.imul(ah5,bl0)|0,hi=Math.imul(ah5,bh0),lo=lo+Math.imul(al4,bl1)|0,mid=(mid=mid+Math.imul(al4,bh1)|0)+Math.imul(ah4,bl1)|0,hi=hi+Math.imul(ah4,bh1)|0,lo=lo+Math.imul(al3,bl2)|0,mid=(mid=mid+Math.imul(al3,bh2)|0)+Math.imul(ah3,bl2)|0,hi=hi+Math.imul(ah3,bh2)|0,lo=lo+Math.imul(al2,bl3)|0,mid=(mid=mid+Math.imul(al2,bh3)|0)+Math.imul(ah2,bl3)|0,hi=hi+Math.imul(ah2,bh3)|0,lo=lo+Math.imul(al1,bl4)|0,mid=(mid=mid+Math.imul(al1,bh4)|0)+Math.imul(ah1,bl4)|0,hi=hi+Math.imul(ah1,bh4)|0;var w5=(c+(lo=lo+Math.imul(al0,bl5)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh5)|0)+Math.imul(ah0,bl5)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh5)|0)+(mid>>>13)|0)+(w5>>>26)|0,w5&=67108863,lo=Math.imul(al6,bl0),mid=(mid=Math.imul(al6,bh0))+Math.imul(ah6,bl0)|0,hi=Math.imul(ah6,bh0),lo=lo+Math.imul(al5,bl1)|0,mid=(mid=mid+Math.imul(al5,bh1)|0)+Math.imul(ah5,bl1)|0,hi=hi+Math.imul(ah5,bh1)|0,lo=lo+Math.imul(al4,bl2)|0,mid=(mid=mid+Math.imul(al4,bh2)|0)+Math.imul(ah4,bl2)|0,hi=hi+Math.imul(ah4,bh2)|0,lo=lo+Math.imul(al3,bl3)|0,mid=(mid=mid+Math.imul(al3,bh3)|0)+Math.imul(ah3,bl3)|0,hi=hi+Math.imul(ah3,bh3)|0,lo=lo+Math.imul(al2,bl4)|0,mid=(mid=mid+Math.imul(al2,bh4)|0)+Math.imul(ah2,bl4)|0,hi=hi+Math.imul(ah2,bh4)|0,lo=lo+Math.imul(al1,bl5)|0,mid=(mid=mid+Math.imul(al1,bh5)|0)+Math.imul(ah1,bl5)|0,hi=hi+Math.imul(ah1,bh5)|0;var w6=(c+(lo=lo+Math.imul(al0,bl6)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh6)|0)+Math.imul(ah0,bl6)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh6)|0)+(mid>>>13)|0)+(w6>>>26)|0,w6&=67108863,lo=Math.imul(al7,bl0),mid=(mid=Math.imul(al7,bh0))+Math.imul(ah7,bl0)|0,hi=Math.imul(ah7,bh0),lo=lo+Math.imul(al6,bl1)|0,mid=(mid=mid+Math.imul(al6,bh1)|0)+Math.imul(ah6,bl1)|0,hi=hi+Math.imul(ah6,bh1)|0,lo=lo+Math.imul(al5,bl2)|0,mid=(mid=mid+Math.imul(al5,bh2)|0)+Math.imul(ah5,bl2)|0,hi=hi+Math.imul(ah5,bh2)|0,lo=lo+Math.imul(al4,bl3)|0,mid=(mid=mid+Math.imul(al4,bh3)|0)+Math.imul(ah4,bl3)|0,hi=hi+Math.imul(ah4,bh3)|0,lo=lo+Math.imul(al3,bl4)|0,mid=(mid=mid+Math.imul(al3,bh4)|0)+Math.imul(ah3,bl4)|0,hi=hi+Math.imul(ah3,bh4)|0,lo=lo+Math.imul(al2,bl5)|0,mid=(mid=mid+Math.imul(al2,bh5)|0)+Math.imul(ah2,bl5)|0,hi=hi+Math.imul(ah2,bh5)|0,lo=lo+Math.imul(al1,bl6)|0,mid=(mid=mid+Math.imul(al1,bh6)|0)+Math.imul(ah1,bl6)|0,hi=hi+Math.imul(ah1,bh6)|0;var w7=(c+(lo=lo+Math.imul(al0,bl7)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh7)|0)+Math.imul(ah0,bl7)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh7)|0)+(mid>>>13)|0)+(w7>>>26)|0,w7&=67108863,lo=Math.imul(al8,bl0),mid=(mid=Math.imul(al8,bh0))+Math.imul(ah8,bl0)|0,hi=Math.imul(ah8,bh0),lo=lo+Math.imul(al7,bl1)|0,mid=(mid=mid+Math.imul(al7,bh1)|0)+Math.imul(ah7,bl1)|0,hi=hi+Math.imul(ah7,bh1)|0,lo=lo+Math.imul(al6,bl2)|0,mid=(mid=mid+Math.imul(al6,bh2)|0)+Math.imul(ah6,bl2)|0,hi=hi+Math.imul(ah6,bh2)|0,lo=lo+Math.imul(al5,bl3)|0,mid=(mid=mid+Math.imul(al5,bh3)|0)+Math.imul(ah5,bl3)|0,hi=hi+Math.imul(ah5,bh3)|0,lo=lo+Math.imul(al4,bl4)|0,mid=(mid=mid+Math.imul(al4,bh4)|0)+Math.imul(ah4,bl4)|0,hi=hi+Math.imul(ah4,bh4)|0,lo=lo+Math.imul(al3,bl5)|0,mid=(mid=mid+Math.imul(al3,bh5)|0)+Math.imul(ah3,bl5)|0,hi=hi+Math.imul(ah3,bh5)|0,lo=lo+Math.imul(al2,bl6)|0,mid=(mid=mid+Math.imul(al2,bh6)|0)+Math.imul(ah2,bl6)|0,hi=hi+Math.imul(ah2,bh6)|0,lo=lo+Math.imul(al1,bl7)|0,mid=(mid=mid+Math.imul(al1,bh7)|0)+Math.imul(ah1,bl7)|0,hi=hi+Math.imul(ah1,bh7)|0;var w8=(c+(lo=lo+Math.imul(al0,bl8)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh8)|0)+Math.imul(ah0,bl8)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh8)|0)+(mid>>>13)|0)+(w8>>>26)|0,w8&=67108863,lo=Math.imul(al9,bl0),mid=(mid=Math.imul(al9,bh0))+Math.imul(ah9,bl0)|0,hi=Math.imul(ah9,bh0),lo=lo+Math.imul(al8,bl1)|0,mid=(mid=mid+Math.imul(al8,bh1)|0)+Math.imul(ah8,bl1)|0,hi=hi+Math.imul(ah8,bh1)|0,lo=lo+Math.imul(al7,bl2)|0,mid=(mid=mid+Math.imul(al7,bh2)|0)+Math.imul(ah7,bl2)|0,hi=hi+Math.imul(ah7,bh2)|0,lo=lo+Math.imul(al6,bl3)|0,mid=(mid=mid+Math.imul(al6,bh3)|0)+Math.imul(ah6,bl3)|0,hi=hi+Math.imul(ah6,bh3)|0,lo=lo+Math.imul(al5,bl4)|0,mid=(mid=mid+Math.imul(al5,bh4)|0)+Math.imul(ah5,bl4)|0,hi=hi+Math.imul(ah5,bh4)|0,lo=lo+Math.imul(al4,bl5)|0,mid=(mid=mid+Math.imul(al4,bh5)|0)+Math.imul(ah4,bl5)|0,hi=hi+Math.imul(ah4,bh5)|0,lo=lo+Math.imul(al3,bl6)|0,mid=(mid=mid+Math.imul(al3,bh6)|0)+Math.imul(ah3,bl6)|0,hi=hi+Math.imul(ah3,bh6)|0,lo=lo+Math.imul(al2,bl7)|0,mid=(mid=mid+Math.imul(al2,bh7)|0)+Math.imul(ah2,bl7)|0,hi=hi+Math.imul(ah2,bh7)|0,lo=lo+Math.imul(al1,bl8)|0,mid=(mid=mid+Math.imul(al1,bh8)|0)+Math.imul(ah1,bl8)|0,hi=hi+Math.imul(ah1,bh8)|0;var w9=(c+(lo=lo+Math.imul(al0,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh9)|0)+Math.imul(ah0,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh9)|0)+(mid>>>13)|0)+(w9>>>26)|0,w9&=67108863,lo=Math.imul(al9,bl1),mid=(mid=Math.imul(al9,bh1))+Math.imul(ah9,bl1)|0,hi=Math.imul(ah9,bh1),lo=lo+Math.imul(al8,bl2)|0,mid=(mid=mid+Math.imul(al8,bh2)|0)+Math.imul(ah8,bl2)|0,hi=hi+Math.imul(ah8,bh2)|0,lo=lo+Math.imul(al7,bl3)|0,mid=(mid=mid+Math.imul(al7,bh3)|0)+Math.imul(ah7,bl3)|0,hi=hi+Math.imul(ah7,bh3)|0,lo=lo+Math.imul(al6,bl4)|0,mid=(mid=mid+Math.imul(al6,bh4)|0)+Math.imul(ah6,bl4)|0,hi=hi+Math.imul(ah6,bh4)|0,lo=lo+Math.imul(al5,bl5)|0,mid=(mid=mid+Math.imul(al5,bh5)|0)+Math.imul(ah5,bl5)|0,hi=hi+Math.imul(ah5,bh5)|0,lo=lo+Math.imul(al4,bl6)|0,mid=(mid=mid+Math.imul(al4,bh6)|0)+Math.imul(ah4,bl6)|0,hi=hi+Math.imul(ah4,bh6)|0,lo=lo+Math.imul(al3,bl7)|0,mid=(mid=mid+Math.imul(al3,bh7)|0)+Math.imul(ah3,bl7)|0,hi=hi+Math.imul(ah3,bh7)|0,lo=lo+Math.imul(al2,bl8)|0,mid=(mid=mid+Math.imul(al2,bh8)|0)+Math.imul(ah2,bl8)|0,hi=hi+Math.imul(ah2,bh8)|0;var w10=(c+(lo=lo+Math.imul(al1,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al1,bh9)|0)+Math.imul(ah1,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah1,bh9)|0)+(mid>>>13)|0)+(w10>>>26)|0,w10&=67108863,lo=Math.imul(al9,bl2),mid=(mid=Math.imul(al9,bh2))+Math.imul(ah9,bl2)|0,hi=Math.imul(ah9,bh2),lo=lo+Math.imul(al8,bl3)|0,mid=(mid=mid+Math.imul(al8,bh3)|0)+Math.imul(ah8,bl3)|0,hi=hi+Math.imul(ah8,bh3)|0,lo=lo+Math.imul(al7,bl4)|0,mid=(mid=mid+Math.imul(al7,bh4)|0)+Math.imul(ah7,bl4)|0,hi=hi+Math.imul(ah7,bh4)|0,lo=lo+Math.imul(al6,bl5)|0,mid=(mid=mid+Math.imul(al6,bh5)|0)+Math.imul(ah6,bl5)|0,hi=hi+Math.imul(ah6,bh5)|0,lo=lo+Math.imul(al5,bl6)|0,mid=(mid=mid+Math.imul(al5,bh6)|0)+Math.imul(ah5,bl6)|0,hi=hi+Math.imul(ah5,bh6)|0,lo=lo+Math.imul(al4,bl7)|0,mid=(mid=mid+Math.imul(al4,bh7)|0)+Math.imul(ah4,bl7)|0,hi=hi+Math.imul(ah4,bh7)|0,lo=lo+Math.imul(al3,bl8)|0,mid=(mid=mid+Math.imul(al3,bh8)|0)+Math.imul(ah3,bl8)|0,hi=hi+Math.imul(ah3,bh8)|0;var w11=(c+(lo=lo+Math.imul(al2,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al2,bh9)|0)+Math.imul(ah2,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah2,bh9)|0)+(mid>>>13)|0)+(w11>>>26)|0,w11&=67108863,lo=Math.imul(al9,bl3),mid=(mid=Math.imul(al9,bh3))+Math.imul(ah9,bl3)|0,hi=Math.imul(ah9,bh3),lo=lo+Math.imul(al8,bl4)|0,mid=(mid=mid+Math.imul(al8,bh4)|0)+Math.imul(ah8,bl4)|0,hi=hi+Math.imul(ah8,bh4)|0,lo=lo+Math.imul(al7,bl5)|0,mid=(mid=mid+Math.imul(al7,bh5)|0)+Math.imul(ah7,bl5)|0,hi=hi+Math.imul(ah7,bh5)|0,lo=lo+Math.imul(al6,bl6)|0,mid=(mid=mid+Math.imul(al6,bh6)|0)+Math.imul(ah6,bl6)|0,hi=hi+Math.imul(ah6,bh6)|0,lo=lo+Math.imul(al5,bl7)|0,mid=(mid=mid+Math.imul(al5,bh7)|0)+Math.imul(ah5,bl7)|0,hi=hi+Math.imul(ah5,bh7)|0,lo=lo+Math.imul(al4,bl8)|0,mid=(mid=mid+Math.imul(al4,bh8)|0)+Math.imul(ah4,bl8)|0,hi=hi+Math.imul(ah4,bh8)|0;var w12=(c+(lo=lo+Math.imul(al3,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al3,bh9)|0)+Math.imul(ah3,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah3,bh9)|0)+(mid>>>13)|0)+(w12>>>26)|0,w12&=67108863,lo=Math.imul(al9,bl4),mid=(mid=Math.imul(al9,bh4))+Math.imul(ah9,bl4)|0,hi=Math.imul(ah9,bh4),lo=lo+Math.imul(al8,bl5)|0,mid=(mid=mid+Math.imul(al8,bh5)|0)+Math.imul(ah8,bl5)|0,hi=hi+Math.imul(ah8,bh5)|0,lo=lo+Math.imul(al7,bl6)|0,mid=(mid=mid+Math.imul(al7,bh6)|0)+Math.imul(ah7,bl6)|0,hi=hi+Math.imul(ah7,bh6)|0,lo=lo+Math.imul(al6,bl7)|0,mid=(mid=mid+Math.imul(al6,bh7)|0)+Math.imul(ah6,bl7)|0,hi=hi+Math.imul(ah6,bh7)|0,lo=lo+Math.imul(al5,bl8)|0,mid=(mid=mid+Math.imul(al5,bh8)|0)+Math.imul(ah5,bl8)|0,hi=hi+Math.imul(ah5,bh8)|0;var w13=(c+(lo=lo+Math.imul(al4,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al4,bh9)|0)+Math.imul(ah4,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah4,bh9)|0)+(mid>>>13)|0)+(w13>>>26)|0,w13&=67108863,lo=Math.imul(al9,bl5),mid=(mid=Math.imul(al9,bh5))+Math.imul(ah9,bl5)|0,hi=Math.imul(ah9,bh5),lo=lo+Math.imul(al8,bl6)|0,mid=(mid=mid+Math.imul(al8,bh6)|0)+Math.imul(ah8,bl6)|0,hi=hi+Math.imul(ah8,bh6)|0,lo=lo+Math.imul(al7,bl7)|0,mid=(mid=mid+Math.imul(al7,bh7)|0)+Math.imul(ah7,bl7)|0,hi=hi+Math.imul(ah7,bh7)|0,lo=lo+Math.imul(al6,bl8)|0,mid=(mid=mid+Math.imul(al6,bh8)|0)+Math.imul(ah6,bl8)|0,hi=hi+Math.imul(ah6,bh8)|0;var w14=(c+(lo=lo+Math.imul(al5,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al5,bh9)|0)+Math.imul(ah5,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah5,bh9)|0)+(mid>>>13)|0)+(w14>>>26)|0,w14&=67108863,lo=Math.imul(al9,bl6),mid=(mid=Math.imul(al9,bh6))+Math.imul(ah9,bl6)|0,hi=Math.imul(ah9,bh6),lo=lo+Math.imul(al8,bl7)|0,mid=(mid=mid+Math.imul(al8,bh7)|0)+Math.imul(ah8,bl7)|0,hi=hi+Math.imul(ah8,bh7)|0,lo=lo+Math.imul(al7,bl8)|0,mid=(mid=mid+Math.imul(al7,bh8)|0)+Math.imul(ah7,bl8)|0,hi=hi+Math.imul(ah7,bh8)|0;var w15=(c+(lo=lo+Math.imul(al6,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al6,bh9)|0)+Math.imul(ah6,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah6,bh9)|0)+(mid>>>13)|0)+(w15>>>26)|0,w15&=67108863,lo=Math.imul(al9,bl7),mid=(mid=Math.imul(al9,bh7))+Math.imul(ah9,bl7)|0,hi=Math.imul(ah9,bh7),lo=lo+Math.imul(al8,bl8)|0,mid=(mid=mid+Math.imul(al8,bh8)|0)+Math.imul(ah8,bl8)|0,hi=hi+Math.imul(ah8,bh8)|0;var w16=(c+(lo=lo+Math.imul(al7,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al7,bh9)|0)+Math.imul(ah7,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah7,bh9)|0)+(mid>>>13)|0)+(w16>>>26)|0,w16&=67108863,lo=Math.imul(al9,bl8),mid=(mid=Math.imul(al9,bh8))+Math.imul(ah9,bl8)|0,hi=Math.imul(ah9,bh8);var w17=(c+(lo=lo+Math.imul(al8,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al8,bh9)|0)+Math.imul(ah8,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah8,bh9)|0)+(mid>>>13)|0)+(w17>>>26)|0,w17&=67108863;var w18=(c+(lo=Math.imul(al9,bl9))|0)+((8191&(mid=(mid=Math.imul(al9,bh9))+Math.imul(ah9,bl9)|0))<<13)|0;return c=((hi=Math.imul(ah9,bh9))+(mid>>>13)|0)+(w18>>>26)|0,w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,0!==c&&(o[19]=c,out.length++),out};function jumboMulTo(self,num,out){return(new FFTM).mulp(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}Math.imul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function mulTo(num,out){var res,len=this.length+num.length;return res=10===this.length&&10===num.length?comb10MulTo(this,num,out):len<63?smallMulTo(this,num,out):len<1024?function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0;k>>26)|0)>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0!==carry?out.words[k]=carry:out.length--,out.strip()}(this,num,out):jumboMulTo(this,num,out),res},FFTM.prototype.makeRBT=function makeRBT(N){for(var t=new Array(N),l=BN.prototype._countBits(N)-1,i=0;i>=1;return rb},FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>=1)i++;return 1<>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;i>=26,carry+=w/67108864|0,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.muln=function muln(num){return this.clone().imuln(num)},BN.prototype.sqr=function sqr(){return this.mul(this)},BN.prototype.isqr=function isqr(){return this.imul(this.clone())},BN.prototype.pow=function pow(num){var w=function toBitArray(num){for(var w=new Array(num.bitLength()),bit=0;bit>>wbit}return w}(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i=0);var i,r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r;if(0!==r){var carry=0;for(i=0;i>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;i>=0;i--)this.words[i+s]=this.words[i];for(i=0;i=0),h=hint?(hint-hint%26)/26:0;var r=bits%26,s=Math.min((bits-r)/26,this.length),mask=67108863^67108863>>>r<s)for(this.length-=s,i=0;i=0&&(0!==carry||i>=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&0!==carry&&(maskedWords.words[maskedWords.length++]=carry),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},BN.prototype.ishrn=function ishrn(bits,hint,extended){return assert(0===this.negative),this.iushrn(bits,hint,extended)},BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function testn(bit){assert("number"==typeof bit&&bit>=0);var r=bit%26,s=(bit-r)/26,q=1<=0);var r=bits%26,s=(bits-r)/26;if(assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!==r&&s++,this.length=Math.min(s,this.length),0!==r){var mask=67108863^67108863>>>r<=67108864;i++)this.words[i]-=67108864,i===this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=Math.max(this.length,i+1),this},BN.prototype.isubn=function isubn(num){if(assert("number"==typeof num),assert(num<67108864),num<0)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i>26)-(right/67108864|0),this.words[i+shift]=67108863&w}for(;i>26,this.words[i+shift]=67108863&w;if(0===carry)return this.strip();for(assert(-1===carry),carry=0,i=0;i>26,this.words[i]=67108863&w;return this.negative=1,this.strip()},BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=(this.length,num.length),a=this.clone(),b=num,bhi=0|b.words[b.length-1];0!==(shift=26-this._countBits(bhi))&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var q,m=a.length-b.length;if("mod"!==mode){(q=new BN(null)).length=m+1,q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=67108864*(0|a.words[b.length+j])+(0|a.words[b.length+j-1]);for(qj=Math.min(qj/bhi|0,67108863),a._ishlnsubmul(b,qj,j);0!==a.negative;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q.strip(),a.strip(),"div"!==mode&&0!==shift&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function divmod(num,mode,positive){return assert(!num.isZero()),this.isZero()?{div:new BN(0),mod:new BN(0)}:0!==this.negative&&0===num.negative?(res=this.neg().divmod(num,mode),"mod"!==mode&&(div=res.div.neg()),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.iadd(num)),{div,mod}):0===this.negative&&0!==num.negative?(res=this.divmod(num.neg(),mode),"mod"!==mode&&(div=res.div.neg()),{div,mod:res.mod}):0!=(this.negative&num.negative)?(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod}):num.length>this.length||this.cmp(num)<0?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modn(num.words[0]))}:this._wordDiv(num,mode);var div,mod,res},BN.prototype.div=function div(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function mod(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function umod(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0!==dm.div.negative?dm.mod.isub(num):dm.mod,half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return cmp<0||1===r2&&0===cmp?dm.div:0!==dm.div.negative?dm.div.isubn(1):dm.div.iaddn(1)},BN.prototype.modn=function modn(num){assert(num<=67108863);for(var p=(1<<26)%num,acc=0,i=this.length-1;i>=0;i--)acc=(p*acc+(0|this.words[i]))%num;return acc},BN.prototype.idivn=function idivn(num){assert(num<=67108863);for(var carry=0,i=this.length-1;i>=0;i--){var w=(0|this.words[i])+67108864*carry;this.words[i]=w/num|0,carry=w%num}return this.strip()},BN.prototype.divn=function divn(num){return this.clone().idivn(num)},BN.prototype.egcd=function egcd(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0!==x.negative?x.umod(p):x.clone();for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0==(x.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(x.iushrn(i);i-- >0;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;0==(y.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(y.iushrn(j);j-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);x.cmp(y)>=0?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function _invmp(p){assert(0===p.negative),assert(!p.isZero());var a=this,b=p.clone();a=0!==a.negative?a.umod(p):a.clone();for(var res,x1=new BN(1),x2=new BN(0),delta=b.clone();a.cmpn(1)>0&&b.cmpn(1)>0;){for(var i=0,im=1;0==(a.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(a.iushrn(i);i-- >0;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;0==(b.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(b.iushrn(j);j-- >0;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);a.cmp(b)>=0?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}return(res=0===a.cmpn(1)?x1:x2).cmpn(0)<0&&res.iadd(p),res},BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);for(;;){for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(r<0){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}return b.iushln(shift)},BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function isEven(){return 0==(1&this.words[0])},BN.prototype.isOdd=function isOdd(){return 1==(1&this.words[0])},BN.prototype.andln=function andln(num){return this.words[0]&num},BN.prototype.bincn=function bincn(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<>>26,w&=67108863,this.words[i]=w}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function isZero(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function cmpn(num){var res,negative=num<0;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;if(this.strip(),this.length>1)res=1;else{negative&&(num=-num),assert(num<=67108863,"Number is too big");var w=0|this.words[0];res=w===num?0:wnum.length)return 1;if(this.length=0;i--){var a=0|this.words[i],b=0|num.words[i];if(a!==b){ab&&(res=1);break}}return res},BN.prototype.gtn=function gtn(num){return 1===this.cmpn(num)},BN.prototype.gt=function gt(num){return 1===this.cmp(num)},BN.prototype.gten=function gten(num){return this.cmpn(num)>=0},BN.prototype.gte=function gte(num){return this.cmp(num)>=0},BN.prototype.ltn=function ltn(num){return-1===this.cmpn(num)},BN.prototype.lt=function lt(num){return-1===this.cmp(num)},BN.prototype.lten=function lten(num){return this.cmpn(num)<=0},BN.prototype.lte=function lte(num){return this.cmp(num)<=0},BN.prototype.eqn=function eqn(num){return 0===this.cmpn(num)},BN.prototype.eq=function eq(num){return 0===this.cmp(num)},BN.red=function red(num){return new Red(num)},BN.prototype.toRed=function toRed(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function fromRed(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function _forceRed(ctx){return this.red=ctx,this},BN.prototype.forceRed=function forceRed(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function redAdd(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function redIAdd(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function redSub(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function redISub(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function redShl(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function redMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function redIMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function redSqr(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function redISqr(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function redSqrt(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function redInvm(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function redNeg(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function redPow(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);return tmp.words=new Array(Math.ceil(this.n/13)),tmp},MPrime.prototype.ireduce=function ireduce(num){var rlen,r=num;do{this.split(r,this.tmp),rlen=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(rlen>this.n);var cmp=rlen0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)},inherits(K256,MPrime),K256.prototype.split=function split(input,output){for(var outLen=Math.min(input.length,9),i=0;i>>22,prev=next}prev>>>=22,input.words[i-10]=prev,0===prev&&input.length>10?input.length-=10:input.length-=9},K256.prototype.imulK=function imulK(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0;i>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else{if("p25519"!==name)throw new Error("Unknown prime "+name);prime=new P25519}return primes[name]=prime,prime},Red.prototype._verify1=function _verify1(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function _verify2(a,b){assert(0==(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function imod(a){return this.prime?this.prime.ireduce(a)._forceRed(this):a.umod(this.m)._forceRed(this)},Red.prototype.neg=function neg(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);return res.cmp(this.m)>=0&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);return res.cmp(this.m)>=0&&res.isub(this.m),res},Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);return res.cmpn(0)<0&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);return res.cmpn(0)<0&&res.iadd(this.m),res},Red.prototype.shl=function shl(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function imul(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function mul(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())},Red.prototype.sqr=function sqr(a){return this.mul(a,a)},Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(mod3%2==1),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i=0;i--){for(var word=num.words[i],j=start-1;j>=0;j--){var bit=word>>j&1;res!==wnd[0]&&(res=this.sqr(res)),0!==bit||0!==current?(current<<=1,current|=bit,(4===++currentLen||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)):currentLen=0}start=26}return res},Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();return res.red=null,res},BN.mont=function mont(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function invm(a){return this.imod(a._invmp(this.m).mul(this.r2))._forceRed(this)}}(module=__webpack_require__.nmd(module),this)},6266:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";var elliptic=exports;elliptic.version=__webpack_require__(8597).i8,elliptic.utils=__webpack_require__(953),elliptic.rand=__webpack_require__(9931),elliptic.curve=__webpack_require__(8254),elliptic.curves=__webpack_require__(5427),elliptic.ec=__webpack_require__(7954),elliptic.eddsa=__webpack_require__(5980)},4918:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var BN=__webpack_require__(3785),utils=__webpack_require__(953),getNAF=utils.getNAF,getJSF=utils.getJSF,assert=utils.assert;function BaseCurve(type,conf){this.type=type,this.p=new BN(conf.p,16),this.red=conf.prime?BN.red(conf.prime):BN.mont(this.p),this.zero=new BN(0).toRed(this.red),this.one=new BN(1).toRed(this.red),this.two=new BN(2).toRed(this.red),this.n=conf.n&&new BN(conf.n,16),this.g=conf.g&&this.pointFromJSON(conf.g,conf.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n?this.n.bitLength():0;var adjustCount=this.n&&this.p.div(this.n);!adjustCount||adjustCount.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}function BasePoint(curve,type){this.curve=curve,this.type=type,this.precomputed=null}module.exports=BaseCurve,BaseCurve.prototype.point=function point(){throw new Error("Not implemented")},BaseCurve.prototype.validate=function validate(){throw new Error("Not implemented")},BaseCurve.prototype._fixedNafMul=function _fixedNafMul(p,k){assert(p.precomputed);var doubles=p._getDoubles(),naf=getNAF(k,1,this._bitLength),I=(1<=j;l--)nafW=(nafW<<1)+naf[l];repr.push(nafW)}for(var a=this.jpoint(null,null,null),b=this.jpoint(null,null,null),i=I;i>0;i--){for(j=0;j=0;i--){for(var l=0;i>=0&&0===naf[i];i--)l++;if(i>=0&&l++,acc=acc.dblp(l),i<0)break;var z=naf[i];assert(0!==z),acc="affine"===p.type?z>0?acc.mixedAdd(wnd[z-1>>1]):acc.mixedAdd(wnd[-z-1>>1].neg()):z>0?acc.add(wnd[z-1>>1]):acc.add(wnd[-z-1>>1].neg())}return"affine"===p.type?acc.toP():acc},BaseCurve.prototype._wnafMulAdd=function _wnafMulAdd(defW,points,coeffs,len,jacobianResult){var i,j,p,wndWidth=this._wnafT1,wnd=this._wnafT2,naf=this._wnafT3,max=0;for(i=0;i=1;i-=2){var a=i-1,b=i;if(1===wndWidth[a]&&1===wndWidth[b]){var comb=[points[a],null,null,points[b]];0===points[a].y.cmp(points[b].y)?(comb[1]=points[a].add(points[b]),comb[2]=points[a].toJ().mixedAdd(points[b].neg())):0===points[a].y.cmp(points[b].y.redNeg())?(comb[1]=points[a].toJ().mixedAdd(points[b]),comb[2]=points[a].add(points[b].neg())):(comb[1]=points[a].toJ().mixedAdd(points[b]),comb[2]=points[a].toJ().mixedAdd(points[b].neg()));var index=[-3,-1,-5,-7,0,7,5,1,3],jsf=getJSF(coeffs[a],coeffs[b]);for(max=Math.max(jsf[0].length,max),naf[a]=new Array(max),naf[b]=new Array(max),j=0;j=0;i--){for(var k=0;i>=0;){var zero=!0;for(j=0;j=0&&k++,acc=acc.dblp(k),i<0)break;for(j=0;j0?p=wnd[j][z-1>>1]:z<0&&(p=wnd[j][-z-1>>1].neg()),acc="affine"===p.type?acc.mixedAdd(p):acc.add(p))}}for(i=0;i=Math.ceil((k.bitLength()+1)/doubles.step)},BasePoint.prototype._getDoubles=function _getDoubles(step,power){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var doubles=[this],acc=this,i=0;i{"use strict";var utils=__webpack_require__(953),BN=__webpack_require__(3785),inherits=__webpack_require__(5717),Base=__webpack_require__(4918),assert=utils.assert;function EdwardsCurve(conf){this.twisted=1!=(0|conf.a),this.mOneA=this.twisted&&-1==(0|conf.a),this.extended=this.mOneA,Base.call(this,"edwards",conf),this.a=new BN(conf.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new BN(conf.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new BN(conf.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),assert(!this.twisted||0===this.c.fromRed().cmpn(1)),this.oneC=1==(0|conf.c)}function Point(curve,x,y,z,t){Base.BasePoint.call(this,curve,"projective"),null===x&&null===y&&null===z?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new BN(x,16),this.y=new BN(y,16),this.z=z?new BN(z,16):this.curve.one,this.t=t&&new BN(t,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}inherits(EdwardsCurve,Base),module.exports=EdwardsCurve,EdwardsCurve.prototype._mulA=function _mulA(num){return this.mOneA?num.redNeg():this.a.redMul(num)},EdwardsCurve.prototype._mulC=function _mulC(num){return this.oneC?num:this.c.redMul(num)},EdwardsCurve.prototype.jpoint=function jpoint(x,y,z,t){return this.point(x,y,z,t)},EdwardsCurve.prototype.pointFromX=function pointFromX(x,odd){(x=new BN(x,16)).red||(x=x.toRed(this.red));var x2=x.redSqr(),rhs=this.c2.redSub(this.a.redMul(x2)),lhs=this.one.redSub(this.c2.redMul(this.d).redMul(x2)),y2=rhs.redMul(lhs.redInvm()),y=y2.redSqrt();if(0!==y.redSqr().redSub(y2).cmp(this.zero))throw new Error("invalid point");var isOdd=y.fromRed().isOdd();return(odd&&!isOdd||!odd&&isOdd)&&(y=y.redNeg()),this.point(x,y)},EdwardsCurve.prototype.pointFromY=function pointFromY(y,odd){(y=new BN(y,16)).red||(y=y.toRed(this.red));var y2=y.redSqr(),lhs=y2.redSub(this.c2),rhs=y2.redMul(this.d).redMul(this.c2).redSub(this.a),x2=lhs.redMul(rhs.redInvm());if(0===x2.cmp(this.zero)){if(odd)throw new Error("invalid point");return this.point(this.zero,y)}var x=x2.redSqrt();if(0!==x.redSqr().redSub(x2).cmp(this.zero))throw new Error("invalid point");return x.fromRed().isOdd()!==odd&&(x=x.redNeg()),this.point(x,y)},EdwardsCurve.prototype.validate=function validate(point){if(point.isInfinity())return!0;point.normalize();var x2=point.x.redSqr(),y2=point.y.redSqr(),lhs=x2.redMul(this.a).redAdd(y2),rhs=this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));return 0===lhs.cmp(rhs)},inherits(Point,Base.BasePoint),EdwardsCurve.prototype.pointFromJSON=function pointFromJSON(obj){return Point.fromJSON(this,obj)},EdwardsCurve.prototype.point=function point(x,y,z,t){return new Point(this,x,y,z,t)},Point.fromJSON=function fromJSON(curve,obj){return new Point(curve,obj[0],obj[1],obj[2])},Point.prototype.inspect=function inspect(){return this.isInfinity()?"":""},Point.prototype.isInfinity=function isInfinity(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},Point.prototype._extDbl=function _extDbl(){var a=this.x.redSqr(),b=this.y.redSqr(),c=this.z.redSqr();c=c.redIAdd(c);var d=this.curve._mulA(a),e=this.x.redAdd(this.y).redSqr().redISub(a).redISub(b),g=d.redAdd(b),f=g.redSub(c),h=d.redSub(b),nx=e.redMul(f),ny=g.redMul(h),nt=e.redMul(h),nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)},Point.prototype._projDbl=function _projDbl(){var nx,ny,nz,e,h,j,b=this.x.redAdd(this.y).redSqr(),c=this.x.redSqr(),d=this.y.redSqr();if(this.curve.twisted){var f=(e=this.curve._mulA(c)).redAdd(d);this.zOne?(nx=b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)),ny=f.redMul(e.redSub(d)),nz=f.redSqr().redSub(f).redSub(f)):(h=this.z.redSqr(),j=f.redSub(h).redISub(h),nx=b.redSub(c).redISub(d).redMul(j),ny=f.redMul(e.redSub(d)),nz=f.redMul(j))}else e=c.redAdd(d),h=this.curve._mulC(this.z).redSqr(),j=e.redSub(h).redSub(h),nx=this.curve._mulC(b.redISub(e)).redMul(j),ny=this.curve._mulC(e).redMul(c.redISub(d)),nz=e.redMul(j);return this.curve.point(nx,ny,nz)},Point.prototype.dbl=function dbl(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},Point.prototype._extAdd=function _extAdd(p){var a=this.y.redSub(this.x).redMul(p.y.redSub(p.x)),b=this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)),c=this.t.redMul(this.curve.dd).redMul(p.t),d=this.z.redMul(p.z.redAdd(p.z)),e=b.redSub(a),f=d.redSub(c),g=d.redAdd(c),h=b.redAdd(a),nx=e.redMul(f),ny=g.redMul(h),nt=e.redMul(h),nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)},Point.prototype._projAdd=function _projAdd(p){var ny,nz,a=this.z.redMul(p.z),b=a.redSqr(),c=this.x.redMul(p.x),d=this.y.redMul(p.y),e=this.curve.d.redMul(c).redMul(d),f=b.redSub(e),g=b.redAdd(e),tmp=this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d),nx=a.redMul(f).redMul(tmp);return this.curve.twisted?(ny=a.redMul(g).redMul(d.redSub(this.curve._mulA(c))),nz=f.redMul(g)):(ny=a.redMul(g).redMul(d.redSub(c)),nz=this.curve._mulC(f).redMul(g)),this.curve.point(nx,ny,nz)},Point.prototype.add=function add(p){return this.isInfinity()?p:p.isInfinity()?this:this.curve.extended?this._extAdd(p):this._projAdd(p)},Point.prototype.mul=function mul(k){return this._hasDoubles(k)?this.curve._fixedNafMul(this,k):this.curve._wnafMul(this,k)},Point.prototype.mulAdd=function mulAdd(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,!1)},Point.prototype.jmulAdd=function jmulAdd(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,!0)},Point.prototype.normalize=function normalize(){if(this.zOne)return this;var zi=this.z.redInvm();return this.x=this.x.redMul(zi),this.y=this.y.redMul(zi),this.t&&(this.t=this.t.redMul(zi)),this.z=this.curve.one,this.zOne=!0,this},Point.prototype.neg=function neg(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Point.prototype.getX=function getX(){return this.normalize(),this.x.fromRed()},Point.prototype.getY=function getY(){return this.normalize(),this.y.fromRed()},Point.prototype.eq=function eq(other){return this===other||0===this.getX().cmp(other.getX())&&0===this.getY().cmp(other.getY())},Point.prototype.eqXToP=function eqXToP(x){var rx=x.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(rx))return!0;for(var xc=x.clone(),t=this.curve.redN.redMul(this.z);;){if(xc.iadd(this.curve.n),xc.cmp(this.curve.p)>=0)return!1;if(rx.redIAdd(t),0===this.x.cmp(rx))return!0}},Point.prototype.toP=Point.prototype.normalize,Point.prototype.mixedAdd=Point.prototype.add},8254:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";var curve=exports;curve.base=__webpack_require__(4918),curve.short=__webpack_require__(6673),curve.mont=__webpack_require__(2881),curve.edwards=__webpack_require__(1138)},2881:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var BN=__webpack_require__(3785),inherits=__webpack_require__(5717),Base=__webpack_require__(4918),utils=__webpack_require__(953);function MontCurve(conf){Base.call(this,"mont",conf),this.a=new BN(conf.a,16).toRed(this.red),this.b=new BN(conf.b,16).toRed(this.red),this.i4=new BN(4).toRed(this.red).redInvm(),this.two=new BN(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}function Point(curve,x,z){Base.BasePoint.call(this,curve,"projective"),null===x&&null===z?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new BN(x,16),this.z=new BN(z,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}inherits(MontCurve,Base),module.exports=MontCurve,MontCurve.prototype.validate=function validate(point){var x=point.normalize().x,x2=x.redSqr(),rhs=x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);return 0===rhs.redSqrt().redSqr().cmp(rhs)},inherits(Point,Base.BasePoint),MontCurve.prototype.decodePoint=function decodePoint(bytes,enc){return this.point(utils.toArray(bytes,enc),1)},MontCurve.prototype.point=function point(x,z){return new Point(this,x,z)},MontCurve.prototype.pointFromJSON=function pointFromJSON(obj){return Point.fromJSON(this,obj)},Point.prototype.precompute=function precompute(){},Point.prototype._encode=function _encode(){return this.getX().toArray("be",this.curve.p.byteLength())},Point.fromJSON=function fromJSON(curve,obj){return new Point(curve,obj[0],obj[1]||curve.one)},Point.prototype.inspect=function inspect(){return this.isInfinity()?"":""},Point.prototype.isInfinity=function isInfinity(){return 0===this.z.cmpn(0)},Point.prototype.dbl=function dbl(){var aa=this.x.redAdd(this.z).redSqr(),bb=this.x.redSub(this.z).redSqr(),c=aa.redSub(bb),nx=aa.redMul(bb),nz=c.redMul(bb.redAdd(this.curve.a24.redMul(c)));return this.curve.point(nx,nz)},Point.prototype.add=function add(){throw new Error("Not supported on Montgomery curve")},Point.prototype.diffAdd=function diffAdd(p,diff){var a=this.x.redAdd(this.z),b=this.x.redSub(this.z),c=p.x.redAdd(p.z),da=p.x.redSub(p.z).redMul(a),cb=c.redMul(b),nx=diff.z.redMul(da.redAdd(cb).redSqr()),nz=diff.x.redMul(da.redISub(cb).redSqr());return this.curve.point(nx,nz)},Point.prototype.mul=function mul(k){for(var t=k.clone(),a=this,b=this.curve.point(null,null),bits=[];0!==t.cmpn(0);t.iushrn(1))bits.push(t.andln(1));for(var i=bits.length-1;i>=0;i--)0===bits[i]?(a=a.diffAdd(b,this),b=b.dbl()):(b=a.diffAdd(b,this),a=a.dbl());return b},Point.prototype.mulAdd=function mulAdd(){throw new Error("Not supported on Montgomery curve")},Point.prototype.jumlAdd=function jumlAdd(){throw new Error("Not supported on Montgomery curve")},Point.prototype.eq=function eq(other){return 0===this.getX().cmp(other.getX())},Point.prototype.normalize=function normalize(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},Point.prototype.getX=function getX(){return this.normalize(),this.x.fromRed()}},6673:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(953),BN=__webpack_require__(3785),inherits=__webpack_require__(5717),Base=__webpack_require__(4918),assert=utils.assert;function ShortCurve(conf){Base.call(this,"short",conf),this.a=new BN(conf.a,16).toRed(this.red),this.b=new BN(conf.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(conf),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}function Point(curve,x,y,isRed){Base.BasePoint.call(this,curve,"affine"),null===x&&null===y?(this.x=null,this.y=null,this.inf=!0):(this.x=new BN(x,16),this.y=new BN(y,16),isRed&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}function JPoint(curve,x,y,z){Base.BasePoint.call(this,curve,"jacobian"),null===x&&null===y&&null===z?(this.x=this.curve.one,this.y=this.curve.one,this.z=new BN(0)):(this.x=new BN(x,16),this.y=new BN(y,16),this.z=new BN(z,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}inherits(ShortCurve,Base),module.exports=ShortCurve,ShortCurve.prototype._getEndomorphism=function _getEndomorphism(conf){if(this.zeroA&&this.g&&this.n&&1===this.p.modn(3)){var beta,lambda;if(conf.beta)beta=new BN(conf.beta,16).toRed(this.red);else{var betas=this._getEndoRoots(this.p);beta=(beta=betas[0].cmp(betas[1])<0?betas[0]:betas[1]).toRed(this.red)}if(conf.lambda)lambda=new BN(conf.lambda,16);else{var lambdas=this._getEndoRoots(this.n);0===this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta))?lambda=lambdas[0]:(lambda=lambdas[1],assert(0===this.g.mul(lambda).x.cmp(this.g.x.redMul(beta))))}return{beta,lambda,basis:conf.basis?conf.basis.map((function(vec){return{a:new BN(vec.a,16),b:new BN(vec.b,16)}})):this._getEndoBasis(lambda)}}},ShortCurve.prototype._getEndoRoots=function _getEndoRoots(num){var red=num===this.p?this.red:BN.mont(num),tinv=new BN(2).toRed(red).redInvm(),ntinv=tinv.redNeg(),s=new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);return[ntinv.redAdd(s).fromRed(),ntinv.redSub(s).fromRed()]},ShortCurve.prototype._getEndoBasis=function _getEndoBasis(lambda){for(var a0,b0,a1,b1,a2,b2,prevR,r,x,aprxSqrt=this.n.ushrn(Math.floor(this.n.bitLength()/2)),u=lambda,v=this.n.clone(),x1=new BN(1),y1=new BN(0),x2=new BN(0),y2=new BN(1),i=0;0!==u.cmpn(0);){var q=v.div(u);r=v.sub(q.mul(u)),x=x2.sub(q.mul(x1));var y=y2.sub(q.mul(y1));if(!a1&&r.cmp(aprxSqrt)<0)a0=prevR.neg(),b0=x1,a1=r.neg(),b1=x;else if(a1&&2==++i)break;prevR=r,v=u,u=r,x2=x1,x1=x,y2=y1,y1=y}a2=r.neg(),b2=x;var len1=a1.sqr().add(b1.sqr());return a2.sqr().add(b2.sqr()).cmp(len1)>=0&&(a2=a0,b2=b0),a1.negative&&(a1=a1.neg(),b1=b1.neg()),a2.negative&&(a2=a2.neg(),b2=b2.neg()),[{a:a1,b:b1},{a:a2,b:b2}]},ShortCurve.prototype._endoSplit=function _endoSplit(k){var basis=this.endo.basis,v1=basis[0],v2=basis[1],c1=v2.b.mul(k).divRound(this.n),c2=v1.b.neg().mul(k).divRound(this.n),p1=c1.mul(v1.a),p2=c2.mul(v2.a),q1=c1.mul(v1.b),q2=c2.mul(v2.b);return{k1:k.sub(p1).sub(p2),k2:q1.add(q2).neg()}},ShortCurve.prototype.pointFromX=function pointFromX(x,odd){(x=new BN(x,16)).red||(x=x.toRed(this.red));var y2=x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b),y=y2.redSqrt();if(0!==y.redSqr().redSub(y2).cmp(this.zero))throw new Error("invalid point");var isOdd=y.fromRed().isOdd();return(odd&&!isOdd||!odd&&isOdd)&&(y=y.redNeg()),this.point(x,y)},ShortCurve.prototype.validate=function validate(point){if(point.inf)return!0;var x=point.x,y=point.y,ax=this.a.redMul(x),rhs=x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);return 0===y.redSqr().redISub(rhs).cmpn(0)},ShortCurve.prototype._endoWnafMulAdd=function _endoWnafMulAdd(points,coeffs,jacobianResult){for(var npoints=this._endoWnafT1,ncoeffs=this._endoWnafT2,i=0;i":""},Point.prototype.isInfinity=function isInfinity(){return this.inf},Point.prototype.add=function add(p){if(this.inf)return p;if(p.inf)return this;if(this.eq(p))return this.dbl();if(this.neg().eq(p))return this.curve.point(null,null);if(0===this.x.cmp(p.x))return this.curve.point(null,null);var c=this.y.redSub(p.y);0!==c.cmpn(0)&&(c=c.redMul(this.x.redSub(p.x).redInvm()));var nx=c.redSqr().redISub(this.x).redISub(p.x),ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)},Point.prototype.dbl=function dbl(){if(this.inf)return this;var ys1=this.y.redAdd(this.y);if(0===ys1.cmpn(0))return this.curve.point(null,null);var a=this.curve.a,x2=this.x.redSqr(),dyinv=ys1.redInvm(),c=x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv),nx=c.redSqr().redISub(this.x.redAdd(this.x)),ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)},Point.prototype.getX=function getX(){return this.x.fromRed()},Point.prototype.getY=function getY(){return this.y.fromRed()},Point.prototype.mul=function mul(k){return k=new BN(k,16),this.isInfinity()?this:this._hasDoubles(k)?this.curve._fixedNafMul(this,k):this.curve.endo?this.curve._endoWnafMulAdd([this],[k]):this.curve._wnafMul(this,k)},Point.prototype.mulAdd=function mulAdd(k1,p2,k2){var points=[this,p2],coeffs=[k1,k2];return this.curve.endo?this.curve._endoWnafMulAdd(points,coeffs):this.curve._wnafMulAdd(1,points,coeffs,2)},Point.prototype.jmulAdd=function jmulAdd(k1,p2,k2){var points=[this,p2],coeffs=[k1,k2];return this.curve.endo?this.curve._endoWnafMulAdd(points,coeffs,!0):this.curve._wnafMulAdd(1,points,coeffs,2,!0)},Point.prototype.eq=function eq(p){return this===p||this.inf===p.inf&&(this.inf||0===this.x.cmp(p.x)&&0===this.y.cmp(p.y))},Point.prototype.neg=function neg(_precompute){if(this.inf)return this;var res=this.curve.point(this.x,this.y.redNeg());if(_precompute&&this.precomputed){var pre=this.precomputed,negate=function(p){return p.neg()};res.precomputed={naf:pre.naf&&{wnd:pre.naf.wnd,points:pre.naf.points.map(negate)},doubles:pre.doubles&&{step:pre.doubles.step,points:pre.doubles.points.map(negate)}}}return res},Point.prototype.toJ=function toJ(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},inherits(JPoint,Base.BasePoint),ShortCurve.prototype.jpoint=function jpoint(x,y,z){return new JPoint(this,x,y,z)},JPoint.prototype.toP=function toP(){if(this.isInfinity())return this.curve.point(null,null);var zinv=this.z.redInvm(),zinv2=zinv.redSqr(),ax=this.x.redMul(zinv2),ay=this.y.redMul(zinv2).redMul(zinv);return this.curve.point(ax,ay)},JPoint.prototype.neg=function neg(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},JPoint.prototype.add=function add(p){if(this.isInfinity())return p;if(p.isInfinity())return this;var pz2=p.z.redSqr(),z2=this.z.redSqr(),u1=this.x.redMul(pz2),u2=p.x.redMul(z2),s1=this.y.redMul(pz2.redMul(p.z)),s2=p.y.redMul(z2.redMul(this.z)),h=u1.redSub(u2),r=s1.redSub(s2);if(0===h.cmpn(0))return 0!==r.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h2=h.redSqr(),h3=h2.redMul(h),v=u1.redMul(h2),nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v),ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)),nz=this.z.redMul(p.z).redMul(h);return this.curve.jpoint(nx,ny,nz)},JPoint.prototype.mixedAdd=function mixedAdd(p){if(this.isInfinity())return p.toJ();if(p.isInfinity())return this;var z2=this.z.redSqr(),u1=this.x,u2=p.x.redMul(z2),s1=this.y,s2=p.y.redMul(z2).redMul(this.z),h=u1.redSub(u2),r=s1.redSub(s2);if(0===h.cmpn(0))return 0!==r.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h2=h.redSqr(),h3=h2.redMul(h),v=u1.redMul(h2),nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v),ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)),nz=this.z.redMul(h);return this.curve.jpoint(nx,ny,nz)},JPoint.prototype.dblp=function dblp(pow){if(0===pow)return this;if(this.isInfinity())return this;if(!pow)return this.dbl();var i;if(this.curve.zeroA||this.curve.threeA){var r=this;for(i=0;i=0)return!1;if(rx.redIAdd(t),0===this.x.cmp(rx))return!0}},JPoint.prototype.inspect=function inspect(){return this.isInfinity()?"":""},JPoint.prototype.isInfinity=function isInfinity(){return 0===this.z.cmpn(0)}},5427:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";var pre,curves=exports,hash=__webpack_require__(3715),curve=__webpack_require__(8254),assert=__webpack_require__(953).assert;function PresetCurve(options){"short"===options.type?this.curve=new curve.short(options):"edwards"===options.type?this.curve=new curve.edwards(options):this.curve=new curve.mont(options),this.g=this.curve.g,this.n=this.curve.n,this.hash=options.hash,assert(this.g.validate(),"Invalid curve"),assert(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}function defineCurve(name,options){Object.defineProperty(curves,name,{configurable:!0,enumerable:!0,get:function(){var curve=new PresetCurve(options);return Object.defineProperty(curves,name,{configurable:!0,enumerable:!0,value:curve}),curve}})}curves.PresetCurve=PresetCurve,defineCurve("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:hash.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),defineCurve("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:hash.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),defineCurve("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:hash.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),defineCurve("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:hash.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),defineCurve("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:hash.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),defineCurve("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:hash.sha256,gRed:!1,g:["9"]}),defineCurve("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:hash.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});try{pre=__webpack_require__(1037)}catch(e){pre=void 0}defineCurve("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:hash.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",pre]})},7954:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var BN=__webpack_require__(3785),HmacDRBG=__webpack_require__(2156),utils=__webpack_require__(953),curves=__webpack_require__(5427),rand=__webpack_require__(9931),assert=utils.assert,KeyPair=__webpack_require__(1251),Signature=__webpack_require__(1814);function EC(options){if(!(this instanceof EC))return new EC(options);"string"==typeof options&&(assert(Object.prototype.hasOwnProperty.call(curves,options),"Unknown curve "+options),options=curves[options]),options instanceof curves.PresetCurve&&(options={curve:options}),this.curve=options.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=options.curve.g,this.g.precompute(options.curve.n.bitLength()+1),this.hash=options.hash||options.curve.hash}module.exports=EC,EC.prototype.keyPair=function keyPair(options){return new KeyPair(this,options)},EC.prototype.keyFromPrivate=function keyFromPrivate(priv,enc){return KeyPair.fromPrivate(this,priv,enc)},EC.prototype.keyFromPublic=function keyFromPublic(pub,enc){return KeyPair.fromPublic(this,pub,enc)},EC.prototype.genKeyPair=function genKeyPair(options){options||(options={});for(var drbg=new HmacDRBG({hash:this.hash,pers:options.pers,persEnc:options.persEnc||"utf8",entropy:options.entropy||rand(this.hash.hmacStrength),entropyEnc:options.entropy&&options.entropyEnc||"utf8",nonce:this.n.toArray()}),bytes=this.n.byteLength(),ns2=this.n.sub(new BN(2));;){var priv=new BN(drbg.generate(bytes));if(!(priv.cmp(ns2)>0))return priv.iaddn(1),this.keyFromPrivate(priv)}},EC.prototype._truncateToN=function _truncateToN(msg,truncOnly){var delta=8*msg.byteLength()-this.n.bitLength();return delta>0&&(msg=msg.ushrn(delta)),!truncOnly&&msg.cmp(this.n)>=0?msg.sub(this.n):msg},EC.prototype.sign=function sign(msg,key,enc,options){"object"==typeof enc&&(options=enc,enc=null),options||(options={}),key=this.keyFromPrivate(key,enc),msg=this._truncateToN(new BN(msg,16));for(var bytes=this.n.byteLength(),bkey=key.getPrivate().toArray("be",bytes),nonce=msg.toArray("be",bytes),drbg=new HmacDRBG({hash:this.hash,entropy:bkey,nonce,pers:options.pers,persEnc:options.persEnc||"utf8"}),ns1=this.n.sub(new BN(1)),iter=0;;iter++){var k=options.k?options.k(iter):new BN(drbg.generate(this.n.byteLength()));if(!((k=this._truncateToN(k,!0)).cmpn(1)<=0||k.cmp(ns1)>=0)){var kp=this.g.mul(k);if(!kp.isInfinity()){var kpX=kp.getX(),r=kpX.umod(this.n);if(0!==r.cmpn(0)){var s=k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));if(0!==(s=s.umod(this.n)).cmpn(0)){var recoveryParam=(kp.getY().isOdd()?1:0)|(0!==kpX.cmp(r)?2:0);return options.canonical&&s.cmp(this.nh)>0&&(s=this.n.sub(s),recoveryParam^=1),new Signature({r,s,recoveryParam})}}}}}},EC.prototype.verify=function verify(msg,signature,key,enc){msg=this._truncateToN(new BN(msg,16)),key=this.keyFromPublic(key,enc);var r=(signature=new Signature(signature,"hex")).r,s=signature.s;if(r.cmpn(1)<0||r.cmp(this.n)>=0)return!1;if(s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var p,sinv=s.invm(this.n),u1=sinv.mul(msg).umod(this.n),u2=sinv.mul(r).umod(this.n);return this.curve._maxwellTrick?!(p=this.g.jmulAdd(u1,key.getPublic(),u2)).isInfinity()&&p.eqXToP(r):!(p=this.g.mulAdd(u1,key.getPublic(),u2)).isInfinity()&&0===p.getX().umod(this.n).cmp(r)},EC.prototype.recoverPubKey=function(msg,signature,j,enc){assert((3&j)===j,"The recovery param is more than two bits"),signature=new Signature(signature,enc);var n=this.n,e=new BN(msg),r=signature.r,s=signature.s,isYOdd=1&j,isSecondKey=j>>1;if(r.cmp(this.curve.p.umod(this.curve.n))>=0&&isSecondKey)throw new Error("Unable to find sencond key candinate");r=isSecondKey?this.curve.pointFromX(r.add(this.curve.n),isYOdd):this.curve.pointFromX(r,isYOdd);var rInv=signature.r.invm(n),s1=n.sub(e).mul(rInv).umod(n),s2=s.mul(rInv).umod(n);return this.g.mulAdd(s1,r,s2)},EC.prototype.getKeyRecoveryParam=function(e,signature,Q,enc){if(null!==(signature=new Signature(signature,enc)).recoveryParam)return signature.recoveryParam;for(var i=0;i<4;i++){var Qprime;try{Qprime=this.recoverPubKey(e,signature,i)}catch(e){continue}if(Qprime.eq(Q))return i}throw new Error("Unable to find valid recovery factor")}},1251:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var BN=__webpack_require__(3785),assert=__webpack_require__(953).assert;function KeyPair(ec,options){this.ec=ec,this.priv=null,this.pub=null,options.priv&&this._importPrivate(options.priv,options.privEnc),options.pub&&this._importPublic(options.pub,options.pubEnc)}module.exports=KeyPair,KeyPair.fromPublic=function fromPublic(ec,pub,enc){return pub instanceof KeyPair?pub:new KeyPair(ec,{pub,pubEnc:enc})},KeyPair.fromPrivate=function fromPrivate(ec,priv,enc){return priv instanceof KeyPair?priv:new KeyPair(ec,{priv,privEnc:enc})},KeyPair.prototype.validate=function validate(){var pub=this.getPublic();return pub.isInfinity()?{result:!1,reason:"Invalid public key"}:pub.validate()?pub.mul(this.ec.curve.n).isInfinity()?{result:!0,reason:null}:{result:!1,reason:"Public key * N != O"}:{result:!1,reason:"Public key is not a point"}},KeyPair.prototype.getPublic=function getPublic(compact,enc){return"string"==typeof compact&&(enc=compact,compact=null),this.pub||(this.pub=this.ec.g.mul(this.priv)),enc?this.pub.encode(enc,compact):this.pub},KeyPair.prototype.getPrivate=function getPrivate(enc){return"hex"===enc?this.priv.toString(16,2):this.priv},KeyPair.prototype._importPrivate=function _importPrivate(key,enc){this.priv=new BN(key,enc||16),this.priv=this.priv.umod(this.ec.curve.n)},KeyPair.prototype._importPublic=function _importPublic(key,enc){if(key.x||key.y)return"mont"===this.ec.curve.type?assert(key.x,"Need x coordinate"):"short"!==this.ec.curve.type&&"edwards"!==this.ec.curve.type||assert(key.x&&key.y,"Need both x and y coordinate"),void(this.pub=this.ec.curve.point(key.x,key.y));this.pub=this.ec.curve.decodePoint(key,enc)},KeyPair.prototype.derive=function derive(pub){return pub.validate()||assert(pub.validate(),"public point not validated"),pub.mul(this.priv).getX()},KeyPair.prototype.sign=function sign(msg,enc,options){return this.ec.sign(msg,this,enc,options)},KeyPair.prototype.verify=function verify(msg,signature){return this.ec.verify(msg,signature,this)},KeyPair.prototype.inspect=function inspect(){return""}},1814:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var BN=__webpack_require__(3785),utils=__webpack_require__(953),assert=utils.assert;function Signature(options,enc){if(options instanceof Signature)return options;this._importDER(options,enc)||(assert(options.r&&options.s,"Signature without r or s"),this.r=new BN(options.r,16),this.s=new BN(options.s,16),void 0===options.recoveryParam?this.recoveryParam=null:this.recoveryParam=options.recoveryParam)}function Position(){this.place=0}function getLength(buf,p){var initial=buf[p.place++];if(!(128&initial))return initial;var octetLen=15&initial;if(0===octetLen||octetLen>4)return!1;for(var val=0,i=0,off=p.place;i>>=0;return!(val<=127)&&(p.place=off,val)}function rmPadding(buf){for(var i=0,len=buf.length-1;!buf[i]&&!(128&buf[i+1])&&i>>3);for(arr.push(128|octets);--octets;)arr.push(len>>>(octets<<3)&255);arr.push(len)}}module.exports=Signature,Signature.prototype._importDER=function _importDER(data,enc){data=utils.toArray(data,enc);var p=new Position;if(48!==data[p.place++])return!1;var len=getLength(data,p);if(!1===len)return!1;if(len+p.place!==data.length)return!1;if(2!==data[p.place++])return!1;var rlen=getLength(data,p);if(!1===rlen)return!1;var r=data.slice(p.place,rlen+p.place);if(p.place+=rlen,2!==data[p.place++])return!1;var slen=getLength(data,p);if(!1===slen)return!1;if(data.length!==slen+p.place)return!1;var s=data.slice(p.place,slen+p.place);if(0===r[0]){if(!(128&r[1]))return!1;r=r.slice(1)}if(0===s[0]){if(!(128&s[1]))return!1;s=s.slice(1)}return this.r=new BN(r),this.s=new BN(s),this.recoveryParam=null,!0},Signature.prototype.toDER=function toDER(enc){var r=this.r.toArray(),s=this.s.toArray();for(128&r[0]&&(r=[0].concat(r)),128&s[0]&&(s=[0].concat(s)),r=rmPadding(r),s=rmPadding(s);!(s[0]||128&s[1]);)s=s.slice(1);var arr=[2];constructLength(arr,r.length),(arr=arr.concat(r)).push(2),constructLength(arr,s.length);var backHalf=arr.concat(s),res=[48];return constructLength(res,backHalf.length),res=res.concat(backHalf),utils.encode(res,enc)}},5980:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var hash=__webpack_require__(3715),curves=__webpack_require__(5427),utils=__webpack_require__(953),assert=utils.assert,parseBytes=utils.parseBytes,KeyPair=__webpack_require__(9087),Signature=__webpack_require__(3622);function EDDSA(curve){if(assert("ed25519"===curve,"only tested with ed25519 so far"),!(this instanceof EDDSA))return new EDDSA(curve);curve=curves[curve].curve,this.curve=curve,this.g=curve.g,this.g.precompute(curve.n.bitLength()+1),this.pointClass=curve.point().constructor,this.encodingLength=Math.ceil(curve.n.bitLength()/8),this.hash=hash.sha512}module.exports=EDDSA,EDDSA.prototype.sign=function sign(message,secret){message=parseBytes(message);var key=this.keyFromSecret(secret),r=this.hashInt(key.messagePrefix(),message),R=this.g.mul(r),Rencoded=this.encodePoint(R),s_=this.hashInt(Rencoded,key.pubBytes(),message).mul(key.priv()),S=r.add(s_).umod(this.curve.n);return this.makeSignature({R,S,Rencoded})},EDDSA.prototype.verify=function verify(message,sig,pub){message=parseBytes(message),sig=this.makeSignature(sig);var key=this.keyFromPublic(pub),h=this.hashInt(sig.Rencoded(),key.pubBytes(),message),SG=this.g.mul(sig.S());return sig.R().add(key.pub().mul(h)).eq(SG)},EDDSA.prototype.hashInt=function hashInt(){for(var hash=this.hash(),i=0;i{"use strict";var utils=__webpack_require__(953),assert=utils.assert,parseBytes=utils.parseBytes,cachedProperty=utils.cachedProperty;function KeyPair(eddsa,params){this.eddsa=eddsa,this._secret=parseBytes(params.secret),eddsa.isPoint(params.pub)?this._pub=params.pub:this._pubBytes=parseBytes(params.pub)}KeyPair.fromPublic=function fromPublic(eddsa,pub){return pub instanceof KeyPair?pub:new KeyPair(eddsa,{pub})},KeyPair.fromSecret=function fromSecret(eddsa,secret){return secret instanceof KeyPair?secret:new KeyPair(eddsa,{secret})},KeyPair.prototype.secret=function secret(){return this._secret},cachedProperty(KeyPair,"pubBytes",(function pubBytes(){return this.eddsa.encodePoint(this.pub())})),cachedProperty(KeyPair,"pub",(function pub(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())})),cachedProperty(KeyPair,"privBytes",(function privBytes(){var eddsa=this.eddsa,hash=this.hash(),lastIx=eddsa.encodingLength-1,a=hash.slice(0,eddsa.encodingLength);return a[0]&=248,a[lastIx]&=127,a[lastIx]|=64,a})),cachedProperty(KeyPair,"priv",(function priv(){return this.eddsa.decodeInt(this.privBytes())})),cachedProperty(KeyPair,"hash",(function hash(){return this.eddsa.hash().update(this.secret()).digest()})),cachedProperty(KeyPair,"messagePrefix",(function messagePrefix(){return this.hash().slice(this.eddsa.encodingLength)})),KeyPair.prototype.sign=function sign(message){return assert(this._secret,"KeyPair can only verify"),this.eddsa.sign(message,this)},KeyPair.prototype.verify=function verify(message,sig){return this.eddsa.verify(message,sig,this)},KeyPair.prototype.getSecret=function getSecret(enc){return assert(this._secret,"KeyPair is public only"),utils.encode(this.secret(),enc)},KeyPair.prototype.getPublic=function getPublic(enc){return utils.encode(this.pubBytes(),enc)},module.exports=KeyPair},3622:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var BN=__webpack_require__(3785),utils=__webpack_require__(953),assert=utils.assert,cachedProperty=utils.cachedProperty,parseBytes=utils.parseBytes;function Signature(eddsa,sig){this.eddsa=eddsa,"object"!=typeof sig&&(sig=parseBytes(sig)),Array.isArray(sig)&&(sig={R:sig.slice(0,eddsa.encodingLength),S:sig.slice(eddsa.encodingLength)}),assert(sig.R&&sig.S,"Signature without R or S"),eddsa.isPoint(sig.R)&&(this._R=sig.R),sig.S instanceof BN&&(this._S=sig.S),this._Rencoded=Array.isArray(sig.R)?sig.R:sig.Rencoded,this._Sencoded=Array.isArray(sig.S)?sig.S:sig.Sencoded}cachedProperty(Signature,"S",(function S(){return this.eddsa.decodeInt(this.Sencoded())})),cachedProperty(Signature,"R",(function R(){return this.eddsa.decodePoint(this.Rencoded())})),cachedProperty(Signature,"Rencoded",(function Rencoded(){return this.eddsa.encodePoint(this.R())})),cachedProperty(Signature,"Sencoded",(function Sencoded(){return this.eddsa.encodeInt(this.S())})),Signature.prototype.toBytes=function toBytes(){return this.Rencoded().concat(this.Sencoded())},Signature.prototype.toHex=function toHex(){return utils.encode(this.toBytes(),"hex").toUpperCase()},module.exports=Signature},1037:module=>{module.exports={doubles:{step:4,points:[["e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a","f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"],["8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508","11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"],["175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739","d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"],["363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640","4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"],["8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c","4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"],["723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda","96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"],["eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa","5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"],["100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0","cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"],["e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d","9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"],["feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d","e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"],["da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1","9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"],["53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0","5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"],["8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047","10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"],["385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862","283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"],["6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7","7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"],["3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd","56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"],["85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83","7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"],["948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a","53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"],["6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8","bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"],["e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d","4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"],["e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725","7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"],["213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754","4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"],["4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c","17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"],["fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6","6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"],["76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39","c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"],["c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891","893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"],["d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b","febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"],["b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03","2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"],["e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d","eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"],["a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070","7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"],["90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4","e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"],["8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da","662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"],["e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11","1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"],["8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e","efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"],["e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41","2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"],["b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef","67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"],["d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8","db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"],["324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d","648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"],["4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96","35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"],["9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd","ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"],["6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5","9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"],["a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266","40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"],["7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71","34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"],["928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac","c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"],["85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751","1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"],["ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e","493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"],["827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241","c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"],["eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3","be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"],["e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f","4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"],["1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19","aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"],["146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be","b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"],["fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9","6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"],["da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2","8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"],["a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13","7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"],["174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c","ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"],["959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba","2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"],["d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151","e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"],["64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073","d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"],["8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458","38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"],["13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b","69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"],["bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366","d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"],["8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa","40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"],["8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0","620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"],["dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787","7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"],["f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e","ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"]]},naf:{wnd:7,points:[["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"],["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4","d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"],["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"],["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe","cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"],["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"],["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8","ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"],["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e","581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"],["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34","4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"],["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c","85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"],["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5","321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"],["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f","2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"],["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714","73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"],["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729","a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"],["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db","2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"],["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4","e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"],["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5","b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"],["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479","2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"],["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d","80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"],["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f","1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"],["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb","d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"],["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9","eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"],["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963","758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"],["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74","958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"],["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530","e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"],["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b","5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"],["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247","cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"],["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1","cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"],["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120","4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"],["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435","91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"],["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18","673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"],["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8","59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"],["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb","3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"],["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f","55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"],["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143","efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"],["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba","e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"],["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45","f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"],["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a","744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"],["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e","c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"],["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8","e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"],["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c","30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"],["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519","e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"],["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab","100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"],["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca","ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"],["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf","8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"],["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610","68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"],["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4","f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"],["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c","d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"],["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940","edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"],["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980","a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"],["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3","66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"],["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf","9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"],["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63","4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"],["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448","fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"],["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf","5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"],["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5","8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"],["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6","8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"],["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5","5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"],["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99","f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"],["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51","f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"],["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5","42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"],["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5","204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"],["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997","4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"],["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881","73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"],["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5","39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"],["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66","d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"],["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726","ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"],["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede","6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"],["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94","60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"],["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31","3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"],["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51","b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"],["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252","ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"],["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5","cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"],["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b","6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"],["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4","322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"],["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f","6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"],["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889","2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"],["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246","b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"],["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984","998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"],["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a","b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"],["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030","bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"],["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197","6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"],["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593","c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"],["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef","21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"],["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38","60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"],["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a","49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"],["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111","5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"],["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502","7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"],["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea","be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"],["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26","8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"],["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986","39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"],["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e","62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"],["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4","25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"],["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda","ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"],["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859","cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"],["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f","f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"],["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c","6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"],["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942","fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"],["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a","1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"],["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80","5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"],["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d","438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"],["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1","cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"],["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63","c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"],["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352","6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"],["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193","ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"],["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00","9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"],["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58","ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"],["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7","d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"],["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8","c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"],["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e","67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"],["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d","cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"],["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b","299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"],["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f","f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"],["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6","462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"],["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297","62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"],["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a","7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"],["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c","ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"],["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52","4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"],["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb","bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"],["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065","bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"],["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917","603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"],["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9","cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"],["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3","553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"],["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57","712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"],["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66","ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"],["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8","9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"],["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721","9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"],["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180","4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]]}}},953:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";var utils=exports,BN=__webpack_require__(3785),minAssert=__webpack_require__(9746),minUtils=__webpack_require__(4504);utils.assert=minAssert,utils.toArray=minUtils.toArray,utils.zero2=minUtils.zero2,utils.toHex=minUtils.toHex,utils.encode=minUtils.encode,utils.getNAF=function getNAF(num,w,bits){var naf=new Array(Math.max(num.bitLength(),bits)+1);naf.fill(0);for(var ws=1<(ws>>1)-1?(ws>>1)-mod:mod,k.isubn(z)):z=0,naf[i]=z,k.iushrn(1)}return naf},utils.getJSF=function getJSF(k1,k2){var jsf=[[],[]];k1=k1.clone(),k2=k2.clone();for(var m8,d1=0,d2=0;k1.cmpn(-d1)>0||k2.cmpn(-d2)>0;){var u1,u2,m14=k1.andln(3)+d1&3,m24=k2.andln(3)+d2&3;3===m14&&(m14=-1),3===m24&&(m24=-1),u1=0==(1&m14)?0:3!==(m8=k1.andln(7)+d1&7)&&5!==m8||2!==m24?m14:-m14,jsf[0].push(u1),u2=0==(1&m24)?0:3!==(m8=k2.andln(7)+d2&7)&&5!==m8||2!==m14?m24:-m24,jsf[1].push(u2),2*d1===u1+1&&(d1=1-d1),2*d2===u2+1&&(d2=1-d2),k1.iushrn(1),k2.iushrn(1)}return jsf},utils.cachedProperty=function cachedProperty(obj,name,computer){var key="_"+name;obj.prototype[name]=function cachedProperty(){return void 0!==this[key]?this[key]:this[key]=computer.call(this)}},utils.parseBytes=function parseBytes(bytes){return"string"==typeof bytes?utils.toArray(bytes,"hex"):bytes},utils.intFromLE=function intFromLE(bytes){return new BN(bytes,"hex","le")}},3785:function(module,__unused_webpack_exports,__webpack_require__){!function(module,exports){"use strict";function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}function BN(number,base,endian){if(BN.isBN(number))return number;this.negative=0,this.words=null,this.length=0,this.red=null,null!==number&&("le"!==base&&"be"!==base||(endian=base,base=10),this._init(number||0,base||10,endian||"be"))}var Buffer;"object"==typeof module?module.exports=BN:exports.BN=BN,BN.BN=BN,BN.wordSize=26;try{Buffer="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:__webpack_require__(5568).Buffer}catch(e){}function parseHex4Bits(string,index){var c=string.charCodeAt(index);return c>=65&&c<=70?c-55:c>=97&&c<=102?c-87:c-48&15}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return index-1>=lowerBound&&(r|=parseHex4Bits(string,index-1)<<4),r}function parseBase(str,start,end,mul){for(var r=0,len=Math.min(str.length,end),i=start;i=49?c-49+10:c>=17?c-17+10:c}return r}BN.isBN=function isBN(num){return num instanceof BN||null!==num&&"object"==typeof num&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words)},BN.max=function max(left,right){return left.cmp(right)>0?left:right},BN.min=function min(left,right){return left.cmp(right)<0?left:right},BN.prototype._init=function init(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&base>=2&&base<=36);var start=0;"-"===(number=number.toString().replace(/\s+/g,""))[0]&&(start++,this.negative=1),start=0;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=w<>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);return this.strip()},BN.prototype._parseHex=function _parseHex(number,start,endian){this.length=Math.ceil((number.length-start)/6),this.words=new Array(this.length);for(var i=0;i=start;i-=2)w=parseHexByte(number,start,i)<=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;else for(i=(number.length-start)%2==0?start+1:start;i=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;this.strip()},BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;limbPow*=base)limbLen++;limbLen--,limbPow=limbPow/base|0;for(var total=number.length-start,mod=total%limbLen,end=Math.min(total,total-mod)+start,word=0,i=start;i1&&0===this.words[this.length-1];)this.length--;return this._normSign()},BN.prototype._normSign=function _normSign(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},BN.prototype.inspect=function inspect(){return(this.red?""};var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=self.length+num.length|0;out.length=len,len=len-1|0;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=r/67108864|0;out.words[0]=lo;for(var k=1;k>>26,rword=67108863&carry,maxJ=Math.min(k,num.length-1),j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j|0;ncarry+=(r=(a=0|self.words[i])*(b=0|num.words[j])+rword)/67108864|0,rword=67108863&r}out.words[k]=0|rword,carry=0|ncarry}return 0!==carry?out.words[k]=0|carry:out.length--,out.strip()}BN.prototype.toString=function toString(base,padding){var out;if(padding=0|padding||1,16===(base=base||10)||"hex"===base){out="";for(var off=0,carry=0,i=0;i>>24-off&16777215)||i!==this.length-1?zeros[6-word.length]+word+out:word+out,(off+=2)>=26&&(off-=26,i--)}for(0!==carry&&(out=carry.toString(16)+out);out.length%padding!=0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&base>=2&&base<=36){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modn(groupBase).toString(base);out=(c=c.idivn(groupBase)).isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);out.length%padding!=0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function toNumber(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:this.length>2&&assert(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-ret:ret},BN.prototype.toJSON=function toJSON(){return this.toString(16)},BN.prototype.toBuffer=function toBuffer(endian,length){return assert(void 0!==Buffer),this.toArrayLike(Buffer,endian,length)},BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)},BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){var byteLength=this.byteLength(),reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length"),assert(reqLength>0,"Requested array length <= 0"),this.strip();var b,i,littleEndian="le"===endian,res=new ArrayType(reqLength),q=this.clone();if(littleEndian){for(i=0;!q.isZero();i++)b=q.andln(255),q.iushrn(8),res[i]=b;for(;i=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function _zeroBits(w){if(0===w)return 26;var t=w,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;for(var r=0,i=0;inum.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function uor(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function iuand(num){var b;b=this.length>num.length?num:this;for(var i=0;inum.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function uand(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function iuxor(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;inum.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function uxor(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function inotn(width){assert("number"==typeof width&&width>=0);var bytesNeeded=0|Math.ceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),bitsLeft>0&&bytesNeeded--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this.strip()},BN.prototype.notn=function notn(width){return this.clone().inotn(width)},BN.prototype.setn=function setn(bit,val){assert("number"==typeof bit&&bit>=0);var off=bit/26|0,wbit=bit%26;return this._expand(off+1),this.words[off]=val?this.words[off]|1<num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>>26;for(;0!==carry&&i>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;inum.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function isub(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var a,b,cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;cmp>0?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>26,this.words[i]=67108863&r;for(;0!==carry&&i>26,this.words[i]=67108863&r;if(0===carry&&i>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13;out.negative=self.negative^num.negative,out.length=19;var w0=(c+(lo=Math.imul(al0,bl0))|0)+((8191&(mid=(mid=Math.imul(al0,bh0))+Math.imul(ah0,bl0)|0))<<13)|0;c=((hi=Math.imul(ah0,bh0))+(mid>>>13)|0)+(w0>>>26)|0,w0&=67108863,lo=Math.imul(al1,bl0),mid=(mid=Math.imul(al1,bh0))+Math.imul(ah1,bl0)|0,hi=Math.imul(ah1,bh0);var w1=(c+(lo=lo+Math.imul(al0,bl1)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh1)|0)+Math.imul(ah0,bl1)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh1)|0)+(mid>>>13)|0)+(w1>>>26)|0,w1&=67108863,lo=Math.imul(al2,bl0),mid=(mid=Math.imul(al2,bh0))+Math.imul(ah2,bl0)|0,hi=Math.imul(ah2,bh0),lo=lo+Math.imul(al1,bl1)|0,mid=(mid=mid+Math.imul(al1,bh1)|0)+Math.imul(ah1,bl1)|0,hi=hi+Math.imul(ah1,bh1)|0;var w2=(c+(lo=lo+Math.imul(al0,bl2)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh2)|0)+Math.imul(ah0,bl2)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh2)|0)+(mid>>>13)|0)+(w2>>>26)|0,w2&=67108863,lo=Math.imul(al3,bl0),mid=(mid=Math.imul(al3,bh0))+Math.imul(ah3,bl0)|0,hi=Math.imul(ah3,bh0),lo=lo+Math.imul(al2,bl1)|0,mid=(mid=mid+Math.imul(al2,bh1)|0)+Math.imul(ah2,bl1)|0,hi=hi+Math.imul(ah2,bh1)|0,lo=lo+Math.imul(al1,bl2)|0,mid=(mid=mid+Math.imul(al1,bh2)|0)+Math.imul(ah1,bl2)|0,hi=hi+Math.imul(ah1,bh2)|0;var w3=(c+(lo=lo+Math.imul(al0,bl3)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh3)|0)+Math.imul(ah0,bl3)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh3)|0)+(mid>>>13)|0)+(w3>>>26)|0,w3&=67108863,lo=Math.imul(al4,bl0),mid=(mid=Math.imul(al4,bh0))+Math.imul(ah4,bl0)|0,hi=Math.imul(ah4,bh0),lo=lo+Math.imul(al3,bl1)|0,mid=(mid=mid+Math.imul(al3,bh1)|0)+Math.imul(ah3,bl1)|0,hi=hi+Math.imul(ah3,bh1)|0,lo=lo+Math.imul(al2,bl2)|0,mid=(mid=mid+Math.imul(al2,bh2)|0)+Math.imul(ah2,bl2)|0,hi=hi+Math.imul(ah2,bh2)|0,lo=lo+Math.imul(al1,bl3)|0,mid=(mid=mid+Math.imul(al1,bh3)|0)+Math.imul(ah1,bl3)|0,hi=hi+Math.imul(ah1,bh3)|0;var w4=(c+(lo=lo+Math.imul(al0,bl4)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh4)|0)+Math.imul(ah0,bl4)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh4)|0)+(mid>>>13)|0)+(w4>>>26)|0,w4&=67108863,lo=Math.imul(al5,bl0),mid=(mid=Math.imul(al5,bh0))+Math.imul(ah5,bl0)|0,hi=Math.imul(ah5,bh0),lo=lo+Math.imul(al4,bl1)|0,mid=(mid=mid+Math.imul(al4,bh1)|0)+Math.imul(ah4,bl1)|0,hi=hi+Math.imul(ah4,bh1)|0,lo=lo+Math.imul(al3,bl2)|0,mid=(mid=mid+Math.imul(al3,bh2)|0)+Math.imul(ah3,bl2)|0,hi=hi+Math.imul(ah3,bh2)|0,lo=lo+Math.imul(al2,bl3)|0,mid=(mid=mid+Math.imul(al2,bh3)|0)+Math.imul(ah2,bl3)|0,hi=hi+Math.imul(ah2,bh3)|0,lo=lo+Math.imul(al1,bl4)|0,mid=(mid=mid+Math.imul(al1,bh4)|0)+Math.imul(ah1,bl4)|0,hi=hi+Math.imul(ah1,bh4)|0;var w5=(c+(lo=lo+Math.imul(al0,bl5)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh5)|0)+Math.imul(ah0,bl5)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh5)|0)+(mid>>>13)|0)+(w5>>>26)|0,w5&=67108863,lo=Math.imul(al6,bl0),mid=(mid=Math.imul(al6,bh0))+Math.imul(ah6,bl0)|0,hi=Math.imul(ah6,bh0),lo=lo+Math.imul(al5,bl1)|0,mid=(mid=mid+Math.imul(al5,bh1)|0)+Math.imul(ah5,bl1)|0,hi=hi+Math.imul(ah5,bh1)|0,lo=lo+Math.imul(al4,bl2)|0,mid=(mid=mid+Math.imul(al4,bh2)|0)+Math.imul(ah4,bl2)|0,hi=hi+Math.imul(ah4,bh2)|0,lo=lo+Math.imul(al3,bl3)|0,mid=(mid=mid+Math.imul(al3,bh3)|0)+Math.imul(ah3,bl3)|0,hi=hi+Math.imul(ah3,bh3)|0,lo=lo+Math.imul(al2,bl4)|0,mid=(mid=mid+Math.imul(al2,bh4)|0)+Math.imul(ah2,bl4)|0,hi=hi+Math.imul(ah2,bh4)|0,lo=lo+Math.imul(al1,bl5)|0,mid=(mid=mid+Math.imul(al1,bh5)|0)+Math.imul(ah1,bl5)|0,hi=hi+Math.imul(ah1,bh5)|0;var w6=(c+(lo=lo+Math.imul(al0,bl6)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh6)|0)+Math.imul(ah0,bl6)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh6)|0)+(mid>>>13)|0)+(w6>>>26)|0,w6&=67108863,lo=Math.imul(al7,bl0),mid=(mid=Math.imul(al7,bh0))+Math.imul(ah7,bl0)|0,hi=Math.imul(ah7,bh0),lo=lo+Math.imul(al6,bl1)|0,mid=(mid=mid+Math.imul(al6,bh1)|0)+Math.imul(ah6,bl1)|0,hi=hi+Math.imul(ah6,bh1)|0,lo=lo+Math.imul(al5,bl2)|0,mid=(mid=mid+Math.imul(al5,bh2)|0)+Math.imul(ah5,bl2)|0,hi=hi+Math.imul(ah5,bh2)|0,lo=lo+Math.imul(al4,bl3)|0,mid=(mid=mid+Math.imul(al4,bh3)|0)+Math.imul(ah4,bl3)|0,hi=hi+Math.imul(ah4,bh3)|0,lo=lo+Math.imul(al3,bl4)|0,mid=(mid=mid+Math.imul(al3,bh4)|0)+Math.imul(ah3,bl4)|0,hi=hi+Math.imul(ah3,bh4)|0,lo=lo+Math.imul(al2,bl5)|0,mid=(mid=mid+Math.imul(al2,bh5)|0)+Math.imul(ah2,bl5)|0,hi=hi+Math.imul(ah2,bh5)|0,lo=lo+Math.imul(al1,bl6)|0,mid=(mid=mid+Math.imul(al1,bh6)|0)+Math.imul(ah1,bl6)|0,hi=hi+Math.imul(ah1,bh6)|0;var w7=(c+(lo=lo+Math.imul(al0,bl7)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh7)|0)+Math.imul(ah0,bl7)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh7)|0)+(mid>>>13)|0)+(w7>>>26)|0,w7&=67108863,lo=Math.imul(al8,bl0),mid=(mid=Math.imul(al8,bh0))+Math.imul(ah8,bl0)|0,hi=Math.imul(ah8,bh0),lo=lo+Math.imul(al7,bl1)|0,mid=(mid=mid+Math.imul(al7,bh1)|0)+Math.imul(ah7,bl1)|0,hi=hi+Math.imul(ah7,bh1)|0,lo=lo+Math.imul(al6,bl2)|0,mid=(mid=mid+Math.imul(al6,bh2)|0)+Math.imul(ah6,bl2)|0,hi=hi+Math.imul(ah6,bh2)|0,lo=lo+Math.imul(al5,bl3)|0,mid=(mid=mid+Math.imul(al5,bh3)|0)+Math.imul(ah5,bl3)|0,hi=hi+Math.imul(ah5,bh3)|0,lo=lo+Math.imul(al4,bl4)|0,mid=(mid=mid+Math.imul(al4,bh4)|0)+Math.imul(ah4,bl4)|0,hi=hi+Math.imul(ah4,bh4)|0,lo=lo+Math.imul(al3,bl5)|0,mid=(mid=mid+Math.imul(al3,bh5)|0)+Math.imul(ah3,bl5)|0,hi=hi+Math.imul(ah3,bh5)|0,lo=lo+Math.imul(al2,bl6)|0,mid=(mid=mid+Math.imul(al2,bh6)|0)+Math.imul(ah2,bl6)|0,hi=hi+Math.imul(ah2,bh6)|0,lo=lo+Math.imul(al1,bl7)|0,mid=(mid=mid+Math.imul(al1,bh7)|0)+Math.imul(ah1,bl7)|0,hi=hi+Math.imul(ah1,bh7)|0;var w8=(c+(lo=lo+Math.imul(al0,bl8)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh8)|0)+Math.imul(ah0,bl8)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh8)|0)+(mid>>>13)|0)+(w8>>>26)|0,w8&=67108863,lo=Math.imul(al9,bl0),mid=(mid=Math.imul(al9,bh0))+Math.imul(ah9,bl0)|0,hi=Math.imul(ah9,bh0),lo=lo+Math.imul(al8,bl1)|0,mid=(mid=mid+Math.imul(al8,bh1)|0)+Math.imul(ah8,bl1)|0,hi=hi+Math.imul(ah8,bh1)|0,lo=lo+Math.imul(al7,bl2)|0,mid=(mid=mid+Math.imul(al7,bh2)|0)+Math.imul(ah7,bl2)|0,hi=hi+Math.imul(ah7,bh2)|0,lo=lo+Math.imul(al6,bl3)|0,mid=(mid=mid+Math.imul(al6,bh3)|0)+Math.imul(ah6,bl3)|0,hi=hi+Math.imul(ah6,bh3)|0,lo=lo+Math.imul(al5,bl4)|0,mid=(mid=mid+Math.imul(al5,bh4)|0)+Math.imul(ah5,bl4)|0,hi=hi+Math.imul(ah5,bh4)|0,lo=lo+Math.imul(al4,bl5)|0,mid=(mid=mid+Math.imul(al4,bh5)|0)+Math.imul(ah4,bl5)|0,hi=hi+Math.imul(ah4,bh5)|0,lo=lo+Math.imul(al3,bl6)|0,mid=(mid=mid+Math.imul(al3,bh6)|0)+Math.imul(ah3,bl6)|0,hi=hi+Math.imul(ah3,bh6)|0,lo=lo+Math.imul(al2,bl7)|0,mid=(mid=mid+Math.imul(al2,bh7)|0)+Math.imul(ah2,bl7)|0,hi=hi+Math.imul(ah2,bh7)|0,lo=lo+Math.imul(al1,bl8)|0,mid=(mid=mid+Math.imul(al1,bh8)|0)+Math.imul(ah1,bl8)|0,hi=hi+Math.imul(ah1,bh8)|0;var w9=(c+(lo=lo+Math.imul(al0,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh9)|0)+Math.imul(ah0,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh9)|0)+(mid>>>13)|0)+(w9>>>26)|0,w9&=67108863,lo=Math.imul(al9,bl1),mid=(mid=Math.imul(al9,bh1))+Math.imul(ah9,bl1)|0,hi=Math.imul(ah9,bh1),lo=lo+Math.imul(al8,bl2)|0,mid=(mid=mid+Math.imul(al8,bh2)|0)+Math.imul(ah8,bl2)|0,hi=hi+Math.imul(ah8,bh2)|0,lo=lo+Math.imul(al7,bl3)|0,mid=(mid=mid+Math.imul(al7,bh3)|0)+Math.imul(ah7,bl3)|0,hi=hi+Math.imul(ah7,bh3)|0,lo=lo+Math.imul(al6,bl4)|0,mid=(mid=mid+Math.imul(al6,bh4)|0)+Math.imul(ah6,bl4)|0,hi=hi+Math.imul(ah6,bh4)|0,lo=lo+Math.imul(al5,bl5)|0,mid=(mid=mid+Math.imul(al5,bh5)|0)+Math.imul(ah5,bl5)|0,hi=hi+Math.imul(ah5,bh5)|0,lo=lo+Math.imul(al4,bl6)|0,mid=(mid=mid+Math.imul(al4,bh6)|0)+Math.imul(ah4,bl6)|0,hi=hi+Math.imul(ah4,bh6)|0,lo=lo+Math.imul(al3,bl7)|0,mid=(mid=mid+Math.imul(al3,bh7)|0)+Math.imul(ah3,bl7)|0,hi=hi+Math.imul(ah3,bh7)|0,lo=lo+Math.imul(al2,bl8)|0,mid=(mid=mid+Math.imul(al2,bh8)|0)+Math.imul(ah2,bl8)|0,hi=hi+Math.imul(ah2,bh8)|0;var w10=(c+(lo=lo+Math.imul(al1,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al1,bh9)|0)+Math.imul(ah1,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah1,bh9)|0)+(mid>>>13)|0)+(w10>>>26)|0,w10&=67108863,lo=Math.imul(al9,bl2),mid=(mid=Math.imul(al9,bh2))+Math.imul(ah9,bl2)|0,hi=Math.imul(ah9,bh2),lo=lo+Math.imul(al8,bl3)|0,mid=(mid=mid+Math.imul(al8,bh3)|0)+Math.imul(ah8,bl3)|0,hi=hi+Math.imul(ah8,bh3)|0,lo=lo+Math.imul(al7,bl4)|0,mid=(mid=mid+Math.imul(al7,bh4)|0)+Math.imul(ah7,bl4)|0,hi=hi+Math.imul(ah7,bh4)|0,lo=lo+Math.imul(al6,bl5)|0,mid=(mid=mid+Math.imul(al6,bh5)|0)+Math.imul(ah6,bl5)|0,hi=hi+Math.imul(ah6,bh5)|0,lo=lo+Math.imul(al5,bl6)|0,mid=(mid=mid+Math.imul(al5,bh6)|0)+Math.imul(ah5,bl6)|0,hi=hi+Math.imul(ah5,bh6)|0,lo=lo+Math.imul(al4,bl7)|0,mid=(mid=mid+Math.imul(al4,bh7)|0)+Math.imul(ah4,bl7)|0,hi=hi+Math.imul(ah4,bh7)|0,lo=lo+Math.imul(al3,bl8)|0,mid=(mid=mid+Math.imul(al3,bh8)|0)+Math.imul(ah3,bl8)|0,hi=hi+Math.imul(ah3,bh8)|0;var w11=(c+(lo=lo+Math.imul(al2,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al2,bh9)|0)+Math.imul(ah2,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah2,bh9)|0)+(mid>>>13)|0)+(w11>>>26)|0,w11&=67108863,lo=Math.imul(al9,bl3),mid=(mid=Math.imul(al9,bh3))+Math.imul(ah9,bl3)|0,hi=Math.imul(ah9,bh3),lo=lo+Math.imul(al8,bl4)|0,mid=(mid=mid+Math.imul(al8,bh4)|0)+Math.imul(ah8,bl4)|0,hi=hi+Math.imul(ah8,bh4)|0,lo=lo+Math.imul(al7,bl5)|0,mid=(mid=mid+Math.imul(al7,bh5)|0)+Math.imul(ah7,bl5)|0,hi=hi+Math.imul(ah7,bh5)|0,lo=lo+Math.imul(al6,bl6)|0,mid=(mid=mid+Math.imul(al6,bh6)|0)+Math.imul(ah6,bl6)|0,hi=hi+Math.imul(ah6,bh6)|0,lo=lo+Math.imul(al5,bl7)|0,mid=(mid=mid+Math.imul(al5,bh7)|0)+Math.imul(ah5,bl7)|0,hi=hi+Math.imul(ah5,bh7)|0,lo=lo+Math.imul(al4,bl8)|0,mid=(mid=mid+Math.imul(al4,bh8)|0)+Math.imul(ah4,bl8)|0,hi=hi+Math.imul(ah4,bh8)|0;var w12=(c+(lo=lo+Math.imul(al3,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al3,bh9)|0)+Math.imul(ah3,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah3,bh9)|0)+(mid>>>13)|0)+(w12>>>26)|0,w12&=67108863,lo=Math.imul(al9,bl4),mid=(mid=Math.imul(al9,bh4))+Math.imul(ah9,bl4)|0,hi=Math.imul(ah9,bh4),lo=lo+Math.imul(al8,bl5)|0,mid=(mid=mid+Math.imul(al8,bh5)|0)+Math.imul(ah8,bl5)|0,hi=hi+Math.imul(ah8,bh5)|0,lo=lo+Math.imul(al7,bl6)|0,mid=(mid=mid+Math.imul(al7,bh6)|0)+Math.imul(ah7,bl6)|0,hi=hi+Math.imul(ah7,bh6)|0,lo=lo+Math.imul(al6,bl7)|0,mid=(mid=mid+Math.imul(al6,bh7)|0)+Math.imul(ah6,bl7)|0,hi=hi+Math.imul(ah6,bh7)|0,lo=lo+Math.imul(al5,bl8)|0,mid=(mid=mid+Math.imul(al5,bh8)|0)+Math.imul(ah5,bl8)|0,hi=hi+Math.imul(ah5,bh8)|0;var w13=(c+(lo=lo+Math.imul(al4,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al4,bh9)|0)+Math.imul(ah4,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah4,bh9)|0)+(mid>>>13)|0)+(w13>>>26)|0,w13&=67108863,lo=Math.imul(al9,bl5),mid=(mid=Math.imul(al9,bh5))+Math.imul(ah9,bl5)|0,hi=Math.imul(ah9,bh5),lo=lo+Math.imul(al8,bl6)|0,mid=(mid=mid+Math.imul(al8,bh6)|0)+Math.imul(ah8,bl6)|0,hi=hi+Math.imul(ah8,bh6)|0,lo=lo+Math.imul(al7,bl7)|0,mid=(mid=mid+Math.imul(al7,bh7)|0)+Math.imul(ah7,bl7)|0,hi=hi+Math.imul(ah7,bh7)|0,lo=lo+Math.imul(al6,bl8)|0,mid=(mid=mid+Math.imul(al6,bh8)|0)+Math.imul(ah6,bl8)|0,hi=hi+Math.imul(ah6,bh8)|0;var w14=(c+(lo=lo+Math.imul(al5,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al5,bh9)|0)+Math.imul(ah5,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah5,bh9)|0)+(mid>>>13)|0)+(w14>>>26)|0,w14&=67108863,lo=Math.imul(al9,bl6),mid=(mid=Math.imul(al9,bh6))+Math.imul(ah9,bl6)|0,hi=Math.imul(ah9,bh6),lo=lo+Math.imul(al8,bl7)|0,mid=(mid=mid+Math.imul(al8,bh7)|0)+Math.imul(ah8,bl7)|0,hi=hi+Math.imul(ah8,bh7)|0,lo=lo+Math.imul(al7,bl8)|0,mid=(mid=mid+Math.imul(al7,bh8)|0)+Math.imul(ah7,bl8)|0,hi=hi+Math.imul(ah7,bh8)|0;var w15=(c+(lo=lo+Math.imul(al6,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al6,bh9)|0)+Math.imul(ah6,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah6,bh9)|0)+(mid>>>13)|0)+(w15>>>26)|0,w15&=67108863,lo=Math.imul(al9,bl7),mid=(mid=Math.imul(al9,bh7))+Math.imul(ah9,bl7)|0,hi=Math.imul(ah9,bh7),lo=lo+Math.imul(al8,bl8)|0,mid=(mid=mid+Math.imul(al8,bh8)|0)+Math.imul(ah8,bl8)|0,hi=hi+Math.imul(ah8,bh8)|0;var w16=(c+(lo=lo+Math.imul(al7,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al7,bh9)|0)+Math.imul(ah7,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah7,bh9)|0)+(mid>>>13)|0)+(w16>>>26)|0,w16&=67108863,lo=Math.imul(al9,bl8),mid=(mid=Math.imul(al9,bh8))+Math.imul(ah9,bl8)|0,hi=Math.imul(ah9,bh8);var w17=(c+(lo=lo+Math.imul(al8,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al8,bh9)|0)+Math.imul(ah8,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah8,bh9)|0)+(mid>>>13)|0)+(w17>>>26)|0,w17&=67108863;var w18=(c+(lo=Math.imul(al9,bl9))|0)+((8191&(mid=(mid=Math.imul(al9,bh9))+Math.imul(ah9,bl9)|0))<<13)|0;return c=((hi=Math.imul(ah9,bh9))+(mid>>>13)|0)+(w18>>>26)|0,w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,0!==c&&(o[19]=c,out.length++),out};function jumboMulTo(self,num,out){return(new FFTM).mulp(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}Math.imul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function mulTo(num,out){var res,len=this.length+num.length;return res=10===this.length&&10===num.length?comb10MulTo(this,num,out):len<63?smallMulTo(this,num,out):len<1024?function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0;k>>26)|0)>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0!==carry?out.words[k]=carry:out.length--,out.strip()}(this,num,out):jumboMulTo(this,num,out),res},FFTM.prototype.makeRBT=function makeRBT(N){for(var t=new Array(N),l=BN.prototype._countBits(N)-1,i=0;i>=1;return rb},FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>=1)i++;return 1<>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;i>=26,carry+=w/67108864|0,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.muln=function muln(num){return this.clone().imuln(num)},BN.prototype.sqr=function sqr(){return this.mul(this)},BN.prototype.isqr=function isqr(){return this.imul(this.clone())},BN.prototype.pow=function pow(num){var w=function toBitArray(num){for(var w=new Array(num.bitLength()),bit=0;bit>>wbit}return w}(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i=0);var i,r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r;if(0!==r){var carry=0;for(i=0;i>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;i>=0;i--)this.words[i+s]=this.words[i];for(i=0;i=0),h=hint?(hint-hint%26)/26:0;var r=bits%26,s=Math.min((bits-r)/26,this.length),mask=67108863^67108863>>>r<s)for(this.length-=s,i=0;i=0&&(0!==carry||i>=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&0!==carry&&(maskedWords.words[maskedWords.length++]=carry),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},BN.prototype.ishrn=function ishrn(bits,hint,extended){return assert(0===this.negative),this.iushrn(bits,hint,extended)},BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function testn(bit){assert("number"==typeof bit&&bit>=0);var r=bit%26,s=(bit-r)/26,q=1<=0);var r=bits%26,s=(bits-r)/26;if(assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!==r&&s++,this.length=Math.min(s,this.length),0!==r){var mask=67108863^67108863>>>r<=67108864;i++)this.words[i]-=67108864,i===this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=Math.max(this.length,i+1),this},BN.prototype.isubn=function isubn(num){if(assert("number"==typeof num),assert(num<67108864),num<0)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i>26)-(right/67108864|0),this.words[i+shift]=67108863&w}for(;i>26,this.words[i+shift]=67108863&w;if(0===carry)return this.strip();for(assert(-1===carry),carry=0,i=0;i>26,this.words[i]=67108863&w;return this.negative=1,this.strip()},BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=(this.length,num.length),a=this.clone(),b=num,bhi=0|b.words[b.length-1];0!==(shift=26-this._countBits(bhi))&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var q,m=a.length-b.length;if("mod"!==mode){(q=new BN(null)).length=m+1,q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=67108864*(0|a.words[b.length+j])+(0|a.words[b.length+j-1]);for(qj=Math.min(qj/bhi|0,67108863),a._ishlnsubmul(b,qj,j);0!==a.negative;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q.strip(),a.strip(),"div"!==mode&&0!==shift&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function divmod(num,mode,positive){return assert(!num.isZero()),this.isZero()?{div:new BN(0),mod:new BN(0)}:0!==this.negative&&0===num.negative?(res=this.neg().divmod(num,mode),"mod"!==mode&&(div=res.div.neg()),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.iadd(num)),{div,mod}):0===this.negative&&0!==num.negative?(res=this.divmod(num.neg(),mode),"mod"!==mode&&(div=res.div.neg()),{div,mod:res.mod}):0!=(this.negative&num.negative)?(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod}):num.length>this.length||this.cmp(num)<0?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modn(num.words[0]))}:this._wordDiv(num,mode);var div,mod,res},BN.prototype.div=function div(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function mod(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function umod(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0!==dm.div.negative?dm.mod.isub(num):dm.mod,half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return cmp<0||1===r2&&0===cmp?dm.div:0!==dm.div.negative?dm.div.isubn(1):dm.div.iaddn(1)},BN.prototype.modn=function modn(num){assert(num<=67108863);for(var p=(1<<26)%num,acc=0,i=this.length-1;i>=0;i--)acc=(p*acc+(0|this.words[i]))%num;return acc},BN.prototype.idivn=function idivn(num){assert(num<=67108863);for(var carry=0,i=this.length-1;i>=0;i--){var w=(0|this.words[i])+67108864*carry;this.words[i]=w/num|0,carry=w%num}return this.strip()},BN.prototype.divn=function divn(num){return this.clone().idivn(num)},BN.prototype.egcd=function egcd(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0!==x.negative?x.umod(p):x.clone();for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0==(x.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(x.iushrn(i);i-- >0;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;0==(y.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(y.iushrn(j);j-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);x.cmp(y)>=0?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function _invmp(p){assert(0===p.negative),assert(!p.isZero());var a=this,b=p.clone();a=0!==a.negative?a.umod(p):a.clone();for(var res,x1=new BN(1),x2=new BN(0),delta=b.clone();a.cmpn(1)>0&&b.cmpn(1)>0;){for(var i=0,im=1;0==(a.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(a.iushrn(i);i-- >0;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;0==(b.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(b.iushrn(j);j-- >0;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);a.cmp(b)>=0?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}return(res=0===a.cmpn(1)?x1:x2).cmpn(0)<0&&res.iadd(p),res},BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);for(;;){for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(r<0){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}return b.iushln(shift)},BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function isEven(){return 0==(1&this.words[0])},BN.prototype.isOdd=function isOdd(){return 1==(1&this.words[0])},BN.prototype.andln=function andln(num){return this.words[0]&num},BN.prototype.bincn=function bincn(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<>>26,w&=67108863,this.words[i]=w}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function isZero(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function cmpn(num){var res,negative=num<0;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;if(this.strip(),this.length>1)res=1;else{negative&&(num=-num),assert(num<=67108863,"Number is too big");var w=0|this.words[0];res=w===num?0:wnum.length)return 1;if(this.length=0;i--){var a=0|this.words[i],b=0|num.words[i];if(a!==b){ab&&(res=1);break}}return res},BN.prototype.gtn=function gtn(num){return 1===this.cmpn(num)},BN.prototype.gt=function gt(num){return 1===this.cmp(num)},BN.prototype.gten=function gten(num){return this.cmpn(num)>=0},BN.prototype.gte=function gte(num){return this.cmp(num)>=0},BN.prototype.ltn=function ltn(num){return-1===this.cmpn(num)},BN.prototype.lt=function lt(num){return-1===this.cmp(num)},BN.prototype.lten=function lten(num){return this.cmpn(num)<=0},BN.prototype.lte=function lte(num){return this.cmp(num)<=0},BN.prototype.eqn=function eqn(num){return 0===this.cmpn(num)},BN.prototype.eq=function eq(num){return 0===this.cmp(num)},BN.red=function red(num){return new Red(num)},BN.prototype.toRed=function toRed(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function fromRed(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function _forceRed(ctx){return this.red=ctx,this},BN.prototype.forceRed=function forceRed(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function redAdd(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function redIAdd(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function redSub(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function redISub(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function redShl(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function redMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function redIMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function redSqr(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function redISqr(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function redSqrt(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function redInvm(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function redNeg(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function redPow(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);return tmp.words=new Array(Math.ceil(this.n/13)),tmp},MPrime.prototype.ireduce=function ireduce(num){var rlen,r=num;do{this.split(r,this.tmp),rlen=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(rlen>this.n);var cmp=rlen0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)},inherits(K256,MPrime),K256.prototype.split=function split(input,output){for(var outLen=Math.min(input.length,9),i=0;i>>22,prev=next}prev>>>=22,input.words[i-10]=prev,0===prev&&input.length>10?input.length-=10:input.length-=9},K256.prototype.imulK=function imulK(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0;i>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else{if("p25519"!==name)throw new Error("Unknown prime "+name);prime=new P25519}return primes[name]=prime,prime},Red.prototype._verify1=function _verify1(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function _verify2(a,b){assert(0==(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function imod(a){return this.prime?this.prime.ireduce(a)._forceRed(this):a.umod(this.m)._forceRed(this)},Red.prototype.neg=function neg(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);return res.cmp(this.m)>=0&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);return res.cmp(this.m)>=0&&res.isub(this.m),res},Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);return res.cmpn(0)<0&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);return res.cmpn(0)<0&&res.iadd(this.m),res},Red.prototype.shl=function shl(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function imul(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function mul(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())},Red.prototype.sqr=function sqr(a){return this.mul(a,a)},Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(mod3%2==1),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i=0;i--){for(var word=num.words[i],j=start-1;j>=0;j--){var bit=word>>j&1;res!==wnd[0]&&(res=this.sqr(res)),0!==bit||0!==current?(current<<=1,current|=bit,(4===++currentLen||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)):currentLen=0}start=26}return res},Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();return res.red=null,res},BN.mont=function mont(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function invm(a){return this.imod(a._invmp(this.m).mul(this.r2))._forceRed(this)}}(module=__webpack_require__.nmd(module),this)},8091:module=>{"use strict";function assign(target,firstSource){if(null==target)throw new TypeError("Cannot convert first argument to object");for(var to=Object(target),i=1;i{"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{BaseContract:()=>BaseContract,BigNumber:()=>BigNumber,Contract:()=>Contract,ContractFactory:()=>ContractFactory,FixedNumber:()=>FixedNumber,Signer:()=>Signer,VoidSigner:()=>VoidSigner,Wallet:()=>Wallet,Wordlist:()=>Wordlist,constants:()=>constants_lib_esm_namespaceObject,errors:()=>ErrorCode,ethers:()=>ethers_namespaceObject,getDefaultProvider:()=>getDefaultProvider,logger:()=>ethers_logger,providers:()=>providers_lib_esm_namespaceObject,utils:()=>lib_esm_utils_namespaceObject,version:()=>ethers_lib_esm_version_version,wordlists:()=>wordlists});var rlp_lib_esm_namespaceObject={};__webpack_require__.r(rlp_lib_esm_namespaceObject),__webpack_require__.d(rlp_lib_esm_namespaceObject,{decode:()=>decode,encode:()=>encode});var constants_lib_esm_namespaceObject={};__webpack_require__.r(constants_lib_esm_namespaceObject),__webpack_require__.d(constants_lib_esm_namespaceObject,{AddressZero:()=>AddressZero,EtherSymbol:()=>EtherSymbol,HashZero:()=>HashZero,MaxInt256:()=>MaxInt256,MaxUint256:()=>MaxUint256,MinInt256:()=>MinInt256,NegativeOne:()=>NegativeOne,One:()=>One,Two:()=>Two,WeiPerEther:()=>WeiPerEther,Zero:()=>Zero});var providers_lib_esm_namespaceObject={};__webpack_require__.r(providers_lib_esm_namespaceObject),__webpack_require__.d(providers_lib_esm_namespaceObject,{AlchemyProvider:()=>AlchemyProvider,AlchemyWebSocketProvider:()=>AlchemyWebSocketProvider,AnkrProvider:()=>AnkrProvider,BaseProvider:()=>BaseProvider,CloudflareProvider:()=>CloudflareProvider,EtherscanProvider:()=>EtherscanProvider,FallbackProvider:()=>FallbackProvider,Formatter:()=>Formatter,InfuraProvider:()=>InfuraProvider,InfuraWebSocketProvider:()=>InfuraWebSocketProvider,IpcProvider:()=>IpcProvider,JsonRpcBatchProvider:()=>JsonRpcBatchProvider,JsonRpcProvider:()=>JsonRpcProvider,JsonRpcSigner:()=>JsonRpcSigner,NodesmithProvider:()=>NodesmithProvider,PocketProvider:()=>PocketProvider,Provider:()=>Provider,Resolver:()=>Resolver,StaticJsonRpcProvider:()=>StaticJsonRpcProvider,UrlJsonRpcProvider:()=>UrlJsonRpcProvider,Web3Provider:()=>Web3Provider,WebSocketProvider:()=>WebSocketProvider,getDefaultProvider:()=>getDefaultProvider,getNetwork:()=>getNetwork,isCommunityResourcable:()=>isCommunityResourcable,isCommunityResource:()=>isCommunityResource,showThrottleMessage:()=>showThrottleMessage});var base64_lib_esm_namespaceObject={};__webpack_require__.r(base64_lib_esm_namespaceObject),__webpack_require__.d(base64_lib_esm_namespaceObject,{decode:()=>base64_decode,encode:()=>base64_encode});var lib_esm_utils_namespaceObject={};__webpack_require__.r(lib_esm_utils_namespaceObject),__webpack_require__.d(lib_esm_utils_namespaceObject,{AbiCoder:()=>AbiCoder,ConstructorFragment:()=>ConstructorFragment,ErrorFragment:()=>ErrorFragment,EventFragment:()=>EventFragment,FormatTypes:()=>FormatTypes,Fragment:()=>Fragment,FunctionFragment:()=>FunctionFragment,HDNode:()=>HDNode,Indexed:()=>Indexed,Interface:()=>Interface,LogDescription:()=>LogDescription,Logger:()=>Logger,ParamType:()=>ParamType,RLP:()=>rlp_lib_esm_namespaceObject,SigningKey:()=>SigningKey,SupportedAlgorithm:()=>SupportedAlgorithm,TransactionDescription:()=>TransactionDescription,TransactionTypes:()=>TransactionTypes,UnicodeNormalizationForm:()=>UnicodeNormalizationForm,Utf8ErrorFuncs:()=>Utf8ErrorFuncs,Utf8ErrorReason:()=>Utf8ErrorReason,_TypedDataEncoder:()=>TypedDataEncoder,_fetchData:()=>_fetchData,_toEscapedUtf8String:()=>_toEscapedUtf8String,accessListify:()=>accessListify,arrayify:()=>arrayify,base58:()=>Base58,base64:()=>base64_lib_esm_namespaceObject,checkProperties:()=>checkProperties,checkResultErrors:()=>checkResultErrors,commify:()=>commify,computeAddress:()=>computeAddress,computeHmac:()=>computeHmac,computePublicKey:()=>computePublicKey,concat:()=>concat,deepCopy:()=>deepCopy,defaultAbiCoder:()=>defaultAbiCoder,defaultPath:()=>defaultPath,defineReadOnly:()=>defineReadOnly,dnsEncode:()=>dnsEncode,entropyToMnemonic:()=>entropyToMnemonic,fetchJson:()=>fetchJson,formatBytes32String:()=>formatBytes32String,formatEther:()=>formatEther,formatUnits:()=>formatUnits,getAccountPath:()=>getAccountPath,getAddress:()=>getAddress,getContractAddress:()=>getContractAddress,getCreate2Address:()=>getCreate2Address,getIcapAddress:()=>getIcapAddress,getJsonWalletAddress:()=>getJsonWalletAddress,getStatic:()=>getStatic,hashMessage:()=>hashMessage,hexConcat:()=>hexConcat,hexDataLength:()=>hexDataLength,hexDataSlice:()=>hexDataSlice,hexStripZeros:()=>hexStripZeros,hexValue:()=>hexValue,hexZeroPad:()=>hexZeroPad,hexlify:()=>hexlify,id:()=>id,isAddress:()=>isAddress,isBytes:()=>isBytes,isBytesLike:()=>isBytesLike,isHexString:()=>lib_esm_isHexString,isValidMnemonic:()=>isValidMnemonic,isValidName:()=>isValidName,joinSignature:()=>joinSignature,keccak256:()=>keccak256,mnemonicToEntropy:()=>mnemonicToEntropy,mnemonicToSeed:()=>mnemonicToSeed,namehash:()=>namehash,nameprep:()=>nameprep,parseBytes32String:()=>parseBytes32String,parseEther:()=>parseEther,parseTransaction:()=>parse,parseUnits:()=>parseUnits,poll:()=>poll,randomBytes:()=>randomBytes,recoverAddress:()=>recoverAddress,recoverPublicKey:()=>recoverPublicKey,resolveProperties:()=>resolveProperties,ripemd160:()=>ripemd160,serializeTransaction:()=>serialize,sha256:()=>sha256,sha512:()=>sha512,shallowCopy:()=>shallowCopy,shuffled:()=>shuffled,solidityKeccak256:()=>lib_esm_keccak256,solidityPack:()=>lib_esm_pack,soliditySha256:()=>lib_esm_sha256,splitSignature:()=>splitSignature,stripZeros:()=>stripZeros,toUtf8Bytes:()=>toUtf8Bytes,toUtf8CodePoints:()=>toUtf8CodePoints,toUtf8String:()=>utf8_toUtf8String,verifyMessage:()=>verifyMessage,verifyTypedData:()=>verifyTypedData,zeroPad:()=>zeroPad});var ethers_namespaceObject={};__webpack_require__.r(ethers_namespaceObject),__webpack_require__.d(ethers_namespaceObject,{BaseContract:()=>BaseContract,BigNumber:()=>BigNumber,Contract:()=>Contract,ContractFactory:()=>ContractFactory,FixedNumber:()=>FixedNumber,Signer:()=>Signer,VoidSigner:()=>VoidSigner,Wallet:()=>Wallet,Wordlist:()=>Wordlist,constants:()=>constants_lib_esm_namespaceObject,errors:()=>ErrorCode,getDefaultProvider:()=>getDefaultProvider,logger:()=>ethers_logger,providers:()=>providers_lib_esm_namespaceObject,utils:()=>lib_esm_utils_namespaceObject,version:()=>ethers_lib_esm_version_version,wordlists:()=>wordlists});let _permanentCensorErrors=!1,_censorErrors=!1;const LogLevels={debug:1,default:2,info:2,warning:3,error:4,off:5};let _logLevel=LogLevels.default,_globalLogger=null;const _normalizeError=function _checkNormalize(){try{const missing=[];if(["NFD","NFC","NFKD","NFKC"].forEach((form=>{try{if("test"!=="test".normalize(form))throw new Error("bad normalize")}catch(error){missing.push(form)}})),missing.length)throw new Error("missing "+missing.join(", "));if(String.fromCharCode(233).normalize("NFD")!==String.fromCharCode(101,769))throw new Error("broken implementation")}catch(error){return error.message}return null}();var LogLevel,ErrorCode;!function(LogLevel){LogLevel.DEBUG="DEBUG",LogLevel.INFO="INFO",LogLevel.WARNING="WARNING",LogLevel.ERROR="ERROR",LogLevel.OFF="OFF"}(LogLevel||(LogLevel={})),function(ErrorCode){ErrorCode.UNKNOWN_ERROR="UNKNOWN_ERROR",ErrorCode.NOT_IMPLEMENTED="NOT_IMPLEMENTED",ErrorCode.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",ErrorCode.NETWORK_ERROR="NETWORK_ERROR",ErrorCode.SERVER_ERROR="SERVER_ERROR",ErrorCode.TIMEOUT="TIMEOUT",ErrorCode.BUFFER_OVERRUN="BUFFER_OVERRUN",ErrorCode.NUMERIC_FAULT="NUMERIC_FAULT",ErrorCode.MISSING_NEW="MISSING_NEW",ErrorCode.INVALID_ARGUMENT="INVALID_ARGUMENT",ErrorCode.MISSING_ARGUMENT="MISSING_ARGUMENT",ErrorCode.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",ErrorCode.CALL_EXCEPTION="CALL_EXCEPTION",ErrorCode.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",ErrorCode.NONCE_EXPIRED="NONCE_EXPIRED",ErrorCode.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",ErrorCode.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",ErrorCode.TRANSACTION_REPLACED="TRANSACTION_REPLACED",ErrorCode.ACTION_REJECTED="ACTION_REJECTED"}(ErrorCode||(ErrorCode={}));const HEX="0123456789abcdef";class Logger{constructor(version){Object.defineProperty(this,"version",{enumerable:!0,value:version,writable:!1})}_log(logLevel,args){const level=logLevel.toLowerCase();null==LogLevels[level]&&this.throwArgumentError("invalid log level name","logLevel",logLevel),_logLevel>LogLevels[level]||console.log.apply(console,args)}debug(...args){this._log(Logger.levels.DEBUG,args)}info(...args){this._log(Logger.levels.INFO,args)}warn(...args){this._log(Logger.levels.WARNING,args)}makeError(message,code,params){if(_censorErrors)return this.makeError("censored error",code,{});code||(code=Logger.errors.UNKNOWN_ERROR),params||(params={});const messageDetails=[];Object.keys(params).forEach((key=>{const value=params[key];try{if(value instanceof Uint8Array){let hex="";for(let i=0;i>4],hex+=HEX[15&value[i]];messageDetails.push(key+"=Uint8Array(0x"+hex+")")}else messageDetails.push(key+"="+JSON.stringify(value))}catch(error){messageDetails.push(key+"="+JSON.stringify(params[key].toString()))}})),messageDetails.push(`code=${code}`),messageDetails.push(`version=${this.version}`);const reason=message;let url="";switch(code){case ErrorCode.NUMERIC_FAULT:{url="NUMERIC_FAULT";const fault=message;switch(fault){case"overflow":case"underflow":case"division-by-zero":url+="-"+fault;break;case"negative-power":case"negative-width":url+="-unsupported";break;case"unbound-bitwise-result":url+="-unbound-result"}break}case ErrorCode.CALL_EXCEPTION:case ErrorCode.INSUFFICIENT_FUNDS:case ErrorCode.MISSING_NEW:case ErrorCode.NONCE_EXPIRED:case ErrorCode.REPLACEMENT_UNDERPRICED:case ErrorCode.TRANSACTION_REPLACED:case ErrorCode.UNPREDICTABLE_GAS_LIMIT:url=code}url&&(message+=" [ See: https://links.ethers.org/v5-errors-"+url+" ]"),messageDetails.length&&(message+=" ("+messageDetails.join(", ")+")");const error=new Error(message);return error.reason=reason,error.code=code,Object.keys(params).forEach((function(key){error[key]=params[key]})),error}throwError(message,code,params){throw this.makeError(message,code,params)}throwArgumentError(message,name,value){return this.throwError(message,Logger.errors.INVALID_ARGUMENT,{argument:name,value})}assert(condition,message,code,params){condition||this.throwError(message,code,params)}assertArgument(condition,message,name,value){condition||this.throwArgumentError(message,name,value)}checkNormalize(message){null==message&&(message="platform missing String.prototype.normalize"),_normalizeError&&this.throwError("platform missing String.prototype.normalize",Logger.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:_normalizeError})}checkSafeUint53(value,message){"number"==typeof value&&(null==message&&(message="value not safe"),(value<0||value>=9007199254740991)&&this.throwError(message,Logger.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value}),value%1&&this.throwError(message,Logger.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value}))}checkArgumentCount(count,expectedCount,message){message=message?": "+message:"",countexpectedCount&&this.throwError("too many arguments"+message,Logger.errors.UNEXPECTED_ARGUMENT,{count,expectedCount})}checkNew(target,kind){target!==Object&&null!=target||this.throwError("missing new",Logger.errors.MISSING_NEW,{name:kind.name})}checkAbstract(target,kind){target===kind?this.throwError("cannot instantiate abstract class "+JSON.stringify(kind.name)+" directly; use a sub-class",Logger.errors.UNSUPPORTED_OPERATION,{name:target.name,operation:"new"}):target!==Object&&null!=target||this.throwError("missing new",Logger.errors.MISSING_NEW,{name:kind.name})}static globalLogger(){return _globalLogger||(_globalLogger=new Logger("logger/5.7.0")),_globalLogger}static setCensorship(censorship,permanent){if(!censorship&&permanent&&this.globalLogger().throwError("cannot permanently disable censorship",Logger.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),_permanentCensorErrors){if(!censorship)return;this.globalLogger().throwError("error censorship permanent",Logger.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}_censorErrors=!!censorship,_permanentCensorErrors=!!permanent}static setLogLevel(logLevel){const level=LogLevels[logLevel.toLowerCase()];null!=level?_logLevel=level:Logger.globalLogger().warn("invalid log level - "+logLevel)}static from(version){return new Logger(version)}}Logger.errors=ErrorCode,Logger.levels=LogLevel;const logger=new Logger("bytes/5.7.0");function isHexable(value){return!!value.toHexString}function addSlice(array){return array.slice||(array.slice=function(){const args=Array.prototype.slice.call(arguments);return addSlice(new Uint8Array(Array.prototype.slice.apply(array,args)))}),array}function isBytesLike(value){return lib_esm_isHexString(value)&&!(value.length%2)||isBytes(value)}function isInteger(value){return"number"==typeof value&&value==value&&value%1==0}function isBytes(value){if(null==value)return!1;if(value.constructor===Uint8Array)return!0;if("string"==typeof value)return!1;if(!isInteger(value.length)||value.length<0)return!1;for(let i=0;i=256)return!1}return!0}function arrayify(value,options){if(options||(options={}),"number"==typeof value){logger.checkSafeUint53(value,"invalid arrayify value");const result=[];for(;value;)result.unshift(255&value),value=parseInt(String(value/256));return 0===result.length&&result.push(0),addSlice(new Uint8Array(result))}if(options.allowMissingPrefix&&"string"==typeof value&&"0x"!==value.substring(0,2)&&(value="0x"+value),isHexable(value)&&(value=value.toHexString()),lib_esm_isHexString(value)){let hex=value.substring(2);hex.length%2&&("left"===options.hexPad?hex="0"+hex:"right"===options.hexPad?hex+="0":logger.throwArgumentError("hex data is odd-length","value",value));const result=[];for(let i=0;iarrayify(item))),length=objects.reduce(((accum,item)=>accum+item.length),0),result=new Uint8Array(length);return objects.reduce(((offset,object)=>(result.set(object,offset),offset+object.length)),0),addSlice(result)}function stripZeros(value){let result=arrayify(value);if(0===result.length)return result;let start=0;for(;startlength&&logger.throwArgumentError("value out of range","value",arguments[0]);const result=new Uint8Array(length);return result.set(value,length-value.length),addSlice(result)}function lib_esm_isHexString(value,length){return!("string"!=typeof value||!value.match(/^0x[0-9A-Fa-f]*$/))&&(!length||value.length===2+2*length)}function hexlify(value,options){if(options||(options={}),"number"==typeof value){logger.checkSafeUint53(value,"invalid hexlify value");let hex="";for(;value;)hex="0123456789abcdef"[15&value]+hex,value=Math.floor(value/16);return hex.length?(hex.length%2&&(hex="0"+hex),"0x"+hex):"0x00"}if("bigint"==typeof value)return(value=value.toString(16)).length%2?"0x0"+value:"0x"+value;if(options.allowMissingPrefix&&"string"==typeof value&&"0x"!==value.substring(0,2)&&(value="0x"+value),isHexable(value))return value.toHexString();if(lib_esm_isHexString(value))return value.length%2&&("left"===options.hexPad?value="0x0"+value.substring(2):"right"===options.hexPad?value+="0":logger.throwArgumentError("hex data is odd-length","value",value)),value.toLowerCase();if(isBytes(value)){let result="0x";for(let i=0;i>4]+"0123456789abcdef"[15&v]}return result}return logger.throwArgumentError("invalid hexlify value","value",value)}function hexDataLength(data){if("string"!=typeof data)data=hexlify(data);else if(!lib_esm_isHexString(data)||data.length%2)return null;return(data.length-2)/2}function hexDataSlice(data,offset,endOffset){return"string"!=typeof data?data=hexlify(data):(!lib_esm_isHexString(data)||data.length%2)&&logger.throwArgumentError("invalid hexData","value",data),offset=2+2*offset,null!=endOffset?"0x"+data.substring(offset,2+2*endOffset):"0x"+data.substring(offset)}function hexConcat(items){let result="0x";return items.forEach((item=>{result+=hexlify(item).substring(2)})),result}function hexValue(value){const trimmed=hexStripZeros(hexlify(value,{hexPad:"left"}));return"0x"===trimmed?"0x0":trimmed}function hexStripZeros(value){"string"!=typeof value&&(value=hexlify(value)),lib_esm_isHexString(value)||logger.throwArgumentError("invalid hex string","value",value),value=value.substring(2);let offset=0;for(;offset2*length+2&&logger.throwArgumentError("value out of range","value",arguments[1]);value.length<2*length+2;)value="0x0"+value.substring(2);return value}function splitSignature(signature){const result={r:"0x",s:"0x",_vs:"0x",recoveryParam:0,v:0,yParityAndS:"0x",compact:"0x"};if(isBytesLike(signature)){let bytes=arrayify(signature);64===bytes.length?(result.v=27+(bytes[32]>>7),bytes[32]&=127,result.r=hexlify(bytes.slice(0,32)),result.s=hexlify(bytes.slice(32,64))):65===bytes.length?(result.r=hexlify(bytes.slice(0,32)),result.s=hexlify(bytes.slice(32,64)),result.v=bytes[64]):logger.throwArgumentError("invalid signature string","signature",signature),result.v<27&&(0===result.v||1===result.v?result.v+=27:logger.throwArgumentError("signature invalid v byte","signature",signature)),result.recoveryParam=1-result.v%2,result.recoveryParam&&(bytes[32]|=128),result._vs=hexlify(bytes.slice(32,64))}else{if(result.r=signature.r,result.s=signature.s,result.v=signature.v,result.recoveryParam=signature.recoveryParam,result._vs=signature._vs,null!=result._vs){const vs=zeroPad(arrayify(result._vs),32);result._vs=hexlify(vs);const recoveryParam=vs[0]>=128?1:0;null==result.recoveryParam?result.recoveryParam=recoveryParam:result.recoveryParam!==recoveryParam&&logger.throwArgumentError("signature recoveryParam mismatch _vs","signature",signature),vs[0]&=127;const s=hexlify(vs);null==result.s?result.s=s:result.s!==s&&logger.throwArgumentError("signature v mismatch _vs","signature",signature)}if(null==result.recoveryParam)null==result.v?logger.throwArgumentError("signature missing v and recoveryParam","signature",signature):0===result.v||1===result.v?result.recoveryParam=result.v:result.recoveryParam=1-result.v%2;else if(null==result.v)result.v=27+result.recoveryParam;else{const recId=0===result.v||1===result.v?result.v:1-result.v%2;result.recoveryParam!==recId&&logger.throwArgumentError("signature recoveryParam mismatch v","signature",signature)}null!=result.r&&lib_esm_isHexString(result.r)?result.r=hexZeroPad(result.r,32):logger.throwArgumentError("signature missing or invalid r","signature",signature),null!=result.s&&lib_esm_isHexString(result.s)?result.s=hexZeroPad(result.s,32):logger.throwArgumentError("signature missing or invalid s","signature",signature);const vs=arrayify(result.s);vs[0]>=128&&logger.throwArgumentError("signature s out of range","signature",signature),result.recoveryParam&&(vs[0]|=128);const _vs=hexlify(vs);result._vs&&(lib_esm_isHexString(result._vs)||logger.throwArgumentError("signature invalid _vs","signature",signature),result._vs=hexZeroPad(result._vs,32)),null==result._vs?result._vs=_vs:result._vs!==_vs&&logger.throwArgumentError("signature _vs mismatch v and s","signature",signature)}return result.yParityAndS=result._vs,result.compact=result.r+result.yParityAndS.substring(2),result}function joinSignature(signature){return hexlify(concat([(signature=splitSignature(signature)).r,signature.s,signature.recoveryParam?"0x1c":"0x1b"]))}var bn=__webpack_require__(3550),bn_default=__webpack_require__.n(bn);var BN=bn_default().BN;const bignumber_logger=new Logger("bignumber/5.7.0"),_constructorGuard={};let _warnedToStringRadix=!1;class BigNumber{constructor(constructorGuard,hex){constructorGuard!==_constructorGuard&&bignumber_logger.throwError("cannot call constructor directly; use BigNumber.from",Logger.errors.UNSUPPORTED_OPERATION,{operation:"new (BigNumber)"}),this._hex=hex,this._isBigNumber=!0,Object.freeze(this)}fromTwos(value){return toBigNumber(toBN(this).fromTwos(value))}toTwos(value){return toBigNumber(toBN(this).toTwos(value))}abs(){return"-"===this._hex[0]?BigNumber.from(this._hex.substring(1)):this}add(other){return toBigNumber(toBN(this).add(toBN(other)))}sub(other){return toBigNumber(toBN(this).sub(toBN(other)))}div(other){return BigNumber.from(other).isZero()&&throwFault("division-by-zero","div"),toBigNumber(toBN(this).div(toBN(other)))}mul(other){return toBigNumber(toBN(this).mul(toBN(other)))}mod(other){const value=toBN(other);return value.isNeg()&&throwFault("division-by-zero","mod"),toBigNumber(toBN(this).umod(value))}pow(other){const value=toBN(other);return value.isNeg()&&throwFault("negative-power","pow"),toBigNumber(toBN(this).pow(value))}and(other){const value=toBN(other);return(this.isNegative()||value.isNeg())&&throwFault("unbound-bitwise-result","and"),toBigNumber(toBN(this).and(value))}or(other){const value=toBN(other);return(this.isNegative()||value.isNeg())&&throwFault("unbound-bitwise-result","or"),toBigNumber(toBN(this).or(value))}xor(other){const value=toBN(other);return(this.isNegative()||value.isNeg())&&throwFault("unbound-bitwise-result","xor"),toBigNumber(toBN(this).xor(value))}mask(value){return(this.isNegative()||value<0)&&throwFault("negative-width","mask"),toBigNumber(toBN(this).maskn(value))}shl(value){return(this.isNegative()||value<0)&&throwFault("negative-width","shl"),toBigNumber(toBN(this).shln(value))}shr(value){return(this.isNegative()||value<0)&&throwFault("negative-width","shr"),toBigNumber(toBN(this).shrn(value))}eq(other){return toBN(this).eq(toBN(other))}lt(other){return toBN(this).lt(toBN(other))}lte(other){return toBN(this).lte(toBN(other))}gt(other){return toBN(this).gt(toBN(other))}gte(other){return toBN(this).gte(toBN(other))}isNegative(){return"-"===this._hex[0]}isZero(){return toBN(this).isZero()}toNumber(){try{return toBN(this).toNumber()}catch(error){throwFault("overflow","toNumber",this.toString())}return null}toBigInt(){try{return BigInt(this.toString())}catch(e){}return bignumber_logger.throwError("this platform does not support BigInt",Logger.errors.UNSUPPORTED_OPERATION,{value:this.toString()})}toString(){return arguments.length>0&&(10===arguments[0]?_warnedToStringRadix||(_warnedToStringRadix=!0,bignumber_logger.warn("BigNumber.toString does not accept any parameters; base-10 is assumed")):16===arguments[0]?bignumber_logger.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()",Logger.errors.UNEXPECTED_ARGUMENT,{}):bignumber_logger.throwError("BigNumber.toString does not accept parameters",Logger.errors.UNEXPECTED_ARGUMENT,{})),toBN(this).toString(10)}toHexString(){return this._hex}toJSON(key){return{type:"BigNumber",hex:this.toHexString()}}static from(value){if(value instanceof BigNumber)return value;if("string"==typeof value)return value.match(/^-?0x[0-9a-f]+$/i)?new BigNumber(_constructorGuard,toHex(value)):value.match(/^-?[0-9]+$/)?new BigNumber(_constructorGuard,toHex(new BN(value))):bignumber_logger.throwArgumentError("invalid BigNumber string","value",value);if("number"==typeof value)return value%1&&throwFault("underflow","BigNumber.from",value),(value>=9007199254740991||value<=-9007199254740991)&&throwFault("overflow","BigNumber.from",value),BigNumber.from(String(value));const anyValue=value;if("bigint"==typeof anyValue)return BigNumber.from(anyValue.toString());if(isBytes(anyValue))return BigNumber.from(hexlify(anyValue));if(anyValue)if(anyValue.toHexString){const hex=anyValue.toHexString();if("string"==typeof hex)return BigNumber.from(hex)}else{let hex=anyValue._hex;if(null==hex&&"BigNumber"===anyValue.type&&(hex=anyValue.hex),"string"==typeof hex&&(lib_esm_isHexString(hex)||"-"===hex[0]&&lib_esm_isHexString(hex.substring(1))))return BigNumber.from(hex)}return bignumber_logger.throwArgumentError("invalid BigNumber value","value",value)}static isBigNumber(value){return!(!value||!value._isBigNumber)}}function toHex(value){if("string"!=typeof value)return toHex(value.toString(16));if("-"===value[0])return"-"===(value=value.substring(1))[0]&&bignumber_logger.throwArgumentError("invalid hex","value",value),"0x00"===(value=toHex(value))?value:"-"+value;if("0x"!==value.substring(0,2)&&(value="0x"+value),"0x"===value)return"0x00";for(value.length%2&&(value="0x0"+value.substring(2));value.length>4&&"0x00"===value.substring(0,4);)value="0x"+value.substring(4);return value}function toBigNumber(value){return BigNumber.from(toHex(value))}function toBN(value){const hex=BigNumber.from(value).toHexString();return"-"===hex[0]?new BN("-"+hex.substring(3),16):new BN(hex.substring(2),16)}function throwFault(fault,operation,value){const params={fault,operation};return null!=value&&(params.value=value),bignumber_logger.throwError(fault,Logger.errors.NUMERIC_FAULT,params)}var __awaiter=function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};const lib_esm_logger=new Logger("properties/5.7.0");function defineReadOnly(object,name,value){Object.defineProperty(object,name,{enumerable:!0,value,writable:!1})}function getStatic(ctor,key){for(let i=0;i<32;i++){if(ctor[key])return ctor[key];if(!ctor.prototype||"object"!=typeof ctor.prototype)break;ctor=Object.getPrototypeOf(ctor.prototype).constructor}return null}function resolveProperties(object){return __awaiter(this,void 0,void 0,(function*(){const promises=Object.keys(object).map((key=>{const value=object[key];return Promise.resolve(value).then((v=>({key,value:v})))}));return(yield Promise.all(promises)).reduce(((accum,result)=>(accum[result.key]=result.value,accum)),{})}))}function checkProperties(object,properties){object&&"object"==typeof object||lib_esm_logger.throwArgumentError("invalid object","object",object),Object.keys(object).forEach((key=>{properties[key]||lib_esm_logger.throwArgumentError("invalid object key - "+key,"transaction:"+key,object)}))}function shallowCopy(object){const result={};for(const key in object)result[key]=object[key];return result}const opaque={bigint:!0,boolean:!0,function:!0,number:!0,string:!0};function _isFrozen(object){if(null==object||opaque[typeof object])return!0;if(Array.isArray(object)||"object"==typeof object){if(!Object.isFrozen(object))return!1;const keys=Object.keys(object);for(let i=0;ideepCopy(item))));if("object"==typeof object){const result={};for(const key in object){const value=object[key];void 0!==value&&defineReadOnly(result,key,deepCopy(value))}return result}return lib_esm_logger.throwArgumentError("Cannot deepCopy "+typeof object,"object",object)}function deepCopy(object){return _deepCopy(object)}class Description{constructor(info){for(const key in info)this[key]=deepCopy(info[key])}}const abstract_coder_logger=new Logger("abi/5.7.0");function checkResultErrors(result){const errors=[],checkErrors=function(path,object){if(Array.isArray(object))for(let key in object){const childPath=path.slice();childPath.push(key);try{checkErrors(childPath,object[key])}catch(error){errors.push({path:childPath,error})}}};return checkErrors([],result),errors}class Coder{constructor(name,type,localName,dynamic){this.name=name,this.type=type,this.localName=localName,this.dynamic=dynamic}_throwError(message,value){abstract_coder_logger.throwArgumentError(message,this.localName,value)}}class Writer{constructor(wordSize){defineReadOnly(this,"wordSize",wordSize||32),this._data=[],this._dataLength=0,this._padding=new Uint8Array(wordSize)}get data(){return hexConcat(this._data)}get length(){return this._dataLength}_writeData(data){return this._data.push(data),this._dataLength+=data.length,data.length}appendWriter(writer){return this._writeData(concat(writer._data))}writeBytes(value){let bytes=arrayify(value);const paddingOffset=bytes.length%this.wordSize;return paddingOffset&&(bytes=concat([bytes,this._padding.slice(paddingOffset)])),this._writeData(bytes)}_getValue(value){let bytes=arrayify(BigNumber.from(value));return bytes.length>this.wordSize&&abstract_coder_logger.throwError("value out-of-bounds",Logger.errors.BUFFER_OVERRUN,{length:this.wordSize,offset:bytes.length}),bytes.length%this.wordSize&&(bytes=concat([this._padding.slice(bytes.length%this.wordSize),bytes])),bytes}writeValue(value){return this._writeData(this._getValue(value))}writeUpdatableValue(){const offset=this._data.length;return this._data.push(this._padding),this._dataLength+=this.wordSize,value=>{this._data[offset]=this._getValue(value)}}}class Reader{constructor(data,wordSize,coerceFunc,allowLoose){defineReadOnly(this,"_data",arrayify(data)),defineReadOnly(this,"wordSize",wordSize||32),defineReadOnly(this,"_coerceFunc",coerceFunc),defineReadOnly(this,"allowLoose",allowLoose),this._offset=0}get data(){return hexlify(this._data)}get consumed(){return this._offset}static coerce(name,value){let match=name.match("^u?int([0-9]+)$");return match&&parseInt(match[1])<=48&&(value=value.toNumber()),value}coerce(name,value){return this._coerceFunc?this._coerceFunc(name,value):Reader.coerce(name,value)}_peekBytes(offset,length,loose){let alignedLength=Math.ceil(length/this.wordSize)*this.wordSize;return this._offset+alignedLength>this._data.length&&(this.allowLoose&&loose&&this._offset+length<=this._data.length?alignedLength=length:abstract_coder_logger.throwError("data out-of-bounds",Logger.errors.BUFFER_OVERRUN,{length:this._data.length,offset:this._offset+alignedLength})),this._data.slice(this._offset,this._offset+alignedLength)}subReader(offset){return new Reader(this._data.slice(this._offset+offset),this.wordSize,this._coerceFunc,this.allowLoose)}readBytes(length,loose){let bytes=this._peekBytes(0,length,!!loose);return this._offset+=bytes.length,bytes.slice(0,length)}readValue(){return BigNumber.from(this.readBytes(this.wordSize))}}var sha3=__webpack_require__(1094),sha3_default=__webpack_require__.n(sha3);function keccak256(data){return"0x"+sha3_default().keccak_256(arrayify(data))}const rlp_lib_esm_logger=new Logger("rlp/5.7.0");function arrayifyInteger(value){const result=[];for(;value;)result.unshift(255&value),value>>=8;return result}function unarrayifyInteger(data,offset,length){let result=0;for(let i=0;ioffset+1+length&&rlp_lib_esm_logger.throwError("child data too short",Logger.errors.BUFFER_OVERRUN,{})}return{consumed:1+length,result}}function _decode(data,offset){if(0===data.length&&rlp_lib_esm_logger.throwError("data too short",Logger.errors.BUFFER_OVERRUN,{}),data[offset]>=248){const lengthLength=data[offset]-247;offset+1+lengthLength>data.length&&rlp_lib_esm_logger.throwError("data short segment too short",Logger.errors.BUFFER_OVERRUN,{});const length=unarrayifyInteger(data,offset+1,lengthLength);return offset+1+lengthLength+length>data.length&&rlp_lib_esm_logger.throwError("data long segment too short",Logger.errors.BUFFER_OVERRUN,{}),_decodeChildren(data,offset,offset+1+lengthLength,lengthLength+length)}if(data[offset]>=192){const length=data[offset]-192;return offset+1+length>data.length&&rlp_lib_esm_logger.throwError("data array too short",Logger.errors.BUFFER_OVERRUN,{}),_decodeChildren(data,offset,offset+1,length)}if(data[offset]>=184){const lengthLength=data[offset]-183;offset+1+lengthLength>data.length&&rlp_lib_esm_logger.throwError("data array too short",Logger.errors.BUFFER_OVERRUN,{});const length=unarrayifyInteger(data,offset+1,lengthLength);offset+1+lengthLength+length>data.length&&rlp_lib_esm_logger.throwError("data array too short",Logger.errors.BUFFER_OVERRUN,{});return{consumed:1+lengthLength+length,result:hexlify(data.slice(offset+1+lengthLength,offset+1+lengthLength+length))}}if(data[offset]>=128){const length=data[offset]-128;offset+1+length>data.length&&rlp_lib_esm_logger.throwError("data too short",Logger.errors.BUFFER_OVERRUN,{});return{consumed:1+length,result:hexlify(data.slice(offset+1,offset+1+length))}}return{consumed:1,result:hexlify(data[offset])}}function decode(data){const bytes=arrayify(data),decoded=_decode(bytes,0);return decoded.consumed!==bytes.length&&rlp_lib_esm_logger.throwArgumentError("invalid rlp data","data",data),decoded.result}const address_lib_esm_logger=new Logger("address/5.7.0");function getChecksumAddress(address){lib_esm_isHexString(address,20)||address_lib_esm_logger.throwArgumentError("invalid address","address",address);const chars=(address=address.toLowerCase()).substring(2).split(""),expanded=new Uint8Array(40);for(let i=0;i<40;i++)expanded[i]=chars[i].charCodeAt(0);const hashed=arrayify(keccak256(expanded));for(let i=0;i<40;i+=2)hashed[i>>1]>>4>=8&&(chars[i]=chars[i].toUpperCase()),(15&hashed[i>>1])>=8&&(chars[i+1]=chars[i+1].toUpperCase());return"0x"+chars.join("")}const ibanLookup={};for(let i=0;i<10;i++)ibanLookup[String(i)]=String(i);for(let i=0;i<26;i++)ibanLookup[String.fromCharCode(65+i)]=String(10+i);const safeDigits=Math.floor(function log10(x){return Math.log10?Math.log10(x):Math.log(x)/Math.LN10}(9007199254740991));function ibanChecksum(address){let expanded=(address=(address=address.toUpperCase()).substring(4)+address.substring(0,2)+"00").split("").map((c=>ibanLookup[c])).join("");for(;expanded.length>=safeDigits;){let block=expanded.substring(0,safeDigits);expanded=parseInt(block,10)%97+expanded.substring(block.length)}let checksum=String(98-parseInt(expanded,10)%97);for(;checksum.length<2;)checksum="0"+checksum;return checksum}function getAddress(address){let result=null;if("string"!=typeof address&&address_lib_esm_logger.throwArgumentError("invalid address","address",address),address.match(/^(0x)?[0-9a-fA-F]{40}$/))"0x"!==address.substring(0,2)&&(address="0x"+address),result=getChecksumAddress(address),address.match(/([A-F].*[a-f])|([a-f].*[A-F])/)&&result!==address&&address_lib_esm_logger.throwArgumentError("bad address checksum","address",address);else if(address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){for(address.substring(2,4)!==ibanChecksum(address)&&address_lib_esm_logger.throwArgumentError("bad icap checksum","address",address),result=function _base36To16(value){return new BN(value,36).toString(16)}(address.substring(4));result.length<40;)result="0"+result;result=getChecksumAddress("0x"+result)}else address_lib_esm_logger.throwArgumentError("invalid address","address",address);return result}function isAddress(address){try{return getAddress(address),!0}catch(error){}return!1}function getIcapAddress(address){let base36=function _base16To36(value){return new BN(value,16).toString(36)}(getAddress(address).substring(2)).toUpperCase();for(;base36.length<30;)base36="0"+base36;return"XE"+ibanChecksum("XE00"+base36)+base36}function getContractAddress(transaction){let from=null;try{from=getAddress(transaction.from)}catch(error){address_lib_esm_logger.throwArgumentError("missing from address","transaction",transaction)}return getAddress(hexDataSlice(keccak256(encode([from,stripZeros(arrayify(BigNumber.from(transaction.nonce).toHexString()))])),12))}function getCreate2Address(from,salt,initCodeHash){return 32!==hexDataLength(salt)&&address_lib_esm_logger.throwArgumentError("salt must be 32 bytes","salt",salt),32!==hexDataLength(initCodeHash)&&address_lib_esm_logger.throwArgumentError("initCodeHash must be 32 bytes","initCodeHash",initCodeHash),getAddress(hexDataSlice(keccak256(concat(["0xff",getAddress(from),salt,initCodeHash])),12))}const utf8_logger=new Logger("strings/5.7.0");var UnicodeNormalizationForm,Utf8ErrorReason;function ignoreFunc(reason,offset,bytes,output,badCodepoint){if(reason===Utf8ErrorReason.BAD_PREFIX||reason===Utf8ErrorReason.UNEXPECTED_CONTINUE){let i=0;for(let o=offset+1;o>6==2;o++)i++;return i}return reason===Utf8ErrorReason.OVERRUN?bytes.length-offset-1:0}!function(UnicodeNormalizationForm){UnicodeNormalizationForm.current="",UnicodeNormalizationForm.NFC="NFC",UnicodeNormalizationForm.NFD="NFD",UnicodeNormalizationForm.NFKC="NFKC",UnicodeNormalizationForm.NFKD="NFKD"}(UnicodeNormalizationForm||(UnicodeNormalizationForm={})),function(Utf8ErrorReason){Utf8ErrorReason.UNEXPECTED_CONTINUE="unexpected continuation byte",Utf8ErrorReason.BAD_PREFIX="bad codepoint prefix",Utf8ErrorReason.OVERRUN="string overrun",Utf8ErrorReason.MISSING_CONTINUE="missing continuation byte",Utf8ErrorReason.OUT_OF_RANGE="out of UTF-8 range",Utf8ErrorReason.UTF16_SURROGATE="UTF-16 surrogate",Utf8ErrorReason.OVERLONG="overlong representation"}(Utf8ErrorReason||(Utf8ErrorReason={}));const Utf8ErrorFuncs=Object.freeze({error:function errorFunc(reason,offset,bytes,output,badCodepoint){return utf8_logger.throwArgumentError(`invalid codepoint at offset ${offset}; ${reason}`,"bytes",bytes)},ignore:ignoreFunc,replace:function replaceFunc(reason,offset,bytes,output,badCodepoint){return reason===Utf8ErrorReason.OVERLONG?(output.push(badCodepoint),0):(output.push(65533),ignoreFunc(reason,offset,bytes))}});function getUtf8CodePoints(bytes,onError){null==onError&&(onError=Utf8ErrorFuncs.error),bytes=arrayify(bytes);const result=[];let i=0;for(;i>7==0){result.push(c);continue}let extraLength=null,overlongMask=null;if(192==(224&c))extraLength=1,overlongMask=127;else if(224==(240&c))extraLength=2,overlongMask=2047;else{if(240!=(248&c)){i+=onError(128==(192&c)?Utf8ErrorReason.UNEXPECTED_CONTINUE:Utf8ErrorReason.BAD_PREFIX,i-1,bytes,result);continue}extraLength=3,overlongMask=65535}if(i-1+extraLength>=bytes.length){i+=onError(Utf8ErrorReason.OVERRUN,i-1,bytes,result);continue}let res=c&(1<<8-extraLength-1)-1;for(let j=0;j1114111?i+=onError(Utf8ErrorReason.OUT_OF_RANGE,i-1-extraLength,bytes,result,res):res>=55296&&res<=57343?i+=onError(Utf8ErrorReason.UTF16_SURROGATE,i-1-extraLength,bytes,result,res):res<=overlongMask?i+=onError(Utf8ErrorReason.OVERLONG,i-1-extraLength,bytes,result,res):result.push(res))}return result}function toUtf8Bytes(str,form=UnicodeNormalizationForm.current){form!=UnicodeNormalizationForm.current&&(utf8_logger.checkNormalize(),str=str.normalize(form));let result=[];for(let i=0;i>6|192),result.push(63&c|128);else if(55296==(64512&c)){i++;const c2=str.charCodeAt(i);if(i>=str.length||56320!=(64512&c2))throw new Error("invalid utf-8 string");const pair=65536+((1023&c)<<10)+(1023&c2);result.push(pair>>18|240),result.push(pair>>12&63|128),result.push(pair>>6&63|128),result.push(63&pair|128)}else result.push(c>>12|224),result.push(c>>6&63|128),result.push(63&c|128)}return arrayify(result)}function escapeChar(value){const hex="0000"+value.toString(16);return"\\u"+hex.substring(hex.length-4)}function _toEscapedUtf8String(bytes,onError){return'"'+getUtf8CodePoints(bytes,onError).map((codePoint=>{if(codePoint<256){switch(codePoint){case 8:return"\\b";case 9:return"\\t";case 10:return"\\n";case 13:return"\\r";case 34:return'\\"';case 92:return"\\\\"}if(codePoint>=32&&codePoint<127)return String.fromCharCode(codePoint)}return codePoint<=65535?escapeChar(codePoint):escapeChar(55296+((codePoint-=65536)>>10&1023))+escapeChar(56320+(1023&codePoint))})).join("")+'"'}function _toUtf8String(codePoints){return codePoints.map((codePoint=>codePoint<=65535?String.fromCharCode(codePoint):(codePoint-=65536,String.fromCharCode(55296+(codePoint>>10&1023),56320+(1023&codePoint))))).join("")}function utf8_toUtf8String(bytes,onError){return _toUtf8String(getUtf8CodePoints(bytes,onError))}function toUtf8CodePoints(str,form=UnicodeNormalizationForm.current){return getUtf8CodePoints(toUtf8Bytes(str,form))}function id(text){return keccak256(toUtf8Bytes(text))}class AddressCoder extends Coder{constructor(localName){super("address","address",localName,!1)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(writer,value){try{value=getAddress(value)}catch(error){this._throwError(error.message,value)}return writer.writeValue(value)}decode(reader){return getAddress(hexZeroPad(reader.readValue().toHexString(),20))}}class AnonymousCoder extends Coder{constructor(coder){super(coder.name,coder.type,void 0,coder.dynamic),this.coder=coder}defaultValue(){return this.coder.defaultValue()}encode(writer,value){return this.coder.encode(writer,value)}decode(reader){return this.coder.decode(reader)}}const array_logger=new Logger("abi/5.7.0");function pack(writer,coders,values){let arrayValues=null;if(Array.isArray(values))arrayValues=values;else if(values&&"object"==typeof values){let unique={};arrayValues=coders.map((coder=>{const name=coder.localName;return name||array_logger.throwError("cannot encode object for signature with missing names",Logger.errors.INVALID_ARGUMENT,{argument:"values",coder,value:values}),unique[name]&&array_logger.throwError("cannot encode object for signature with duplicate names",Logger.errors.INVALID_ARGUMENT,{argument:"values",coder,value:values}),unique[name]=!0,values[name]}))}else array_logger.throwArgumentError("invalid tuple value","tuple",values);coders.length!==arrayValues.length&&array_logger.throwArgumentError("types/value length mismatch","tuple",values);let staticWriter=new Writer(writer.wordSize),dynamicWriter=new Writer(writer.wordSize),updateFuncs=[];coders.forEach(((coder,index)=>{let value=arrayValues[index];if(coder.dynamic){let dynamicOffset=dynamicWriter.length;coder.encode(dynamicWriter,value);let updateFunc=staticWriter.writeUpdatableValue();updateFuncs.push((baseOffset=>{updateFunc(baseOffset+dynamicOffset)}))}else coder.encode(staticWriter,value)})),updateFuncs.forEach((func=>{func(staticWriter.length)}));let length=writer.appendWriter(staticWriter);return length+=writer.appendWriter(dynamicWriter),length}function unpack(reader,coders){let values=[],baseReader=reader.subReader(0);coders.forEach((coder=>{let value=null;if(coder.dynamic){let offset=reader.readValue(),offsetReader=baseReader.subReader(offset.toNumber());try{value=coder.decode(offsetReader)}catch(error){if(error.code===Logger.errors.BUFFER_OVERRUN)throw error;value=error,value.baseType=coder.name,value.name=coder.localName,value.type=coder.type}}else try{value=coder.decode(reader)}catch(error){if(error.code===Logger.errors.BUFFER_OVERRUN)throw error;value=error,value.baseType=coder.name,value.name=coder.localName,value.type=coder.type}null!=value&&values.push(value)}));const uniqueNames=coders.reduce(((accum,coder)=>{const name=coder.localName;return name&&(accum[name]||(accum[name]=0),accum[name]++),accum}),{});coders.forEach(((coder,index)=>{let name=coder.localName;if(!name||1!==uniqueNames[name])return;if("length"===name&&(name="_length"),null!=values[name])return;const value=values[index];value instanceof Error?Object.defineProperty(values,name,{enumerable:!0,get:()=>{throw value}}):values[name]=value}));for(let i=0;i{throw value}})}return Object.freeze(values)}class ArrayCoder extends Coder{constructor(coder,length,localName){super("array",coder.type+"["+(length>=0?length:"")+"]",localName,-1===length||coder.dynamic),this.coder=coder,this.length=length}defaultValue(){const defaultChild=this.coder.defaultValue(),result=[];for(let i=0;ireader._data.length&&array_logger.throwError("insufficient data length",Logger.errors.BUFFER_OVERRUN,{length:reader._data.length,count}));let coders=[];for(let i=0;i{coder.dynamic&&(dynamic=!0),types.push(coder.type)}));super("tuple","tuple("+types.join(",")+")",localName,dynamic),this.coders=coders}defaultValue(){const values=[];this.coders.forEach((coder=>{values.push(coder.defaultValue())}));const uniqueNames=this.coders.reduce(((accum,coder)=>{const name=coder.localName;return name&&(accum[name]||(accum[name]=0),accum[name]++),accum}),{});return this.coders.forEach(((coder,index)=>{let name=coder.localName;name&&1===uniqueNames[name]&&("length"===name&&(name="_length"),null==values[name]&&(values[name]=values[index]))})),Object.freeze(values)}encode(writer,value){return pack(writer,this.coders,value)}decode(reader){return reader.coerce(this.name,unpack(reader,this.coders))}}const fragments_logger=new Logger("abi/5.7.0"),fragments_constructorGuard={};let ModifiersBytes={calldata:!0,memory:!0,storage:!0},ModifiersNest={calldata:!0,memory:!0};function checkModifier(type,name){if("bytes"===type||"string"===type){if(ModifiersBytes[name])return!0}else if("address"===type){if("payable"===name)return!0}else if((type.indexOf("[")>=0||"tuple"===type)&&ModifiersNest[name])return!0;return(ModifiersBytes[name]||"payable"===name)&&fragments_logger.throwArgumentError("invalid modifier","name",name),!1}function populate(object,params){for(let key in params)defineReadOnly(object,key,params[key])}const FormatTypes=Object.freeze({sighash:"sighash",minimal:"minimal",full:"full",json:"json"}),paramTypeArray=new RegExp(/^(.*)\[([0-9]*)\]$/);class ParamType{constructor(constructorGuard,params){constructorGuard!==fragments_constructorGuard&&fragments_logger.throwError("use fromString",Logger.errors.UNSUPPORTED_OPERATION,{operation:"new ParamType()"}),populate(this,params);let match=this.type.match(paramTypeArray);populate(this,match?{arrayLength:parseInt(match[2]||"-1"),arrayChildren:ParamType.fromObject({type:match[1],components:this.components}),baseType:"array"}:{arrayLength:null,arrayChildren:null,baseType:null!=this.components?"tuple":this.type}),this._isParamType=!0,Object.freeze(this)}format(format){if(format||(format=FormatTypes.sighash),FormatTypes[format]||fragments_logger.throwArgumentError("invalid format type","format",format),format===FormatTypes.json){let result={type:"tuple"===this.baseType?"tuple":this.type,name:this.name||void 0};return"boolean"==typeof this.indexed&&(result.indexed=this.indexed),this.components&&(result.components=this.components.map((comp=>JSON.parse(comp.format(format))))),JSON.stringify(result)}let result="";return"array"===this.baseType?(result+=this.arrayChildren.format(format),result+="["+(this.arrayLength<0?"":String(this.arrayLength))+"]"):"tuple"===this.baseType?(format!==FormatTypes.sighash&&(result+=this.type),result+="("+this.components.map((comp=>comp.format(format))).join(format===FormatTypes.full?", ":",")+")"):result+=this.type,format!==FormatTypes.sighash&&(!0===this.indexed&&(result+=" indexed"),format===FormatTypes.full&&this.name&&(result+=" "+this.name)),result}static from(value,allowIndexed){return"string"==typeof value?ParamType.fromString(value,allowIndexed):ParamType.fromObject(value)}static fromObject(value){return ParamType.isParamType(value)?value:new ParamType(fragments_constructorGuard,{name:value.name||null,type:verifyType(value.type),indexed:null==value.indexed?null:!!value.indexed,components:value.components?value.components.map(ParamType.fromObject):null})}static fromString(value,allowIndexed){return function ParamTypify(node){return ParamType.fromObject({name:node.name,type:node.type,indexed:node.indexed,components:node.components})}(function parseParamType(param,allowIndexed){let originalParam=param;function throwError(i){fragments_logger.throwArgumentError(`unexpected character at position ${i}`,"param",param)}function newNode(parent){let node={type:"",name:"",parent,state:{allowType:!0}};return allowIndexed&&(node.indexed=!1),node}param=param.replace(/\s/g," ");let parent={type:"",name:"",state:{allowType:!0}},node=parent;for(let i=0;iParamType.fromString(param,allowIndex)))}class Fragment{constructor(constructorGuard,params){constructorGuard!==fragments_constructorGuard&&fragments_logger.throwError("use a static from method",Logger.errors.UNSUPPORTED_OPERATION,{operation:"new Fragment()"}),populate(this,params),this._isFragment=!0,Object.freeze(this)}static from(value){return Fragment.isFragment(value)?value:"string"==typeof value?Fragment.fromString(value):Fragment.fromObject(value)}static fromObject(value){if(Fragment.isFragment(value))return value;switch(value.type){case"function":return FunctionFragment.fromObject(value);case"event":return EventFragment.fromObject(value);case"constructor":return ConstructorFragment.fromObject(value);case"error":return ErrorFragment.fromObject(value);case"fallback":case"receive":return null}return fragments_logger.throwArgumentError("invalid fragment object","value",value)}static fromString(value){return"event"===(value=(value=(value=value.replace(/\s/g," ")).replace(/\(/g," (").replace(/\)/g,") ").replace(/\s+/g," ")).trim()).split(" ")[0]?EventFragment.fromString(value.substring(5).trim()):"function"===value.split(" ")[0]?FunctionFragment.fromString(value.substring(8).trim()):"constructor"===value.split("(")[0].trim()?ConstructorFragment.fromString(value.trim()):"error"===value.split(" ")[0]?ErrorFragment.fromString(value.substring(5).trim()):fragments_logger.throwArgumentError("unsupported fragment","value",value)}static isFragment(value){return!(!value||!value._isFragment)}}class EventFragment extends Fragment{format(format){if(format||(format=FormatTypes.sighash),FormatTypes[format]||fragments_logger.throwArgumentError("invalid format type","format",format),format===FormatTypes.json)return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map((input=>JSON.parse(input.format(format))))});let result="";return format!==FormatTypes.sighash&&(result+="event "),result+=this.name+"("+this.inputs.map((input=>input.format(format))).join(format===FormatTypes.full?", ":",")+") ",format!==FormatTypes.sighash&&this.anonymous&&(result+="anonymous "),result.trim()}static from(value){return"string"==typeof value?EventFragment.fromString(value):EventFragment.fromObject(value)}static fromObject(value){if(EventFragment.isEventFragment(value))return value;"event"!==value.type&&fragments_logger.throwArgumentError("invalid event object","value",value);const params={name:verifyIdentifier(value.name),anonymous:value.anonymous,inputs:value.inputs?value.inputs.map(ParamType.fromObject):[],type:"event"};return new EventFragment(fragments_constructorGuard,params)}static fromString(value){let match=value.match(regexParen);match||fragments_logger.throwArgumentError("invalid event string","value",value);let anonymous=!1;return match[3].split(" ").forEach((modifier=>{switch(modifier.trim()){case"anonymous":anonymous=!0;break;case"":break;default:fragments_logger.warn("unknown modifier: "+modifier)}})),EventFragment.fromObject({name:match[1].trim(),anonymous,inputs:parseParams(match[2],!0),type:"event"})}static isEventFragment(value){return value&&value._isFragment&&"event"===value.type}}function parseGas(value,params){params.gas=null;let comps=value.split("@");return 1!==comps.length?(comps.length>2&&fragments_logger.throwArgumentError("invalid human-readable ABI signature","value",value),comps[1].match(/^[0-9]+$/)||fragments_logger.throwArgumentError("invalid human-readable ABI signature gas","value",value),params.gas=BigNumber.from(comps[1]),comps[0]):value}function parseModifiers(value,params){params.constant=!1,params.payable=!1,params.stateMutability="nonpayable",value.split(" ").forEach((modifier=>{switch(modifier.trim()){case"constant":params.constant=!0;break;case"payable":params.payable=!0,params.stateMutability="payable";break;case"nonpayable":params.payable=!1,params.stateMutability="nonpayable";break;case"pure":params.constant=!0,params.stateMutability="pure";break;case"view":params.constant=!0,params.stateMutability="view";break;case"external":case"public":case"":break;default:console.log("unknown modifier: "+modifier)}}))}function verifyState(value){let result={constant:!1,payable:!0,stateMutability:"payable"};return null!=value.stateMutability?(result.stateMutability=value.stateMutability,result.constant="view"===result.stateMutability||"pure"===result.stateMutability,null!=value.constant&&!!value.constant!==result.constant&&fragments_logger.throwArgumentError("cannot have constant function with mutability "+result.stateMutability,"value",value),result.payable="payable"===result.stateMutability,null!=value.payable&&!!value.payable!==result.payable&&fragments_logger.throwArgumentError("cannot have payable function with mutability "+result.stateMutability,"value",value)):null!=value.payable?(result.payable=!!value.payable,null!=value.constant||result.payable||"constructor"===value.type||fragments_logger.throwArgumentError("unable to determine stateMutability","value",value),result.constant=!!value.constant,result.constant?result.stateMutability="view":result.stateMutability=result.payable?"payable":"nonpayable",result.payable&&result.constant&&fragments_logger.throwArgumentError("cannot have constant payable function","value",value)):null!=value.constant?(result.constant=!!value.constant,result.payable=!result.constant,result.stateMutability=result.constant?"view":"payable"):"constructor"!==value.type&&fragments_logger.throwArgumentError("unable to determine stateMutability","value",value),result}class ConstructorFragment extends Fragment{format(format){if(format||(format=FormatTypes.sighash),FormatTypes[format]||fragments_logger.throwArgumentError("invalid format type","format",format),format===FormatTypes.json)return JSON.stringify({type:"constructor",stateMutability:"nonpayable"!==this.stateMutability?this.stateMutability:void 0,payable:this.payable,gas:this.gas?this.gas.toNumber():void 0,inputs:this.inputs.map((input=>JSON.parse(input.format(format))))});format===FormatTypes.sighash&&fragments_logger.throwError("cannot format a constructor for sighash",Logger.errors.UNSUPPORTED_OPERATION,{operation:"format(sighash)"});let result="constructor("+this.inputs.map((input=>input.format(format))).join(format===FormatTypes.full?", ":",")+") ";return this.stateMutability&&"nonpayable"!==this.stateMutability&&(result+=this.stateMutability+" "),result.trim()}static from(value){return"string"==typeof value?ConstructorFragment.fromString(value):ConstructorFragment.fromObject(value)}static fromObject(value){if(ConstructorFragment.isConstructorFragment(value))return value;"constructor"!==value.type&&fragments_logger.throwArgumentError("invalid constructor object","value",value);let state=verifyState(value);state.constant&&fragments_logger.throwArgumentError("constructor cannot be constant","value",value);const params={name:null,type:value.type,inputs:value.inputs?value.inputs.map(ParamType.fromObject):[],payable:state.payable,stateMutability:state.stateMutability,gas:value.gas?BigNumber.from(value.gas):null};return new ConstructorFragment(fragments_constructorGuard,params)}static fromString(value){let params={type:"constructor"},parens=(value=parseGas(value,params)).match(regexParen);return parens&&"constructor"===parens[1].trim()||fragments_logger.throwArgumentError("invalid constructor string","value",value),params.inputs=parseParams(parens[2].trim(),!1),parseModifiers(parens[3].trim(),params),ConstructorFragment.fromObject(params)}static isConstructorFragment(value){return value&&value._isFragment&&"constructor"===value.type}}class FunctionFragment extends ConstructorFragment{format(format){if(format||(format=FormatTypes.sighash),FormatTypes[format]||fragments_logger.throwArgumentError("invalid format type","format",format),format===FormatTypes.json)return JSON.stringify({type:"function",name:this.name,constant:this.constant,stateMutability:"nonpayable"!==this.stateMutability?this.stateMutability:void 0,payable:this.payable,gas:this.gas?this.gas.toNumber():void 0,inputs:this.inputs.map((input=>JSON.parse(input.format(format)))),outputs:this.outputs.map((output=>JSON.parse(output.format(format))))});let result="";return format!==FormatTypes.sighash&&(result+="function "),result+=this.name+"("+this.inputs.map((input=>input.format(format))).join(format===FormatTypes.full?", ":",")+") ",format!==FormatTypes.sighash&&(this.stateMutability?"nonpayable"!==this.stateMutability&&(result+=this.stateMutability+" "):this.constant&&(result+="view "),this.outputs&&this.outputs.length&&(result+="returns ("+this.outputs.map((output=>output.format(format))).join(", ")+") "),null!=this.gas&&(result+="@"+this.gas.toString()+" ")),result.trim()}static from(value){return"string"==typeof value?FunctionFragment.fromString(value):FunctionFragment.fromObject(value)}static fromObject(value){if(FunctionFragment.isFunctionFragment(value))return value;"function"!==value.type&&fragments_logger.throwArgumentError("invalid function object","value",value);let state=verifyState(value);const params={type:value.type,name:verifyIdentifier(value.name),constant:state.constant,inputs:value.inputs?value.inputs.map(ParamType.fromObject):[],outputs:value.outputs?value.outputs.map(ParamType.fromObject):[],payable:state.payable,stateMutability:state.stateMutability,gas:value.gas?BigNumber.from(value.gas):null};return new FunctionFragment(fragments_constructorGuard,params)}static fromString(value){let params={type:"function"},comps=(value=parseGas(value,params)).split(" returns ");comps.length>2&&fragments_logger.throwArgumentError("invalid function string","value",value);let parens=comps[0].match(regexParen);if(parens||fragments_logger.throwArgumentError("invalid function signature","value",value),params.name=parens[1].trim(),params.name&&verifyIdentifier(params.name),params.inputs=parseParams(parens[2],!1),parseModifiers(parens[3].trim(),params),comps.length>1){let returns=comps[1].match(regexParen);""==returns[1].trim()&&""==returns[3].trim()||fragments_logger.throwArgumentError("unexpected tokens","value",value),params.outputs=parseParams(returns[2],!1)}else params.outputs=[];return FunctionFragment.fromObject(params)}static isFunctionFragment(value){return value&&value._isFragment&&"function"===value.type}}function checkForbidden(fragment){const sig=fragment.format();return"Error(string)"!==sig&&"Panic(uint256)"!==sig||fragments_logger.throwArgumentError(`cannot specify user defined ${sig} error`,"fragment",fragment),fragment}class ErrorFragment extends Fragment{format(format){if(format||(format=FormatTypes.sighash),FormatTypes[format]||fragments_logger.throwArgumentError("invalid format type","format",format),format===FormatTypes.json)return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map((input=>JSON.parse(input.format(format))))});let result="";return format!==FormatTypes.sighash&&(result+="error "),result+=this.name+"("+this.inputs.map((input=>input.format(format))).join(format===FormatTypes.full?", ":",")+") ",result.trim()}static from(value){return"string"==typeof value?ErrorFragment.fromString(value):ErrorFragment.fromObject(value)}static fromObject(value){if(ErrorFragment.isErrorFragment(value))return value;"error"!==value.type&&fragments_logger.throwArgumentError("invalid error object","value",value);const params={type:value.type,name:verifyIdentifier(value.name),inputs:value.inputs?value.inputs.map(ParamType.fromObject):[]};return checkForbidden(new ErrorFragment(fragments_constructorGuard,params))}static fromString(value){let params={type:"error"},parens=value.match(regexParen);return parens||fragments_logger.throwArgumentError("invalid error signature","value",value),params.name=parens[1].trim(),params.name&&verifyIdentifier(params.name),params.inputs=parseParams(parens[2],!1),checkForbidden(ErrorFragment.fromObject(params))}static isErrorFragment(value){return value&&value._isFragment&&"error"===value.type}}function verifyType(type){return type.match(/^uint($|[^1-9])/)?type="uint256"+type.substring(4):type.match(/^int($|[^1-9])/)&&(type="int256"+type.substring(3)),type}const regexIdentifier=new RegExp("^[a-zA-Z$_][a-zA-Z0-9$_]*$");function verifyIdentifier(value){return value&&value.match(regexIdentifier)||fragments_logger.throwArgumentError(`invalid identifier "${value}"`,"value",value),value}const regexParen=new RegExp("^([^)(]*)\\((.*)\\)([^)(]*)$");const abi_coder_logger=new Logger("abi/5.7.0"),paramTypeBytes=new RegExp(/^bytes([0-9]*)$/),paramTypeNumber=new RegExp(/^(u?int)([0-9]*)$/);class AbiCoder{constructor(coerceFunc){defineReadOnly(this,"coerceFunc",coerceFunc||null)}_getCoder(param){switch(param.baseType){case"address":return new AddressCoder(param.name);case"bool":return new BooleanCoder(param.name);case"string":return new StringCoder(param.name);case"bytes":return new BytesCoder(param.name);case"array":return new ArrayCoder(this._getCoder(param.arrayChildren),param.arrayLength,param.name);case"tuple":return new TupleCoder((param.components||[]).map((component=>this._getCoder(component))),param.name);case"":return new NullCoder(param.name)}let match=param.type.match(paramTypeNumber);if(match){let size=parseInt(match[2]||"256");return(0===size||size>256||size%8!=0)&&abi_coder_logger.throwArgumentError("invalid "+match[1]+" bit length","param",param),new NumberCoder(size/8,"int"===match[1],param.name)}if(match=param.type.match(paramTypeBytes),match){let size=parseInt(match[1]);return(0===size||size>32)&&abi_coder_logger.throwArgumentError("invalid bytes length","param",param),new FixedBytesCoder(size,param.name)}return abi_coder_logger.throwArgumentError("invalid type","type",param.type)}_getWordSize(){return 32}_getReader(data,allowLoose){return new Reader(data,this._getWordSize(),this.coerceFunc,allowLoose)}_getWriter(){return new Writer(this._getWordSize())}getDefaultValue(types){const coders=types.map((type=>this._getCoder(ParamType.from(type))));return new TupleCoder(coders,"_").defaultValue()}encode(types,values){types.length!==values.length&&abi_coder_logger.throwError("types/values length mismatch",Logger.errors.INVALID_ARGUMENT,{count:{types:types.length,values:values.length},value:{types,values}});const coders=types.map((type=>this._getCoder(ParamType.from(type)))),coder=new TupleCoder(coders,"_"),writer=this._getWriter();return coder.encode(writer,values),writer.data}decode(types,data,loose){const coders=types.map((type=>this._getCoder(ParamType.from(type))));return new TupleCoder(coders,"_").decode(this._getReader(arrayify(data),loose))}}const defaultAbiCoder=new AbiCoder,interface_logger=new Logger("abi/5.7.0");class LogDescription extends Description{}class TransactionDescription extends Description{}class ErrorDescription extends Description{}class Indexed extends Description{static isIndexed(value){return!(!value||!value._isIndexed)}}const BuiltinErrors={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:!0},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"]}};function wrapAccessError(property,error){const wrap=new Error(`deferred error during ABI decoding triggered accessing ${property}`);return wrap.error=error,wrap}class Interface{constructor(fragments){let abi=[];abi="string"==typeof fragments?JSON.parse(fragments):fragments,defineReadOnly(this,"fragments",abi.map((fragment=>Fragment.from(fragment))).filter((fragment=>null!=fragment))),defineReadOnly(this,"_abiCoder",getStatic(new.target,"getAbiCoder")()),defineReadOnly(this,"functions",{}),defineReadOnly(this,"errors",{}),defineReadOnly(this,"events",{}),defineReadOnly(this,"structs",{}),this.fragments.forEach((fragment=>{let bucket=null;switch(fragment.type){case"constructor":return this.deploy?void interface_logger.warn("duplicate definition - constructor"):void defineReadOnly(this,"deploy",fragment);case"function":bucket=this.functions;break;case"event":bucket=this.events;break;case"error":bucket=this.errors;break;default:return}let signature=fragment.format();bucket[signature]?interface_logger.warn("duplicate definition - "+signature):bucket[signature]=fragment})),this.deploy||defineReadOnly(this,"deploy",ConstructorFragment.from({payable:!1,type:"constructor"})),defineReadOnly(this,"_isInterface",!0)}format(format){format||(format=FormatTypes.full),format===FormatTypes.sighash&&interface_logger.throwArgumentError("interface does not support formatting sighash","format",format);const abi=this.fragments.map((fragment=>fragment.format(format)));return format===FormatTypes.json?JSON.stringify(abi.map((j=>JSON.parse(j)))):abi}static getAbiCoder(){return defaultAbiCoder}static getAddress(address){return getAddress(address)}static getSighash(fragment){return hexDataSlice(id(fragment.format()),0,4)}static getEventTopic(eventFragment){return id(eventFragment.format())}getFunction(nameOrSignatureOrSighash){if(lib_esm_isHexString(nameOrSignatureOrSighash)){for(const name in this.functions)if(nameOrSignatureOrSighash===this.getSighash(name))return this.functions[name];interface_logger.throwArgumentError("no matching function","sighash",nameOrSignatureOrSighash)}if(-1===nameOrSignatureOrSighash.indexOf("(")){const name=nameOrSignatureOrSighash.trim(),matching=Object.keys(this.functions).filter((f=>f.split("(")[0]===name));return 0===matching.length?interface_logger.throwArgumentError("no matching function","name",name):matching.length>1&&interface_logger.throwArgumentError("multiple matching functions","name",name),this.functions[matching[0]]}const result=this.functions[FunctionFragment.fromString(nameOrSignatureOrSighash).format()];return result||interface_logger.throwArgumentError("no matching function","signature",nameOrSignatureOrSighash),result}getEvent(nameOrSignatureOrTopic){if(lib_esm_isHexString(nameOrSignatureOrTopic)){const topichash=nameOrSignatureOrTopic.toLowerCase();for(const name in this.events)if(topichash===this.getEventTopic(name))return this.events[name];interface_logger.throwArgumentError("no matching event","topichash",topichash)}if(-1===nameOrSignatureOrTopic.indexOf("(")){const name=nameOrSignatureOrTopic.trim(),matching=Object.keys(this.events).filter((f=>f.split("(")[0]===name));return 0===matching.length?interface_logger.throwArgumentError("no matching event","name",name):matching.length>1&&interface_logger.throwArgumentError("multiple matching events","name",name),this.events[matching[0]]}const result=this.events[EventFragment.fromString(nameOrSignatureOrTopic).format()];return result||interface_logger.throwArgumentError("no matching event","signature",nameOrSignatureOrTopic),result}getError(nameOrSignatureOrSighash){if(lib_esm_isHexString(nameOrSignatureOrSighash)){const getSighash=getStatic(this.constructor,"getSighash");for(const name in this.errors){if(nameOrSignatureOrSighash===getSighash(this.errors[name]))return this.errors[name]}interface_logger.throwArgumentError("no matching error","sighash",nameOrSignatureOrSighash)}if(-1===nameOrSignatureOrSighash.indexOf("(")){const name=nameOrSignatureOrSighash.trim(),matching=Object.keys(this.errors).filter((f=>f.split("(")[0]===name));return 0===matching.length?interface_logger.throwArgumentError("no matching error","name",name):matching.length>1&&interface_logger.throwArgumentError("multiple matching errors","name",name),this.errors[matching[0]]}const result=this.errors[FunctionFragment.fromString(nameOrSignatureOrSighash).format()];return result||interface_logger.throwArgumentError("no matching error","signature",nameOrSignatureOrSighash),result}getSighash(fragment){if("string"==typeof fragment)try{fragment=this.getFunction(fragment)}catch(error){try{fragment=this.getError(fragment)}catch(_){throw error}}return getStatic(this.constructor,"getSighash")(fragment)}getEventTopic(eventFragment){return"string"==typeof eventFragment&&(eventFragment=this.getEvent(eventFragment)),getStatic(this.constructor,"getEventTopic")(eventFragment)}_decodeParams(params,data){return this._abiCoder.decode(params,data)}_encodeParams(params,values){return this._abiCoder.encode(params,values)}encodeDeploy(values){return this._encodeParams(this.deploy.inputs,values||[])}decodeErrorResult(fragment,data){"string"==typeof fragment&&(fragment=this.getError(fragment));const bytes=arrayify(data);return hexlify(bytes.slice(0,4))!==this.getSighash(fragment)&&interface_logger.throwArgumentError(`data signature does not match error ${fragment.name}.`,"data",hexlify(bytes)),this._decodeParams(fragment.inputs,bytes.slice(4))}encodeErrorResult(fragment,values){return"string"==typeof fragment&&(fragment=this.getError(fragment)),hexlify(concat([this.getSighash(fragment),this._encodeParams(fragment.inputs,values||[])]))}decodeFunctionData(functionFragment,data){"string"==typeof functionFragment&&(functionFragment=this.getFunction(functionFragment));const bytes=arrayify(data);return hexlify(bytes.slice(0,4))!==this.getSighash(functionFragment)&&interface_logger.throwArgumentError(`data signature does not match function ${functionFragment.name}.`,"data",hexlify(bytes)),this._decodeParams(functionFragment.inputs,bytes.slice(4))}encodeFunctionData(functionFragment,values){return"string"==typeof functionFragment&&(functionFragment=this.getFunction(functionFragment)),hexlify(concat([this.getSighash(functionFragment),this._encodeParams(functionFragment.inputs,values||[])]))}decodeFunctionResult(functionFragment,data){"string"==typeof functionFragment&&(functionFragment=this.getFunction(functionFragment));let bytes=arrayify(data),reason=null,message="",errorArgs=null,errorName=null,errorSignature=null;switch(bytes.length%this._abiCoder._getWordSize()){case 0:try{return this._abiCoder.decode(functionFragment.outputs,bytes)}catch(error){}break;case 4:{const selector=hexlify(bytes.slice(0,4)),builtin=BuiltinErrors[selector];if(builtin)errorArgs=this._abiCoder.decode(builtin.inputs,bytes.slice(4)),errorName=builtin.name,errorSignature=builtin.signature,builtin.reason&&(reason=errorArgs[0]),"Error"===errorName?message=`; VM Exception while processing transaction: reverted with reason string ${JSON.stringify(errorArgs[0])}`:"Panic"===errorName&&(message=`; VM Exception while processing transaction: reverted with panic code ${errorArgs[0]}`);else try{const error=this.getError(selector);errorArgs=this._abiCoder.decode(error.inputs,bytes.slice(4)),errorName=error.name,errorSignature=error.format()}catch(error){}break}}return interface_logger.throwError("call revert exception"+message,Logger.errors.CALL_EXCEPTION,{method:functionFragment.format(),data:hexlify(data),errorArgs,errorName,errorSignature,reason})}encodeFunctionResult(functionFragment,values){return"string"==typeof functionFragment&&(functionFragment=this.getFunction(functionFragment)),hexlify(this._abiCoder.encode(functionFragment.outputs,values||[]))}encodeFilterTopics(eventFragment,values){"string"==typeof eventFragment&&(eventFragment=this.getEvent(eventFragment)),values.length>eventFragment.inputs.length&&interface_logger.throwError("too many arguments for "+eventFragment.format(),Logger.errors.UNEXPECTED_ARGUMENT,{argument:"values",value:values});let topics=[];eventFragment.anonymous||topics.push(this.getEventTopic(eventFragment));const encodeTopic=(param,value)=>"string"===param.type?id(value):"bytes"===param.type?keccak256(hexlify(value)):("bool"===param.type&&"boolean"==typeof value&&(value=value?"0x01":"0x00"),param.type.match(/^u?int/)&&(value=BigNumber.from(value).toHexString()),"address"===param.type&&this._abiCoder.encode(["address"],[value]),hexZeroPad(hexlify(value),32));for(values.forEach(((value,index)=>{let param=eventFragment.inputs[index];param.indexed?null==value?topics.push(null):"array"===param.baseType||"tuple"===param.baseType?interface_logger.throwArgumentError("filtering with tuples or arrays not supported","contract."+param.name,value):Array.isArray(value)?topics.push(value.map((value=>encodeTopic(param,value)))):topics.push(encodeTopic(param,value)):null!=value&&interface_logger.throwArgumentError("cannot filter non-indexed parameters; must be null","contract."+param.name,value)}));topics.length&&null===topics[topics.length-1];)topics.pop();return topics}encodeEventLog(eventFragment,values){"string"==typeof eventFragment&&(eventFragment=this.getEvent(eventFragment));const topics=[],dataTypes=[],dataValues=[];return eventFragment.anonymous||topics.push(this.getEventTopic(eventFragment)),values.length!==eventFragment.inputs.length&&interface_logger.throwArgumentError("event arguments/values mismatch","values",values),eventFragment.inputs.forEach(((param,index)=>{const value=values[index];if(param.indexed)if("string"===param.type)topics.push(id(value));else if("bytes"===param.type)topics.push(keccak256(value));else{if("tuple"===param.baseType||"array"===param.baseType)throw new Error("not implemented");topics.push(this._abiCoder.encode([param.type],[value]))}else dataTypes.push(param),dataValues.push(value)})),{data:this._abiCoder.encode(dataTypes,dataValues),topics}}decodeEventLog(eventFragment,data,topics){if("string"==typeof eventFragment&&(eventFragment=this.getEvent(eventFragment)),null!=topics&&!eventFragment.anonymous){let topicHash=this.getEventTopic(eventFragment);lib_esm_isHexString(topics[0],32)&&topics[0].toLowerCase()===topicHash||interface_logger.throwError("fragment/topic mismatch",Logger.errors.INVALID_ARGUMENT,{argument:"topics[0]",expected:topicHash,value:topics[0]}),topics=topics.slice(1)}let indexed=[],nonIndexed=[],dynamic=[];eventFragment.inputs.forEach(((param,index)=>{param.indexed?"string"===param.type||"bytes"===param.type||"tuple"===param.baseType||"array"===param.baseType?(indexed.push(ParamType.fromObject({type:"bytes32",name:param.name})),dynamic.push(!0)):(indexed.push(param),dynamic.push(!1)):(nonIndexed.push(param),dynamic.push(!1))}));let resultIndexed=null!=topics?this._abiCoder.decode(indexed,concat(topics)):null,resultNonIndexed=this._abiCoder.decode(nonIndexed,data,!0),result=[],nonIndexedIndex=0,indexedIndex=0;eventFragment.inputs.forEach(((param,index)=>{if(param.indexed)if(null==resultIndexed)result[index]=new Indexed({_isIndexed:!0,hash:null});else if(dynamic[index])result[index]=new Indexed({_isIndexed:!0,hash:resultIndexed[indexedIndex++]});else try{result[index]=resultIndexed[indexedIndex++]}catch(error){result[index]=error}else try{result[index]=resultNonIndexed[nonIndexedIndex++]}catch(error){result[index]=error}if(param.name&&null==result[param.name]){const value=result[index];value instanceof Error?Object.defineProperty(result,param.name,{enumerable:!0,get:()=>{throw wrapAccessError(`property ${JSON.stringify(param.name)}`,value)}}):result[param.name]=value}}));for(let i=0;i{throw wrapAccessError(`index ${i}`,value)}})}return Object.freeze(result)}parseTransaction(tx){let fragment=this.getFunction(tx.data.substring(0,10).toLowerCase());return fragment?new TransactionDescription({args:this._abiCoder.decode(fragment.inputs,"0x"+tx.data.substring(10)),functionFragment:fragment,name:fragment.name,signature:fragment.format(),sighash:this.getSighash(fragment),value:BigNumber.from(tx.value||"0")}):null}parseLog(log){let fragment=this.getEvent(log.topics[0]);return!fragment||fragment.anonymous?null:new LogDescription({eventFragment:fragment,name:fragment.name,signature:fragment.format(),topic:this.getEventTopic(fragment),args:this.decodeEventLog(fragment,log.data,log.topics)})}parseError(data){const hexData=hexlify(data);let fragment=this.getError(hexData.substring(0,10).toLowerCase());return fragment?new ErrorDescription({args:this._abiCoder.decode(fragment.inputs,"0x"+hexData.substring(10)),errorFragment:fragment,name:fragment.name,signature:fragment.format(),sighash:this.getSighash(fragment)}):null}static isInterface(value){return!(!value||!value._isInterface)}}var lib_esm_awaiter=function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};const abstract_provider_lib_esm_logger=new Logger("abstract-provider/5.7.0");class ForkEvent extends Description{static isForkEvent(value){return!(!value||!value._isForkEvent)}}class Provider{constructor(){abstract_provider_lib_esm_logger.checkAbstract(new.target,Provider),defineReadOnly(this,"_isProvider",!0)}getFeeData(){return lib_esm_awaiter(this,void 0,void 0,(function*(){const{block,gasPrice}=yield resolveProperties({block:this.getBlock("latest"),gasPrice:this.getGasPrice().catch((error=>null))});let lastBaseFeePerGas=null,maxFeePerGas=null,maxPriorityFeePerGas=null;return block&&block.baseFeePerGas&&(lastBaseFeePerGas=block.baseFeePerGas,maxPriorityFeePerGas=BigNumber.from("1500000000"),maxFeePerGas=block.baseFeePerGas.mul(2).add(maxPriorityFeePerGas)),{lastBaseFeePerGas,maxFeePerGas,maxPriorityFeePerGas,gasPrice}}))}addListener(eventName,listener){return this.on(eventName,listener)}removeListener(eventName,listener){return this.off(eventName,listener)}static isProvider(value){return!(!value||!value._isProvider)}}var abstract_signer_lib_esm_awaiter=function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};const abstract_signer_lib_esm_logger=new Logger("abstract-signer/5.7.0"),allowedTransactionKeys=["accessList","ccipReadEnabled","chainId","customData","data","from","gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","nonce","to","type","value"],forwardErrors=[Logger.errors.INSUFFICIENT_FUNDS,Logger.errors.NONCE_EXPIRED,Logger.errors.REPLACEMENT_UNDERPRICED];class Signer{constructor(){abstract_signer_lib_esm_logger.checkAbstract(new.target,Signer),defineReadOnly(this,"_isSigner",!0)}getBalance(blockTag){return abstract_signer_lib_esm_awaiter(this,void 0,void 0,(function*(){return this._checkProvider("getBalance"),yield this.provider.getBalance(this.getAddress(),blockTag)}))}getTransactionCount(blockTag){return abstract_signer_lib_esm_awaiter(this,void 0,void 0,(function*(){return this._checkProvider("getTransactionCount"),yield this.provider.getTransactionCount(this.getAddress(),blockTag)}))}estimateGas(transaction){return abstract_signer_lib_esm_awaiter(this,void 0,void 0,(function*(){this._checkProvider("estimateGas");const tx=yield resolveProperties(this.checkTransaction(transaction));return yield this.provider.estimateGas(tx)}))}call(transaction,blockTag){return abstract_signer_lib_esm_awaiter(this,void 0,void 0,(function*(){this._checkProvider("call");const tx=yield resolveProperties(this.checkTransaction(transaction));return yield this.provider.call(tx,blockTag)}))}sendTransaction(transaction){return abstract_signer_lib_esm_awaiter(this,void 0,void 0,(function*(){this._checkProvider("sendTransaction");const tx=yield this.populateTransaction(transaction),signedTx=yield this.signTransaction(tx);return yield this.provider.sendTransaction(signedTx)}))}getChainId(){return abstract_signer_lib_esm_awaiter(this,void 0,void 0,(function*(){this._checkProvider("getChainId");return(yield this.provider.getNetwork()).chainId}))}getGasPrice(){return abstract_signer_lib_esm_awaiter(this,void 0,void 0,(function*(){return this._checkProvider("getGasPrice"),yield this.provider.getGasPrice()}))}getFeeData(){return abstract_signer_lib_esm_awaiter(this,void 0,void 0,(function*(){return this._checkProvider("getFeeData"),yield this.provider.getFeeData()}))}resolveName(name){return abstract_signer_lib_esm_awaiter(this,void 0,void 0,(function*(){return this._checkProvider("resolveName"),yield this.provider.resolveName(name)}))}checkTransaction(transaction){for(const key in transaction)-1===allowedTransactionKeys.indexOf(key)&&abstract_signer_lib_esm_logger.throwArgumentError("invalid transaction key: "+key,"transaction",transaction);const tx=shallowCopy(transaction);return null==tx.from?tx.from=this.getAddress():tx.from=Promise.all([Promise.resolve(tx.from),this.getAddress()]).then((result=>(result[0].toLowerCase()!==result[1].toLowerCase()&&abstract_signer_lib_esm_logger.throwArgumentError("from address mismatch","transaction",transaction),result[0]))),tx}populateTransaction(transaction){return abstract_signer_lib_esm_awaiter(this,void 0,void 0,(function*(){const tx=yield resolveProperties(this.checkTransaction(transaction));null!=tx.to&&(tx.to=Promise.resolve(tx.to).then((to=>abstract_signer_lib_esm_awaiter(this,void 0,void 0,(function*(){if(null==to)return null;const address=yield this.resolveName(to);return null==address&&abstract_signer_lib_esm_logger.throwArgumentError("provided ENS name resolves to null","tx.to",to),address})))),tx.to.catch((error=>{})));const hasEip1559=null!=tx.maxFeePerGas||null!=tx.maxPriorityFeePerGas;if(null==tx.gasPrice||2!==tx.type&&!hasEip1559?0!==tx.type&&1!==tx.type||!hasEip1559||abstract_signer_lib_esm_logger.throwArgumentError("pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas","transaction",transaction):abstract_signer_lib_esm_logger.throwArgumentError("eip-1559 transaction do not support gasPrice","transaction",transaction),2!==tx.type&&null!=tx.type||null==tx.maxFeePerGas||null==tx.maxPriorityFeePerGas)if(0===tx.type||1===tx.type)null==tx.gasPrice&&(tx.gasPrice=this.getGasPrice());else{const feeData=yield this.getFeeData();if(null==tx.type)if(null!=feeData.maxFeePerGas&&null!=feeData.maxPriorityFeePerGas)if(tx.type=2,null!=tx.gasPrice){const gasPrice=tx.gasPrice;delete tx.gasPrice,tx.maxFeePerGas=gasPrice,tx.maxPriorityFeePerGas=gasPrice}else null==tx.maxFeePerGas&&(tx.maxFeePerGas=feeData.maxFeePerGas),null==tx.maxPriorityFeePerGas&&(tx.maxPriorityFeePerGas=feeData.maxPriorityFeePerGas);else null!=feeData.gasPrice?(hasEip1559&&abstract_signer_lib_esm_logger.throwError("network does not support EIP-1559",Logger.errors.UNSUPPORTED_OPERATION,{operation:"populateTransaction"}),null==tx.gasPrice&&(tx.gasPrice=feeData.gasPrice),tx.type=0):abstract_signer_lib_esm_logger.throwError("failed to get consistent fee data",Logger.errors.UNSUPPORTED_OPERATION,{operation:"signer.getFeeData"});else 2===tx.type&&(null==tx.maxFeePerGas&&(tx.maxFeePerGas=feeData.maxFeePerGas),null==tx.maxPriorityFeePerGas&&(tx.maxPriorityFeePerGas=feeData.maxPriorityFeePerGas))}else tx.type=2;return null==tx.nonce&&(tx.nonce=this.getTransactionCount("pending")),null==tx.gasLimit&&(tx.gasLimit=this.estimateGas(tx).catch((error=>{if(forwardErrors.indexOf(error.code)>=0)throw error;return abstract_signer_lib_esm_logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit",Logger.errors.UNPREDICTABLE_GAS_LIMIT,{error,tx})}))),null==tx.chainId?tx.chainId=this.getChainId():tx.chainId=Promise.all([Promise.resolve(tx.chainId),this.getChainId()]).then((results=>(0!==results[1]&&results[0]!==results[1]&&abstract_signer_lib_esm_logger.throwArgumentError("chainId address mismatch","transaction",transaction),results[0]))),yield resolveProperties(tx)}))}_checkProvider(operation){this.provider||abstract_signer_lib_esm_logger.throwError("missing provider",Logger.errors.UNSUPPORTED_OPERATION,{operation:operation||"_checkProvider"})}static isSigner(value){return!(!value||!value._isSigner)}}class VoidSigner extends Signer{constructor(address,provider){super(),defineReadOnly(this,"address",address),defineReadOnly(this,"provider",provider||null)}getAddress(){return Promise.resolve(this.address)}_fail(message,operation){return Promise.resolve().then((()=>{abstract_signer_lib_esm_logger.throwError(message,Logger.errors.UNSUPPORTED_OPERATION,{operation})}))}signMessage(message){return this._fail("VoidSigner cannot sign messages","signMessage")}signTransaction(transaction){return this._fail("VoidSigner cannot sign transactions","signTransaction")}_signTypedData(domain,types,value){return this._fail("VoidSigner cannot sign typed data","signTypedData")}connect(provider){return new VoidSigner(this.address,provider)}}var hash=__webpack_require__(3715),hash_default=__webpack_require__.n(hash);"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==__webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self&&self;function createCommonjsModule(fn,basedir,module){return module={path:basedir,exports:{},require:function(path,base){return function commonjsRequire(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==base&&module.path)}},fn(module,module.exports),module.exports}var minimalisticAssert=assert;function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}assert.equal=function assertEqual(l,r,msg){if(l!=r)throw new Error(msg||"Assertion failed: "+l+" != "+r)};var utils_1=createCommonjsModule((function(module,exports){var utils=exports;function zero2(word){return 1===word.length?"0"+word:word}function toHex(msg){for(var res="",i=0;i>8,lo=255&c;hi?res.push(hi,lo):res.push(lo)}return res},utils.zero2=zero2,utils.toHex=toHex,utils.encode=function encode(arr,enc){return"hex"===enc?toHex(arr):arr}})),utils_1$1=createCommonjsModule((function(module,exports){var utils=exports;utils.assert=minimalisticAssert,utils.toArray=utils_1.toArray,utils.zero2=utils_1.zero2,utils.toHex=utils_1.toHex,utils.encode=utils_1.encode,utils.getNAF=function getNAF(num,w,bits){var naf=new Array(Math.max(num.bitLength(),bits)+1);naf.fill(0);for(var ws=1<(ws>>1)-1?(ws>>1)-mod:mod,k.isubn(z)):z=0,naf[i]=z,k.iushrn(1)}return naf},utils.getJSF=function getJSF(k1,k2){var jsf=[[],[]];k1=k1.clone(),k2=k2.clone();for(var m8,d1=0,d2=0;k1.cmpn(-d1)>0||k2.cmpn(-d2)>0;){var u1,u2,m14=k1.andln(3)+d1&3,m24=k2.andln(3)+d2&3;3===m14&&(m14=-1),3===m24&&(m24=-1),u1=0==(1&m14)?0:3!==(m8=k1.andln(7)+d1&7)&&5!==m8||2!==m24?m14:-m14,jsf[0].push(u1),u2=0==(1&m24)?0:3!==(m8=k2.andln(7)+d2&7)&&5!==m8||2!==m14?m24:-m24,jsf[1].push(u2),2*d1===u1+1&&(d1=1-d1),2*d2===u2+1&&(d2=1-d2),k1.iushrn(1),k2.iushrn(1)}return jsf},utils.cachedProperty=function cachedProperty(obj,name,computer){var key="_"+name;obj.prototype[name]=function cachedProperty(){return void 0!==this[key]?this[key]:this[key]=computer.call(this)}},utils.parseBytes=function parseBytes(bytes){return"string"==typeof bytes?utils.toArray(bytes,"hex"):bytes},utils.intFromLE=function intFromLE(bytes){return new(bn_default())(bytes,"hex","le")}})),getNAF=utils_1$1.getNAF,getJSF=utils_1$1.getJSF,assert$1=utils_1$1.assert;function BaseCurve(type,conf){this.type=type,this.p=new(bn_default())(conf.p,16),this.red=conf.prime?bn_default().red(conf.prime):bn_default().mont(this.p),this.zero=new(bn_default())(0).toRed(this.red),this.one=new(bn_default())(1).toRed(this.red),this.two=new(bn_default())(2).toRed(this.red),this.n=conf.n&&new(bn_default())(conf.n,16),this.g=conf.g&&this.pointFromJSON(conf.g,conf.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n?this.n.bitLength():0;var adjustCount=this.n&&this.p.div(this.n);!adjustCount||adjustCount.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}var base=BaseCurve;function BasePoint(curve,type){this.curve=curve,this.type=type,this.precomputed=null}BaseCurve.prototype.point=function point(){throw new Error("Not implemented")},BaseCurve.prototype.validate=function validate(){throw new Error("Not implemented")},BaseCurve.prototype._fixedNafMul=function _fixedNafMul(p,k){assert$1(p.precomputed);var doubles=p._getDoubles(),naf=getNAF(k,1,this._bitLength),I=(1<=j;l--)nafW=(nafW<<1)+naf[l];repr.push(nafW)}for(var a=this.jpoint(null,null,null),b=this.jpoint(null,null,null),i=I;i>0;i--){for(j=0;j=0;i--){for(var l=0;i>=0&&0===naf[i];i--)l++;if(i>=0&&l++,acc=acc.dblp(l),i<0)break;var z=naf[i];assert$1(0!==z),acc="affine"===p.type?z>0?acc.mixedAdd(wnd[z-1>>1]):acc.mixedAdd(wnd[-z-1>>1].neg()):z>0?acc.add(wnd[z-1>>1]):acc.add(wnd[-z-1>>1].neg())}return"affine"===p.type?acc.toP():acc},BaseCurve.prototype._wnafMulAdd=function _wnafMulAdd(defW,points,coeffs,len,jacobianResult){var i,j,p,wndWidth=this._wnafT1,wnd=this._wnafT2,naf=this._wnafT3,max=0;for(i=0;i=1;i-=2){var a=i-1,b=i;if(1===wndWidth[a]&&1===wndWidth[b]){var comb=[points[a],null,null,points[b]];0===points[a].y.cmp(points[b].y)?(comb[1]=points[a].add(points[b]),comb[2]=points[a].toJ().mixedAdd(points[b].neg())):0===points[a].y.cmp(points[b].y.redNeg())?(comb[1]=points[a].toJ().mixedAdd(points[b]),comb[2]=points[a].add(points[b].neg())):(comb[1]=points[a].toJ().mixedAdd(points[b]),comb[2]=points[a].toJ().mixedAdd(points[b].neg()));var index=[-3,-1,-5,-7,0,7,5,1,3],jsf=getJSF(coeffs[a],coeffs[b]);for(max=Math.max(jsf[0].length,max),naf[a]=new Array(max),naf[b]=new Array(max),j=0;j=0;i--){for(var k=0;i>=0;){var zero=!0;for(j=0;j=0&&k++,acc=acc.dblp(k),i<0)break;for(j=0;j0?p=wnd[j][z-1>>1]:z<0&&(p=wnd[j][-z-1>>1].neg()),acc="affine"===p.type?acc.mixedAdd(p):acc.add(p))}}for(i=0;i=Math.ceil((k.bitLength()+1)/doubles.step)},BasePoint.prototype._getDoubles=function _getDoubles(step,power){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var doubles=[this],acc=this,i=0;i=0&&(a2=a0,b2=b0),a1.negative&&(a1=a1.neg(),b1=b1.neg()),a2.negative&&(a2=a2.neg(),b2=b2.neg()),[{a:a1,b:b1},{a:a2,b:b2}]},ShortCurve.prototype._endoSplit=function _endoSplit(k){var basis=this.endo.basis,v1=basis[0],v2=basis[1],c1=v2.b.mul(k).divRound(this.n),c2=v1.b.neg().mul(k).divRound(this.n),p1=c1.mul(v1.a),p2=c2.mul(v2.a),q1=c1.mul(v1.b),q2=c2.mul(v2.b);return{k1:k.sub(p1).sub(p2),k2:q1.add(q2).neg()}},ShortCurve.prototype.pointFromX=function pointFromX(x,odd){(x=new(bn_default())(x,16)).red||(x=x.toRed(this.red));var y2=x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b),y=y2.redSqrt();if(0!==y.redSqr().redSub(y2).cmp(this.zero))throw new Error("invalid point");var isOdd=y.fromRed().isOdd();return(odd&&!isOdd||!odd&&isOdd)&&(y=y.redNeg()),this.point(x,y)},ShortCurve.prototype.validate=function validate(point){if(point.inf)return!0;var x=point.x,y=point.y,ax=this.a.redMul(x),rhs=x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);return 0===y.redSqr().redISub(rhs).cmpn(0)},ShortCurve.prototype._endoWnafMulAdd=function _endoWnafMulAdd(points,coeffs,jacobianResult){for(var npoints=this._endoWnafT1,ncoeffs=this._endoWnafT2,i=0;i":""},Point.prototype.isInfinity=function isInfinity(){return this.inf},Point.prototype.add=function add(p){if(this.inf)return p;if(p.inf)return this;if(this.eq(p))return this.dbl();if(this.neg().eq(p))return this.curve.point(null,null);if(0===this.x.cmp(p.x))return this.curve.point(null,null);var c=this.y.redSub(p.y);0!==c.cmpn(0)&&(c=c.redMul(this.x.redSub(p.x).redInvm()));var nx=c.redSqr().redISub(this.x).redISub(p.x),ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)},Point.prototype.dbl=function dbl(){if(this.inf)return this;var ys1=this.y.redAdd(this.y);if(0===ys1.cmpn(0))return this.curve.point(null,null);var a=this.curve.a,x2=this.x.redSqr(),dyinv=ys1.redInvm(),c=x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv),nx=c.redSqr().redISub(this.x.redAdd(this.x)),ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)},Point.prototype.getX=function getX(){return this.x.fromRed()},Point.prototype.getY=function getY(){return this.y.fromRed()},Point.prototype.mul=function mul(k){return k=new(bn_default())(k,16),this.isInfinity()?this:this._hasDoubles(k)?this.curve._fixedNafMul(this,k):this.curve.endo?this.curve._endoWnafMulAdd([this],[k]):this.curve._wnafMul(this,k)},Point.prototype.mulAdd=function mulAdd(k1,p2,k2){var points=[this,p2],coeffs=[k1,k2];return this.curve.endo?this.curve._endoWnafMulAdd(points,coeffs):this.curve._wnafMulAdd(1,points,coeffs,2)},Point.prototype.jmulAdd=function jmulAdd(k1,p2,k2){var points=[this,p2],coeffs=[k1,k2];return this.curve.endo?this.curve._endoWnafMulAdd(points,coeffs,!0):this.curve._wnafMulAdd(1,points,coeffs,2,!0)},Point.prototype.eq=function eq(p){return this===p||this.inf===p.inf&&(this.inf||0===this.x.cmp(p.x)&&0===this.y.cmp(p.y))},Point.prototype.neg=function neg(_precompute){if(this.inf)return this;var res=this.curve.point(this.x,this.y.redNeg());if(_precompute&&this.precomputed){var pre=this.precomputed,negate=function(p){return p.neg()};res.precomputed={naf:pre.naf&&{wnd:pre.naf.wnd,points:pre.naf.points.map(negate)},doubles:pre.doubles&&{step:pre.doubles.step,points:pre.doubles.points.map(negate)}}}return res},Point.prototype.toJ=function toJ(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},inherits_browser(JPoint,base.BasePoint),ShortCurve.prototype.jpoint=function jpoint(x,y,z){return new JPoint(this,x,y,z)},JPoint.prototype.toP=function toP(){if(this.isInfinity())return this.curve.point(null,null);var zinv=this.z.redInvm(),zinv2=zinv.redSqr(),ax=this.x.redMul(zinv2),ay=this.y.redMul(zinv2).redMul(zinv);return this.curve.point(ax,ay)},JPoint.prototype.neg=function neg(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},JPoint.prototype.add=function add(p){if(this.isInfinity())return p;if(p.isInfinity())return this;var pz2=p.z.redSqr(),z2=this.z.redSqr(),u1=this.x.redMul(pz2),u2=p.x.redMul(z2),s1=this.y.redMul(pz2.redMul(p.z)),s2=p.y.redMul(z2.redMul(this.z)),h=u1.redSub(u2),r=s1.redSub(s2);if(0===h.cmpn(0))return 0!==r.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h2=h.redSqr(),h3=h2.redMul(h),v=u1.redMul(h2),nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v),ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)),nz=this.z.redMul(p.z).redMul(h);return this.curve.jpoint(nx,ny,nz)},JPoint.prototype.mixedAdd=function mixedAdd(p){if(this.isInfinity())return p.toJ();if(p.isInfinity())return this;var z2=this.z.redSqr(),u1=this.x,u2=p.x.redMul(z2),s1=this.y,s2=p.y.redMul(z2).redMul(this.z),h=u1.redSub(u2),r=s1.redSub(s2);if(0===h.cmpn(0))return 0!==r.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h2=h.redSqr(),h3=h2.redMul(h),v=u1.redMul(h2),nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v),ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)),nz=this.z.redMul(h);return this.curve.jpoint(nx,ny,nz)},JPoint.prototype.dblp=function dblp(pow){if(0===pow)return this;if(this.isInfinity())return this;if(!pow)return this.dbl();var i;if(this.curve.zeroA||this.curve.threeA){var r=this;for(i=0;i=0)return!1;if(rx.redIAdd(t),0===this.x.cmp(rx))return!0}},JPoint.prototype.inspect=function inspect(){return this.isInfinity()?"":""},JPoint.prototype.isInfinity=function isInfinity(){return 0===this.z.cmpn(0)};var curve_1=createCommonjsModule((function(module,exports){var curve=exports;curve.base=base,curve.short=short_1,curve.mont=null,curve.edwards=null})),curves_1=createCommonjsModule((function(module,exports){var pre,curves=exports,assert=utils_1$1.assert;function PresetCurve(options){"short"===options.type?this.curve=new curve_1.short(options):"edwards"===options.type?this.curve=new curve_1.edwards(options):this.curve=new curve_1.mont(options),this.g=this.curve.g,this.n=this.curve.n,this.hash=options.hash,assert(this.g.validate(),"Invalid curve"),assert(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}function defineCurve(name,options){Object.defineProperty(curves,name,{configurable:!0,enumerable:!0,get:function(){var curve=new PresetCurve(options);return Object.defineProperty(curves,name,{configurable:!0,enumerable:!0,value:curve}),curve}})}curves.PresetCurve=PresetCurve,defineCurve("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:hash_default().sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),defineCurve("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:hash_default().sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),defineCurve("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:hash_default().sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),defineCurve("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:hash_default().sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),defineCurve("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:hash_default().sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),defineCurve("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:hash_default().sha256,gRed:!1,g:["9"]}),defineCurve("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:hash_default().sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});try{pre=null.crash()}catch(e){pre=void 0}defineCurve("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:hash_default().sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",pre]})}));function HmacDRBG(options){if(!(this instanceof HmacDRBG))return new HmacDRBG(options);this.hash=options.hash,this.predResist=!!options.predResist,this.outLen=this.hash.outSize,this.minEntropy=options.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var entropy=utils_1.toArray(options.entropy,options.entropyEnc||"hex"),nonce=utils_1.toArray(options.nonce,options.nonceEnc||"hex"),pers=utils_1.toArray(options.pers,options.persEnc||"hex");minimalisticAssert(entropy.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(entropy,nonce,pers)}var hmacDrbg=HmacDRBG;HmacDRBG.prototype._init=function init(entropy,nonce,pers){var seed=entropy.concat(nonce).concat(pers);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(entropy.concat(add||[])),this._reseed=1},HmacDRBG.prototype.generate=function generate(len,enc,add,addEnc){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof enc&&(addEnc=add,add=enc,enc=null),add&&(add=utils_1.toArray(add,addEnc||"hex"),this._update(add));for(var temp=[];temp.length"};var assert$4=utils_1$1.assert;function Signature(options,enc){if(options instanceof Signature)return options;this._importDER(options,enc)||(assert$4(options.r&&options.s,"Signature without r or s"),this.r=new(bn_default())(options.r,16),this.s=new(bn_default())(options.s,16),void 0===options.recoveryParam?this.recoveryParam=null:this.recoveryParam=options.recoveryParam)}var signature=Signature;function Position(){this.place=0}function getLength(buf,p){var initial=buf[p.place++];if(!(128&initial))return initial;var octetLen=15&initial;if(0===octetLen||octetLen>4)return!1;for(var val=0,i=0,off=p.place;i>>=0;return!(val<=127)&&(p.place=off,val)}function rmPadding(buf){for(var i=0,len=buf.length-1;!buf[i]&&!(128&buf[i+1])&&i>>3);for(arr.push(128|octets);--octets;)arr.push(len>>>(octets<<3)&255);arr.push(len)}}Signature.prototype._importDER=function _importDER(data,enc){data=utils_1$1.toArray(data,enc);var p=new Position;if(48!==data[p.place++])return!1;var len=getLength(data,p);if(!1===len)return!1;if(len+p.place!==data.length)return!1;if(2!==data[p.place++])return!1;var rlen=getLength(data,p);if(!1===rlen)return!1;var r=data.slice(p.place,rlen+p.place);if(p.place+=rlen,2!==data[p.place++])return!1;var slen=getLength(data,p);if(!1===slen)return!1;if(data.length!==slen+p.place)return!1;var s=data.slice(p.place,slen+p.place);if(0===r[0]){if(!(128&r[1]))return!1;r=r.slice(1)}if(0===s[0]){if(!(128&s[1]))return!1;s=s.slice(1)}return this.r=new(bn_default())(r),this.s=new(bn_default())(s),this.recoveryParam=null,!0},Signature.prototype.toDER=function toDER(enc){var r=this.r.toArray(),s=this.s.toArray();for(128&r[0]&&(r=[0].concat(r)),128&s[0]&&(s=[0].concat(s)),r=rmPadding(r),s=rmPadding(s);!(s[0]||128&s[1]);)s=s.slice(1);var arr=[2];constructLength(arr,r.length),(arr=arr.concat(r)).push(2),constructLength(arr,s.length);var backHalf=arr.concat(s),res=[48];return constructLength(res,backHalf.length),res=res.concat(backHalf),utils_1$1.encode(res,enc)};var rand=function(){throw new Error("unsupported")},assert$5=utils_1$1.assert;function EC(options){if(!(this instanceof EC))return new EC(options);"string"==typeof options&&(assert$5(Object.prototype.hasOwnProperty.call(curves_1,options),"Unknown curve "+options),options=curves_1[options]),options instanceof curves_1.PresetCurve&&(options={curve:options}),this.curve=options.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=options.curve.g,this.g.precompute(options.curve.n.bitLength()+1),this.hash=options.hash||options.curve.hash}var ec=EC;EC.prototype.keyPair=function keyPair(options){return new key(this,options)},EC.prototype.keyFromPrivate=function keyFromPrivate(priv,enc){return key.fromPrivate(this,priv,enc)},EC.prototype.keyFromPublic=function keyFromPublic(pub,enc){return key.fromPublic(this,pub,enc)},EC.prototype.genKeyPair=function genKeyPair(options){options||(options={});for(var drbg=new hmacDrbg({hash:this.hash,pers:options.pers,persEnc:options.persEnc||"utf8",entropy:options.entropy||rand(this.hash.hmacStrength),entropyEnc:options.entropy&&options.entropyEnc||"utf8",nonce:this.n.toArray()}),bytes=this.n.byteLength(),ns2=this.n.sub(new(bn_default())(2));;){var priv=new(bn_default())(drbg.generate(bytes));if(!(priv.cmp(ns2)>0))return priv.iaddn(1),this.keyFromPrivate(priv)}},EC.prototype._truncateToN=function _truncateToN(msg,truncOnly){var delta=8*msg.byteLength()-this.n.bitLength();return delta>0&&(msg=msg.ushrn(delta)),!truncOnly&&msg.cmp(this.n)>=0?msg.sub(this.n):msg},EC.prototype.sign=function sign(msg,key,enc,options){"object"==typeof enc&&(options=enc,enc=null),options||(options={}),key=this.keyFromPrivate(key,enc),msg=this._truncateToN(new(bn_default())(msg,16));for(var bytes=this.n.byteLength(),bkey=key.getPrivate().toArray("be",bytes),nonce=msg.toArray("be",bytes),drbg=new hmacDrbg({hash:this.hash,entropy:bkey,nonce,pers:options.pers,persEnc:options.persEnc||"utf8"}),ns1=this.n.sub(new(bn_default())(1)),iter=0;;iter++){var k=options.k?options.k(iter):new(bn_default())(drbg.generate(this.n.byteLength()));if(!((k=this._truncateToN(k,!0)).cmpn(1)<=0||k.cmp(ns1)>=0)){var kp=this.g.mul(k);if(!kp.isInfinity()){var kpX=kp.getX(),r=kpX.umod(this.n);if(0!==r.cmpn(0)){var s=k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));if(0!==(s=s.umod(this.n)).cmpn(0)){var recoveryParam=(kp.getY().isOdd()?1:0)|(0!==kpX.cmp(r)?2:0);return options.canonical&&s.cmp(this.nh)>0&&(s=this.n.sub(s),recoveryParam^=1),new signature({r,s,recoveryParam})}}}}}},EC.prototype.verify=function verify(msg,signature$1,key,enc){msg=this._truncateToN(new(bn_default())(msg,16)),key=this.keyFromPublic(key,enc);var r=(signature$1=new signature(signature$1,"hex")).r,s=signature$1.s;if(r.cmpn(1)<0||r.cmp(this.n)>=0)return!1;if(s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var p,sinv=s.invm(this.n),u1=sinv.mul(msg).umod(this.n),u2=sinv.mul(r).umod(this.n);return this.curve._maxwellTrick?!(p=this.g.jmulAdd(u1,key.getPublic(),u2)).isInfinity()&&p.eqXToP(r):!(p=this.g.mulAdd(u1,key.getPublic(),u2)).isInfinity()&&0===p.getX().umod(this.n).cmp(r)},EC.prototype.recoverPubKey=function(msg,signature$1,j,enc){assert$5((3&j)===j,"The recovery param is more than two bits"),signature$1=new signature(signature$1,enc);var n=this.n,e=new(bn_default())(msg),r=signature$1.r,s=signature$1.s,isYOdd=1&j,isSecondKey=j>>1;if(r.cmp(this.curve.p.umod(this.curve.n))>=0&&isSecondKey)throw new Error("Unable to find sencond key candinate");r=isSecondKey?this.curve.pointFromX(r.add(this.curve.n),isYOdd):this.curve.pointFromX(r,isYOdd);var rInv=signature$1.r.invm(n),s1=n.sub(e).mul(rInv).umod(n),s2=s.mul(rInv).umod(n);return this.g.mulAdd(s1,r,s2)},EC.prototype.getKeyRecoveryParam=function(e,signature$1,Q,enc){if(null!==(signature$1=new signature(signature$1,enc)).recoveryParam)return signature$1.recoveryParam;for(var i=0;i<4;i++){var Qprime;try{Qprime=this.recoverPubKey(e,signature$1,i)}catch(e){continue}if(Qprime.eq(Q))return i}throw new Error("Unable to find valid recovery factor")};var EC$1=createCommonjsModule((function(module,exports){var elliptic=exports;elliptic.version="6.5.4",elliptic.utils=utils_1$1,elliptic.rand=function(){throw new Error("unsupported")},elliptic.curve=curve_1,elliptic.curves=curves_1,elliptic.ec=ec,elliptic.eddsa=null})).ec;const signing_key_lib_esm_logger=new Logger("signing-key/5.7.0");let _curve=null;function getCurve(){return _curve||(_curve=new EC$1("secp256k1")),_curve}class SigningKey{constructor(privateKey){defineReadOnly(this,"curve","secp256k1"),defineReadOnly(this,"privateKey",hexlify(privateKey)),32!==hexDataLength(this.privateKey)&&signing_key_lib_esm_logger.throwArgumentError("invalid private key","privateKey","[[ REDACTED ]]");const keyPair=getCurve().keyFromPrivate(arrayify(this.privateKey));defineReadOnly(this,"publicKey","0x"+keyPair.getPublic(!1,"hex")),defineReadOnly(this,"compressedPublicKey","0x"+keyPair.getPublic(!0,"hex")),defineReadOnly(this,"_isSigningKey",!0)}_addPoint(other){const p0=getCurve().keyFromPublic(arrayify(this.publicKey)),p1=getCurve().keyFromPublic(arrayify(other));return"0x"+p0.pub.add(p1.pub).encodeCompressed("hex")}signDigest(digest){const keyPair=getCurve().keyFromPrivate(arrayify(this.privateKey)),digestBytes=arrayify(digest);32!==digestBytes.length&&signing_key_lib_esm_logger.throwArgumentError("bad digest length","digest",digest);const signature=keyPair.sign(digestBytes,{canonical:!0});return splitSignature({recoveryParam:signature.recoveryParam,r:hexZeroPad("0x"+signature.r.toString(16),32),s:hexZeroPad("0x"+signature.s.toString(16),32)})}computeSharedSecret(otherKey){const keyPair=getCurve().keyFromPrivate(arrayify(this.privateKey)),otherKeyPair=getCurve().keyFromPublic(arrayify(computePublicKey(otherKey)));return hexZeroPad("0x"+keyPair.derive(otherKeyPair.getPublic()).toString(16),32)}static isSigningKey(value){return!(!value||!value._isSigningKey)}}function recoverPublicKey(digest,signature){const sig=splitSignature(signature),rs={r:arrayify(sig.r),s:arrayify(sig.s)};return"0x"+getCurve().recoverPubKey(arrayify(digest),rs,sig.recoveryParam).encode("hex",!1)}function computePublicKey(key,compressed){const bytes=arrayify(key);if(32===bytes.length){const signingKey=new SigningKey(bytes);return compressed?"0x"+getCurve().keyFromPrivate(bytes).getPublic(!0,"hex"):signingKey.publicKey}return 33===bytes.length?compressed?hexlify(bytes):"0x"+getCurve().keyFromPublic(bytes).getPublic(!1,"hex"):65===bytes.length?compressed?"0x"+getCurve().keyFromPublic(bytes).getPublic(!0,"hex"):hexlify(bytes):signing_key_lib_esm_logger.throwArgumentError("invalid public or private key","key","[REDACTED]")}const transactions_lib_esm_logger=new Logger("transactions/5.7.0");var TransactionTypes;function handleAddress(value){return"0x"===value?null:getAddress(value)}function handleNumber(value){return"0x"===value?Zero:BigNumber.from(value)}!function(TransactionTypes){TransactionTypes[TransactionTypes.legacy=0]="legacy",TransactionTypes[TransactionTypes.eip2930=1]="eip2930",TransactionTypes[TransactionTypes.eip1559=2]="eip1559"}(TransactionTypes||(TransactionTypes={}));const transactionFields=[{name:"nonce",maxLength:32,numeric:!0},{name:"gasPrice",maxLength:32,numeric:!0},{name:"gasLimit",maxLength:32,numeric:!0},{name:"to",length:20},{name:"value",maxLength:32,numeric:!0},{name:"data"}],lib_esm_allowedTransactionKeys={chainId:!0,data:!0,gasLimit:!0,gasPrice:!0,nonce:!0,to:!0,type:!0,value:!0};function computeAddress(key){return getAddress(hexDataSlice(keccak256(hexDataSlice(computePublicKey(key),1)),12))}function recoverAddress(digest,signature){return computeAddress(recoverPublicKey(arrayify(digest),signature))}function formatNumber(value,name){const result=stripZeros(BigNumber.from(value).toHexString());return result.length>32&&transactions_lib_esm_logger.throwArgumentError("invalid length for "+name,"transaction:"+name,value),result}function accessSetify(addr,storageKeys){return{address:getAddress(addr),storageKeys:(storageKeys||[]).map(((storageKey,index)=>(32!==hexDataLength(storageKey)&&transactions_lib_esm_logger.throwArgumentError("invalid access list storageKey",`accessList[${addr}:${index}]`,storageKey),storageKey.toLowerCase())))}}function accessListify(value){if(Array.isArray(value))return value.map(((set,index)=>Array.isArray(set)?(set.length>2&&transactions_lib_esm_logger.throwArgumentError("access list expected to be [ address, storageKeys[] ]",`value[${index}]`,set),accessSetify(set[0],set[1])):accessSetify(set.address,set.storageKeys)));const result=Object.keys(value).map((addr=>{const storageKeys=value[addr].reduce(((accum,storageKey)=>(accum[storageKey]=!0,accum)),{});return accessSetify(addr,Object.keys(storageKeys).sort())}));return result.sort(((a,b)=>a.address.localeCompare(b.address))),result}function formatAccessList(value){return accessListify(value).map((set=>[set.address,set.storageKeys]))}function _serializeEip1559(transaction,signature){if(null!=transaction.gasPrice){const gasPrice=BigNumber.from(transaction.gasPrice),maxFeePerGas=BigNumber.from(transaction.maxFeePerGas||0);gasPrice.eq(maxFeePerGas)||transactions_lib_esm_logger.throwArgumentError("mismatch EIP-1559 gasPrice != maxFeePerGas","tx",{gasPrice,maxFeePerGas})}const fields=[formatNumber(transaction.chainId||0,"chainId"),formatNumber(transaction.nonce||0,"nonce"),formatNumber(transaction.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),formatNumber(transaction.maxFeePerGas||0,"maxFeePerGas"),formatNumber(transaction.gasLimit||0,"gasLimit"),null!=transaction.to?getAddress(transaction.to):"0x",formatNumber(transaction.value||0,"value"),transaction.data||"0x",formatAccessList(transaction.accessList||[])];if(signature){const sig=splitSignature(signature);fields.push(formatNumber(sig.recoveryParam,"recoveryParam")),fields.push(stripZeros(sig.r)),fields.push(stripZeros(sig.s))}return hexConcat(["0x02",encode(fields)])}function _serializeEip2930(transaction,signature){const fields=[formatNumber(transaction.chainId||0,"chainId"),formatNumber(transaction.nonce||0,"nonce"),formatNumber(transaction.gasPrice||0,"gasPrice"),formatNumber(transaction.gasLimit||0,"gasLimit"),null!=transaction.to?getAddress(transaction.to):"0x",formatNumber(transaction.value||0,"value"),transaction.data||"0x",formatAccessList(transaction.accessList||[])];if(signature){const sig=splitSignature(signature);fields.push(formatNumber(sig.recoveryParam,"recoveryParam")),fields.push(stripZeros(sig.r)),fields.push(stripZeros(sig.s))}return hexConcat(["0x01",encode(fields)])}function serialize(transaction,signature){if(null==transaction.type||0===transaction.type)return null!=transaction.accessList&&transactions_lib_esm_logger.throwArgumentError("untyped transactions do not support accessList; include type: 1","transaction",transaction),function _serialize(transaction,signature){checkProperties(transaction,lib_esm_allowedTransactionKeys);const raw=[];transactionFields.forEach((function(fieldInfo){let value=transaction[fieldInfo.name]||[];const options={};fieldInfo.numeric&&(options.hexPad="left"),value=arrayify(hexlify(value,options)),fieldInfo.length&&value.length!==fieldInfo.length&&value.length>0&&transactions_lib_esm_logger.throwArgumentError("invalid length for "+fieldInfo.name,"transaction:"+fieldInfo.name,value),fieldInfo.maxLength&&(value=stripZeros(value),value.length>fieldInfo.maxLength&&transactions_lib_esm_logger.throwArgumentError("invalid length for "+fieldInfo.name,"transaction:"+fieldInfo.name,value)),raw.push(hexlify(value))}));let chainId=0;if(null!=transaction.chainId?(chainId=transaction.chainId,"number"!=typeof chainId&&transactions_lib_esm_logger.throwArgumentError("invalid transaction.chainId","transaction",transaction)):signature&&!isBytesLike(signature)&&signature.v>28&&(chainId=Math.floor((signature.v-35)/2)),0!==chainId&&(raw.push(hexlify(chainId)),raw.push("0x"),raw.push("0x")),!signature)return encode(raw);const sig=splitSignature(signature);let v=27+sig.recoveryParam;return 0!==chainId?(raw.pop(),raw.pop(),raw.pop(),v+=2*chainId+8,sig.v>28&&sig.v!==v&&transactions_lib_esm_logger.throwArgumentError("transaction.chainId/signature.v mismatch","signature",signature)):sig.v!==v&&transactions_lib_esm_logger.throwArgumentError("transaction.chainId/signature.v mismatch","signature",signature),raw.push(hexlify(v)),raw.push(stripZeros(arrayify(sig.r))),raw.push(stripZeros(arrayify(sig.s))),encode(raw)}(transaction,signature);switch(transaction.type){case 1:return _serializeEip2930(transaction,signature);case 2:return _serializeEip1559(transaction,signature)}return transactions_lib_esm_logger.throwError(`unsupported transaction type: ${transaction.type}`,Logger.errors.UNSUPPORTED_OPERATION,{operation:"serializeTransaction",transactionType:transaction.type})}function _parseEipSignature(tx,fields,serialize){try{const recid=handleNumber(fields[0]).toNumber();if(0!==recid&&1!==recid)throw new Error("bad recid");tx.v=recid}catch(error){transactions_lib_esm_logger.throwArgumentError("invalid v for transaction type: 1","v",fields[0])}tx.r=hexZeroPad(fields[1],32),tx.s=hexZeroPad(fields[2],32);try{const digest=keccak256(serialize(tx));tx.from=recoverAddress(digest,{r:tx.r,s:tx.s,recoveryParam:tx.v})}catch(error){}}function parse(rawTransaction){const payload=arrayify(rawTransaction);if(payload[0]>127)return function _parse(rawTransaction){const transaction=decode(rawTransaction);9!==transaction.length&&6!==transaction.length&&transactions_lib_esm_logger.throwArgumentError("invalid raw transaction","rawTransaction",rawTransaction);const tx={nonce:handleNumber(transaction[0]).toNumber(),gasPrice:handleNumber(transaction[1]),gasLimit:handleNumber(transaction[2]),to:handleAddress(transaction[3]),value:handleNumber(transaction[4]),data:transaction[5],chainId:0};if(6===transaction.length)return tx;try{tx.v=BigNumber.from(transaction[6]).toNumber()}catch(error){return tx}if(tx.r=hexZeroPad(transaction[7],32),tx.s=hexZeroPad(transaction[8],32),BigNumber.from(tx.r).isZero()&&BigNumber.from(tx.s).isZero())tx.chainId=tx.v,tx.v=0;else{tx.chainId=Math.floor((tx.v-35)/2),tx.chainId<0&&(tx.chainId=0);let recoveryParam=tx.v-27;const raw=transaction.slice(0,6);0!==tx.chainId&&(raw.push(hexlify(tx.chainId)),raw.push("0x"),raw.push("0x"),recoveryParam-=2*tx.chainId+8);const digest=keccak256(encode(raw));try{tx.from=recoverAddress(digest,{r:hexlify(tx.r),s:hexlify(tx.s),recoveryParam})}catch(error){}tx.hash=keccak256(rawTransaction)}return tx.type=null,tx}(payload);switch(payload[0]){case 1:return function _parseEip2930(payload){const transaction=decode(payload.slice(1));8!==transaction.length&&11!==transaction.length&&transactions_lib_esm_logger.throwArgumentError("invalid component count for transaction type: 1","payload",hexlify(payload));const tx={type:1,chainId:handleNumber(transaction[0]).toNumber(),nonce:handleNumber(transaction[1]).toNumber(),gasPrice:handleNumber(transaction[2]),gasLimit:handleNumber(transaction[3]),to:handleAddress(transaction[4]),value:handleNumber(transaction[5]),data:transaction[6],accessList:accessListify(transaction[7])};return 8===transaction.length||(tx.hash=keccak256(payload),_parseEipSignature(tx,transaction.slice(8),_serializeEip2930)),tx}(payload);case 2:return function _parseEip1559(payload){const transaction=decode(payload.slice(1));9!==transaction.length&&12!==transaction.length&&transactions_lib_esm_logger.throwArgumentError("invalid component count for transaction type: 2","payload",hexlify(payload));const maxPriorityFeePerGas=handleNumber(transaction[2]),maxFeePerGas=handleNumber(transaction[3]),tx={type:2,chainId:handleNumber(transaction[0]).toNumber(),nonce:handleNumber(transaction[1]).toNumber(),maxPriorityFeePerGas,maxFeePerGas,gasPrice:null,gasLimit:handleNumber(transaction[4]),to:handleAddress(transaction[5]),value:handleNumber(transaction[6]),data:transaction[7],accessList:accessListify(transaction[8])};return 9===transaction.length||(tx.hash=keccak256(payload),_parseEipSignature(tx,transaction.slice(9),_serializeEip1559)),tx}(payload)}return transactions_lib_esm_logger.throwError(`unsupported transaction type: ${payload[0]}`,Logger.errors.UNSUPPORTED_OPERATION,{operation:"parseTransaction",transactionType:payload[0]})}var contracts_lib_esm_awaiter=function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};const contracts_lib_esm_logger=new Logger("contracts/5.7.0"),contracts_lib_esm_allowedTransactionKeys={chainId:!0,data:!0,from:!0,gasLimit:!0,gasPrice:!0,nonce:!0,to:!0,value:!0,type:!0,accessList:!0,maxFeePerGas:!0,maxPriorityFeePerGas:!0,customData:!0,ccipReadEnabled:!0};function resolveName(resolver,nameOrPromise){return contracts_lib_esm_awaiter(this,void 0,void 0,(function*(){const name=yield nameOrPromise;"string"!=typeof name&&contracts_lib_esm_logger.throwArgumentError("invalid address or ENS name","name",name);try{return getAddress(name)}catch(error){}resolver||contracts_lib_esm_logger.throwError("a provider or signer is needed to resolve ENS names",Logger.errors.UNSUPPORTED_OPERATION,{operation:"resolveName"});const address=yield resolver.resolveName(name);return null==address&&contracts_lib_esm_logger.throwArgumentError("resolver or addr is not configured for ENS name","name",name),address}))}function resolveAddresses(resolver,value,paramType){return contracts_lib_esm_awaiter(this,void 0,void 0,(function*(){return Array.isArray(paramType)?yield Promise.all(paramType.map(((paramType,index)=>resolveAddresses(resolver,Array.isArray(value)?value[index]:value[paramType.name],paramType)))):"address"===paramType.type?yield resolveName(resolver,value):"tuple"===paramType.type?yield resolveAddresses(resolver,value,paramType.components):"array"===paramType.baseType?Array.isArray(value)?yield Promise.all(value.map((v=>resolveAddresses(resolver,v,paramType.arrayChildren)))):Promise.reject(contracts_lib_esm_logger.makeError("invalid value for array",Logger.errors.INVALID_ARGUMENT,{argument:"value",value})):value}))}function populateTransaction(contract,fragment,args){return contracts_lib_esm_awaiter(this,void 0,void 0,(function*(){let overrides={};args.length===fragment.inputs.length+1&&"object"==typeof args[args.length-1]&&(overrides=shallowCopy(args.pop())),contracts_lib_esm_logger.checkArgumentCount(args.length,fragment.inputs.length,"passed to contract"),contract.signer?overrides.from?overrides.from=resolveProperties({override:resolveName(contract.signer,overrides.from),signer:contract.signer.getAddress()}).then((check=>contracts_lib_esm_awaiter(this,void 0,void 0,(function*(){return getAddress(check.signer)!==check.override&&contracts_lib_esm_logger.throwError("Contract with a Signer cannot override from",Logger.errors.UNSUPPORTED_OPERATION,{operation:"overrides.from"}),check.override})))):overrides.from=contract.signer.getAddress():overrides.from&&(overrides.from=resolveName(contract.provider,overrides.from));const resolved=yield resolveProperties({args:resolveAddresses(contract.signer||contract.provider,args,fragment.inputs),address:contract.resolvedAddress,overrides:resolveProperties(overrides)||{}}),data=contract.interface.encodeFunctionData(fragment,resolved.args),tx={data,to:resolved.address},ro=resolved.overrides;if(null!=ro.nonce&&(tx.nonce=BigNumber.from(ro.nonce).toNumber()),null!=ro.gasLimit&&(tx.gasLimit=BigNumber.from(ro.gasLimit)),null!=ro.gasPrice&&(tx.gasPrice=BigNumber.from(ro.gasPrice)),null!=ro.maxFeePerGas&&(tx.maxFeePerGas=BigNumber.from(ro.maxFeePerGas)),null!=ro.maxPriorityFeePerGas&&(tx.maxPriorityFeePerGas=BigNumber.from(ro.maxPriorityFeePerGas)),null!=ro.from&&(tx.from=ro.from),null!=ro.type&&(tx.type=ro.type),null!=ro.accessList&&(tx.accessList=accessListify(ro.accessList)),null==tx.gasLimit&&null!=fragment.gas){let intrinsic=21e3;const bytes=arrayify(data);for(let i=0;inull!=overrides[key]));return leftovers.length&&contracts_lib_esm_logger.throwError(`cannot override ${leftovers.map((l=>JSON.stringify(l))).join(",")}`,Logger.errors.UNSUPPORTED_OPERATION,{operation:"overrides",overrides:leftovers}),tx}))}function addContractWait(contract,tx){const wait=tx.wait.bind(tx);tx.wait=confirmations=>wait(confirmations).then((receipt=>(receipt.events=receipt.logs.map((log=>{let event=deepCopy(log),parsed=null;try{parsed=contract.interface.parseLog(log)}catch(e){}return parsed&&(event.args=parsed.args,event.decode=(data,topics)=>contract.interface.decodeEventLog(parsed.eventFragment,data,topics),event.event=parsed.name,event.eventSignature=parsed.signature),event.removeListener=()=>contract.provider,event.getBlock=()=>contract.provider.getBlock(receipt.blockHash),event.getTransaction=()=>contract.provider.getTransaction(receipt.transactionHash),event.getTransactionReceipt=()=>Promise.resolve(receipt),event})),receipt)))}function buildCall(contract,fragment,collapseSimple){const signerOrProvider=contract.signer||contract.provider;return function(...args){return contracts_lib_esm_awaiter(this,void 0,void 0,(function*(){let blockTag;if(args.length===fragment.inputs.length+1&&"object"==typeof args[args.length-1]){const overrides=shallowCopy(args.pop());null!=overrides.blockTag&&(blockTag=yield overrides.blockTag),delete overrides.blockTag,args.push(overrides)}null!=contract.deployTransaction&&(yield contract._deployed(blockTag));const tx=yield populateTransaction(contract,fragment,args),result=yield signerOrProvider.call(tx,blockTag);try{let value=contract.interface.decodeFunctionResult(fragment,result);return collapseSimple&&1===fragment.outputs.length&&(value=value[0]),value}catch(error){throw error.code===Logger.errors.CALL_EXCEPTION&&(error.address=contract.address,error.args=args,error.transaction=tx),error}}))}}function buildDefault(contract,fragment,collapseSimple){return fragment.constant?buildCall(contract,fragment,collapseSimple):function buildSend(contract,fragment){return function(...args){return contracts_lib_esm_awaiter(this,void 0,void 0,(function*(){contract.signer||contracts_lib_esm_logger.throwError("sending a transaction requires a signer",Logger.errors.UNSUPPORTED_OPERATION,{operation:"sendTransaction"}),null!=contract.deployTransaction&&(yield contract._deployed());const txRequest=yield populateTransaction(contract,fragment,args),tx=yield contract.signer.sendTransaction(txRequest);return addContractWait(contract,tx),tx}))}}(contract,fragment)}function getEventTag(filter){return!filter.address||null!=filter.topics&&0!==filter.topics.length?(filter.address||"*")+"@"+(filter.topics?filter.topics.map((topic=>Array.isArray(topic)?topic.join("|"):topic)).join(":"):""):"*"}class RunningEvent{constructor(tag,filter){defineReadOnly(this,"tag",tag),defineReadOnly(this,"filter",filter),this._listeners=[]}addListener(listener,once){this._listeners.push({listener,once})}removeListener(listener){let done=!1;this._listeners=this._listeners.filter((item=>!(!done&&item.listener===listener)||(done=!0,!1)))}removeAllListeners(){this._listeners=[]}listeners(){return this._listeners.map((i=>i.listener))}listenerCount(){return this._listeners.length}run(args){const listenerCount=this.listenerCount();return this._listeners=this._listeners.filter((item=>{const argsCopy=args.slice();return setTimeout((()=>{item.listener.apply(this,argsCopy)}),0),!item.once})),listenerCount}prepareEvent(event){}getEmit(event){return[event]}}class ErrorRunningEvent extends RunningEvent{constructor(){super("error",null)}}class FragmentRunningEvent extends RunningEvent{constructor(address,contractInterface,fragment,topics){const filter={address};let topic=contractInterface.getEventTopic(fragment);topics?(topic!==topics[0]&&contracts_lib_esm_logger.throwArgumentError("topic mismatch","topics",topics),filter.topics=topics.slice()):filter.topics=[topic],super(getEventTag(filter),filter),defineReadOnly(this,"address",address),defineReadOnly(this,"interface",contractInterface),defineReadOnly(this,"fragment",fragment)}prepareEvent(event){super.prepareEvent(event),event.event=this.fragment.name,event.eventSignature=this.fragment.format(),event.decode=(data,topics)=>this.interface.decodeEventLog(this.fragment,data,topics);try{event.args=this.interface.decodeEventLog(this.fragment,event.data,event.topics)}catch(error){event.args=null,event.decodeError=error}}getEmit(event){const errors=checkResultErrors(event.args);if(errors.length)throw errors[0].error;const args=(event.args||[]).slice();return args.push(event),args}}class WildcardRunningEvent extends RunningEvent{constructor(address,contractInterface){super("*",{address}),defineReadOnly(this,"address",address),defineReadOnly(this,"interface",contractInterface)}prepareEvent(event){super.prepareEvent(event);try{const parsed=this.interface.parseLog(event);event.event=parsed.name,event.eventSignature=parsed.signature,event.decode=(data,topics)=>this.interface.decodeEventLog(parsed.eventFragment,data,topics),event.args=parsed.args}catch(error){}}}class BaseContract{constructor(addressOrName,contractInterface,signerOrProvider){defineReadOnly(this,"interface",getStatic(new.target,"getInterface")(contractInterface)),null==signerOrProvider?(defineReadOnly(this,"provider",null),defineReadOnly(this,"signer",null)):Signer.isSigner(signerOrProvider)?(defineReadOnly(this,"provider",signerOrProvider.provider||null),defineReadOnly(this,"signer",signerOrProvider)):Provider.isProvider(signerOrProvider)?(defineReadOnly(this,"provider",signerOrProvider),defineReadOnly(this,"signer",null)):contracts_lib_esm_logger.throwArgumentError("invalid signer or provider","signerOrProvider",signerOrProvider),defineReadOnly(this,"callStatic",{}),defineReadOnly(this,"estimateGas",{}),defineReadOnly(this,"functions",{}),defineReadOnly(this,"populateTransaction",{}),defineReadOnly(this,"filters",{});{const uniqueFilters={};Object.keys(this.interface.events).forEach((eventSignature=>{const event=this.interface.events[eventSignature];defineReadOnly(this.filters,eventSignature,((...args)=>({address:this.address,topics:this.interface.encodeFilterTopics(event,args)}))),uniqueFilters[event.name]||(uniqueFilters[event.name]=[]),uniqueFilters[event.name].push(eventSignature)})),Object.keys(uniqueFilters).forEach((name=>{const filters=uniqueFilters[name];1===filters.length?defineReadOnly(this.filters,name,this.filters[filters[0]]):contracts_lib_esm_logger.warn(`Duplicate definition of ${name} (${filters.join(", ")})`)}))}if(defineReadOnly(this,"_runningEvents",{}),defineReadOnly(this,"_wrappedEmits",{}),null==addressOrName&&contracts_lib_esm_logger.throwArgumentError("invalid contract address or ENS name","addressOrName",addressOrName),defineReadOnly(this,"address",addressOrName),this.provider)defineReadOnly(this,"resolvedAddress",resolveName(this.provider,addressOrName));else try{defineReadOnly(this,"resolvedAddress",Promise.resolve(getAddress(addressOrName)))}catch(error){contracts_lib_esm_logger.throwError("provider is required to use ENS name as contract address",Logger.errors.UNSUPPORTED_OPERATION,{operation:"new Contract"})}this.resolvedAddress.catch((e=>{}));const uniqueNames={},uniqueSignatures={};Object.keys(this.interface.functions).forEach((signature=>{const fragment=this.interface.functions[signature];if(uniqueSignatures[signature])contracts_lib_esm_logger.warn(`Duplicate ABI entry for ${JSON.stringify(signature)}`);else{uniqueSignatures[signature]=!0;{const name=fragment.name;uniqueNames[`%${name}`]||(uniqueNames[`%${name}`]=[]),uniqueNames[`%${name}`].push(signature)}null==this[signature]&&defineReadOnly(this,signature,buildDefault(this,fragment,!0)),null==this.functions[signature]&&defineReadOnly(this.functions,signature,buildDefault(this,fragment,!1)),null==this.callStatic[signature]&&defineReadOnly(this.callStatic,signature,buildCall(this,fragment,!0)),null==this.populateTransaction[signature]&&defineReadOnly(this.populateTransaction,signature,function buildPopulate(contract,fragment){return function(...args){return populateTransaction(contract,fragment,args)}}(this,fragment)),null==this.estimateGas[signature]&&defineReadOnly(this.estimateGas,signature,function buildEstimate(contract,fragment){const signerOrProvider=contract.signer||contract.provider;return function(...args){return contracts_lib_esm_awaiter(this,void 0,void 0,(function*(){signerOrProvider||contracts_lib_esm_logger.throwError("estimate require a provider or signer",Logger.errors.UNSUPPORTED_OPERATION,{operation:"estimateGas"});const tx=yield populateTransaction(contract,fragment,args);return yield signerOrProvider.estimateGas(tx)}))}}(this,fragment))}})),Object.keys(uniqueNames).forEach((name=>{const signatures=uniqueNames[name];if(signatures.length>1)return;name=name.substring(1);const signature=signatures[0];try{null==this[name]&&defineReadOnly(this,name,this[signature])}catch(e){}null==this.functions[name]&&defineReadOnly(this.functions,name,this.functions[signature]),null==this.callStatic[name]&&defineReadOnly(this.callStatic,name,this.callStatic[signature]),null==this.populateTransaction[name]&&defineReadOnly(this.populateTransaction,name,this.populateTransaction[signature]),null==this.estimateGas[name]&&defineReadOnly(this.estimateGas,name,this.estimateGas[signature])}))}static getContractAddress(transaction){return getContractAddress(transaction)}static getInterface(contractInterface){return Interface.isInterface(contractInterface)?contractInterface:new Interface(contractInterface)}deployed(){return this._deployed()}_deployed(blockTag){return this._deployedPromise||(this.deployTransaction?this._deployedPromise=this.deployTransaction.wait().then((()=>this)):this._deployedPromise=this.provider.getCode(this.address,blockTag).then((code=>("0x"===code&&contracts_lib_esm_logger.throwError("contract not deployed",Logger.errors.UNSUPPORTED_OPERATION,{contractAddress:this.address,operation:"getDeployed"}),this)))),this._deployedPromise}fallback(overrides){this.signer||contracts_lib_esm_logger.throwError("sending a transactions require a signer",Logger.errors.UNSUPPORTED_OPERATION,{operation:"sendTransaction(fallback)"});const tx=shallowCopy(overrides||{});return["from","to"].forEach((function(key){null!=tx[key]&&contracts_lib_esm_logger.throwError("cannot override "+key,Logger.errors.UNSUPPORTED_OPERATION,{operation:key})})),tx.to=this.resolvedAddress,this.deployed().then((()=>this.signer.sendTransaction(tx)))}connect(signerOrProvider){"string"==typeof signerOrProvider&&(signerOrProvider=new VoidSigner(signerOrProvider,this.provider));const contract=new this.constructor(this.address,this.interface,signerOrProvider);return this.deployTransaction&&defineReadOnly(contract,"deployTransaction",this.deployTransaction),contract}attach(addressOrName){return new this.constructor(addressOrName,this.interface,this.signer||this.provider)}static isIndexed(value){return Indexed.isIndexed(value)}_normalizeRunningEvent(runningEvent){return this._runningEvents[runningEvent.tag]?this._runningEvents[runningEvent.tag]:runningEvent}_getRunningEvent(eventName){if("string"==typeof eventName){if("error"===eventName)return this._normalizeRunningEvent(new ErrorRunningEvent);if("event"===eventName)return this._normalizeRunningEvent(new RunningEvent("event",null));if("*"===eventName)return this._normalizeRunningEvent(new WildcardRunningEvent(this.address,this.interface));const fragment=this.interface.getEvent(eventName);return this._normalizeRunningEvent(new FragmentRunningEvent(this.address,this.interface,fragment))}if(eventName.topics&&eventName.topics.length>0){try{const topic=eventName.topics[0];if("string"!=typeof topic)throw new Error("invalid topic");const fragment=this.interface.getEvent(topic);return this._normalizeRunningEvent(new FragmentRunningEvent(this.address,this.interface,fragment,eventName.topics))}catch(error){}const filter={address:this.address,topics:eventName.topics};return this._normalizeRunningEvent(new RunningEvent(getEventTag(filter),filter))}return this._normalizeRunningEvent(new WildcardRunningEvent(this.address,this.interface))}_checkRunningEvents(runningEvent){if(0===runningEvent.listenerCount()){delete this._runningEvents[runningEvent.tag];const emit=this._wrappedEmits[runningEvent.tag];emit&&runningEvent.filter&&(this.provider.off(runningEvent.filter,emit),delete this._wrappedEmits[runningEvent.tag])}}_wrapEvent(runningEvent,log,listener){const event=deepCopy(log);return event.removeListener=()=>{listener&&(runningEvent.removeListener(listener),this._checkRunningEvents(runningEvent))},event.getBlock=()=>this.provider.getBlock(log.blockHash),event.getTransaction=()=>this.provider.getTransaction(log.transactionHash),event.getTransactionReceipt=()=>this.provider.getTransactionReceipt(log.transactionHash),runningEvent.prepareEvent(event),event}_addEventListener(runningEvent,listener,once){if(this.provider||contracts_lib_esm_logger.throwError("events require a provider or a signer with a provider",Logger.errors.UNSUPPORTED_OPERATION,{operation:"once"}),runningEvent.addListener(listener,once),this._runningEvents[runningEvent.tag]=runningEvent,!this._wrappedEmits[runningEvent.tag]){const wrappedEmit=log=>{let event=this._wrapEvent(runningEvent,log,listener);if(null==event.decodeError)try{const args=runningEvent.getEmit(event);this.emit(runningEvent.filter,...args)}catch(error){event.decodeError=error.error}null!=runningEvent.filter&&this.emit("event",event),null!=event.decodeError&&this.emit("error",event.decodeError,event)};this._wrappedEmits[runningEvent.tag]=wrappedEmit,null!=runningEvent.filter&&this.provider.on(runningEvent.filter,wrappedEmit)}}queryFilter(event,fromBlockOrBlockhash,toBlock){const runningEvent=this._getRunningEvent(event),filter=shallowCopy(runningEvent.filter);return"string"==typeof fromBlockOrBlockhash&&lib_esm_isHexString(fromBlockOrBlockhash,32)?(null!=toBlock&&contracts_lib_esm_logger.throwArgumentError("cannot specify toBlock with blockhash","toBlock",toBlock),filter.blockHash=fromBlockOrBlockhash):(filter.fromBlock=null!=fromBlockOrBlockhash?fromBlockOrBlockhash:0,filter.toBlock=null!=toBlock?toBlock:"latest"),this.provider.getLogs(filter).then((logs=>logs.map((log=>this._wrapEvent(runningEvent,log,null)))))}on(event,listener){return this._addEventListener(this._getRunningEvent(event),listener,!1),this}once(event,listener){return this._addEventListener(this._getRunningEvent(event),listener,!0),this}emit(eventName,...args){if(!this.provider)return!1;const runningEvent=this._getRunningEvent(eventName),result=runningEvent.run(args)>0;return this._checkRunningEvents(runningEvent),result}listenerCount(eventName){return this.provider?null==eventName?Object.keys(this._runningEvents).reduce(((accum,key)=>accum+this._runningEvents[key].listenerCount()),0):this._getRunningEvent(eventName).listenerCount():0}listeners(eventName){if(!this.provider)return[];if(null==eventName){const result=[];for(let tag in this._runningEvents)this._runningEvents[tag].listeners().forEach((listener=>{result.push(listener)}));return result}return this._getRunningEvent(eventName).listeners()}removeAllListeners(eventName){if(!this.provider)return this;if(null==eventName){for(const tag in this._runningEvents){const runningEvent=this._runningEvents[tag];runningEvent.removeAllListeners(),this._checkRunningEvents(runningEvent)}return this}const runningEvent=this._getRunningEvent(eventName);return runningEvent.removeAllListeners(),this._checkRunningEvents(runningEvent),this}off(eventName,listener){if(!this.provider)return this;const runningEvent=this._getRunningEvent(eventName);return runningEvent.removeListener(listener),this._checkRunningEvents(runningEvent),this}removeListener(eventName,listener){return this.off(eventName,listener)}}class Contract extends BaseContract{}class ContractFactory{constructor(contractInterface,bytecode,signer){let bytecodeHex=null;bytecodeHex="string"==typeof bytecode?bytecode:isBytes(bytecode)?hexlify(bytecode):bytecode&&"string"==typeof bytecode.object?bytecode.object:"!","0x"!==bytecodeHex.substring(0,2)&&(bytecodeHex="0x"+bytecodeHex),(!lib_esm_isHexString(bytecodeHex)||bytecodeHex.length%2)&&contracts_lib_esm_logger.throwArgumentError("invalid bytecode","bytecode",bytecode),signer&&!Signer.isSigner(signer)&&contracts_lib_esm_logger.throwArgumentError("invalid signer","signer",signer),defineReadOnly(this,"bytecode",bytecodeHex),defineReadOnly(this,"interface",getStatic(new.target,"getInterface")(contractInterface)),defineReadOnly(this,"signer",signer||null)}getDeployTransaction(...args){let tx={};if(args.length===this.interface.deploy.inputs.length+1&&"object"==typeof args[args.length-1]){tx=shallowCopy(args.pop());for(const key in tx)if(!contracts_lib_esm_allowedTransactionKeys[key])throw new Error("unknown transaction override "+key)}if(["data","from","to"].forEach((key=>{null!=tx[key]&&contracts_lib_esm_logger.throwError("cannot override "+key,Logger.errors.UNSUPPORTED_OPERATION,{operation:key})})),tx.value){BigNumber.from(tx.value).isZero()||this.interface.deploy.payable||contracts_lib_esm_logger.throwError("non-payable constructor cannot override value",Logger.errors.UNSUPPORTED_OPERATION,{operation:"overrides.value",value:tx.value})}return contracts_lib_esm_logger.checkArgumentCount(args.length,this.interface.deploy.inputs.length," in Contract constructor"),tx.data=hexlify(concat([this.bytecode,this.interface.encodeDeploy(args)])),tx}deploy(...args){return contracts_lib_esm_awaiter(this,void 0,void 0,(function*(){let overrides={};args.length===this.interface.deploy.inputs.length+1&&(overrides=args.pop()),contracts_lib_esm_logger.checkArgumentCount(args.length,this.interface.deploy.inputs.length," in Contract constructor");const params=yield resolveAddresses(this.signer,args,this.interface.deploy.inputs);params.push(overrides);const unsignedTx=this.getDeployTransaction(...params),tx=yield this.signer.sendTransaction(unsignedTx),address=getStatic(this.constructor,"getContractAddress")(tx),contract=getStatic(this.constructor,"getContract")(address,this.interface,this.signer);return addContractWait(contract,tx),defineReadOnly(contract,"deployTransaction",tx),contract}))}attach(address){return this.constructor.getContract(address,this.interface,this.signer)}connect(signer){return new this.constructor(this.interface,this.bytecode,signer)}static fromSolidity(compilerOutput,signer){null==compilerOutput&&contracts_lib_esm_logger.throwError("missing compiler output",Logger.errors.MISSING_ARGUMENT,{argument:"compilerOutput"}),"string"==typeof compilerOutput&&(compilerOutput=JSON.parse(compilerOutput));const abi=compilerOutput.abi;let bytecode=null;return compilerOutput.bytecode?bytecode=compilerOutput.bytecode:compilerOutput.evm&&compilerOutput.evm.bytecode&&(bytecode=compilerOutput.evm.bytecode),new this(abi,bytecode,signer)}static getInterface(contractInterface){return Contract.getInterface(contractInterface)}static getContractAddress(tx){return getContractAddress(tx)}static getContract(address,contractInterface,signer){return new Contract(address,contractInterface,signer)}}const fixednumber_logger=new Logger("bignumber/5.7.0"),fixednumber_constructorGuard={},fixednumber_Zero=BigNumber.from(0),fixednumber_NegativeOne=BigNumber.from(-1);function fixednumber_throwFault(message,fault,operation,value){const params={fault,operation};return void 0!==value&&(params.value=value),fixednumber_logger.throwError(message,Logger.errors.NUMERIC_FAULT,params)}let zeros="0";for(;zeros.length<256;)zeros+=zeros;function getMultiplier(decimals){if("number"!=typeof decimals)try{decimals=BigNumber.from(decimals).toNumber()}catch(e){}return"number"==typeof decimals&&decimals>=0&&decimals<=256&&!(decimals%1)?"1"+zeros.substring(0,decimals):fixednumber_logger.throwArgumentError("invalid decimal size","decimals",decimals)}function formatFixed(value,decimals){null==decimals&&(decimals=0);const multiplier=getMultiplier(decimals),negative=(value=BigNumber.from(value)).lt(fixednumber_Zero);negative&&(value=value.mul(fixednumber_NegativeOne));let fraction=value.mod(multiplier).toString();for(;fraction.length2&&fixednumber_logger.throwArgumentError("too many decimal points","value",value);let whole=comps[0],fraction=comps[1];for(whole||(whole="0"),fraction||(fraction="0");"0"===fraction[fraction.length-1];)fraction=fraction.substring(0,fraction.length-1);for(fraction.length>multiplier.length-1&&fixednumber_throwFault("fractional component exceeds decimals","underflow","parseFixed"),""===fraction&&(fraction="0");fraction.lengthnull==value[key]?defaultValue:(typeof value[key]!==type&&fixednumber_logger.throwArgumentError("invalid fixed format ("+key+" not "+type+")","format."+key,value[key]),value[key]);signed=check("signed","boolean",signed),width=check("width","number",width),decimals=check("decimals","number",decimals)}return width%8&&fixednumber_logger.throwArgumentError("invalid fixed format width (not byte aligned)","format.width",width),decimals>80&&fixednumber_logger.throwArgumentError("invalid fixed format (decimals too large)","format.decimals",decimals),new FixedFormat(fixednumber_constructorGuard,signed,width,decimals)}}class FixedNumber{constructor(constructorGuard,hex,value,format){constructorGuard!==fixednumber_constructorGuard&&fixednumber_logger.throwError("cannot use FixedNumber constructor; use FixedNumber.from",Logger.errors.UNSUPPORTED_OPERATION,{operation:"new FixedFormat"}),this.format=format,this._hex=hex,this._value=value,this._isFixedNumber=!0,Object.freeze(this)}_checkFormat(other){this.format.name!==other.format.name&&fixednumber_logger.throwArgumentError("incompatible format; use fixedNumber.toFormat","other",other)}addUnsafe(other){this._checkFormat(other);const a=parseFixed(this._value,this.format.decimals),b=parseFixed(other._value,other.format.decimals);return FixedNumber.fromValue(a.add(b),this.format.decimals,this.format)}subUnsafe(other){this._checkFormat(other);const a=parseFixed(this._value,this.format.decimals),b=parseFixed(other._value,other.format.decimals);return FixedNumber.fromValue(a.sub(b),this.format.decimals,this.format)}mulUnsafe(other){this._checkFormat(other);const a=parseFixed(this._value,this.format.decimals),b=parseFixed(other._value,other.format.decimals);return FixedNumber.fromValue(a.mul(b).div(this.format._multiplier),this.format.decimals,this.format)}divUnsafe(other){this._checkFormat(other);const a=parseFixed(this._value,this.format.decimals),b=parseFixed(other._value,other.format.decimals);return FixedNumber.fromValue(a.mul(this.format._multiplier).div(b),this.format.decimals,this.format)}floor(){const comps=this.toString().split(".");1===comps.length&&comps.push("0");let result=FixedNumber.from(comps[0],this.format);const hasFraction=!comps[1].match(/^(0*)$/);return this.isNegative()&&hasFraction&&(result=result.subUnsafe(ONE.toFormat(result.format))),result}ceiling(){const comps=this.toString().split(".");1===comps.length&&comps.push("0");let result=FixedNumber.from(comps[0],this.format);const hasFraction=!comps[1].match(/^(0*)$/);return!this.isNegative()&&hasFraction&&(result=result.addUnsafe(ONE.toFormat(result.format))),result}round(decimals){null==decimals&&(decimals=0);const comps=this.toString().split(".");if(1===comps.length&&comps.push("0"),(decimals<0||decimals>80||decimals%1)&&fixednumber_logger.throwArgumentError("invalid decimal count","decimals",decimals),comps[1].length<=decimals)return this;const factor=FixedNumber.from("1"+zeros.substring(0,decimals),this.format),bump=BUMP.toFormat(this.format);return this.mulUnsafe(factor).addUnsafe(bump).floor().divUnsafe(factor)}isZero(){return"0.0"===this._value||"0"===this._value}isNegative(){return"-"===this._value[0]}toString(){return this._value}toHexString(width){if(null==width)return this._hex;width%8&&fixednumber_logger.throwArgumentError("invalid byte width","width",width);return hexZeroPad(BigNumber.from(this._hex).fromTwos(this.format.width).toTwos(width).toHexString(),width/8)}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(format){return FixedNumber.fromString(this._value,format)}static fromValue(value,decimals,format){return null!=format||null==decimals||function isBigNumberish(value){return null!=value&&(BigNumber.isBigNumber(value)||"number"==typeof value&&value%1==0||"string"==typeof value&&!!value.match(/^-?[0-9]+$/)||lib_esm_isHexString(value)||"bigint"==typeof value||isBytes(value))}(decimals)||(format=decimals,decimals=null),null==decimals&&(decimals=0),null==format&&(format="fixed"),FixedNumber.fromString(formatFixed(value,decimals),FixedFormat.from(format))}static fromString(value,format){null==format&&(format="fixed");const fixedFormat=FixedFormat.from(format),numeric=parseFixed(value,fixedFormat.decimals);!fixedFormat.signed&&numeric.lt(fixednumber_Zero)&&fixednumber_throwFault("unsigned value cannot be negative","overflow","value",value);let hex=null;fixedFormat.signed?hex=numeric.toTwos(fixedFormat.width).toHexString():(hex=numeric.toHexString(),hex=hexZeroPad(hex,fixedFormat.width/8));const decimal=formatFixed(numeric,fixedFormat.decimals);return new FixedNumber(fixednumber_constructorGuard,hex,decimal,fixedFormat)}static fromBytes(value,format){null==format&&(format="fixed");const fixedFormat=FixedFormat.from(format);if(arrayify(value).length>fixedFormat.width/8)throw new Error("overflow");let numeric=BigNumber.from(value);fixedFormat.signed&&(numeric=numeric.fromTwos(fixedFormat.width));const hex=numeric.toTwos((fixedFormat.signed?0:1)+fixedFormat.width).toHexString(),decimal=formatFixed(numeric,fixedFormat.decimals);return new FixedNumber(fixednumber_constructorGuard,hex,decimal,fixedFormat)}static from(value,format){if("string"==typeof value)return FixedNumber.fromString(value,format);if(isBytes(value))return FixedNumber.fromBytes(value,format);try{return FixedNumber.fromValue(value,0,format)}catch(error){if(error.code!==Logger.errors.INVALID_ARGUMENT)throw error}return fixednumber_logger.throwArgumentError("invalid FixedNumber value","value",value)}static isFixedNumber(value){return!(!value||!value._isFixedNumber)}}const ONE=FixedNumber.from(1),BUMP=FixedNumber.from("0.5");function hashMessage(message){return"string"==typeof message&&(message=toUtf8Bytes(message)),keccak256(concat([toUtf8Bytes("Ethereum Signed Message:\n"),toUtf8Bytes(String(message.length)),message]))}var typed_data_awaiter=function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};const typed_data_logger=new Logger("hash/5.7.0"),padding=new Uint8Array(32);padding.fill(0);const typed_data_NegativeOne=BigNumber.from(-1),typed_data_Zero=BigNumber.from(0),typed_data_One=BigNumber.from(1),typed_data_MaxUint256=BigNumber.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");const hexTrue=hexZeroPad(typed_data_One.toHexString(),32),hexFalse=hexZeroPad(typed_data_Zero.toHexString(),32),domainFieldTypes={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"},domainFieldNames=["name","version","chainId","verifyingContract","salt"];function checkString(key){return function(value){return"string"!=typeof value&&typed_data_logger.throwArgumentError(`invalid domain value for ${JSON.stringify(key)}`,`domain.${key}`,value),value}}const domainChecks={name:checkString("name"),version:checkString("version"),chainId:function(value){try{return BigNumber.from(value).toString()}catch(error){}return typed_data_logger.throwArgumentError('invalid domain value for "chainId"',"domain.chainId",value)},verifyingContract:function(value){try{return getAddress(value).toLowerCase()}catch(error){}return typed_data_logger.throwArgumentError('invalid domain value "verifyingContract"',"domain.verifyingContract",value)},salt:function(value){try{const bytes=arrayify(value);if(32!==bytes.length)throw new Error("bad length");return hexlify(bytes)}catch(error){}return typed_data_logger.throwArgumentError('invalid domain value "salt"',"domain.salt",value)}};function getBaseEncoder(type){{const match=type.match(/^(u?)int(\d*)$/);if(match){const signed=""===match[1],width=parseInt(match[2]||"256");(width%8!=0||width>256||match[2]&&match[2]!==String(width))&&typed_data_logger.throwArgumentError("invalid numeric width","type",type);const boundsUpper=typed_data_MaxUint256.mask(signed?width-1:width),boundsLower=signed?boundsUpper.add(typed_data_One).mul(typed_data_NegativeOne):typed_data_Zero;return function(value){const v=BigNumber.from(value);return(v.lt(boundsLower)||v.gt(boundsUpper))&&typed_data_logger.throwArgumentError(`value out-of-bounds for ${type}`,"value",value),hexZeroPad(v.toTwos(256).toHexString(),32)}}}{const match=type.match(/^bytes(\d+)$/);if(match){const width=parseInt(match[1]);return(0===width||width>32||match[1]!==String(width))&&typed_data_logger.throwArgumentError("invalid bytes width","type",type),function(value){return arrayify(value).length!==width&&typed_data_logger.throwArgumentError(`invalid length for ${type}`,"value",value),function hexPadRight(value){const bytes=arrayify(value),padOffset=bytes.length%32;return padOffset?hexConcat([bytes,padding.slice(padOffset)]):hexlify(bytes)}(value)}}}switch(type){case"address":return function(value){return hexZeroPad(getAddress(value),32)};case"bool":return function(value){return value?hexTrue:hexFalse};case"bytes":return function(value){return keccak256(value)};case"string":return function(value){return id(value)}}return null}function encodeType(name,fields){return`${name}(${fields.map((({name,type})=>type+" "+name)).join(",")})`}class TypedDataEncoder{constructor(types){defineReadOnly(this,"types",Object.freeze(deepCopy(types))),defineReadOnly(this,"_encoderCache",{}),defineReadOnly(this,"_types",{});const links={},parents={},subtypes={};Object.keys(types).forEach((type=>{links[type]={},parents[type]=[],subtypes[type]={}}));for(const name in types){const uniqueNames={};types[name].forEach((field=>{uniqueNames[field.name]&&typed_data_logger.throwArgumentError(`duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`,"types",types),uniqueNames[field.name]=!0;const baseType=field.type.match(/^([^\x5b]*)(\x5b|$)/)[1];baseType===name&&typed_data_logger.throwArgumentError(`circular type reference to ${JSON.stringify(baseType)}`,"types",types);getBaseEncoder(baseType)||(parents[baseType]||typed_data_logger.throwArgumentError(`unknown type ${JSON.stringify(baseType)}`,"types",types),parents[baseType].push(name),links[name][baseType]=!0)}))}const primaryTypes=Object.keys(parents).filter((n=>0===parents[n].length));0===primaryTypes.length?typed_data_logger.throwArgumentError("missing primary type","types",types):primaryTypes.length>1&&typed_data_logger.throwArgumentError(`ambiguous primary types or unused types: ${primaryTypes.map((t=>JSON.stringify(t))).join(", ")}`,"types",types),defineReadOnly(this,"primaryType",primaryTypes[0]),function checkCircular(type,found){found[type]&&typed_data_logger.throwArgumentError(`circular type reference to ${JSON.stringify(type)}`,"types",types),found[type]=!0,Object.keys(links[type]).forEach((child=>{parents[child]&&(checkCircular(child,found),Object.keys(found).forEach((subtype=>{subtypes[subtype][child]=!0})))})),delete found[type]}(this.primaryType,{});for(const name in subtypes){const st=Object.keys(subtypes[name]);st.sort(),this._types[name]=encodeType(name,types[name])+st.map((t=>encodeType(t,types[t]))).join("")}}getEncoder(type){let encoder=this._encoderCache[type];return encoder||(encoder=this._encoderCache[type]=this._getEncoder(type)),encoder}_getEncoder(type){{const encoder=getBaseEncoder(type);if(encoder)return encoder}const match=type.match(/^(.*)(\x5b(\d*)\x5d)$/);if(match){const subtype=match[1],subEncoder=this.getEncoder(subtype),length=parseInt(match[3]);return value=>{length>=0&&value.length!==length&&typed_data_logger.throwArgumentError("array length mismatch; expected length ${ arrayLength }","value",value);let result=value.map(subEncoder);return this._types[subtype]&&(result=result.map(keccak256)),keccak256(hexConcat(result))}}const fields=this.types[type];if(fields){const encodedType=id(this._types[type]);return value=>{const values=fields.map((({name,type})=>{const result=this.getEncoder(type)(value[name]);return this._types[type]?keccak256(result):result}));return values.unshift(encodedType),hexConcat(values)}}return typed_data_logger.throwArgumentError(`unknown type: ${type}`,"type",type)}encodeType(name){const result=this._types[name];return result||typed_data_logger.throwArgumentError(`unknown type: ${JSON.stringify(name)}`,"name",name),result}encodeData(type,value){return this.getEncoder(type)(value)}hashStruct(name,value){return keccak256(this.encodeData(name,value))}encode(value){return this.encodeData(this.primaryType,value)}hash(value){return this.hashStruct(this.primaryType,value)}_visit(type,value,callback){if(getBaseEncoder(type))return callback(type,value);const match=type.match(/^(.*)(\x5b(\d*)\x5d)$/);if(match){const subtype=match[1],length=parseInt(match[3]);return length>=0&&value.length!==length&&typed_data_logger.throwArgumentError("array length mismatch; expected length ${ arrayLength }","value",value),value.map((v=>this._visit(subtype,v,callback)))}const fields=this.types[type];return fields?fields.reduce(((accum,{name,type})=>(accum[name]=this._visit(type,value[name],callback),accum)),{}):typed_data_logger.throwArgumentError(`unknown type: ${type}`,"type",type)}visit(value,callback){return this._visit(this.primaryType,value,callback)}static from(types){return new TypedDataEncoder(types)}static getPrimaryType(types){return TypedDataEncoder.from(types).primaryType}static hashStruct(name,types,value){return TypedDataEncoder.from(types).hashStruct(name,value)}static hashDomain(domain){const domainFields=[];for(const name in domain){const type=domainFieldTypes[name];type||typed_data_logger.throwArgumentError(`invalid typed-data domain key: ${JSON.stringify(name)}`,"domain",domain),domainFields.push({name,type})}return domainFields.sort(((a,b)=>domainFieldNames.indexOf(a.name)-domainFieldNames.indexOf(b.name))),TypedDataEncoder.hashStruct("EIP712Domain",{EIP712Domain:domainFields},domain)}static encode(domain,types,value){return hexConcat(["0x1901",TypedDataEncoder.hashDomain(domain),TypedDataEncoder.from(types).hash(value)])}static hash(domain,types,value){return keccak256(TypedDataEncoder.encode(domain,types,value))}static resolveNames(domain,types,value,resolveName){return typed_data_awaiter(this,void 0,void 0,(function*(){domain=shallowCopy(domain);const ensCache={};domain.verifyingContract&&!lib_esm_isHexString(domain.verifyingContract,20)&&(ensCache[domain.verifyingContract]="0x");const encoder=TypedDataEncoder.from(types);encoder.visit(value,((type,value)=>("address"!==type||lib_esm_isHexString(value,20)||(ensCache[value]="0x"),value)));for(const name in ensCache)ensCache[name]=yield resolveName(name);return domain.verifyingContract&&ensCache[domain.verifyingContract]&&(domain.verifyingContract=ensCache[domain.verifyingContract]),value=encoder.visit(value,((type,value)=>"address"===type&&ensCache[value]?ensCache[value]:value)),{domain,value}}))}static getPayload(domain,types,value){TypedDataEncoder.hashDomain(domain);const domainValues={},domainTypes=[];domainFieldNames.forEach((name=>{const value=domain[name];null!=value&&(domainValues[name]=domainChecks[name](value),domainTypes.push({name,type:domainFieldTypes[name]}))}));const encoder=TypedDataEncoder.from(types),typesWithDomain=shallowCopy(types);return typesWithDomain.EIP712Domain?typed_data_logger.throwArgumentError("types must not contain EIP712Domain type","types.EIP712Domain",types):typesWithDomain.EIP712Domain=domainTypes,encoder.encode(value),{types:typesWithDomain,domain:domainValues,primaryType:encoder.primaryType,message:encoder.visit(value,((type,value)=>{if(type.match(/^bytes(\d*)/))return hexlify(arrayify(value));if(type.match(/^u?int/))return BigNumber.from(value).toString();switch(type){case"address":return value.toLowerCase();case"bool":return!!value;case"string":return"string"!=typeof value&&typed_data_logger.throwArgumentError("invalid string","value",value),value}return typed_data_logger.throwArgumentError("unsupported type","type",type)}))}}}class BaseX{constructor(alphabet){defineReadOnly(this,"alphabet",alphabet),defineReadOnly(this,"base",alphabet.length),defineReadOnly(this,"_alphabetMap",{}),defineReadOnly(this,"_leader",alphabet.charAt(0));for(let i=0;i0;)digits.push(carry%this.base),carry=carry/this.base|0}let string="";for(let k=0;0===source[k]&&k=0;--q)string+=this.alphabet[digits[q]];return string}decode(value){if("string"!=typeof value)throw new TypeError("Expected String");let bytes=[];if(0===value.length)return new Uint8Array(bytes);bytes.push(0);for(let i=0;i>=8;for(;carry>0;)bytes.push(255&carry),carry>>=8}for(let k=0;value[k]===this._leader&&k>24&255,block1[salt.length+1]=i>>16&255,block1[salt.length+2]=i>>8&255,block1[salt.length+3]=255&i;let U=arrayify(computeHmac(hashAlgorithm,password,block1));hLen||(hLen=U.length,T=new Uint8Array(hLen),l=Math.ceil(keylen/hLen),r=keylen-(l-1)*hLen),T.set(U);for(let j=1;j=256)throw new Error("Depth too large!");return base58check(concat([null!=this.privateKey?"0x0488ADE4":"0x0488B21E",hexlify(this.depth),this.parentFingerprint,hexZeroPad(hexlify(this.index),4),this.chainCode,null!=this.privateKey?concat(["0x00",this.privateKey]):this.publicKey]))}neuter(){return new HDNode(lib_esm_constructorGuard,null,this.publicKey,this.parentFingerprint,this.chainCode,this.index,this.depth,this.path)}_derive(index){if(index>4294967295)throw new Error("invalid index - "+String(index));let path=this.path;path&&(path+="/"+(2147483647&index));const data=new Uint8Array(37);if(2147483648&index){if(!this.privateKey)throw new Error("cannot derive child of neutered node");data.set(arrayify(this.privateKey),1),path&&(path+="'")}else data.set(arrayify(this.publicKey));for(let i=24;i>=0;i-=8)data[33+(i>>3)]=index>>24-i&255;const I=arrayify(computeHmac(SupportedAlgorithm.sha512,this.chainCode,data)),IL=I.slice(0,32),IR=I.slice(32);let ki=null,Ki=null;if(this.privateKey)ki=bytes32(BigNumber.from(IL).add(this.privateKey).mod(N));else{Ki=new SigningKey(hexlify(IL))._addPoint(this.publicKey)}let mnemonicOrPath=path;const srcMnemonic=this.mnemonic;return srcMnemonic&&(mnemonicOrPath=Object.freeze({phrase:srcMnemonic.phrase,path,locale:srcMnemonic.locale||"en"})),new HDNode(lib_esm_constructorGuard,ki,Ki,this.fingerprint,bytes32(IR),index,this.depth+1,mnemonicOrPath)}derivePath(path){const components=path.split("/");if(0===components.length||"m"===components[0]&&0!==this.depth)throw new Error("invalid path - "+path);"m"===components[0]&&components.shift();let result=this;for(let i=0;i=2147483648)throw new Error("invalid path index - "+component);result=result._derive(2147483648+index)}else{if(!component.match(/^[0-9]+$/))throw new Error("invalid path component - "+component);{const index=parseInt(component);if(index>=2147483648)throw new Error("invalid path index - "+component);result=result._derive(index)}}}return result}static _fromSeed(seed,mnemonic){const seedArray=arrayify(seed);if(seedArray.length<16||seedArray.length>64)throw new Error("invalid seed");const I=arrayify(computeHmac(SupportedAlgorithm.sha512,MasterSecret,seedArray));return new HDNode(lib_esm_constructorGuard,bytes32(I.slice(0,32)),null,"0x00000000",bytes32(I.slice(32)),0,0,mnemonic)}static fromMnemonic(mnemonic,password,wordlist){return mnemonic=entropyToMnemonic(mnemonicToEntropy(mnemonic,wordlist=getWordlist(wordlist)),wordlist),HDNode._fromSeed(mnemonicToSeed(mnemonic,password),{phrase:mnemonic,path:"m",locale:wordlist.locale})}static fromSeed(seed){return HDNode._fromSeed(seed,null)}static fromExtendedKey(extendedKey){const bytes=Base58.decode(extendedKey);82===bytes.length&&base58check(bytes.slice(0,78))===extendedKey||hdnode_lib_esm_logger.throwArgumentError("invalid extended key","extendedKey","[REDACTED]");const depth=bytes[4],parentFingerprint=hexlify(bytes.slice(5,9)),index=parseInt(hexlify(bytes.slice(9,13)).substring(2),16),chainCode=hexlify(bytes.slice(13,45)),key=bytes.slice(45,78);switch(hexlify(bytes.slice(0,4))){case"0x0488b21e":case"0x043587cf":return new HDNode(lib_esm_constructorGuard,null,hexlify(key),parentFingerprint,chainCode,index,depth,null);case"0x0488ade4":case"0x04358394 ":if(0!==key[0])break;return new HDNode(lib_esm_constructorGuard,hexlify(key.slice(1)),null,parentFingerprint,chainCode,index,depth,null)}return hdnode_lib_esm_logger.throwArgumentError("invalid extended key","extendedKey","[REDACTED]")}}function mnemonicToSeed(mnemonic,password){password||(password="");const salt=toUtf8Bytes("mnemonic"+password,UnicodeNormalizationForm.NFKD);return pbkdf2(toUtf8Bytes(mnemonic,UnicodeNormalizationForm.NFKD),salt,2048,64,"sha512")}function mnemonicToEntropy(mnemonic,wordlist){wordlist=getWordlist(wordlist),hdnode_lib_esm_logger.checkNormalize();const words=wordlist.split(mnemonic);if(words.length%3!=0)throw new Error("invalid mnemonic");const entropy=arrayify(new Uint8Array(Math.ceil(11*words.length/8)));let offset=0;for(let i=0;i>3]|=1<<7-offset%8),offset++}const entropyBits=32*words.length/3,checksumMask=getUpperMask(words.length/3);if((arrayify(sha256(entropy.slice(0,entropyBits/8)))[0]&checksumMask)!==(entropy[entropy.length-1]&checksumMask))throw new Error("invalid checksum");return hexlify(entropy.slice(0,entropyBits/8))}function entropyToMnemonic(entropy,wordlist){if(wordlist=getWordlist(wordlist),(entropy=arrayify(entropy)).length%4!=0||entropy.length<16||entropy.length>32)throw new Error("invalid entropy");const indices=[0];let remainingBits=11;for(let i=0;i8?(indices[indices.length-1]<<=8,indices[indices.length-1]|=entropy[i],remainingBits-=8):(indices[indices.length-1]<<=remainingBits,indices[indices.length-1]|=entropy[i]>>8-remainingBits,indices.push(entropy[i]&(1<<8-remainingBits)-1),remainingBits+=3);const checksumBits=entropy.length/4,checksum=arrayify(sha256(entropy))[0]&getUpperMask(checksumBits);return indices[indices.length-1]<<=checksumBits,indices[indices.length-1]|=checksum>>8-checksumBits,wordlist.join(indices.map((index=>wordlist.getWord(index))))}function isValidMnemonic(mnemonic,wordlist){try{return mnemonicToEntropy(mnemonic,wordlist),!0}catch(error){}return!1}function getAccountPath(index){return("number"!=typeof index||index<0||index>=2147483648||index%1)&&hdnode_lib_esm_logger.throwArgumentError("invalid account index","index",index),`m/44'/60'/${index}'/0/0`}const random_logger=new Logger("random/5.7.0");const anyGlobal=function getGlobal(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==__webpack_require__.g)return __webpack_require__.g;throw new Error("unable to locate global object")}();let random_crypto=anyGlobal.crypto||anyGlobal.msCrypto;function randomBytes(length){(length<=0||length>1024||length%1||length!=length)&&random_logger.throwArgumentError("invalid length","length",length);const result=new Uint8Array(length);return random_crypto.getRandomValues(result),arrayify(result)}random_crypto&&random_crypto.getRandomValues||(random_logger.warn("WARNING: Missing strong random number source"),random_crypto={getRandomValues:function(buffer){return random_logger.throwError("no secure random source avaialble",Logger.errors.UNSUPPORTED_OPERATION,{operation:"crypto.getRandomValues"})}});var aes_js=__webpack_require__(8826),aes_js_default=__webpack_require__.n(aes_js),scrypt=__webpack_require__(7635),scrypt_default=__webpack_require__.n(scrypt);function looseArrayify(hexString){return"string"==typeof hexString&&"0x"!==hexString.substring(0,2)&&(hexString="0x"+hexString),arrayify(hexString)}function zpad(value,length){for(value=String(value);value.lengthsigningKey)),defineReadOnly(this,"address",computeAddress(this.publicKey)),this.address!==getAddress(privateKey.address)&&wallet_lib_esm_logger.throwArgumentError("privateKey/address mismatch","privateKey","[REDACTED]"),function lib_esm_hasMnemonic(value){const mnemonic=value.mnemonic;return mnemonic&&mnemonic.phrase}(privateKey)){const srcMnemonic=privateKey.mnemonic;defineReadOnly(this,"_mnemonic",(()=>({phrase:srcMnemonic.phrase,path:srcMnemonic.path||defaultPath,locale:srcMnemonic.locale||"en"})));const mnemonic=this.mnemonic;computeAddress(HDNode.fromMnemonic(mnemonic.phrase,null,mnemonic.locale).derivePath(mnemonic.path).privateKey)!==this.address&&wallet_lib_esm_logger.throwArgumentError("mnemonic/address mismatch","privateKey","[REDACTED]")}else defineReadOnly(this,"_mnemonic",(()=>null))}else{if(SigningKey.isSigningKey(privateKey))"secp256k1"!==privateKey.curve&&wallet_lib_esm_logger.throwArgumentError("unsupported curve; must be secp256k1","privateKey","[REDACTED]"),defineReadOnly(this,"_signingKey",(()=>privateKey));else{"string"==typeof privateKey&&privateKey.match(/^[0-9a-f]*$/i)&&64===privateKey.length&&(privateKey="0x"+privateKey);const signingKey=new SigningKey(privateKey);defineReadOnly(this,"_signingKey",(()=>signingKey))}defineReadOnly(this,"_mnemonic",(()=>null)),defineReadOnly(this,"address",computeAddress(this.publicKey))}provider&&!Provider.isProvider(provider)&&wallet_lib_esm_logger.throwArgumentError("invalid provider","provider",provider),defineReadOnly(this,"provider",provider||null)}get mnemonic(){return this._mnemonic()}get privateKey(){return this._signingKey().privateKey}get publicKey(){return this._signingKey().publicKey}getAddress(){return Promise.resolve(this.address)}connect(provider){return new Wallet(this,provider)}signTransaction(transaction){return resolveProperties(transaction).then((tx=>{null!=tx.from&&(getAddress(tx.from)!==this.address&&wallet_lib_esm_logger.throwArgumentError("transaction from address mismatch","transaction.from",transaction.from),delete tx.from);const signature=this._signingKey().signDigest(keccak256(serialize(tx)));return serialize(tx,signature)}))}signMessage(message){return wallet_lib_esm_awaiter(this,void 0,void 0,(function*(){return joinSignature(this._signingKey().signDigest(hashMessage(message)))}))}_signTypedData(domain,types,value){return wallet_lib_esm_awaiter(this,void 0,void 0,(function*(){const populated=yield TypedDataEncoder.resolveNames(domain,types,value,(name=>(null==this.provider&&wallet_lib_esm_logger.throwError("cannot resolve ENS names without a provider",Logger.errors.UNSUPPORTED_OPERATION,{operation:"resolveName",value:name}),this.provider.resolveName(name))));return joinSignature(this._signingKey().signDigest(TypedDataEncoder.hash(populated.domain,types,populated.value)))}))}encrypt(password,options,progressCallback){if("function"!=typeof options||progressCallback||(progressCallback=options,options={}),progressCallback&&"function"!=typeof progressCallback)throw new Error("invalid callback");return options||(options={}),function encrypt(account,password,options,progressCallback){try{if(getAddress(account.address)!==computeAddress(account.privateKey))throw new Error("address/privateKey mismatch");if(hasMnemonic(account)){const mnemonic=account.mnemonic;if(HDNode.fromMnemonic(mnemonic.phrase,null,mnemonic.locale).derivePath(mnemonic.path||defaultPath).privateKey!=account.privateKey)throw new Error("mnemonic mismatch")}}catch(e){return Promise.reject(e)}"function"!=typeof options||progressCallback||(progressCallback=options,options={}),options||(options={});const privateKey=arrayify(account.privateKey),passwordBytes=getPassword(password);let entropy=null,path=null,locale=null;if(hasMnemonic(account)){const srcMnemonic=account.mnemonic;entropy=arrayify(mnemonicToEntropy(srcMnemonic.phrase,srcMnemonic.locale||"en")),path=srcMnemonic.path||defaultPath,locale=srcMnemonic.locale||"en"}let client=options.client;client||(client="ethers.js");let salt=null;salt=options.salt?arrayify(options.salt):randomBytes(32);let iv=null;if(options.iv){if(iv=arrayify(options.iv),16!==iv.length)throw new Error("invalid iv")}else iv=randomBytes(16);let uuidRandom=null;if(options.uuid){if(uuidRandom=arrayify(options.uuid),16!==uuidRandom.length)throw new Error("invalid uuid")}else uuidRandom=randomBytes(16);let N=1<<17,r=8,p=1;return options.scrypt&&(options.scrypt.N&&(N=options.scrypt.N),options.scrypt.r&&(r=options.scrypt.r),options.scrypt.p&&(p=options.scrypt.p)),scrypt_default().scrypt(passwordBytes,salt,N,r,p,64,progressCallback).then((key=>{const derivedKey=(key=arrayify(key)).slice(0,16),macPrefix=key.slice(16,32),mnemonicKey=key.slice(32,64),counter=new(aes_js_default().Counter)(iv),ciphertext=arrayify(new(aes_js_default().ModeOfOperation.ctr)(derivedKey,counter).encrypt(privateKey)),mac=keccak256(concat([macPrefix,ciphertext])),data={address:account.address.substring(2).toLowerCase(),id:uuidV4(uuidRandom),version:3,crypto:{cipher:"aes-128-ctr",cipherparams:{iv:hexlify(iv).substring(2)},ciphertext:hexlify(ciphertext).substring(2),kdf:"scrypt",kdfparams:{salt:hexlify(salt).substring(2),n:N,dklen:32,p,r},mac:mac.substring(2)}};if(entropy){const mnemonicIv=randomBytes(16),mnemonicCounter=new(aes_js_default().Counter)(mnemonicIv),mnemonicCiphertext=arrayify(new(aes_js_default().ModeOfOperation.ctr)(mnemonicKey,mnemonicCounter).encrypt(entropy)),now=new Date,timestamp=now.getUTCFullYear()+"-"+zpad(now.getUTCMonth()+1,2)+"-"+zpad(now.getUTCDate(),2)+"T"+zpad(now.getUTCHours(),2)+"-"+zpad(now.getUTCMinutes(),2)+"-"+zpad(now.getUTCSeconds(),2)+".0Z";data["x-ethers"]={client,gethFilename:"UTC--"+timestamp+"--"+data.address,mnemonicCounter:hexlify(mnemonicIv).substring(2),mnemonicCiphertext:hexlify(mnemonicCiphertext).substring(2),path,locale,version:"0.1"}}return JSON.stringify(data)}))}(this,password,options,progressCallback)}static createRandom(options){let entropy=randomBytes(16);options||(options={}),options.extraEntropy&&(entropy=arrayify(hexDataSlice(keccak256(concat([entropy,options.extraEntropy])),0,16)));const mnemonic=entropyToMnemonic(entropy,options.locale);return Wallet.fromMnemonic(mnemonic,options.path,options.locale)}static fromEncryptedJson(json,password,progressCallback){return decryptJsonWallet(json,password,progressCallback).then((account=>new Wallet(account)))}static fromEncryptedJsonSync(json,password){return new Wallet(decryptJsonWalletSync(json,password))}static fromMnemonic(mnemonic,path,wordlist){return path||(path=defaultPath),new Wallet(HDNode.fromMnemonic(mnemonic,null,wordlist).derivePath(path))}}function verifyMessage(message,signature){return recoverAddress(hashMessage(message),signature)}function verifyTypedData(domain,types,value,signature){return recoverAddress(TypedDataEncoder.hash(domain,types,value),signature)}const AddressZero="0x0000000000000000000000000000000000000000",HashZero="0x0000000000000000000000000000000000000000000000000000000000000000",EtherSymbol="Ξ",networks_lib_esm_logger=new Logger("networks/5.7.1");function ethDefaultProvider(network){const func=function(providers,options){null==options&&(options={});const providerList=[];if(providers.InfuraProvider&&"-"!==options.infura)try{providerList.push(new providers.InfuraProvider(network,options.infura))}catch(error){}if(providers.EtherscanProvider&&"-"!==options.etherscan)try{providerList.push(new providers.EtherscanProvider(network,options.etherscan))}catch(error){}if(providers.AlchemyProvider&&"-"!==options.alchemy)try{providerList.push(new providers.AlchemyProvider(network,options.alchemy))}catch(error){}if(providers.PocketProvider&&"-"!==options.pocket){const skip=["goerli","ropsten","rinkeby","sepolia"];try{const provider=new providers.PocketProvider(network,options.pocket);provider.network&&-1===skip.indexOf(provider.network.name)&&providerList.push(provider)}catch(error){}}if(providers.CloudflareProvider&&"-"!==options.cloudflare)try{providerList.push(new providers.CloudflareProvider(network))}catch(error){}if(providers.AnkrProvider&&"-"!==options.ankr)try{const skip=["ropsten"],provider=new providers.AnkrProvider(network,options.ankr);provider.network&&-1===skip.indexOf(provider.network.name)&&providerList.push(provider)}catch(error){}if(0===providerList.length)return null;if(providers.FallbackProvider){let quorum=1;return null!=options.quorum?quorum=options.quorum:"homestead"===network&&(quorum=2),new providers.FallbackProvider(providerList,quorum)}return providerList[0]};return func.renetwork=function(network){return ethDefaultProvider(network)},func}function etcDefaultProvider(url,network){const func=function(providers,options){return providers.JsonRpcProvider?new providers.JsonRpcProvider(url,network):null};return func.renetwork=function(network){return etcDefaultProvider(url,network)},func}const homestead={chainId:1,ensAddress:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",name:"homestead",_defaultProvider:ethDefaultProvider("homestead")},ropsten={chainId:3,ensAddress:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",name:"ropsten",_defaultProvider:ethDefaultProvider("ropsten")},classicMordor={chainId:63,name:"classicMordor",_defaultProvider:etcDefaultProvider("https://www.ethercluster.com/mordor","classicMordor")},networks={unspecified:{chainId:0,name:"unspecified"},homestead,mainnet:homestead,morden:{chainId:2,name:"morden"},ropsten,testnet:ropsten,rinkeby:{chainId:4,ensAddress:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",name:"rinkeby",_defaultProvider:ethDefaultProvider("rinkeby")},kovan:{chainId:42,name:"kovan",_defaultProvider:ethDefaultProvider("kovan")},goerli:{chainId:5,ensAddress:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",name:"goerli",_defaultProvider:ethDefaultProvider("goerli")},kintsugi:{chainId:1337702,name:"kintsugi"},sepolia:{chainId:11155111,name:"sepolia",_defaultProvider:ethDefaultProvider("sepolia")},classic:{chainId:61,name:"classic",_defaultProvider:etcDefaultProvider("https://www.ethercluster.com/etc","classic")},classicMorden:{chainId:62,name:"classicMorden"},classicMordor,classicTestnet:classicMordor,classicKotti:{chainId:6,name:"classicKotti",_defaultProvider:etcDefaultProvider("https://www.ethercluster.com/kotti","classicKotti")},xdai:{chainId:100,name:"xdai"},matic:{chainId:137,name:"matic",_defaultProvider:ethDefaultProvider("matic")},maticmum:{chainId:80001,name:"maticmum"},optimism:{chainId:10,name:"optimism",_defaultProvider:ethDefaultProvider("optimism")},"optimism-kovan":{chainId:69,name:"optimism-kovan"},"optimism-goerli":{chainId:420,name:"optimism-goerli"},arbitrum:{chainId:42161,name:"arbitrum"},"arbitrum-rinkeby":{chainId:421611,name:"arbitrum-rinkeby"},"arbitrum-goerli":{chainId:421613,name:"arbitrum-goerli"},bnb:{chainId:56,name:"bnb"},bnbt:{chainId:97,name:"bnbt"}};function getNetwork(network){if(null==network)return null;if("number"==typeof network){for(const name in networks){const standard=networks[name];if(standard.chainId===network)return{name:standard.name,chainId:standard.chainId,ensAddress:standard.ensAddress||null,_defaultProvider:standard._defaultProvider||null}}return{chainId:network,name:"unknown"}}if("string"==typeof network){const standard=networks[network];return null==standard?null:{name:standard.name,chainId:standard.chainId,ensAddress:standard.ensAddress,_defaultProvider:standard._defaultProvider||null}}const standard=networks[network.name];if(!standard)return"number"!=typeof network.chainId&&networks_lib_esm_logger.throwArgumentError("invalid network chainId","network",network),network;0!==network.chainId&&network.chainId!==standard.chainId&&networks_lib_esm_logger.throwArgumentError("network chainId mismatch","network",network);let defaultProvider=network._defaultProvider||null;return null==defaultProvider&&standard._defaultProvider&&(defaultProvider=function isRenetworkable(value){return value&&"function"==typeof value.renetwork}(standard._defaultProvider)?standard._defaultProvider.renetwork(network):standard._defaultProvider),{name:network.name,chainId:standard.chainId,ensAddress:network.ensAddress||standard.ensAddress||null,_defaultProvider:defaultProvider}}function base64_decode(textData){textData=atob(textData);const data=[];for(let i=0;i0&&Array.isArray(val)?flatDeep(val,depth-1):result.push(val)}))};return flatDeep(array,depth),result}function read_compressed_payload(bytes){return function read_payload(v){let pos=0;return()=>v[pos++]}(function decode_arithmetic(bytes){let pos=0;function u16(){return bytes[pos++]<<8|bytes[pos++]}let symbol_count=u16(),total=1,acc=[0,1];for(let i=1;i>--read_width&1}const FULL=Math.pow(2,31),HALF=FULL>>>1,QRTR=HALF>>1,MASK=FULL-1;let register=0;for(let i=0;i<31;i++)register=register<<1|read_bit();let symbols=[],low=0,range=FULL;for(;;){let value=Math.floor(((register-low+1)*total-1)/range),start=0,end=symbol_count;for(;end-start>1;){let mid=start+end>>>1;value>>1|read_bit(),a=a<<1^HALF,b=(b^HALF)<<1|HALF|1;low=a,range=1+b-a}let offset=symbol_count-4;return symbols.map((x=>{switch(x-offset){case 3:return offset+65792+(bytes[pos_payload++]<<16|bytes[pos_payload++]<<8|bytes[pos_payload++]);case 2:return offset+256+(bytes[pos_payload++]<<8|bytes[pos_payload++]);case 1:return offset+bytes[pos_payload++];default:return x-1}}))}(bytes))}function signed(i){return 1&i?~i>>1:i>>1}function read_ascending(n,next){let v=Array(n);for(let i=0,x=-1;ilookup[x])):v}function read_transposed(n,w,next){let m=Array(n).fill(void 0).map((()=>[]));for(let i=0;im[j].push(x)));return m}function read_linear_table(w,next){let dx=1+next(),dy=next(),vN=function read_zero_terminated_array(next){let v=[];for(;;){let i=next();if(0==i)break;v.push(i)}return v}(next);return flat(read_transposed(vN.length,1+w,next).map(((v,i)=>{const x=v[0],ys=v.slice(1);return Array(vN[i]).fill(void 0).map(((_,j)=>{let j_dy=j*dy;return[x+j*dx,ys.map((y=>y+j_dy))]}))})))}function read_replacement_table(w,next){return read_transposed(1+next(),1+w,next).map((v=>[v[0],v.slice(1)]))}const r=function getData(){return read_compressed_payload(base64_decode("AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA=="))}(),VALID=new Set(read_member_array(r)),IGNORED=new Set(read_member_array(r)),MAPPED=function read_mapped_map(next){let ret=[];for(;;){let w=next();if(0==w)break;ret.push(read_linear_table(w,next))}for(;;){let w=next()-1;if(w<0)break;ret.push(read_replacement_table(w,next))}return function fromEntries(array){const result={};for(let i=0;ia-b));return function read(){let branches=[];for(;;){let keys=read_member_array(next,sorted);if(0==keys.length)break;branches.push({set:new Set(keys),node:read()})}branches.sort(((a,b)=>b.set.size-a.set.size));let temp=next(),valid=temp%3;temp=temp/3|0;let fe0f=!!(1&temp);return temp>>=1,{branches,valid,fe0f,save:1==temp,check:2==temp}}()}(r);function explode_cp(name){return toUtf8CodePoints(name)}function filter_fe0f(cps){return cps.filter((cp=>65039!=cp))}function ens_normalize_post_check(name){for(let label of name.split(".")){let cps=explode_cp(label);try{for(let i=cps.lastIndexOf(95)-1;i>=0;i--)if(95!==cps[i])throw new Error("underscore only allowed at start");if(cps.length>=4&&cps.every((cp=>cp<128))&&45===cps[2]&&45===cps[3])throw new Error("invalid label extension")}catch(err){throw new Error(`Invalid label "${label}": ${err.message}`)}}return name}function ens_normalize(name){return ens_normalize_post_check(function normalize(name,emoji_filter){let input=explode_cp(name).reverse(),output=[];for(;input.length;){let emoji=consume_emoji_reversed(input);if(emoji){output.push(...emoji_filter(emoji));continue}let cp=input.pop();if(VALID.has(cp)){output.push(cp);continue}if(IGNORED.has(cp))continue;let cps=MAPPED[cp];if(!cps)throw new Error(`Disallowed codepoint: 0x${cp.toString(16).toUpperCase()}`);output.push(...cps)}return ens_normalize_post_check(function nfc(s){return s.normalize("NFC")}(String.fromCodePoint(...output)))}(name,filter_fe0f))}function consume_emoji_reversed(cps,eaten){var _a;let emoji,saved,node=EMOJI_ROOT,stack=[],pos=cps.length;for(eaten&&(eaten.length=0);pos;){let cp=cps[--pos];if(node=null===(_a=node.branches.find((x=>x.set.has(cp))))||void 0===_a?void 0:_a.node,!node)break;if(node.save)saved=cp;else if(node.check&&cp===saved)break;stack.push(cp),node.fe0f&&(stack.push(65039),pos>0&&65039==cps[pos-1]&&pos--),node.valid&&(emoji=stack.slice(),2==node.valid&&emoji.splice(1,1),eaten&&eaten.push(...cps.slice(pos).reverse()),cps.length=pos)}return emoji}const namehash_logger=new Logger("hash/5.7.0"),Zeros=new Uint8Array(32);function checkComponent(comp){if(0===comp.length)throw new Error("invalid ENS name; empty component");return comp}function ensNameSplit(name){const bytes=toUtf8Bytes(ens_normalize(name)),comps=[];if(0===name.length)return comps;let last=0;for(let i=0;i=bytes.length)throw new Error("invalid ENS name; empty component");return comps.push(checkComponent(bytes.slice(last))),comps}function isValidName(name){try{return 0!==ensNameSplit(name).length}catch(error){}return!1}function namehash(name){"string"!=typeof name&&namehash_logger.throwArgumentError("invalid ENS name; not a string","name",name);let result=Zeros;const comps=ensNameSplit(name);for(;comps.length;)result=keccak256(concat([result,keccak256(comps.pop())]));return hexlify(result)}function dnsEncode(name){return hexlify(concat(ensNameSplit(name).map((comp=>{if(comp.length>63)throw new Error("invalid DNS encoded entry; length exceeds 63 bytes");const bytes=new Uint8Array(comp.length+1);return bytes.set(comp,1),bytes[0]=bytes.length-1,bytes}))))+"00"}Zeros.fill(0);var geturl_awaiter=function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};function getUrl(href,options){return geturl_awaiter(this,void 0,void 0,(function*(){null==options&&(options={});const request={method:options.method||"GET",headers:options.headers||{},body:options.body||void 0};if(!0!==options.skipFetchSetup&&(request.mode="cors",request.cache="no-cache",request.credentials="same-origin",request.redirect="follow",request.referrer="client"),null!=options.fetchOptions){const opts=options.fetchOptions;opts.mode&&(request.mode=opts.mode),opts.cache&&(request.cache=opts.cache),opts.credentials&&(request.credentials=opts.credentials),opts.redirect&&(request.redirect=opts.redirect),opts.referrer&&(request.referrer=opts.referrer)}const response=yield fetch(href,request),body=yield response.arrayBuffer(),headers={};return response.headers.forEach?response.headers.forEach(((value,key)=>{headers[key.toLowerCase()]=value})):response.headers.keys().forEach((key=>{headers[key.toLowerCase()]=response.headers.get(key)})),{headers,statusCode:response.status,statusMessage:response.statusText,body:arrayify(new Uint8Array(body))}}))}var web_lib_esm_awaiter=function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};const web_lib_esm_logger=new Logger("web/5.7.1");function staller(duration){return new Promise((resolve=>{setTimeout(resolve,duration)}))}function bodyify(value,type){if(null==value)return null;if("string"==typeof value)return value;if(isBytesLike(value)){if(type&&("text"===type.split("/")[0]||"application/json"===type.split(";")[0].trim()))try{return utf8_toUtf8String(value)}catch(error){}return hexlify(value)}return value}function _fetchData(connection,body,processFunc){const attemptLimit="object"==typeof connection&&null!=connection.throttleLimit?connection.throttleLimit:12;web_lib_esm_logger.assertArgument(attemptLimit>0&&attemptLimit%1==0,"invalid connection throttle limit","connection.throttleLimit",attemptLimit);const throttleCallback="object"==typeof connection?connection.throttleCallback:null,throttleSlotInterval="object"==typeof connection&&"number"==typeof connection.throttleSlotInterval?connection.throttleSlotInterval:100;web_lib_esm_logger.assertArgument(throttleSlotInterval>0&&throttleSlotInterval%1==0,"invalid connection throttle slot interval","connection.throttleSlotInterval",throttleSlotInterval);const errorPassThrough="object"==typeof connection&&!!connection.errorPassThrough,headers={};let url=null;const options={method:"GET"};let allow304=!1,timeout=12e4;if("string"==typeof connection)url=connection;else if("object"==typeof connection){if(null!=connection&&null!=connection.url||web_lib_esm_logger.throwArgumentError("missing URL","connection.url",connection),url=connection.url,"number"==typeof connection.timeout&&connection.timeout>0&&(timeout=connection.timeout),connection.headers)for(const key in connection.headers)headers[key.toLowerCase()]={key,value:String(connection.headers[key])},["if-none-match","if-modified-since"].indexOf(key.toLowerCase())>=0&&(allow304=!0);if(options.allowGzip=!!connection.allowGzip,null!=connection.user&&null!=connection.password){"https:"!==url.substring(0,6)&&!0!==connection.allowInsecureAuthentication&&web_lib_esm_logger.throwError("basic authentication requires a secure https url",Logger.errors.INVALID_ARGUMENT,{argument:"url",url,user:connection.user,password:"[REDACTED]"});const authorization=connection.user+":"+connection.password;headers.authorization={key:"Authorization",value:"Basic "+base64_encode(toUtf8Bytes(authorization))}}null!=connection.skipFetchSetup&&(options.skipFetchSetup=!!connection.skipFetchSetup),null!=connection.fetchOptions&&(options.fetchOptions=shallowCopy(connection.fetchOptions))}const reData=new RegExp("^data:([^;:]*)?(;base64)?,(.*)$","i"),dataMatch=url?url.match(reData):null;if(dataMatch)try{const response={statusCode:200,statusMessage:"OK",headers:{"content-type":dataMatch[1]||"text/plain"},body:dataMatch[2]?base64_decode(dataMatch[3]):(value=dataMatch[3],toUtf8Bytes(value.replace(/%([0-9a-f][0-9a-f])/gi,((all,code)=>String.fromCharCode(parseInt(code,16))))))};let result=response.body;return processFunc&&(result=processFunc(response.body,response)),Promise.resolve(result)}catch(error){web_lib_esm_logger.throwError("processing response error",Logger.errors.SERVER_ERROR,{body:bodyify(dataMatch[1],dataMatch[2]),error,requestBody:null,requestMethod:"GET",url})}var value;body&&(options.method="POST",options.body=body,null==headers["content-type"]&&(headers["content-type"]={key:"Content-Type",value:"application/octet-stream"}),null==headers["content-length"]&&(headers["content-length"]={key:"Content-Length",value:String(body.length)}));const flatHeaders={};Object.keys(headers).forEach((key=>{const header=headers[key];flatHeaders[header.key]=header.value})),options.headers=flatHeaders;const runningTimeout=function(){let timer=null;return{promise:new Promise((function(resolve,reject){timeout&&(timer=setTimeout((()=>{null!=timer&&(timer=null,reject(web_lib_esm_logger.makeError("timeout",Logger.errors.TIMEOUT,{requestBody:bodyify(options.body,flatHeaders["content-type"]),requestMethod:options.method,timeout,url})))}),timeout))})),cancel:function(){null!=timer&&(clearTimeout(timer),timer=null)}}}(),runningFetch=function(){return web_lib_esm_awaiter(this,void 0,void 0,(function*(){for(let attempt=0;attempt=300)&&(runningTimeout.cancel(),web_lib_esm_logger.throwError("bad response",Logger.errors.SERVER_ERROR,{status:response.statusCode,headers:response.headers,body:bodyify(body,response.headers?response.headers["content-type"]:null),requestBody:bodyify(options.body,flatHeaders["content-type"]),requestMethod:options.method,url})),processFunc)try{const result=yield processFunc(body,response);return runningTimeout.cancel(),result}catch(error){if(error.throttleRetry&&attempt"content-type"===k.toLowerCase())).length||(updated.headers=shallowCopy(updated.headers),updated.headers["content-type"]="application/json")}else updated.headers={"content-type":"application/json"};connection=updated}return _fetchData(connection,body,((value,response)=>{let result=null;if(null!=value)try{result=JSON.parse(utf8_toUtf8String(value))}catch(error){web_lib_esm_logger.throwError("invalid JSON",Logger.errors.SERVER_ERROR,{body:value,error})}return processFunc&&(result=processFunc(result,response)),result}))}function poll(func,options){return options||(options={}),null==(options=shallowCopy(options)).floor&&(options.floor=0),null==options.ceiling&&(options.ceiling=1e4),null==options.interval&&(options.interval=250),new Promise((function(resolve,reject){let timer=null,done=!1;const cancel=()=>!done&&(done=!0,timer&&clearTimeout(timer),!0);options.timeout&&(timer=setTimeout((()=>{cancel()&&reject(new Error("timeout"))}),options.timeout));const retryLimit=options.retryLimit;let attempt=0;!function check(){return func().then((function(result){if(void 0!==result)cancel()&&resolve(result);else if(options.oncePoll)options.oncePoll.once("poll",check);else if(options.onceBlock)options.onceBlock.once("block",check);else if(!done){if(attempt++,attempt>retryLimit)return void(cancel()&&reject(new Error("retry limit reached")));let timeout=options.interval*parseInt(String(Math.random()*Math.pow(2,attempt)));timeoutoptions.ceiling&&(timeout=options.ceiling),setTimeout(check,timeout)}return null}),(function(error){cancel()&&reject(error)}))}()}))}var bech32=__webpack_require__(5751),bech32_default=__webpack_require__.n(bech32);const formatter_logger=new Logger("providers/5.7.2");class Formatter{constructor(){this.formats=this.getDefaultFormats()}getDefaultFormats(){const formats={},address=this.address.bind(this),bigNumber=this.bigNumber.bind(this),blockTag=this.blockTag.bind(this),data=this.data.bind(this),hash=this.hash.bind(this),hex=this.hex.bind(this),number=this.number.bind(this),type=this.type.bind(this);return formats.transaction={hash,type,accessList:Formatter.allowNull(this.accessList.bind(this),null),blockHash:Formatter.allowNull(hash,null),blockNumber:Formatter.allowNull(number,null),transactionIndex:Formatter.allowNull(number,null),confirmations:Formatter.allowNull(number,null),from:address,gasPrice:Formatter.allowNull(bigNumber),maxPriorityFeePerGas:Formatter.allowNull(bigNumber),maxFeePerGas:Formatter.allowNull(bigNumber),gasLimit:bigNumber,to:Formatter.allowNull(address,null),value:bigNumber,nonce:number,data,r:Formatter.allowNull(this.uint256),s:Formatter.allowNull(this.uint256),v:Formatter.allowNull(number),creates:Formatter.allowNull(address,null),raw:Formatter.allowNull(data)},formats.transactionRequest={from:Formatter.allowNull(address),nonce:Formatter.allowNull(number),gasLimit:Formatter.allowNull(bigNumber),gasPrice:Formatter.allowNull(bigNumber),maxPriorityFeePerGas:Formatter.allowNull(bigNumber),maxFeePerGas:Formatter.allowNull(bigNumber),to:Formatter.allowNull(address),value:Formatter.allowNull(bigNumber),data:Formatter.allowNull((v=>this.data(v,!0))),type:Formatter.allowNull(number),accessList:Formatter.allowNull(this.accessList.bind(this),null)},formats.receiptLog={transactionIndex:number,blockNumber:number,transactionHash:hash,address,topics:Formatter.arrayOf(hash),data,logIndex:number,blockHash:hash},formats.receipt={to:Formatter.allowNull(this.address,null),from:Formatter.allowNull(this.address,null),contractAddress:Formatter.allowNull(address,null),transactionIndex:number,root:Formatter.allowNull(hex),gasUsed:bigNumber,logsBloom:Formatter.allowNull(data),blockHash:hash,transactionHash:hash,logs:Formatter.arrayOf(this.receiptLog.bind(this)),blockNumber:number,confirmations:Formatter.allowNull(number,null),cumulativeGasUsed:bigNumber,effectiveGasPrice:Formatter.allowNull(bigNumber),status:Formatter.allowNull(number),type},formats.block={hash:Formatter.allowNull(hash),parentHash:hash,number,timestamp:number,nonce:Formatter.allowNull(hex),difficulty:this.difficulty.bind(this),gasLimit:bigNumber,gasUsed:bigNumber,miner:Formatter.allowNull(address),extraData:data,transactions:Formatter.allowNull(Formatter.arrayOf(hash)),baseFeePerGas:Formatter.allowNull(bigNumber)},formats.blockWithTransactions=shallowCopy(formats.block),formats.blockWithTransactions.transactions=Formatter.allowNull(Formatter.arrayOf(this.transactionResponse.bind(this))),formats.filter={fromBlock:Formatter.allowNull(blockTag,void 0),toBlock:Formatter.allowNull(blockTag,void 0),blockHash:Formatter.allowNull(hash,void 0),address:Formatter.allowNull(address,void 0),topics:Formatter.allowNull(this.topics.bind(this),void 0)},formats.filterLog={blockNumber:Formatter.allowNull(number),blockHash:Formatter.allowNull(hash),transactionIndex:number,removed:Formatter.allowNull(this.boolean.bind(this)),address,data:Formatter.allowFalsish(data,"0x"),topics:Formatter.arrayOf(hash),transactionHash:hash,logIndex:number},formats}accessList(accessList){return accessListify(accessList||[])}number(number){return"0x"===number?0:BigNumber.from(number).toNumber()}type(number){return"0x"===number||null==number?0:BigNumber.from(number).toNumber()}bigNumber(value){return BigNumber.from(value)}boolean(value){if("boolean"==typeof value)return value;if("string"==typeof value){if("true"===(value=value.toLowerCase()))return!0;if("false"===value)return!1}throw new Error("invalid boolean - "+value)}hex(value,strict){return"string"==typeof value&&(strict||"0x"===value.substring(0,2)||(value="0x"+value),lib_esm_isHexString(value))?value.toLowerCase():formatter_logger.throwArgumentError("invalid hash","value",value)}data(value,strict){const result=this.hex(value,strict);if(result.length%2!=0)throw new Error("invalid data; odd-length - "+value);return result}address(value){return getAddress(value)}callAddress(value){if(!lib_esm_isHexString(value,32))return null;const address=getAddress(hexDataSlice(value,12));return address===AddressZero?null:address}contractAddress(value){return getContractAddress(value)}blockTag(blockTag){if(null==blockTag)return"latest";if("earliest"===blockTag)return"0x0";switch(blockTag){case"earliest":return"0x0";case"latest":case"pending":case"safe":case"finalized":return blockTag}if("number"==typeof blockTag||lib_esm_isHexString(blockTag))return hexValue(blockTag);throw new Error("invalid blockTag")}hash(value,strict){const result=this.hex(value,strict);return 32!==hexDataLength(result)?formatter_logger.throwArgumentError("invalid hash","value",value):result}difficulty(value){if(null==value)return null;const v=BigNumber.from(value);try{return v.toNumber()}catch(error){}return null}uint256(value){if(!lib_esm_isHexString(value))throw new Error("invalid uint256");return hexZeroPad(value,32)}_block(value,format){null!=value.author&&null==value.miner&&(value.miner=value.author);const difficulty=null!=value._difficulty?value._difficulty:value.difficulty,result=Formatter.check(format,value);return result._difficulty=null==difficulty?null:BigNumber.from(difficulty),result}block(value){return this._block(value,this.formats.block)}blockWithTransactions(value){return this._block(value,this.formats.blockWithTransactions)}transactionRequest(value){return Formatter.check(this.formats.transactionRequest,value)}transactionResponse(transaction){null!=transaction.gas&&null==transaction.gasLimit&&(transaction.gasLimit=transaction.gas),transaction.to&&BigNumber.from(transaction.to).isZero()&&(transaction.to="0x0000000000000000000000000000000000000000"),null!=transaction.input&&null==transaction.data&&(transaction.data=transaction.input),null==transaction.to&&null==transaction.creates&&(transaction.creates=this.contractAddress(transaction)),1!==transaction.type&&2!==transaction.type||null!=transaction.accessList||(transaction.accessList=[]);const result=Formatter.check(this.formats.transaction,transaction);if(null!=transaction.chainId){let chainId=transaction.chainId;lib_esm_isHexString(chainId)&&(chainId=BigNumber.from(chainId).toNumber()),result.chainId=chainId}else{let chainId=transaction.networkId;null==chainId&&null==result.v&&(chainId=transaction.chainId),lib_esm_isHexString(chainId)&&(chainId=BigNumber.from(chainId).toNumber()),"number"!=typeof chainId&&null!=result.v&&(chainId=(result.v-35)/2,chainId<0&&(chainId=0),chainId=parseInt(chainId)),"number"!=typeof chainId&&(chainId=0),result.chainId=chainId}return result.blockHash&&"x"===result.blockHash.replace(/0/g,"")&&(result.blockHash=null),result}transaction(value){return parse(value)}receiptLog(value){return Formatter.check(this.formats.receiptLog,value)}receipt(value){const result=Formatter.check(this.formats.receipt,value);if(null!=result.root)if(result.root.length<=4){const value=BigNumber.from(result.root).toNumber();0===value||1===value?(null!=result.status&&result.status!==value&&formatter_logger.throwArgumentError("alt-root-status/status mismatch","value",{root:result.root,status:result.status}),result.status=value,delete result.root):formatter_logger.throwArgumentError("invalid alt-root-status","value.root",result.root)}else 66!==result.root.length&&formatter_logger.throwArgumentError("invalid root hash","value.root",result.root);return null!=result.status&&(result.byzantium=!0),result}topics(value){return Array.isArray(value)?value.map((v=>this.topics(v))):null!=value?this.hash(value,!0):null}filter(value){return Formatter.check(this.formats.filter,value)}filterLog(value){return Formatter.check(this.formats.filterLog,value)}static check(format,object){const result={};for(const key in format)try{const value=format[key](object[key]);void 0!==value&&(result[key]=value)}catch(error){throw error.checkKey=key,error.checkValue=object[key],error}return result}static allowNull(format,nullValue){return function(value){return null==value?nullValue:format(value)}}static allowFalsish(format,replaceValue){return function(value){return value?format(value):replaceValue}}static arrayOf(format){return function(array){if(!Array.isArray(array))throw new Error("not an array");const result=[];return array.forEach((function(value){result.push(format(value))})),result}}}function isCommunityResourcable(value){return value&&"function"==typeof value.isCommunityResource}function isCommunityResource(value){return isCommunityResourcable(value)&&value.isCommunityResource()}let throttleMessage=!1;function showThrottleMessage(){throttleMessage||(throttleMessage=!0,console.log("========= NOTICE ========="),console.log("Request-Rate Exceeded (this message will not be repeated)"),console.log(""),console.log("The default API keys for each service are provided as a highly-throttled,"),console.log("community resource for low-traffic projects and early prototyping."),console.log(""),console.log("While your application will continue to function, we highly recommended"),console.log("signing up for your own API keys to improve performance, increase your"),console.log("request rate/limit and enable other perks, such as metrics and advanced APIs."),console.log(""),console.log("For more details: https://docs.ethers.io/api-keys/"),console.log("=========================="))}var base_provider_awaiter=function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};const base_provider_logger=new Logger("providers/5.7.2");function checkTopic(topic){return null==topic?"null":(32!==hexDataLength(topic)&&base_provider_logger.throwArgumentError("invalid topic","topic",topic),topic.toLowerCase())}function serializeTopics(topics){for(topics=topics.slice();topics.length>0&&null==topics[topics.length-1];)topics.pop();return topics.map((topic=>{if(Array.isArray(topic)){const unique={};topic.forEach((topic=>{unique[checkTopic(topic)]=!0}));const sorted=Object.keys(unique);return sorted.sort(),sorted.join("|")}return checkTopic(topic)})).join("&")}function base_provider_getEventTag(eventName){if("string"==typeof eventName){if(32===hexDataLength(eventName=eventName.toLowerCase()))return"tx:"+eventName;if(-1===eventName.indexOf(":"))return eventName}else{if(Array.isArray(eventName))return"filter:*:"+serializeTopics(eventName);if(ForkEvent.isForkEvent(eventName))throw base_provider_logger.warn("not implemented"),new Error("not implemented");if(eventName&&"object"==typeof eventName)return"filter:"+(eventName.address||"*")+":"+serializeTopics(eventName.topics||[])}throw new Error("invalid event - "+eventName)}function getTime(){return(new Date).getTime()}function stall(duration){return new Promise((resolve=>{setTimeout(resolve,duration)}))}const PollableEvents=["block","network","pending","poll"];class Event{constructor(tag,listener,once){defineReadOnly(this,"tag",tag),defineReadOnly(this,"listener",listener),defineReadOnly(this,"once",once),this._lastBlockNumber=-2,this._inflight=!1}get event(){switch(this.type){case"tx":return this.hash;case"filter":return this.filter}return this.tag}get type(){return this.tag.split(":")[0]}get hash(){const comps=this.tag.split(":");return"tx"!==comps[0]?null:comps[1]}get filter(){const comps=this.tag.split(":");if("filter"!==comps[0])return null;const address=comps[1],topics=function deserializeTopics(data){return""===data?[]:data.split(/&/g).map((topic=>{if(""===topic)return[];const comps=topic.split("|").map((topic=>"null"===topic?null:topic));return 1===comps.length?comps[0]:comps}))}(comps[2]),filter={};return topics.length>0&&(filter.topics=topics),address&&"*"!==address&&(filter.address=address),filter}pollable(){return this.tag.indexOf(":")>=0||PollableEvents.indexOf(this.tag)>=0}}const coinInfos={0:{symbol:"btc",p2pkh:0,p2sh:5,prefix:"bc"},2:{symbol:"ltc",p2pkh:48,p2sh:50,prefix:"ltc"},3:{symbol:"doge",p2pkh:30,p2sh:22},60:{symbol:"eth",ilk:"eth"},61:{symbol:"etc",ilk:"eth"},700:{symbol:"xdai",ilk:"eth"}};function bytes32ify(value){return hexZeroPad(BigNumber.from(value).toHexString(),32)}function base58Encode(data){return Base58.encode(concat([data,hexDataSlice(sha256(sha256(data)),0,4)]))}const matcherIpfs=new RegExp("^(ipfs)://(.*)$","i"),matchers=[new RegExp("^(https)://(.*)$","i"),new RegExp("^(data):(.*)$","i"),matcherIpfs,new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$","i")];function _parseString(result,start){try{return utf8_toUtf8String(_parseBytes(result,start))}catch(error){}return null}function _parseBytes(result,start){if("0x"===result)return null;const offset=BigNumber.from(hexDataSlice(result,start,start+32)).toNumber(),length=BigNumber.from(hexDataSlice(result,offset,offset+32)).toNumber();return hexDataSlice(result,offset+32,offset+32+length)}function getIpfsLink(link){return link.match(/^ipfs:\/\/ipfs\//i)?link=link.substring(12):link.match(/^ipfs:\/\//i)?link=link.substring(7):base_provider_logger.throwArgumentError("unsupported IPFS format","link",link),`https://gateway.ipfs.io/ipfs/${link}`}function numPad(value){const result=arrayify(value);if(result.length>32)throw new Error("internal; should not happen");const padded=new Uint8Array(32);return padded.set(result,32-result.length),padded}function bytesPad(value){if(value.length%32==0)return value;const result=new Uint8Array(32*Math.ceil(value.length/32));return result.set(value),result}function encodeBytes(datas){const result=[];let byteCount=0;for(let i=0;iBigNumber.from(result).eq(1))).catch((error=>{if(error.code===Logger.errors.CALL_EXCEPTION)return!1;throw this._supportsEip2544=null,error}))),this._supportsEip2544}_fetch(selector,parameters){return base_provider_awaiter(this,void 0,void 0,(function*(){const tx={to:this.address,ccipReadEnabled:!0,data:hexConcat([selector,namehash(this.name),parameters||"0x"])};let parseBytes=!1;(yield this.supportsWildcard())&&(parseBytes=!0,tx.data=hexConcat(["0x9061b923",encodeBytes([dnsEncode(this.name),tx.data])]));try{let result=yield this.provider.call(tx);return arrayify(result).length%32==4&&base_provider_logger.throwError("resolver threw error",Logger.errors.CALL_EXCEPTION,{transaction:tx,data:result}),parseBytes&&(result=_parseBytes(result,0)),result}catch(error){if(error.code===Logger.errors.CALL_EXCEPTION)return null;throw error}}))}_fetchBytes(selector,parameters){return base_provider_awaiter(this,void 0,void 0,(function*(){const result=yield this._fetch(selector,parameters);return null!=result?_parseBytes(result,0):null}))}_getAddress(coinType,hexBytes){const coinInfo=coinInfos[String(coinType)];if(null==coinInfo&&base_provider_logger.throwError(`unsupported coin type: ${coinType}`,Logger.errors.UNSUPPORTED_OPERATION,{operation:`getAddress(${coinType})`}),"eth"===coinInfo.ilk)return this.provider.formatter.address(hexBytes);const bytes=arrayify(hexBytes);if(null!=coinInfo.p2pkh){const p2pkh=hexBytes.match(/^0x76a9([0-9a-f][0-9a-f])([0-9a-f]*)88ac$/);if(p2pkh){const length=parseInt(p2pkh[1],16);if(p2pkh[2].length===2*length&&length>=1&&length<=75)return base58Encode(concat([[coinInfo.p2pkh],"0x"+p2pkh[2]]))}}if(null!=coinInfo.p2sh){const p2sh=hexBytes.match(/^0xa9([0-9a-f][0-9a-f])([0-9a-f]*)87$/);if(p2sh){const length=parseInt(p2sh[1],16);if(p2sh[2].length===2*length&&length>=1&&length<=75)return base58Encode(concat([[coinInfo.p2sh],"0x"+p2sh[2]]))}}if(null!=coinInfo.prefix){const length=bytes[1];let version=bytes[0];if(0===version?20!==length&&32!==length&&(version=-1):version=-1,version>=0&&bytes.length===2+length&&length>=1&&length<=75){const words=bech32_default().toWords(bytes.slice(2));return words.unshift(version),bech32_default().encode(coinInfo.prefix,words)}}return null}getAddress(coinType){return base_provider_awaiter(this,void 0,void 0,(function*(){if(null==coinType&&(coinType=60),60===coinType)try{const result=yield this._fetch("0x3b3b57de");return"0x"===result||result===HashZero?null:this.provider.formatter.callAddress(result)}catch(error){if(error.code===Logger.errors.CALL_EXCEPTION)return null;throw error}const hexBytes=yield this._fetchBytes("0xf1cb7e06",bytes32ify(coinType));if(null==hexBytes||"0x"===hexBytes)return null;const address=this._getAddress(coinType,hexBytes);return null==address&&base_provider_logger.throwError("invalid or unsupported coin data",Logger.errors.UNSUPPORTED_OPERATION,{operation:`getAddress(${coinType})`,coinType,data:hexBytes}),address}))}getAvatar(){return base_provider_awaiter(this,void 0,void 0,(function*(){const linkage=[{type:"name",content:this.name}];try{const avatar=yield this.getText("avatar");if(null==avatar)return null;for(let i=0;iurlSafe[a]))}return base_provider_logger.throwError("invalid or unsupported content hash data",Logger.errors.UNSUPPORTED_OPERATION,{operation:"getContentHash()",data:hexBytes})}))}getText(key){return base_provider_awaiter(this,void 0,void 0,(function*(){let keyBytes=toUtf8Bytes(key);keyBytes=concat([bytes32ify(64),bytes32ify(keyBytes.length),keyBytes]),keyBytes.length%32!=0&&(keyBytes=concat([keyBytes,hexZeroPad("0x",32-key.length%32)]));const hexBytes=yield this._fetchBytes("0x59d1d43c",hexlify(keyBytes));return null==hexBytes||"0x"===hexBytes?null:utf8_toUtf8String(hexBytes)}))}}let defaultFormatter=null,nextPollId=1;class BaseProvider extends Provider{constructor(network){if(super(),this._events=[],this._emitted={block:-2},this.disableCcipRead=!1,this.formatter=new.target.getFormatter(),defineReadOnly(this,"anyNetwork","any"===network),this.anyNetwork&&(network=this.detectNetwork()),network instanceof Promise)this._networkPromise=network,network.catch((error=>{})),this._ready().catch((error=>{}));else{const knownNetwork=getStatic(new.target,"getNetwork")(network);knownNetwork?(defineReadOnly(this,"_network",knownNetwork),this.emit("network",knownNetwork,null)):base_provider_logger.throwArgumentError("invalid network","network",network)}this._maxInternalBlockNumber=-1024,this._lastBlockNumber=-2,this._maxFilterBlockRange=10,this._pollingInterval=4e3,this._fastQueryDate=0}_ready(){return base_provider_awaiter(this,void 0,void 0,(function*(){if(null==this._network){let network=null;if(this._networkPromise)try{network=yield this._networkPromise}catch(error){}null==network&&(network=yield this.detectNetwork()),network||base_provider_logger.throwError("no network detected",Logger.errors.UNKNOWN_ERROR,{}),null==this._network&&(this.anyNetwork?this._network=network:defineReadOnly(this,"_network",network),this.emit("network",network,null))}return this._network}))}get ready(){return poll((()=>this._ready().then((network=>network),(error=>{if(error.code!==Logger.errors.NETWORK_ERROR||"noNetwork"!==error.event)throw error}))))}static getFormatter(){return null==defaultFormatter&&(defaultFormatter=new Formatter),defaultFormatter}static getNetwork(network){return getNetwork(null==network?"homestead":network)}ccipReadFetch(tx,calldata,urls){return base_provider_awaiter(this,void 0,void 0,(function*(){if(this.disableCcipRead||0===urls.length)return null;const sender=tx.to.toLowerCase(),data=calldata.toLowerCase(),errorMessages=[];for(let i=0;i=0?null:JSON.stringify({data,sender}),result=yield fetchJson({url:href,errorPassThrough:!0},json,((value,response)=>(value.status=response.statusCode,value)));if(result.data)return result.data;const errorMessage=result.message||"unknown error";if(result.status>=400&&result.status<500)return base_provider_logger.throwError(`response not found during CCIP fetch: ${errorMessage}`,Logger.errors.SERVER_ERROR,{url,errorMessage});errorMessages.push(errorMessage)}return base_provider_logger.throwError(`error encountered during CCIP fetch: ${errorMessages.map((m=>JSON.stringify(m))).join(", ")}`,Logger.errors.SERVER_ERROR,{urls,errorMessages})}))}_getInternalBlockNumber(maxAge){return base_provider_awaiter(this,void 0,void 0,(function*(){if(yield this._ready(),maxAge>0)for(;this._internalBlockNumber;){const internalBlockNumber=this._internalBlockNumber;try{const result=yield internalBlockNumber;if(getTime()-result.respTime<=maxAge)return result.blockNumber;break}catch(error){if(this._internalBlockNumber===internalBlockNumber)break}}const reqTime=getTime(),checkInternalBlockNumber=resolveProperties({blockNumber:this.perform("getBlockNumber",{}),networkError:this.getNetwork().then((network=>null),(error=>error))}).then((({blockNumber,networkError})=>{if(networkError)throw this._internalBlockNumber===checkInternalBlockNumber&&(this._internalBlockNumber=null),networkError;const respTime=getTime();return(blockNumber=BigNumber.from(blockNumber).toNumber()){this._internalBlockNumber===checkInternalBlockNumber&&(this._internalBlockNumber=null)})),(yield checkInternalBlockNumber).blockNumber}))}poll(){return base_provider_awaiter(this,void 0,void 0,(function*(){const pollId=nextPollId++,runners=[];let blockNumber=null;try{blockNumber=yield this._getInternalBlockNumber(100+this.pollingInterval/2)}catch(error){return void this.emit("error",error)}if(this._setFastBlockNumber(blockNumber),this.emit("poll",pollId,blockNumber),blockNumber!==this._lastBlockNumber){if(-2===this._emitted.block&&(this._emitted.block=blockNumber-1),Math.abs(this._emitted.block-blockNumber)>1e3)base_provider_logger.warn(`network block skew detected; skipping block events (emitted=${this._emitted.block} blockNumber${blockNumber})`),this.emit("error",base_provider_logger.makeError("network block skew detected",Logger.errors.NETWORK_ERROR,{blockNumber,event:"blockSkew",previousBlockNumber:this._emitted.block})),this.emit("block",blockNumber);else for(let i=this._emitted.block+1;i<=blockNumber;i++)this.emit("block",i);this._emitted.block!==blockNumber&&(this._emitted.block=blockNumber,Object.keys(this._emitted).forEach((key=>{if("block"===key)return;const eventBlockNumber=this._emitted[key];"pending"!==eventBlockNumber&&blockNumber-eventBlockNumber>12&&delete this._emitted[key]}))),-2===this._lastBlockNumber&&(this._lastBlockNumber=blockNumber-1),this._events.forEach((event=>{switch(event.type){case"tx":{const hash=event.hash;let runner=this.getTransactionReceipt(hash).then((receipt=>receipt&&null!=receipt.blockNumber?(this._emitted["t:"+hash]=receipt.blockNumber,this.emit(hash,receipt),null):null)).catch((error=>{this.emit("error",error)}));runners.push(runner);break}case"filter":if(!event._inflight){event._inflight=!0,-2===event._lastBlockNumber&&(event._lastBlockNumber=blockNumber-1);const filter=event.filter;filter.fromBlock=event._lastBlockNumber+1,filter.toBlock=blockNumber;const minFromBlock=filter.toBlock-this._maxFilterBlockRange;minFromBlock>filter.fromBlock&&(filter.fromBlock=minFromBlock),filter.fromBlock<0&&(filter.fromBlock=0);const runner=this.getLogs(filter).then((logs=>{event._inflight=!1,0!==logs.length&&logs.forEach((log=>{log.blockNumber>event._lastBlockNumber&&(event._lastBlockNumber=log.blockNumber),this._emitted["b:"+log.blockHash]=log.blockNumber,this._emitted["t:"+log.transactionHash]=log.blockNumber,this.emit(filter,log)}))})).catch((error=>{this.emit("error",error),event._inflight=!1}));runners.push(runner)}}})),this._lastBlockNumber=blockNumber,Promise.all(runners).then((()=>{this.emit("didPoll",pollId)})).catch((error=>{this.emit("error",error)}))}else this.emit("didPoll",pollId)}))}resetEventsBlock(blockNumber){this._lastBlockNumber=blockNumber-1,this.polling&&this.poll()}get network(){return this._network}detectNetwork(){return base_provider_awaiter(this,void 0,void 0,(function*(){return base_provider_logger.throwError("provider does not support network detection",Logger.errors.UNSUPPORTED_OPERATION,{operation:"provider.detectNetwork"})}))}getNetwork(){return base_provider_awaiter(this,void 0,void 0,(function*(){const network=yield this._ready(),currentNetwork=yield this.detectNetwork();if(network.chainId!==currentNetwork.chainId){if(this.anyNetwork)return this._network=currentNetwork,this._lastBlockNumber=-2,this._fastBlockNumber=null,this._fastBlockNumberPromise=null,this._fastQueryDate=0,this._emitted.block=-2,this._maxInternalBlockNumber=-1024,this._internalBlockNumber=null,this.emit("network",currentNetwork,network),yield stall(0),this._network;const error=base_provider_logger.makeError("underlying network changed",Logger.errors.NETWORK_ERROR,{event:"changed",network,detectedNetwork:currentNetwork});throw this.emit("error",error),error}return network}))}get blockNumber(){return this._getInternalBlockNumber(100+this.pollingInterval/2).then((blockNumber=>{this._setFastBlockNumber(blockNumber)}),(error=>{})),null!=this._fastBlockNumber?this._fastBlockNumber:-1}get polling(){return null!=this._poller}set polling(value){value&&!this._poller?(this._poller=setInterval((()=>{this.poll()}),this.pollingInterval),this._bootstrapPoll||(this._bootstrapPoll=setTimeout((()=>{this.poll(),this._bootstrapPoll=setTimeout((()=>{this._poller||this.poll(),this._bootstrapPoll=null}),this.pollingInterval)}),0))):!value&&this._poller&&(clearInterval(this._poller),this._poller=null)}get pollingInterval(){return this._pollingInterval}set pollingInterval(value){if("number"!=typeof value||value<=0||parseInt(String(value))!=value)throw new Error("invalid polling interval");this._pollingInterval=value,this._poller&&(clearInterval(this._poller),this._poller=setInterval((()=>{this.poll()}),this._pollingInterval))}_getFastBlockNumber(){const now=getTime();return now-this._fastQueryDate>2*this._pollingInterval&&(this._fastQueryDate=now,this._fastBlockNumberPromise=this.getBlockNumber().then((blockNumber=>((null==this._fastBlockNumber||blockNumber>this._fastBlockNumber)&&(this._fastBlockNumber=blockNumber),this._fastBlockNumber)))),this._fastBlockNumberPromise}_setFastBlockNumber(blockNumber){null!=this._fastBlockNumber&&blockNumberthis._fastBlockNumber)&&(this._fastBlockNumber=blockNumber,this._fastBlockNumberPromise=Promise.resolve(blockNumber)))}waitForTransaction(transactionHash,confirmations,timeout){return base_provider_awaiter(this,void 0,void 0,(function*(){return this._waitForTransaction(transactionHash,null==confirmations?1:confirmations,timeout||0,null)}))}_waitForTransaction(transactionHash,confirmations,timeout,replaceable){return base_provider_awaiter(this,void 0,void 0,(function*(){const receipt=yield this.getTransactionReceipt(transactionHash);return(receipt?receipt.confirmations:0)>=confirmations?receipt:new Promise(((resolve,reject)=>{const cancelFuncs=[];let done=!1;const alreadyDone=function(){return!!done||(done=!0,cancelFuncs.forEach((func=>{func()})),!1)},minedHandler=receipt=>{receipt.confirmations{this.removeListener(transactionHash,minedHandler)})),replaceable){let lastBlockNumber=replaceable.startBlock,scannedBlock=null;const replaceHandler=blockNumber=>base_provider_awaiter(this,void 0,void 0,(function*(){done||(yield stall(1e3),this.getTransactionCount(replaceable.from).then((nonce=>base_provider_awaiter(this,void 0,void 0,(function*(){if(!done){if(nonce<=replaceable.nonce)lastBlockNumber=blockNumber;else{{const mined=yield this.getTransaction(transactionHash);if(mined&&null!=mined.blockNumber)return}for(null==scannedBlock&&(scannedBlock=lastBlockNumber-3,scannedBlock{done||this.once("block",replaceHandler)})))}));if(done)return;this.once("block",replaceHandler),cancelFuncs.push((()=>{this.removeListener("block",replaceHandler)}))}if("number"==typeof timeout&&timeout>0){const timer=setTimeout((()=>{alreadyDone()||reject(base_provider_logger.makeError("timeout exceeded",Logger.errors.TIMEOUT,{timeout}))}),timeout);timer.unref&&timer.unref(),cancelFuncs.push((()=>{clearTimeout(timer)}))}}))}))}getBlockNumber(){return base_provider_awaiter(this,void 0,void 0,(function*(){return this._getInternalBlockNumber(0)}))}getGasPrice(){return base_provider_awaiter(this,void 0,void 0,(function*(){yield this.getNetwork();const result=yield this.perform("getGasPrice",{});try{return BigNumber.from(result)}catch(error){return base_provider_logger.throwError("bad result from backend",Logger.errors.SERVER_ERROR,{method:"getGasPrice",result,error})}}))}getBalance(addressOrName,blockTag){return base_provider_awaiter(this,void 0,void 0,(function*(){yield this.getNetwork();const params=yield resolveProperties({address:this._getAddress(addressOrName),blockTag:this._getBlockTag(blockTag)}),result=yield this.perform("getBalance",params);try{return BigNumber.from(result)}catch(error){return base_provider_logger.throwError("bad result from backend",Logger.errors.SERVER_ERROR,{method:"getBalance",params,result,error})}}))}getTransactionCount(addressOrName,blockTag){return base_provider_awaiter(this,void 0,void 0,(function*(){yield this.getNetwork();const params=yield resolveProperties({address:this._getAddress(addressOrName),blockTag:this._getBlockTag(blockTag)}),result=yield this.perform("getTransactionCount",params);try{return BigNumber.from(result).toNumber()}catch(error){return base_provider_logger.throwError("bad result from backend",Logger.errors.SERVER_ERROR,{method:"getTransactionCount",params,result,error})}}))}getCode(addressOrName,blockTag){return base_provider_awaiter(this,void 0,void 0,(function*(){yield this.getNetwork();const params=yield resolveProperties({address:this._getAddress(addressOrName),blockTag:this._getBlockTag(blockTag)}),result=yield this.perform("getCode",params);try{return hexlify(result)}catch(error){return base_provider_logger.throwError("bad result from backend",Logger.errors.SERVER_ERROR,{method:"getCode",params,result,error})}}))}getStorageAt(addressOrName,position,blockTag){return base_provider_awaiter(this,void 0,void 0,(function*(){yield this.getNetwork();const params=yield resolveProperties({address:this._getAddress(addressOrName),blockTag:this._getBlockTag(blockTag),position:Promise.resolve(position).then((p=>hexValue(p)))}),result=yield this.perform("getStorageAt",params);try{return hexlify(result)}catch(error){return base_provider_logger.throwError("bad result from backend",Logger.errors.SERVER_ERROR,{method:"getStorageAt",params,result,error})}}))}_wrapTransaction(tx,hash,startBlock){if(null!=hash&&32!==hexDataLength(hash))throw new Error("invalid response - sendTransaction");const result=tx;return null!=hash&&tx.hash!==hash&&base_provider_logger.throwError("Transaction hash mismatch from Provider.sendTransaction.",Logger.errors.UNKNOWN_ERROR,{expectedHash:tx.hash,returnedHash:hash}),result.wait=(confirms,timeout)=>base_provider_awaiter(this,void 0,void 0,(function*(){let replacement;null==confirms&&(confirms=1),null==timeout&&(timeout=0),0!==confirms&&null!=startBlock&&(replacement={data:tx.data,from:tx.from,nonce:tx.nonce,to:tx.to,value:tx.value,startBlock});const receipt=yield this._waitForTransaction(tx.hash,confirms,timeout,replacement);return null==receipt&&0===confirms?null:(this._emitted["t:"+tx.hash]=receipt.blockNumber,0===receipt.status&&base_provider_logger.throwError("transaction failed",Logger.errors.CALL_EXCEPTION,{transactionHash:tx.hash,transaction:tx,receipt}),receipt)})),result}sendTransaction(signedTransaction){return base_provider_awaiter(this,void 0,void 0,(function*(){yield this.getNetwork();const hexTx=yield Promise.resolve(signedTransaction).then((t=>hexlify(t))),tx=this.formatter.transaction(signedTransaction);null==tx.confirmations&&(tx.confirmations=0);const blockNumber=yield this._getInternalBlockNumber(100+2*this.pollingInterval);try{const hash=yield this.perform("sendTransaction",{signedTransaction:hexTx});return this._wrapTransaction(tx,hash,blockNumber)}catch(error){throw error.transaction=tx,error.transactionHash=tx.hash,error}}))}_getTransactionRequest(transaction){return base_provider_awaiter(this,void 0,void 0,(function*(){const values=yield transaction,tx={};return["from","to"].forEach((key=>{null!=values[key]&&(tx[key]=Promise.resolve(values[key]).then((v=>v?this._getAddress(v):null)))})),["gasLimit","gasPrice","maxFeePerGas","maxPriorityFeePerGas","value"].forEach((key=>{null!=values[key]&&(tx[key]=Promise.resolve(values[key]).then((v=>v?BigNumber.from(v):null)))})),["type"].forEach((key=>{null!=values[key]&&(tx[key]=Promise.resolve(values[key]).then((v=>null!=v?v:null)))})),values.accessList&&(tx.accessList=this.formatter.accessList(values.accessList)),["data"].forEach((key=>{null!=values[key]&&(tx[key]=Promise.resolve(values[key]).then((v=>v?hexlify(v):null)))})),this.formatter.transactionRequest(yield resolveProperties(tx))}))}_getFilter(filter){return base_provider_awaiter(this,void 0,void 0,(function*(){filter=yield filter;const result={};return null!=filter.address&&(result.address=this._getAddress(filter.address)),["blockHash","topics"].forEach((key=>{null!=filter[key]&&(result[key]=filter[key])})),["fromBlock","toBlock"].forEach((key=>{null!=filter[key]&&(result[key]=this._getBlockTag(filter[key]))})),this.formatter.filter(yield resolveProperties(result))}))}_call(transaction,blockTag,attempt){return base_provider_awaiter(this,void 0,void 0,(function*(){attempt>=10&&base_provider_logger.throwError("CCIP read exceeded maximum redirections",Logger.errors.SERVER_ERROR,{redirects:attempt,transaction});const txSender=transaction.to,result=yield this.perform("call",{transaction,blockTag});if(attempt>=0&&"latest"===blockTag&&null!=txSender&&"0x556f1830"===result.substring(0,10)&&hexDataLength(result)%32==4)try{const data=hexDataSlice(result,4),sender=hexDataSlice(data,0,32);BigNumber.from(sender).eq(txSender)||base_provider_logger.throwError("CCIP Read sender did not match",Logger.errors.CALL_EXCEPTION,{name:"OffchainLookup",signature:"OffchainLookup(address,string[],bytes,bytes4,bytes)",transaction,data:result});const urls=[],urlsOffset=BigNumber.from(hexDataSlice(data,32,64)).toNumber(),urlsLength=BigNumber.from(hexDataSlice(data,urlsOffset,urlsOffset+32)).toNumber(),urlsData=hexDataSlice(data,urlsOffset+32);for(let u=0;ubase_provider_awaiter(this,void 0,void 0,(function*(){const block=yield this.perform("getBlock",params);if(null==block)return null!=params.blockHash&&null==this._emitted["b:"+params.blockHash]||null!=params.blockTag&&blockNumber>this._emitted.block?null:void 0;if(includeTransactions){let blockNumber=null;for(let i=0;ithis._wrapTransaction(tx))),blockWithTxs}return this.formatter.block(block)}))),{oncePoll:this})}))}getBlock(blockHashOrBlockTag){return this._getBlock(blockHashOrBlockTag,!1)}getBlockWithTransactions(blockHashOrBlockTag){return this._getBlock(blockHashOrBlockTag,!0)}getTransaction(transactionHash){return base_provider_awaiter(this,void 0,void 0,(function*(){yield this.getNetwork(),transactionHash=yield transactionHash;const params={transactionHash:this.formatter.hash(transactionHash,!0)};return poll((()=>base_provider_awaiter(this,void 0,void 0,(function*(){const result=yield this.perform("getTransaction",params);if(null==result)return null==this._emitted["t:"+transactionHash]?null:void 0;const tx=this.formatter.transactionResponse(result);if(null==tx.blockNumber)tx.confirmations=0;else if(null==tx.confirmations){let confirmations=(yield this._getInternalBlockNumber(100+2*this.pollingInterval))-tx.blockNumber+1;confirmations<=0&&(confirmations=1),tx.confirmations=confirmations}return this._wrapTransaction(tx)}))),{oncePoll:this})}))}getTransactionReceipt(transactionHash){return base_provider_awaiter(this,void 0,void 0,(function*(){yield this.getNetwork(),transactionHash=yield transactionHash;const params={transactionHash:this.formatter.hash(transactionHash,!0)};return poll((()=>base_provider_awaiter(this,void 0,void 0,(function*(){const result=yield this.perform("getTransactionReceipt",params);if(null==result)return null==this._emitted["t:"+transactionHash]?null:void 0;if(null==result.blockHash)return;const receipt=this.formatter.receipt(result);if(null==receipt.blockNumber)receipt.confirmations=0;else if(null==receipt.confirmations){let confirmations=(yield this._getInternalBlockNumber(100+2*this.pollingInterval))-receipt.blockNumber+1;confirmations<=0&&(confirmations=1),receipt.confirmations=confirmations}return receipt}))),{oncePoll:this})}))}getLogs(filter){return base_provider_awaiter(this,void 0,void 0,(function*(){yield this.getNetwork();const params=yield resolveProperties({filter:this._getFilter(filter)}),logs=yield this.perform("getLogs",params);return logs.forEach((log=>{null==log.removed&&(log.removed=!1)})),Formatter.arrayOf(this.formatter.filterLog.bind(this.formatter))(logs)}))}getEtherPrice(){return base_provider_awaiter(this,void 0,void 0,(function*(){return yield this.getNetwork(),this.perform("getEtherPrice",{})}))}_getBlockTag(blockTag){return base_provider_awaiter(this,void 0,void 0,(function*(){if("number"==typeof(blockTag=yield blockTag)&&blockTag<0){blockTag%1&&base_provider_logger.throwArgumentError("invalid BlockTag","blockTag",blockTag);let blockNumber=yield this._getInternalBlockNumber(100+2*this.pollingInterval);return blockNumber+=blockTag,blockNumber<0&&(blockNumber=0),this.formatter.blockTag(blockNumber)}return this.formatter.blockTag(blockTag)}))}getResolver(name){return base_provider_awaiter(this,void 0,void 0,(function*(){let currentName=name;for(;;){if(""===currentName||"."===currentName)return null;if("eth"!==name&&"eth"===currentName)return null;const addr=yield this._getResolver(currentName,"getResolver");if(null!=addr){const resolver=new Resolver(this,addr,name);return currentName===name||(yield resolver.supportsWildcard())?resolver:null}currentName=currentName.split(".").slice(1).join(".")}}))}_getResolver(name,operation){return base_provider_awaiter(this,void 0,void 0,(function*(){null==operation&&(operation="ENS");const network=yield this.getNetwork();network.ensAddress||base_provider_logger.throwError("network does not support ENS",Logger.errors.UNSUPPORTED_OPERATION,{operation,network:network.name});try{const addrData=yield this.call({to:network.ensAddress,data:"0x0178b8bf"+namehash(name).substring(2)});return this.formatter.callAddress(addrData)}catch(error){}return null}))}resolveName(name){return base_provider_awaiter(this,void 0,void 0,(function*(){name=yield name;try{return Promise.resolve(this.formatter.address(name))}catch(error){if(lib_esm_isHexString(name))throw error}"string"!=typeof name&&base_provider_logger.throwArgumentError("invalid ENS name","name",name);const resolver=yield this.getResolver(name);return resolver?yield resolver.getAddress():null}))}lookupAddress(address){return base_provider_awaiter(this,void 0,void 0,(function*(){address=yield address;const node=(address=this.formatter.address(address)).substring(2).toLowerCase()+".addr.reverse",resolverAddr=yield this._getResolver(node,"lookupAddress");if(null==resolverAddr)return null;const name=_parseString(yield this.call({to:resolverAddr,data:"0x691f3431"+namehash(node).substring(2)}),0);return(yield this.resolveName(name))!=address?null:name}))}getAvatar(nameOrAddress){return base_provider_awaiter(this,void 0,void 0,(function*(){let resolver=null;if(lib_esm_isHexString(nameOrAddress)){const node=this.formatter.address(nameOrAddress).substring(2).toLowerCase()+".addr.reverse",resolverAddress=yield this._getResolver(node,"getAvatar");if(!resolverAddress)return null;resolver=new Resolver(this,resolverAddress,node);try{const avatar=yield resolver.getAvatar();if(avatar)return avatar.url}catch(error){if(error.code!==Logger.errors.CALL_EXCEPTION)throw error}try{const name=_parseString(yield this.call({to:resolverAddress,data:"0x691f3431"+namehash(node).substring(2)}),0);resolver=yield this.getResolver(name)}catch(error){if(error.code!==Logger.errors.CALL_EXCEPTION)throw error;return null}}else if(resolver=yield this.getResolver(nameOrAddress),!resolver)return null;const avatar=yield resolver.getAvatar();return null==avatar?null:avatar.url}))}perform(method,params){return base_provider_logger.throwError(method+" not implemented",Logger.errors.NOT_IMPLEMENTED,{operation:method})}_startEvent(event){this.polling=this._events.filter((e=>e.pollable())).length>0}_stopEvent(event){this.polling=this._events.filter((e=>e.pollable())).length>0}_addEventListener(eventName,listener,once){const event=new Event(base_provider_getEventTag(eventName),listener,once);return this._events.push(event),this._startEvent(event),this}on(eventName,listener){return this._addEventListener(eventName,listener,!1)}once(eventName,listener){return this._addEventListener(eventName,listener,!0)}emit(eventName,...args){let result=!1,stopped=[],eventTag=base_provider_getEventTag(eventName);return this._events=this._events.filter((event=>event.tag!==eventTag||(setTimeout((()=>{event.listener.apply(this,args)}),0),result=!0,!event.once||(stopped.push(event),!1)))),stopped.forEach((event=>{this._stopEvent(event)})),result}listenerCount(eventName){if(!eventName)return this._events.length;let eventTag=base_provider_getEventTag(eventName);return this._events.filter((event=>event.tag===eventTag)).length}listeners(eventName){if(null==eventName)return this._events.map((event=>event.listener));let eventTag=base_provider_getEventTag(eventName);return this._events.filter((event=>event.tag===eventTag)).map((event=>event.listener))}off(eventName,listener){if(null==listener)return this.removeAllListeners(eventName);const stopped=[];let found=!1,eventTag=base_provider_getEventTag(eventName);return this._events=this._events.filter((event=>event.tag!==eventTag||event.listener!=listener||(!!found||(found=!0,stopped.push(event),!1)))),stopped.forEach((event=>{this._stopEvent(event)})),this}removeAllListeners(eventName){let stopped=[];if(null==eventName)stopped=this._events,this._events=[];else{const eventTag=base_provider_getEventTag(eventName);this._events=this._events.filter((event=>event.tag!==eventTag||(stopped.push(event),!1)))}return stopped.forEach((event=>{this._stopEvent(event)})),this}}var json_rpc_provider_awaiter=function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};const json_rpc_provider_logger=new Logger("providers/5.7.2"),errorGas=["call","estimateGas"];function spelunk(value,requireData){if(null==value)return null;if("string"==typeof value.message&&value.message.match("reverted")){const data=lib_esm_isHexString(value.data)?value.data:null;if(!requireData||data)return{message:value.message,data}}if("object"==typeof value){for(const key in value){const result=spelunk(value[key],requireData);if(result)return result}return null}if("string"==typeof value)try{return spelunk(JSON.parse(value),requireData)}catch(error){}return null}function checkError(method,error,params){const transaction=params.transaction||params.signedTransaction;if("call"===method){const result=spelunk(error,!0);if(result)return result.data;json_rpc_provider_logger.throwError("missing revert data in call exception; Transaction reverted without a reason string",Logger.errors.CALL_EXCEPTION,{data:"0x",transaction,error})}if("estimateGas"===method){let result=spelunk(error.body,!1);null==result&&(result=spelunk(error,!1)),result&&json_rpc_provider_logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit",Logger.errors.UNPREDICTABLE_GAS_LIMIT,{reason:result.message,method,transaction,error})}let message=error.message;throw error.code===Logger.errors.SERVER_ERROR&&error.error&&"string"==typeof error.error.message?message=error.error.message:"string"==typeof error.body?message=error.body:"string"==typeof error.responseText&&(message=error.responseText),message=(message||"").toLowerCase(),message.match(/insufficient funds|base fee exceeds gas limit|InsufficientFunds/i)&&json_rpc_provider_logger.throwError("insufficient funds for intrinsic transaction cost",Logger.errors.INSUFFICIENT_FUNDS,{error,method,transaction}),message.match(/nonce (is )?too low/i)&&json_rpc_provider_logger.throwError("nonce has already been used",Logger.errors.NONCE_EXPIRED,{error,method,transaction}),message.match(/replacement transaction underpriced|transaction gas price.*too low/i)&&json_rpc_provider_logger.throwError("replacement fee too low",Logger.errors.REPLACEMENT_UNDERPRICED,{error,method,transaction}),message.match(/only replay-protected/i)&&json_rpc_provider_logger.throwError("legacy pre-eip-155 transactions not supported",Logger.errors.UNSUPPORTED_OPERATION,{error,method,transaction}),errorGas.indexOf(method)>=0&&message.match(/gas required exceeds allowance|always failing transaction|execution reverted|revert/)&&json_rpc_provider_logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit",Logger.errors.UNPREDICTABLE_GAS_LIMIT,{error,method,transaction}),error}function timer(timeout){return new Promise((function(resolve){setTimeout(resolve,timeout)}))}function getResult(payload){if(payload.error){const error=new Error(payload.error.message);throw error.code=payload.error.code,error.data=payload.error.data,error}return payload.result}function getLowerCase(value){return value?value.toLowerCase():value}const json_rpc_provider_constructorGuard={};class JsonRpcSigner extends Signer{constructor(constructorGuard,provider,addressOrIndex){if(super(),constructorGuard!==json_rpc_provider_constructorGuard)throw new Error("do not call the JsonRpcSigner constructor directly; use provider.getSigner");defineReadOnly(this,"provider",provider),null==addressOrIndex&&(addressOrIndex=0),"string"==typeof addressOrIndex?(defineReadOnly(this,"_address",this.provider.formatter.address(addressOrIndex)),defineReadOnly(this,"_index",null)):"number"==typeof addressOrIndex?(defineReadOnly(this,"_index",addressOrIndex),defineReadOnly(this,"_address",null)):json_rpc_provider_logger.throwArgumentError("invalid address or index","addressOrIndex",addressOrIndex)}connect(provider){return json_rpc_provider_logger.throwError("cannot alter JSON-RPC Signer connection",Logger.errors.UNSUPPORTED_OPERATION,{operation:"connect"})}connectUnchecked(){return new UncheckedJsonRpcSigner(json_rpc_provider_constructorGuard,this.provider,this._address||this._index)}getAddress(){return this._address?Promise.resolve(this._address):this.provider.send("eth_accounts",[]).then((accounts=>(accounts.length<=this._index&&json_rpc_provider_logger.throwError("unknown account #"+this._index,Logger.errors.UNSUPPORTED_OPERATION,{operation:"getAddress"}),this.provider.formatter.address(accounts[this._index]))))}sendUncheckedTransaction(transaction){transaction=shallowCopy(transaction);const fromAddress=this.getAddress().then((address=>(address&&(address=address.toLowerCase()),address)));if(null==transaction.gasLimit){const estimate=shallowCopy(transaction);estimate.from=fromAddress,transaction.gasLimit=this.provider.estimateGas(estimate)}return null!=transaction.to&&(transaction.to=Promise.resolve(transaction.to).then((to=>json_rpc_provider_awaiter(this,void 0,void 0,(function*(){if(null==to)return null;const address=yield this.provider.resolveName(to);return null==address&&json_rpc_provider_logger.throwArgumentError("provided ENS name resolves to null","tx.to",to),address}))))),resolveProperties({tx:resolveProperties(transaction),sender:fromAddress}).then((({tx,sender})=>{null!=tx.from?tx.from.toLowerCase()!==sender&&json_rpc_provider_logger.throwArgumentError("from address mismatch","transaction",transaction):tx.from=sender;const hexTx=this.provider.constructor.hexlifyTransaction(tx,{from:!0});return this.provider.send("eth_sendTransaction",[hexTx]).then((hash=>hash),(error=>("string"==typeof error.message&&error.message.match(/user denied/i)&&json_rpc_provider_logger.throwError("user rejected transaction",Logger.errors.ACTION_REJECTED,{action:"sendTransaction",transaction:tx}),checkError("sendTransaction",error,hexTx))))}))}signTransaction(transaction){return json_rpc_provider_logger.throwError("signing transactions is unsupported",Logger.errors.UNSUPPORTED_OPERATION,{operation:"signTransaction"})}sendTransaction(transaction){return json_rpc_provider_awaiter(this,void 0,void 0,(function*(){const blockNumber=yield this.provider._getInternalBlockNumber(100+2*this.provider.pollingInterval),hash=yield this.sendUncheckedTransaction(transaction);try{return yield poll((()=>json_rpc_provider_awaiter(this,void 0,void 0,(function*(){const tx=yield this.provider.getTransaction(hash);if(null!==tx)return this.provider._wrapTransaction(tx,hash,blockNumber)}))),{oncePoll:this.provider})}catch(error){throw error.transactionHash=hash,error}}))}signMessage(message){return json_rpc_provider_awaiter(this,void 0,void 0,(function*(){const data="string"==typeof message?toUtf8Bytes(message):message,address=yield this.getAddress();try{return yield this.provider.send("personal_sign",[hexlify(data),address.toLowerCase()])}catch(error){throw"string"==typeof error.message&&error.message.match(/user denied/i)&&json_rpc_provider_logger.throwError("user rejected signing",Logger.errors.ACTION_REJECTED,{action:"signMessage",from:address,messageData:message}),error}}))}_legacySignMessage(message){return json_rpc_provider_awaiter(this,void 0,void 0,(function*(){const data="string"==typeof message?toUtf8Bytes(message):message,address=yield this.getAddress();try{return yield this.provider.send("eth_sign",[address.toLowerCase(),hexlify(data)])}catch(error){throw"string"==typeof error.message&&error.message.match(/user denied/i)&&json_rpc_provider_logger.throwError("user rejected signing",Logger.errors.ACTION_REJECTED,{action:"_legacySignMessage",from:address,messageData:message}),error}}))}_signTypedData(domain,types,value){return json_rpc_provider_awaiter(this,void 0,void 0,(function*(){const populated=yield TypedDataEncoder.resolveNames(domain,types,value,(name=>this.provider.resolveName(name))),address=yield this.getAddress();try{return yield this.provider.send("eth_signTypedData_v4",[address.toLowerCase(),JSON.stringify(TypedDataEncoder.getPayload(populated.domain,types,populated.value))])}catch(error){throw"string"==typeof error.message&&error.message.match(/user denied/i)&&json_rpc_provider_logger.throwError("user rejected signing",Logger.errors.ACTION_REJECTED,{action:"_signTypedData",from:address,messageData:{domain:populated.domain,types,value:populated.value}}),error}}))}unlock(password){return json_rpc_provider_awaiter(this,void 0,void 0,(function*(){const provider=this.provider,address=yield this.getAddress();return provider.send("personal_unlockAccount",[address.toLowerCase(),password,null])}))}}class UncheckedJsonRpcSigner extends JsonRpcSigner{sendTransaction(transaction){return this.sendUncheckedTransaction(transaction).then((hash=>({hash,nonce:null,gasLimit:null,gasPrice:null,data:null,value:null,chainId:null,confirmations:0,from:null,wait:confirmations=>this.provider.waitForTransaction(hash,confirmations)})))}}const json_rpc_provider_allowedTransactionKeys={chainId:!0,data:!0,gasLimit:!0,gasPrice:!0,nonce:!0,to:!0,value:!0,type:!0,accessList:!0,maxFeePerGas:!0,maxPriorityFeePerGas:!0};class JsonRpcProvider extends BaseProvider{constructor(url,network){let networkOrReady=network;null==networkOrReady&&(networkOrReady=new Promise(((resolve,reject)=>{setTimeout((()=>{this.detectNetwork().then((network=>{resolve(network)}),(error=>{reject(error)}))}),0)}))),super(networkOrReady),url||(url=getStatic(this.constructor,"defaultUrl")()),defineReadOnly(this,"connection","string"==typeof url?Object.freeze({url}):Object.freeze(shallowCopy(url))),this._nextId=42}get _cache(){return null==this._eventLoopCache&&(this._eventLoopCache={}),this._eventLoopCache}static defaultUrl(){return"http://localhost:8545"}detectNetwork(){return this._cache.detectNetwork||(this._cache.detectNetwork=this._uncachedDetectNetwork(),setTimeout((()=>{this._cache.detectNetwork=null}),0)),this._cache.detectNetwork}_uncachedDetectNetwork(){return json_rpc_provider_awaiter(this,void 0,void 0,(function*(){yield timer(0);let chainId=null;try{chainId=yield this.send("eth_chainId",[])}catch(error){try{chainId=yield this.send("net_version",[])}catch(error){}}if(null!=chainId){const getNetwork=getStatic(this.constructor,"getNetwork");try{return getNetwork(BigNumber.from(chainId).toNumber())}catch(error){return json_rpc_provider_logger.throwError("could not detect network",Logger.errors.NETWORK_ERROR,{chainId,event:"invalidNetwork",serverError:error})}}return json_rpc_provider_logger.throwError("could not detect network",Logger.errors.NETWORK_ERROR,{event:"noNetwork"})}))}getSigner(addressOrIndex){return new JsonRpcSigner(json_rpc_provider_constructorGuard,this,addressOrIndex)}getUncheckedSigner(addressOrIndex){return this.getSigner(addressOrIndex).connectUnchecked()}listAccounts(){return this.send("eth_accounts",[]).then((accounts=>accounts.map((a=>this.formatter.address(a)))))}send(method,params){const request={method,params,id:this._nextId++,jsonrpc:"2.0"};this.emit("debug",{action:"request",request:deepCopy(request),provider:this});const cache=["eth_chainId","eth_blockNumber"].indexOf(method)>=0;if(cache&&this._cache[method])return this._cache[method];const result=fetchJson(this.connection,JSON.stringify(request),getResult).then((result=>(this.emit("debug",{action:"response",request,response:result,provider:this}),result)),(error=>{throw this.emit("debug",{action:"response",error,request,provider:this}),error}));return cache&&(this._cache[method]=result,setTimeout((()=>{this._cache[method]=null}),0)),result}prepareRequest(method,params){switch(method){case"getBlockNumber":return["eth_blockNumber",[]];case"getGasPrice":return["eth_gasPrice",[]];case"getBalance":return["eth_getBalance",[getLowerCase(params.address),params.blockTag]];case"getTransactionCount":return["eth_getTransactionCount",[getLowerCase(params.address),params.blockTag]];case"getCode":return["eth_getCode",[getLowerCase(params.address),params.blockTag]];case"getStorageAt":return["eth_getStorageAt",[getLowerCase(params.address),hexZeroPad(params.position,32),params.blockTag]];case"sendTransaction":return["eth_sendRawTransaction",[params.signedTransaction]];case"getBlock":return params.blockTag?["eth_getBlockByNumber",[params.blockTag,!!params.includeTransactions]]:params.blockHash?["eth_getBlockByHash",[params.blockHash,!!params.includeTransactions]]:null;case"getTransaction":return["eth_getTransactionByHash",[params.transactionHash]];case"getTransactionReceipt":return["eth_getTransactionReceipt",[params.transactionHash]];case"call":return["eth_call",[getStatic(this.constructor,"hexlifyTransaction")(params.transaction,{from:!0}),params.blockTag]];case"estimateGas":return["eth_estimateGas",[getStatic(this.constructor,"hexlifyTransaction")(params.transaction,{from:!0})]];case"getLogs":return params.filter&&null!=params.filter.address&&(params.filter.address=getLowerCase(params.filter.address)),["eth_getLogs",[params.filter]]}return null}perform(method,params){return json_rpc_provider_awaiter(this,void 0,void 0,(function*(){if("call"===method||"estimateGas"===method){const tx=params.transaction;if(tx&&null!=tx.type&&BigNumber.from(tx.type).isZero()&&null==tx.maxFeePerGas&&null==tx.maxPriorityFeePerGas){const feeData=yield this.getFeeData();null==feeData.maxFeePerGas&&null==feeData.maxPriorityFeePerGas&&((params=shallowCopy(params)).transaction=shallowCopy(tx),delete params.transaction.type)}}const args=this.prepareRequest(method,params);null==args&&json_rpc_provider_logger.throwError(method+" not implemented",Logger.errors.NOT_IMPLEMENTED,{operation:method});try{return yield this.send(args[0],args[1])}catch(error){return checkError(method,error,params)}}))}_startEvent(event){"pending"===event.tag&&this._startPending(),super._startEvent(event)}_startPending(){if(null!=this._pendingFilter)return;const self=this,pendingFilter=this.send("eth_newPendingTransactionFilter",[]);this._pendingFilter=pendingFilter,pendingFilter.then((function(filterId){return function poll(){self.send("eth_getFilterChanges",[filterId]).then((function(hashes){if(self._pendingFilter!=pendingFilter)return null;let seq=Promise.resolve();return hashes.forEach((function(hash){self._emitted["t:"+hash.toLowerCase()]="pending",seq=seq.then((function(){return self.getTransaction(hash).then((function(tx){return self.emit("pending",tx),null}))}))})),seq.then((function(){return timer(1e3)}))})).then((function(){if(self._pendingFilter==pendingFilter)return setTimeout((function(){poll()}),0),null;self.send("eth_uninstallFilter",[filterId])})).catch((error=>{}))}(),filterId})).catch((error=>{}))}_stopEvent(event){"pending"===event.tag&&0===this.listenerCount("pending")&&(this._pendingFilter=null),super._stopEvent(event)}static hexlifyTransaction(transaction,allowExtra){const allowed=shallowCopy(json_rpc_provider_allowedTransactionKeys);if(allowExtra)for(const key in allowExtra)allowExtra[key]&&(allowed[key]=!0);checkProperties(transaction,allowed);const result={};return["chainId","gasLimit","gasPrice","type","maxFeePerGas","maxPriorityFeePerGas","nonce","value"].forEach((function(key){if(null==transaction[key])return;const value=hexValue(BigNumber.from(transaction[key]));"gasLimit"===key&&(key="gas"),result[key]=value})),["from","to","data"].forEach((function(key){null!=transaction[key]&&(result[key]=hexlify(transaction[key]))})),transaction.accessList&&(result.accessList=accessListify(transaction.accessList)),result}}let WS=null;try{if(WS=WebSocket,null==WS)throw new Error("inject please")}catch(error){const logger=new Logger("providers/5.7.2");WS=function(){logger.throwError("WebSockets not supported in this environment",Logger.errors.UNSUPPORTED_OPERATION,{operation:"new WebSocket()"})}}var websocket_provider_awaiter=function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};const websocket_provider_logger=new Logger("providers/5.7.2");let NextId=1;class WebSocketProvider extends JsonRpcProvider{constructor(url,network){"any"===network&&websocket_provider_logger.throwError("WebSocketProvider does not support 'any' network yet",Logger.errors.UNSUPPORTED_OPERATION,{operation:"network:any"}),super("string"==typeof url?url:"_websocket",network),this._pollingInterval=-1,this._wsReady=!1,defineReadOnly(this,"_websocket","string"==typeof url?new WS(this.connection.url):url),defineReadOnly(this,"_requests",{}),defineReadOnly(this,"_subs",{}),defineReadOnly(this,"_subIds",{}),defineReadOnly(this,"_detectNetwork",super.detectNetwork()),this.websocket.onopen=()=>{this._wsReady=!0,Object.keys(this._requests).forEach((id=>{this.websocket.send(this._requests[id].payload)}))},this.websocket.onmessage=messageEvent=>{const data=messageEvent.data,result=JSON.parse(data);if(null!=result.id){const id=String(result.id),request=this._requests[id];if(delete this._requests[id],void 0!==result.result)request.callback(null,result.result),this.emit("debug",{action:"response",request:JSON.parse(request.payload),response:result.result,provider:this});else{let error=null;result.error?(error=new Error(result.error.message||"unknown error"),defineReadOnly(error,"code",result.error.code||null),defineReadOnly(error,"response",data)):error=new Error("unknown error"),request.callback(error,void 0),this.emit("debug",{action:"response",error,request:JSON.parse(request.payload),provider:this})}}else if("eth_subscription"===result.method){const sub=this._subs[result.params.subscription];sub&&sub.processFunc(result.params.result)}else console.warn("this should not happen")};const fauxPoll=setInterval((()=>{this.emit("poll")}),1e3);fauxPoll.unref&&fauxPoll.unref()}get websocket(){return this._websocket}detectNetwork(){return this._detectNetwork}get pollingInterval(){return 0}resetEventsBlock(blockNumber){websocket_provider_logger.throwError("cannot reset events block on WebSocketProvider",Logger.errors.UNSUPPORTED_OPERATION,{operation:"resetEventBlock"})}set pollingInterval(value){websocket_provider_logger.throwError("cannot set polling interval on WebSocketProvider",Logger.errors.UNSUPPORTED_OPERATION,{operation:"setPollingInterval"})}poll(){return websocket_provider_awaiter(this,void 0,void 0,(function*(){return null}))}set polling(value){value&&websocket_provider_logger.throwError("cannot set polling on WebSocketProvider",Logger.errors.UNSUPPORTED_OPERATION,{operation:"setPolling"})}send(method,params){const rid=NextId++;return new Promise(((resolve,reject)=>{const payload=JSON.stringify({method,params,id:rid,jsonrpc:"2.0"});this.emit("debug",{action:"request",request:JSON.parse(payload),provider:this}),this._requests[String(rid)]={callback:function callback(error,result){return error?reject(error):resolve(result)},payload},this._wsReady&&this.websocket.send(payload)}))}static defaultUrl(){return"ws://localhost:8546"}_subscribe(tag,param,processFunc){return websocket_provider_awaiter(this,void 0,void 0,(function*(){let subIdPromise=this._subIds[tag];null==subIdPromise&&(subIdPromise=Promise.all(param).then((param=>this.send("eth_subscribe",param))),this._subIds[tag]=subIdPromise);const subId=yield subIdPromise;this._subs[subId]={tag,processFunc}}))}_startEvent(event){switch(event.type){case"block":this._subscribe("block",["newHeads"],(result=>{const blockNumber=BigNumber.from(result.number).toNumber();this._emitted.block=blockNumber,this.emit("block",blockNumber)}));break;case"pending":this._subscribe("pending",["newPendingTransactions"],(result=>{this.emit("pending",result)}));break;case"filter":this._subscribe(event.tag,["logs",this._getFilter(event.filter)],(result=>{null==result.removed&&(result.removed=!1),this.emit(event.filter,this.formatter.filterLog(result))}));break;case"tx":{const emitReceipt=event=>{const hash=event.hash;this.getTransactionReceipt(hash).then((receipt=>{receipt&&this.emit(hash,receipt)}))};emitReceipt(event),this._subscribe("tx",["newHeads"],(result=>{this._events.filter((e=>"tx"===e.type)).forEach(emitReceipt)}));break}case"debug":case"poll":case"willPoll":case"didPoll":case"error":break;default:console.log("unhandled:",event)}}_stopEvent(event){let tag=event.tag;if("tx"===event.type){if(this._events.filter((e=>"tx"===e.type)).length)return;tag="tx"}else if(this.listenerCount(event.event))return;const subId=this._subIds[tag];subId&&(delete this._subIds[tag],subId.then((subId=>{this._subs[subId]&&(delete this._subs[subId],this.send("eth_unsubscribe",[subId]))})))}destroy(){return websocket_provider_awaiter(this,void 0,void 0,(function*(){this.websocket.readyState===WS.CONNECTING&&(yield new Promise((resolve=>{this.websocket.onopen=function(){resolve(!0)},this.websocket.onerror=function(){resolve(!1)}}))),this.websocket.close(1e3)}))}}var url_json_rpc_provider_awaiter=function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};const url_json_rpc_provider_logger=new Logger("providers/5.7.2");class StaticJsonRpcProvider extends JsonRpcProvider{detectNetwork(){const _super=Object.create(null,{detectNetwork:{get:()=>super.detectNetwork}});return url_json_rpc_provider_awaiter(this,void 0,void 0,(function*(){let network=this.network;return null==network&&(network=yield _super.detectNetwork.call(this),network||url_json_rpc_provider_logger.throwError("no network detected",Logger.errors.UNKNOWN_ERROR,{}),null==this._network&&(defineReadOnly(this,"_network",network),this.emit("network",network,null))),network}))}}class UrlJsonRpcProvider extends StaticJsonRpcProvider{constructor(network,apiKey){url_json_rpc_provider_logger.checkAbstract(new.target,UrlJsonRpcProvider),network=getStatic(new.target,"getNetwork")(network),apiKey=getStatic(new.target,"getApiKey")(apiKey);super(getStatic(new.target,"getUrl")(network,apiKey),network),"string"==typeof apiKey?defineReadOnly(this,"apiKey",apiKey):null!=apiKey&&Object.keys(apiKey).forEach((key=>{defineReadOnly(this,key,apiKey[key])}))}_startPending(){url_json_rpc_provider_logger.warn("WARNING: API provider does not support pending filters")}isCommunityResource(){return!1}getSigner(address){return url_json_rpc_provider_logger.throwError("API provider does not support signing",Logger.errors.UNSUPPORTED_OPERATION,{operation:"getSigner"})}listAccounts(){return Promise.resolve([])}static getApiKey(apiKey){return apiKey}static getUrl(network,apiKey){return url_json_rpc_provider_logger.throwError("not implemented; sub-classes must override getUrl",Logger.errors.NOT_IMPLEMENTED,{operation:"getUrl"})}}const alchemy_provider_logger=new Logger("providers/5.7.2"),defaultApiKey="_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC";class AlchemyWebSocketProvider extends WebSocketProvider{constructor(network,apiKey){const provider=new AlchemyProvider(network,apiKey);super(provider.connection.url.replace(/^http/i,"ws").replace(".alchemyapi.",".ws.alchemyapi."),provider.network),defineReadOnly(this,"apiKey",provider.apiKey)}isCommunityResource(){return this.apiKey===defaultApiKey}}class AlchemyProvider extends UrlJsonRpcProvider{static getWebSocketProvider(network,apiKey){return new AlchemyWebSocketProvider(network,apiKey)}static getApiKey(apiKey){return null==apiKey?defaultApiKey:(apiKey&&"string"!=typeof apiKey&&alchemy_provider_logger.throwArgumentError("invalid apiKey","apiKey",apiKey),apiKey)}static getUrl(network,apiKey){let host=null;switch(network.name){case"homestead":host="eth-mainnet.alchemyapi.io/v2/";break;case"goerli":host="eth-goerli.g.alchemy.com/v2/";break;case"matic":host="polygon-mainnet.g.alchemy.com/v2/";break;case"maticmum":host="polygon-mumbai.g.alchemy.com/v2/";break;case"arbitrum":host="arb-mainnet.g.alchemy.com/v2/";break;case"arbitrum-goerli":host="arb-goerli.g.alchemy.com/v2/";break;case"optimism":host="opt-mainnet.g.alchemy.com/v2/";break;case"optimism-goerli":host="opt-goerli.g.alchemy.com/v2/";break;default:alchemy_provider_logger.throwArgumentError("unsupported network","network",arguments[0])}return{allowGzip:!0,url:"https://"+host+apiKey,throttleCallback:(attempt,url)=>(apiKey===defaultApiKey&&showThrottleMessage(),Promise.resolve(!0))}}isCommunityResource(){return this.apiKey===defaultApiKey}}const ankr_provider_logger=new Logger("providers/5.7.2"),ankr_provider_defaultApiKey="9f7d929b018cdffb338517efa06f58359e86ff1ffd350bc889738523659e7972";function getHost(name){switch(name){case"homestead":return"rpc.ankr.com/eth/";case"ropsten":return"rpc.ankr.com/eth_ropsten/";case"rinkeby":return"rpc.ankr.com/eth_rinkeby/";case"goerli":return"rpc.ankr.com/eth_goerli/";case"matic":return"rpc.ankr.com/polygon/";case"arbitrum":return"rpc.ankr.com/arbitrum/"}return ankr_provider_logger.throwArgumentError("unsupported network","name",name)}class AnkrProvider extends UrlJsonRpcProvider{isCommunityResource(){return this.apiKey===ankr_provider_defaultApiKey}static getApiKey(apiKey){return null==apiKey?ankr_provider_defaultApiKey:apiKey}static getUrl(network,apiKey){null==apiKey&&(apiKey=ankr_provider_defaultApiKey);const connection={allowGzip:!0,url:"https://"+getHost(network.name)+apiKey,throttleCallback:(attempt,url)=>(apiKey.apiKey===ankr_provider_defaultApiKey&&showThrottleMessage(),Promise.resolve(!0))};return null!=apiKey.projectSecret&&(connection.user="",connection.password=apiKey.projectSecret),connection}}var cloudflare_provider_awaiter=function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};const cloudflare_provider_logger=new Logger("providers/5.7.2");class CloudflareProvider extends UrlJsonRpcProvider{static getApiKey(apiKey){return null!=apiKey&&cloudflare_provider_logger.throwArgumentError("apiKey not supported for cloudflare","apiKey",apiKey),null}static getUrl(network,apiKey){let host=null;if("homestead"===network.name)host="https://cloudflare-eth.com/";else cloudflare_provider_logger.throwArgumentError("unsupported network","network",arguments[0]);return host}perform(method,params){const _super=Object.create(null,{perform:{get:()=>super.perform}});return cloudflare_provider_awaiter(this,void 0,void 0,(function*(){if("getBlockNumber"===method){return(yield _super.perform.call(this,"getBlock",{blockTag:"latest"})).number}return _super.perform.call(this,method,params)}))}}var etherscan_provider_awaiter=function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};const etherscan_provider_logger=new Logger("providers/5.7.2");function getTransactionPostData(transaction){const result={};for(let key in transaction){if(null==transaction[key])continue;let value=transaction[key];"type"===key&&0===value||(value={type:!0,gasLimit:!0,gasPrice:!0,maxFeePerGs:!0,maxPriorityFeePerGas:!0,nonce:!0,value:!0}[key]?hexValue(hexlify(value)):"accessList"===key?"["+accessListify(value).map((set=>`{address:"${set.address}",storageKeys:["${set.storageKeys.join('","')}"]}`)).join(",")+"]":hexlify(value),result[key]=value)}return result}function etherscan_provider_getResult(result){if(0==result.status&&("No records found"===result.message||"No transactions found"===result.message))return result.result;if(1!=result.status||"string"!=typeof result.message||!result.message.match(/^OK/)){const error=new Error("invalid response");throw error.result=JSON.stringify(result),(result.result||"").toLowerCase().indexOf("rate limit")>=0&&(error.throttleRetry=!0),error}return result.result}function getJsonResult(result){if(result&&0==result.status&&"NOTOK"==result.message&&(result.result||"").toLowerCase().indexOf("rate limit")>=0){const error=new Error("throttled response");throw error.result=JSON.stringify(result),error.throttleRetry=!0,error}if("2.0"!=result.jsonrpc){const error=new Error("invalid response");throw error.result=JSON.stringify(result),error}if(result.error){const error=new Error(result.error.message||"unknown error");throw result.error.code&&(error.code=result.error.code),result.error.data&&(error.data=result.error.data),error}return result.result}function checkLogTag(blockTag){if("pending"===blockTag)throw new Error("pending not supported");return"latest"===blockTag?blockTag:parseInt(blockTag.substring(2),16)}function etherscan_provider_checkError(method,error,transaction){if("call"===method&&error.code===Logger.errors.SERVER_ERROR){const e=error.error;if(e&&(e.message.match(/reverted/i)||e.message.match(/VM execution error/i))){let data=e.data;if(data&&(data="0x"+data.replace(/^.*0x/i,"")),lib_esm_isHexString(data))return data;etherscan_provider_logger.throwError("missing revert data in call exception",Logger.errors.CALL_EXCEPTION,{error,data:"0x"})}}let message=error.message;throw error.code===Logger.errors.SERVER_ERROR&&(error.error&&"string"==typeof error.error.message?message=error.error.message:"string"==typeof error.body?message=error.body:"string"==typeof error.responseText&&(message=error.responseText)),message=(message||"").toLowerCase(),message.match(/insufficient funds/)&ðerscan_provider_logger.throwError("insufficient funds for intrinsic transaction cost",Logger.errors.INSUFFICIENT_FUNDS,{error,method,transaction}),message.match(/same hash was already imported|transaction nonce is too low|nonce too low/)&ðerscan_provider_logger.throwError("nonce has already been used",Logger.errors.NONCE_EXPIRED,{error,method,transaction}),message.match(/another transaction with same nonce/)&ðerscan_provider_logger.throwError("replacement fee too low",Logger.errors.REPLACEMENT_UNDERPRICED,{error,method,transaction}),message.match(/execution failed due to an exception|execution reverted/)&ðerscan_provider_logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit",Logger.errors.UNPREDICTABLE_GAS_LIMIT,{error,method,transaction}),error}class EtherscanProvider extends BaseProvider{constructor(network,apiKey){super(network),defineReadOnly(this,"baseUrl",this.getBaseUrl()),defineReadOnly(this,"apiKey",apiKey||null)}getBaseUrl(){switch(this.network?this.network.name:"invalid"){case"homestead":return"https://api.etherscan.io";case"goerli":return"https://api-goerli.etherscan.io";case"sepolia":return"https://api-sepolia.etherscan.io";case"matic":return"https://api.polygonscan.com";case"maticmum":return"https://api-testnet.polygonscan.com";case"arbitrum":return"https://api.arbiscan.io";case"arbitrum-goerli":return"https://api-goerli.arbiscan.io";case"optimism":return"https://api-optimistic.etherscan.io";case"optimism-goerli":return"https://api-goerli-optimistic.etherscan.io"}return etherscan_provider_logger.throwArgumentError("unsupported network","network",this.network.name)}getUrl(module,params){const query=Object.keys(params).reduce(((accum,key)=>{const value=params[key];return null!=value&&(accum+=`&${key}=${value}`),accum}),""),apiKey=this.apiKey?`&apikey=${this.apiKey}`:"";return`${this.baseUrl}/api?module=${module}${query}${apiKey}`}getPostUrl(){return`${this.baseUrl}/api`}getPostData(module,params){return params.module=module,params.apikey=this.apiKey,params}fetch(module,params,post){return etherscan_provider_awaiter(this,void 0,void 0,(function*(){const url=post?this.getPostUrl():this.getUrl(module,params),payload=post?this.getPostData(module,params):null,procFunc="proxy"===module?getJsonResult:etherscan_provider_getResult;this.emit("debug",{action:"request",request:url,provider:this});const connection={url,throttleSlotInterval:1e3,throttleCallback:(attempt,url)=>(this.isCommunityResource()&&showThrottleMessage(),Promise.resolve(!0))};let payloadStr=null;payload&&(connection.headers={"content-type":"application/x-www-form-urlencoded; charset=UTF-8"},payloadStr=Object.keys(payload).map((key=>`${key}=${payload[key]}`)).join("&"));const result=yield fetchJson(connection,payloadStr,procFunc||getJsonResult);return this.emit("debug",{action:"response",request:url,response:deepCopy(result),provider:this}),result}))}detectNetwork(){return etherscan_provider_awaiter(this,void 0,void 0,(function*(){return this.network}))}perform(method,params){const _super=Object.create(null,{perform:{get:()=>super.perform}});return etherscan_provider_awaiter(this,void 0,void 0,(function*(){switch(method){case"getBlockNumber":return this.fetch("proxy",{action:"eth_blockNumber"});case"getGasPrice":return this.fetch("proxy",{action:"eth_gasPrice"});case"getBalance":return this.fetch("account",{action:"balance",address:params.address,tag:params.blockTag});case"getTransactionCount":return this.fetch("proxy",{action:"eth_getTransactionCount",address:params.address,tag:params.blockTag});case"getCode":return this.fetch("proxy",{action:"eth_getCode",address:params.address,tag:params.blockTag});case"getStorageAt":return this.fetch("proxy",{action:"eth_getStorageAt",address:params.address,position:params.position,tag:params.blockTag});case"sendTransaction":return this.fetch("proxy",{action:"eth_sendRawTransaction",hex:params.signedTransaction},!0).catch((error=>etherscan_provider_checkError("sendTransaction",error,params.signedTransaction)));case"getBlock":if(params.blockTag)return this.fetch("proxy",{action:"eth_getBlockByNumber",tag:params.blockTag,boolean:params.includeTransactions?"true":"false"});throw new Error("getBlock by blockHash not implemented");case"getTransaction":return this.fetch("proxy",{action:"eth_getTransactionByHash",txhash:params.transactionHash});case"getTransactionReceipt":return this.fetch("proxy",{action:"eth_getTransactionReceipt",txhash:params.transactionHash});case"call":{if("latest"!==params.blockTag)throw new Error("EtherscanProvider does not support blockTag for call");const postData=getTransactionPostData(params.transaction);postData.module="proxy",postData.action="eth_call";try{return yield this.fetch("proxy",postData,!0)}catch(error){return etherscan_provider_checkError("call",error,params.transaction)}}case"estimateGas":{const postData=getTransactionPostData(params.transaction);postData.module="proxy",postData.action="eth_estimateGas";try{return yield this.fetch("proxy",postData,!0)}catch(error){return etherscan_provider_checkError("estimateGas",error,params.transaction)}}case"getLogs":{const args={action:"getLogs"};if(params.filter.fromBlock&&(args.fromBlock=checkLogTag(params.filter.fromBlock)),params.filter.toBlock&&(args.toBlock=checkLogTag(params.filter.toBlock)),params.filter.address&&(args.address=params.filter.address),params.filter.topics&¶ms.filter.topics.length>0&&(params.filter.topics.length>1&ðerscan_provider_logger.throwError("unsupported topic count",Logger.errors.UNSUPPORTED_OPERATION,{topics:params.filter.topics}),1===params.filter.topics.length)){const topic0=params.filter.topics[0];"string"==typeof topic0&&66===topic0.length||etherscan_provider_logger.throwError("unsupported topic format",Logger.errors.UNSUPPORTED_OPERATION,{topic0}),args.topic0=topic0}const logs=yield this.fetch("logs",args);let blocks={};for(let i=0;i{["contractAddress","to"].forEach((function(key){""==tx[key]&&delete tx[key]})),null==tx.creates&&null!=tx.contractAddress&&(tx.creates=tx.contractAddress);const item=this.formatter.transactionResponse(tx);return tx.timeStamp&&(item.timestamp=parseInt(tx.timeStamp)),item}))}))}isCommunityResource(){return null==this.apiKey}}function shuffled(array){for(let i=(array=array.slice()).length-1;i>0;i--){const j=Math.floor(Math.random()*(i+1)),tmp=array[i];array[i]=array[j],array[j]=tmp}return array}var fallback_provider_awaiter=function(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P?value:new P((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))};const fallback_provider_logger=new Logger("providers/5.7.2");function now(){return(new Date).getTime()}function checkNetworks(networks){let result=null;for(let i=0;imaxDelta?null:(a+b)/2}function fallback_provider_serialize(value){if(null===value)return"null";if("number"==typeof value||"boolean"==typeof value)return JSON.stringify(value);if("string"==typeof value)return value;if(BigNumber.isBigNumber(value))return value.toString();if(Array.isArray(value))return JSON.stringify(value.map((i=>fallback_provider_serialize(i))));if("object"==typeof value){const keys=Object.keys(value);return keys.sort(),"{"+keys.map((key=>{let v=value[key];return v="function"==typeof v?"[function]":fallback_provider_serialize(v),JSON.stringify(key)+":"+v})).join(",")+"}"}throw new Error("unknown value type: "+typeof value)}let nextRid=1;function fallback_provider_stall(duration){let cancel=null,timer=null,promise=new Promise((resolve=>{cancel=function(){timer&&(clearTimeout(timer),timer=null),resolve()},timer=setTimeout(cancel,duration)}));return{cancel,getPromise:function getPromise(){return promise},wait:func=>(promise=promise.then(func),promise)}}const ForwardErrors=[Logger.errors.CALL_EXCEPTION,Logger.errors.INSUFFICIENT_FUNDS,Logger.errors.NONCE_EXPIRED,Logger.errors.REPLACEMENT_UNDERPRICED,Logger.errors.UNPREDICTABLE_GAS_LIMIT],ForwardProperties=["address","args","errorArgs","errorSignature","method","transaction"];function exposeDebugConfig(config,now){const result={weight:config.weight};return Object.defineProperty(result,"provider",{get:()=>config.provider}),config.start&&(result.start=config.start),now&&(result.duration=now-config.start),config.done&&(config.error?result.error=config.error:result.result=config.result||null),result}function getProcessFunc(provider,method,params){let normalize=fallback_provider_serialize;switch(method){case"getBlockNumber":return function(configs){const values=configs.map((c=>c.result));let blockNumber=median(configs.map((c=>c.result)),2);if(null!=blockNumber)return blockNumber=Math.ceil(blockNumber),values.indexOf(blockNumber+1)>=0&&blockNumber++,blockNumber>=provider._highestBlockNumber&&(provider._highestBlockNumber=blockNumber),provider._highestBlockNumber};case"getGasPrice":return function(configs){const values=configs.map((c=>c.result));return values.sort(),values[Math.floor(values.length/2)]};case"getEtherPrice":return function(configs){return median(configs.map((c=>c.result)))};case"getBalance":case"getTransactionCount":case"getCode":case"getStorageAt":case"call":case"estimateGas":case"getLogs":break;case"getTransaction":case"getTransactionReceipt":normalize=function(tx){return null==tx?null:((tx=shallowCopy(tx)).confirmations=-1,fallback_provider_serialize(tx))};break;case"getBlock":normalize=params.includeTransactions?function(block){return null==block?null:((block=shallowCopy(block)).transactions=block.transactions.map((tx=>((tx=shallowCopy(tx)).confirmations=-1,tx))),fallback_provider_serialize(block))}:function(block){return null==block?null:fallback_provider_serialize(block)};break;default:throw new Error("unknown method: "+method)}return function normalizedTally(normalize,quorum){return function(configs){const tally={};configs.forEach((c=>{const value=normalize(c.result);tally[value]||(tally[value]={count:0,result:c.result}),tally[value].count++}));const keys=Object.keys(tally);for(let i=0;i=quorum)return check.result}}}(normalize,provider.quorum)}function waitForSync(config,blockNumber){return fallback_provider_awaiter(this,void 0,void 0,(function*(){const provider=config.provider;return null!=provider.blockNumber&&provider.blockNumber>=blockNumber||-1===blockNumber?provider:poll((()=>new Promise(((resolve,reject)=>{setTimeout((function(){return provider.blockNumber>=blockNumber?resolve(provider):config.cancelled?resolve(null):resolve(void 0)}),0)}))),{oncePoll:provider})}))}function getRunner(config,currentBlockNumber,method,params){return fallback_provider_awaiter(this,void 0,void 0,(function*(){let provider=config.provider;switch(method){case"getBlockNumber":case"getGasPrice":return provider[method]();case"getEtherPrice":if(provider.getEtherPrice)return provider.getEtherPrice();break;case"getBalance":case"getTransactionCount":case"getCode":return params.blockTag&&lib_esm_isHexString(params.blockTag)&&(provider=yield waitForSync(config,currentBlockNumber)),provider[method](params.address,params.blockTag||"latest");case"getStorageAt":return params.blockTag&&lib_esm_isHexString(params.blockTag)&&(provider=yield waitForSync(config,currentBlockNumber)),provider.getStorageAt(params.address,params.position,params.blockTag||"latest");case"getBlock":return params.blockTag&&lib_esm_isHexString(params.blockTag)&&(provider=yield waitForSync(config,currentBlockNumber)),provider[params.includeTransactions?"getBlockWithTransactions":"getBlock"](params.blockTag||params.blockHash);case"call":case"estimateGas":return params.blockTag&&lib_esm_isHexString(params.blockTag)&&(provider=yield waitForSync(config,currentBlockNumber)),"call"===method&¶ms.blockTag?provider[method](params.transaction,params.blockTag):provider[method](params.transaction);case"getTransaction":case"getTransactionReceipt":return provider[method](params.transactionHash);case"getLogs":{let filter=params.filter;return(filter.fromBlock&&lib_esm_isHexString(filter.fromBlock)||filter.toBlock&&lib_esm_isHexString(filter.toBlock))&&(provider=yield waitForSync(config,currentBlockNumber)),provider.getLogs(filter)}}return fallback_provider_logger.throwError("unknown method error",Logger.errors.UNKNOWN_ERROR,{method,params})}))}class FallbackProvider extends BaseProvider{constructor(providers,quorum){0===providers.length&&fallback_provider_logger.throwArgumentError("missing providers","providers",providers);const providerConfigs=providers.map(((configOrProvider,index)=>{if(Provider.isProvider(configOrProvider)){const stallTimeout=isCommunityResource(configOrProvider)?2e3:750,priority=1;return Object.freeze({provider:configOrProvider,weight:1,stallTimeout,priority})}const config=shallowCopy(configOrProvider);null==config.priority&&(config.priority=1),null==config.stallTimeout&&(config.stallTimeout=isCommunityResource(configOrProvider)?2e3:750),null==config.weight&&(config.weight=1);const weight=config.weight;return(weight%1||weight>512||weight<1)&&fallback_provider_logger.throwArgumentError("invalid weight; must be integer in [1, 512]",`providers[${index}].weight`,weight),Object.freeze(config)})),total=providerConfigs.reduce(((accum,c)=>accum+c.weight),0);null==quorum?quorum=total/2:quorum>total&&fallback_provider_logger.throwArgumentError("quorum will always fail; larger than total weight","quorum",quorum);let networkOrReady=checkNetworks(providerConfigs.map((c=>c.provider.network)));null==networkOrReady&&(networkOrReady=new Promise(((resolve,reject)=>{setTimeout((()=>{this.detectNetwork().then(resolve,reject)}),0)}))),super(networkOrReady),defineReadOnly(this,"providerConfigs",Object.freeze(providerConfigs)),defineReadOnly(this,"quorum",quorum),this._highestBlockNumber=-1}detectNetwork(){return fallback_provider_awaiter(this,void 0,void 0,(function*(){return checkNetworks(yield Promise.all(this.providerConfigs.map((c=>c.provider.getNetwork()))))}))}perform(method,params){return fallback_provider_awaiter(this,void 0,void 0,(function*(){if("sendTransaction"===method){const results=yield Promise.all(this.providerConfigs.map((c=>c.provider.sendTransaction(params.signedTransaction).then((result=>result.hash),(error=>error)))));for(let i=0;ia.priority-b.priority));const currentBlockNumber=this._highestBlockNumber;let i=0,first=!0;for(;;){const t0=now();let inflightWeight=configs.filter((c=>c.runner&&t0-c.startaccum+c.weight),0);for(;inflightWeight{config.staller=null})),config.runner=getRunner(config,currentBlockNumber,method,params).then((result=>{config.done=!0,config.result=result,this.listenerCount("debug")&&this.emit("debug",{action:"request",rid,backend:exposeDebugConfig(config,now()),request:{method,params:deepCopy(params)},provider:this})}),(error=>{config.done=!0,config.error=error,this.listenerCount("debug")&&this.emit("debug",{action:"request",rid,backend:exposeDebugConfig(config,now()),request:{method,params:deepCopy(params)},provider:this})})),this.listenerCount("debug")&&this.emit("debug",{action:"request",rid,backend:exposeDebugConfig(config,null),request:{method,params:deepCopy(params)},provider:this}),inflightWeight+=config.weight}const waiting=[];configs.forEach((c=>{!c.done&&c.runner&&(waiting.push(c.runner),c.staller&&waiting.push(c.staller.getPromise()))})),waiting.length&&(yield Promise.race(waiting));const results=configs.filter((c=>c.done&&null==c.error));if(results.length>=this.quorum){const result=processFunc(results);if(void 0!==result)return configs.forEach((c=>{c.staller&&c.staller.cancel(),c.cancelled=!0})),result;first||(yield fallback_provider_stall(100).getPromise()),first=!1}const errors=configs.reduce(((accum,c)=>{if(!c.done||null==c.error)return accum;const code=c.error.code;return ForwardErrors.indexOf(code)>=0&&(accum[code]||(accum[code]={error:c.error,weight:0}),accum[code].weight+=c.weight),accum}),{});if(Object.keys(errors).forEach((errorCode=>{const tally=errors[errorCode];if(tally.weight{c.staller&&c.staller.cancel(),c.cancelled=!0}));const e=tally.error,props={};ForwardProperties.forEach((name=>{null!=e[name]&&(props[name]=e[name])})),fallback_provider_logger.throwError(e.reason||e.message,errorCode,props)})),0===configs.filter((c=>!c.done)).length)break}return configs.forEach((c=>{c.staller&&c.staller.cancel(),c.cancelled=!0})),fallback_provider_logger.throwError("failed to meet quorum",Logger.errors.SERVER_ERROR,{method,params,results:configs.map((c=>exposeDebugConfig(c))),provider:this})}))}}const IpcProvider=null,infura_provider_logger=new Logger("providers/5.7.2"),defaultProjectId="84842078b09946638c03157f83405213";class InfuraWebSocketProvider extends WebSocketProvider{constructor(network,apiKey){const provider=new InfuraProvider(network,apiKey),connection=provider.connection;connection.password&&infura_provider_logger.throwError("INFURA WebSocket project secrets unsupported",Logger.errors.UNSUPPORTED_OPERATION,{operation:"InfuraProvider.getWebSocketProvider()"});super(connection.url.replace(/^http/i,"ws").replace("/v3/","/ws/v3/"),network),defineReadOnly(this,"apiKey",provider.projectId),defineReadOnly(this,"projectId",provider.projectId),defineReadOnly(this,"projectSecret",provider.projectSecret)}isCommunityResource(){return this.projectId===defaultProjectId}}class InfuraProvider extends UrlJsonRpcProvider{static getWebSocketProvider(network,apiKey){return new InfuraWebSocketProvider(network,apiKey)}static getApiKey(apiKey){const apiKeyObj={apiKey:defaultProjectId,projectId:defaultProjectId,projectSecret:null};return null==apiKey||("string"==typeof apiKey?apiKeyObj.projectId=apiKey:null!=apiKey.projectSecret?(infura_provider_logger.assertArgument("string"==typeof apiKey.projectId,"projectSecret requires a projectId","projectId",apiKey.projectId),infura_provider_logger.assertArgument("string"==typeof apiKey.projectSecret,"invalid projectSecret","projectSecret","[REDACTED]"),apiKeyObj.projectId=apiKey.projectId,apiKeyObj.projectSecret=apiKey.projectSecret):apiKey.projectId&&(apiKeyObj.projectId=apiKey.projectId),apiKeyObj.apiKey=apiKeyObj.projectId),apiKeyObj}static getUrl(network,apiKey){let host=null;switch(network?network.name:"unknown"){case"homestead":host="mainnet.infura.io";break;case"goerli":host="goerli.infura.io";break;case"sepolia":host="sepolia.infura.io";break;case"matic":host="polygon-mainnet.infura.io";break;case"maticmum":host="polygon-mumbai.infura.io";break;case"optimism":host="optimism-mainnet.infura.io";break;case"optimism-goerli":host="optimism-goerli.infura.io";break;case"arbitrum":host="arbitrum-mainnet.infura.io";break;case"arbitrum-goerli":host="arbitrum-goerli.infura.io";break;default:infura_provider_logger.throwError("unsupported network",Logger.errors.INVALID_ARGUMENT,{argument:"network",value:network})}const connection={allowGzip:!0,url:"https://"+host+"/v3/"+apiKey.projectId,throttleCallback:(attempt,url)=>(apiKey.projectId===defaultProjectId&&showThrottleMessage(),Promise.resolve(!0))};return null!=apiKey.projectSecret&&(connection.user="",connection.password=apiKey.projectSecret),connection}isCommunityResource(){return this.projectId===defaultProjectId}}class JsonRpcBatchProvider extends JsonRpcProvider{send(method,params){const request={method,params,id:this._nextId++,jsonrpc:"2.0"};null==this._pendingBatch&&(this._pendingBatch=[]);const inflightRequest={request,resolve:null,reject:null},promise=new Promise(((resolve,reject)=>{inflightRequest.resolve=resolve,inflightRequest.reject=reject}));return this._pendingBatch.push(inflightRequest),this._pendingBatchAggregator||(this._pendingBatchAggregator=setTimeout((()=>{const batch=this._pendingBatch;this._pendingBatch=null,this._pendingBatchAggregator=null;const request=batch.map((inflight=>inflight.request));return this.emit("debug",{action:"requestBatch",request:deepCopy(request),provider:this}),fetchJson(this.connection,JSON.stringify(request)).then((result=>{this.emit("debug",{action:"response",request,response:result,provider:this}),batch.forEach(((inflightRequest,index)=>{const payload=result[index];if(payload.error){const error=new Error(payload.error.message);error.code=payload.error.code,error.data=payload.error.data,inflightRequest.reject(error)}else inflightRequest.resolve(payload.result)}))}),(error=>{this.emit("debug",{action:"response",error,request,provider:this}),batch.forEach((inflightRequest=>{inflightRequest.reject(error)}))}))}),10)),promise}}const nodesmith_provider_logger=new Logger("providers/5.7.2");class NodesmithProvider extends UrlJsonRpcProvider{static getApiKey(apiKey){return apiKey&&"string"!=typeof apiKey&&nodesmith_provider_logger.throwArgumentError("invalid apiKey","apiKey",apiKey),apiKey||"ETHERS_JS_SHARED"}static getUrl(network,apiKey){nodesmith_provider_logger.warn("NodeSmith will be discontinued on 2019-12-20; please migrate to another platform.");let host=null;switch(network.name){case"homestead":host="https://ethereum.api.nodesmith.io/v1/mainnet/jsonrpc";break;case"ropsten":host="https://ethereum.api.nodesmith.io/v1/ropsten/jsonrpc";break;case"rinkeby":host="https://ethereum.api.nodesmith.io/v1/rinkeby/jsonrpc";break;case"goerli":host="https://ethereum.api.nodesmith.io/v1/goerli/jsonrpc";break;case"kovan":host="https://ethereum.api.nodesmith.io/v1/kovan/jsonrpc";break;default:nodesmith_provider_logger.throwArgumentError("unsupported network","network",arguments[0])}return host+"?apiKey="+apiKey}}const pocket_provider_logger=new Logger("providers/5.7.2");class PocketProvider extends UrlJsonRpcProvider{static getApiKey(apiKey){const apiKeyObj={applicationId:null,loadBalancer:!0,applicationSecretKey:null};return null==apiKey?apiKeyObj.applicationId="62e1ad51b37b8e00394bda3b":"string"==typeof apiKey?apiKeyObj.applicationId=apiKey:null!=apiKey.applicationSecretKey?(apiKeyObj.applicationId=apiKey.applicationId,apiKeyObj.applicationSecretKey=apiKey.applicationSecretKey):apiKey.applicationId?apiKeyObj.applicationId=apiKey.applicationId:pocket_provider_logger.throwArgumentError("unsupported PocketProvider apiKey","apiKey",apiKey),apiKeyObj}static getUrl(network,apiKey){let host=null;switch(network?network.name:"unknown"){case"goerli":host="eth-goerli.gateway.pokt.network";break;case"homestead":host="eth-mainnet.gateway.pokt.network";break;case"kovan":host="poa-kovan.gateway.pokt.network";break;case"matic":host="poly-mainnet.gateway.pokt.network";break;case"maticmum":host="polygon-mumbai-rpc.gateway.pokt.network";break;case"rinkeby":host="eth-rinkeby.gateway.pokt.network";break;case"ropsten":host="eth-ropsten.gateway.pokt.network";break;default:pocket_provider_logger.throwError("unsupported network",Logger.errors.INVALID_ARGUMENT,{argument:"network",value:network})}const connection={headers:{},url:`https://${host}/v1/lb/${apiKey.applicationId}`};return null!=apiKey.applicationSecretKey&&(connection.user="",connection.password=apiKey.applicationSecretKey),connection}isCommunityResource(){return"62e1ad51b37b8e00394bda3b"===this.applicationId}}const web3_provider_logger=new Logger("providers/5.7.2");let _nextId=1;function buildWeb3LegacyFetcher(provider,sendFunc){const fetcher="Web3LegacyFetcher";return function(method,params){const request={method,params,id:_nextId++,jsonrpc:"2.0"};return new Promise(((resolve,reject)=>{this.emit("debug",{action:"request",fetcher,request:deepCopy(request),provider:this}),sendFunc(request,((error,response)=>{if(error)return this.emit("debug",{action:"response",fetcher,error,request,provider:this}),reject(error);if(this.emit("debug",{action:"response",fetcher,request,response,provider:this}),response.error){const error=new Error(response.error.message);return error.code=response.error.code,error.data=response.error.data,reject(error)}resolve(response.result)}))}))}}class Web3Provider extends JsonRpcProvider{constructor(provider,network){null==provider&&web3_provider_logger.throwArgumentError("missing provider","provider",provider);let path=null,jsonRpcFetchFunc=null,subprovider=null;"function"==typeof provider?(path="unknown:",jsonRpcFetchFunc=provider):(path=provider.host||provider.path||"",!path&&provider.isMetaMask&&(path="metamask"),subprovider=provider,provider.request?(""===path&&(path="eip-1193:"),jsonRpcFetchFunc=function buildEip1193Fetcher(provider){return function(method,params){null==params&&(params=[]);const request={method,params};return this.emit("debug",{action:"request",fetcher:"Eip1193Fetcher",request:deepCopy(request),provider:this}),provider.request(request).then((response=>(this.emit("debug",{action:"response",fetcher:"Eip1193Fetcher",request,response,provider:this}),response)),(error=>{throw this.emit("debug",{action:"response",fetcher:"Eip1193Fetcher",request,error,provider:this}),error}))}}(provider)):provider.sendAsync?jsonRpcFetchFunc=buildWeb3LegacyFetcher(0,provider.sendAsync.bind(provider)):provider.send?jsonRpcFetchFunc=buildWeb3LegacyFetcher(0,provider.send.bind(provider)):web3_provider_logger.throwArgumentError("unsupported provider","provider",provider),path||(path="unknown:")),super(path,network),defineReadOnly(this,"jsonRpcFetchFunc",jsonRpcFetchFunc),defineReadOnly(this,"provider",subprovider)}send(method,params){return this.jsonRpcFetchFunc(method,params)}}const providers_lib_esm_logger=new Logger("providers/5.7.2");function getDefaultProvider(network,options){if(null==network&&(network="homestead"),"string"==typeof network){const match=network.match(/^(ws|http)s?:/i);if(match)switch(match[1].toLowerCase()){case"http":case"https":return new JsonRpcProvider(network);case"ws":case"wss":return new WebSocketProvider(network);default:providers_lib_esm_logger.throwArgumentError("unsupported URL scheme","network",network)}}const n=getNetwork(network);return n&&n._defaultProvider||providers_lib_esm_logger.throwError("unsupported getDefaultProvider network",Logger.errors.NETWORK_ERROR,{operation:"getDefaultProvider",network}),n._defaultProvider({FallbackProvider,AlchemyProvider,AnkrProvider,CloudflareProvider,EtherscanProvider,InfuraProvider,JsonRpcProvider,NodesmithProvider,PocketProvider,Web3Provider,IpcProvider},options)}const regexBytes=new RegExp("^bytes([0-9]+)$"),regexNumber=new RegExp("^(u?int)([0-9]*)$"),regexArray=new RegExp("^(.*)\\[([0-9]*)\\]$"),solidity_lib_esm_logger=new Logger("solidity/5.7.0");function _pack(type,value,isArray){switch(type){case"address":return isArray?zeroPad(value,32):arrayify(value);case"string":return toUtf8Bytes(value);case"bytes":return arrayify(value);case"bool":return value=value?"0x01":"0x00",isArray?zeroPad(value,32):arrayify(value)}let match=type.match(regexNumber);if(match){let size=parseInt(match[2]||"256");return(match[2]&&String(size)!==match[2]||size%8!=0||0===size||size>256)&&solidity_lib_esm_logger.throwArgumentError("invalid number type","type",type),isArray&&(size=256),zeroPad(value=BigNumber.from(value).toTwos(size),size/8)}if(match=type.match(regexBytes),match){const size=parseInt(match[1]);return(String(size)!==match[1]||0===size||size>32)&&solidity_lib_esm_logger.throwArgumentError("invalid bytes type","type",type),arrayify(value).byteLength!==size&&solidity_lib_esm_logger.throwArgumentError(`invalid value for ${type}`,"value",value),isArray?arrayify((value+"0000000000000000000000000000000000000000000000000000000000000000").substring(0,66)):value}if(match=type.match(regexArray),match&&Array.isArray(value)){const baseType=match[1];parseInt(match[2]||String(value.length))!=value.length&&solidity_lib_esm_logger.throwArgumentError(`invalid array length for ${type}`,"value",value);const result=[];return value.forEach((function(value){result.push(_pack(baseType,value,!0))})),concat(result)}return solidity_lib_esm_logger.throwArgumentError("invalid type","type",type)}function lib_esm_pack(types,values){types.length!=values.length&&solidity_lib_esm_logger.throwArgumentError("wrong number of values; expected ${ types.length }","values",values);const tight=[];return types.forEach((function(type,index){tight.push(_pack(type,values[index]))})),hexlify(concat(tight))}function lib_esm_keccak256(types,values){return keccak256(lib_esm_pack(types,values))}function lib_esm_sha256(types,values){return sha256(lib_esm_pack(types,values))}function createTable(data,func){func||(func=function(value){return[parseInt(value,16)]});let lo=0,result={};return data.split(",").forEach((pair=>{let comps=pair.split(":");lo+=parseInt(comps[0],16),result[lo]=func(comps[1])})),result}function createRangeTable(data){let hi=0;return data.split(",").map((v=>{let comps=v.split("-");1===comps.length?comps[1]="0":""===comps[1]&&(comps[1]="1");let lo=hi+parseInt(comps[0],16);return hi=parseInt(comps[1],16),{l:lo,h:hi}}))}function matchMap(value,ranges){let lo=0;for(let i=0;i=lo&&value<=lo+range.h&&(value-lo)%(range.d||1)==0){if(range.e&&-1!==range.e.indexOf(value-lo))continue;return range}}return null}const Table_A_1_ranges=createRangeTable("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d"),Table_B_1_flags="ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map((v=>parseInt(v,16))),Table_B_2_ranges=[{h:25,s:32,l:65},{h:30,s:32,e:[23],l:127},{h:54,s:1,e:[48],l:64,d:2},{h:14,s:1,l:57,d:2},{h:44,s:1,l:17,d:2},{h:10,s:1,e:[2,6,8],l:61,d:2},{h:16,s:1,l:68,d:2},{h:84,s:1,e:[18,24,66],l:19,d:2},{h:26,s:32,e:[17],l:435},{h:22,s:1,l:71,d:2},{h:15,s:80,l:40},{h:31,s:32,l:16},{h:32,s:1,l:80,d:2},{h:52,s:1,l:42,d:2},{h:12,s:1,l:55,d:2},{h:40,s:1,e:[38],l:15,d:2},{h:14,s:1,l:48,d:2},{h:37,s:48,l:49},{h:148,s:1,l:6351,d:2},{h:88,s:1,l:160,d:2},{h:15,s:16,l:704},{h:25,s:26,l:854},{h:25,s:32,l:55915},{h:37,s:40,l:1247},{h:25,s:-119711,l:53248},{h:25,s:-119763,l:52},{h:25,s:-119815,l:52},{h:25,s:-119867,e:[1,4,5,7,8,11,12,17],l:52},{h:25,s:-119919,l:52},{h:24,s:-119971,e:[2,7,8,17],l:52},{h:24,s:-120023,e:[2,7,13,15,16,17],l:52},{h:25,s:-120075,l:52},{h:25,s:-120127,l:52},{h:25,s:-120179,l:52},{h:25,s:-120231,l:52},{h:25,s:-120283,l:52},{h:25,s:-120335,l:52},{h:24,s:-119543,e:[17],l:56},{h:24,s:-119601,e:[17],l:58},{h:24,s:-119659,e:[17],l:58},{h:24,s:-119717,e:[17],l:58},{h:24,s:-119775,e:[17],l:58}],Table_B_2_lut_abs=createTable("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3"),Table_B_2_lut_rel=createTable("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7"),Table_B_2_complex=createTable("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D",(function bytes2(data){if(data.length%4!=0)throw new Error("bad data");let result=[];for(let i=0;i(value.forEach((value=>{accum.push(value)})),accum)),[])}(codes.map((code=>{if(Table_B_1_flags.indexOf(code)>=0)return[];if(code>=65024&&code<=65039)return[];let codesTableB2=function _nameprepTableB2(codepoint){let range=matchMap(codepoint,Table_B_2_ranges);if(range)return[codepoint+range.s];let codes=Table_B_2_lut_abs[codepoint];if(codes)return codes;let shift=Table_B_2_lut_rel[codepoint];return shift?[codepoint+shift[0]]:Table_B_2_complex[codepoint]||null}(code);return codesTableB2||[code]}))),codes=toUtf8CodePoints(_toUtf8String(codes),UnicodeNormalizationForm.NFKC),codes.forEach((code=>{if(function _nameprepTableC(codepoint){return!!matchMap(codepoint,Table_C_ranges)}(code))throw new Error("STRINGPREP_CONTAINS_PROHIBITED")})),codes.forEach((code=>{if(function _nameprepTableA1(codepoint){return!!matchMap(codepoint,Table_A_1_ranges)}(code))throw new Error("STRINGPREP_CONTAINS_UNASSIGNED")}));let name=_toUtf8String(codes);if("-"===name.substring(0,1)||"--"===name.substring(2,4)||"-"===name.substring(name.length-1))throw new Error("invalid hyphen");return name}function formatBytes32String(text){const bytes=toUtf8Bytes(text);if(bytes.length>31)throw new Error("bytes32 string must be less than 32 bytes");return hexlify(concat([bytes,HashZero]).slice(0,32))}function parseBytes32String(bytes){const data=arrayify(bytes);if(32!==data.length)throw new Error("invalid bytes32 - not 32 bytes long");if(0!==data[31])throw new Error("invalid bytes32 string - no null terminator");let length=31;for(;0===data[length-1];)length--;return utf8_toUtf8String(data.slice(0,length))}const units_lib_esm_logger=new Logger("units/5.7.0"),names=["wei","kwei","mwei","gwei","szabo","finney","ether"];function commify(value){const comps=String(value).split(".");(comps.length>2||!comps[0].match(/^-?[0-9]*$/)||comps[1]&&!comps[1].match(/^[0-9]*$/)||"."===value||"-."===value)&&units_lib_esm_logger.throwArgumentError("invalid value","value",value);let whole=comps[0],negative="";for("-"===whole.substring(0,1)&&(negative="-",whole=whole.substring(1));"0"===whole.substring(0,1);)whole=whole.substring(1);""===whole&&(whole="0");let suffix="";for(2===comps.length&&(suffix="."+(comps[1]||"0"));suffix.length>2&&"0"===suffix[suffix.length-1];)suffix=suffix.substring(0,suffix.length-1);const formatted=[];for(;whole.length;){if(whole.length<=3){formatted.unshift(whole);break}{const index=whole.length-3;formatted.unshift(whole.substring(index)),whole=whole.substring(0,index)}}return negative+formatted.join(",")+suffix}function formatUnits(value,unitName){if("string"==typeof unitName){const index=names.indexOf(unitName);-1!==index&&(unitName=3*index)}return formatFixed(value,null!=unitName?unitName:18)}function parseUnits(value,unitName){if("string"!=typeof value&&units_lib_esm_logger.throwArgumentError("value must be a string","value",value),"string"==typeof unitName){const index=names.indexOf(unitName);-1!==index&&(unitName=3*index)}return parseFixed(value,null!=unitName?unitName:18)}function formatEther(wei){return formatUnits(wei,18)}function parseEther(ether){return parseUnits(ether,18)}const ethers_lib_esm_version_version="ethers/5.7.2",ethers_logger=new Logger(ethers_lib_esm_version_version);try{const anyGlobal=window;null==anyGlobal._ethers&&(anyGlobal._ethers=ethers_namespaceObject)}catch(error){}},7187:module=>{"use strict";var ReflectOwnKeys,R="object"==typeof Reflect?Reflect:null,ReflectApply=R&&"function"==typeof R.apply?R.apply:function ReflectApply(target,receiver,args){return Function.prototype.apply.call(target,receiver,args)};ReflectOwnKeys=R&&"function"==typeof R.ownKeys?R.ownKeys:Object.getOwnPropertySymbols?function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))}:function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target)};var NumberIsNaN=Number.isNaN||function NumberIsNaN(value){return value!=value};function EventEmitter(){EventEmitter.init.call(this)}module.exports=EventEmitter,module.exports.once=function once(emitter,name){return new Promise((function(resolve,reject){function errorListener(err){emitter.removeListener(name,resolver),reject(err)}function resolver(){"function"==typeof emitter.removeListener&&emitter.removeListener("error",errorListener),resolve([].slice.call(arguments))}eventTargetAgnosticAddListener(emitter,name,resolver,{once:!0}),"error"!==name&&function addErrorHandlerIfEventEmitter(emitter,handler,flags){"function"==typeof emitter.on&&eventTargetAgnosticAddListener(emitter,"error",handler,flags)}(emitter,errorListener,{once:!0})}))},EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._eventsCount=0,EventEmitter.prototype._maxListeners=void 0;var defaultMaxListeners=10;function checkListener(listener){if("function"!=typeof listener)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof listener)}function _getMaxListeners(that){return void 0===that._maxListeners?EventEmitter.defaultMaxListeners:that._maxListeners}function _addListener(target,type,listener,prepend){var m,events,existing;if(checkListener(listener),void 0===(events=target._events)?(events=target._events=Object.create(null),target._eventsCount=0):(void 0!==events.newListener&&(target.emit("newListener",type,listener.listener?listener.listener:listener),events=target._events),existing=events[type]),void 0===existing)existing=events[type]=listener,++target._eventsCount;else if("function"==typeof existing?existing=events[type]=prepend?[listener,existing]:[existing,listener]:prepend?existing.unshift(listener):existing.push(listener),(m=_getMaxListeners(target))>0&&existing.length>m&&!existing.warned){existing.warned=!0;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+String(type)+" listeners added. Use emitter.setMaxListeners() to increase limit");w.name="MaxListenersExceededWarning",w.emitter=target,w.type=type,w.count=existing.length,function ProcessEmitWarning(warning){console&&console.warn&&console.warn(warning)}(w)}return target}function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap(target,type,listener){var state={fired:!1,wrapFn:void 0,target,type,listener},wrapped=onceWrapper.bind(state);return wrapped.listener=listener,state.wrapFn=wrapped,wrapped}function _listeners(target,type,unwrap){var events=target._events;if(void 0===events)return[];var evlistener=events[type];return void 0===evlistener?[]:"function"==typeof evlistener?unwrap?[evlistener.listener||evlistener]:[evlistener]:unwrap?function unwrapListeners(arr){for(var ret=new Array(arr.length),i=0;i0&&(er=args[0]),er instanceof Error)throw er;var err=new Error("Unhandled error."+(er?" ("+er.message+")":""));throw err.context=er,err}var handler=events[type];if(void 0===handler)return!1;if("function"==typeof handler)ReflectApply(handler,this,args);else{var len=handler.length,listeners=arrayClone(handler,len);for(i=0;i=0;i--)if(list[i]===listener||list[i].listener===listener){originalListener=list[i].listener,position=i;break}if(position<0)return this;0===position?list.shift():function spliceOne(list,index){for(;index+1=0;i--)this.removeListener(type,listeners[i]);return this},EventEmitter.prototype.listeners=function listeners(type){return _listeners(this,type,!0)},EventEmitter.prototype.rawListeners=function rawListeners(type){return _listeners(this,type,!1)},EventEmitter.listenerCount=function(emitter,type){return"function"==typeof emitter.listenerCount?emitter.listenerCount(type):listenerCount.call(emitter,type)},EventEmitter.prototype.listenerCount=listenerCount,EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]}},3048:(module,__unused_webpack_exports,__webpack_require__)=>{var Buffer=__webpack_require__(9509).Buffer,MD5=__webpack_require__(2318);module.exports=function EVP_BytesToKey(password,salt,keyBits,ivLen){if(Buffer.isBuffer(password)||(password=Buffer.from(password,"binary")),salt&&(Buffer.isBuffer(salt)||(salt=Buffer.from(salt,"binary")),8!==salt.length))throw new RangeError("salt should be Buffer with 8 byte length");for(var keyLen=keyBits/8,key=Buffer.alloc(keyLen),iv=Buffer.alloc(ivLen||0),tmp=Buffer.alloc(0);keyLen>0||ivLen>0;){var hash=new MD5;hash.update(tmp),hash.update(password),salt&&hash.update(salt),tmp=hash.digest();var used=0;if(keyLen>0){var keyStart=key.length-keyLen;used=Math.min(keyLen,tmp.length),tmp.copy(key,keyStart,0,used),keyLen-=used}if(used0){var ivStart=iv.length-ivLen,length=Math.min(ivLen,tmp.length-used);tmp.copy(iv,ivStart,used,used+length),ivLen-=length}}return tmp.fill(0),{key,iv}}},9804:module=>{var hasOwn=Object.prototype.hasOwnProperty,toString=Object.prototype.toString;module.exports=function forEach(obj,fn,ctx){if("[object Function]"!==toString.call(fn))throw new TypeError("iterator must be a function");var l=obj.length;if(l===+l)for(var i=0;i{"use strict";var ERROR_MESSAGE="Function.prototype.bind called on incompatible ",slice=Array.prototype.slice,toStr=Object.prototype.toString;module.exports=function bind(that){var target=this;if("function"!=typeof target||"[object Function]"!==toStr.call(target))throw new TypeError(ERROR_MESSAGE+target);for(var bound,args=slice.call(arguments,1),binder=function(){if(this instanceof bound){var result=target.apply(this,args.concat(slice.call(arguments)));return Object(result)===result?result:this}return target.apply(that,args.concat(slice.call(arguments)))},boundLength=Math.max(0,target.length-args.length),boundArgs=[],i=0;i{"use strict";var implementation=__webpack_require__(7648);module.exports=Function.prototype.bind||implementation},210:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var $SyntaxError=SyntaxError,$Function=Function,$TypeError=TypeError,getEvalledConstructor=function(expressionSyntax){try{return $Function('"use strict"; return ('+expressionSyntax+").constructor;")()}catch(e){}},$gOPD=Object.getOwnPropertyDescriptor;if($gOPD)try{$gOPD({},"")}catch(e){$gOPD=null}var throwTypeError=function(){throw new $TypeError},ThrowTypeError=$gOPD?function(){try{return throwTypeError}catch(calleeThrows){try{return $gOPD(arguments,"callee").get}catch(gOPDthrows){return throwTypeError}}}():throwTypeError,hasSymbols=__webpack_require__(1405)(),getProto=Object.getPrototypeOf||function(x){return x.__proto__},needsEval={},TypedArray="undefined"==typeof Uint8Array?undefined:getProto(Uint8Array),INTRINSICS={"%AggregateError%":"undefined"==typeof AggregateError?undefined:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?undefined:ArrayBuffer,"%ArrayIteratorPrototype%":hasSymbols?getProto([][Symbol.iterator]()):undefined,"%AsyncFromSyncIteratorPrototype%":undefined,"%AsyncFunction%":needsEval,"%AsyncGenerator%":needsEval,"%AsyncGeneratorFunction%":needsEval,"%AsyncIteratorPrototype%":needsEval,"%Atomics%":"undefined"==typeof Atomics?undefined:Atomics,"%BigInt%":"undefined"==typeof BigInt?undefined:BigInt,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?undefined:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?undefined:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?undefined:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?undefined:FinalizationRegistry,"%Function%":$Function,"%GeneratorFunction%":needsEval,"%Int8Array%":"undefined"==typeof Int8Array?undefined:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?undefined:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?undefined:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":hasSymbols?getProto(getProto([][Symbol.iterator]())):undefined,"%JSON%":"object"==typeof JSON?JSON:undefined,"%Map%":"undefined"==typeof Map?undefined:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&hasSymbols?getProto((new Map)[Symbol.iterator]()):undefined,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?undefined:Promise,"%Proxy%":"undefined"==typeof Proxy?undefined:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?undefined:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?undefined:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&hasSymbols?getProto((new Set)[Symbol.iterator]()):undefined,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?undefined:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":hasSymbols?getProto(""[Symbol.iterator]()):undefined,"%Symbol%":hasSymbols?Symbol:undefined,"%SyntaxError%":$SyntaxError,"%ThrowTypeError%":ThrowTypeError,"%TypedArray%":TypedArray,"%TypeError%":$TypeError,"%Uint8Array%":"undefined"==typeof Uint8Array?undefined:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?undefined:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?undefined:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?undefined:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?undefined:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?undefined:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?undefined:WeakSet},doEval=function doEval(name){var value;if("%AsyncFunction%"===name)value=getEvalledConstructor("async function () {}");else if("%GeneratorFunction%"===name)value=getEvalledConstructor("function* () {}");else if("%AsyncGeneratorFunction%"===name)value=getEvalledConstructor("async function* () {}");else if("%AsyncGenerator%"===name){var fn=doEval("%AsyncGeneratorFunction%");fn&&(value=fn.prototype)}else if("%AsyncIteratorPrototype%"===name){var gen=doEval("%AsyncGenerator%");gen&&(value=getProto(gen.prototype))}return INTRINSICS[name]=value,value},LEGACY_ALIASES={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},bind=__webpack_require__(8612),hasOwn=__webpack_require__(7642),$concat=bind.call(Function.call,Array.prototype.concat),$spliceApply=bind.call(Function.apply,Array.prototype.splice),$replace=bind.call(Function.call,String.prototype.replace),$strSlice=bind.call(Function.call,String.prototype.slice),rePropName=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,reEscapeChar=/\\(\\)?/g,stringToPath=function stringToPath(string){var first=$strSlice(string,0,1),last=$strSlice(string,-1);if("%"===first&&"%"!==last)throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");if("%"===last&&"%"!==first)throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");var result=[];return $replace(string,rePropName,(function(match,number,quote,subString){result[result.length]=quote?$replace(subString,reEscapeChar,"$1"):number||match})),result},getBaseIntrinsic=function getBaseIntrinsic(name,allowMissing){var alias,intrinsicName=name;if(hasOwn(LEGACY_ALIASES,intrinsicName)&&(intrinsicName="%"+(alias=LEGACY_ALIASES[intrinsicName])[0]+"%"),hasOwn(INTRINSICS,intrinsicName)){var value=INTRINSICS[intrinsicName];if(value===needsEval&&(value=doEval(intrinsicName)),void 0===value&&!allowMissing)throw new $TypeError("intrinsic "+name+" exists, but is not available. Please file an issue!");return{alias,name:intrinsicName,value}}throw new $SyntaxError("intrinsic "+name+" does not exist!")};module.exports=function GetIntrinsic(name,allowMissing){if("string"!=typeof name||0===name.length)throw new $TypeError("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof allowMissing)throw new $TypeError('"allowMissing" argument must be a boolean');var parts=stringToPath(name),intrinsicBaseName=parts.length>0?parts[0]:"",intrinsic=getBaseIntrinsic("%"+intrinsicBaseName+"%",allowMissing),intrinsicRealName=intrinsic.name,value=intrinsic.value,skipFurtherCaching=!1,alias=intrinsic.alias;alias&&(intrinsicBaseName=alias[0],$spliceApply(parts,$concat([0,1],alias)));for(var i=1,isOwn=!0;i=parts.length){var desc=$gOPD(value,part);value=(isOwn=!!desc)&&"get"in desc&&!("originalValue"in desc.get)?desc.get:value[part]}else isOwn=hasOwn(value,part),value=value[part];isOwn&&!skipFurtherCaching&&(INTRINSICS[intrinsicRealName]=value)}}return value}},1044:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var $defineProperty=__webpack_require__(210)("%Object.defineProperty%",!0),hasPropertyDescriptors=function hasPropertyDescriptors(){if($defineProperty)try{return $defineProperty({},"a",{value:1}),!0}catch(e){return!1}return!1};hasPropertyDescriptors.hasArrayLengthDefineBug=function hasArrayLengthDefineBug(){if(!hasPropertyDescriptors())return null;try{return 1!==$defineProperty([],"length",{value:1}).length}catch(e){return!0}},module.exports=hasPropertyDescriptors},1405:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var origSymbol="undefined"!=typeof Symbol&&Symbol,hasSymbolSham=__webpack_require__(5419);module.exports=function hasNativeSymbols(){return"function"==typeof origSymbol&&("function"==typeof Symbol&&("symbol"==typeof origSymbol("foo")&&("symbol"==typeof Symbol("bar")&&hasSymbolSham())))}},5419:module=>{"use strict";module.exports=function hasSymbols(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var obj={},sym=Symbol("test"),symObj=Object(sym);if("string"==typeof sym)return!1;if("[object Symbol]"!==Object.prototype.toString.call(sym))return!1;if("[object Symbol]"!==Object.prototype.toString.call(symObj))return!1;for(sym in obj[sym]=42,obj)return!1;if("function"==typeof Object.keys&&0!==Object.keys(obj).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(obj).length)return!1;var syms=Object.getOwnPropertySymbols(obj);if(1!==syms.length||syms[0]!==sym)return!1;if(!Object.prototype.propertyIsEnumerable.call(obj,sym))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var descriptor=Object.getOwnPropertyDescriptor(obj,sym);if(42!==descriptor.value||!0!==descriptor.enumerable)return!1}return!0}},6410:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var hasSymbols=__webpack_require__(5419);module.exports=function hasToStringTagShams(){return hasSymbols()&&!!Symbol.toStringTag}},7642:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var bind=__webpack_require__(8612);module.exports=bind.call(Function.call,Object.prototype.hasOwnProperty)},3349:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var Buffer=__webpack_require__(9509).Buffer,Transform=__webpack_require__(8473).Transform;function HashBase(blockSize){Transform.call(this),this._block=Buffer.allocUnsafe(blockSize),this._blockSize=blockSize,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}__webpack_require__(5717)(HashBase,Transform),HashBase.prototype._transform=function(chunk,encoding,callback){var error=null;try{this.update(chunk,encoding)}catch(err){error=err}callback(error)},HashBase.prototype._flush=function(callback){var error=null;try{this.push(this.digest())}catch(err){error=err}callback(error)},HashBase.prototype.update=function(data,encoding){if(function throwIfNotStringOrBuffer(val,prefix){if(!Buffer.isBuffer(val)&&"string"!=typeof val)throw new TypeError(prefix+" must be a string or a buffer")}(data,"Data"),this._finalized)throw new Error("Digest already called");Buffer.isBuffer(data)||(data=Buffer.from(data,encoding));for(var block=this._block,offset=0;this._blockOffset+data.length-offset>=this._blockSize;){for(var i=this._blockOffset;i0;++j)this._length[j]+=carry,(carry=this._length[j]/4294967296|0)>0&&(this._length[j]-=4294967296*carry);return this},HashBase.prototype._update=function(){throw new Error("_update is not implemented")},HashBase.prototype.digest=function(encoding){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var digest=this._digest();void 0!==encoding&&(digest=digest.toString(encoding)),this._block.fill(0),this._blockOffset=0;for(var i=0;i<4;++i)this._length[i]=0;return digest},HashBase.prototype._digest=function(){throw new Error("_digest is not implemented")},module.exports=HashBase},3715:(__unused_webpack_module,exports,__webpack_require__)=>{var hash=exports;hash.utils=__webpack_require__(6436),hash.common=__webpack_require__(5772),hash.sha=__webpack_require__(9041),hash.ripemd=__webpack_require__(2949),hash.hmac=__webpack_require__(2344),hash.sha1=hash.sha.sha1,hash.sha256=hash.sha.sha256,hash.sha224=hash.sha.sha224,hash.sha384=hash.sha.sha384,hash.sha512=hash.sha.sha512,hash.ripemd160=hash.ripemd.ripemd160},5772:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(6436),assert=__webpack_require__(9746);function BlockHash(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}exports.BlockHash=BlockHash,BlockHash.prototype.update=function update(msg,enc){if(msg=utils.toArray(msg,enc),this.pending?this.pending=this.pending.concat(msg):this.pending=msg,this.pendingTotal+=msg.length,this.pending.length>=this._delta8){var r=(msg=this.pending).length%this._delta8;this.pending=msg.slice(msg.length-r,msg.length),0===this.pending.length&&(this.pending=null),msg=utils.join32(msg,0,msg.length-r,this.endian);for(var i=0;i>>24&255,res[i++]=len>>>16&255,res[i++]=len>>>8&255,res[i++]=255&len}else for(res[i++]=255&len,res[i++]=len>>>8&255,res[i++]=len>>>16&255,res[i++]=len>>>24&255,res[i++]=0,res[i++]=0,res[i++]=0,res[i++]=0,t=8;t{"use strict";var utils=__webpack_require__(6436),assert=__webpack_require__(9746);function Hmac(hash,key,enc){if(!(this instanceof Hmac))return new Hmac(hash,key,enc);this.Hash=hash,this.blockSize=hash.blockSize/8,this.outSize=hash.outSize/8,this.inner=null,this.outer=null,this._init(utils.toArray(key,enc))}module.exports=Hmac,Hmac.prototype._init=function init(key){key.length>this.blockSize&&(key=(new this.Hash).update(key).digest()),assert(key.length<=this.blockSize);for(var i=key.length;i{"use strict";var utils=__webpack_require__(6436),common=__webpack_require__(5772),rotl32=utils.rotl32,sum32=utils.sum32,sum32_3=utils.sum32_3,sum32_4=utils.sum32_4,BlockHash=common.BlockHash;function RIPEMD160(){if(!(this instanceof RIPEMD160))return new RIPEMD160;BlockHash.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}function f(j,x,y,z){return j<=15?x^y^z:j<=31?x&y|~x&z:j<=47?(x|~y)^z:j<=63?x&z|y&~z:x^(y|~z)}function K(j){return j<=15?0:j<=31?1518500249:j<=47?1859775393:j<=63?2400959708:2840853838}function Kh(j){return j<=15?1352829926:j<=31?1548603684:j<=47?1836072691:j<=63?2053994217:0}utils.inherits(RIPEMD160,BlockHash),exports.ripemd160=RIPEMD160,RIPEMD160.blockSize=512,RIPEMD160.outSize=160,RIPEMD160.hmacStrength=192,RIPEMD160.padLength=64,RIPEMD160.prototype._update=function update(msg,start){for(var A=this.h[0],B=this.h[1],C=this.h[2],D=this.h[3],E=this.h[4],Ah=A,Bh=B,Ch=C,Dh=D,Eh=E,j=0;j<80;j++){var T=sum32(rotl32(sum32_4(A,f(j,B,C,D),msg[r[j]+start],K(j)),s[j]),E);A=E,E=D,D=rotl32(C,10),C=B,B=T,T=sum32(rotl32(sum32_4(Ah,f(79-j,Bh,Ch,Dh),msg[rh[j]+start],Kh(j)),sh[j]),Eh),Ah=Eh,Eh=Dh,Dh=rotl32(Ch,10),Ch=Bh,Bh=T}T=sum32_3(this.h[1],C,Dh),this.h[1]=sum32_3(this.h[2],D,Eh),this.h[2]=sum32_3(this.h[3],E,Ah),this.h[3]=sum32_3(this.h[4],A,Bh),this.h[4]=sum32_3(this.h[0],B,Ch),this.h[0]=T},RIPEMD160.prototype._digest=function digest(enc){return"hex"===enc?utils.toHex32(this.h,"little"):utils.split32(this.h,"little")};var r=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],rh=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],s=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],sh=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]},9041:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";exports.sha1=__webpack_require__(4761),exports.sha224=__webpack_require__(799),exports.sha256=__webpack_require__(9344),exports.sha384=__webpack_require__(772),exports.sha512=__webpack_require__(5900)},4761:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(6436),common=__webpack_require__(5772),shaCommon=__webpack_require__(7038),rotl32=utils.rotl32,sum32=utils.sum32,sum32_5=utils.sum32_5,ft_1=shaCommon.ft_1,BlockHash=common.BlockHash,sha1_K=[1518500249,1859775393,2400959708,3395469782];function SHA1(){if(!(this instanceof SHA1))return new SHA1;BlockHash.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}utils.inherits(SHA1,BlockHash),module.exports=SHA1,SHA1.blockSize=512,SHA1.outSize=160,SHA1.hmacStrength=80,SHA1.padLength=64,SHA1.prototype._update=function _update(msg,start){for(var W=this.W,i=0;i<16;i++)W[i]=msg[start+i];for(;i{"use strict";var utils=__webpack_require__(6436),SHA256=__webpack_require__(9344);function SHA224(){if(!(this instanceof SHA224))return new SHA224;SHA256.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}utils.inherits(SHA224,SHA256),module.exports=SHA224,SHA224.blockSize=512,SHA224.outSize=224,SHA224.hmacStrength=192,SHA224.padLength=64,SHA224.prototype._digest=function digest(enc){return"hex"===enc?utils.toHex32(this.h.slice(0,7),"big"):utils.split32(this.h.slice(0,7),"big")}},9344:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(6436),common=__webpack_require__(5772),shaCommon=__webpack_require__(7038),assert=__webpack_require__(9746),sum32=utils.sum32,sum32_4=utils.sum32_4,sum32_5=utils.sum32_5,ch32=shaCommon.ch32,maj32=shaCommon.maj32,s0_256=shaCommon.s0_256,s1_256=shaCommon.s1_256,g0_256=shaCommon.g0_256,g1_256=shaCommon.g1_256,BlockHash=common.BlockHash,sha256_K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function SHA256(){if(!(this instanceof SHA256))return new SHA256;BlockHash.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=sha256_K,this.W=new Array(64)}utils.inherits(SHA256,BlockHash),module.exports=SHA256,SHA256.blockSize=512,SHA256.outSize=256,SHA256.hmacStrength=192,SHA256.padLength=64,SHA256.prototype._update=function _update(msg,start){for(var W=this.W,i=0;i<16;i++)W[i]=msg[start+i];for(;i{"use strict";var utils=__webpack_require__(6436),SHA512=__webpack_require__(5900);function SHA384(){if(!(this instanceof SHA384))return new SHA384;SHA512.call(this),this.h=[3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]}utils.inherits(SHA384,SHA512),module.exports=SHA384,SHA384.blockSize=1024,SHA384.outSize=384,SHA384.hmacStrength=192,SHA384.padLength=128,SHA384.prototype._digest=function digest(enc){return"hex"===enc?utils.toHex32(this.h.slice(0,12),"big"):utils.split32(this.h.slice(0,12),"big")}},5900:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var utils=__webpack_require__(6436),common=__webpack_require__(5772),assert=__webpack_require__(9746),rotr64_hi=utils.rotr64_hi,rotr64_lo=utils.rotr64_lo,shr64_hi=utils.shr64_hi,shr64_lo=utils.shr64_lo,sum64=utils.sum64,sum64_hi=utils.sum64_hi,sum64_lo=utils.sum64_lo,sum64_4_hi=utils.sum64_4_hi,sum64_4_lo=utils.sum64_4_lo,sum64_5_hi=utils.sum64_5_hi,sum64_5_lo=utils.sum64_5_lo,BlockHash=common.BlockHash,sha512_K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function SHA512(){if(!(this instanceof SHA512))return new SHA512;BlockHash.call(this),this.h=[1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209],this.k=sha512_K,this.W=new Array(160)}function ch64_hi(xh,xl,yh,yl,zh){var r=xh&yh^~xh&zh;return r<0&&(r+=4294967296),r}function ch64_lo(xh,xl,yh,yl,zh,zl){var r=xl&yl^~xl&zl;return r<0&&(r+=4294967296),r}function maj64_hi(xh,xl,yh,yl,zh){var r=xh&yh^xh&zh^yh&zh;return r<0&&(r+=4294967296),r}function maj64_lo(xh,xl,yh,yl,zh,zl){var r=xl&yl^xl&zl^yl&zl;return r<0&&(r+=4294967296),r}function s0_512_hi(xh,xl){var r=rotr64_hi(xh,xl,28)^rotr64_hi(xl,xh,2)^rotr64_hi(xl,xh,7);return r<0&&(r+=4294967296),r}function s0_512_lo(xh,xl){var r=rotr64_lo(xh,xl,28)^rotr64_lo(xl,xh,2)^rotr64_lo(xl,xh,7);return r<0&&(r+=4294967296),r}function s1_512_hi(xh,xl){var r=rotr64_hi(xh,xl,14)^rotr64_hi(xh,xl,18)^rotr64_hi(xl,xh,9);return r<0&&(r+=4294967296),r}function s1_512_lo(xh,xl){var r=rotr64_lo(xh,xl,14)^rotr64_lo(xh,xl,18)^rotr64_lo(xl,xh,9);return r<0&&(r+=4294967296),r}function g0_512_hi(xh,xl){var r=rotr64_hi(xh,xl,1)^rotr64_hi(xh,xl,8)^shr64_hi(xh,xl,7);return r<0&&(r+=4294967296),r}function g0_512_lo(xh,xl){var r=rotr64_lo(xh,xl,1)^rotr64_lo(xh,xl,8)^shr64_lo(xh,xl,7);return r<0&&(r+=4294967296),r}function g1_512_hi(xh,xl){var r=rotr64_hi(xh,xl,19)^rotr64_hi(xl,xh,29)^shr64_hi(xh,xl,6);return r<0&&(r+=4294967296),r}function g1_512_lo(xh,xl){var r=rotr64_lo(xh,xl,19)^rotr64_lo(xl,xh,29)^shr64_lo(xh,xl,6);return r<0&&(r+=4294967296),r}utils.inherits(SHA512,BlockHash),module.exports=SHA512,SHA512.blockSize=1024,SHA512.outSize=512,SHA512.hmacStrength=192,SHA512.padLength=128,SHA512.prototype._prepareBlock=function _prepareBlock(msg,start){for(var W=this.W,i=0;i<32;i++)W[i]=msg[start+i];for(;i{"use strict";var rotr32=__webpack_require__(6436).rotr32;function ch32(x,y,z){return x&y^~x&z}function maj32(x,y,z){return x&y^x&z^y&z}function p32(x,y,z){return x^y^z}exports.ft_1=function ft_1(s,x,y,z){return 0===s?ch32(x,y,z):1===s||3===s?p32(x,y,z):2===s?maj32(x,y,z):void 0},exports.ch32=ch32,exports.maj32=maj32,exports.p32=p32,exports.s0_256=function s0_256(x){return rotr32(x,2)^rotr32(x,13)^rotr32(x,22)},exports.s1_256=function s1_256(x){return rotr32(x,6)^rotr32(x,11)^rotr32(x,25)},exports.g0_256=function g0_256(x){return rotr32(x,7)^rotr32(x,18)^x>>>3},exports.g1_256=function g1_256(x){return rotr32(x,17)^rotr32(x,19)^x>>>10}},6436:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";var assert=__webpack_require__(9746),inherits=__webpack_require__(5717);function isSurrogatePair(msg,i){return 55296==(64512&msg.charCodeAt(i))&&(!(i<0||i+1>=msg.length)&&56320==(64512&msg.charCodeAt(i+1)))}function htonl(w){return(w>>>24|w>>>8&65280|w<<8&16711680|(255&w)<<24)>>>0}function zero2(word){return 1===word.length?"0"+word:word}function zero8(word){return 7===word.length?"0"+word:6===word.length?"00"+word:5===word.length?"000"+word:4===word.length?"0000"+word:3===word.length?"00000"+word:2===word.length?"000000"+word:1===word.length?"0000000"+word:word}exports.inherits=inherits,exports.toArray=function toArray(msg,enc){if(Array.isArray(msg))return msg.slice();if(!msg)return[];var res=[];if("string"==typeof msg)if(enc){if("hex"===enc)for((msg=msg.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(msg="0"+msg),i=0;i>6|192,res[p++]=63&c|128):isSurrogatePair(msg,i)?(c=65536+((1023&c)<<10)+(1023&msg.charCodeAt(++i)),res[p++]=c>>18|240,res[p++]=c>>12&63|128,res[p++]=c>>6&63|128,res[p++]=63&c|128):(res[p++]=c>>12|224,res[p++]=c>>6&63|128,res[p++]=63&c|128)}else for(i=0;i>>0}return res},exports.split32=function split32(msg,endian){for(var res=new Array(4*msg.length),i=0,k=0;i>>24,res[k+1]=m>>>16&255,res[k+2]=m>>>8&255,res[k+3]=255&m):(res[k+3]=m>>>24,res[k+2]=m>>>16&255,res[k+1]=m>>>8&255,res[k]=255&m)}return res},exports.rotr32=function rotr32(w,b){return w>>>b|w<<32-b},exports.rotl32=function rotl32(w,b){return w<>>32-b},exports.sum32=function sum32(a,b){return a+b>>>0},exports.sum32_3=function sum32_3(a,b,c){return a+b+c>>>0},exports.sum32_4=function sum32_4(a,b,c,d){return a+b+c+d>>>0},exports.sum32_5=function sum32_5(a,b,c,d,e){return a+b+c+d+e>>>0},exports.sum64=function sum64(buf,pos,ah,al){var bh=buf[pos],lo=al+buf[pos+1]>>>0,hi=(lo>>0,buf[pos+1]=lo},exports.sum64_hi=function sum64_hi(ah,al,bh,bl){return(al+bl>>>0>>0},exports.sum64_lo=function sum64_lo(ah,al,bh,bl){return al+bl>>>0},exports.sum64_4_hi=function sum64_4_hi(ah,al,bh,bl,ch,cl,dh,dl){var carry=0,lo=al;return carry+=(lo=lo+bl>>>0)>>0)>>0)>>0},exports.sum64_4_lo=function sum64_4_lo(ah,al,bh,bl,ch,cl,dh,dl){return al+bl+cl+dl>>>0},exports.sum64_5_hi=function sum64_5_hi(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var carry=0,lo=al;return carry+=(lo=lo+bl>>>0)>>0)>>0)>>0)>>0},exports.sum64_5_lo=function sum64_5_lo(ah,al,bh,bl,ch,cl,dh,dl,eh,el){return al+bl+cl+dl+el>>>0},exports.rotr64_hi=function rotr64_hi(ah,al,num){return(al<<32-num|ah>>>num)>>>0},exports.rotr64_lo=function rotr64_lo(ah,al,num){return(ah<<32-num|al>>>num)>>>0},exports.shr64_hi=function shr64_hi(ah,al,num){return ah>>>num},exports.shr64_lo=function shr64_lo(ah,al,num){return(ah<<32-num|al>>>num)>>>0}},9840:(module,__unused_webpack_exports,__webpack_require__)=>{var assert=__webpack_require__(9282),Buffer=__webpack_require__(9509).Buffer,crypto=__webpack_require__(5835),bs58check=__webpack_require__(8334),secp256k1=__webpack_require__(7221),MASTER_SECRET=Buffer.from("Bitcoin seed","utf8"),BITCOIN_VERSIONS={private:76066276,public:76067358};function HDKey(versions){this.versions=versions||BITCOIN_VERSIONS,this.depth=0,this.index=0,this._privateKey=null,this._publicKey=null,this.chainCode=null,this._fingerprint=0,this.parentFingerprint=0}function serialize(hdkey,version,key){var buffer=Buffer.allocUnsafe(78);buffer.writeUInt32BE(version,0),buffer.writeUInt8(hdkey.depth,4);var fingerprint=hdkey.depth?hdkey.parentFingerprint:0;return buffer.writeUInt32BE(fingerprint,5),buffer.writeUInt32BE(hdkey.index,9),hdkey.chainCode.copy(buffer,13),key.copy(buffer,45),buffer}function hash160(buf){var sha=crypto.createHash("sha256").update(buf).digest();return crypto.createHash("ripemd160").update(sha).digest()}Object.defineProperty(HDKey.prototype,"fingerprint",{get:function(){return this._fingerprint}}),Object.defineProperty(HDKey.prototype,"identifier",{get:function(){return this._identifier}}),Object.defineProperty(HDKey.prototype,"pubKeyHash",{get:function(){return this.identifier}}),Object.defineProperty(HDKey.prototype,"privateKey",{get:function(){return this._privateKey},set:function(value){assert.equal(value.length,32,"Private key must be 32 bytes."),assert(!0===secp256k1.privateKeyVerify(value),"Invalid private key"),this._privateKey=value,this._publicKey=Buffer.from(secp256k1.publicKeyCreate(value,!0)),this._identifier=hash160(this.publicKey),this._fingerprint=this._identifier.slice(0,4).readUInt32BE(0)}}),Object.defineProperty(HDKey.prototype,"publicKey",{get:function(){return this._publicKey},set:function(value){assert(33===value.length||65===value.length,"Public key must be 33 or 65 bytes."),assert(!0===secp256k1.publicKeyVerify(value),"Invalid public key"),this._publicKey=Buffer.from(secp256k1.publicKeyConvert(value,!0)),this._identifier=hash160(this.publicKey),this._fingerprint=this._identifier.slice(0,4).readUInt32BE(0),this._privateKey=null}}),Object.defineProperty(HDKey.prototype,"privateExtendedKey",{get:function(){return this._privateKey?bs58check.encode(serialize(this,this.versions.private,Buffer.concat([Buffer.alloc(1,0),this.privateKey]))):null}}),Object.defineProperty(HDKey.prototype,"publicExtendedKey",{get:function(){return bs58check.encode(serialize(this,this.versions.public,this.publicKey))}}),HDKey.prototype.derive=function(path){if("m"===path||"M"===path||"m'"===path||"M'"===path)return this;var entries=path.split("/"),hdkey=this;return entries.forEach((function(c,i){if(0!==i){var hardened=c.length>1&&"'"===c[c.length-1],childIndex=parseInt(c,10);assert(childIndex<2147483648,"Invalid index"),hardened&&(childIndex+=2147483648),hdkey=hdkey.deriveChild(childIndex)}else assert(/^[mM]{1}/.test(c),'Path must start with "m" or "M"')})),hdkey},HDKey.prototype.deriveChild=function(index){var data,isHardened=index>=2147483648,indexBuffer=Buffer.allocUnsafe(4);if(indexBuffer.writeUInt32BE(index,0),isHardened){assert(this.privateKey,"Could not derive hardened child key");var pk=this.privateKey,zb=Buffer.alloc(1,0);pk=Buffer.concat([zb,pk]),data=Buffer.concat([pk,indexBuffer])}else data=Buffer.concat([this.publicKey,indexBuffer]);var I=crypto.createHmac("sha512",this.chainCode).update(data).digest(),IL=I.slice(0,32),IR=I.slice(32),hd=new HDKey(this.versions);if(this.privateKey)try{hd.privateKey=Buffer.from(secp256k1.privateKeyTweakAdd(Buffer.from(this.privateKey),IL))}catch(err){return this.deriveChild(index+1)}else try{hd.publicKey=Buffer.from(secp256k1.publicKeyTweakAdd(Buffer.from(this.publicKey),IL,!0))}catch(err){return this.deriveChild(index+1)}return hd.chainCode=IR,hd.depth=this.depth+1,hd.parentFingerprint=this.fingerprint,hd.index=index,hd},HDKey.prototype.sign=function(hash){return Buffer.from(secp256k1.ecdsaSign(hash,this.privateKey).signature)},HDKey.prototype.verify=function(hash,signature){return secp256k1.ecdsaVerify(Uint8Array.from(signature),Uint8Array.from(hash),Uint8Array.from(this.publicKey))},HDKey.prototype.wipePrivateData=function(){return this._privateKey&&crypto.randomBytes(this._privateKey.length).copy(this._privateKey),this._privateKey=null,this},HDKey.prototype.toJSON=function(){return{xpriv:this.privateExtendedKey,xpub:this.publicExtendedKey}},HDKey.fromMasterSeed=function(seedBuffer,versions){var I=crypto.createHmac("sha512",MASTER_SECRET).update(seedBuffer).digest(),IL=I.slice(0,32),IR=I.slice(32),hdkey=new HDKey(versions);return hdkey.chainCode=IR,hdkey.privateKey=IL,hdkey},HDKey.fromExtendedKey=function(base58key,versions){var hdkey=new HDKey(versions=versions||BITCOIN_VERSIONS),keyBuffer=bs58check.decode(base58key),version=keyBuffer.readUInt32BE(0);assert(version===versions.private||version===versions.public,"Version mismatch: does not match private or public"),hdkey.depth=keyBuffer.readUInt8(4),hdkey.parentFingerprint=keyBuffer.readUInt32BE(5),hdkey.index=keyBuffer.readUInt32BE(9),hdkey.chainCode=keyBuffer.slice(13,45);var key=keyBuffer.slice(45);return 0===key.readUInt8(0)?(assert(version===versions.private,"Version mismatch: version does not match private"),hdkey.privateKey=key.slice(1)):(assert(version===versions.public,"Version mismatch: version does not match public"),hdkey.publicKey=key),hdkey},HDKey.fromJSON=function(obj){return HDKey.fromExtendedKey(obj.xpriv)},HDKey.HARDENED_OFFSET=2147483648,module.exports=HDKey},2156:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var hash=__webpack_require__(3715),utils=__webpack_require__(4504),assert=__webpack_require__(9746);function HmacDRBG(options){if(!(this instanceof HmacDRBG))return new HmacDRBG(options);this.hash=options.hash,this.predResist=!!options.predResist,this.outLen=this.hash.outSize,this.minEntropy=options.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var entropy=utils.toArray(options.entropy,options.entropyEnc||"hex"),nonce=utils.toArray(options.nonce,options.nonceEnc||"hex"),pers=utils.toArray(options.pers,options.persEnc||"hex");assert(entropy.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(entropy,nonce,pers)}module.exports=HmacDRBG,HmacDRBG.prototype._init=function init(entropy,nonce,pers){var seed=entropy.concat(nonce).concat(pers);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(entropy.concat(add||[])),this._reseed=1},HmacDRBG.prototype.generate=function generate(len,enc,add,addEnc){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof enc&&(addEnc=add,add=enc,enc=null),add&&(add=utils.toArray(add,addEnc||"hex"),this._update(add));for(var temp=[];temp.length{exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=8*nBytes-mLen-1,eMax=(1<>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;nBits>0;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;nBits>0;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:1/0*(s?-1:1);m+=Math.pow(2,mLen),e-=eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)},exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=8*nBytes-mLen-1,eMax=(1<>1,rt=23===mLen?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||0===value&&1/value<0?1:0;for(value=Math.abs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=Math.floor(Math.log(value)/Math.LN2),value*(c=Math.pow(2,-e))<1&&(e--,c*=2),(value+=e+eBias>=1?rt/c:rt*Math.pow(2,1-eBias))*c>=2&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):e+eBias>=1?(m=(value*c-1)*Math.pow(2,mLen),e+=eBias):(m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen),e=0));mLen>=8;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<0;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},5717:module=>{"function"==typeof Object.create?module.exports=function inherits(ctor,superCtor){superCtor&&(ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}}))}:module.exports=function inherits(ctor,superCtor){if(superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}}},2584:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var hasToStringTag=__webpack_require__(6410)(),$toString=__webpack_require__(1924)("Object.prototype.toString"),isStandardArguments=function isArguments(value){return!(hasToStringTag&&value&&"object"==typeof value&&Symbol.toStringTag in value)&&"[object Arguments]"===$toString(value)},isLegacyArguments=function isArguments(value){return!!isStandardArguments(value)||null!==value&&"object"==typeof value&&"number"==typeof value.length&&value.length>=0&&"[object Array]"!==$toString(value)&&"[object Function]"===$toString(value.callee)},supportsStandardArguments=function(){return isStandardArguments(arguments)}();isStandardArguments.isLegacyArguments=isLegacyArguments,module.exports=supportsStandardArguments?isStandardArguments:isLegacyArguments},8662:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var GeneratorFunction,toStr=Object.prototype.toString,fnToStr=Function.prototype.toString,isFnRegex=/^\s*(?:function)?\*/,hasToStringTag=__webpack_require__(6410)(),getProto=Object.getPrototypeOf;module.exports=function isGeneratorFunction(fn){if("function"!=typeof fn)return!1;if(isFnRegex.test(fnToStr.call(fn)))return!0;if(!hasToStringTag)return"[object GeneratorFunction]"===toStr.call(fn);if(!getProto)return!1;if(void 0===GeneratorFunction){var generatorFunc=function(){if(!hasToStringTag)return!1;try{return Function("return function*() {}")()}catch(e){}}();GeneratorFunction=!!generatorFunc&&getProto(generatorFunc)}return getProto(fn)===GeneratorFunction}},8611:module=>{"use strict";module.exports=function isNaN(value){return value!=value}},360:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var callBind=__webpack_require__(5559),define=__webpack_require__(4289),implementation=__webpack_require__(8611),getPolyfill=__webpack_require__(9415),shim=__webpack_require__(3194),polyfill=callBind(getPolyfill(),Number);define(polyfill,{getPolyfill,implementation,shim}),module.exports=polyfill},9415:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var implementation=__webpack_require__(8611);module.exports=function getPolyfill(){return Number.isNaN&&Number.isNaN(NaN)&&!Number.isNaN("a")?Number.isNaN:implementation}},3194:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var define=__webpack_require__(4289),getPolyfill=__webpack_require__(9415);module.exports=function shimNumberIsNaN(){var polyfill=getPolyfill();return define(Number,{isNaN:polyfill},{isNaN:function testIsNaN(){return Number.isNaN!==polyfill}}),polyfill}},5692:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var forEach=__webpack_require__(9804),availableTypedArrays=__webpack_require__(3083),callBound=__webpack_require__(1924),$toString=callBound("Object.prototype.toString"),hasToStringTag=__webpack_require__(6410)(),g="undefined"==typeof globalThis?__webpack_require__.g:globalThis,typedArrays=availableTypedArrays(),$indexOf=callBound("Array.prototype.indexOf",!0)||function indexOf(array,value){for(var i=0;i-1}return!!gOPD&&function tryAllTypedArrays(value){var anyTrue=!1;return forEach(toStrTags,(function(getter,typedArray){if(!anyTrue)try{anyTrue=getter.call(value)===typedArray}catch(e){}})),anyTrue}(value)}},6792:(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{default:()=>__WEBPACK_DEFAULT_EXPORT__});var ws=null;"undefined"!=typeof WebSocket?ws=WebSocket:"undefined"!=typeof MozWebSocket?ws=MozWebSocket:void 0!==__webpack_require__.g?ws=__webpack_require__.g.WebSocket||__webpack_require__.g.MozWebSocket:"undefined"!=typeof window?ws=window.WebSocket||window.MozWebSocket:"undefined"!=typeof self&&(ws=self.WebSocket||self.MozWebSocket);const __WEBPACK_DEFAULT_EXPORT__=ws},1094:(module,exports,__webpack_require__)=>{var __WEBPACK_AMD_DEFINE_RESULT__;!function(){"use strict";var INPUT_ERROR="input is invalid type",WINDOW="object"==typeof window,root=WINDOW?window:{};root.JS_SHA3_NO_WINDOW&&(WINDOW=!1);var WEB_WORKER=!WINDOW&&"object"==typeof self;!root.JS_SHA3_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node?root=__webpack_require__.g:WEB_WORKER&&(root=self);var COMMON_JS=!root.JS_SHA3_NO_COMMON_JS&&module.exports,AMD=__webpack_require__.amdO,ARRAY_BUFFER=!root.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,HEX_CHARS="0123456789abcdef".split(""),CSHAKE_PADDING=[4,1024,262144,67108864],SHIFT=[0,8,16,24],RC=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],BITS=[224,256,384,512],SHAKE_BITS=[128,256],OUTPUT_TYPES=["hex","buffer","arrayBuffer","array","digest"],CSHAKE_BYTEPAD={128:168,256:136};!root.JS_SHA3_NO_NODE_JS&&Array.isArray||(Array.isArray=function(obj){return"[object Array]"===Object.prototype.toString.call(obj)}),!ARRAY_BUFFER||!root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(obj){return"object"==typeof obj&&obj.buffer&&obj.buffer.constructor===ArrayBuffer});for(var createOutputMethod=function(bits,padding,outputType){return function(message){return new Keccak(bits,padding,bits).update(message)[outputType]()}},createShakeOutputMethod=function(bits,padding,outputType){return function(message,outputBits){return new Keccak(bits,padding,outputBits).update(message)[outputType]()}},createCshakeOutputMethod=function(bits,padding,outputType){return function(message,outputBits,n,s){return methods["cshake"+bits].update(message,outputBits,n,s)[outputType]()}},createKmacOutputMethod=function(bits,padding,outputType){return function(key,message,outputBits,s){return methods["kmac"+bits].update(key,message,outputBits,s)[outputType]()}},createOutputMethods=function(method,createMethod,bits,padding){for(var i=0;i>5,this.byteCount=this.blockCount<<2,this.outputBlocks=outputBits>>5,this.extraBytes=(31&outputBits)>>3;for(var i=0;i<50;++i)this.s[i]=0}function Kmac(bits,padding,outputBits){Keccak.call(this,bits,padding,outputBits)}Keccak.prototype.update=function(message){if(this.finalized)throw new Error("finalize already called");var notString,type=typeof message;if("string"!==type){if("object"!==type)throw new Error(INPUT_ERROR);if(null===message)throw new Error(INPUT_ERROR);if(ARRAY_BUFFER&&message.constructor===ArrayBuffer)message=new Uint8Array(message);else if(!(Array.isArray(message)||ARRAY_BUFFER&&ArrayBuffer.isView(message)))throw new Error(INPUT_ERROR);notString=!0}for(var i,code,blocks=this.blocks,byteCount=this.byteCount,length=message.length,blockCount=this.blockCount,index=0,s=this.s;index>2]|=message[index]<>2]|=code<>2]|=(192|code>>6)<>2]|=(128|63&code)<=57344?(blocks[i>>2]|=(224|code>>12)<>2]|=(128|code>>6&63)<>2]|=(128|63&code)<>2]|=(240|code>>18)<>2]|=(128|code>>12&63)<>2]|=(128|code>>6&63)<>2]|=(128|63&code)<=byteCount){for(this.start=i-byteCount,this.block=blocks[blockCount],i=0;i>=8);o>0;)bytes.unshift(o),o=255&(x>>=8),++n;return right?bytes.push(n):bytes.unshift(n),this.update(bytes),bytes.length},Keccak.prototype.encodeString=function(str){var notString,type=typeof str;if("string"!==type){if("object"!==type)throw new Error(INPUT_ERROR);if(null===str)throw new Error(INPUT_ERROR);if(ARRAY_BUFFER&&str.constructor===ArrayBuffer)str=new Uint8Array(str);else if(!(Array.isArray(str)||ARRAY_BUFFER&&ArrayBuffer.isView(str)))throw new Error(INPUT_ERROR);notString=!0}var bytes=0,length=str.length;if(notString)bytes=length;else for(var i=0;i=57344?bytes+=3:(code=65536+((1023&code)<<10|1023&str.charCodeAt(++i)),bytes+=4)}return bytes+=this.encode(8*bytes),this.update(str),bytes},Keccak.prototype.bytepad=function(strs,w){for(var bytes=this.encode(w),i=0;i>2]|=this.padding[3&i],this.lastByteIndex===this.byteCount)for(blocks[0]=blocks[blockCount],i=1;i>4&15]+HEX_CHARS[15&block]+HEX_CHARS[block>>12&15]+HEX_CHARS[block>>8&15]+HEX_CHARS[block>>20&15]+HEX_CHARS[block>>16&15]+HEX_CHARS[block>>28&15]+HEX_CHARS[block>>24&15];j%blockCount==0&&(f(s),i=0)}return extraBytes&&(block=s[i],hex+=HEX_CHARS[block>>4&15]+HEX_CHARS[15&block],extraBytes>1&&(hex+=HEX_CHARS[block>>12&15]+HEX_CHARS[block>>8&15]),extraBytes>2&&(hex+=HEX_CHARS[block>>20&15]+HEX_CHARS[block>>16&15])),hex},Keccak.prototype.arrayBuffer=function(){this.finalize();var buffer,blockCount=this.blockCount,s=this.s,outputBlocks=this.outputBlocks,extraBytes=this.extraBytes,i=0,j=0,bytes=this.outputBits>>3;buffer=extraBytes?new ArrayBuffer(outputBlocks+1<<2):new ArrayBuffer(bytes);for(var array=new Uint32Array(buffer);j>8&255,array[offset+2]=block>>16&255,array[offset+3]=block>>24&255;j%blockCount==0&&f(s)}return extraBytes&&(offset=j<<2,block=s[i],array[offset]=255&block,extraBytes>1&&(array[offset+1]=block>>8&255),extraBytes>2&&(array[offset+2]=block>>16&255)),array},Kmac.prototype=new Keccak,Kmac.prototype.finalize=function(){return this.encode(this.outputBits,!0),Keccak.prototype.finalize.call(this)};var f=function(s){var h,l,n,c0,c1,c2,c3,c4,c5,c6,c7,c8,c9,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,b19,b20,b21,b22,b23,b24,b25,b26,b27,b28,b29,b30,b31,b32,b33,b34,b35,b36,b37,b38,b39,b40,b41,b42,b43,b44,b45,b46,b47,b48,b49;for(n=0;n<48;n+=2)c0=s[0]^s[10]^s[20]^s[30]^s[40],c1=s[1]^s[11]^s[21]^s[31]^s[41],c2=s[2]^s[12]^s[22]^s[32]^s[42],c3=s[3]^s[13]^s[23]^s[33]^s[43],c4=s[4]^s[14]^s[24]^s[34]^s[44],c5=s[5]^s[15]^s[25]^s[35]^s[45],c6=s[6]^s[16]^s[26]^s[36]^s[46],c7=s[7]^s[17]^s[27]^s[37]^s[47],h=(c8=s[8]^s[18]^s[28]^s[38]^s[48])^(c2<<1|c3>>>31),l=(c9=s[9]^s[19]^s[29]^s[39]^s[49])^(c3<<1|c2>>>31),s[0]^=h,s[1]^=l,s[10]^=h,s[11]^=l,s[20]^=h,s[21]^=l,s[30]^=h,s[31]^=l,s[40]^=h,s[41]^=l,h=c0^(c4<<1|c5>>>31),l=c1^(c5<<1|c4>>>31),s[2]^=h,s[3]^=l,s[12]^=h,s[13]^=l,s[22]^=h,s[23]^=l,s[32]^=h,s[33]^=l,s[42]^=h,s[43]^=l,h=c2^(c6<<1|c7>>>31),l=c3^(c7<<1|c6>>>31),s[4]^=h,s[5]^=l,s[14]^=h,s[15]^=l,s[24]^=h,s[25]^=l,s[34]^=h,s[35]^=l,s[44]^=h,s[45]^=l,h=c4^(c8<<1|c9>>>31),l=c5^(c9<<1|c8>>>31),s[6]^=h,s[7]^=l,s[16]^=h,s[17]^=l,s[26]^=h,s[27]^=l,s[36]^=h,s[37]^=l,s[46]^=h,s[47]^=l,h=c6^(c0<<1|c1>>>31),l=c7^(c1<<1|c0>>>31),s[8]^=h,s[9]^=l,s[18]^=h,s[19]^=l,s[28]^=h,s[29]^=l,s[38]^=h,s[39]^=l,s[48]^=h,s[49]^=l,b0=s[0],b1=s[1],b32=s[11]<<4|s[10]>>>28,b33=s[10]<<4|s[11]>>>28,b14=s[20]<<3|s[21]>>>29,b15=s[21]<<3|s[20]>>>29,b46=s[31]<<9|s[30]>>>23,b47=s[30]<<9|s[31]>>>23,b28=s[40]<<18|s[41]>>>14,b29=s[41]<<18|s[40]>>>14,b20=s[2]<<1|s[3]>>>31,b21=s[3]<<1|s[2]>>>31,b2=s[13]<<12|s[12]>>>20,b3=s[12]<<12|s[13]>>>20,b34=s[22]<<10|s[23]>>>22,b35=s[23]<<10|s[22]>>>22,b16=s[33]<<13|s[32]>>>19,b17=s[32]<<13|s[33]>>>19,b48=s[42]<<2|s[43]>>>30,b49=s[43]<<2|s[42]>>>30,b40=s[5]<<30|s[4]>>>2,b41=s[4]<<30|s[5]>>>2,b22=s[14]<<6|s[15]>>>26,b23=s[15]<<6|s[14]>>>26,b4=s[25]<<11|s[24]>>>21,b5=s[24]<<11|s[25]>>>21,b36=s[34]<<15|s[35]>>>17,b37=s[35]<<15|s[34]>>>17,b18=s[45]<<29|s[44]>>>3,b19=s[44]<<29|s[45]>>>3,b10=s[6]<<28|s[7]>>>4,b11=s[7]<<28|s[6]>>>4,b42=s[17]<<23|s[16]>>>9,b43=s[16]<<23|s[17]>>>9,b24=s[26]<<25|s[27]>>>7,b25=s[27]<<25|s[26]>>>7,b6=s[36]<<21|s[37]>>>11,b7=s[37]<<21|s[36]>>>11,b38=s[47]<<24|s[46]>>>8,b39=s[46]<<24|s[47]>>>8,b30=s[8]<<27|s[9]>>>5,b31=s[9]<<27|s[8]>>>5,b12=s[18]<<20|s[19]>>>12,b13=s[19]<<20|s[18]>>>12,b44=s[29]<<7|s[28]>>>25,b45=s[28]<<7|s[29]>>>25,b26=s[38]<<8|s[39]>>>24,b27=s[39]<<8|s[38]>>>24,b8=s[48]<<14|s[49]>>>18,b9=s[49]<<14|s[48]>>>18,s[0]=b0^~b2&b4,s[1]=b1^~b3&b5,s[10]=b10^~b12&b14,s[11]=b11^~b13&b15,s[20]=b20^~b22&b24,s[21]=b21^~b23&b25,s[30]=b30^~b32&b34,s[31]=b31^~b33&b35,s[40]=b40^~b42&b44,s[41]=b41^~b43&b45,s[2]=b2^~b4&b6,s[3]=b3^~b5&b7,s[12]=b12^~b14&b16,s[13]=b13^~b15&b17,s[22]=b22^~b24&b26,s[23]=b23^~b25&b27,s[32]=b32^~b34&b36,s[33]=b33^~b35&b37,s[42]=b42^~b44&b46,s[43]=b43^~b45&b47,s[4]=b4^~b6&b8,s[5]=b5^~b7&b9,s[14]=b14^~b16&b18,s[15]=b15^~b17&b19,s[24]=b24^~b26&b28,s[25]=b25^~b27&b29,s[34]=b34^~b36&b38,s[35]=b35^~b37&b39,s[44]=b44^~b46&b48,s[45]=b45^~b47&b49,s[6]=b6^~b8&b0,s[7]=b7^~b9&b1,s[16]=b16^~b18&b10,s[17]=b17^~b19&b11,s[26]=b26^~b28&b20,s[27]=b27^~b29&b21,s[36]=b36^~b38&b30,s[37]=b37^~b39&b31,s[46]=b46^~b48&b40,s[47]=b47^~b49&b41,s[8]=b8^~b0&b2,s[9]=b9^~b1&b3,s[18]=b18^~b10&b12,s[19]=b19^~b11&b13,s[28]=b28^~b20&b22,s[29]=b29^~b21&b23,s[38]=b38^~b30&b32,s[39]=b39^~b31&b33,s[48]=b48^~b40&b42,s[49]=b49^~b41&b43,s[0]^=RC[n],s[1]^=RC[n+1]};if(COMMON_JS)module.exports=methods;else{for(i=0;i{"use strict";var inherits=__webpack_require__(5717),HashBase=__webpack_require__(3349),Buffer=__webpack_require__(9509).Buffer,ARRAY16=new Array(16);function MD5(){HashBase.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}function rotl(x,n){return x<>>32-n}function fnF(a,b,c,d,m,k,s){return rotl(a+(b&c|~b&d)+m+k|0,s)+b|0}function fnG(a,b,c,d,m,k,s){return rotl(a+(b&d|c&~d)+m+k|0,s)+b|0}function fnH(a,b,c,d,m,k,s){return rotl(a+(b^c^d)+m+k|0,s)+b|0}function fnI(a,b,c,d,m,k,s){return rotl(a+(c^(b|~d))+m+k|0,s)+b|0}inherits(MD5,HashBase),MD5.prototype._update=function(){for(var M=ARRAY16,i=0;i<16;++i)M[i]=this._block.readInt32LE(4*i);var a=this._a,b=this._b,c=this._c,d=this._d;a=fnF(a,b,c,d,M[0],3614090360,7),d=fnF(d,a,b,c,M[1],3905402710,12),c=fnF(c,d,a,b,M[2],606105819,17),b=fnF(b,c,d,a,M[3],3250441966,22),a=fnF(a,b,c,d,M[4],4118548399,7),d=fnF(d,a,b,c,M[5],1200080426,12),c=fnF(c,d,a,b,M[6],2821735955,17),b=fnF(b,c,d,a,M[7],4249261313,22),a=fnF(a,b,c,d,M[8],1770035416,7),d=fnF(d,a,b,c,M[9],2336552879,12),c=fnF(c,d,a,b,M[10],4294925233,17),b=fnF(b,c,d,a,M[11],2304563134,22),a=fnF(a,b,c,d,M[12],1804603682,7),d=fnF(d,a,b,c,M[13],4254626195,12),c=fnF(c,d,a,b,M[14],2792965006,17),a=fnG(a,b=fnF(b,c,d,a,M[15],1236535329,22),c,d,M[1],4129170786,5),d=fnG(d,a,b,c,M[6],3225465664,9),c=fnG(c,d,a,b,M[11],643717713,14),b=fnG(b,c,d,a,M[0],3921069994,20),a=fnG(a,b,c,d,M[5],3593408605,5),d=fnG(d,a,b,c,M[10],38016083,9),c=fnG(c,d,a,b,M[15],3634488961,14),b=fnG(b,c,d,a,M[4],3889429448,20),a=fnG(a,b,c,d,M[9],568446438,5),d=fnG(d,a,b,c,M[14],3275163606,9),c=fnG(c,d,a,b,M[3],4107603335,14),b=fnG(b,c,d,a,M[8],1163531501,20),a=fnG(a,b,c,d,M[13],2850285829,5),d=fnG(d,a,b,c,M[2],4243563512,9),c=fnG(c,d,a,b,M[7],1735328473,14),a=fnH(a,b=fnG(b,c,d,a,M[12],2368359562,20),c,d,M[5],4294588738,4),d=fnH(d,a,b,c,M[8],2272392833,11),c=fnH(c,d,a,b,M[11],1839030562,16),b=fnH(b,c,d,a,M[14],4259657740,23),a=fnH(a,b,c,d,M[1],2763975236,4),d=fnH(d,a,b,c,M[4],1272893353,11),c=fnH(c,d,a,b,M[7],4139469664,16),b=fnH(b,c,d,a,M[10],3200236656,23),a=fnH(a,b,c,d,M[13],681279174,4),d=fnH(d,a,b,c,M[0],3936430074,11),c=fnH(c,d,a,b,M[3],3572445317,16),b=fnH(b,c,d,a,M[6],76029189,23),a=fnH(a,b,c,d,M[9],3654602809,4),d=fnH(d,a,b,c,M[12],3873151461,11),c=fnH(c,d,a,b,M[15],530742520,16),a=fnI(a,b=fnH(b,c,d,a,M[2],3299628645,23),c,d,M[0],4096336452,6),d=fnI(d,a,b,c,M[7],1126891415,10),c=fnI(c,d,a,b,M[14],2878612391,15),b=fnI(b,c,d,a,M[5],4237533241,21),a=fnI(a,b,c,d,M[12],1700485571,6),d=fnI(d,a,b,c,M[3],2399980690,10),c=fnI(c,d,a,b,M[10],4293915773,15),b=fnI(b,c,d,a,M[1],2240044497,21),a=fnI(a,b,c,d,M[8],1873313359,6),d=fnI(d,a,b,c,M[15],4264355552,10),c=fnI(c,d,a,b,M[6],2734768916,15),b=fnI(b,c,d,a,M[13],1309151649,21),a=fnI(a,b,c,d,M[4],4149444226,6),d=fnI(d,a,b,c,M[11],3174756917,10),c=fnI(c,d,a,b,M[2],718787259,15),b=fnI(b,c,d,a,M[9],3951481745,21),this._a=this._a+a|0,this._b=this._b+b|0,this._c=this._c+c|0,this._d=this._d+d|0},MD5.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var buffer=Buffer.allocUnsafe(16);return buffer.writeInt32LE(this._a,0),buffer.writeInt32LE(this._b,4),buffer.writeInt32LE(this._c,8),buffer.writeInt32LE(this._d,12),buffer},module.exports=MD5},3047:(module,__unused_webpack_exports,__webpack_require__)=>{var bn=__webpack_require__(6240),brorand=__webpack_require__(9931);function MillerRabin(rand){this.rand=rand||new brorand.Rand}module.exports=MillerRabin,MillerRabin.create=function create(rand){return new MillerRabin(rand)},MillerRabin.prototype._randbelow=function _randbelow(n){var len=n.bitLength(),min_bytes=Math.ceil(len/8);do{var a=new bn(this.rand.generate(min_bytes))}while(a.cmp(n)>=0);return a},MillerRabin.prototype._randrange=function _randrange(start,stop){var size=stop.sub(start);return start.add(this._randbelow(size))},MillerRabin.prototype.test=function test(n,k,cb){var len=n.bitLength(),red=bn.mont(n),rone=new bn(1).toRed(red);k||(k=Math.max(1,len/48|0));for(var n1=n.subn(1),s=0;!n1.testn(s);s++);for(var d=n.shrn(s),rn1=n1.toRed(red);k>0;k--){var a=this._randrange(new bn(2),n1);cb&&cb(a);var x=a.toRed(red).redPow(d);if(0!==x.cmp(rone)&&0!==x.cmp(rn1)){for(var i=1;i0;k--){var a=this._randrange(new bn(2),n1),g=n.gcd(a);if(0!==g.cmpn(1))return g;var x=a.toRed(red).redPow(d);if(0!==x.cmp(rone)&&0!==x.cmp(rn1)){for(var i=1;i=65&&c<=70?c-55:c>=97&&c<=102?c-87:c-48&15}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return index-1>=lowerBound&&(r|=parseHex4Bits(string,index-1)<<4),r}function parseBase(str,start,end,mul){for(var r=0,len=Math.min(str.length,end),i=start;i=49?c-49+10:c>=17?c-17+10:c}return r}BN.isBN=function isBN(num){return num instanceof BN||null!==num&&"object"==typeof num&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words)},BN.max=function max(left,right){return left.cmp(right)>0?left:right},BN.min=function min(left,right){return left.cmp(right)<0?left:right},BN.prototype._init=function init(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&base>=2&&base<=36);var start=0;"-"===(number=number.toString().replace(/\s+/g,""))[0]&&(start++,this.negative=1),start=0;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=w<>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);return this.strip()},BN.prototype._parseHex=function _parseHex(number,start,endian){this.length=Math.ceil((number.length-start)/6),this.words=new Array(this.length);for(var i=0;i=start;i-=2)w=parseHexByte(number,start,i)<=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;else for(i=(number.length-start)%2==0?start+1:start;i=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;this.strip()},BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;limbPow*=base)limbLen++;limbLen--,limbPow=limbPow/base|0;for(var total=number.length-start,mod=total%limbLen,end=Math.min(total,total-mod)+start,word=0,i=start;i1&&0===this.words[this.length-1];)this.length--;return this._normSign()},BN.prototype._normSign=function _normSign(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},BN.prototype.inspect=function inspect(){return(this.red?""};var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=self.length+num.length|0;out.length=len,len=len-1|0;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=r/67108864|0;out.words[0]=lo;for(var k=1;k>>26,rword=67108863&carry,maxJ=Math.min(k,num.length-1),j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j|0;ncarry+=(r=(a=0|self.words[i])*(b=0|num.words[j])+rword)/67108864|0,rword=67108863&r}out.words[k]=0|rword,carry=0|ncarry}return 0!==carry?out.words[k]=0|carry:out.length--,out.strip()}BN.prototype.toString=function toString(base,padding){var out;if(padding=0|padding||1,16===(base=base||10)||"hex"===base){out="";for(var off=0,carry=0,i=0;i>>24-off&16777215)||i!==this.length-1?zeros[6-word.length]+word+out:word+out,(off+=2)>=26&&(off-=26,i--)}for(0!==carry&&(out=carry.toString(16)+out);out.length%padding!=0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&base>=2&&base<=36){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modn(groupBase).toString(base);out=(c=c.idivn(groupBase)).isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);out.length%padding!=0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function toNumber(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:this.length>2&&assert(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-ret:ret},BN.prototype.toJSON=function toJSON(){return this.toString(16)},BN.prototype.toBuffer=function toBuffer(endian,length){return assert(void 0!==Buffer),this.toArrayLike(Buffer,endian,length)},BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)},BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){var byteLength=this.byteLength(),reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length"),assert(reqLength>0,"Requested array length <= 0"),this.strip();var b,i,littleEndian="le"===endian,res=new ArrayType(reqLength),q=this.clone();if(littleEndian){for(i=0;!q.isZero();i++)b=q.andln(255),q.iushrn(8),res[i]=b;for(;i=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function _zeroBits(w){if(0===w)return 26;var t=w,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;for(var r=0,i=0;inum.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function uor(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function iuand(num){var b;b=this.length>num.length?num:this;for(var i=0;inum.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function uand(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function iuxor(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;inum.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function uxor(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function inotn(width){assert("number"==typeof width&&width>=0);var bytesNeeded=0|Math.ceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),bitsLeft>0&&bytesNeeded--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this.strip()},BN.prototype.notn=function notn(width){return this.clone().inotn(width)},BN.prototype.setn=function setn(bit,val){assert("number"==typeof bit&&bit>=0);var off=bit/26|0,wbit=bit%26;return this._expand(off+1),this.words[off]=val?this.words[off]|1<num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>>26;for(;0!==carry&&i>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;inum.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function isub(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var a,b,cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;cmp>0?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>26,this.words[i]=67108863&r;for(;0!==carry&&i>26,this.words[i]=67108863&r;if(0===carry&&i>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13;out.negative=self.negative^num.negative,out.length=19;var w0=(c+(lo=Math.imul(al0,bl0))|0)+((8191&(mid=(mid=Math.imul(al0,bh0))+Math.imul(ah0,bl0)|0))<<13)|0;c=((hi=Math.imul(ah0,bh0))+(mid>>>13)|0)+(w0>>>26)|0,w0&=67108863,lo=Math.imul(al1,bl0),mid=(mid=Math.imul(al1,bh0))+Math.imul(ah1,bl0)|0,hi=Math.imul(ah1,bh0);var w1=(c+(lo=lo+Math.imul(al0,bl1)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh1)|0)+Math.imul(ah0,bl1)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh1)|0)+(mid>>>13)|0)+(w1>>>26)|0,w1&=67108863,lo=Math.imul(al2,bl0),mid=(mid=Math.imul(al2,bh0))+Math.imul(ah2,bl0)|0,hi=Math.imul(ah2,bh0),lo=lo+Math.imul(al1,bl1)|0,mid=(mid=mid+Math.imul(al1,bh1)|0)+Math.imul(ah1,bl1)|0,hi=hi+Math.imul(ah1,bh1)|0;var w2=(c+(lo=lo+Math.imul(al0,bl2)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh2)|0)+Math.imul(ah0,bl2)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh2)|0)+(mid>>>13)|0)+(w2>>>26)|0,w2&=67108863,lo=Math.imul(al3,bl0),mid=(mid=Math.imul(al3,bh0))+Math.imul(ah3,bl0)|0,hi=Math.imul(ah3,bh0),lo=lo+Math.imul(al2,bl1)|0,mid=(mid=mid+Math.imul(al2,bh1)|0)+Math.imul(ah2,bl1)|0,hi=hi+Math.imul(ah2,bh1)|0,lo=lo+Math.imul(al1,bl2)|0,mid=(mid=mid+Math.imul(al1,bh2)|0)+Math.imul(ah1,bl2)|0,hi=hi+Math.imul(ah1,bh2)|0;var w3=(c+(lo=lo+Math.imul(al0,bl3)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh3)|0)+Math.imul(ah0,bl3)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh3)|0)+(mid>>>13)|0)+(w3>>>26)|0,w3&=67108863,lo=Math.imul(al4,bl0),mid=(mid=Math.imul(al4,bh0))+Math.imul(ah4,bl0)|0,hi=Math.imul(ah4,bh0),lo=lo+Math.imul(al3,bl1)|0,mid=(mid=mid+Math.imul(al3,bh1)|0)+Math.imul(ah3,bl1)|0,hi=hi+Math.imul(ah3,bh1)|0,lo=lo+Math.imul(al2,bl2)|0,mid=(mid=mid+Math.imul(al2,bh2)|0)+Math.imul(ah2,bl2)|0,hi=hi+Math.imul(ah2,bh2)|0,lo=lo+Math.imul(al1,bl3)|0,mid=(mid=mid+Math.imul(al1,bh3)|0)+Math.imul(ah1,bl3)|0,hi=hi+Math.imul(ah1,bh3)|0;var w4=(c+(lo=lo+Math.imul(al0,bl4)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh4)|0)+Math.imul(ah0,bl4)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh4)|0)+(mid>>>13)|0)+(w4>>>26)|0,w4&=67108863,lo=Math.imul(al5,bl0),mid=(mid=Math.imul(al5,bh0))+Math.imul(ah5,bl0)|0,hi=Math.imul(ah5,bh0),lo=lo+Math.imul(al4,bl1)|0,mid=(mid=mid+Math.imul(al4,bh1)|0)+Math.imul(ah4,bl1)|0,hi=hi+Math.imul(ah4,bh1)|0,lo=lo+Math.imul(al3,bl2)|0,mid=(mid=mid+Math.imul(al3,bh2)|0)+Math.imul(ah3,bl2)|0,hi=hi+Math.imul(ah3,bh2)|0,lo=lo+Math.imul(al2,bl3)|0,mid=(mid=mid+Math.imul(al2,bh3)|0)+Math.imul(ah2,bl3)|0,hi=hi+Math.imul(ah2,bh3)|0,lo=lo+Math.imul(al1,bl4)|0,mid=(mid=mid+Math.imul(al1,bh4)|0)+Math.imul(ah1,bl4)|0,hi=hi+Math.imul(ah1,bh4)|0;var w5=(c+(lo=lo+Math.imul(al0,bl5)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh5)|0)+Math.imul(ah0,bl5)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh5)|0)+(mid>>>13)|0)+(w5>>>26)|0,w5&=67108863,lo=Math.imul(al6,bl0),mid=(mid=Math.imul(al6,bh0))+Math.imul(ah6,bl0)|0,hi=Math.imul(ah6,bh0),lo=lo+Math.imul(al5,bl1)|0,mid=(mid=mid+Math.imul(al5,bh1)|0)+Math.imul(ah5,bl1)|0,hi=hi+Math.imul(ah5,bh1)|0,lo=lo+Math.imul(al4,bl2)|0,mid=(mid=mid+Math.imul(al4,bh2)|0)+Math.imul(ah4,bl2)|0,hi=hi+Math.imul(ah4,bh2)|0,lo=lo+Math.imul(al3,bl3)|0,mid=(mid=mid+Math.imul(al3,bh3)|0)+Math.imul(ah3,bl3)|0,hi=hi+Math.imul(ah3,bh3)|0,lo=lo+Math.imul(al2,bl4)|0,mid=(mid=mid+Math.imul(al2,bh4)|0)+Math.imul(ah2,bl4)|0,hi=hi+Math.imul(ah2,bh4)|0,lo=lo+Math.imul(al1,bl5)|0,mid=(mid=mid+Math.imul(al1,bh5)|0)+Math.imul(ah1,bl5)|0,hi=hi+Math.imul(ah1,bh5)|0;var w6=(c+(lo=lo+Math.imul(al0,bl6)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh6)|0)+Math.imul(ah0,bl6)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh6)|0)+(mid>>>13)|0)+(w6>>>26)|0,w6&=67108863,lo=Math.imul(al7,bl0),mid=(mid=Math.imul(al7,bh0))+Math.imul(ah7,bl0)|0,hi=Math.imul(ah7,bh0),lo=lo+Math.imul(al6,bl1)|0,mid=(mid=mid+Math.imul(al6,bh1)|0)+Math.imul(ah6,bl1)|0,hi=hi+Math.imul(ah6,bh1)|0,lo=lo+Math.imul(al5,bl2)|0,mid=(mid=mid+Math.imul(al5,bh2)|0)+Math.imul(ah5,bl2)|0,hi=hi+Math.imul(ah5,bh2)|0,lo=lo+Math.imul(al4,bl3)|0,mid=(mid=mid+Math.imul(al4,bh3)|0)+Math.imul(ah4,bl3)|0,hi=hi+Math.imul(ah4,bh3)|0,lo=lo+Math.imul(al3,bl4)|0,mid=(mid=mid+Math.imul(al3,bh4)|0)+Math.imul(ah3,bl4)|0,hi=hi+Math.imul(ah3,bh4)|0,lo=lo+Math.imul(al2,bl5)|0,mid=(mid=mid+Math.imul(al2,bh5)|0)+Math.imul(ah2,bl5)|0,hi=hi+Math.imul(ah2,bh5)|0,lo=lo+Math.imul(al1,bl6)|0,mid=(mid=mid+Math.imul(al1,bh6)|0)+Math.imul(ah1,bl6)|0,hi=hi+Math.imul(ah1,bh6)|0;var w7=(c+(lo=lo+Math.imul(al0,bl7)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh7)|0)+Math.imul(ah0,bl7)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh7)|0)+(mid>>>13)|0)+(w7>>>26)|0,w7&=67108863,lo=Math.imul(al8,bl0),mid=(mid=Math.imul(al8,bh0))+Math.imul(ah8,bl0)|0,hi=Math.imul(ah8,bh0),lo=lo+Math.imul(al7,bl1)|0,mid=(mid=mid+Math.imul(al7,bh1)|0)+Math.imul(ah7,bl1)|0,hi=hi+Math.imul(ah7,bh1)|0,lo=lo+Math.imul(al6,bl2)|0,mid=(mid=mid+Math.imul(al6,bh2)|0)+Math.imul(ah6,bl2)|0,hi=hi+Math.imul(ah6,bh2)|0,lo=lo+Math.imul(al5,bl3)|0,mid=(mid=mid+Math.imul(al5,bh3)|0)+Math.imul(ah5,bl3)|0,hi=hi+Math.imul(ah5,bh3)|0,lo=lo+Math.imul(al4,bl4)|0,mid=(mid=mid+Math.imul(al4,bh4)|0)+Math.imul(ah4,bl4)|0,hi=hi+Math.imul(ah4,bh4)|0,lo=lo+Math.imul(al3,bl5)|0,mid=(mid=mid+Math.imul(al3,bh5)|0)+Math.imul(ah3,bl5)|0,hi=hi+Math.imul(ah3,bh5)|0,lo=lo+Math.imul(al2,bl6)|0,mid=(mid=mid+Math.imul(al2,bh6)|0)+Math.imul(ah2,bl6)|0,hi=hi+Math.imul(ah2,bh6)|0,lo=lo+Math.imul(al1,bl7)|0,mid=(mid=mid+Math.imul(al1,bh7)|0)+Math.imul(ah1,bl7)|0,hi=hi+Math.imul(ah1,bh7)|0;var w8=(c+(lo=lo+Math.imul(al0,bl8)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh8)|0)+Math.imul(ah0,bl8)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh8)|0)+(mid>>>13)|0)+(w8>>>26)|0,w8&=67108863,lo=Math.imul(al9,bl0),mid=(mid=Math.imul(al9,bh0))+Math.imul(ah9,bl0)|0,hi=Math.imul(ah9,bh0),lo=lo+Math.imul(al8,bl1)|0,mid=(mid=mid+Math.imul(al8,bh1)|0)+Math.imul(ah8,bl1)|0,hi=hi+Math.imul(ah8,bh1)|0,lo=lo+Math.imul(al7,bl2)|0,mid=(mid=mid+Math.imul(al7,bh2)|0)+Math.imul(ah7,bl2)|0,hi=hi+Math.imul(ah7,bh2)|0,lo=lo+Math.imul(al6,bl3)|0,mid=(mid=mid+Math.imul(al6,bh3)|0)+Math.imul(ah6,bl3)|0,hi=hi+Math.imul(ah6,bh3)|0,lo=lo+Math.imul(al5,bl4)|0,mid=(mid=mid+Math.imul(al5,bh4)|0)+Math.imul(ah5,bl4)|0,hi=hi+Math.imul(ah5,bh4)|0,lo=lo+Math.imul(al4,bl5)|0,mid=(mid=mid+Math.imul(al4,bh5)|0)+Math.imul(ah4,bl5)|0,hi=hi+Math.imul(ah4,bh5)|0,lo=lo+Math.imul(al3,bl6)|0,mid=(mid=mid+Math.imul(al3,bh6)|0)+Math.imul(ah3,bl6)|0,hi=hi+Math.imul(ah3,bh6)|0,lo=lo+Math.imul(al2,bl7)|0,mid=(mid=mid+Math.imul(al2,bh7)|0)+Math.imul(ah2,bl7)|0,hi=hi+Math.imul(ah2,bh7)|0,lo=lo+Math.imul(al1,bl8)|0,mid=(mid=mid+Math.imul(al1,bh8)|0)+Math.imul(ah1,bl8)|0,hi=hi+Math.imul(ah1,bh8)|0;var w9=(c+(lo=lo+Math.imul(al0,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh9)|0)+Math.imul(ah0,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh9)|0)+(mid>>>13)|0)+(w9>>>26)|0,w9&=67108863,lo=Math.imul(al9,bl1),mid=(mid=Math.imul(al9,bh1))+Math.imul(ah9,bl1)|0,hi=Math.imul(ah9,bh1),lo=lo+Math.imul(al8,bl2)|0,mid=(mid=mid+Math.imul(al8,bh2)|0)+Math.imul(ah8,bl2)|0,hi=hi+Math.imul(ah8,bh2)|0,lo=lo+Math.imul(al7,bl3)|0,mid=(mid=mid+Math.imul(al7,bh3)|0)+Math.imul(ah7,bl3)|0,hi=hi+Math.imul(ah7,bh3)|0,lo=lo+Math.imul(al6,bl4)|0,mid=(mid=mid+Math.imul(al6,bh4)|0)+Math.imul(ah6,bl4)|0,hi=hi+Math.imul(ah6,bh4)|0,lo=lo+Math.imul(al5,bl5)|0,mid=(mid=mid+Math.imul(al5,bh5)|0)+Math.imul(ah5,bl5)|0,hi=hi+Math.imul(ah5,bh5)|0,lo=lo+Math.imul(al4,bl6)|0,mid=(mid=mid+Math.imul(al4,bh6)|0)+Math.imul(ah4,bl6)|0,hi=hi+Math.imul(ah4,bh6)|0,lo=lo+Math.imul(al3,bl7)|0,mid=(mid=mid+Math.imul(al3,bh7)|0)+Math.imul(ah3,bl7)|0,hi=hi+Math.imul(ah3,bh7)|0,lo=lo+Math.imul(al2,bl8)|0,mid=(mid=mid+Math.imul(al2,bh8)|0)+Math.imul(ah2,bl8)|0,hi=hi+Math.imul(ah2,bh8)|0;var w10=(c+(lo=lo+Math.imul(al1,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al1,bh9)|0)+Math.imul(ah1,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah1,bh9)|0)+(mid>>>13)|0)+(w10>>>26)|0,w10&=67108863,lo=Math.imul(al9,bl2),mid=(mid=Math.imul(al9,bh2))+Math.imul(ah9,bl2)|0,hi=Math.imul(ah9,bh2),lo=lo+Math.imul(al8,bl3)|0,mid=(mid=mid+Math.imul(al8,bh3)|0)+Math.imul(ah8,bl3)|0,hi=hi+Math.imul(ah8,bh3)|0,lo=lo+Math.imul(al7,bl4)|0,mid=(mid=mid+Math.imul(al7,bh4)|0)+Math.imul(ah7,bl4)|0,hi=hi+Math.imul(ah7,bh4)|0,lo=lo+Math.imul(al6,bl5)|0,mid=(mid=mid+Math.imul(al6,bh5)|0)+Math.imul(ah6,bl5)|0,hi=hi+Math.imul(ah6,bh5)|0,lo=lo+Math.imul(al5,bl6)|0,mid=(mid=mid+Math.imul(al5,bh6)|0)+Math.imul(ah5,bl6)|0,hi=hi+Math.imul(ah5,bh6)|0,lo=lo+Math.imul(al4,bl7)|0,mid=(mid=mid+Math.imul(al4,bh7)|0)+Math.imul(ah4,bl7)|0,hi=hi+Math.imul(ah4,bh7)|0,lo=lo+Math.imul(al3,bl8)|0,mid=(mid=mid+Math.imul(al3,bh8)|0)+Math.imul(ah3,bl8)|0,hi=hi+Math.imul(ah3,bh8)|0;var w11=(c+(lo=lo+Math.imul(al2,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al2,bh9)|0)+Math.imul(ah2,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah2,bh9)|0)+(mid>>>13)|0)+(w11>>>26)|0,w11&=67108863,lo=Math.imul(al9,bl3),mid=(mid=Math.imul(al9,bh3))+Math.imul(ah9,bl3)|0,hi=Math.imul(ah9,bh3),lo=lo+Math.imul(al8,bl4)|0,mid=(mid=mid+Math.imul(al8,bh4)|0)+Math.imul(ah8,bl4)|0,hi=hi+Math.imul(ah8,bh4)|0,lo=lo+Math.imul(al7,bl5)|0,mid=(mid=mid+Math.imul(al7,bh5)|0)+Math.imul(ah7,bl5)|0,hi=hi+Math.imul(ah7,bh5)|0,lo=lo+Math.imul(al6,bl6)|0,mid=(mid=mid+Math.imul(al6,bh6)|0)+Math.imul(ah6,bl6)|0,hi=hi+Math.imul(ah6,bh6)|0,lo=lo+Math.imul(al5,bl7)|0,mid=(mid=mid+Math.imul(al5,bh7)|0)+Math.imul(ah5,bl7)|0,hi=hi+Math.imul(ah5,bh7)|0,lo=lo+Math.imul(al4,bl8)|0,mid=(mid=mid+Math.imul(al4,bh8)|0)+Math.imul(ah4,bl8)|0,hi=hi+Math.imul(ah4,bh8)|0;var w12=(c+(lo=lo+Math.imul(al3,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al3,bh9)|0)+Math.imul(ah3,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah3,bh9)|0)+(mid>>>13)|0)+(w12>>>26)|0,w12&=67108863,lo=Math.imul(al9,bl4),mid=(mid=Math.imul(al9,bh4))+Math.imul(ah9,bl4)|0,hi=Math.imul(ah9,bh4),lo=lo+Math.imul(al8,bl5)|0,mid=(mid=mid+Math.imul(al8,bh5)|0)+Math.imul(ah8,bl5)|0,hi=hi+Math.imul(ah8,bh5)|0,lo=lo+Math.imul(al7,bl6)|0,mid=(mid=mid+Math.imul(al7,bh6)|0)+Math.imul(ah7,bl6)|0,hi=hi+Math.imul(ah7,bh6)|0,lo=lo+Math.imul(al6,bl7)|0,mid=(mid=mid+Math.imul(al6,bh7)|0)+Math.imul(ah6,bl7)|0,hi=hi+Math.imul(ah6,bh7)|0,lo=lo+Math.imul(al5,bl8)|0,mid=(mid=mid+Math.imul(al5,bh8)|0)+Math.imul(ah5,bl8)|0,hi=hi+Math.imul(ah5,bh8)|0;var w13=(c+(lo=lo+Math.imul(al4,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al4,bh9)|0)+Math.imul(ah4,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah4,bh9)|0)+(mid>>>13)|0)+(w13>>>26)|0,w13&=67108863,lo=Math.imul(al9,bl5),mid=(mid=Math.imul(al9,bh5))+Math.imul(ah9,bl5)|0,hi=Math.imul(ah9,bh5),lo=lo+Math.imul(al8,bl6)|0,mid=(mid=mid+Math.imul(al8,bh6)|0)+Math.imul(ah8,bl6)|0,hi=hi+Math.imul(ah8,bh6)|0,lo=lo+Math.imul(al7,bl7)|0,mid=(mid=mid+Math.imul(al7,bh7)|0)+Math.imul(ah7,bl7)|0,hi=hi+Math.imul(ah7,bh7)|0,lo=lo+Math.imul(al6,bl8)|0,mid=(mid=mid+Math.imul(al6,bh8)|0)+Math.imul(ah6,bl8)|0,hi=hi+Math.imul(ah6,bh8)|0;var w14=(c+(lo=lo+Math.imul(al5,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al5,bh9)|0)+Math.imul(ah5,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah5,bh9)|0)+(mid>>>13)|0)+(w14>>>26)|0,w14&=67108863,lo=Math.imul(al9,bl6),mid=(mid=Math.imul(al9,bh6))+Math.imul(ah9,bl6)|0,hi=Math.imul(ah9,bh6),lo=lo+Math.imul(al8,bl7)|0,mid=(mid=mid+Math.imul(al8,bh7)|0)+Math.imul(ah8,bl7)|0,hi=hi+Math.imul(ah8,bh7)|0,lo=lo+Math.imul(al7,bl8)|0,mid=(mid=mid+Math.imul(al7,bh8)|0)+Math.imul(ah7,bl8)|0,hi=hi+Math.imul(ah7,bh8)|0;var w15=(c+(lo=lo+Math.imul(al6,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al6,bh9)|0)+Math.imul(ah6,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah6,bh9)|0)+(mid>>>13)|0)+(w15>>>26)|0,w15&=67108863,lo=Math.imul(al9,bl7),mid=(mid=Math.imul(al9,bh7))+Math.imul(ah9,bl7)|0,hi=Math.imul(ah9,bh7),lo=lo+Math.imul(al8,bl8)|0,mid=(mid=mid+Math.imul(al8,bh8)|0)+Math.imul(ah8,bl8)|0,hi=hi+Math.imul(ah8,bh8)|0;var w16=(c+(lo=lo+Math.imul(al7,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al7,bh9)|0)+Math.imul(ah7,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah7,bh9)|0)+(mid>>>13)|0)+(w16>>>26)|0,w16&=67108863,lo=Math.imul(al9,bl8),mid=(mid=Math.imul(al9,bh8))+Math.imul(ah9,bl8)|0,hi=Math.imul(ah9,bh8);var w17=(c+(lo=lo+Math.imul(al8,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al8,bh9)|0)+Math.imul(ah8,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah8,bh9)|0)+(mid>>>13)|0)+(w17>>>26)|0,w17&=67108863;var w18=(c+(lo=Math.imul(al9,bl9))|0)+((8191&(mid=(mid=Math.imul(al9,bh9))+Math.imul(ah9,bl9)|0))<<13)|0;return c=((hi=Math.imul(ah9,bh9))+(mid>>>13)|0)+(w18>>>26)|0,w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,0!==c&&(o[19]=c,out.length++),out};function jumboMulTo(self,num,out){return(new FFTM).mulp(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}Math.imul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function mulTo(num,out){var res,len=this.length+num.length;return res=10===this.length&&10===num.length?comb10MulTo(this,num,out):len<63?smallMulTo(this,num,out):len<1024?function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0;k>>26)|0)>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0!==carry?out.words[k]=carry:out.length--,out.strip()}(this,num,out):jumboMulTo(this,num,out),res},FFTM.prototype.makeRBT=function makeRBT(N){for(var t=new Array(N),l=BN.prototype._countBits(N)-1,i=0;i>=1;return rb},FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>=1)i++;return 1<>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;i>=26,carry+=w/67108864|0,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.muln=function muln(num){return this.clone().imuln(num)},BN.prototype.sqr=function sqr(){return this.mul(this)},BN.prototype.isqr=function isqr(){return this.imul(this.clone())},BN.prototype.pow=function pow(num){var w=function toBitArray(num){for(var w=new Array(num.bitLength()),bit=0;bit>>wbit}return w}(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i=0);var i,r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r;if(0!==r){var carry=0;for(i=0;i>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;i>=0;i--)this.words[i+s]=this.words[i];for(i=0;i=0),h=hint?(hint-hint%26)/26:0;var r=bits%26,s=Math.min((bits-r)/26,this.length),mask=67108863^67108863>>>r<s)for(this.length-=s,i=0;i=0&&(0!==carry||i>=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&0!==carry&&(maskedWords.words[maskedWords.length++]=carry),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},BN.prototype.ishrn=function ishrn(bits,hint,extended){return assert(0===this.negative),this.iushrn(bits,hint,extended)},BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function testn(bit){assert("number"==typeof bit&&bit>=0);var r=bit%26,s=(bit-r)/26,q=1<=0);var r=bits%26,s=(bits-r)/26;if(assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!==r&&s++,this.length=Math.min(s,this.length),0!==r){var mask=67108863^67108863>>>r<=67108864;i++)this.words[i]-=67108864,i===this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=Math.max(this.length,i+1),this},BN.prototype.isubn=function isubn(num){if(assert("number"==typeof num),assert(num<67108864),num<0)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i>26)-(right/67108864|0),this.words[i+shift]=67108863&w}for(;i>26,this.words[i+shift]=67108863&w;if(0===carry)return this.strip();for(assert(-1===carry),carry=0,i=0;i>26,this.words[i]=67108863&w;return this.negative=1,this.strip()},BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=(this.length,num.length),a=this.clone(),b=num,bhi=0|b.words[b.length-1];0!==(shift=26-this._countBits(bhi))&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var q,m=a.length-b.length;if("mod"!==mode){(q=new BN(null)).length=m+1,q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=67108864*(0|a.words[b.length+j])+(0|a.words[b.length+j-1]);for(qj=Math.min(qj/bhi|0,67108863),a._ishlnsubmul(b,qj,j);0!==a.negative;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q.strip(),a.strip(),"div"!==mode&&0!==shift&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function divmod(num,mode,positive){return assert(!num.isZero()),this.isZero()?{div:new BN(0),mod:new BN(0)}:0!==this.negative&&0===num.negative?(res=this.neg().divmod(num,mode),"mod"!==mode&&(div=res.div.neg()),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.iadd(num)),{div,mod}):0===this.negative&&0!==num.negative?(res=this.divmod(num.neg(),mode),"mod"!==mode&&(div=res.div.neg()),{div,mod:res.mod}):0!=(this.negative&num.negative)?(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod}):num.length>this.length||this.cmp(num)<0?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modn(num.words[0]))}:this._wordDiv(num,mode);var div,mod,res},BN.prototype.div=function div(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function mod(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function umod(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0!==dm.div.negative?dm.mod.isub(num):dm.mod,half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return cmp<0||1===r2&&0===cmp?dm.div:0!==dm.div.negative?dm.div.isubn(1):dm.div.iaddn(1)},BN.prototype.modn=function modn(num){assert(num<=67108863);for(var p=(1<<26)%num,acc=0,i=this.length-1;i>=0;i--)acc=(p*acc+(0|this.words[i]))%num;return acc},BN.prototype.idivn=function idivn(num){assert(num<=67108863);for(var carry=0,i=this.length-1;i>=0;i--){var w=(0|this.words[i])+67108864*carry;this.words[i]=w/num|0,carry=w%num}return this.strip()},BN.prototype.divn=function divn(num){return this.clone().idivn(num)},BN.prototype.egcd=function egcd(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0!==x.negative?x.umod(p):x.clone();for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0==(x.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(x.iushrn(i);i-- >0;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;0==(y.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(y.iushrn(j);j-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);x.cmp(y)>=0?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function _invmp(p){assert(0===p.negative),assert(!p.isZero());var a=this,b=p.clone();a=0!==a.negative?a.umod(p):a.clone();for(var res,x1=new BN(1),x2=new BN(0),delta=b.clone();a.cmpn(1)>0&&b.cmpn(1)>0;){for(var i=0,im=1;0==(a.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(a.iushrn(i);i-- >0;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;0==(b.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(b.iushrn(j);j-- >0;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);a.cmp(b)>=0?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}return(res=0===a.cmpn(1)?x1:x2).cmpn(0)<0&&res.iadd(p),res},BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);for(;;){for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(r<0){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}return b.iushln(shift)},BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function isEven(){return 0==(1&this.words[0])},BN.prototype.isOdd=function isOdd(){return 1==(1&this.words[0])},BN.prototype.andln=function andln(num){return this.words[0]&num},BN.prototype.bincn=function bincn(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<>>26,w&=67108863,this.words[i]=w}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function isZero(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function cmpn(num){var res,negative=num<0;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;if(this.strip(),this.length>1)res=1;else{negative&&(num=-num),assert(num<=67108863,"Number is too big");var w=0|this.words[0];res=w===num?0:wnum.length)return 1;if(this.length=0;i--){var a=0|this.words[i],b=0|num.words[i];if(a!==b){ab&&(res=1);break}}return res},BN.prototype.gtn=function gtn(num){return 1===this.cmpn(num)},BN.prototype.gt=function gt(num){return 1===this.cmp(num)},BN.prototype.gten=function gten(num){return this.cmpn(num)>=0},BN.prototype.gte=function gte(num){return this.cmp(num)>=0},BN.prototype.ltn=function ltn(num){return-1===this.cmpn(num)},BN.prototype.lt=function lt(num){return-1===this.cmp(num)},BN.prototype.lten=function lten(num){return this.cmpn(num)<=0},BN.prototype.lte=function lte(num){return this.cmp(num)<=0},BN.prototype.eqn=function eqn(num){return 0===this.cmpn(num)},BN.prototype.eq=function eq(num){return 0===this.cmp(num)},BN.red=function red(num){return new Red(num)},BN.prototype.toRed=function toRed(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function fromRed(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function _forceRed(ctx){return this.red=ctx,this},BN.prototype.forceRed=function forceRed(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function redAdd(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function redIAdd(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function redSub(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function redISub(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function redShl(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function redMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function redIMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function redSqr(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function redISqr(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function redSqrt(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function redInvm(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function redNeg(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function redPow(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);return tmp.words=new Array(Math.ceil(this.n/13)),tmp},MPrime.prototype.ireduce=function ireduce(num){var rlen,r=num;do{this.split(r,this.tmp),rlen=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(rlen>this.n);var cmp=rlen0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)},inherits(K256,MPrime),K256.prototype.split=function split(input,output){for(var outLen=Math.min(input.length,9),i=0;i>>22,prev=next}prev>>>=22,input.words[i-10]=prev,0===prev&&input.length>10?input.length-=10:input.length-=9},K256.prototype.imulK=function imulK(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0;i>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else{if("p25519"!==name)throw new Error("Unknown prime "+name);prime=new P25519}return primes[name]=prime,prime},Red.prototype._verify1=function _verify1(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function _verify2(a,b){assert(0==(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function imod(a){return this.prime?this.prime.ireduce(a)._forceRed(this):a.umod(this.m)._forceRed(this)},Red.prototype.neg=function neg(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);return res.cmp(this.m)>=0&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);return res.cmp(this.m)>=0&&res.isub(this.m),res},Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);return res.cmpn(0)<0&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);return res.cmpn(0)<0&&res.iadd(this.m),res},Red.prototype.shl=function shl(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function imul(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function mul(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())},Red.prototype.sqr=function sqr(a){return this.mul(a,a)},Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(mod3%2==1),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i=0;i--){for(var word=num.words[i],j=start-1;j>=0;j--){var bit=word>>j&1;res!==wnd[0]&&(res=this.sqr(res)),0!==bit||0!==current?(current<<=1,current|=bit,(4===++currentLen||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)):currentLen=0}start=26}return res},Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();return res.red=null,res},BN.mont=function mont(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function invm(a){return this.imod(a._invmp(this.m).mul(this.r2))._forceRed(this)}}(module=__webpack_require__.nmd(module),this)},9746:module=>{function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}module.exports=assert,assert.equal=function assertEqual(l,r,msg){if(l!=r)throw new Error(msg||"Assertion failed: "+l+" != "+r)}},4504:(__unused_webpack_module,exports)=>{"use strict";var utils=exports;function zero2(word){return 1===word.length?"0"+word:word}function toHex(msg){for(var res="",i=0;i>8,lo=255&c;hi?res.push(hi,lo):res.push(lo)}return res},utils.zero2=zero2,utils.toHex=toHex,utils.encode=function encode(arr,enc){return"hex"===enc?toHex(arr):arr}},4244:module=>{"use strict";var numberIsNaN=function(value){return value!=value};module.exports=function is(a,b){return 0===a&&0===b?1/a==1/b:a===b||!(!numberIsNaN(a)||!numberIsNaN(b))}},609:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var define=__webpack_require__(4289),callBind=__webpack_require__(5559),implementation=__webpack_require__(4244),getPolyfill=__webpack_require__(5624),shim=__webpack_require__(2281),polyfill=callBind(getPolyfill(),Object);define(polyfill,{getPolyfill,implementation,shim}),module.exports=polyfill},5624:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var implementation=__webpack_require__(4244);module.exports=function getPolyfill(){return"function"==typeof Object.is?Object.is:implementation}},2281:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var getPolyfill=__webpack_require__(5624),define=__webpack_require__(4289);module.exports=function shimObjectIs(){var polyfill=getPolyfill();return define(Object,{is:polyfill},{is:function testObjectIs(){return Object.is!==polyfill}}),polyfill}},8987:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var keysShim;if(!Object.keys){var has=Object.prototype.hasOwnProperty,toStr=Object.prototype.toString,isArgs=__webpack_require__(1414),isEnumerable=Object.prototype.propertyIsEnumerable,hasDontEnumBug=!isEnumerable.call({toString:null},"toString"),hasProtoEnumBug=isEnumerable.call((function(){}),"prototype"),dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],equalsConstructorPrototype=function(o){var ctor=o.constructor;return ctor&&ctor.prototype===o},excludedKeys={$applicationCache:!0,$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$onmozfullscreenchange:!0,$onmozfullscreenerror:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},hasAutomationEqualityBug=function(){if("undefined"==typeof window)return!1;for(var k in window)try{if(!excludedKeys["$"+k]&&has.call(window,k)&&null!==window[k]&&"object"==typeof window[k])try{equalsConstructorPrototype(window[k])}catch(e){return!0}}catch(e){return!0}return!1}();keysShim=function keys(object){var isObject=null!==object&&"object"==typeof object,isFunction="[object Function]"===toStr.call(object),isArguments=isArgs(object),isString=isObject&&"[object String]"===toStr.call(object),theKeys=[];if(!isObject&&!isFunction&&!isArguments)throw new TypeError("Object.keys called on a non-object");var skipProto=hasProtoEnumBug&&isFunction;if(isString&&object.length>0&&!has.call(object,0))for(var i=0;i0)for(var j=0;j{"use strict";var slice=Array.prototype.slice,isArgs=__webpack_require__(1414),origKeys=Object.keys,keysShim=origKeys?function keys(o){return origKeys(o)}:__webpack_require__(8987),originalKeys=Object.keys;keysShim.shim=function shimObjectKeys(){if(Object.keys){var keysWorksWithArguments=function(){var args=Object.keys(arguments);return args&&args.length===arguments.length}(1,2);keysWorksWithArguments||(Object.keys=function keys(object){return isArgs(object)?originalKeys(slice.call(object)):originalKeys(object)})}else Object.keys=keysShim;return Object.keys||keysShim},module.exports=keysShim},1414:module=>{"use strict";var toStr=Object.prototype.toString;module.exports=function isArguments(value){var str=toStr.call(value),isArgs="[object Arguments]"===str;return isArgs||(isArgs="[object Array]"!==str&&null!==value&&"object"==typeof value&&"number"==typeof value.length&&value.length>=0&&"[object Function]"===toStr.call(value.callee)),isArgs}},2818:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";var asn1=__webpack_require__(9809);exports.certificate=__webpack_require__(1934);var RSAPrivateKey=asn1.define("RSAPrivateKey",(function(){this.seq().obj(this.key("version").int(),this.key("modulus").int(),this.key("publicExponent").int(),this.key("privateExponent").int(),this.key("prime1").int(),this.key("prime2").int(),this.key("exponent1").int(),this.key("exponent2").int(),this.key("coefficient").int())}));exports.RSAPrivateKey=RSAPrivateKey;var RSAPublicKey=asn1.define("RSAPublicKey",(function(){this.seq().obj(this.key("modulus").int(),this.key("publicExponent").int())}));exports.RSAPublicKey=RSAPublicKey;var PublicKey=asn1.define("SubjectPublicKeyInfo",(function(){this.seq().obj(this.key("algorithm").use(AlgorithmIdentifier),this.key("subjectPublicKey").bitstr())}));exports.PublicKey=PublicKey;var AlgorithmIdentifier=asn1.define("AlgorithmIdentifier",(function(){this.seq().obj(this.key("algorithm").objid(),this.key("none").null_().optional(),this.key("curve").objid().optional(),this.key("params").seq().obj(this.key("p").int(),this.key("q").int(),this.key("g").int()).optional())})),PrivateKeyInfo=asn1.define("PrivateKeyInfo",(function(){this.seq().obj(this.key("version").int(),this.key("algorithm").use(AlgorithmIdentifier),this.key("subjectPrivateKey").octstr())}));exports.PrivateKey=PrivateKeyInfo;var EncryptedPrivateKeyInfo=asn1.define("EncryptedPrivateKeyInfo",(function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("id").objid(),this.key("decrypt").seq().obj(this.key("kde").seq().obj(this.key("id").objid(),this.key("kdeparams").seq().obj(this.key("salt").octstr(),this.key("iters").int())),this.key("cipher").seq().obj(this.key("algo").objid(),this.key("iv").octstr()))),this.key("subjectPrivateKey").octstr())}));exports.EncryptedPrivateKey=EncryptedPrivateKeyInfo;var DSAPrivateKey=asn1.define("DSAPrivateKey",(function(){this.seq().obj(this.key("version").int(),this.key("p").int(),this.key("q").int(),this.key("g").int(),this.key("pub_key").int(),this.key("priv_key").int())}));exports.DSAPrivateKey=DSAPrivateKey,exports.DSAparam=asn1.define("DSAparam",(function(){this.int()}));var ECPrivateKey=asn1.define("ECPrivateKey",(function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").optional().explicit(0).use(ECParameters),this.key("publicKey").optional().explicit(1).bitstr())}));exports.ECPrivateKey=ECPrivateKey;var ECParameters=asn1.define("ECParameters",(function(){this.choice({namedCurve:this.objid()})}));exports.signature=asn1.define("signature",(function(){this.seq().obj(this.key("r").int(),this.key("s").int())}))},1934:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var asn=__webpack_require__(9809),Time=asn.define("Time",(function(){this.choice({utcTime:this.utctime(),generalTime:this.gentime()})})),AttributeTypeValue=asn.define("AttributeTypeValue",(function(){this.seq().obj(this.key("type").objid(),this.key("value").any())})),AlgorithmIdentifier=asn.define("AlgorithmIdentifier",(function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional(),this.key("curve").objid().optional())})),SubjectPublicKeyInfo=asn.define("SubjectPublicKeyInfo",(function(){this.seq().obj(this.key("algorithm").use(AlgorithmIdentifier),this.key("subjectPublicKey").bitstr())})),RelativeDistinguishedName=asn.define("RelativeDistinguishedName",(function(){this.setof(AttributeTypeValue)})),RDNSequence=asn.define("RDNSequence",(function(){this.seqof(RelativeDistinguishedName)})),Name=asn.define("Name",(function(){this.choice({rdnSequence:this.use(RDNSequence)})})),Validity=asn.define("Validity",(function(){this.seq().obj(this.key("notBefore").use(Time),this.key("notAfter").use(Time))})),Extension=asn.define("Extension",(function(){this.seq().obj(this.key("extnID").objid(),this.key("critical").bool().def(!1),this.key("extnValue").octstr())})),TBSCertificate=asn.define("TBSCertificate",(function(){this.seq().obj(this.key("version").explicit(0).int().optional(),this.key("serialNumber").int(),this.key("signature").use(AlgorithmIdentifier),this.key("issuer").use(Name),this.key("validity").use(Validity),this.key("subject").use(Name),this.key("subjectPublicKeyInfo").use(SubjectPublicKeyInfo),this.key("issuerUniqueID").implicit(1).bitstr().optional(),this.key("subjectUniqueID").implicit(2).bitstr().optional(),this.key("extensions").explicit(3).seqof(Extension).optional())})),X509Certificate=asn.define("X509Certificate",(function(){this.seq().obj(this.key("tbsCertificate").use(TBSCertificate),this.key("signatureAlgorithm").use(AlgorithmIdentifier),this.key("signatureValue").bitstr())}));module.exports=X509Certificate},7631:(module,__unused_webpack_exports,__webpack_require__)=>{var findProc=/Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m,startRegex=/^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m,fullRegex=/^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m,evp=__webpack_require__(3048),ciphers=__webpack_require__(4696),Buffer=__webpack_require__(9509).Buffer;module.exports=function(okey,password){var decrypted,key=okey.toString(),match=key.match(findProc);if(match){var suite="aes"+match[1],iv=Buffer.from(match[2],"hex"),cipherText=Buffer.from(match[3].replace(/[\r\n]/g,""),"base64"),cipherKey=evp(password,iv.slice(0,8),parseInt(match[1],10)).key,out=[],cipher=ciphers.createDecipheriv(suite,cipherKey,iv);out.push(cipher.update(cipherText)),out.push(cipher.final()),decrypted=Buffer.concat(out)}else{var match2=key.match(fullRegex);decrypted=Buffer.from(match2[2].replace(/[\r\n]/g,""),"base64")}return{tag:key.match(startRegex)[1],data:decrypted}}},980:(module,__unused_webpack_exports,__webpack_require__)=>{var asn1=__webpack_require__(2818),aesid=__webpack_require__(2562),fixProc=__webpack_require__(7631),ciphers=__webpack_require__(4696),compat=__webpack_require__(5632),Buffer=__webpack_require__(9509).Buffer;function parseKeys(buffer){var password;"object"!=typeof buffer||Buffer.isBuffer(buffer)||(password=buffer.passphrase,buffer=buffer.key),"string"==typeof buffer&&(buffer=Buffer.from(buffer));var subtype,ndata,stripped=fixProc(buffer,password),type=stripped.tag,data=stripped.data;switch(type){case"CERTIFICATE":ndata=asn1.certificate.decode(data,"der").tbsCertificate.subjectPublicKeyInfo;case"PUBLIC KEY":switch(ndata||(ndata=asn1.PublicKey.decode(data,"der")),subtype=ndata.algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data,"der");case"1.2.840.10045.2.1":return ndata.subjectPrivateKey=ndata.subjectPublicKey,{type:"ec",data:ndata};case"1.2.840.10040.4.1":return ndata.algorithm.params.pub_key=asn1.DSAparam.decode(ndata.subjectPublicKey.data,"der"),{type:"dsa",data:ndata.algorithm.params};default:throw new Error("unknown key id "+subtype)}case"ENCRYPTED PRIVATE KEY":data=function decrypt(data,password){var salt=data.algorithm.decrypt.kde.kdeparams.salt,iters=parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(),10),algo=aesid[data.algorithm.decrypt.cipher.algo.join(".")],iv=data.algorithm.decrypt.cipher.iv,cipherText=data.subjectPrivateKey,keylen=parseInt(algo.split("-")[1],10)/8,key=compat.pbkdf2Sync(password,salt,iters,keylen,"sha1"),cipher=ciphers.createDecipheriv(algo,key,iv),out=[];return out.push(cipher.update(cipherText)),out.push(cipher.final()),Buffer.concat(out)}(data=asn1.EncryptedPrivateKey.decode(data,"der"),password);case"PRIVATE KEY":switch(subtype=(ndata=asn1.PrivateKey.decode(data,"der")).algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey,"der");case"1.2.840.10045.2.1":return{curve:ndata.algorithm.curve,privateKey:asn1.ECPrivateKey.decode(ndata.subjectPrivateKey,"der").privateKey};case"1.2.840.10040.4.1":return ndata.algorithm.params.priv_key=asn1.DSAparam.decode(ndata.subjectPrivateKey,"der"),{type:"dsa",params:ndata.algorithm.params};default:throw new Error("unknown key id "+subtype)}case"RSA PUBLIC KEY":return asn1.RSAPublicKey.decode(data,"der");case"RSA PRIVATE KEY":return asn1.RSAPrivateKey.decode(data,"der");case"DSA PRIVATE KEY":return{type:"dsa",params:asn1.DSAPrivateKey.decode(data,"der")};case"EC PRIVATE KEY":return{curve:(data=asn1.ECPrivateKey.decode(data,"der")).parameters.value,privateKey:data.privateKey};default:throw new Error("unknown key type "+type)}}module.exports=parseKeys,parseKeys.signature=asn1.signature},5632:(__unused_webpack_module,exports,__webpack_require__)=>{exports.pbkdf2=__webpack_require__(8638),exports.pbkdf2Sync=__webpack_require__(1257)},8638:(module,__unused_webpack_exports,__webpack_require__)=>{var ZERO_BUF,nextTick,Buffer=__webpack_require__(9509).Buffer,checkParameters=__webpack_require__(7357),defaultEncoding=__webpack_require__(2368),sync=__webpack_require__(1257),toBuffer=__webpack_require__(7777),subtle=__webpack_require__.g.crypto&&__webpack_require__.g.crypto.subtle,toBrowser={sha:"SHA-1","sha-1":"SHA-1",sha1:"SHA-1",sha256:"SHA-256","sha-256":"SHA-256",sha384:"SHA-384","sha-384":"SHA-384","sha-512":"SHA-512",sha512:"SHA-512"},checks=[];function getNextTick(){return nextTick||(nextTick=__webpack_require__.g.process&&__webpack_require__.g.process.nextTick?__webpack_require__.g.process.nextTick:__webpack_require__.g.queueMicrotask?__webpack_require__.g.queueMicrotask:__webpack_require__.g.setImmediate?__webpack_require__.g.setImmediate:__webpack_require__.g.setTimeout)}function browserPbkdf2(password,salt,iterations,length,algo){return subtle.importKey("raw",password,{name:"PBKDF2"},!1,["deriveBits"]).then((function(key){return subtle.deriveBits({name:"PBKDF2",salt,iterations,hash:{name:algo}},key,length<<3)})).then((function(res){return Buffer.from(res)}))}module.exports=function(password,salt,iterations,keylen,digest,callback){"function"==typeof digest&&(callback=digest,digest=void 0);var algo=toBrowser[(digest=digest||"sha1").toLowerCase()];if(algo&&"function"==typeof __webpack_require__.g.Promise){if(checkParameters(iterations,keylen),password=toBuffer(password,defaultEncoding,"Password"),salt=toBuffer(salt,defaultEncoding,"Salt"),"function"!=typeof callback)throw new Error("No callback provided to pbkdf2");!function resolvePromise(promise,callback){promise.then((function(out){getNextTick()((function(){callback(null,out)}))}),(function(e){getNextTick()((function(){callback(e)}))}))}(function checkNative(algo){if(__webpack_require__.g.process&&!__webpack_require__.g.process.browser)return Promise.resolve(!1);if(!subtle||!subtle.importKey||!subtle.deriveBits)return Promise.resolve(!1);if(void 0!==checks[algo])return checks[algo];var prom=browserPbkdf2(ZERO_BUF=ZERO_BUF||Buffer.alloc(8),ZERO_BUF,10,128,algo).then((function(){return!0})).catch((function(){return!1}));return checks[algo]=prom,prom}(algo).then((function(resp){return resp?browserPbkdf2(password,salt,iterations,keylen,algo):sync(password,salt,iterations,keylen,digest)})),callback)}else getNextTick()((function(){var out;try{out=sync(password,salt,iterations,keylen,digest)}catch(e){return callback(e)}callback(null,out)}))}},2368:(module,__unused_webpack_exports,__webpack_require__)=>{var defaultEncoding;if(__webpack_require__.g.process&&__webpack_require__.g.process.browser)defaultEncoding="utf-8";else if(__webpack_require__.g.process&&__webpack_require__.g.process.version){defaultEncoding=parseInt(process.version.split(".")[0].slice(1),10)>=6?"utf-8":"binary"}else defaultEncoding="utf-8";module.exports=defaultEncoding},7357:module=>{var MAX_ALLOC=Math.pow(2,30)-1;module.exports=function(iterations,keylen){if("number"!=typeof iterations)throw new TypeError("Iterations not a number");if(iterations<0)throw new TypeError("Bad iterations");if("number"!=typeof keylen)throw new TypeError("Key length not a number");if(keylen<0||keylen>MAX_ALLOC||keylen!=keylen)throw new TypeError("Bad key length")}},1257:(module,__unused_webpack_exports,__webpack_require__)=>{var md5=__webpack_require__(8028),RIPEMD160=__webpack_require__(9785),sha=__webpack_require__(9072),Buffer=__webpack_require__(9509).Buffer,checkParameters=__webpack_require__(7357),defaultEncoding=__webpack_require__(2368),toBuffer=__webpack_require__(7777),ZEROS=Buffer.alloc(128),sizes={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,rmd160:20,ripemd160:20};function Hmac(alg,key,saltLen){var hash=function getDigest(alg){function shaFunc(data){return sha(alg).update(data).digest()}function rmd160Func(data){return(new RIPEMD160).update(data).digest()}return"rmd160"===alg||"ripemd160"===alg?rmd160Func:"md5"===alg?md5:shaFunc}(alg),blocksize="sha512"===alg||"sha384"===alg?128:64;key.length>blocksize?key=hash(key):key.length{var Buffer=__webpack_require__(9509).Buffer;module.exports=function(thing,encoding,name){if(Buffer.isBuffer(thing))return thing;if("string"==typeof thing)return Buffer.from(thing,encoding);if(ArrayBuffer.isView(thing))return Buffer.from(thing.buffer);throw new TypeError(name+" must be a string, a Buffer, a typed array or a DataView")}},7900:(__unused_webpack_module,exports,__webpack_require__)=>{exports.publicEncrypt=__webpack_require__(6559),exports.privateDecrypt=__webpack_require__(6138),exports.privateEncrypt=function privateEncrypt(key,buf){return exports.publicEncrypt(key,buf,!0)},exports.publicDecrypt=function publicDecrypt(key,buf){return exports.privateDecrypt(key,buf,!0)}},9199:(module,__unused_webpack_exports,__webpack_require__)=>{var createHash=__webpack_require__(3482),Buffer=__webpack_require__(9509).Buffer;function i2ops(c){var out=Buffer.allocUnsafe(4);return out.writeUInt32BE(c,0),out}module.exports=function(seed,len){for(var c,t=Buffer.alloc(0),i=0;t.length=65&&c<=70?c-55:c>=97&&c<=102?c-87:c-48&15}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return index-1>=lowerBound&&(r|=parseHex4Bits(string,index-1)<<4),r}function parseBase(str,start,end,mul){for(var r=0,len=Math.min(str.length,end),i=start;i=49?c-49+10:c>=17?c-17+10:c}return r}BN.isBN=function isBN(num){return num instanceof BN||null!==num&&"object"==typeof num&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words)},BN.max=function max(left,right){return left.cmp(right)>0?left:right},BN.min=function min(left,right){return left.cmp(right)<0?left:right},BN.prototype._init=function init(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&base>=2&&base<=36);var start=0;"-"===(number=number.toString().replace(/\s+/g,""))[0]&&(start++,this.negative=1),start=0;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=w<>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i>>26-off&67108863,(off+=24)>=26&&(off-=26,j++);return this.strip()},BN.prototype._parseHex=function _parseHex(number,start,endian){this.length=Math.ceil((number.length-start)/6),this.words=new Array(this.length);for(var i=0;i=start;i-=2)w=parseHexByte(number,start,i)<=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;else for(i=(number.length-start)%2==0?start+1:start;i=18?(off-=18,j+=1,this.words[j]|=w>>>26):off+=8;this.strip()},BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;limbPow*=base)limbLen++;limbLen--,limbPow=limbPow/base|0;for(var total=number.length-start,mod=total%limbLen,end=Math.min(total,total-mod)+start,word=0,i=start;i1&&0===this.words[this.length-1];)this.length--;return this._normSign()},BN.prototype._normSign=function _normSign(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},BN.prototype.inspect=function inspect(){return(this.red?""};var zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function smallMulTo(self,num,out){out.negative=num.negative^self.negative;var len=self.length+num.length|0;out.length=len,len=len-1|0;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=r/67108864|0;out.words[0]=lo;for(var k=1;k>>26,rword=67108863&carry,maxJ=Math.min(k,num.length-1),j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j|0;ncarry+=(r=(a=0|self.words[i])*(b=0|num.words[j])+rword)/67108864|0,rword=67108863&r}out.words[k]=0|rword,carry=0|ncarry}return 0!==carry?out.words[k]=0|carry:out.length--,out.strip()}BN.prototype.toString=function toString(base,padding){var out;if(padding=0|padding||1,16===(base=base||10)||"hex"===base){out="";for(var off=0,carry=0,i=0;i>>24-off&16777215)||i!==this.length-1?zeros[6-word.length]+word+out:word+out,(off+=2)>=26&&(off-=26,i--)}for(0!==carry&&(out=carry.toString(16)+out);out.length%padding!=0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&base>=2&&base<=36){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modn(groupBase).toString(base);out=(c=c.idivn(groupBase)).isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);out.length%padding!=0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function toNumber(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:this.length>2&&assert(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-ret:ret},BN.prototype.toJSON=function toJSON(){return this.toString(16)},BN.prototype.toBuffer=function toBuffer(endian,length){return assert(void 0!==Buffer),this.toArrayLike(Buffer,endian,length)},BN.prototype.toArray=function toArray(endian,length){return this.toArrayLike(Array,endian,length)},BN.prototype.toArrayLike=function toArrayLike(ArrayType,endian,length){var byteLength=this.byteLength(),reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length"),assert(reqLength>0,"Requested array length <= 0"),this.strip();var b,i,littleEndian="le"===endian,res=new ArrayType(reqLength),q=this.clone();if(littleEndian){for(i=0;!q.isZero();i++)b=q.andln(255),q.iushrn(8),res[i]=b;for(;i=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function _zeroBits(w){if(0===w)return 26;var t=w,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},BN.prototype.bitLength=function bitLength(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;for(var r=0,i=0;inum.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function uor(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function iuand(num){var b;b=this.length>num.length?num:this;for(var i=0;inum.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function uand(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function iuxor(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;inum.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function uxor(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function inotn(width){assert("number"==typeof width&&width>=0);var bytesNeeded=0|Math.ceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),bitsLeft>0&&bytesNeeded--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this.strip()},BN.prototype.notn=function notn(width){return this.clone().inotn(width)},BN.prototype.setn=function setn(bit,val){assert("number"==typeof bit&&bit>=0);var off=bit/26|0,wbit=bit%26;return this._expand(off+1),this.words[off]=val?this.words[off]|1<num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>>26;for(;0!==carry&&i>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;inum.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function isub(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var a,b,cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;cmp>0?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>26,this.words[i]=67108863&r;for(;0!==carry&&i>26,this.words[i]=67108863&r;if(0===carry&&i>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13;out.negative=self.negative^num.negative,out.length=19;var w0=(c+(lo=Math.imul(al0,bl0))|0)+((8191&(mid=(mid=Math.imul(al0,bh0))+Math.imul(ah0,bl0)|0))<<13)|0;c=((hi=Math.imul(ah0,bh0))+(mid>>>13)|0)+(w0>>>26)|0,w0&=67108863,lo=Math.imul(al1,bl0),mid=(mid=Math.imul(al1,bh0))+Math.imul(ah1,bl0)|0,hi=Math.imul(ah1,bh0);var w1=(c+(lo=lo+Math.imul(al0,bl1)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh1)|0)+Math.imul(ah0,bl1)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh1)|0)+(mid>>>13)|0)+(w1>>>26)|0,w1&=67108863,lo=Math.imul(al2,bl0),mid=(mid=Math.imul(al2,bh0))+Math.imul(ah2,bl0)|0,hi=Math.imul(ah2,bh0),lo=lo+Math.imul(al1,bl1)|0,mid=(mid=mid+Math.imul(al1,bh1)|0)+Math.imul(ah1,bl1)|0,hi=hi+Math.imul(ah1,bh1)|0;var w2=(c+(lo=lo+Math.imul(al0,bl2)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh2)|0)+Math.imul(ah0,bl2)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh2)|0)+(mid>>>13)|0)+(w2>>>26)|0,w2&=67108863,lo=Math.imul(al3,bl0),mid=(mid=Math.imul(al3,bh0))+Math.imul(ah3,bl0)|0,hi=Math.imul(ah3,bh0),lo=lo+Math.imul(al2,bl1)|0,mid=(mid=mid+Math.imul(al2,bh1)|0)+Math.imul(ah2,bl1)|0,hi=hi+Math.imul(ah2,bh1)|0,lo=lo+Math.imul(al1,bl2)|0,mid=(mid=mid+Math.imul(al1,bh2)|0)+Math.imul(ah1,bl2)|0,hi=hi+Math.imul(ah1,bh2)|0;var w3=(c+(lo=lo+Math.imul(al0,bl3)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh3)|0)+Math.imul(ah0,bl3)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh3)|0)+(mid>>>13)|0)+(w3>>>26)|0,w3&=67108863,lo=Math.imul(al4,bl0),mid=(mid=Math.imul(al4,bh0))+Math.imul(ah4,bl0)|0,hi=Math.imul(ah4,bh0),lo=lo+Math.imul(al3,bl1)|0,mid=(mid=mid+Math.imul(al3,bh1)|0)+Math.imul(ah3,bl1)|0,hi=hi+Math.imul(ah3,bh1)|0,lo=lo+Math.imul(al2,bl2)|0,mid=(mid=mid+Math.imul(al2,bh2)|0)+Math.imul(ah2,bl2)|0,hi=hi+Math.imul(ah2,bh2)|0,lo=lo+Math.imul(al1,bl3)|0,mid=(mid=mid+Math.imul(al1,bh3)|0)+Math.imul(ah1,bl3)|0,hi=hi+Math.imul(ah1,bh3)|0;var w4=(c+(lo=lo+Math.imul(al0,bl4)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh4)|0)+Math.imul(ah0,bl4)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh4)|0)+(mid>>>13)|0)+(w4>>>26)|0,w4&=67108863,lo=Math.imul(al5,bl0),mid=(mid=Math.imul(al5,bh0))+Math.imul(ah5,bl0)|0,hi=Math.imul(ah5,bh0),lo=lo+Math.imul(al4,bl1)|0,mid=(mid=mid+Math.imul(al4,bh1)|0)+Math.imul(ah4,bl1)|0,hi=hi+Math.imul(ah4,bh1)|0,lo=lo+Math.imul(al3,bl2)|0,mid=(mid=mid+Math.imul(al3,bh2)|0)+Math.imul(ah3,bl2)|0,hi=hi+Math.imul(ah3,bh2)|0,lo=lo+Math.imul(al2,bl3)|0,mid=(mid=mid+Math.imul(al2,bh3)|0)+Math.imul(ah2,bl3)|0,hi=hi+Math.imul(ah2,bh3)|0,lo=lo+Math.imul(al1,bl4)|0,mid=(mid=mid+Math.imul(al1,bh4)|0)+Math.imul(ah1,bl4)|0,hi=hi+Math.imul(ah1,bh4)|0;var w5=(c+(lo=lo+Math.imul(al0,bl5)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh5)|0)+Math.imul(ah0,bl5)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh5)|0)+(mid>>>13)|0)+(w5>>>26)|0,w5&=67108863,lo=Math.imul(al6,bl0),mid=(mid=Math.imul(al6,bh0))+Math.imul(ah6,bl0)|0,hi=Math.imul(ah6,bh0),lo=lo+Math.imul(al5,bl1)|0,mid=(mid=mid+Math.imul(al5,bh1)|0)+Math.imul(ah5,bl1)|0,hi=hi+Math.imul(ah5,bh1)|0,lo=lo+Math.imul(al4,bl2)|0,mid=(mid=mid+Math.imul(al4,bh2)|0)+Math.imul(ah4,bl2)|0,hi=hi+Math.imul(ah4,bh2)|0,lo=lo+Math.imul(al3,bl3)|0,mid=(mid=mid+Math.imul(al3,bh3)|0)+Math.imul(ah3,bl3)|0,hi=hi+Math.imul(ah3,bh3)|0,lo=lo+Math.imul(al2,bl4)|0,mid=(mid=mid+Math.imul(al2,bh4)|0)+Math.imul(ah2,bl4)|0,hi=hi+Math.imul(ah2,bh4)|0,lo=lo+Math.imul(al1,bl5)|0,mid=(mid=mid+Math.imul(al1,bh5)|0)+Math.imul(ah1,bl5)|0,hi=hi+Math.imul(ah1,bh5)|0;var w6=(c+(lo=lo+Math.imul(al0,bl6)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh6)|0)+Math.imul(ah0,bl6)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh6)|0)+(mid>>>13)|0)+(w6>>>26)|0,w6&=67108863,lo=Math.imul(al7,bl0),mid=(mid=Math.imul(al7,bh0))+Math.imul(ah7,bl0)|0,hi=Math.imul(ah7,bh0),lo=lo+Math.imul(al6,bl1)|0,mid=(mid=mid+Math.imul(al6,bh1)|0)+Math.imul(ah6,bl1)|0,hi=hi+Math.imul(ah6,bh1)|0,lo=lo+Math.imul(al5,bl2)|0,mid=(mid=mid+Math.imul(al5,bh2)|0)+Math.imul(ah5,bl2)|0,hi=hi+Math.imul(ah5,bh2)|0,lo=lo+Math.imul(al4,bl3)|0,mid=(mid=mid+Math.imul(al4,bh3)|0)+Math.imul(ah4,bl3)|0,hi=hi+Math.imul(ah4,bh3)|0,lo=lo+Math.imul(al3,bl4)|0,mid=(mid=mid+Math.imul(al3,bh4)|0)+Math.imul(ah3,bl4)|0,hi=hi+Math.imul(ah3,bh4)|0,lo=lo+Math.imul(al2,bl5)|0,mid=(mid=mid+Math.imul(al2,bh5)|0)+Math.imul(ah2,bl5)|0,hi=hi+Math.imul(ah2,bh5)|0,lo=lo+Math.imul(al1,bl6)|0,mid=(mid=mid+Math.imul(al1,bh6)|0)+Math.imul(ah1,bl6)|0,hi=hi+Math.imul(ah1,bh6)|0;var w7=(c+(lo=lo+Math.imul(al0,bl7)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh7)|0)+Math.imul(ah0,bl7)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh7)|0)+(mid>>>13)|0)+(w7>>>26)|0,w7&=67108863,lo=Math.imul(al8,bl0),mid=(mid=Math.imul(al8,bh0))+Math.imul(ah8,bl0)|0,hi=Math.imul(ah8,bh0),lo=lo+Math.imul(al7,bl1)|0,mid=(mid=mid+Math.imul(al7,bh1)|0)+Math.imul(ah7,bl1)|0,hi=hi+Math.imul(ah7,bh1)|0,lo=lo+Math.imul(al6,bl2)|0,mid=(mid=mid+Math.imul(al6,bh2)|0)+Math.imul(ah6,bl2)|0,hi=hi+Math.imul(ah6,bh2)|0,lo=lo+Math.imul(al5,bl3)|0,mid=(mid=mid+Math.imul(al5,bh3)|0)+Math.imul(ah5,bl3)|0,hi=hi+Math.imul(ah5,bh3)|0,lo=lo+Math.imul(al4,bl4)|0,mid=(mid=mid+Math.imul(al4,bh4)|0)+Math.imul(ah4,bl4)|0,hi=hi+Math.imul(ah4,bh4)|0,lo=lo+Math.imul(al3,bl5)|0,mid=(mid=mid+Math.imul(al3,bh5)|0)+Math.imul(ah3,bl5)|0,hi=hi+Math.imul(ah3,bh5)|0,lo=lo+Math.imul(al2,bl6)|0,mid=(mid=mid+Math.imul(al2,bh6)|0)+Math.imul(ah2,bl6)|0,hi=hi+Math.imul(ah2,bh6)|0,lo=lo+Math.imul(al1,bl7)|0,mid=(mid=mid+Math.imul(al1,bh7)|0)+Math.imul(ah1,bl7)|0,hi=hi+Math.imul(ah1,bh7)|0;var w8=(c+(lo=lo+Math.imul(al0,bl8)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh8)|0)+Math.imul(ah0,bl8)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh8)|0)+(mid>>>13)|0)+(w8>>>26)|0,w8&=67108863,lo=Math.imul(al9,bl0),mid=(mid=Math.imul(al9,bh0))+Math.imul(ah9,bl0)|0,hi=Math.imul(ah9,bh0),lo=lo+Math.imul(al8,bl1)|0,mid=(mid=mid+Math.imul(al8,bh1)|0)+Math.imul(ah8,bl1)|0,hi=hi+Math.imul(ah8,bh1)|0,lo=lo+Math.imul(al7,bl2)|0,mid=(mid=mid+Math.imul(al7,bh2)|0)+Math.imul(ah7,bl2)|0,hi=hi+Math.imul(ah7,bh2)|0,lo=lo+Math.imul(al6,bl3)|0,mid=(mid=mid+Math.imul(al6,bh3)|0)+Math.imul(ah6,bl3)|0,hi=hi+Math.imul(ah6,bh3)|0,lo=lo+Math.imul(al5,bl4)|0,mid=(mid=mid+Math.imul(al5,bh4)|0)+Math.imul(ah5,bl4)|0,hi=hi+Math.imul(ah5,bh4)|0,lo=lo+Math.imul(al4,bl5)|0,mid=(mid=mid+Math.imul(al4,bh5)|0)+Math.imul(ah4,bl5)|0,hi=hi+Math.imul(ah4,bh5)|0,lo=lo+Math.imul(al3,bl6)|0,mid=(mid=mid+Math.imul(al3,bh6)|0)+Math.imul(ah3,bl6)|0,hi=hi+Math.imul(ah3,bh6)|0,lo=lo+Math.imul(al2,bl7)|0,mid=(mid=mid+Math.imul(al2,bh7)|0)+Math.imul(ah2,bl7)|0,hi=hi+Math.imul(ah2,bh7)|0,lo=lo+Math.imul(al1,bl8)|0,mid=(mid=mid+Math.imul(al1,bh8)|0)+Math.imul(ah1,bl8)|0,hi=hi+Math.imul(ah1,bh8)|0;var w9=(c+(lo=lo+Math.imul(al0,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al0,bh9)|0)+Math.imul(ah0,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah0,bh9)|0)+(mid>>>13)|0)+(w9>>>26)|0,w9&=67108863,lo=Math.imul(al9,bl1),mid=(mid=Math.imul(al9,bh1))+Math.imul(ah9,bl1)|0,hi=Math.imul(ah9,bh1),lo=lo+Math.imul(al8,bl2)|0,mid=(mid=mid+Math.imul(al8,bh2)|0)+Math.imul(ah8,bl2)|0,hi=hi+Math.imul(ah8,bh2)|0,lo=lo+Math.imul(al7,bl3)|0,mid=(mid=mid+Math.imul(al7,bh3)|0)+Math.imul(ah7,bl3)|0,hi=hi+Math.imul(ah7,bh3)|0,lo=lo+Math.imul(al6,bl4)|0,mid=(mid=mid+Math.imul(al6,bh4)|0)+Math.imul(ah6,bl4)|0,hi=hi+Math.imul(ah6,bh4)|0,lo=lo+Math.imul(al5,bl5)|0,mid=(mid=mid+Math.imul(al5,bh5)|0)+Math.imul(ah5,bl5)|0,hi=hi+Math.imul(ah5,bh5)|0,lo=lo+Math.imul(al4,bl6)|0,mid=(mid=mid+Math.imul(al4,bh6)|0)+Math.imul(ah4,bl6)|0,hi=hi+Math.imul(ah4,bh6)|0,lo=lo+Math.imul(al3,bl7)|0,mid=(mid=mid+Math.imul(al3,bh7)|0)+Math.imul(ah3,bl7)|0,hi=hi+Math.imul(ah3,bh7)|0,lo=lo+Math.imul(al2,bl8)|0,mid=(mid=mid+Math.imul(al2,bh8)|0)+Math.imul(ah2,bl8)|0,hi=hi+Math.imul(ah2,bh8)|0;var w10=(c+(lo=lo+Math.imul(al1,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al1,bh9)|0)+Math.imul(ah1,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah1,bh9)|0)+(mid>>>13)|0)+(w10>>>26)|0,w10&=67108863,lo=Math.imul(al9,bl2),mid=(mid=Math.imul(al9,bh2))+Math.imul(ah9,bl2)|0,hi=Math.imul(ah9,bh2),lo=lo+Math.imul(al8,bl3)|0,mid=(mid=mid+Math.imul(al8,bh3)|0)+Math.imul(ah8,bl3)|0,hi=hi+Math.imul(ah8,bh3)|0,lo=lo+Math.imul(al7,bl4)|0,mid=(mid=mid+Math.imul(al7,bh4)|0)+Math.imul(ah7,bl4)|0,hi=hi+Math.imul(ah7,bh4)|0,lo=lo+Math.imul(al6,bl5)|0,mid=(mid=mid+Math.imul(al6,bh5)|0)+Math.imul(ah6,bl5)|0,hi=hi+Math.imul(ah6,bh5)|0,lo=lo+Math.imul(al5,bl6)|0,mid=(mid=mid+Math.imul(al5,bh6)|0)+Math.imul(ah5,bl6)|0,hi=hi+Math.imul(ah5,bh6)|0,lo=lo+Math.imul(al4,bl7)|0,mid=(mid=mid+Math.imul(al4,bh7)|0)+Math.imul(ah4,bl7)|0,hi=hi+Math.imul(ah4,bh7)|0,lo=lo+Math.imul(al3,bl8)|0,mid=(mid=mid+Math.imul(al3,bh8)|0)+Math.imul(ah3,bl8)|0,hi=hi+Math.imul(ah3,bh8)|0;var w11=(c+(lo=lo+Math.imul(al2,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al2,bh9)|0)+Math.imul(ah2,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah2,bh9)|0)+(mid>>>13)|0)+(w11>>>26)|0,w11&=67108863,lo=Math.imul(al9,bl3),mid=(mid=Math.imul(al9,bh3))+Math.imul(ah9,bl3)|0,hi=Math.imul(ah9,bh3),lo=lo+Math.imul(al8,bl4)|0,mid=(mid=mid+Math.imul(al8,bh4)|0)+Math.imul(ah8,bl4)|0,hi=hi+Math.imul(ah8,bh4)|0,lo=lo+Math.imul(al7,bl5)|0,mid=(mid=mid+Math.imul(al7,bh5)|0)+Math.imul(ah7,bl5)|0,hi=hi+Math.imul(ah7,bh5)|0,lo=lo+Math.imul(al6,bl6)|0,mid=(mid=mid+Math.imul(al6,bh6)|0)+Math.imul(ah6,bl6)|0,hi=hi+Math.imul(ah6,bh6)|0,lo=lo+Math.imul(al5,bl7)|0,mid=(mid=mid+Math.imul(al5,bh7)|0)+Math.imul(ah5,bl7)|0,hi=hi+Math.imul(ah5,bh7)|0,lo=lo+Math.imul(al4,bl8)|0,mid=(mid=mid+Math.imul(al4,bh8)|0)+Math.imul(ah4,bl8)|0,hi=hi+Math.imul(ah4,bh8)|0;var w12=(c+(lo=lo+Math.imul(al3,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al3,bh9)|0)+Math.imul(ah3,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah3,bh9)|0)+(mid>>>13)|0)+(w12>>>26)|0,w12&=67108863,lo=Math.imul(al9,bl4),mid=(mid=Math.imul(al9,bh4))+Math.imul(ah9,bl4)|0,hi=Math.imul(ah9,bh4),lo=lo+Math.imul(al8,bl5)|0,mid=(mid=mid+Math.imul(al8,bh5)|0)+Math.imul(ah8,bl5)|0,hi=hi+Math.imul(ah8,bh5)|0,lo=lo+Math.imul(al7,bl6)|0,mid=(mid=mid+Math.imul(al7,bh6)|0)+Math.imul(ah7,bl6)|0,hi=hi+Math.imul(ah7,bh6)|0,lo=lo+Math.imul(al6,bl7)|0,mid=(mid=mid+Math.imul(al6,bh7)|0)+Math.imul(ah6,bl7)|0,hi=hi+Math.imul(ah6,bh7)|0,lo=lo+Math.imul(al5,bl8)|0,mid=(mid=mid+Math.imul(al5,bh8)|0)+Math.imul(ah5,bl8)|0,hi=hi+Math.imul(ah5,bh8)|0;var w13=(c+(lo=lo+Math.imul(al4,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al4,bh9)|0)+Math.imul(ah4,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah4,bh9)|0)+(mid>>>13)|0)+(w13>>>26)|0,w13&=67108863,lo=Math.imul(al9,bl5),mid=(mid=Math.imul(al9,bh5))+Math.imul(ah9,bl5)|0,hi=Math.imul(ah9,bh5),lo=lo+Math.imul(al8,bl6)|0,mid=(mid=mid+Math.imul(al8,bh6)|0)+Math.imul(ah8,bl6)|0,hi=hi+Math.imul(ah8,bh6)|0,lo=lo+Math.imul(al7,bl7)|0,mid=(mid=mid+Math.imul(al7,bh7)|0)+Math.imul(ah7,bl7)|0,hi=hi+Math.imul(ah7,bh7)|0,lo=lo+Math.imul(al6,bl8)|0,mid=(mid=mid+Math.imul(al6,bh8)|0)+Math.imul(ah6,bl8)|0,hi=hi+Math.imul(ah6,bh8)|0;var w14=(c+(lo=lo+Math.imul(al5,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al5,bh9)|0)+Math.imul(ah5,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah5,bh9)|0)+(mid>>>13)|0)+(w14>>>26)|0,w14&=67108863,lo=Math.imul(al9,bl6),mid=(mid=Math.imul(al9,bh6))+Math.imul(ah9,bl6)|0,hi=Math.imul(ah9,bh6),lo=lo+Math.imul(al8,bl7)|0,mid=(mid=mid+Math.imul(al8,bh7)|0)+Math.imul(ah8,bl7)|0,hi=hi+Math.imul(ah8,bh7)|0,lo=lo+Math.imul(al7,bl8)|0,mid=(mid=mid+Math.imul(al7,bh8)|0)+Math.imul(ah7,bl8)|0,hi=hi+Math.imul(ah7,bh8)|0;var w15=(c+(lo=lo+Math.imul(al6,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al6,bh9)|0)+Math.imul(ah6,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah6,bh9)|0)+(mid>>>13)|0)+(w15>>>26)|0,w15&=67108863,lo=Math.imul(al9,bl7),mid=(mid=Math.imul(al9,bh7))+Math.imul(ah9,bl7)|0,hi=Math.imul(ah9,bh7),lo=lo+Math.imul(al8,bl8)|0,mid=(mid=mid+Math.imul(al8,bh8)|0)+Math.imul(ah8,bl8)|0,hi=hi+Math.imul(ah8,bh8)|0;var w16=(c+(lo=lo+Math.imul(al7,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al7,bh9)|0)+Math.imul(ah7,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah7,bh9)|0)+(mid>>>13)|0)+(w16>>>26)|0,w16&=67108863,lo=Math.imul(al9,bl8),mid=(mid=Math.imul(al9,bh8))+Math.imul(ah9,bl8)|0,hi=Math.imul(ah9,bh8);var w17=(c+(lo=lo+Math.imul(al8,bl9)|0)|0)+((8191&(mid=(mid=mid+Math.imul(al8,bh9)|0)+Math.imul(ah8,bl9)|0))<<13)|0;c=((hi=hi+Math.imul(ah8,bh9)|0)+(mid>>>13)|0)+(w17>>>26)|0,w17&=67108863;var w18=(c+(lo=Math.imul(al9,bl9))|0)+((8191&(mid=(mid=Math.imul(al9,bh9))+Math.imul(ah9,bl9)|0))<<13)|0;return c=((hi=Math.imul(ah9,bh9))+(mid>>>13)|0)+(w18>>>26)|0,w18&=67108863,o[0]=w0,o[1]=w1,o[2]=w2,o[3]=w3,o[4]=w4,o[5]=w5,o[6]=w6,o[7]=w7,o[8]=w8,o[9]=w9,o[10]=w10,o[11]=w11,o[12]=w12,o[13]=w13,o[14]=w14,o[15]=w15,o[16]=w16,o[17]=w17,o[18]=w18,0!==c&&(o[19]=c,out.length++),out};function jumboMulTo(self,num,out){return(new FFTM).mulp(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}Math.imul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function mulTo(num,out){var res,len=this.length+num.length;return res=10===this.length&&10===num.length?comb10MulTo(this,num,out):len<63?smallMulTo(this,num,out):len<1024?function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0;k>>26)|0)>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0!==carry?out.words[k]=carry:out.length--,out.strip()}(this,num,out):jumboMulTo(this,num,out),res},FFTM.prototype.makeRBT=function makeRBT(N){for(var t=new Array(N),l=BN.prototype._countBits(N)-1,i=0;i>=1;return rb},FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>=1)i++;return 1<>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;i>=26,carry+=w/67108864|0,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.muln=function muln(num){return this.clone().imuln(num)},BN.prototype.sqr=function sqr(){return this.mul(this)},BN.prototype.isqr=function isqr(){return this.imul(this.clone())},BN.prototype.pow=function pow(num){var w=function toBitArray(num){for(var w=new Array(num.bitLength()),bit=0;bit>>wbit}return w}(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i=0);var i,r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r;if(0!==r){var carry=0;for(i=0;i>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;i>=0;i--)this.words[i+s]=this.words[i];for(i=0;i=0),h=hint?(hint-hint%26)/26:0;var r=bits%26,s=Math.min((bits-r)/26,this.length),mask=67108863^67108863>>>r<s)for(this.length-=s,i=0;i=0&&(0!==carry||i>=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&0!==carry&&(maskedWords.words[maskedWords.length++]=carry),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},BN.prototype.ishrn=function ishrn(bits,hint,extended){return assert(0===this.negative),this.iushrn(bits,hint,extended)},BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function testn(bit){assert("number"==typeof bit&&bit>=0);var r=bit%26,s=(bit-r)/26,q=1<=0);var r=bits%26,s=(bits-r)/26;if(assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!==r&&s++,this.length=Math.min(s,this.length),0!==r){var mask=67108863^67108863>>>r<=67108864;i++)this.words[i]-=67108864,i===this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=Math.max(this.length,i+1),this},BN.prototype.isubn=function isubn(num){if(assert("number"==typeof num),assert(num<67108864),num<0)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i>26)-(right/67108864|0),this.words[i+shift]=67108863&w}for(;i>26,this.words[i+shift]=67108863&w;if(0===carry)return this.strip();for(assert(-1===carry),carry=0,i=0;i>26,this.words[i]=67108863&w;return this.negative=1,this.strip()},BN.prototype._wordDiv=function _wordDiv(num,mode){var shift=(this.length,num.length),a=this.clone(),b=num,bhi=0|b.words[b.length-1];0!==(shift=26-this._countBits(bhi))&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var q,m=a.length-b.length;if("mod"!==mode){(q=new BN(null)).length=m+1,q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=67108864*(0|a.words[b.length+j])+(0|a.words[b.length+j-1]);for(qj=Math.min(qj/bhi|0,67108863),a._ishlnsubmul(b,qj,j);0!==a.negative;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q.strip(),a.strip(),"div"!==mode&&0!==shift&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function divmod(num,mode,positive){return assert(!num.isZero()),this.isZero()?{div:new BN(0),mod:new BN(0)}:0!==this.negative&&0===num.negative?(res=this.neg().divmod(num,mode),"mod"!==mode&&(div=res.div.neg()),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.iadd(num)),{div,mod}):0===this.negative&&0!==num.negative?(res=this.divmod(num.neg(),mode),"mod"!==mode&&(div=res.div.neg()),{div,mod:res.mod}):0!=(this.negative&num.negative)?(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod}):num.length>this.length||this.cmp(num)<0?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modn(num.words[0]))}:this._wordDiv(num,mode);var div,mod,res},BN.prototype.div=function div(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function mod(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function umod(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0!==dm.div.negative?dm.mod.isub(num):dm.mod,half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return cmp<0||1===r2&&0===cmp?dm.div:0!==dm.div.negative?dm.div.isubn(1):dm.div.iaddn(1)},BN.prototype.modn=function modn(num){assert(num<=67108863);for(var p=(1<<26)%num,acc=0,i=this.length-1;i>=0;i--)acc=(p*acc+(0|this.words[i]))%num;return acc},BN.prototype.idivn=function idivn(num){assert(num<=67108863);for(var carry=0,i=this.length-1;i>=0;i--){var w=(0|this.words[i])+67108864*carry;this.words[i]=w/num|0,carry=w%num}return this.strip()},BN.prototype.divn=function divn(num){return this.clone().idivn(num)},BN.prototype.egcd=function egcd(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0!==x.negative?x.umod(p):x.clone();for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0==(x.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(x.iushrn(i);i-- >0;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;0==(y.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(y.iushrn(j);j-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);x.cmp(y)>=0?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function _invmp(p){assert(0===p.negative),assert(!p.isZero());var a=this,b=p.clone();a=0!==a.negative?a.umod(p):a.clone();for(var res,x1=new BN(1),x2=new BN(0),delta=b.clone();a.cmpn(1)>0&&b.cmpn(1)>0;){for(var i=0,im=1;0==(a.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(a.iushrn(i);i-- >0;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;0==(b.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(b.iushrn(j);j-- >0;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);a.cmp(b)>=0?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}return(res=0===a.cmpn(1)?x1:x2).cmpn(0)<0&&res.iadd(p),res},BN.prototype.gcd=function gcd(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);for(;;){for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(r<0){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}return b.iushln(shift)},BN.prototype.invm=function invm(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function isEven(){return 0==(1&this.words[0])},BN.prototype.isOdd=function isOdd(){return 1==(1&this.words[0])},BN.prototype.andln=function andln(num){return this.words[0]&num},BN.prototype.bincn=function bincn(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<>>26,w&=67108863,this.words[i]=w}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function isZero(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function cmpn(num){var res,negative=num<0;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;if(this.strip(),this.length>1)res=1;else{negative&&(num=-num),assert(num<=67108863,"Number is too big");var w=0|this.words[0];res=w===num?0:wnum.length)return 1;if(this.length=0;i--){var a=0|this.words[i],b=0|num.words[i];if(a!==b){ab&&(res=1);break}}return res},BN.prototype.gtn=function gtn(num){return 1===this.cmpn(num)},BN.prototype.gt=function gt(num){return 1===this.cmp(num)},BN.prototype.gten=function gten(num){return this.cmpn(num)>=0},BN.prototype.gte=function gte(num){return this.cmp(num)>=0},BN.prototype.ltn=function ltn(num){return-1===this.cmpn(num)},BN.prototype.lt=function lt(num){return-1===this.cmp(num)},BN.prototype.lten=function lten(num){return this.cmpn(num)<=0},BN.prototype.lte=function lte(num){return this.cmp(num)<=0},BN.prototype.eqn=function eqn(num){return 0===this.cmpn(num)},BN.prototype.eq=function eq(num){return 0===this.cmp(num)},BN.red=function red(num){return new Red(num)},BN.prototype.toRed=function toRed(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function fromRed(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function _forceRed(ctx){return this.red=ctx,this},BN.prototype.forceRed=function forceRed(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function redAdd(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function redIAdd(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function redSub(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function redISub(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function redShl(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function redMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function redIMul(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function redSqr(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function redISqr(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function redSqrt(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function redInvm(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function redNeg(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function redPow(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};function MPrime(name,p){this.name=name,this.p=new BN(p,16),this.n=this.p.bitLength(),this.k=new BN(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){var prime=BN._prime(m);this.m=prime.p,this.prime=prime}else assert(m.gtn(1),"modulus must be greater than 1"),this.m=m,this.prime=null}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new BN(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}MPrime.prototype._tmp=function _tmp(){var tmp=new BN(null);return tmp.words=new Array(Math.ceil(this.n/13)),tmp},MPrime.prototype.ireduce=function ireduce(num){var rlen,r=num;do{this.split(r,this.tmp),rlen=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(rlen>this.n);var cmp=rlen0?r.isub(this.p):void 0!==r.strip?r.strip():r._strip(),r},MPrime.prototype.split=function split(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function imulK(num){return num.imul(this.k)},inherits(K256,MPrime),K256.prototype.split=function split(input,output){for(var outLen=Math.min(input.length,9),i=0;i>>22,prev=next}prev>>>=22,input.words[i-10]=prev,0===prev&&input.length>10?input.length-=10:input.length-=9},K256.prototype.imulK=function imulK(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0;i>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else{if("p25519"!==name)throw new Error("Unknown prime "+name);prime=new P25519}return primes[name]=prime,prime},Red.prototype._verify1=function _verify1(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function _verify2(a,b){assert(0==(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function imod(a){return this.prime?this.prime.ireduce(a)._forceRed(this):a.umod(this.m)._forceRed(this)},Red.prototype.neg=function neg(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function add(a,b){this._verify2(a,b);var res=a.add(b);return res.cmp(this.m)>=0&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function iadd(a,b){this._verify2(a,b);var res=a.iadd(b);return res.cmp(this.m)>=0&&res.isub(this.m),res},Red.prototype.sub=function sub(a,b){this._verify2(a,b);var res=a.sub(b);return res.cmpn(0)<0&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function isub(a,b){this._verify2(a,b);var res=a.isub(b);return res.cmpn(0)<0&&res.iadd(this.m),res},Red.prototype.shl=function shl(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function imul(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function mul(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function isqr(a){return this.imul(a,a.clone())},Red.prototype.sqr=function sqr(a){return this.mul(a,a)},Red.prototype.sqrt=function sqrt(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(mod3%2==1),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i=0;i--){for(var word=num.words[i],j=start-1;j>=0;j--){var bit=word>>j&1;res!==wnd[0]&&(res=this.sqr(res)),0!==bit||0!==current?(current<<=1,current|=bit,(4===++currentLen||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)):currentLen=0}start=26}return res},Red.prototype.convertTo=function convertTo(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function convertFrom(num){var res=num.clone();return res.red=null,res},BN.mont=function mont(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function convertTo(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function convertFrom(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function imul(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function mul(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function invm(a){return this.imod(a._invmp(this.m).mul(this.r2))._forceRed(this)}}(module=__webpack_require__.nmd(module),this)},6138:(module,__unused_webpack_exports,__webpack_require__)=>{var parseKeys=__webpack_require__(980),mgf=__webpack_require__(9199),xor=__webpack_require__(7859),BN=__webpack_require__(2144),crt=__webpack_require__(3663),createHash=__webpack_require__(3482),withPublic=__webpack_require__(4818),Buffer=__webpack_require__(9509).Buffer;module.exports=function privateDecrypt(privateKey,enc,reverse){var padding;padding=privateKey.padding?privateKey.padding:reverse?1:4;var msg,key=parseKeys(privateKey),k=key.modulus.byteLength();if(enc.length>k||new BN(enc).cmp(key.modulus)>=0)throw new Error("decryption error");msg=reverse?withPublic(new BN(enc),key):crt(enc,key);var zBuffer=Buffer.alloc(k-msg.length);if(msg=Buffer.concat([zBuffer,msg],k),4===padding)return function oaep(key,msg){var k=key.modulus.byteLength(),iHash=createHash("sha1").update(Buffer.alloc(0)).digest(),hLen=iHash.length;if(0!==msg[0])throw new Error("decryption error");var maskedSeed=msg.slice(1,hLen+1),maskedDb=msg.slice(hLen+1),seed=xor(maskedSeed,mgf(maskedDb,hLen)),db=xor(maskedDb,mgf(seed,k-hLen-1));if(function compare(a,b){a=Buffer.from(a),b=Buffer.from(b);var dif=0,len=a.length;a.length!==b.length&&(dif++,len=Math.min(a.length,b.length));var i=-1;for(;++i=msg.length){status++;break}var ps=msg.slice(2,i-1);("0002"!==p1.toString("hex")&&!reverse||"0001"!==p1.toString("hex")&&reverse)&&status++;ps.length<8&&status++;if(status)throw new Error("decryption error");return msg.slice(i)}(0,msg,reverse);if(3===padding)return msg;throw new Error("unknown padding")}},6559:(module,__unused_webpack_exports,__webpack_require__)=>{var parseKeys=__webpack_require__(980),randomBytes=__webpack_require__(1798),createHash=__webpack_require__(3482),mgf=__webpack_require__(9199),xor=__webpack_require__(7859),BN=__webpack_require__(2144),withPublic=__webpack_require__(4818),crt=__webpack_require__(3663),Buffer=__webpack_require__(9509).Buffer;module.exports=function publicEncrypt(publicKey,msg,reverse){var padding;padding=publicKey.padding?publicKey.padding:reverse?1:4;var paddedMsg,key=parseKeys(publicKey);if(4===padding)paddedMsg=function oaep(key,msg){var k=key.modulus.byteLength(),mLen=msg.length,iHash=createHash("sha1").update(Buffer.alloc(0)).digest(),hLen=iHash.length,hLen2=2*hLen;if(mLen>k-hLen2-2)throw new Error("message too long");var ps=Buffer.alloc(k-mLen-hLen2-2),dblen=k-hLen-1,seed=randomBytes(hLen),maskedDb=xor(Buffer.concat([iHash,ps,Buffer.alloc(1,1),msg],dblen),mgf(seed,dblen)),maskedSeed=xor(seed,mgf(maskedDb,hLen));return new BN(Buffer.concat([Buffer.alloc(1),maskedSeed,maskedDb],k))}(key,msg);else if(1===padding)paddedMsg=function pkcs1(key,msg,reverse){var ps,mLen=msg.length,k=key.modulus.byteLength();if(mLen>k-11)throw new Error("message too long");ps=reverse?Buffer.alloc(k-mLen-3,255):function nonZero(len){var num,out=Buffer.allocUnsafe(len),i=0,cache=randomBytes(2*len),cur=0;for(;i=0)throw new Error("data too long for modulus")}return reverse?crt(paddedMsg,key):withPublic(paddedMsg,key)}},4818:(module,__unused_webpack_exports,__webpack_require__)=>{var BN=__webpack_require__(2144),Buffer=__webpack_require__(9509).Buffer;module.exports=function withPublic(paddedMsg,key){return Buffer.from(paddedMsg.toRed(BN.mont(key.modulus)).redPow(new BN(key.publicExponent)).fromRed().toArray())}},7859:module=>{module.exports=function xor(a,b){for(var len=a.length,i=-1;++i{"use strict";var Buffer=__webpack_require__(9509).Buffer,crypto=__webpack_require__.g.crypto||__webpack_require__.g.msCrypto;crypto&&crypto.getRandomValues?module.exports=function randomBytes(size,cb){if(size>4294967295)throw new RangeError("requested too many random bytes");var bytes=Buffer.allocUnsafe(size);if(size>0)if(size>65536)for(var generated=0;generated{"use strict";function oldBrowser(){throw new Error("secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11")}var safeBuffer=__webpack_require__(9509),randombytes=__webpack_require__(1798),Buffer=safeBuffer.Buffer,kBufferMaxLength=safeBuffer.kMaxLength,crypto=__webpack_require__.g.crypto||__webpack_require__.g.msCrypto,kMaxUint32=Math.pow(2,32)-1;function assertOffset(offset,length){if("number"!=typeof offset||offset!=offset)throw new TypeError("offset must be a number");if(offset>kMaxUint32||offset<0)throw new TypeError("offset must be a uint32");if(offset>kBufferMaxLength||offset>length)throw new RangeError("offset out of range")}function assertSize(size,offset,length){if("number"!=typeof size||size!=size)throw new TypeError("size must be a number");if(size>kMaxUint32||size<0)throw new TypeError("size must be a uint32");if(size+offset>length||size>kBufferMaxLength)throw new RangeError("buffer too small")}function actualFill(buf,offset,size,cb){if(process.browser){var ourBuf=buf.buffer,uint=new Uint8Array(ourBuf,offset,size);return crypto.getRandomValues(uint),cb?void process.nextTick((function(){cb(null,buf)})):buf}if(!cb)return randombytes(size).copy(buf,offset),buf;randombytes(size,(function(err,bytes){if(err)return cb(err);bytes.copy(buf,offset),cb(null,buf)}))}crypto&&crypto.getRandomValues||!process.browser?(exports.randomFill=function randomFill(buf,offset,size,cb){if(!(Buffer.isBuffer(buf)||buf instanceof __webpack_require__.g.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');if("function"==typeof offset)cb=offset,offset=0,size=buf.length;else if("function"==typeof size)cb=size,size=buf.length-offset;else if("function"!=typeof cb)throw new TypeError('"cb" argument must be a function');return assertOffset(offset,buf.length),assertSize(size,offset,buf.length),actualFill(buf,offset,size,cb)},exports.randomFillSync=function randomFillSync(buf,offset,size){void 0===offset&&(offset=0);if(!(Buffer.isBuffer(buf)||buf instanceof __webpack_require__.g.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');assertOffset(offset,buf.length),void 0===size&&(size=buf.length-offset);return assertSize(size,offset,buf.length),actualFill(buf,offset,size)}):(exports.randomFill=oldBrowser,exports.randomFillSync=oldBrowser)},4281:module=>{"use strict";var codes={};function createErrorType(code,message,Base){Base||(Base=Error);var NodeError=function(_Base){function NodeError(arg1,arg2,arg3){return _Base.call(this,function getMessage(arg1,arg2,arg3){return"string"==typeof message?message:message(arg1,arg2,arg3)}(arg1,arg2,arg3))||this}return function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype),subClass.prototype.constructor=subClass,subClass.__proto__=superClass}(NodeError,_Base),NodeError}(Base);NodeError.prototype.name=Base.name,NodeError.prototype.code=code,codes[code]=NodeError}function oneOf(expected,thing){if(Array.isArray(expected)){var len=expected.length;return expected=expected.map((function(i){return String(i)})),len>2?"one of ".concat(thing," ").concat(expected.slice(0,len-1).join(", "),", or ")+expected[len-1]:2===len?"one of ".concat(thing," ").concat(expected[0]," or ").concat(expected[1]):"of ".concat(thing," ").concat(expected[0])}return"of ".concat(thing," ").concat(String(expected))}createErrorType("ERR_INVALID_OPT_VALUE",(function(name,value){return'The value "'+value+'" is invalid for option "'+name+'"'}),TypeError),createErrorType("ERR_INVALID_ARG_TYPE",(function(name,expected,actual){var determiner,msg;if("string"==typeof expected&&function startsWith(str,search,pos){return str.substr(!pos||pos<0?0:+pos,search.length)===search}(expected,"not ")?(determiner="must not be",expected=expected.replace(/^not /,"")):determiner="must be",function endsWith(str,search,this_len){return(void 0===this_len||this_len>str.length)&&(this_len=str.length),str.substring(this_len-search.length,this_len)===search}(name," argument"))msg="The ".concat(name," ").concat(determiner," ").concat(oneOf(expected,"type"));else{var type=function includes(str,search,start){return"number"!=typeof start&&(start=0),!(start+search.length>str.length)&&-1!==str.indexOf(search,start)}(name,".")?"property":"argument";msg='The "'.concat(name,'" ').concat(type," ").concat(determiner," ").concat(oneOf(expected,"type"))}return msg+=". Received type ".concat(typeof actual)}),TypeError),createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),createErrorType("ERR_METHOD_NOT_IMPLEMENTED",(function(name){return"The "+name+" method is not implemented"})),createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close"),createErrorType("ERR_STREAM_DESTROYED",(function(name){return"Cannot call "+name+" after a stream was destroyed"})),createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),createErrorType("ERR_UNKNOWN_ENCODING",(function(arg){return"Unknown encoding: "+arg}),TypeError),createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),module.exports.q=codes},6753:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var Readable=__webpack_require__(9481),Writable=__webpack_require__(4229);__webpack_require__(5717)(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0;v{"use strict";module.exports=PassThrough;var Transform=__webpack_require__(4605);function PassThrough(options){if(!(this instanceof PassThrough))return new PassThrough(options);Transform.call(this,options)}__webpack_require__(5717)(PassThrough,Transform),PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},9481:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var Duplex;module.exports=Readable,Readable.ReadableState=ReadableState;__webpack_require__(7187).EventEmitter;var EElistenerCount=function EElistenerCount(emitter,type){return emitter.listeners(type).length},Stream=__webpack_require__(2503),Buffer=__webpack_require__(8764).Buffer,OurUint8Array=__webpack_require__.g.Uint8Array||function(){};var debug,debugUtil=__webpack_require__(4616);debug=debugUtil&&debugUtil.debuglog?debugUtil.debuglog("stream"):function debug(){};var StringDecoder,createReadableStreamAsyncIterator,from,BufferList=__webpack_require__(7327),destroyImpl=__webpack_require__(1195),getHighWaterMark=__webpack_require__(2457).getHighWaterMark,_require$codes=__webpack_require__(4281).q,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_STREAM_PUSH_AFTER_EOF=_require$codes.ERR_STREAM_PUSH_AFTER_EOF,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_STREAM_UNSHIFT_AFTER_END_EVENT=_require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;__webpack_require__(5717)(Readable,Stream);var errorOrDestroy=destroyImpl.errorOrDestroy,kProxyEvents=["error","close","destroy","pause","resume"];function ReadableState(options,stream,isDuplex){Duplex=Duplex||__webpack_require__(6753),options=options||{},"boolean"!=typeof isDuplex&&(isDuplex=stream instanceof Duplex),this.objectMode=!!options.objectMode,isDuplex&&(this.objectMode=this.objectMode||!!options.readableObjectMode),this.highWaterMark=getHighWaterMark(this,options,"readableHighWaterMark",isDuplex),this.buffer=new BufferList,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==options.emitClose,this.autoDestroy=!!options.autoDestroy,this.destroyed=!1,this.defaultEncoding=options.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,options.encoding&&(StringDecoder||(StringDecoder=__webpack_require__(2553).s),this.decoder=new StringDecoder(options.encoding),this.encoding=options.encoding)}function Readable(options){if(Duplex=Duplex||__webpack_require__(6753),!(this instanceof Readable))return new Readable(options);var isDuplex=this instanceof Duplex;this._readableState=new ReadableState(options,this,isDuplex),this.readable=!0,options&&("function"==typeof options.read&&(this._read=options.read),"function"==typeof options.destroy&&(this._destroy=options.destroy)),Stream.call(this)}function readableAddChunk(stream,chunk,encoding,addToFront,skipChunkCheck){debug("readableAddChunk",chunk);var er,state=stream._readableState;if(null===chunk)state.reading=!1,function onEofChunk(stream,state){if(debug("onEofChunk"),state.ended)return;if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,state.sync?emitReadable(stream):(state.needReadable=!1,state.emittedReadable||(state.emittedReadable=!0,emitReadable_(stream)))}(stream,state);else if(skipChunkCheck||(er=function chunkInvalid(state,chunk){var er;(function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array})(chunk)||"string"==typeof chunk||void 0===chunk||state.objectMode||(er=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer","Uint8Array"],chunk));return er}(state,chunk)),er)errorOrDestroy(stream,er);else if(state.objectMode||chunk&&chunk.length>0)if("string"==typeof chunk||state.objectMode||Object.getPrototypeOf(chunk)===Buffer.prototype||(chunk=function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}(chunk)),addToFront)state.endEmitted?errorOrDestroy(stream,new ERR_STREAM_UNSHIFT_AFTER_END_EVENT):addChunk(stream,state,chunk,!0);else if(state.ended)errorOrDestroy(stream,new ERR_STREAM_PUSH_AFTER_EOF);else{if(state.destroyed)return!1;state.reading=!1,state.decoder&&!encoding?(chunk=state.decoder.write(chunk),state.objectMode||0!==chunk.length?addChunk(stream,state,chunk,!1):maybeReadMore(stream,state)):addChunk(stream,state,chunk,!1)}else addToFront||(state.reading=!1,maybeReadMore(stream,state));return!state.ended&&(state.lengthstate.highWaterMark&&(state.highWaterMark=function computeNewHighWaterMark(n){return n>=1073741824?n=1073741824:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0))}function emitReadable(stream){var state=stream._readableState;debug("emitReadable",state.needReadable,state.emittedReadable),state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,process.nextTick(emitReadable_,stream))}function emitReadable_(stream){var state=stream._readableState;debug("emitReadable_",state.destroyed,state.length,state.ended),state.destroyed||!state.length&&!state.ended||(stream.emit("readable"),state.emittedReadable=!1),state.needReadable=!state.flowing&&!state.ended&&state.length<=state.highWaterMark,flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(;!state.reading&&!state.ended&&(state.length0,state.resumeScheduled&&!state.paused?state.flowing=!0:self.listenerCount("data")>0&&self.resume()}function nReadingNextTick(self){debug("readable nexttick read 0"),self.read(0)}function resume_(stream,state){debug("resume",state.reading),state.reading||stream.read(0),state.resumeScheduled=!1,stream.emit("resume"),flow(stream),state.flowing&&!state.reading&&stream.read(0)}function flow(stream){var state=stream._readableState;for(debug("flow",state.flowing);state.flowing&&null!==stream.read(););}function fromList(n,state){return 0===state.length?null:(state.objectMode?ret=state.buffer.shift():!n||n>=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.first():state.buffer.concat(state.length),state.buffer.clear()):ret=state.buffer.consume(n,state.decoder),ret);var ret}function endReadable(stream){var state=stream._readableState;debug("endReadable",state.endEmitted),state.endEmitted||(state.ended=!0,process.nextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){if(debug("endReadableNT",state.endEmitted,state.length),!state.endEmitted&&0===state.length&&(state.endEmitted=!0,stream.readable=!1,stream.emit("end"),state.autoDestroy)){var wState=stream._writableState;(!wState||wState.autoDestroy&&wState.finished)&&stream.destroy()}}function indexOf(xs,x){for(var i=0,l=xs.length;i=state.highWaterMark:state.length>0)||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(0===(n=howMuchToRead(n,state))&&state.ended)return 0===state.length&&endReadable(this),null;var ret,doRead=state.needReadable;return debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null)?(state.needReadable=state.length<=state.highWaterMark,n=0):(state.length-=n,state.awaitDrain=0),0===state.length&&(state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){errorOrDestroy(this,new ERR_METHOD_NOT_IMPLEMENTED("_read()"))},Readable.prototype.pipe=function(dest,pipeOpts){var src=this,state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var endFn=(!pipeOpts||!1!==pipeOpts.end)&&dest!==process.stdout&&dest!==process.stderr?onend:unpipe;function onunpipe(readable,unpipeInfo){debug("onunpipe"),readable===src&&unpipeInfo&&!1===unpipeInfo.hasUnpiped&&(unpipeInfo.hasUnpiped=!0,function cleanup(){debug("cleanup"),dest.removeListener("close",onclose),dest.removeListener("finish",onfinish),dest.removeListener("drain",ondrain),dest.removeListener("error",onerror),dest.removeListener("unpipe",onunpipe),src.removeListener("end",onend),src.removeListener("end",unpipe),src.removeListener("data",ondata),cleanedUp=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}())}function onend(){debug("onend"),dest.end()}state.endEmitted?process.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=function pipeOnDrain(src){return function pipeOnDrainFunctionResult(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain),state.awaitDrain&&state.awaitDrain--,0===state.awaitDrain&&EElistenerCount(src,"data")&&(state.flowing=!0,flow(src))}}(src);dest.on("drain",ondrain);var cleanedUp=!1;function ondata(chunk){debug("ondata");var ret=dest.write(chunk);debug("dest.write",ret),!1===ret&&((1===state.pipesCount&&state.pipes===dest||state.pipesCount>1&&-1!==indexOf(state.pipes,dest))&&!cleanedUp&&(debug("false write response, pause",state.awaitDrain),state.awaitDrain++),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&errorOrDestroy(dest,er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}return src.on("data",ondata),function prependListener(emitter,event,fn){if("function"==typeof emitter.prependListener)return emitter.prependListener(event,fn);emitter._events&&emitter._events[event]?Array.isArray(emitter._events[event])?emitter._events[event].unshift(fn):emitter._events[event]=[fn,emitter._events[event]]:emitter.on(event,fn)}(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState,unpipeInfo={hasUnpiped:!1};if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes||(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this,unpipeInfo)),this;if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i0,!1!==state.flowing&&this.resume()):"readable"===ev&&(state.endEmitted||state.readableListening||(state.readableListening=state.needReadable=!0,state.flowing=!1,state.emittedReadable=!1,debug("on readable",state.length,state.reading),state.length?emitReadable(this):state.reading||process.nextTick(nReadingNextTick,this))),res},Readable.prototype.addListener=Readable.prototype.on,Readable.prototype.removeListener=function(ev,fn){var res=Stream.prototype.removeListener.call(this,ev,fn);return"readable"===ev&&process.nextTick(updateReadableListening,this),res},Readable.prototype.removeAllListeners=function(ev){var res=Stream.prototype.removeAllListeners.apply(this,arguments);return"readable"!==ev&&void 0!==ev||process.nextTick(updateReadableListening,this),res},Readable.prototype.resume=function(){var state=this._readableState;return state.flowing||(debug("resume"),state.flowing=!state.readableListening,function resume(stream,state){state.resumeScheduled||(state.resumeScheduled=!0,process.nextTick(resume_,stream,state))}(this,state)),state.paused=!1,this},Readable.prototype.pause=function(){return debug("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(debug("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},Readable.prototype.wrap=function(stream){var _this=this,state=this._readableState,paused=!1;for(var i in stream.on("end",(function(){if(debug("wrapped end"),state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&_this.push(chunk)}_this.push(null)})),stream.on("data",(function(chunk){(debug("wrapped data"),state.decoder&&(chunk=state.decoder.write(chunk)),state.objectMode&&null==chunk)||(state.objectMode||chunk&&chunk.length)&&(_this.push(chunk)||(paused=!0,stream.pause()))})),stream)void 0===this[i]&&"function"==typeof stream[i]&&(this[i]=function methodWrap(method){return function methodWrapReturnFunction(){return stream[method].apply(stream,arguments)}}(i));for(var n=0;n{"use strict";module.exports=Transform;var _require$codes=__webpack_require__(4281).q,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes.ERR_MULTIPLE_CALLBACK,ERR_TRANSFORM_ALREADY_TRANSFORMING=_require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,ERR_TRANSFORM_WITH_LENGTH_0=_require$codes.ERR_TRANSFORM_WITH_LENGTH_0,Duplex=__webpack_require__(6753);function afterTransform(er,data){var ts=this._transformState;ts.transforming=!1;var cb=ts.writecb;if(null===cb)return this.emit("error",new ERR_MULTIPLE_CALLBACK);ts.writechunk=null,ts.writecb=null,null!=data&&this.push(data),cb(er);var rs=this._readableState;rs.reading=!1,(rs.needReadable||rs.length{"use strict";function CorkedRequest(state){var _this=this;this.next=null,this.entry=null,this.finish=function(){!function onCorkedFinish(corkReq,state,err){var entry=corkReq.entry;corkReq.entry=null;for(;entry;){var cb=entry.callback;state.pendingcb--,cb(err),entry=entry.next}state.corkedRequestsFree.next=corkReq}(_this,state)}}var Duplex;module.exports=Writable,Writable.WritableState=WritableState;var internalUtil={deprecate:__webpack_require__(4927)},Stream=__webpack_require__(2503),Buffer=__webpack_require__(8764).Buffer,OurUint8Array=__webpack_require__.g.Uint8Array||function(){};var realHasInstance,destroyImpl=__webpack_require__(1195),getHighWaterMark=__webpack_require__(2457).getHighWaterMark,_require$codes=__webpack_require__(4281).q,ERR_INVALID_ARG_TYPE=_require$codes.ERR_INVALID_ARG_TYPE,ERR_METHOD_NOT_IMPLEMENTED=_require$codes.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes.ERR_MULTIPLE_CALLBACK,ERR_STREAM_CANNOT_PIPE=_require$codes.ERR_STREAM_CANNOT_PIPE,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED,ERR_STREAM_NULL_VALUES=_require$codes.ERR_STREAM_NULL_VALUES,ERR_STREAM_WRITE_AFTER_END=_require$codes.ERR_STREAM_WRITE_AFTER_END,ERR_UNKNOWN_ENCODING=_require$codes.ERR_UNKNOWN_ENCODING,errorOrDestroy=destroyImpl.errorOrDestroy;function nop(){}function WritableState(options,stream,isDuplex){Duplex=Duplex||__webpack_require__(6753),options=options||{},"boolean"!=typeof isDuplex&&(isDuplex=stream instanceof Duplex),this.objectMode=!!options.objectMode,isDuplex&&(this.objectMode=this.objectMode||!!options.writableObjectMode),this.highWaterMark=getHighWaterMark(this,options,"writableHighWaterMark",isDuplex),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var noDecode=!1===options.decodeStrings;this.decodeStrings=!noDecode,this.defaultEncoding=options.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(er){!function onwrite(stream,er){var state=stream._writableState,sync=state.sync,cb=state.writecb;if("function"!=typeof cb)throw new ERR_MULTIPLE_CALLBACK;if(function onwriteStateUpdate(state){state.writing=!1,state.writecb=null,state.length-=state.writelen,state.writelen=0}(state),er)!function onwriteError(stream,state,sync,er,cb){--state.pendingcb,sync?(process.nextTick(cb,er),process.nextTick(finishMaybe,stream,state),stream._writableState.errorEmitted=!0,errorOrDestroy(stream,er)):(cb(er),stream._writableState.errorEmitted=!0,errorOrDestroy(stream,er),finishMaybe(stream,state))}(stream,state,sync,er,cb);else{var finished=needFinish(state)||stream.destroyed;finished||state.corked||state.bufferProcessing||!state.bufferedRequest||clearBuffer(stream,state),sync?process.nextTick(afterWrite,stream,state,finished,cb):afterWrite(stream,state,finished,cb)}}(stream,er)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==options.emitClose,this.autoDestroy=!!options.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new CorkedRequest(this)}function Writable(options){var isDuplex=this instanceof(Duplex=Duplex||__webpack_require__(6753));if(!isDuplex&&!realHasInstance.call(Writable,this))return new Writable(options);this._writableState=new WritableState(options,this,isDuplex),this.writable=!0,options&&("function"==typeof options.write&&(this._write=options.write),"function"==typeof options.writev&&(this._writev=options.writev),"function"==typeof options.destroy&&(this._destroy=options.destroy),"function"==typeof options.final&&(this._final=options.final)),Stream.call(this)}function doWrite(stream,state,writev,len,chunk,encoding,cb){state.writelen=len,state.writecb=cb,state.writing=!0,state.sync=!0,state.destroyed?state.onwrite(new ERR_STREAM_DESTROYED("write")):writev?stream._writev(chunk,state.onwrite):stream._write(chunk,encoding,state.onwrite),state.sync=!1}function afterWrite(stream,state,finished,cb){finished||function onwriteDrain(stream,state){0===state.length&&state.needDrain&&(state.needDrain=!1,stream.emit("drain"))}(stream,state),state.pendingcb--,cb(),finishMaybe(stream,state)}function clearBuffer(stream,state){state.bufferProcessing=!0;var entry=state.bufferedRequest;if(stream._writev&&entry&&entry.next){var l=state.bufferedRequestCount,buffer=new Array(l),holder=state.corkedRequestsFree;holder.entry=entry;for(var count=0,allBuffers=!0;entry;)buffer[count]=entry,entry.isBuf||(allBuffers=!1),entry=entry.next,count+=1;buffer.allBuffers=allBuffers,doWrite(stream,state,!0,state.length,buffer,"",holder.finish),state.pendingcb++,state.lastBufferedRequest=null,holder.next?(state.corkedRequestsFree=holder.next,holder.next=null):state.corkedRequestsFree=new CorkedRequest(state),state.bufferedRequestCount=0}else{for(;entry;){var chunk=entry.chunk,encoding=entry.encoding,cb=entry.callback;if(doWrite(stream,state,!1,state.objectMode?1:chunk.length,chunk,encoding,cb),entry=entry.next,state.bufferedRequestCount--,state.writing)break}null===entry&&(state.lastBufferedRequest=null)}state.bufferedRequest=entry,state.bufferProcessing=!1}function needFinish(state){return state.ending&&0===state.length&&null===state.bufferedRequest&&!state.finished&&!state.writing}function callFinal(stream,state){stream._final((function(err){state.pendingcb--,err&&errorOrDestroy(stream,err),state.prefinished=!0,stream.emit("prefinish"),finishMaybe(stream,state)}))}function finishMaybe(stream,state){var need=needFinish(state);if(need&&(function prefinish(stream,state){state.prefinished||state.finalCalled||("function"!=typeof stream._final||state.destroyed?(state.prefinished=!0,stream.emit("prefinish")):(state.pendingcb++,state.finalCalled=!0,process.nextTick(callFinal,stream,state)))}(stream,state),0===state.pendingcb&&(state.finished=!0,stream.emit("finish"),state.autoDestroy))){var rState=stream._readableState;(!rState||rState.autoDestroy&&rState.endEmitted)&&stream.destroy()}return need}__webpack_require__(5717)(Writable,Stream),WritableState.prototype.getBuffer=function getBuffer(){for(var current=this.bufferedRequest,out=[];current;)out.push(current),current=current.next;return out},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate((function writableStateBufferGetter(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(_){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function value(object){return!!realHasInstance.call(this,object)||this===Writable&&(object&&object._writableState instanceof WritableState)}})):realHasInstance=function realHasInstance(object){return object instanceof this},Writable.prototype.pipe=function(){errorOrDestroy(this,new ERR_STREAM_CANNOT_PIPE)},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1,isBuf=!state.objectMode&&function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}(chunk);return isBuf&&!Buffer.isBuffer(chunk)&&(chunk=function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}(chunk)),"function"==typeof encoding&&(cb=encoding,encoding=null),isBuf?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ending?function writeAfterEnd(stream,cb){var er=new ERR_STREAM_WRITE_AFTER_END;errorOrDestroy(stream,er),process.nextTick(cb,er)}(this,cb):(isBuf||function validChunk(stream,state,chunk,cb){var er;return null===chunk?er=new ERR_STREAM_NULL_VALUES:"string"==typeof chunk||state.objectMode||(er=new ERR_INVALID_ARG_TYPE("chunk",["string","Buffer"],chunk)),!er||(errorOrDestroy(stream,er),process.nextTick(cb,er),!1)}(this,state,chunk,cb))&&(state.pendingcb++,ret=function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){var newChunk=function decodeChunk(state,chunk,encoding){state.objectMode||!1===state.decodeStrings||"string"!=typeof chunk||(chunk=Buffer.from(chunk,encoding));return chunk}(state,chunk,encoding);chunk!==newChunk&&(isBuf=!0,encoding="buffer",chunk=newChunk)}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length-1))throw new ERR_UNKNOWN_ENCODING(encoding);return this._writableState.defaultEncoding=encoding,this},Object.defineProperty(Writable.prototype,"writableBuffer",{enumerable:!1,get:function get(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:!1,get:function get(){return this._writableState.highWaterMark}}),Writable.prototype._write=function(chunk,encoding,cb){cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;return"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!=chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||function endWritable(stream,state,cb){state.ending=!0,finishMaybe(stream,state),cb&&(state.finished?process.nextTick(cb):stream.once("finish",cb));state.ended=!0,stream.writable=!1}(this,state,cb),this},Object.defineProperty(Writable.prototype,"writableLength",{enumerable:!1,get:function get(){return this._writableState.length}}),Object.defineProperty(Writable.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._writableState&&this._writableState.destroyed},set:function set(value){this._writableState&&(this._writableState.destroyed=value)}}),Writable.prototype.destroy=destroyImpl.destroy,Writable.prototype._undestroy=destroyImpl.undestroy,Writable.prototype._destroy=function(err,cb){cb(err)}},5850:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var _Object$setPrototypeO;function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}var finished=__webpack_require__(8610),kLastResolve=Symbol("lastResolve"),kLastReject=Symbol("lastReject"),kError=Symbol("error"),kEnded=Symbol("ended"),kLastPromise=Symbol("lastPromise"),kHandlePromise=Symbol("handlePromise"),kStream=Symbol("stream");function createIterResult(value,done){return{value,done}}function readAndResolve(iter){var resolve=iter[kLastResolve];if(null!==resolve){var data=iter[kStream].read();null!==data&&(iter[kLastPromise]=null,iter[kLastResolve]=null,iter[kLastReject]=null,resolve(createIterResult(data,!1)))}}function onReadable(iter){process.nextTick(readAndResolve,iter)}var AsyncIteratorPrototype=Object.getPrototypeOf((function(){})),ReadableStreamAsyncIteratorPrototype=Object.setPrototypeOf((_defineProperty(_Object$setPrototypeO={get stream(){return this[kStream]},next:function next(){var _this=this,error=this[kError];if(null!==error)return Promise.reject(error);if(this[kEnded])return Promise.resolve(createIterResult(void 0,!0));if(this[kStream].destroyed)return new Promise((function(resolve,reject){process.nextTick((function(){_this[kError]?reject(_this[kError]):resolve(createIterResult(void 0,!0))}))}));var promise,lastPromise=this[kLastPromise];if(lastPromise)promise=new Promise(function wrapForNext(lastPromise,iter){return function(resolve,reject){lastPromise.then((function(){iter[kEnded]?resolve(createIterResult(void 0,!0)):iter[kHandlePromise](resolve,reject)}),reject)}}(lastPromise,this));else{var data=this[kStream].read();if(null!==data)return Promise.resolve(createIterResult(data,!1));promise=new Promise(this[kHandlePromise])}return this[kLastPromise]=promise,promise}},Symbol.asyncIterator,(function(){return this})),_defineProperty(_Object$setPrototypeO,"return",(function _return(){var _this2=this;return new Promise((function(resolve,reject){_this2[kStream].destroy(null,(function(err){err?reject(err):resolve(createIterResult(void 0,!0))}))}))})),_Object$setPrototypeO),AsyncIteratorPrototype);module.exports=function createReadableStreamAsyncIterator(stream){var _Object$create,iterator=Object.create(ReadableStreamAsyncIteratorPrototype,(_defineProperty(_Object$create={},kStream,{value:stream,writable:!0}),_defineProperty(_Object$create,kLastResolve,{value:null,writable:!0}),_defineProperty(_Object$create,kLastReject,{value:null,writable:!0}),_defineProperty(_Object$create,kError,{value:null,writable:!0}),_defineProperty(_Object$create,kEnded,{value:stream._readableState.endEmitted,writable:!0}),_defineProperty(_Object$create,kHandlePromise,{value:function value(resolve,reject){var data=iterator[kStream].read();data?(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,resolve(createIterResult(data,!1))):(iterator[kLastResolve]=resolve,iterator[kLastReject]=reject)},writable:!0}),_Object$create));return iterator[kLastPromise]=null,finished(stream,(function(err){if(err&&"ERR_STREAM_PREMATURE_CLOSE"!==err.code){var reject=iterator[kLastReject];return null!==reject&&(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,reject(err)),void(iterator[kError]=err)}var resolve=iterator[kLastResolve];null!==resolve&&(iterator[kLastPromise]=null,iterator[kLastResolve]=null,iterator[kLastReject]=null,resolve(createIterResult(void 0,!0))),iterator[kEnded]=!0})),stream.on("readable",onReadable.bind(null,iterator)),iterator}},7327:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))),keys.push.apply(keys,symbols)}return keys}function _defineProperty(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function _defineProperties(target,props){for(var i=0;i0?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length}},{key:"unshift",value:function unshift(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length}},{key:"shift",value:function shift(){if(0!==this.length){var ret=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,ret}}},{key:"clear",value:function clear(){this.head=this.tail=null,this.length=0}},{key:"join",value:function join(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret}},{key:"concat",value:function concat(n){if(0===this.length)return Buffer.alloc(0);for(var src,target,offset,ret=Buffer.allocUnsafe(n>>>0),p=this.head,i=0;p;)src=p.data,target=ret,offset=i,Buffer.prototype.copy.call(src,target,offset),i+=p.data.length,p=p.next;return ret}},{key:"consume",value:function consume(n,hasStrings){var ret;return nstr.length?str.length:n;if(nb===str.length?ret+=str:ret+=str.slice(0,n),0===(n-=nb)){nb===str.length?(++c,p.next?this.head=p.next:this.head=this.tail=null):(this.head=p,p.data=str.slice(nb));break}++c}return this.length-=c,ret}},{key:"_getBuffer",value:function _getBuffer(n){var ret=Buffer.allocUnsafe(n),p=this.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),0===(n-=nb)){nb===buf.length?(++c,p.next?this.head=p.next:this.head=this.tail=null):(this.head=p,p.data=buf.slice(nb));break}++c}return this.length-=c,ret}},{key:custom,value:function value(_,options){return inspect(this,function _objectSpread(target){for(var i=1;i{"use strict";function emitErrorAndCloseNT(self,err){emitErrorNT(self,err),emitCloseNT(self)}function emitCloseNT(self){self._writableState&&!self._writableState.emitClose||self._readableState&&!self._readableState.emitClose||self.emit("close")}function emitErrorNT(self,err){self.emit("error",err)}module.exports={destroy:function destroy(err,cb){var _this=this,readableDestroyed=this._readableState&&this._readableState.destroyed,writableDestroyed=this._writableState&&this._writableState.destroyed;return readableDestroyed||writableDestroyed?(cb?cb(err):err&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(emitErrorNT,this,err)):process.nextTick(emitErrorNT,this,err)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(err||null,(function(err){!cb&&err?_this._writableState?_this._writableState.errorEmitted?process.nextTick(emitCloseNT,_this):(_this._writableState.errorEmitted=!0,process.nextTick(emitErrorAndCloseNT,_this,err)):process.nextTick(emitErrorAndCloseNT,_this,err):cb?(process.nextTick(emitCloseNT,_this),cb(err)):process.nextTick(emitCloseNT,_this)})),this)},undestroy:function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function errorOrDestroy(stream,err){var rState=stream._readableState,wState=stream._writableState;rState&&rState.autoDestroy||wState&&wState.autoDestroy?stream.destroy(err):stream.emit("error",err)}}},8610:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var ERR_STREAM_PREMATURE_CLOSE=__webpack_require__(4281).q.ERR_STREAM_PREMATURE_CLOSE;function noop(){}module.exports=function eos(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=function once(callback){var called=!1;return function(){if(!called){called=!0;for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];callback.apply(this,args)}}}(callback||noop);var readable=opts.readable||!1!==opts.readable&&stream.readable,writable=opts.writable||!1!==opts.writable&&stream.writable,onlegacyfinish=function onlegacyfinish(){stream.writable||onfinish()},writableEnded=stream._writableState&&stream._writableState.finished,onfinish=function onfinish(){writable=!1,writableEnded=!0,readable||callback.call(stream)},readableEnded=stream._readableState&&stream._readableState.endEmitted,onend=function onend(){readable=!1,readableEnded=!0,writable||callback.call(stream)},onerror=function onerror(err){callback.call(stream,err)},onclose=function onclose(){var err;return readable&&!readableEnded?(stream._readableState&&stream._readableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):writable&&!writableEnded?(stream._writableState&&stream._writableState.ended||(err=new ERR_STREAM_PREMATURE_CLOSE),callback.call(stream,err)):void 0},onrequest=function onrequest(){stream.req.on("finish",onfinish)};return!function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}(stream)?writable&&!stream._writableState&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)):(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)),stream.on("end",onend),stream.on("finish",onfinish),!1!==opts.error&&stream.on("error",onerror),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("end",onend),stream.removeListener("error",onerror),stream.removeListener("close",onclose)}}},5167:module=>{module.exports=function(){throw new Error("Readable.from is not available in the browser")}},9946:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var eos;var _require$codes=__webpack_require__(4281).q,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED;function noop(err){if(err)throw err}function destroyer(stream,reading,writing,callback){callback=function once(callback){var called=!1;return function(){called||(called=!0,callback.apply(void 0,arguments))}}(callback);var closed=!1;stream.on("close",(function(){closed=!0})),void 0===eos&&(eos=__webpack_require__(8610)),eos(stream,{readable:reading,writable:writing},(function(err){if(err)return callback(err);closed=!0,callback()}));var destroyed=!1;return function(err){if(!closed&&!destroyed)return destroyed=!0,function isRequest(stream){return stream.setHeader&&"function"==typeof stream.abort}(stream)?stream.abort():"function"==typeof stream.destroy?stream.destroy():void callback(err||new ERR_STREAM_DESTROYED("pipe"))}}function call(fn){fn()}function pipe(from,to){return from.pipe(to)}function popCallback(streams){return streams.length?"function"!=typeof streams[streams.length-1]?noop:streams.pop():noop}module.exports=function pipeline(){for(var _len=arguments.length,streams=new Array(_len),_key=0;_key<_len;_key++)streams[_key]=arguments[_key];var error,callback=popCallback(streams);if(Array.isArray(streams[0])&&(streams=streams[0]),streams.length<2)throw new ERR_MISSING_ARGS("streams");var destroys=streams.map((function(stream,i){var reading=i0,(function(err){error||(error=err),err&&destroys.forEach(call),reading||(destroys.forEach(call),callback(error))}))}));return streams.reduce(pipe)}},2457:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var ERR_INVALID_OPT_VALUE=__webpack_require__(4281).q.ERR_INVALID_OPT_VALUE;module.exports={getHighWaterMark:function getHighWaterMark(state,options,duplexKey,isDuplex){var hwm=function highWaterMarkFrom(options,isDuplex,duplexKey){return null!=options.highWaterMark?options.highWaterMark:isDuplex?options[duplexKey]:null}(options,isDuplex,duplexKey);if(null!=hwm){if(!isFinite(hwm)||Math.floor(hwm)!==hwm||hwm<0)throw new ERR_INVALID_OPT_VALUE(isDuplex?duplexKey:"highWaterMark",hwm);return Math.floor(hwm)}return state.objectMode?16:16384}}},2503:(module,__unused_webpack_exports,__webpack_require__)=>{module.exports=__webpack_require__(7187).EventEmitter},8473:(module,exports,__webpack_require__)=>{(exports=module.exports=__webpack_require__(9481)).Stream=exports,exports.Readable=exports,exports.Writable=__webpack_require__(4229),exports.Duplex=__webpack_require__(6753),exports.Transform=__webpack_require__(4605),exports.PassThrough=__webpack_require__(2725),exports.finished=__webpack_require__(8610),exports.pipeline=__webpack_require__(9946)},9785:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var Buffer=__webpack_require__(8764).Buffer,inherits=__webpack_require__(5717),HashBase=__webpack_require__(3349),ARRAY16=new Array(16),zl=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],zr=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],sl=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],sr=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],hl=[0,1518500249,1859775393,2400959708,2840853838],hr=[1352829926,1548603684,1836072691,2053994217,0];function RIPEMD160(){HashBase.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function rotl(x,n){return x<>>32-n}function fn1(a,b,c,d,e,m,k,s){return rotl(a+(b^c^d)+m+k|0,s)+e|0}function fn2(a,b,c,d,e,m,k,s){return rotl(a+(b&c|~b&d)+m+k|0,s)+e|0}function fn3(a,b,c,d,e,m,k,s){return rotl(a+((b|~c)^d)+m+k|0,s)+e|0}function fn4(a,b,c,d,e,m,k,s){return rotl(a+(b&d|c&~d)+m+k|0,s)+e|0}function fn5(a,b,c,d,e,m,k,s){return rotl(a+(b^(c|~d))+m+k|0,s)+e|0}inherits(RIPEMD160,HashBase),RIPEMD160.prototype._update=function(){for(var words=ARRAY16,j=0;j<16;++j)words[j]=this._block.readInt32LE(4*j);for(var al=0|this._a,bl=0|this._b,cl=0|this._c,dl=0|this._d,el=0|this._e,ar=0|this._a,br=0|this._b,cr=0|this._c,dr=0|this._d,er=0|this._e,i=0;i<80;i+=1){var tl,tr;i<16?(tl=fn1(al,bl,cl,dl,el,words[zl[i]],hl[0],sl[i]),tr=fn5(ar,br,cr,dr,er,words[zr[i]],hr[0],sr[i])):i<32?(tl=fn2(al,bl,cl,dl,el,words[zl[i]],hl[1],sl[i]),tr=fn4(ar,br,cr,dr,er,words[zr[i]],hr[1],sr[i])):i<48?(tl=fn3(al,bl,cl,dl,el,words[zl[i]],hl[2],sl[i]),tr=fn3(ar,br,cr,dr,er,words[zr[i]],hr[2],sr[i])):i<64?(tl=fn4(al,bl,cl,dl,el,words[zl[i]],hl[3],sl[i]),tr=fn2(ar,br,cr,dr,er,words[zr[i]],hr[3],sr[i])):(tl=fn5(al,bl,cl,dl,el,words[zl[i]],hl[4],sl[i]),tr=fn1(ar,br,cr,dr,er,words[zr[i]],hr[4],sr[i])),al=el,el=dl,dl=rotl(cl,10),cl=bl,bl=tl,ar=er,er=dr,dr=rotl(cr,10),cr=br,br=tr}var t=this._b+cl+dr|0;this._b=this._c+dl+er|0,this._c=this._d+el+ar|0,this._d=this._e+al+br|0,this._e=this._a+bl+cr|0,this._a=t},RIPEMD160.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var buffer=Buffer.alloc?Buffer.alloc(20):new Buffer(20);return buffer.writeInt32LE(this._a,0),buffer.writeInt32LE(this._b,4),buffer.writeInt32LE(this._c,8),buffer.writeInt32LE(this._d,12),buffer.writeInt32LE(this._e,16),buffer},module.exports=RIPEMD160},9509:(module,exports,__webpack_require__)=>{var buffer=__webpack_require__(8764),Buffer=buffer.Buffer;function copyProps(src,dst){for(var key in src)dst[key]=src[key]}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),SafeBuffer.prototype=Object.create(Buffer.prototype),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(arg,encodingOrOffset,length){if("number"==typeof arg)throw new TypeError("Argument must not be a number");return Buffer(arg,encodingOrOffset,length)},SafeBuffer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError("Argument must be a number");var buf=Buffer(size);return void 0!==fill?"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf},SafeBuffer.allocUnsafe=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return Buffer(size)},SafeBuffer.allocUnsafeSlow=function(size){if("number"!=typeof size)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(size)}},2399:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var key,buffer=__webpack_require__(8764),Buffer=buffer.Buffer,safer={};for(key in buffer)buffer.hasOwnProperty(key)&&"SlowBuffer"!==key&&"Buffer"!==key&&(safer[key]=buffer[key]);var Safer=safer.Buffer={};for(key in Buffer)Buffer.hasOwnProperty(key)&&"allocUnsafe"!==key&&"allocUnsafeSlow"!==key&&(Safer[key]=Buffer[key]);if(safer.Buffer.prototype=Buffer.prototype,Safer.from&&Safer.from!==Uint8Array.from||(Safer.from=function(value,encodingOrOffset,length){if("number"==typeof value)throw new TypeError('The "value" argument must not be of type number. Received type '+typeof value);if(value&&void 0===value.length)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value);return Buffer(value,encodingOrOffset,length)}),Safer.alloc||(Safer.alloc=function(size,fill,encoding){if("number"!=typeof size)throw new TypeError('The "size" argument must be of type number. Received type '+typeof size);if(size<0||size>=2*(1<<30))throw new RangeError('The value "'+size+'" is invalid for option "size"');var buf=Buffer(size);return fill&&0!==fill.length?"string"==typeof encoding?buf.fill(fill,encoding):buf.fill(fill):buf.fill(0),buf}),!safer.kStringMaxLength)try{safer.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch(e){}safer.constants||(safer.constants={MAX_LENGTH:safer.kMaxLength},safer.kStringMaxLength&&(safer.constants.MAX_STRING_LENGTH=safer.kStringMaxLength)),module.exports=safer},7635:function(module){"use strict";!function(root){function SHA256(m){const K=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);let h0=1779033703,h1=3144134277,h2=1013904242,h3=2773480762,h4=1359893119,h5=2600822924,h6=528734635,h7=1541459225;const w=new Uint32Array(64);function blocks(p){let off=0,len=p.length;for(;len>=64;){let u,i,j,t1,t2,a=h0,b=h1,c=h2,d=h3,e=h4,f=h5,g=h6,h=h7;for(i=0;i<16;i++)j=off+4*i,w[i]=(255&p[j])<<24|(255&p[j+1])<<16|(255&p[j+2])<<8|255&p[j+3];for(i=16;i<64;i++)u=w[i-2],t1=(u>>>17|u<<15)^(u>>>19|u<<13)^u>>>10,u=w[i-15],t2=(u>>>7|u<<25)^(u>>>18|u<<14)^u>>>3,w[i]=(t1+w[i-7]|0)+(t2+w[i-16]|0)|0;for(i=0;i<64;i++)t1=(((e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7))+(e&f^~e&g)|0)+(h+(K[i]+w[i]|0)|0)|0,t2=((a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10))+(a&b^a&c^b&c)|0,h=g,g=f,f=e,e=d+t1|0,d=c,c=b,b=a,a=t1+t2|0;h0=h0+a|0,h1=h1+b|0,h2=h2+c|0,h3=h3+d|0,h4=h4+e|0,h5=h5+f|0,h6=h6+g|0,h7=h7+h|0,off+=64,len-=64}}blocks(m);let i,bytesLeft=m.length%64,bitLenHi=m.length/536870912|0,bitLenLo=m.length<<3,numZeros=bytesLeft<56?56:120,p=m.slice(m.length-bytesLeft,m.length);for(p.push(128),i=bytesLeft+1;i>>24&255),p.push(bitLenHi>>>16&255),p.push(bitLenHi>>>8&255),p.push(bitLenHi>>>0&255),p.push(bitLenLo>>>24&255),p.push(bitLenLo>>>16&255),p.push(bitLenLo>>>8&255),p.push(bitLenLo>>>0&255),blocks(p),[h0>>>24&255,h0>>>16&255,h0>>>8&255,h0>>>0&255,h1>>>24&255,h1>>>16&255,h1>>>8&255,h1>>>0&255,h2>>>24&255,h2>>>16&255,h2>>>8&255,h2>>>0&255,h3>>>24&255,h3>>>16&255,h3>>>8&255,h3>>>0&255,h4>>>24&255,h4>>>16&255,h4>>>8&255,h4>>>0&255,h5>>>24&255,h5>>>16&255,h5>>>8&255,h5>>>0&255,h6>>>24&255,h6>>>16&255,h6>>>8&255,h6>>>0&255,h7>>>24&255,h7>>>16&255,h7>>>8&255,h7>>>0&255]}function PBKDF2_HMAC_SHA256_OneIter(password,salt,dkLen){password=password.length<=64?password:SHA256(password);const innerLen=64+salt.length+4,inner=new Array(innerLen),outerKey=new Array(64);let i,dk=[];for(i=0;i<64;i++)inner[i]=54;for(i=0;i=innerLen-4;i--){if(inner[i]++,inner[i]<=255)return;inner[i]=0}}for(;dkLen>=32;)incrementCounter(),dk=dk.concat(SHA256(outerKey.concat(SHA256(inner)))),dkLen-=32;return dkLen>0&&(incrementCounter(),dk=dk.concat(SHA256(outerKey.concat(SHA256(inner))).slice(0,dkLen))),dk}function blockmix_salsa8(BY,Yi,r,x,_X){let i;for(arraycopy(BY,16*(2*r-1),_X,0,16),i=0;i<2*r;i++)blockxor(BY,16*i,_X,16),salsa20_8(_X,x),arraycopy(_X,0,BY,Yi+16*i,16);for(i=0;i>>32-b}function salsa20_8(B,x){arraycopy(B,0,x,0,16);for(let i=8;i>0;i-=2)x[4]^=R(x[0]+x[12],7),x[8]^=R(x[4]+x[0],9),x[12]^=R(x[8]+x[4],13),x[0]^=R(x[12]+x[8],18),x[9]^=R(x[5]+x[1],7),x[13]^=R(x[9]+x[5],9),x[1]^=R(x[13]+x[9],13),x[5]^=R(x[1]+x[13],18),x[14]^=R(x[10]+x[6],7),x[2]^=R(x[14]+x[10],9),x[6]^=R(x[2]+x[14],13),x[10]^=R(x[6]+x[2],18),x[3]^=R(x[15]+x[11],7),x[7]^=R(x[3]+x[15],9),x[11]^=R(x[7]+x[3],13),x[15]^=R(x[11]+x[7],18),x[1]^=R(x[0]+x[3],7),x[2]^=R(x[1]+x[0],9),x[3]^=R(x[2]+x[1],13),x[0]^=R(x[3]+x[2],18),x[6]^=R(x[5]+x[4],7),x[7]^=R(x[6]+x[5],9),x[4]^=R(x[7]+x[6],13),x[5]^=R(x[4]+x[7],18),x[11]^=R(x[10]+x[9],7),x[8]^=R(x[11]+x[10],9),x[9]^=R(x[8]+x[11],13),x[10]^=R(x[9]+x[8],18),x[12]^=R(x[15]+x[14],7),x[13]^=R(x[12]+x[15],9),x[14]^=R(x[13]+x[12],13),x[15]^=R(x[14]+x[13],18);for(let i=0;i<16;++i)B[i]+=x[i]}function blockxor(S,Si,D,len){for(let i=0;i=256)return!1}return!0}function ensureInteger(value,name){if("number"!=typeof value||value%1)throw new Error("invalid "+name);return value}function _scrypt(password,salt,N,r,p,dkLen,callback){if(N=ensureInteger(N,"N"),r=ensureInteger(r,"r"),p=ensureInteger(p,"p"),dkLen=ensureInteger(dkLen,"dkLen"),0===N||0!=(N&N-1))throw new Error("N must be power of 2");if(N>2147483647/128/r)throw new Error("N too large");if(r>2147483647/128/p)throw new Error("r too large");if(!checkBufferish(password))throw new Error("password must be an array or buffer");if(password=Array.prototype.slice.call(password),!checkBufferish(salt))throw new Error("salt must be an array or buffer");salt=Array.prototype.slice.call(salt);let b=PBKDF2_HMAC_SHA256_OneIter(password,salt,128*p*r);const B=new Uint32Array(32*p*r);for(let i=0;ilimit&&(steps=limit);for(let i=0;ilimit&&(steps=limit);for(let i=0;i>0&255),b.push(B[i]>>8&255),b.push(B[i]>>16&255),b.push(B[i]>>24&255);const derivedKey=PBKDF2_HMAC_SHA256_OneIter(password,b,dkLen);return callback&&callback(null,1,derivedKey),derivedKey}callback&&nextTick(incrementalSMix)};if(!callback)for(;;){const derivedKey=incrementalSMix();if(null!=derivedKey)return derivedKey}incrementalSMix()}const lib={scrypt:function(password,salt,N,r,p,dkLen,progressCallback){return new Promise((function(resolve,reject){let lastProgress=0;progressCallback&&progressCallback(0),_scrypt(password,salt,N,r,p,dkLen,(function(error,progress,key){if(error)reject(error);else if(key)progressCallback&&1!==lastProgress&&progressCallback(1),resolve(new Uint8Array(key));else if(progressCallback&&progress!==lastProgress)return lastProgress=progress,progressCallback(progress)}))}))},syncScrypt:function(password,salt,N,r,p,dkLen){return new Uint8Array(_scrypt(password,salt,N,r,p,dkLen))}};module.exports=lib}()},7221:(module,__unused_webpack_exports,__webpack_require__)=>{module.exports=__webpack_require__(9119)(__webpack_require__(8573))},8573:(module,__unused_webpack_exports,__webpack_require__)=>{const ec=new(0,__webpack_require__(6266).ec)("secp256k1"),ecparams=ec.curve,BN=ecparams.n.constructor;function loadPublicKey(pubkey){const first=pubkey[0];switch(first){case 2:case 3:return 33!==pubkey.length?null:function loadCompressedPublicKey(first,xbuf){let x=new BN(xbuf);if(x.cmp(ecparams.p)>=0)return null;x=x.toRed(ecparams.red);let y=x.redSqr().redIMul(x).redIAdd(ecparams.b).redSqrt();return 3===first!==y.isOdd()&&(y=y.redNeg()),ec.keyPair({pub:{x,y}})}(first,pubkey.subarray(1,33));case 4:case 6:case 7:return 65!==pubkey.length?null:function loadUncompressedPublicKey(first,xbuf,ybuf){let x=new BN(xbuf),y=new BN(ybuf);if(x.cmp(ecparams.p)>=0||y.cmp(ecparams.p)>=0)return null;if(x=x.toRed(ecparams.red),y=y.toRed(ecparams.red),(6===first||7===first)&&y.isOdd()!==(7===first))return null;const x3=x.redSqr().redIMul(x);return y.redSqr().redISub(x3.redIAdd(ecparams.b)).isZero()?ec.keyPair({pub:{x,y}}):null}(first,pubkey.subarray(1,33),pubkey.subarray(33,65));default:return null}}function savePublicKey(output,point){const pubkey=point.encode(null,33===output.length);for(let i=0;i0,privateKeyVerify(seckey){const bn=new BN(seckey);return bn.cmp(ecparams.n)<0&&!bn.isZero()?0:1},privateKeyNegate(seckey){const bn=new BN(seckey),negate=ecparams.n.sub(bn).umod(ecparams.n).toArrayLike(Uint8Array,"be",32);return seckey.set(negate),0},privateKeyTweakAdd(seckey,tweak){const bn=new BN(tweak);if(bn.cmp(ecparams.n)>=0)return 1;if(bn.iadd(new BN(seckey)),bn.cmp(ecparams.n)>=0&&bn.isub(ecparams.n),bn.isZero())return 1;const tweaked=bn.toArrayLike(Uint8Array,"be",32);return seckey.set(tweaked),0},privateKeyTweakMul(seckey,tweak){let bn=new BN(tweak);if(bn.cmp(ecparams.n)>=0||bn.isZero())return 1;bn.imul(new BN(seckey)),bn.cmp(ecparams.n)>=0&&(bn=bn.umod(ecparams.n));const tweaked=bn.toArrayLike(Uint8Array,"be",32);return seckey.set(tweaked),0},publicKeyVerify:pubkey=>null===loadPublicKey(pubkey)?1:0,publicKeyCreate(output,seckey){const bn=new BN(seckey);if(bn.cmp(ecparams.n)>=0||bn.isZero())return 1;return savePublicKey(output,ec.keyFromPrivate(seckey).getPublic()),0},publicKeyConvert(output,pubkey){const pair=loadPublicKey(pubkey);if(null===pair)return 1;return savePublicKey(output,pair.getPublic()),0},publicKeyNegate(output,pubkey){const pair=loadPublicKey(pubkey);if(null===pair)return 1;const point=pair.getPublic();return point.y=point.y.redNeg(),savePublicKey(output,point),0},publicKeyCombine(output,pubkeys){const pairs=new Array(pubkeys.length);for(let i=0;i=0)return 2;const point=pair.getPublic().add(ecparams.g.mul(tweak));return point.isInfinity()?2:(savePublicKey(output,point),0)},publicKeyTweakMul(output,pubkey,tweak){const pair=loadPublicKey(pubkey);if(null===pair)return 1;if((tweak=new BN(tweak)).cmp(ecparams.n)>=0||tweak.isZero())return 2;return savePublicKey(output,pair.getPublic().mul(tweak)),0},signatureNormalize(sig){const r=new BN(sig.subarray(0,32)),s=new BN(sig.subarray(32,64));return r.cmp(ecparams.n)>=0||s.cmp(ecparams.n)>=0?1:(1===s.cmp(ec.nh)&&sig.set(ecparams.n.sub(s).toArrayLike(Uint8Array,"be",32),32),0)},signatureExport(obj,sig){const sigR=sig.subarray(0,32),sigS=sig.subarray(32,64);if(new BN(sigR).cmp(ecparams.n)>=0)return 1;if(new BN(sigS).cmp(ecparams.n)>=0)return 1;const{output}=obj;let r=output.subarray(4,37);r[0]=0,r.set(sigR,1);let lenR=33,posR=0;for(;lenR>1&&0===r[posR]&&!(128&r[posR+1]);--lenR,++posR);if(r=r.subarray(posR),128&r[0])return 1;if(lenR>1&&0===r[0]&&!(128&r[1]))return 1;let s=output.subarray(39,72);s[0]=0,s.set(sigS,1);let lenS=33,posS=0;for(;lenS>1&&0===s[posS]&&!(128&s[posS+1]);--lenS,++posS);return s=s.subarray(posS),128&s[0]||lenS>1&&0===s[0]&&!(128&s[1])?1:(obj.outputlen=6+lenR+lenS,output[0]=48,output[1]=obj.outputlen-2,output[2]=2,output[3]=r.length,output.set(r,4),output[4+lenR]=2,output[5+lenR]=s.length,output.set(s,6+lenR),0)},signatureImport(output,sig){if(sig.length<8)return 1;if(sig.length>72)return 1;if(48!==sig[0])return 1;if(sig[1]!==sig.length-2)return 1;if(2!==sig[2])return 1;const lenR=sig[3];if(0===lenR)return 1;if(5+lenR>=sig.length)return 1;if(2!==sig[4+lenR])return 1;const lenS=sig[5+lenR];if(0===lenS)return 1;if(6+lenR+lenS!==sig.length)return 1;if(128&sig[4])return 1;if(lenR>1&&0===sig[4]&&!(128&sig[5]))return 1;if(128&sig[lenR+6])return 1;if(lenS>1&&0===sig[lenR+6]&&!(128&sig[lenR+7]))return 1;let sigR=sig.subarray(4,4+lenR);if(33===sigR.length&&0===sigR[0]&&(sigR=sigR.subarray(1)),sigR.length>32)return 1;let sigS=sig.subarray(6+lenR);if(33===sigS.length&&0===sigS[0]&&(sigS=sigS.slice(1)),sigS.length>32)throw new Error("S length is too long");let r=new BN(sigR);r.cmp(ecparams.n)>=0&&(r=new BN(0));let s=new BN(sig.subarray(6+lenR));return s.cmp(ecparams.n)>=0&&(s=new BN(0)),output.set(r.toArrayLike(Uint8Array,"be",32),0),output.set(s.toArrayLike(Uint8Array,"be",32),32),0},ecdsaSign(obj,message,seckey,data,noncefn){if(noncefn){const _noncefn=noncefn;noncefn=counter=>{const nonce=_noncefn(message,seckey,null,data,counter);if(!(nonce instanceof Uint8Array&&32===nonce.length))throw new Error("This is the way");return new BN(nonce)}}const d=new BN(seckey);if(d.cmp(ecparams.n)>=0||d.isZero())return 1;let sig;try{sig=ec.sign(message,seckey,{canonical:!0,k:noncefn,pers:data})}catch(err){return 1}return obj.signature.set(sig.r.toArrayLike(Uint8Array,"be",32),0),obj.signature.set(sig.s.toArrayLike(Uint8Array,"be",32),32),obj.recid=sig.recoveryParam,0},ecdsaVerify(sig,msg32,pubkey){const sigObj={r:sig.subarray(0,32),s:sig.subarray(32,64)},sigr=new BN(sigObj.r),sigs=new BN(sigObj.s);if(sigr.cmp(ecparams.n)>=0||sigs.cmp(ecparams.n)>=0)return 1;if(1===sigs.cmp(ec.nh)||sigr.isZero()||sigs.isZero())return 3;const pair=loadPublicKey(pubkey);if(null===pair)return 2;const point=pair.getPublic();return ec.verify(msg32,sigObj,point)?0:3},ecdsaRecover(output,sig,recid,msg32){const sigObj={r:sig.slice(0,32),s:sig.slice(32,64)},sigr=new BN(sigObj.r),sigs=new BN(sigObj.s);if(sigr.cmp(ecparams.n)>=0||sigs.cmp(ecparams.n)>=0)return 1;if(sigr.isZero()||sigs.isZero())return 2;let point;try{point=ec.recoverPubKey(msg32,sigObj,recid)}catch(err){return 2}return savePublicKey(output,point),0},ecdh(output,pubkey,seckey,data,hashfn,xbuf,ybuf){const pair=loadPublicKey(pubkey);if(null===pair)return 1;const scalar=new BN(seckey);if(scalar.cmp(ecparams.n)>=0||scalar.isZero())return 2;const point=pair.getPublic().mul(scalar);if(void 0===hashfn){const data=point.encode(null,!0),sha256=ec.hash().update(data).digest();for(let i=0;i<32;++i)output[i]=sha256[i]}else{xbuf||(xbuf=new Uint8Array(32));const x=point.getX().toArray("be",32);for(let i=0;i<32;++i)xbuf[i]=x[i];ybuf||(ybuf=new Uint8Array(32));const y=point.getY().toArray("be",32);for(let i=0;i<32;++i)ybuf[i]=y[i];const hash=hashfn(xbuf,ybuf,data);if(!(hash instanceof Uint8Array&&hash.length===output.length))return 2;output.set(hash)}return 0}}},9119:module=>{const errors_IMPOSSIBLE_CASE="Impossible case. Please create issue.",errors_TWEAK_ADD="The tweak was out of range or the resulted private key is invalid",errors_TWEAK_MUL="The tweak was out of range or equal to zero",errors_CONTEXT_RANDOMIZE_UNKNOW="Unknow error on context randomization",errors_SECKEY_INVALID="Private Key is invalid",errors_PUBKEY_PARSE="Public Key could not be parsed",errors_PUBKEY_SERIALIZE="Public Key serialization error",errors_PUBKEY_COMBINE="The sum of the public keys is not valid",errors_SIG_PARSE="Signature could not be parsed",errors_SIGN="The nonce generation function failed, or the private key was invalid",errors_RECOVER="Public key could not be recover",errors_ECDH="Scalar was invalid (zero or overflow)";function assert(cond,msg){if(!cond)throw new Error(msg)}function isUint8Array(name,value,length){if(assert(value instanceof Uint8Array,`Expected ${name} to be an Uint8Array`),void 0!==length)if(Array.isArray(length)){const msg=`Expected ${name} to be an Uint8Array with length [${length.join(", ")}]`;assert(length.includes(value.length),msg)}else{const msg=`Expected ${name} to be an Uint8Array with length ${length}`;assert(value.length===length,msg)}}function isCompressed(value){assert("Boolean"===toTypeString(value),"Expected compressed to be a Boolean")}function getAssertedOutput(output=(len=>new Uint8Array(len)),length){return"function"==typeof output&&(output=output(length)),isUint8Array("output",output,length),output}function toTypeString(value){return Object.prototype.toString.call(value).slice(8,-1)}module.exports=secp256k1=>({contextRandomize(seed){if(assert(null===seed||seed instanceof Uint8Array,"Expected seed to be an Uint8Array or null"),null!==seed&&isUint8Array("seed",seed,32),1===secp256k1.contextRandomize(seed))throw new Error(errors_CONTEXT_RANDOMIZE_UNKNOW)},privateKeyVerify:seckey=>(isUint8Array("private key",seckey,32),0===secp256k1.privateKeyVerify(seckey)),privateKeyNegate(seckey){switch(isUint8Array("private key",seckey,32),secp256k1.privateKeyNegate(seckey)){case 0:return seckey;case 1:throw new Error(errors_IMPOSSIBLE_CASE)}},privateKeyTweakAdd(seckey,tweak){switch(isUint8Array("private key",seckey,32),isUint8Array("tweak",tweak,32),secp256k1.privateKeyTweakAdd(seckey,tweak)){case 0:return seckey;case 1:throw new Error(errors_TWEAK_ADD)}},privateKeyTweakMul(seckey,tweak){switch(isUint8Array("private key",seckey,32),isUint8Array("tweak",tweak,32),secp256k1.privateKeyTweakMul(seckey,tweak)){case 0:return seckey;case 1:throw new Error(errors_TWEAK_MUL)}},publicKeyVerify:pubkey=>(isUint8Array("public key",pubkey,[33,65]),0===secp256k1.publicKeyVerify(pubkey)),publicKeyCreate(seckey,compressed=!0,output){switch(isUint8Array("private key",seckey,32),isCompressed(compressed),output=getAssertedOutput(output,compressed?33:65),secp256k1.publicKeyCreate(output,seckey)){case 0:return output;case 1:throw new Error(errors_SECKEY_INVALID);case 2:throw new Error(errors_PUBKEY_SERIALIZE)}},publicKeyConvert(pubkey,compressed=!0,output){switch(isUint8Array("public key",pubkey,[33,65]),isCompressed(compressed),output=getAssertedOutput(output,compressed?33:65),secp256k1.publicKeyConvert(output,pubkey)){case 0:return output;case 1:throw new Error(errors_PUBKEY_PARSE);case 2:throw new Error(errors_PUBKEY_SERIALIZE)}},publicKeyNegate(pubkey,compressed=!0,output){switch(isUint8Array("public key",pubkey,[33,65]),isCompressed(compressed),output=getAssertedOutput(output,compressed?33:65),secp256k1.publicKeyNegate(output,pubkey)){case 0:return output;case 1:throw new Error(errors_PUBKEY_PARSE);case 2:throw new Error(errors_IMPOSSIBLE_CASE);case 3:throw new Error(errors_PUBKEY_SERIALIZE)}},publicKeyCombine(pubkeys,compressed=!0,output){assert(Array.isArray(pubkeys),"Expected public keys to be an Array"),assert(pubkeys.length>0,"Expected public keys array will have more than zero items");for(const pubkey of pubkeys)isUint8Array("public key",pubkey,[33,65]);switch(isCompressed(compressed),output=getAssertedOutput(output,compressed?33:65),secp256k1.publicKeyCombine(output,pubkeys)){case 0:return output;case 1:throw new Error(errors_PUBKEY_PARSE);case 2:throw new Error(errors_PUBKEY_COMBINE);case 3:throw new Error(errors_PUBKEY_SERIALIZE)}},publicKeyTweakAdd(pubkey,tweak,compressed=!0,output){switch(isUint8Array("public key",pubkey,[33,65]),isUint8Array("tweak",tweak,32),isCompressed(compressed),output=getAssertedOutput(output,compressed?33:65),secp256k1.publicKeyTweakAdd(output,pubkey,tweak)){case 0:return output;case 1:throw new Error(errors_PUBKEY_PARSE);case 2:throw new Error(errors_TWEAK_ADD)}},publicKeyTweakMul(pubkey,tweak,compressed=!0,output){switch(isUint8Array("public key",pubkey,[33,65]),isUint8Array("tweak",tweak,32),isCompressed(compressed),output=getAssertedOutput(output,compressed?33:65),secp256k1.publicKeyTweakMul(output,pubkey,tweak)){case 0:return output;case 1:throw new Error(errors_PUBKEY_PARSE);case 2:throw new Error(errors_TWEAK_MUL)}},signatureNormalize(sig){switch(isUint8Array("signature",sig,64),secp256k1.signatureNormalize(sig)){case 0:return sig;case 1:throw new Error(errors_SIG_PARSE)}},signatureExport(sig,output){isUint8Array("signature",sig,64);const obj={output:output=getAssertedOutput(output,72),outputlen:72};switch(secp256k1.signatureExport(obj,sig)){case 0:return output.slice(0,obj.outputlen);case 1:throw new Error(errors_SIG_PARSE);case 2:throw new Error(errors_IMPOSSIBLE_CASE)}},signatureImport(sig,output){switch(isUint8Array("signature",sig),output=getAssertedOutput(output,64),secp256k1.signatureImport(output,sig)){case 0:return output;case 1:throw new Error(errors_SIG_PARSE);case 2:throw new Error(errors_IMPOSSIBLE_CASE)}},ecdsaSign(msg32,seckey,options={},output){isUint8Array("message",msg32,32),isUint8Array("private key",seckey,32),assert("Object"===toTypeString(options),"Expected options to be an Object"),void 0!==options.data&&isUint8Array("options.data",options.data),void 0!==options.noncefn&&assert("Function"===toTypeString(options.noncefn),"Expected options.noncefn to be a Function");const obj={signature:output=getAssertedOutput(output,64),recid:null};switch(secp256k1.ecdsaSign(obj,msg32,seckey,options.data,options.noncefn)){case 0:return obj;case 1:throw new Error(errors_SIGN);case 2:throw new Error(errors_IMPOSSIBLE_CASE)}},ecdsaVerify(sig,msg32,pubkey){switch(isUint8Array("signature",sig,64),isUint8Array("message",msg32,32),isUint8Array("public key",pubkey,[33,65]),secp256k1.ecdsaVerify(sig,msg32,pubkey)){case 0:return!0;case 3:return!1;case 1:throw new Error(errors_SIG_PARSE);case 2:throw new Error(errors_PUBKEY_PARSE)}},ecdsaRecover(sig,recid,msg32,compressed=!0,output){switch(isUint8Array("signature",sig,64),assert("Number"===toTypeString(recid)&&recid>=0&&recid<=3,"Expected recovery id to be a Number within interval [0, 3]"),isUint8Array("message",msg32,32),isCompressed(compressed),output=getAssertedOutput(output,compressed?33:65),secp256k1.ecdsaRecover(output,sig,recid,msg32)){case 0:return output;case 1:throw new Error(errors_SIG_PARSE);case 2:throw new Error(errors_RECOVER);case 3:throw new Error(errors_IMPOSSIBLE_CASE)}},ecdh(pubkey,seckey,options={},output){switch(isUint8Array("public key",pubkey,[33,65]),isUint8Array("private key",seckey,32),assert("Object"===toTypeString(options),"Expected options to be an Object"),void 0!==options.data&&isUint8Array("options.data",options.data),void 0!==options.hashfn?(assert("Function"===toTypeString(options.hashfn),"Expected options.hashfn to be a Function"),void 0!==options.xbuf&&isUint8Array("options.xbuf",options.xbuf,32),void 0!==options.ybuf&&isUint8Array("options.ybuf",options.ybuf,32),isUint8Array("output",output)):output=getAssertedOutput(output,32),secp256k1.ecdh(output,pubkey,seckey,options.data,options.hashfn,options.xbuf,options.ybuf)){case 0:return output;case 1:throw new Error(errors_PUBKEY_PARSE);case 2:throw new Error(errors_ECDH)}}})},4189:(module,__unused_webpack_exports,__webpack_require__)=>{var Buffer=__webpack_require__(9509).Buffer;function Hash(blockSize,finalSize){this._block=Buffer.alloc(blockSize),this._finalSize=finalSize,this._blockSize=blockSize,this._len=0}Hash.prototype.update=function(data,enc){"string"==typeof data&&(enc=enc||"utf8",data=Buffer.from(data,enc));for(var block=this._block,blockSize=this._blockSize,length=data.length,accum=this._len,offset=0;offset=this._finalSize&&(this._update(this._block),this._block.fill(0));var bits=8*this._len;if(bits<=4294967295)this._block.writeUInt32BE(bits,this._blockSize-4);else{var lowBits=(4294967295&bits)>>>0,highBits=(bits-lowBits)/4294967296;this._block.writeUInt32BE(highBits,this._blockSize-8),this._block.writeUInt32BE(lowBits,this._blockSize-4)}this._update(this._block);var hash=this._hash();return enc?hash.toString(enc):hash},Hash.prototype._update=function(){throw new Error("_update must be implemented by subclass")},module.exports=Hash},9072:(module,__unused_webpack_exports,__webpack_require__)=>{var exports=module.exports=function SHA(algorithm){algorithm=algorithm.toLowerCase();var Algorithm=exports[algorithm];if(!Algorithm)throw new Error(algorithm+" is not supported (we accept pull requests)");return new Algorithm};exports.sha=__webpack_require__(4448),exports.sha1=__webpack_require__(8336),exports.sha224=__webpack_require__(8432),exports.sha256=__webpack_require__(7499),exports.sha384=__webpack_require__(1686),exports.sha512=__webpack_require__(7816)},4448:(module,__unused_webpack_exports,__webpack_require__)=>{var inherits=__webpack_require__(5717),Hash=__webpack_require__(4189),Buffer=__webpack_require__(9509).Buffer,K=[1518500249,1859775393,-1894007588,-899497514],W=new Array(80);function Sha(){this.init(),this._w=W,Hash.call(this,64,56)}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){return 0===s?b&c|~b&d:2===s?b&c|b&d|c&d:b^c^d}inherits(Sha,Hash),Sha.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},Sha.prototype._update=function(M){for(var num,W=this._w,a=0|this._a,b=0|this._b,c=0|this._c,d=0|this._d,e=0|this._e,i=0;i<16;++i)W[i]=M.readInt32BE(4*i);for(;i<80;++i)W[i]=W[i-3]^W[i-8]^W[i-14]^W[i-16];for(var j=0;j<80;++j){var s=~~(j/20),t=0|((num=a)<<5|num>>>27)+ft(s,b,c,d)+e+W[j]+K[s];e=d,d=c,c=rotl30(b),b=a,a=t}this._a=a+this._a|0,this._b=b+this._b|0,this._c=c+this._c|0,this._d=d+this._d|0,this._e=e+this._e|0},Sha.prototype._hash=function(){var H=Buffer.allocUnsafe(20);return H.writeInt32BE(0|this._a,0),H.writeInt32BE(0|this._b,4),H.writeInt32BE(0|this._c,8),H.writeInt32BE(0|this._d,12),H.writeInt32BE(0|this._e,16),H},module.exports=Sha},8336:(module,__unused_webpack_exports,__webpack_require__)=>{var inherits=__webpack_require__(5717),Hash=__webpack_require__(4189),Buffer=__webpack_require__(9509).Buffer,K=[1518500249,1859775393,-1894007588,-899497514],W=new Array(80);function Sha1(){this.init(),this._w=W,Hash.call(this,64,56)}function rotl5(num){return num<<5|num>>>27}function rotl30(num){return num<<30|num>>>2}function ft(s,b,c,d){return 0===s?b&c|~b&d:2===s?b&c|b&d|c&d:b^c^d}inherits(Sha1,Hash),Sha1.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},Sha1.prototype._update=function(M){for(var num,W=this._w,a=0|this._a,b=0|this._b,c=0|this._c,d=0|this._d,e=0|this._e,i=0;i<16;++i)W[i]=M.readInt32BE(4*i);for(;i<80;++i)W[i]=(num=W[i-3]^W[i-8]^W[i-14]^W[i-16])<<1|num>>>31;for(var j=0;j<80;++j){var s=~~(j/20),t=rotl5(a)+ft(s,b,c,d)+e+W[j]+K[s]|0;e=d,d=c,c=rotl30(b),b=a,a=t}this._a=a+this._a|0,this._b=b+this._b|0,this._c=c+this._c|0,this._d=d+this._d|0,this._e=e+this._e|0},Sha1.prototype._hash=function(){var H=Buffer.allocUnsafe(20);return H.writeInt32BE(0|this._a,0),H.writeInt32BE(0|this._b,4),H.writeInt32BE(0|this._c,8),H.writeInt32BE(0|this._d,12),H.writeInt32BE(0|this._e,16),H},module.exports=Sha1},8432:(module,__unused_webpack_exports,__webpack_require__)=>{var inherits=__webpack_require__(5717),Sha256=__webpack_require__(7499),Hash=__webpack_require__(4189),Buffer=__webpack_require__(9509).Buffer,W=new Array(64);function Sha224(){this.init(),this._w=W,Hash.call(this,64,56)}inherits(Sha224,Sha256),Sha224.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},Sha224.prototype._hash=function(){var H=Buffer.allocUnsafe(28);return H.writeInt32BE(this._a,0),H.writeInt32BE(this._b,4),H.writeInt32BE(this._c,8),H.writeInt32BE(this._d,12),H.writeInt32BE(this._e,16),H.writeInt32BE(this._f,20),H.writeInt32BE(this._g,24),H},module.exports=Sha224},7499:(module,__unused_webpack_exports,__webpack_require__)=>{var inherits=__webpack_require__(5717),Hash=__webpack_require__(4189),Buffer=__webpack_require__(9509).Buffer,K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],W=new Array(64);function Sha256(){this.init(),this._w=W,Hash.call(this,64,56)}function ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x){return(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10)}function sigma1(x){return(x>>>6|x<<26)^(x>>>11|x<<21)^(x>>>25|x<<7)}function gamma0(x){return(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3}inherits(Sha256,Hash),Sha256.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},Sha256.prototype._update=function(M){for(var x,W=this._w,a=0|this._a,b=0|this._b,c=0|this._c,d=0|this._d,e=0|this._e,f=0|this._f,g=0|this._g,h=0|this._h,i=0;i<16;++i)W[i]=M.readInt32BE(4*i);for(;i<64;++i)W[i]=0|(((x=W[i-2])>>>17|x<<15)^(x>>>19|x<<13)^x>>>10)+W[i-7]+gamma0(W[i-15])+W[i-16];for(var j=0;j<64;++j){var T1=h+sigma1(e)+ch(e,f,g)+K[j]+W[j]|0,T2=sigma0(a)+maj(a,b,c)|0;h=g,g=f,f=e,e=d+T1|0,d=c,c=b,b=a,a=T1+T2|0}this._a=a+this._a|0,this._b=b+this._b|0,this._c=c+this._c|0,this._d=d+this._d|0,this._e=e+this._e|0,this._f=f+this._f|0,this._g=g+this._g|0,this._h=h+this._h|0},Sha256.prototype._hash=function(){var H=Buffer.allocUnsafe(32);return H.writeInt32BE(this._a,0),H.writeInt32BE(this._b,4),H.writeInt32BE(this._c,8),H.writeInt32BE(this._d,12),H.writeInt32BE(this._e,16),H.writeInt32BE(this._f,20),H.writeInt32BE(this._g,24),H.writeInt32BE(this._h,28),H},module.exports=Sha256},1686:(module,__unused_webpack_exports,__webpack_require__)=>{var inherits=__webpack_require__(5717),SHA512=__webpack_require__(7816),Hash=__webpack_require__(4189),Buffer=__webpack_require__(9509).Buffer,W=new Array(160);function Sha384(){this.init(),this._w=W,Hash.call(this,128,112)}inherits(Sha384,SHA512),Sha384.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},Sha384.prototype._hash=function(){var H=Buffer.allocUnsafe(48);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset),H.writeInt32BE(l,offset+4)}return writeInt64BE(this._ah,this._al,0),writeInt64BE(this._bh,this._bl,8),writeInt64BE(this._ch,this._cl,16),writeInt64BE(this._dh,this._dl,24),writeInt64BE(this._eh,this._el,32),writeInt64BE(this._fh,this._fl,40),H},module.exports=Sha384},7816:(module,__unused_webpack_exports,__webpack_require__)=>{var inherits=__webpack_require__(5717),Hash=__webpack_require__(4189),Buffer=__webpack_require__(9509).Buffer,K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],W=new Array(160);function Sha512(){this.init(),this._w=W,Hash.call(this,128,112)}function Ch(x,y,z){return z^x&(y^z)}function maj(x,y,z){return x&y|z&(x|y)}function sigma0(x,xl){return(x>>>28|xl<<4)^(xl>>>2|x<<30)^(xl>>>7|x<<25)}function sigma1(x,xl){return(x>>>14|xl<<18)^(x>>>18|xl<<14)^(xl>>>9|x<<23)}function Gamma0(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^x>>>7}function Gamma0l(x,xl){return(x>>>1|xl<<31)^(x>>>8|xl<<24)^(x>>>7|xl<<25)}function Gamma1(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^x>>>6}function Gamma1l(x,xl){return(x>>>19|xl<<13)^(xl>>>29|x<<3)^(x>>>6|xl<<26)}function getCarry(a,b){return a>>>0>>0?1:0}inherits(Sha512,Hash),Sha512.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},Sha512.prototype._update=function(M){for(var W=this._w,ah=0|this._ah,bh=0|this._bh,ch=0|this._ch,dh=0|this._dh,eh=0|this._eh,fh=0|this._fh,gh=0|this._gh,hh=0|this._hh,al=0|this._al,bl=0|this._bl,cl=0|this._cl,dl=0|this._dl,el=0|this._el,fl=0|this._fl,gl=0|this._gl,hl=0|this._hl,i=0;i<32;i+=2)W[i]=M.readInt32BE(4*i),W[i+1]=M.readInt32BE(4*i+4);for(;i<160;i+=2){var xh=W[i-30],xl=W[i-30+1],gamma0=Gamma0(xh,xl),gamma0l=Gamma0l(xl,xh),gamma1=Gamma1(xh=W[i-4],xl=W[i-4+1]),gamma1l=Gamma1l(xl,xh),Wi7h=W[i-14],Wi7l=W[i-14+1],Wi16h=W[i-32],Wi16l=W[i-32+1],Wil=gamma0l+Wi7l|0,Wih=gamma0+Wi7h+getCarry(Wil,gamma0l)|0;Wih=(Wih=Wih+gamma1+getCarry(Wil=Wil+gamma1l|0,gamma1l)|0)+Wi16h+getCarry(Wil=Wil+Wi16l|0,Wi16l)|0,W[i]=Wih,W[i+1]=Wil}for(var j=0;j<160;j+=2){Wih=W[j],Wil=W[j+1];var majh=maj(ah,bh,ch),majl=maj(al,bl,cl),sigma0h=sigma0(ah,al),sigma0l=sigma0(al,ah),sigma1h=sigma1(eh,el),sigma1l=sigma1(el,eh),Kih=K[j],Kil=K[j+1],chh=Ch(eh,fh,gh),chl=Ch(el,fl,gl),t1l=hl+sigma1l|0,t1h=hh+sigma1h+getCarry(t1l,hl)|0;t1h=(t1h=(t1h=t1h+chh+getCarry(t1l=t1l+chl|0,chl)|0)+Kih+getCarry(t1l=t1l+Kil|0,Kil)|0)+Wih+getCarry(t1l=t1l+Wil|0,Wil)|0;var t2l=sigma0l+majl|0,t2h=sigma0h+majh+getCarry(t2l,sigma0l)|0;hh=gh,hl=gl,gh=fh,gl=fl,fh=eh,fl=el,eh=dh+t1h+getCarry(el=dl+t1l|0,dl)|0,dh=ch,dl=cl,ch=bh,cl=bl,bh=ah,bl=al,ah=t1h+t2h+getCarry(al=t1l+t2l|0,t1l)|0}this._al=this._al+al|0,this._bl=this._bl+bl|0,this._cl=this._cl+cl|0,this._dl=this._dl+dl|0,this._el=this._el+el|0,this._fl=this._fl+fl|0,this._gl=this._gl+gl|0,this._hl=this._hl+hl|0,this._ah=this._ah+ah+getCarry(this._al,al)|0,this._bh=this._bh+bh+getCarry(this._bl,bl)|0,this._ch=this._ch+ch+getCarry(this._cl,cl)|0,this._dh=this._dh+dh+getCarry(this._dl,dl)|0,this._eh=this._eh+eh+getCarry(this._el,el)|0,this._fh=this._fh+fh+getCarry(this._fl,fl)|0,this._gh=this._gh+gh+getCarry(this._gl,gl)|0,this._hh=this._hh+hh+getCarry(this._hl,hl)|0},Sha512.prototype._hash=function(){var H=Buffer.allocUnsafe(64);function writeInt64BE(h,l,offset){H.writeInt32BE(h,offset),H.writeInt32BE(l,offset+4)}return writeInt64BE(this._ah,this._al,0),writeInt64BE(this._bh,this._bl,8),writeInt64BE(this._ch,this._cl,16),writeInt64BE(this._dh,this._dl,24),writeInt64BE(this._eh,this._el,32),writeInt64BE(this._fh,this._fl,40),writeInt64BE(this._gh,this._gl,48),writeInt64BE(this._hh,this._hl,56),H},module.exports=Sha512},1860:function(module){!function(window,define){var _={version:"2.14.2",areas:{},apis:{},nsdelim:".",inherit:function(api,o){for(var p in api)o.hasOwnProperty(p)||Object.defineProperty(o,p,Object.getOwnPropertyDescriptor(api,p));return o},stringify:function(d,fn){return void 0===d||"function"==typeof d?d+"":JSON.stringify(d,fn||_.replace)},parse:function(s,fn){try{return JSON.parse(s,fn||_.revive)}catch(e){return s}},fn:function(name,fn){for(var api in _.storeAPI[name]=fn,_.apis)_.apis[api][name]=fn},get:function(area,key){return area.getItem(key)},set:function(area,key,string){area.setItem(key,string)},remove:function(area,key){area.removeItem(key)},key:function(area,i){return area.key(i)},length:function(area){return area.length},clear:function(area){area.clear()},Store:function(id,area,namespace){var store=_.inherit(_.storeAPI,(function(key,data,overwrite){return 0===arguments.length?store.getAll():"function"==typeof data?store.transact(key,data,overwrite):void 0!==data?store.set(key,data,overwrite):"string"==typeof key||"number"==typeof key?store.get(key):"function"==typeof key?store.each(key):key?store.setAll(key,data):store.clear()}));store._id=id;try{area.setItem("__store2_test","ok"),store._area=area,area.removeItem("__store2_test")}catch(e){store._area=_.storage("fake")}return store._ns=namespace||"",_.areas[id]||(_.areas[id]=store._area),_.apis[store._ns+store._id]||(_.apis[store._ns+store._id]=store),store},storeAPI:{area:function(id,area){var store=this[id];return store&&store.area||(store=_.Store(id,area,this._ns),this[id]||(this[id]=store)),store},namespace:function(namespace,singleArea,delim){if(delim=delim||this._delim||_.nsdelim,!namespace)return this._ns?this._ns.substring(0,this._ns.length-delim.length):"";var ns=namespace,store=this[ns];if(!(store&&store.namespace||((store=_.Store(this._id,this._area,this._ns+ns+delim))._delim=delim,this[ns]||(this[ns]=store),singleArea)))for(var name in _.areas)store.area(name,_.areas[name]);return store},isFake:function(force){return force?(this._real=this._area,this._area=_.storage("fake")):!1===force&&(this._area=this._real||this._area),"fake"===this._area.name},toString:function(){return"store"+(this._ns?"."+this.namespace():"")+"["+this._id+"]"},has:function(key){return this._area.has?this._area.has(this._in(key)):!!(this._in(key)in this._area)},size:function(){return this.keys().length},each:function(fn,fill){for(var i=0,m=_.length(this._area);i_.length(this._area)&&(m--,i--)}return fill||this},keys:function(fillList){return this.each((function(k,v,list){list.push(k)}),fillList||[])},get:function(key,alt){var fn,s=_.get(this._area,this._in(key));return"function"==typeof alt&&(fn=alt,alt=null),null!==s?_.parse(s,fn):null!=alt?alt:s},getAll:function(fillObj){return this.each((function(k,v,all){all[k]=v}),fillObj||{})},transact:function(key,fn,alt){var val=this.get(key,alt),ret=fn(val);return this.set(key,void 0===ret?val:ret),this},set:function(key,data,overwrite){var replacer,d=this.get(key);return null!=d&&!1===overwrite?data:("function"==typeof overwrite&&(replacer=overwrite,overwrite=void 0),_.set(this._area,this._in(key),_.stringify(data,replacer),overwrite)||d)},setAll:function(data,overwrite){var changed,val;for(var key in data)val=data[key],this.set(key,val,overwrite)!==val&&(changed=!0);return changed},add:function(key,data,replacer){var d=this.get(key);if(d instanceof Array)data=d.concat(data);else if(null!==d){var type=typeof d;if(type===typeof data&&"object"===type){for(var k in data)d[k]=data[k];data=d}else data=d+data}return _.set(this._area,this._in(key),_.stringify(data,replacer)),data},remove:function(key,alt){var d=this.get(key,alt);return _.remove(this._area,this._in(key)),d},clear:function(){return this._ns?this.each((function(k){_.remove(this._area,this._in(k))}),1):_.clear(this._area),this},clearAll:function(){var area=this._area;for(var id in _.areas)_.areas.hasOwnProperty(id)&&(this._area=_.areas[id],this.clear());return this._area=area,this},_in:function(k){return"string"!=typeof k&&(k=_.stringify(k)),this._ns?this._ns+k:k},_out:function(k){return this._ns?k&&0===k.indexOf(this._ns)?k.substring(this._ns.length):void 0:k}},storage:function(name){return _.inherit(_.storageAPI,{items:{},name})},storageAPI:{length:0,has:function(k){return this.items.hasOwnProperty(k)},key:function(i){var c=0;for(var k in this.items)if(this.has(k)&&i===c++)return k},setItem:function(k,v){this.has(k)||this.length++,this.items[k]=v},removeItem:function(k){this.has(k)&&(delete this.items[k],this.length--)},getItem:function(k){return this.has(k)?this.items[k]:null},clear:function(){for(var k in this.items)this.removeItem(k)}}},store=_.Store("local",function(){try{return localStorage}catch(e){}}());store.local=store,store._=_,store.area("session",function(){try{return sessionStorage}catch(e){}}()),store.area("page",_.storage("page")),"function"==typeof define&&void 0!==define.amd?define("store2",[],(function(){return store})):module.exports?module.exports=store:(window.store&&(_.conflict=window.store),window.store=store)}(this,this&&this.define)},2830:(module,__unused_webpack_exports,__webpack_require__)=>{module.exports=Stream;var EE=__webpack_require__(7187).EventEmitter;function Stream(){EE.call(this)}__webpack_require__(5717)(Stream,EE),Stream.Readable=__webpack_require__(9481),Stream.Writable=__webpack_require__(4229),Stream.Duplex=__webpack_require__(6753),Stream.Transform=__webpack_require__(4605),Stream.PassThrough=__webpack_require__(2725),Stream.finished=__webpack_require__(8610),Stream.pipeline=__webpack_require__(9946),Stream.Stream=Stream,Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){dest.writable&&!1===dest.write(chunk)&&source.pause&&source.pause()}function ondrain(){source.readable&&source.resume&&source.resume()}source.on("data",ondata),dest.on("drain",ondrain),dest._isStdio||options&&!1===options.end||(source.on("end",onend),source.on("close",onclose));var didOnEnd=!1;function onend(){didOnEnd||(didOnEnd=!0,dest.end())}function onclose(){didOnEnd||(didOnEnd=!0,"function"==typeof dest.destroy&&dest.destroy())}function onerror(er){if(cleanup(),0===EE.listenerCount(this,"error"))throw er}function cleanup(){source.removeListener("data",ondata),dest.removeListener("drain",ondrain),source.removeListener("end",onend),source.removeListener("close",onclose),source.removeListener("error",onerror),dest.removeListener("error",onerror),source.removeListener("end",cleanup),source.removeListener("close",cleanup),dest.removeListener("close",cleanup)}return source.on("error",onerror),dest.on("error",onerror),source.on("end",cleanup),source.on("close",cleanup),dest.on("close",cleanup),dest.emit("pipe",source),dest}},2553:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";var Buffer=__webpack_require__(9509).Buffer,isEncoding=Buffer.isEncoding||function(encoding){switch((encoding=""+encoding)&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function StringDecoder(encoding){var nb;switch(this.encoding=function normalizeEncoding(enc){var nenc=function _normalizeEncoding(enc){if(!enc)return"utf8";for(var retried;;)switch(enc){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return enc;default:if(retried)return;enc=(""+enc).toLowerCase(),retried=!0}}(enc);if("string"!=typeof nenc&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}(encoding),this.encoding){case"utf16le":this.text=utf16Text,this.end=utf16End,nb=4;break;case"utf8":this.fillLast=utf8FillLast,nb=4;break;case"base64":this.text=base64Text,this.end=base64End,nb=3;break;default:return this.write=simpleWrite,void(this.end=simpleEnd)}this.lastNeed=0,this.lastTotal=0,this.lastChar=Buffer.allocUnsafe(nb)}function utf8CheckByte(byte){return byte<=127?0:byte>>5==6?2:byte>>4==14?3:byte>>3==30?4:byte>>6==2?-1:-2}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed,r=function utf8CheckExtraBytes(self,buf,p){if(128!=(192&buf[0]))return self.lastNeed=0,"�";if(self.lastNeed>1&&buf.length>1){if(128!=(192&buf[1]))return self.lastNeed=1,"�";if(self.lastNeed>2&&buf.length>2&&128!=(192&buf[2]))return self.lastNeed=2,"�"}}(this,buf);return void 0!==r?r:this.lastNeed<=buf.length?(buf.copy(this.lastChar,p,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(buf.copy(this.lastChar,p,0,buf.length),void(this.lastNeed-=buf.length))}function utf16Text(buf,i){if((buf.length-i)%2==0){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(c>=55296&&c<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=buf[buf.length-1],buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;return 0===n?buf.toString("base64",i):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=buf[buf.length-1]:(this.lastChar[0]=buf[buf.length-2],this.lastChar[1]=buf[buf.length-1]),buf.toString("base64",i,buf.length-n))}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";return this.lastNeed?r+this.lastChar.toString("base64",0,3-this.lastNeed):r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}exports.s=StringDecoder,StringDecoder.prototype.write=function(buf){if(0===buf.length)return"";var r,i;if(this.lastNeed){if(void 0===(r=this.fillLast(buf)))return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i=0)return nb>0&&(self.lastNeed=nb-1),nb;if(--j=0)return nb>0&&(self.lastNeed=nb-2),nb;if(--j=0)return nb>0&&(2===nb?nb=0:self.lastNeed=nb-3),nb;return 0}(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);return buf.copy(this.lastChar,0,end),buf.toString("utf8",i,end)},StringDecoder.prototype.fillLast=function(buf){if(this.lastNeed<=buf.length)return buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);buf.copy(this.lastChar,this.lastTotal-this.lastNeed,0,buf.length),this.lastNeed-=buf.length}},4927:(module,__unused_webpack_exports,__webpack_require__)=>{function config(name){try{if(!__webpack_require__.g.localStorage)return!1}catch(_){return!1}var val=__webpack_require__.g.localStorage[name];return null!=val&&"true"===String(val).toLowerCase()}module.exports=function deprecate(fn,msg){if(config("noDeprecation"))return fn;var warned=!1;return function deprecated(){if(!warned){if(config("throwDeprecation"))throw new Error(msg);config("traceDeprecation")?console.trace(msg):console.warn(msg),warned=!0}return fn.apply(this,arguments)}}},384:module=>{module.exports=function isBuffer(arg){return arg&&"object"==typeof arg&&"function"==typeof arg.copy&&"function"==typeof arg.fill&&"function"==typeof arg.readUInt8}},5955:(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";var isArgumentsObject=__webpack_require__(2584),isGeneratorFunction=__webpack_require__(8662),whichTypedArray=__webpack_require__(6430),isTypedArray=__webpack_require__(5692);function uncurryThis(f){return f.call.bind(f)}var BigIntSupported="undefined"!=typeof BigInt,SymbolSupported="undefined"!=typeof Symbol,ObjectToString=uncurryThis(Object.prototype.toString),numberValue=uncurryThis(Number.prototype.valueOf),stringValue=uncurryThis(String.prototype.valueOf),booleanValue=uncurryThis(Boolean.prototype.valueOf);if(BigIntSupported)var bigIntValue=uncurryThis(BigInt.prototype.valueOf);if(SymbolSupported)var symbolValue=uncurryThis(Symbol.prototype.valueOf);function checkBoxedPrimitive(value,prototypeValueOf){if("object"!=typeof value)return!1;try{return prototypeValueOf(value),!0}catch(e){return!1}}function isMapToString(value){return"[object Map]"===ObjectToString(value)}function isSetToString(value){return"[object Set]"===ObjectToString(value)}function isWeakMapToString(value){return"[object WeakMap]"===ObjectToString(value)}function isWeakSetToString(value){return"[object WeakSet]"===ObjectToString(value)}function isArrayBufferToString(value){return"[object ArrayBuffer]"===ObjectToString(value)}function isArrayBuffer(value){return"undefined"!=typeof ArrayBuffer&&(isArrayBufferToString.working?isArrayBufferToString(value):value instanceof ArrayBuffer)}function isDataViewToString(value){return"[object DataView]"===ObjectToString(value)}function isDataView(value){return"undefined"!=typeof DataView&&(isDataViewToString.working?isDataViewToString(value):value instanceof DataView)}exports.isArgumentsObject=isArgumentsObject,exports.isGeneratorFunction=isGeneratorFunction,exports.isTypedArray=isTypedArray,exports.isPromise=function isPromise(input){return"undefined"!=typeof Promise&&input instanceof Promise||null!==input&&"object"==typeof input&&"function"==typeof input.then&&"function"==typeof input.catch},exports.isArrayBufferView=function isArrayBufferView(value){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(value):isTypedArray(value)||isDataView(value)},exports.isUint8Array=function isUint8Array(value){return"Uint8Array"===whichTypedArray(value)},exports.isUint8ClampedArray=function isUint8ClampedArray(value){return"Uint8ClampedArray"===whichTypedArray(value)},exports.isUint16Array=function isUint16Array(value){return"Uint16Array"===whichTypedArray(value)},exports.isUint32Array=function isUint32Array(value){return"Uint32Array"===whichTypedArray(value)},exports.isInt8Array=function isInt8Array(value){return"Int8Array"===whichTypedArray(value)},exports.isInt16Array=function isInt16Array(value){return"Int16Array"===whichTypedArray(value)},exports.isInt32Array=function isInt32Array(value){return"Int32Array"===whichTypedArray(value)},exports.isFloat32Array=function isFloat32Array(value){return"Float32Array"===whichTypedArray(value)},exports.isFloat64Array=function isFloat64Array(value){return"Float64Array"===whichTypedArray(value)},exports.isBigInt64Array=function isBigInt64Array(value){return"BigInt64Array"===whichTypedArray(value)},exports.isBigUint64Array=function isBigUint64Array(value){return"BigUint64Array"===whichTypedArray(value)},isMapToString.working="undefined"!=typeof Map&&isMapToString(new Map),exports.isMap=function isMap(value){return"undefined"!=typeof Map&&(isMapToString.working?isMapToString(value):value instanceof Map)},isSetToString.working="undefined"!=typeof Set&&isSetToString(new Set),exports.isSet=function isSet(value){return"undefined"!=typeof Set&&(isSetToString.working?isSetToString(value):value instanceof Set)},isWeakMapToString.working="undefined"!=typeof WeakMap&&isWeakMapToString(new WeakMap),exports.isWeakMap=function isWeakMap(value){return"undefined"!=typeof WeakMap&&(isWeakMapToString.working?isWeakMapToString(value):value instanceof WeakMap)},isWeakSetToString.working="undefined"!=typeof WeakSet&&isWeakSetToString(new WeakSet),exports.isWeakSet=function isWeakSet(value){return isWeakSetToString(value)},isArrayBufferToString.working="undefined"!=typeof ArrayBuffer&&isArrayBufferToString(new ArrayBuffer),exports.isArrayBuffer=isArrayBuffer,isDataViewToString.working="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView&&isDataViewToString(new DataView(new ArrayBuffer(1),0,1)),exports.isDataView=isDataView;var SharedArrayBufferCopy="undefined"!=typeof SharedArrayBuffer?SharedArrayBuffer:void 0;function isSharedArrayBufferToString(value){return"[object SharedArrayBuffer]"===ObjectToString(value)}function isSharedArrayBuffer(value){return void 0!==SharedArrayBufferCopy&&(void 0===isSharedArrayBufferToString.working&&(isSharedArrayBufferToString.working=isSharedArrayBufferToString(new SharedArrayBufferCopy)),isSharedArrayBufferToString.working?isSharedArrayBufferToString(value):value instanceof SharedArrayBufferCopy)}function isNumberObject(value){return checkBoxedPrimitive(value,numberValue)}function isStringObject(value){return checkBoxedPrimitive(value,stringValue)}function isBooleanObject(value){return checkBoxedPrimitive(value,booleanValue)}function isBigIntObject(value){return BigIntSupported&&checkBoxedPrimitive(value,bigIntValue)}function isSymbolObject(value){return SymbolSupported&&checkBoxedPrimitive(value,symbolValue)}exports.isSharedArrayBuffer=isSharedArrayBuffer,exports.isAsyncFunction=function isAsyncFunction(value){return"[object AsyncFunction]"===ObjectToString(value)},exports.isMapIterator=function isMapIterator(value){return"[object Map Iterator]"===ObjectToString(value)},exports.isSetIterator=function isSetIterator(value){return"[object Set Iterator]"===ObjectToString(value)},exports.isGeneratorObject=function isGeneratorObject(value){return"[object Generator]"===ObjectToString(value)},exports.isWebAssemblyCompiledModule=function isWebAssemblyCompiledModule(value){return"[object WebAssembly.Module]"===ObjectToString(value)},exports.isNumberObject=isNumberObject,exports.isStringObject=isStringObject,exports.isBooleanObject=isBooleanObject,exports.isBigIntObject=isBigIntObject,exports.isSymbolObject=isSymbolObject,exports.isBoxedPrimitive=function isBoxedPrimitive(value){return isNumberObject(value)||isStringObject(value)||isBooleanObject(value)||isBigIntObject(value)||isSymbolObject(value)},exports.isAnyArrayBuffer=function isAnyArrayBuffer(value){return"undefined"!=typeof Uint8Array&&(isArrayBuffer(value)||isSharedArrayBuffer(value))},["isProxy","isExternal","isModuleNamespaceObject"].forEach((function(method){Object.defineProperty(exports,method,{enumerable:!1,value:function(){throw new Error(method+" is not supported in userland")}})}))},9539:(__unused_webpack_module,exports,__webpack_require__)=>{var getOwnPropertyDescriptors=Object.getOwnPropertyDescriptors||function getOwnPropertyDescriptors(obj){for(var keys=Object.keys(obj),descriptors={},i=0;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}})),x=args[i];i=3&&(ctx.depth=arguments[2]),arguments.length>=4&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str,styleType){return str}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&(!value.constructor||value.constructor.prototype!==value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=function arrayToHash(array){var hash={};return array.forEach((function(val,idx){hash[val]=!0})),hash}(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0))return formatError(value);if(0===keys.length){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value))return ctx.stylize(RegExp.prototype.toString.call(value),"regexp");if(isDate(value))return ctx.stylize(Date.prototype.toString.call(value),"date");if(isError(value))return formatError(value)}var output,base="",array=!1,braces=["{","}"];(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value))&&(base=" [Function"+(value.name?": "+value.name:"")+"]");return isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0!==keys.length||array&&0!=value.length?recurseTimes<0?isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special"):(ctx.seen.push(value),output=array?function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;i=0&&0,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1}),0)>60)return braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1];return braces[0]+base+" "+output.join(", ")+" "+braces[1]}(output,base,braces)):braces[0]+base+braces[1]}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;if((desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]}).get?str=desc.set?ctx.stylize("[Getter/Setter]","special"):ctx.stylize("[Getter]","special"):desc.set&&(str=ctx.stylize("[Setter]","special")),hasOwnProperty(visibleKeys,key)||(name="["+key+"]"),str||(ctx.seen.indexOf(desc.value)<0?(str=isNull(recurseTimes)?formatValue(ctx,desc.value,null):formatValue(ctx,desc.value,recurseTimes-1)).indexOf("\n")>-1&&(str=array?str.split("\n").map((function(line){return" "+line})).join("\n").substr(2):"\n"+str.split("\n").map((function(line){return" "+line})).join("\n")):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;(name=JSON.stringify(""+key)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}exports.debuglog=function(set){if(set=set.toUpperCase(),!debugs[set])if(debugEnvRegex.test(set)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else debugs[set]=function(){};return debugs[set]},exports.inspect=inspect,inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},inspect.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},exports.types=__webpack_require__(5955),exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=function isNullOrUndefined(arg){return null==arg},exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=function isSymbol(arg){return"symbol"==typeof arg},exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.types.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.types.isDate=isDate,exports.isError=isError,exports.types.isNativeError=isError,exports.isFunction=isFunction,exports.isPrimitive=function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||void 0===arg},exports.isBuffer=__webpack_require__(384);var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))},exports.inherits=__webpack_require__(5717),exports._extend=function(origin,add){if(!add||!isObject(add))return origin;for(var keys=Object.keys(add),i=keys.length;i--;)origin[keys[i]]=add[keys[i]];return origin};var kCustomPromisifiedSymbol="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function callbackifyOnRejected(reason,cb){if(!reason){var newReason=new Error("Promise was rejected with a falsy value");newReason.reason=reason,reason=newReason}return cb(reason)}exports.promisify=function promisify(original){if("function"!=typeof original)throw new TypeError('The "original" argument must be of type Function');if(kCustomPromisifiedSymbol&&original[kCustomPromisifiedSymbol]){var fn;if("function"!=typeof(fn=original[kCustomPromisifiedSymbol]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(fn,kCustomPromisifiedSymbol,{value:fn,enumerable:!1,writable:!1,configurable:!0}),fn}function fn(){for(var promiseResolve,promiseReject,promise=new Promise((function(resolve,reject){promiseResolve=resolve,promiseReject=reject})),args=[],i=0;i{"use strict";var forEach=__webpack_require__(9804),availableTypedArrays=__webpack_require__(3083),callBound=__webpack_require__(1924),$toString=callBound("Object.prototype.toString"),hasToStringTag=__webpack_require__(6410)(),g="undefined"==typeof globalThis?__webpack_require__.g:globalThis,typedArrays=availableTypedArrays(),$slice=callBound("String.prototype.slice"),toStrTags={},gOPD=__webpack_require__(882),getPrototypeOf=Object.getPrototypeOf;hasToStringTag&&gOPD&&getPrototypeOf&&forEach(typedArrays,(function(typedArray){if("function"==typeof g[typedArray]){var arr=new g[typedArray];if(Symbol.toStringTag in arr){var proto=getPrototypeOf(arr),descriptor=gOPD(proto,Symbol.toStringTag);if(!descriptor){var superProto=getPrototypeOf(proto);descriptor=gOPD(superProto,Symbol.toStringTag)}toStrTags[typedArray]=descriptor.get}}}));var isTypedArray=__webpack_require__(5692);module.exports=function whichTypedArray(value){return!!isTypedArray(value)&&(hasToStringTag&&Symbol.toStringTag in value?function tryAllTypedArrays(value){var foundName=!1;return forEach(toStrTags,(function(getter,typedArray){if(!foundName)try{var name=getter.call(value);name===typedArray&&(foundName=name)}catch(e){}})),foundName}(value):$slice($toString(value),8,-1))}},2302:(__unused_webpack_module,exports,__webpack_require__)=>{var FilterCSS=__webpack_require__(9970).FilterCSS,getDefaultCSSWhiteList=__webpack_require__(9970).getDefaultWhiteList,_=__webpack_require__(5938);function getDefaultWhiteList(){return{a:["target","href","title"],abbr:["title"],address:[],area:["shape","coords","href","alt"],article:[],aside:[],audio:["autoplay","controls","crossorigin","loop","muted","preload","src"],b:[],bdi:["dir"],bdo:["dir"],big:[],blockquote:["cite"],br:[],caption:[],center:[],cite:[],code:[],col:["align","valign","span","width"],colgroup:["align","valign","span","width"],dd:[],del:["datetime"],details:["open"],div:[],dl:[],dt:[],em:[],figcaption:[],figure:[],font:["color","size","face"],footer:[],h1:[],h2:[],h3:[],h4:[],h5:[],h6:[],header:[],hr:[],i:[],img:["src","alt","title","width","height"],ins:["datetime"],li:[],mark:[],nav:[],ol:[],p:[],pre:[],s:[],section:[],small:[],span:[],sub:[],summary:[],sup:[],strong:[],strike:[],table:["width","border","align","valign"],tbody:["align","valign"],td:["width","rowspan","colspan","align","valign"],tfoot:["align","valign"],th:["width","rowspan","colspan","align","valign"],thead:["align","valign"],tr:["rowspan","align","valign"],tt:[],u:[],ul:[],video:["autoplay","controls","crossorigin","loop","muted","playsinline","poster","preload","src","height","width"]}}var defaultCSSFilter=new FilterCSS;function escapeHtml(html){return html.replace(REGEXP_LT,"<").replace(REGEXP_GT,">")}var REGEXP_LT=//g,REGEXP_QUOTE=/"/g,REGEXP_QUOTE_2=/"/g,REGEXP_ATTR_VALUE_1=/&#([a-zA-Z0-9]*);?/gim,REGEXP_ATTR_VALUE_COLON=/:?/gim,REGEXP_ATTR_VALUE_NEWLINE=/&newline;?/gim,REGEXP_DEFAULT_ON_TAG_ATTR_4=/((j\s*a\s*v\s*a|v\s*b|l\s*i\s*v\s*e)\s*s\s*c\s*r\s*i\s*p\s*t\s*|m\s*o\s*c\s*h\s*a):/gi,REGEXP_DEFAULT_ON_TAG_ATTR_7=/e\s*x\s*p\s*r\s*e\s*s\s*s\s*i\s*o\s*n\s*\(.*/gi,REGEXP_DEFAULT_ON_TAG_ATTR_8=/u\s*r\s*l\s*\(.*/gi;function escapeQuote(str){return str.replace(REGEXP_QUOTE,""")}function unescapeQuote(str){return str.replace(REGEXP_QUOTE_2,'"')}function escapeHtmlEntities(str){return str.replace(REGEXP_ATTR_VALUE_1,(function replaceUnicode(str,code){return"x"===code[0]||"X"===code[0]?String.fromCharCode(parseInt(code.substr(1),16)):String.fromCharCode(parseInt(code,10))}))}function escapeDangerHtml5Entities(str){return str.replace(REGEXP_ATTR_VALUE_COLON,":").replace(REGEXP_ATTR_VALUE_NEWLINE," ")}function clearNonPrintableCharacter(str){for(var str2="",i=0,len=str.length;i{var DEFAULT=__webpack_require__(2302),parser=__webpack_require__(3268),FilterXSS=__webpack_require__(2973);function filterXSS(html,options){return new FilterXSS(options).process(html)}(exports=module.exports=filterXSS).filterXSS=filterXSS,exports.FilterXSS=FilterXSS,function(){for(var i in DEFAULT)exports[i]=DEFAULT[i];for(var j in parser)exports[j]=parser[j]}(),"undefined"!=typeof window&&(window.filterXSS=module.exports),function isWorkerEnv(){return"undefined"!=typeof self&&"undefined"!=typeof DedicatedWorkerGlobalScope&&self instanceof DedicatedWorkerGlobalScope}()&&(self.filterXSS=module.exports)},3268:(__unused_webpack_module,exports,__webpack_require__)=>{var _=__webpack_require__(5938);function getTagName(html){var tagName,i=_.spaceIndex(html);return tagName=-1===i?html.slice(1,-1):html.slice(1,i+1),"/"===(tagName=_.trim(tagName).toLowerCase()).slice(0,1)&&(tagName=tagName.slice(1)),"/"===tagName.slice(-1)&&(tagName=tagName.slice(0,-1)),tagName}function isClosing(html){return"0;i--){var c=str[i];if(" "!==c)return"="===c?i:-1}}function stripQuoteWrap(text){return function isQuoteWrapString(text){return'"'===text[0]&&'"'===text[text.length-1]||"'"===text[0]&&"'"===text[text.length-1]}(text)?text.substr(1,text.length-2):text}exports.parseTag=function parseTag(html,onTag,escapeHtml){"use strict";var rethtml="",lastPos=0,tagStart=!1,quoteStart=!1,currentPos=0,len=html.length,currentTagName="",currentHtml="";chariterator:for(currentPos=0;currentPos"===c||currentPos===len-1){rethtml+=escapeHtml(html.slice(lastPos,tagStart)),currentTagName=getTagName(currentHtml=html.slice(tagStart,currentPos+1)),rethtml+=onTag(tagStart,rethtml.length,currentTagName,currentHtml,isClosing(currentHtml)),lastPos=currentPos+1,tagStart=!1;continue}if('"'===c||"'"===c)for(var i=1,ic=html.charAt(currentPos-i);""===ic.trim()||"="===ic;){if("="===ic){quoteStart=c;continue chariterator}ic=html.charAt(currentPos-++i)}}else if(c===quoteStart){quoteStart=!1;continue}}return lastPos{module.exports={indexOf:function(arr,item){var i,j;if(Array.prototype.indexOf)return arr.indexOf(item);for(i=0,j=arr.length;i{var FilterCSS=__webpack_require__(9970).FilterCSS,DEFAULT=__webpack_require__(2302),parser=__webpack_require__(3268),parseTag=parser.parseTag,parseAttr=parser.parseAttr,_=__webpack_require__(5938);function isNull(obj){return null==obj}function FilterXSS(options){(options=function shallowCopyObject(obj){var ret={};for(var i in obj)ret[i]=obj[i];return ret}(options||{})).stripIgnoreTag&&(options.onIgnoreTag&&console.error('Notes: cannot use these two options "stripIgnoreTag" and "onIgnoreTag" at the same time'),options.onIgnoreTag=DEFAULT.onIgnoreTagStripAll),options.whiteList||options.allowList?options.whiteList=function keysToLowerCase(obj){var ret={};for(var i in obj)Array.isArray(obj[i])?ret[i.toLowerCase()]=obj[i].map((function(item){return item.toLowerCase()})):ret[i.toLowerCase()]=obj[i];return ret}(options.whiteList||options.allowList):options.whiteList=DEFAULT.whiteList,options.onTag=options.onTag||DEFAULT.onTag,options.onTagAttr=options.onTagAttr||DEFAULT.onTagAttr,options.onIgnoreTag=options.onIgnoreTag||DEFAULT.onIgnoreTag,options.onIgnoreTagAttr=options.onIgnoreTagAttr||DEFAULT.onIgnoreTagAttr,options.safeAttrValue=options.safeAttrValue||DEFAULT.safeAttrValue,options.escapeHtml=options.escapeHtml||DEFAULT.escapeHtml,this.options=options,!1===options.css?this.cssFilter=!1:(options.css=options.css||{},this.cssFilter=new FilterCSS(options.css))}FilterXSS.prototype.process=function(html){if(!(html=(html=html||"").toString()))return"";var options=this.options,whiteList=options.whiteList,onTag=options.onTag,onIgnoreTag=options.onIgnoreTag,onTagAttr=options.onTagAttr,onIgnoreTagAttr=options.onIgnoreTagAttr,safeAttrValue=options.safeAttrValue,escapeHtml=options.escapeHtml,cssFilter=this.cssFilter;options.stripBlankChar&&(html=DEFAULT.stripBlankChar(html)),options.allowCommentTag||(html=DEFAULT.stripCommentTag(html));var stripIgnoreTagBody=!1;options.stripIgnoreTagBody&&(stripIgnoreTagBody=DEFAULT.StripTagBody(options.stripIgnoreTagBody,onIgnoreTag),onIgnoreTag=stripIgnoreTagBody.onIgnoreTag);var retHtml=parseTag(html,(function(sourcePosition,position,tag,html,isClosing){var info={sourcePosition,position,isClosing,isWhite:Object.prototype.hasOwnProperty.call(whiteList,tag)},ret=onTag(tag,html,info);if(!isNull(ret))return ret;if(info.isWhite){if(info.isClosing)return"";var attrs=function getAttrs(html){var i=_.spaceIndex(html);if(-1===i)return{html:"",closing:"/"===html[html.length-2]};var isClosing="/"===(html=_.trim(html.slice(i+1,-1)))[html.length-1];return isClosing&&(html=_.trim(html.slice(0,-1))),{html,closing:isClosing}}(html),whiteAttrList=whiteList[tag],attrsHtml=parseAttr(attrs.html,(function(name,value){var isWhiteAttr=-1!==_.indexOf(whiteAttrList,name),ret=onTagAttr(tag,name,value,isWhiteAttr);return isNull(ret)?isWhiteAttr?(value=safeAttrValue(tag,name,value,cssFilter))?name+'="'+value+'"':name:isNull(ret=onIgnoreTagAttr(tag,name,value,isWhiteAttr))?void 0:ret:ret}));return html="<"+tag,attrsHtml&&(html+=" "+attrsHtml),attrs.closing&&(html+=" /"),html+=">"}return isNull(ret=onIgnoreTag(tag,html,info))?escapeHtml(html):ret}),escapeHtml);return stripIgnoreTagBody&&(retHtml=stripIgnoreTagBody.remove(retHtml)),retHtml},module.exports=FilterXSS},950:()=>{},6601:()=>{},9214:()=>{},1922:()=>{},2363:()=>{},8623:()=>{},7748:()=>{},5568:()=>{},6619:()=>{},7108:()=>{},2361:()=>{},4616:()=>{},3083:(module,__unused_webpack_exports,__webpack_require__)=>{"use strict";var possibleNames=["BigInt64Array","BigUint64Array","Float32Array","Float64Array","Int16Array","Int32Array","Int8Array","Uint16Array","Uint32Array","Uint8Array","Uint8ClampedArray"],g="undefined"==typeof globalThis?__webpack_require__.g:globalThis;module.exports=function availableTypedArrays(){for(var out=[],i=0;i{"use strict";var $gOPD=__webpack_require__(210)("%Object.getOwnPropertyDescriptor%",!0);if($gOPD)try{$gOPD([],"length")}catch(e){$gOPD=null}module.exports=$gOPD},6996:module=>{"use strict";module.exports=JSON.parse('["的","一","是","在","不","了","有","和","人","这","中","大","为","上","个","国","我","以","要","他","时","来","用","们","生","到","作","地","于","出","就","分","对","成","会","可","主","发","年","动","同","工","也","能","下","过","子","说","产","种","面","而","方","后","多","定","行","学","法","所","民","得","经","十","三","之","进","着","等","部","度","家","电","力","里","如","水","化","高","自","二","理","起","小","物","现","实","加","量","都","两","体","制","机","当","使","点","从","业","本","去","把","性","好","应","开","它","合","还","因","由","其","些","然","前","外","天","政","四","日","那","社","义","事","平","形","相","全","表","间","样","与","关","各","重","新","线","内","数","正","心","反","你","明","看","原","又","么","利","比","或","但","质","气","第","向","道","命","此","变","条","只","没","结","解","问","意","建","月","公","无","系","军","很","情","者","最","立","代","想","已","通","并","提","直","题","党","程","展","五","果","料","象","员","革","位","入","常","文","总","次","品","式","活","设","及","管","特","件","长","求","老","头","基","资","边","流","路","级","少","图","山","统","接","知","较","将","组","见","计","别","她","手","角","期","根","论","运","农","指","几","九","区","强","放","决","西","被","干","做","必","战","先","回","则","任","取","据","处","队","南","给","色","光","门","即","保","治","北","造","百","规","热","领","七","海","口","东","导","器","压","志","世","金","增","争","济","阶","油","思","术","极","交","受","联","什","认","六","共","权","收","证","改","清","美","再","采","转","更","单","风","切","打","白","教","速","花","带","安","场","身","车","例","真","务","具","万","每","目","至","达","走","积","示","议","声","报","斗","完","类","八","离","华","名","确","才","科","张","信","马","节","话","米","整","空","元","况","今","集","温","传","土","许","步","群","广","石","记","需","段","研","界","拉","林","律","叫","且","究","观","越","织","装","影","算","低","持","音","众","书","布","复","容","儿","须","际","商","非","验","连","断","深","难","近","矿","千","周","委","素","技","备","半","办","青","省","列","习","响","约","支","般","史","感","劳","便","团","往","酸","历","市","克","何","除","消","构","府","称","太","准","精","值","号","率","族","维","划","选","标","写","存","候","毛","亲","快","效","斯","院","查","江","型","眼","王","按","格","养","易","置","派","层","片","始","却","专","状","育","厂","京","识","适","属","圆","包","火","住","调","满","县","局","照","参","红","细","引","听","该","铁","价","严","首","底","液","官","德","随","病","苏","失","尔","死","讲","配","女","黄","推","显","谈","罪","神","艺","呢","席","含","企","望","密","批","营","项","防","举","球","英","氧","势","告","李","台","落","木","帮","轮","破","亚","师","围","注","远","字","材","排","供","河","态","封","另","施","减","树","溶","怎","止","案","言","士","均","武","固","叶","鱼","波","视","仅","费","紧","爱","左","章","早","朝","害","续","轻","服","试","食","充","兵","源","判","护","司","足","某","练","差","致","板","田","降","黑","犯","负","击","范","继","兴","似","余","坚","曲","输","修","故","城","夫","够","送","笔","船","占","右","财","吃","富","春","职","觉","汉","画","功","巴","跟","虽","杂","飞","检","吸","助","升","阳","互","初","创","抗","考","投","坏","策","古","径","换","未","跑","留","钢","曾","端","责","站","简","述","钱","副","尽","帝","射","草","冲","承","独","令","限","阿","宣","环","双","请","超","微","让","控","州","良","轴","找","否","纪","益","依","优","顶","础","载","倒","房","突","坐","粉","敌","略","客","袁","冷","胜","绝","析","块","剂","测","丝","协","诉","念","陈","仍","罗","盐","友","洋","错","苦","夜","刑","移","频","逐","靠","混","母","短","皮","终","聚","汽","村","云","哪","既","距","卫","停","烈","央","察","烧","迅","境","若","印","洲","刻","括","激","孔","搞","甚","室","待","核","校","散","侵","吧","甲","游","久","菜","味","旧","模","湖","货","损","预","阻","毫","普","稳","乙","妈","植","息","扩","银","语","挥","酒","守","拿","序","纸","医","缺","雨","吗","针","刘","啊","急","唱","误","训","愿","审","附","获","茶","鲜","粮","斤","孩","脱","硫","肥","善","龙","演","父","渐","血","欢","械","掌","歌","沙","刚","攻","谓","盾","讨","晚","粒","乱","燃","矛","乎","杀","药","宁","鲁","贵","钟","煤","读","班","伯","香","介","迫","句","丰","培","握","兰","担","弦","蛋","沉","假","穿","执","答","乐","谁","顺","烟","缩","征","脸","喜","松","脚","困","异","免","背","星","福","买","染","井","概","慢","怕","磁","倍","祖","皇","促","静","补","评","翻","肉","践","尼","衣","宽","扬","棉","希","伤","操","垂","秋","宜","氢","套","督","振","架","亮","末","宪","庆","编","牛","触","映","雷","销","诗","座","居","抓","裂","胞","呼","娘","景","威","绿","晶","厚","盟","衡","鸡","孙","延","危","胶","屋","乡","临","陆","顾","掉","呀","灯","岁","措","束","耐","剧","玉","赵","跳","哥","季","课","凯","胡","额","款","绍","卷","齐","伟","蒸","殖","永","宗","苗","川","炉","岩","弱","零","杨","奏","沿","露","杆","探","滑","镇","饭","浓","航","怀","赶","库","夺","伊","灵","税","途","灭","赛","归","召","鼓","播","盘","裁","险","康","唯","录","菌","纯","借","糖","盖","横","符","私","努","堂","域","枪","润","幅","哈","竟","熟","虫","泽","脑","壤","碳","欧","遍","侧","寨","敢","彻","虑","斜","薄","庭","纳","弹","饲","伸","折","麦","湿","暗","荷","瓦","塞","床","筑","恶","户","访","塔","奇","透","梁","刀","旋","迹","卡","氯","遇","份","毒","泥","退","洗","摆","灰","彩","卖","耗","夏","择","忙","铜","献","硬","予","繁","圈","雪","函","亦","抽","篇","阵","阴","丁","尺","追","堆","雄","迎","泛","爸","楼","避","谋","吨","野","猪","旗","累","偏","典","馆","索","秦","脂","潮","爷","豆","忽","托","惊","塑","遗","愈","朱","替","纤","粗","倾","尚","痛","楚","谢","奋","购","磨","君","池","旁","碎","骨","监","捕","弟","暴","割","贯","殊","释","词","亡","壁","顿","宝","午","尘","闻","揭","炮","残","冬","桥","妇","警","综","招","吴","付","浮","遭","徐","您","摇","谷","赞","箱","隔","订","男","吹","园","纷","唐","败","宋","玻","巨","耕","坦","荣","闭","湾","键","凡","驻","锅","救","恩","剥","凝","碱","齿","截","炼","麻","纺","禁","废","盛","版","缓","净","睛","昌","婚","涉","筒","嘴","插","岸","朗","庄","街","藏","姑","贸","腐","奴","啦","惯","乘","伙","恢","匀","纱","扎","辩","耳","彪","臣","亿","璃","抵","脉","秀","萨","俄","网","舞","店","喷","纵","寸","汗","挂","洪","贺","闪","柬","爆","烯","津","稻","墙","软","勇","像","滚","厘","蒙","芳","肯","坡","柱","荡","腿","仪","旅","尾","轧","冰","贡","登","黎","削","钻","勒","逃","障","氨","郭","峰","币","港","伏","轨","亩","毕","擦","莫","刺","浪","秘","援","株","健","售","股","岛","甘","泡","睡","童","铸","汤","阀","休","汇","舍","牧","绕","炸","哲","磷","绩","朋","淡","尖","启","陷","柴","呈","徒","颜","泪","稍","忘","泵","蓝","拖","洞","授","镜","辛","壮","锋","贫","虚","弯","摩","泰","幼","廷","尊","窗","纲","弄","隶","疑","氏","宫","姐","震","瑞","怪","尤","琴","循","描","膜","违","夹","腰","缘","珠","穷","森","枝","竹","沟","催","绳","忆","邦","剩","幸","浆","栏","拥","牙","贮","礼","滤","钠","纹","罢","拍","咱","喊","袖","埃","勤","罚","焦","潜","伍","墨","欲","缝","姓","刊","饱","仿","奖","铝","鬼","丽","跨","默","挖","链","扫","喝","袋","炭","污","幕","诸","弧","励","梅","奶","洁","灾","舟","鉴","苯","讼","抱","毁","懂","寒","智","埔","寄","届","跃","渡","挑","丹","艰","贝","碰","拔","爹","戴","码","梦","芽","熔","赤","渔","哭","敬","颗","奔","铅","仲","虎","稀","妹","乏","珍","申","桌","遵","允","隆","螺","仓","魏","锐","晓","氮","兼","隐","碍","赫","拨","忠","肃","缸","牵","抢","博","巧","壳","兄","杜","讯","诚","碧","祥","柯","页","巡","矩","悲","灌","龄","伦","票","寻","桂","铺","圣","恐","恰","郑","趣","抬","荒","腾","贴","柔","滴","猛","阔","辆","妻","填","撤","储","签","闹","扰","紫","砂","递","戏","吊","陶","伐","喂","疗","瓶","婆","抚","臂","摸","忍","虾","蜡","邻","胸","巩","挤","偶","弃","槽","劲","乳","邓","吉","仁","烂","砖","租","乌","舰","伴","瓜","浅","丙","暂","燥","橡","柳","迷","暖","牌","秧","胆","详","簧","踏","瓷","谱","呆","宾","糊","洛","辉","愤","竞","隙","怒","粘","乃","绪","肩","籍","敏","涂","熙","皆","侦","悬","掘","享","纠","醒","狂","锁","淀","恨","牲","霸","爬","赏","逆","玩","陵","祝","秒","浙","貌","役","彼","悉","鸭","趋","凤","晨","畜","辈","秩","卵","署","梯","炎","滩","棋","驱","筛","峡","冒","啥","寿","译","浸","泉","帽","迟","硅","疆","贷","漏","稿","冠","嫩","胁","芯","牢","叛","蚀","奥","鸣","岭","羊","凭","串","塘","绘","酵","融","盆","锡","庙","筹","冻","辅","摄","袭","筋","拒","僚","旱","钾","鸟","漆","沈","眉","疏","添","棒","穗","硝","韩","逼","扭","侨","凉","挺","碗","栽","炒","杯","患","馏","劝","豪","辽","勃","鸿","旦","吏","拜","狗","埋","辊","掩","饮","搬","骂","辞","勾","扣","估","蒋","绒","雾","丈","朵","姆","拟","宇","辑","陕","雕","偿","蓄","崇","剪","倡","厅","咬","驶","薯","刷","斥","番","赋","奉","佛","浇","漫","曼","扇","钙","桃","扶","仔","返","俗","亏","腔","鞋","棱","覆","框","悄","叔","撞","骗","勘","旺","沸","孤","吐","孟","渠","屈","疾","妙","惜","仰","狠","胀","谐","抛","霉","桑","岗","嘛","衰","盗","渗","脏","赖","涌","甜","曹","阅","肌","哩","厉","烃","纬","毅","昨","伪","症","煮","叹","钉","搭","茎","笼","酷","偷","弓","锥","恒","杰","坑","鼻","翼","纶","叙","狱","逮","罐","络","棚","抑","膨","蔬","寺","骤","穆","冶","枯","册","尸","凸","绅","坯","牺","焰","轰","欣","晋","瘦","御","锭","锦","丧","旬","锻","垄","搜","扑","邀","亭","酯","迈","舒","脆","酶","闲","忧","酚","顽","羽","涨","卸","仗","陪","辟","惩","杭","姚","肚","捉","飘","漂","昆","欺","吾","郎","烷","汁","呵","饰","萧","雅","邮","迁","燕","撒","姻","赴","宴","烦","债","帐","斑","铃","旨","醇","董","饼","雏","姿","拌","傅","腹","妥","揉","贤","拆","歪","葡","胺","丢","浩","徽","昂","垫","挡","览","贪","慰","缴","汪","慌","冯","诺","姜","谊","凶","劣","诬","耀","昏","躺","盈","骑","乔","溪","丛","卢","抹","闷","咨","刮","驾","缆","悟","摘","铒","掷","颇","幻","柄","惠","惨","佳","仇","腊","窝","涤","剑","瞧","堡","泼","葱","罩","霍","捞","胎","苍","滨","俩","捅","湘","砍","霞","邵","萄","疯","淮","遂","熊","粪","烘","宿","档","戈","驳","嫂","裕","徙","箭","捐","肠","撑","晒","辨","殿","莲","摊","搅","酱","屏","疫","哀","蔡","堵","沫","皱","畅","叠","阁","莱","敲","辖","钩","痕","坝","巷","饿","祸","丘","玄","溜","曰","逻","彭","尝","卿","妨","艇","吞","韦","怨","矮","歇"]')},4262:module=>{"use strict";module.exports=JSON.parse('["的","一","是","在","不","了","有","和","人","這","中","大","為","上","個","國","我","以","要","他","時","來","用","們","生","到","作","地","於","出","就","分","對","成","會","可","主","發","年","動","同","工","也","能","下","過","子","說","產","種","面","而","方","後","多","定","行","學","法","所","民","得","經","十","三","之","進","著","等","部","度","家","電","力","裡","如","水","化","高","自","二","理","起","小","物","現","實","加","量","都","兩","體","制","機","當","使","點","從","業","本","去","把","性","好","應","開","它","合","還","因","由","其","些","然","前","外","天","政","四","日","那","社","義","事","平","形","相","全","表","間","樣","與","關","各","重","新","線","內","數","正","心","反","你","明","看","原","又","麼","利","比","或","但","質","氣","第","向","道","命","此","變","條","只","沒","結","解","問","意","建","月","公","無","系","軍","很","情","者","最","立","代","想","已","通","並","提","直","題","黨","程","展","五","果","料","象","員","革","位","入","常","文","總","次","品","式","活","設","及","管","特","件","長","求","老","頭","基","資","邊","流","路","級","少","圖","山","統","接","知","較","將","組","見","計","別","她","手","角","期","根","論","運","農","指","幾","九","區","強","放","決","西","被","幹","做","必","戰","先","回","則","任","取","據","處","隊","南","給","色","光","門","即","保","治","北","造","百","規","熱","領","七","海","口","東","導","器","壓","志","世","金","增","爭","濟","階","油","思","術","極","交","受","聯","什","認","六","共","權","收","證","改","清","美","再","採","轉","更","單","風","切","打","白","教","速","花","帶","安","場","身","車","例","真","務","具","萬","每","目","至","達","走","積","示","議","聲","報","鬥","完","類","八","離","華","名","確","才","科","張","信","馬","節","話","米","整","空","元","況","今","集","溫","傳","土","許","步","群","廣","石","記","需","段","研","界","拉","林","律","叫","且","究","觀","越","織","裝","影","算","低","持","音","眾","書","布","复","容","兒","須","際","商","非","驗","連","斷","深","難","近","礦","千","週","委","素","技","備","半","辦","青","省","列","習","響","約","支","般","史","感","勞","便","團","往","酸","歷","市","克","何","除","消","構","府","稱","太","準","精","值","號","率","族","維","劃","選","標","寫","存","候","毛","親","快","效","斯","院","查","江","型","眼","王","按","格","養","易","置","派","層","片","始","卻","專","狀","育","廠","京","識","適","屬","圓","包","火","住","調","滿","縣","局","照","參","紅","細","引","聽","該","鐵","價","嚴","首","底","液","官","德","隨","病","蘇","失","爾","死","講","配","女","黃","推","顯","談","罪","神","藝","呢","席","含","企","望","密","批","營","項","防","舉","球","英","氧","勢","告","李","台","落","木","幫","輪","破","亞","師","圍","注","遠","字","材","排","供","河","態","封","另","施","減","樹","溶","怎","止","案","言","士","均","武","固","葉","魚","波","視","僅","費","緊","愛","左","章","早","朝","害","續","輕","服","試","食","充","兵","源","判","護","司","足","某","練","差","致","板","田","降","黑","犯","負","擊","范","繼","興","似","餘","堅","曲","輸","修","故","城","夫","夠","送","筆","船","佔","右","財","吃","富","春","職","覺","漢","畫","功","巴","跟","雖","雜","飛","檢","吸","助","昇","陽","互","初","創","抗","考","投","壞","策","古","徑","換","未","跑","留","鋼","曾","端","責","站","簡","述","錢","副","盡","帝","射","草","衝","承","獨","令","限","阿","宣","環","雙","請","超","微","讓","控","州","良","軸","找","否","紀","益","依","優","頂","礎","載","倒","房","突","坐","粉","敵","略","客","袁","冷","勝","絕","析","塊","劑","測","絲","協","訴","念","陳","仍","羅","鹽","友","洋","錯","苦","夜","刑","移","頻","逐","靠","混","母","短","皮","終","聚","汽","村","雲","哪","既","距","衛","停","烈","央","察","燒","迅","境","若","印","洲","刻","括","激","孔","搞","甚","室","待","核","校","散","侵","吧","甲","遊","久","菜","味","舊","模","湖","貨","損","預","阻","毫","普","穩","乙","媽","植","息","擴","銀","語","揮","酒","守","拿","序","紙","醫","缺","雨","嗎","針","劉","啊","急","唱","誤","訓","願","審","附","獲","茶","鮮","糧","斤","孩","脫","硫","肥","善","龍","演","父","漸","血","歡","械","掌","歌","沙","剛","攻","謂","盾","討","晚","粒","亂","燃","矛","乎","殺","藥","寧","魯","貴","鐘","煤","讀","班","伯","香","介","迫","句","豐","培","握","蘭","擔","弦","蛋","沉","假","穿","執","答","樂","誰","順","煙","縮","徵","臉","喜","松","腳","困","異","免","背","星","福","買","染","井","概","慢","怕","磁","倍","祖","皇","促","靜","補","評","翻","肉","踐","尼","衣","寬","揚","棉","希","傷","操","垂","秋","宜","氫","套","督","振","架","亮","末","憲","慶","編","牛","觸","映","雷","銷","詩","座","居","抓","裂","胞","呼","娘","景","威","綠","晶","厚","盟","衡","雞","孫","延","危","膠","屋","鄉","臨","陸","顧","掉","呀","燈","歲","措","束","耐","劇","玉","趙","跳","哥","季","課","凱","胡","額","款","紹","卷","齊","偉","蒸","殖","永","宗","苗","川","爐","岩","弱","零","楊","奏","沿","露","桿","探","滑","鎮","飯","濃","航","懷","趕","庫","奪","伊","靈","稅","途","滅","賽","歸","召","鼓","播","盤","裁","險","康","唯","錄","菌","純","借","糖","蓋","橫","符","私","努","堂","域","槍","潤","幅","哈","竟","熟","蟲","澤","腦","壤","碳","歐","遍","側","寨","敢","徹","慮","斜","薄","庭","納","彈","飼","伸","折","麥","濕","暗","荷","瓦","塞","床","築","惡","戶","訪","塔","奇","透","梁","刀","旋","跡","卡","氯","遇","份","毒","泥","退","洗","擺","灰","彩","賣","耗","夏","擇","忙","銅","獻","硬","予","繁","圈","雪","函","亦","抽","篇","陣","陰","丁","尺","追","堆","雄","迎","泛","爸","樓","避","謀","噸","野","豬","旗","累","偏","典","館","索","秦","脂","潮","爺","豆","忽","托","驚","塑","遺","愈","朱","替","纖","粗","傾","尚","痛","楚","謝","奮","購","磨","君","池","旁","碎","骨","監","捕","弟","暴","割","貫","殊","釋","詞","亡","壁","頓","寶","午","塵","聞","揭","炮","殘","冬","橋","婦","警","綜","招","吳","付","浮","遭","徐","您","搖","谷","贊","箱","隔","訂","男","吹","園","紛","唐","敗","宋","玻","巨","耕","坦","榮","閉","灣","鍵","凡","駐","鍋","救","恩","剝","凝","鹼","齒","截","煉","麻","紡","禁","廢","盛","版","緩","淨","睛","昌","婚","涉","筒","嘴","插","岸","朗","莊","街","藏","姑","貿","腐","奴","啦","慣","乘","夥","恢","勻","紗","扎","辯","耳","彪","臣","億","璃","抵","脈","秀","薩","俄","網","舞","店","噴","縱","寸","汗","掛","洪","賀","閃","柬","爆","烯","津","稻","牆","軟","勇","像","滾","厘","蒙","芳","肯","坡","柱","盪","腿","儀","旅","尾","軋","冰","貢","登","黎","削","鑽","勒","逃","障","氨","郭","峰","幣","港","伏","軌","畝","畢","擦","莫","刺","浪","秘","援","株","健","售","股","島","甘","泡","睡","童","鑄","湯","閥","休","匯","舍","牧","繞","炸","哲","磷","績","朋","淡","尖","啟","陷","柴","呈","徒","顏","淚","稍","忘","泵","藍","拖","洞","授","鏡","辛","壯","鋒","貧","虛","彎","摩","泰","幼","廷","尊","窗","綱","弄","隸","疑","氏","宮","姐","震","瑞","怪","尤","琴","循","描","膜","違","夾","腰","緣","珠","窮","森","枝","竹","溝","催","繩","憶","邦","剩","幸","漿","欄","擁","牙","貯","禮","濾","鈉","紋","罷","拍","咱","喊","袖","埃","勤","罰","焦","潛","伍","墨","欲","縫","姓","刊","飽","仿","獎","鋁","鬼","麗","跨","默","挖","鏈","掃","喝","袋","炭","污","幕","諸","弧","勵","梅","奶","潔","災","舟","鑑","苯","訟","抱","毀","懂","寒","智","埔","寄","屆","躍","渡","挑","丹","艱","貝","碰","拔","爹","戴","碼","夢","芽","熔","赤","漁","哭","敬","顆","奔","鉛","仲","虎","稀","妹","乏","珍","申","桌","遵","允","隆","螺","倉","魏","銳","曉","氮","兼","隱","礙","赫","撥","忠","肅","缸","牽","搶","博","巧","殼","兄","杜","訊","誠","碧","祥","柯","頁","巡","矩","悲","灌","齡","倫","票","尋","桂","鋪","聖","恐","恰","鄭","趣","抬","荒","騰","貼","柔","滴","猛","闊","輛","妻","填","撤","儲","簽","鬧","擾","紫","砂","遞","戲","吊","陶","伐","餵","療","瓶","婆","撫","臂","摸","忍","蝦","蠟","鄰","胸","鞏","擠","偶","棄","槽","勁","乳","鄧","吉","仁","爛","磚","租","烏","艦","伴","瓜","淺","丙","暫","燥","橡","柳","迷","暖","牌","秧","膽","詳","簧","踏","瓷","譜","呆","賓","糊","洛","輝","憤","競","隙","怒","粘","乃","緒","肩","籍","敏","塗","熙","皆","偵","懸","掘","享","糾","醒","狂","鎖","淀","恨","牲","霸","爬","賞","逆","玩","陵","祝","秒","浙","貌","役","彼","悉","鴨","趨","鳳","晨","畜","輩","秩","卵","署","梯","炎","灘","棋","驅","篩","峽","冒","啥","壽","譯","浸","泉","帽","遲","矽","疆","貸","漏","稿","冠","嫩","脅","芯","牢","叛","蝕","奧","鳴","嶺","羊","憑","串","塘","繪","酵","融","盆","錫","廟","籌","凍","輔","攝","襲","筋","拒","僚","旱","鉀","鳥","漆","沈","眉","疏","添","棒","穗","硝","韓","逼","扭","僑","涼","挺","碗","栽","炒","杯","患","餾","勸","豪","遼","勃","鴻","旦","吏","拜","狗","埋","輥","掩","飲","搬","罵","辭","勾","扣","估","蔣","絨","霧","丈","朵","姆","擬","宇","輯","陝","雕","償","蓄","崇","剪","倡","廳","咬","駛","薯","刷","斥","番","賦","奉","佛","澆","漫","曼","扇","鈣","桃","扶","仔","返","俗","虧","腔","鞋","棱","覆","框","悄","叔","撞","騙","勘","旺","沸","孤","吐","孟","渠","屈","疾","妙","惜","仰","狠","脹","諧","拋","黴","桑","崗","嘛","衰","盜","滲","臟","賴","湧","甜","曹","閱","肌","哩","厲","烴","緯","毅","昨","偽","症","煮","嘆","釘","搭","莖","籠","酷","偷","弓","錐","恆","傑","坑","鼻","翼","綸","敘","獄","逮","罐","絡","棚","抑","膨","蔬","寺","驟","穆","冶","枯","冊","屍","凸","紳","坯","犧","焰","轟","欣","晉","瘦","禦","錠","錦","喪","旬","鍛","壟","搜","撲","邀","亭","酯","邁","舒","脆","酶","閒","憂","酚","頑","羽","漲","卸","仗","陪","闢","懲","杭","姚","肚","捉","飄","漂","昆","欺","吾","郎","烷","汁","呵","飾","蕭","雅","郵","遷","燕","撒","姻","赴","宴","煩","債","帳","斑","鈴","旨","醇","董","餅","雛","姿","拌","傅","腹","妥","揉","賢","拆","歪","葡","胺","丟","浩","徽","昂","墊","擋","覽","貪","慰","繳","汪","慌","馮","諾","姜","誼","兇","劣","誣","耀","昏","躺","盈","騎","喬","溪","叢","盧","抹","悶","諮","刮","駕","纜","悟","摘","鉺","擲","頗","幻","柄","惠","慘","佳","仇","臘","窩","滌","劍","瞧","堡","潑","蔥","罩","霍","撈","胎","蒼","濱","倆","捅","湘","砍","霞","邵","萄","瘋","淮","遂","熊","糞","烘","宿","檔","戈","駁","嫂","裕","徙","箭","捐","腸","撐","曬","辨","殿","蓮","攤","攪","醬","屏","疫","哀","蔡","堵","沫","皺","暢","疊","閣","萊","敲","轄","鉤","痕","壩","巷","餓","禍","丘","玄","溜","曰","邏","彭","嘗","卿","妨","艇","吞","韋","怨","矮","歇"]')},32:module=>{"use strict";module.exports=JSON.parse('["abdikace","abeceda","adresa","agrese","akce","aktovka","alej","alkohol","amputace","ananas","andulka","anekdota","anketa","antika","anulovat","archa","arogance","asfalt","asistent","aspirace","astma","astronom","atlas","atletika","atol","autobus","azyl","babka","bachor","bacil","baculka","badatel","bageta","bagr","bahno","bakterie","balada","baletka","balkon","balonek","balvan","balza","bambus","bankomat","barbar","baret","barman","baroko","barva","baterka","batoh","bavlna","bazalka","bazilika","bazuka","bedna","beran","beseda","bestie","beton","bezinka","bezmoc","beztak","bicykl","bidlo","biftek","bikiny","bilance","biograf","biolog","bitva","bizon","blahobyt","blatouch","blecha","bledule","blesk","blikat","blizna","blokovat","bloudit","blud","bobek","bobr","bodlina","bodnout","bohatost","bojkot","bojovat","bokorys","bolest","borec","borovice","bota","boubel","bouchat","bouda","boule","bourat","boxer","bradavka","brambora","branka","bratr","brepta","briketa","brko","brloh","bronz","broskev","brunetka","brusinka","brzda","brzy","bublina","bubnovat","buchta","buditel","budka","budova","bufet","bujarost","bukvice","buldok","bulva","bunda","bunkr","burza","butik","buvol","buzola","bydlet","bylina","bytovka","bzukot","capart","carevna","cedr","cedule","cejch","cejn","cela","celer","celkem","celnice","cenina","cennost","cenovka","centrum","cenzor","cestopis","cetka","chalupa","chapadlo","charita","chata","chechtat","chemie","chichot","chirurg","chlad","chleba","chlubit","chmel","chmura","chobot","chochol","chodba","cholera","chomout","chopit","choroba","chov","chrapot","chrlit","chrt","chrup","chtivost","chudina","chutnat","chvat","chvilka","chvost","chyba","chystat","chytit","cibule","cigareta","cihelna","cihla","cinkot","cirkus","cisterna","citace","citrus","cizinec","cizost","clona","cokoliv","couvat","ctitel","ctnost","cudnost","cuketa","cukr","cupot","cvaknout","cval","cvik","cvrkot","cyklista","daleko","dareba","datel","datum","dcera","debata","dechovka","decibel","deficit","deflace","dekl","dekret","demokrat","deprese","derby","deska","detektiv","dikobraz","diktovat","dioda","diplom","disk","displej","divadlo","divoch","dlaha","dlouho","dluhopis","dnes","dobro","dobytek","docent","dochutit","dodnes","dohled","dohoda","dohra","dojem","dojnice","doklad","dokola","doktor","dokument","dolar","doleva","dolina","doma","dominant","domluvit","domov","donutit","dopad","dopis","doplnit","doposud","doprovod","dopustit","dorazit","dorost","dort","dosah","doslov","dostatek","dosud","dosyta","dotaz","dotek","dotknout","doufat","doutnat","dovozce","dozadu","doznat","dozorce","drahota","drak","dramatik","dravec","draze","drdol","drobnost","drogerie","drozd","drsnost","drtit","drzost","duben","duchovno","dudek","duha","duhovka","dusit","dusno","dutost","dvojice","dvorec","dynamit","ekolog","ekonomie","elektron","elipsa","email","emise","emoce","empatie","epizoda","epocha","epopej","epos","esej","esence","eskorta","eskymo","etiketa","euforie","evoluce","exekuce","exkurze","expedice","exploze","export","extrakt","facka","fajfka","fakulta","fanatik","fantazie","farmacie","favorit","fazole","federace","fejeton","fenka","fialka","figurant","filozof","filtr","finance","finta","fixace","fjord","flanel","flirt","flotila","fond","fosfor","fotbal","fotka","foton","frakce","freska","fronta","fukar","funkce","fyzika","galeje","garant","genetika","geolog","gilotina","glazura","glejt","golem","golfista","gotika","graf","gramofon","granule","grep","gril","grog","groteska","guma","hadice","hadr","hala","halenka","hanba","hanopis","harfa","harpuna","havran","hebkost","hejkal","hejno","hejtman","hektar","helma","hematom","herec","herna","heslo","hezky","historik","hladovka","hlasivky","hlava","hledat","hlen","hlodavec","hloh","hloupost","hltat","hlubina","hluchota","hmat","hmota","hmyz","hnis","hnojivo","hnout","hoblina","hoboj","hoch","hodiny","hodlat","hodnota","hodovat","hojnost","hokej","holinka","holka","holub","homole","honitba","honorace","horal","horda","horizont","horko","horlivec","hormon","hornina","horoskop","horstvo","hospoda","hostina","hotovost","houba","houf","houpat","houska","hovor","hradba","hranice","hravost","hrazda","hrbolek","hrdina","hrdlo","hrdost","hrnek","hrobka","hromada","hrot","hrouda","hrozen","hrstka","hrubost","hryzat","hubenost","hubnout","hudba","hukot","humr","husita","hustota","hvozd","hybnost","hydrant","hygiena","hymna","hysterik","idylka","ihned","ikona","iluze","imunita","infekce","inflace","inkaso","inovace","inspekce","internet","invalida","investor","inzerce","ironie","jablko","jachta","jahoda","jakmile","jakost","jalovec","jantar","jarmark","jaro","jasan","jasno","jatka","javor","jazyk","jedinec","jedle","jednatel","jehlan","jekot","jelen","jelito","jemnost","jenom","jepice","jeseter","jevit","jezdec","jezero","jinak","jindy","jinoch","jiskra","jistota","jitrnice","jizva","jmenovat","jogurt","jurta","kabaret","kabel","kabinet","kachna","kadet","kadidlo","kahan","kajak","kajuta","kakao","kaktus","kalamita","kalhoty","kalibr","kalnost","kamera","kamkoliv","kamna","kanibal","kanoe","kantor","kapalina","kapela","kapitola","kapka","kaple","kapota","kapr","kapusta","kapybara","karamel","karotka","karton","kasa","katalog","katedra","kauce","kauza","kavalec","kazajka","kazeta","kazivost","kdekoliv","kdesi","kedluben","kemp","keramika","kino","klacek","kladivo","klam","klapot","klasika","klaun","klec","klenba","klepat","klesnout","klid","klima","klisna","klobouk","klokan","klopa","kloub","klubovna","klusat","kluzkost","kmen","kmitat","kmotr","kniha","knot","koalice","koberec","kobka","kobliha","kobyla","kocour","kohout","kojenec","kokos","koktejl","kolaps","koleda","kolize","kolo","komando","kometa","komik","komnata","komora","kompas","komunita","konat","koncept","kondice","konec","konfese","kongres","konina","konkurs","kontakt","konzerva","kopanec","kopie","kopnout","koprovka","korbel","korektor","kormidlo","koroptev","korpus","koruna","koryto","korzet","kosatec","kostka","kotel","kotleta","kotoul","koukat","koupelna","kousek","kouzlo","kovboj","koza","kozoroh","krabice","krach","krajina","kralovat","krasopis","kravata","kredit","krejcar","kresba","kreveta","kriket","kritik","krize","krkavec","krmelec","krmivo","krocan","krok","kronika","kropit","kroupa","krovka","krtek","kruhadlo","krupice","krutost","krvinka","krychle","krypta","krystal","kryt","kudlanka","kufr","kujnost","kukla","kulajda","kulich","kulka","kulomet","kultura","kuna","kupodivu","kurt","kurzor","kutil","kvalita","kvasinka","kvestor","kynolog","kyselina","kytara","kytice","kytka","kytovec","kyvadlo","labrador","lachtan","ladnost","laik","lakomec","lamela","lampa","lanovka","lasice","laso","lastura","latinka","lavina","lebka","leckdy","leden","lednice","ledovka","ledvina","legenda","legie","legrace","lehce","lehkost","lehnout","lektvar","lenochod","lentilka","lepenka","lepidlo","letadlo","letec","letmo","letokruh","levhart","levitace","levobok","libra","lichotka","lidojed","lidskost","lihovina","lijavec","lilek","limetka","linie","linka","linoleum","listopad","litina","litovat","lobista","lodivod","logika","logoped","lokalita","loket","lomcovat","lopata","lopuch","lord","losos","lotr","loudal","louh","louka","louskat","lovec","lstivost","lucerna","lucifer","lump","lusk","lustrace","lvice","lyra","lyrika","lysina","madam","madlo","magistr","mahagon","majetek","majitel","majorita","makak","makovice","makrela","malba","malina","malovat","malvice","maminka","mandle","manko","marnost","masakr","maskot","masopust","matice","matrika","maturita","mazanec","mazivo","mazlit","mazurka","mdloba","mechanik","meditace","medovina","melasa","meloun","mentolka","metla","metoda","metr","mezera","migrace","mihnout","mihule","mikina","mikrofon","milenec","milimetr","milost","mimika","mincovna","minibar","minomet","minulost","miska","mistr","mixovat","mladost","mlha","mlhovina","mlok","mlsat","mluvit","mnich","mnohem","mobil","mocnost","modelka","modlitba","mohyla","mokro","molekula","momentka","monarcha","monokl","monstrum","montovat","monzun","mosaz","moskyt","most","motivace","motorka","motyka","moucha","moudrost","mozaika","mozek","mozol","mramor","mravenec","mrkev","mrtvola","mrzet","mrzutost","mstitel","mudrc","muflon","mulat","mumie","munice","muset","mutace","muzeum","muzikant","myslivec","mzda","nabourat","nachytat","nadace","nadbytek","nadhoz","nadobro","nadpis","nahlas","nahnat","nahodile","nahradit","naivita","najednou","najisto","najmout","naklonit","nakonec","nakrmit","nalevo","namazat","namluvit","nanometr","naoko","naopak","naostro","napadat","napevno","naplnit","napnout","naposled","naprosto","narodit","naruby","narychlo","nasadit","nasekat","naslepo","nastat","natolik","navenek","navrch","navzdory","nazvat","nebe","nechat","necky","nedaleko","nedbat","neduh","negace","nehet","nehoda","nejen","nejprve","neklid","nelibost","nemilost","nemoc","neochota","neonka","nepokoj","nerost","nerv","nesmysl","nesoulad","netvor","neuron","nevina","nezvykle","nicota","nijak","nikam","nikdy","nikl","nikterak","nitro","nocleh","nohavice","nominace","nora","norek","nositel","nosnost","nouze","noviny","novota","nozdra","nuda","nudle","nuget","nutit","nutnost","nutrie","nymfa","obal","obarvit","obava","obdiv","obec","obehnat","obejmout","obezita","obhajoba","obilnice","objasnit","objekt","obklopit","oblast","oblek","obliba","obloha","obluda","obnos","obohatit","obojek","obout","obrazec","obrna","obruba","obrys","obsah","obsluha","obstarat","obuv","obvaz","obvinit","obvod","obvykle","obyvatel","obzor","ocas","ocel","ocenit","ochladit","ochota","ochrana","ocitnout","odboj","odbyt","odchod","odcizit","odebrat","odeslat","odevzdat","odezva","odhadce","odhodit","odjet","odjinud","odkaz","odkoupit","odliv","odluka","odmlka","odolnost","odpad","odpis","odplout","odpor","odpustit","odpykat","odrazka","odsoudit","odstup","odsun","odtok","odtud","odvaha","odveta","odvolat","odvracet","odznak","ofina","ofsajd","ohlas","ohnisko","ohrada","ohrozit","ohryzek","okap","okenice","oklika","okno","okouzlit","okovy","okrasa","okres","okrsek","okruh","okupant","okurka","okusit","olejnina","olizovat","omak","omeleta","omezit","omladina","omlouvat","omluva","omyl","onehdy","opakovat","opasek","operace","opice","opilost","opisovat","opora","opozice","opravdu","oproti","orbital","orchestr","orgie","orlice","orloj","ortel","osada","oschnout","osika","osivo","oslava","oslepit","oslnit","oslovit","osnova","osoba","osolit","ospalec","osten","ostraha","ostuda","ostych","osvojit","oteplit","otisk","otop","otrhat","otrlost","otrok","otruby","otvor","ovanout","ovar","oves","ovlivnit","ovoce","oxid","ozdoba","pachatel","pacient","padouch","pahorek","pakt","palanda","palec","palivo","paluba","pamflet","pamlsek","panenka","panika","panna","panovat","panstvo","pantofle","paprika","parketa","parodie","parta","paruka","paryba","paseka","pasivita","pastelka","patent","patrona","pavouk","pazneht","pazourek","pecka","pedagog","pejsek","peklo","peloton","penalta","pendrek","penze","periskop","pero","pestrost","petarda","petice","petrolej","pevnina","pexeso","pianista","piha","pijavice","pikle","piknik","pilina","pilnost","pilulka","pinzeta","pipeta","pisatel","pistole","pitevna","pivnice","pivovar","placenta","plakat","plamen","planeta","plastika","platit","plavidlo","plaz","plech","plemeno","plenta","ples","pletivo","plevel","plivat","plnit","plno","plocha","plodina","plomba","plout","pluk","plyn","pobavit","pobyt","pochod","pocit","poctivec","podat","podcenit","podepsat","podhled","podivit","podklad","podmanit","podnik","podoba","podpora","podraz","podstata","podvod","podzim","poezie","pohanka","pohnutka","pohovor","pohroma","pohyb","pointa","pojistka","pojmout","pokazit","pokles","pokoj","pokrok","pokuta","pokyn","poledne","polibek","polknout","poloha","polynom","pomalu","pominout","pomlka","pomoc","pomsta","pomyslet","ponechat","ponorka","ponurost","popadat","popel","popisek","poplach","poprosit","popsat","popud","poradce","porce","porod","porucha","poryv","posadit","posed","posila","poskok","poslanec","posoudit","pospolu","postava","posudek","posyp","potah","potkan","potlesk","potomek","potrava","potupa","potvora","poukaz","pouto","pouzdro","povaha","povidla","povlak","povoz","povrch","povstat","povyk","povzdech","pozdrav","pozemek","poznatek","pozor","pozvat","pracovat","prahory","praktika","prales","praotec","praporek","prase","pravda","princip","prkno","probudit","procento","prodej","profese","prohra","projekt","prolomit","promile","pronikat","propad","prorok","prosba","proton","proutek","provaz","prskavka","prsten","prudkost","prut","prvek","prvohory","psanec","psovod","pstruh","ptactvo","puberta","puch","pudl","pukavec","puklina","pukrle","pult","pumpa","punc","pupen","pusa","pusinka","pustina","putovat","putyka","pyramida","pysk","pytel","racek","rachot","radiace","radnice","radon","raft","ragby","raketa","rakovina","rameno","rampouch","rande","rarach","rarita","rasovna","rastr","ratolest","razance","razidlo","reagovat","reakce","recept","redaktor","referent","reflex","rejnok","reklama","rekord","rekrut","rektor","reputace","revize","revma","revolver","rezerva","riskovat","riziko","robotika","rodokmen","rohovka","rokle","rokoko","romaneto","ropovod","ropucha","rorejs","rosol","rostlina","rotmistr","rotoped","rotunda","roubenka","roucho","roup","roura","rovina","rovnice","rozbor","rozchod","rozdat","rozeznat","rozhodce","rozinka","rozjezd","rozkaz","rozloha","rozmar","rozpad","rozruch","rozsah","roztok","rozum","rozvod","rubrika","ruchadlo","rukavice","rukopis","ryba","rybolov","rychlost","rydlo","rypadlo","rytina","ryzost","sadista","sahat","sako","samec","samizdat","samota","sanitka","sardinka","sasanka","satelit","sazba","sazenice","sbor","schovat","sebranka","secese","sedadlo","sediment","sedlo","sehnat","sejmout","sekera","sekta","sekunda","sekvoje","semeno","seno","servis","sesadit","seshora","seskok","seslat","sestra","sesuv","sesypat","setba","setina","setkat","setnout","setrvat","sever","seznam","shoda","shrnout","sifon","silnice","sirka","sirotek","sirup","situace","skafandr","skalisko","skanzen","skaut","skeptik","skica","skladba","sklenice","sklo","skluz","skoba","skokan","skoro","skripta","skrz","skupina","skvost","skvrna","slabika","sladidlo","slanina","slast","slavnost","sledovat","slepec","sleva","slezina","slib","slina","sliznice","slon","sloupek","slovo","sluch","sluha","slunce","slupka","slza","smaragd","smetana","smilstvo","smlouva","smog","smrad","smrk","smrtka","smutek","smysl","snad","snaha","snob","sobota","socha","sodovka","sokol","sopka","sotva","souboj","soucit","soudce","souhlas","soulad","soumrak","souprava","soused","soutok","souviset","spalovna","spasitel","spis","splav","spodek","spojenec","spolu","sponzor","spornost","spousta","sprcha","spustit","sranda","sraz","srdce","srna","srnec","srovnat","srpen","srst","srub","stanice","starosta","statika","stavba","stehno","stezka","stodola","stolek","stopa","storno","stoupat","strach","stres","strhnout","strom","struna","studna","stupnice","stvol","styk","subjekt","subtropy","suchar","sudost","sukno","sundat","sunout","surikata","surovina","svah","svalstvo","svetr","svatba","svazek","svisle","svitek","svoboda","svodidlo","svorka","svrab","sykavka","sykot","synek","synovec","sypat","sypkost","syrovost","sysel","sytost","tabletka","tabule","tahoun","tajemno","tajfun","tajga","tajit","tajnost","taktika","tamhle","tampon","tancovat","tanec","tanker","tapeta","tavenina","tazatel","technika","tehdy","tekutina","telefon","temnota","tendence","tenista","tenor","teplota","tepna","teprve","terapie","termoska","textil","ticho","tiskopis","titulek","tkadlec","tkanina","tlapka","tleskat","tlukot","tlupa","tmel","toaleta","topinka","topol","torzo","touha","toulec","tradice","traktor","tramp","trasa","traverza","trefit","trest","trezor","trhavina","trhlina","trochu","trojice","troska","trouba","trpce","trpitel","trpkost","trubec","truchlit","truhlice","trus","trvat","tudy","tuhnout","tuhost","tundra","turista","turnaj","tuzemsko","tvaroh","tvorba","tvrdost","tvrz","tygr","tykev","ubohost","uboze","ubrat","ubrousek","ubrus","ubytovna","ucho","uctivost","udivit","uhradit","ujednat","ujistit","ujmout","ukazatel","uklidnit","uklonit","ukotvit","ukrojit","ulice","ulita","ulovit","umyvadlo","unavit","uniforma","uniknout","upadnout","uplatnit","uplynout","upoutat","upravit","uran","urazit","usednout","usilovat","usmrtit","usnadnit","usnout","usoudit","ustlat","ustrnout","utahovat","utkat","utlumit","utonout","utopenec","utrousit","uvalit","uvolnit","uvozovka","uzdravit","uzel","uzenina","uzlina","uznat","vagon","valcha","valoun","vana","vandal","vanilka","varan","varhany","varovat","vcelku","vchod","vdova","vedro","vegetace","vejce","velbloud","veletrh","velitel","velmoc","velryba","venkov","veranda","verze","veselka","veskrze","vesnice","vespodu","vesta","veterina","veverka","vibrace","vichr","videohra","vidina","vidle","vila","vinice","viset","vitalita","vize","vizitka","vjezd","vklad","vkus","vlajka","vlak","vlasec","vlevo","vlhkost","vliv","vlnovka","vloupat","vnucovat","vnuk","voda","vodivost","vodoznak","vodstvo","vojensky","vojna","vojsko","volant","volba","volit","volno","voskovka","vozidlo","vozovna","vpravo","vrabec","vracet","vrah","vrata","vrba","vrcholek","vrhat","vrstva","vrtule","vsadit","vstoupit","vstup","vtip","vybavit","vybrat","vychovat","vydat","vydra","vyfotit","vyhledat","vyhnout","vyhodit","vyhradit","vyhubit","vyjasnit","vyjet","vyjmout","vyklopit","vykonat","vylekat","vymazat","vymezit","vymizet","vymyslet","vynechat","vynikat","vynutit","vypadat","vyplatit","vypravit","vypustit","vyrazit","vyrovnat","vyrvat","vyslovit","vysoko","vystavit","vysunout","vysypat","vytasit","vytesat","vytratit","vyvinout","vyvolat","vyvrhel","vyzdobit","vyznat","vzadu","vzbudit","vzchopit","vzdor","vzduch","vzdychat","vzestup","vzhledem","vzkaz","vzlykat","vznik","vzorek","vzpoura","vztah","vztek","xylofon","zabrat","zabydlet","zachovat","zadarmo","zadusit","zafoukat","zahltit","zahodit","zahrada","zahynout","zajatec","zajet","zajistit","zaklepat","zakoupit","zalepit","zamezit","zamotat","zamyslet","zanechat","zanikat","zaplatit","zapojit","zapsat","zarazit","zastavit","zasunout","zatajit","zatemnit","zatknout","zaujmout","zavalit","zavelet","zavinit","zavolat","zavrtat","zazvonit","zbavit","zbrusu","zbudovat","zbytek","zdaleka","zdarma","zdatnost","zdivo","zdobit","zdroj","zdvih","zdymadlo","zelenina","zeman","zemina","zeptat","zezadu","zezdola","zhatit","zhltnout","zhluboka","zhotovit","zhruba","zima","zimnice","zjemnit","zklamat","zkoumat","zkratka","zkumavka","zlato","zlehka","zloba","zlom","zlost","zlozvyk","zmapovat","zmar","zmatek","zmije","zmizet","zmocnit","zmodrat","zmrzlina","zmutovat","znak","znalost","znamenat","znovu","zobrazit","zotavit","zoubek","zoufale","zplodit","zpomalit","zprava","zprostit","zprudka","zprvu","zrada","zranit","zrcadlo","zrnitost","zrno","zrovna","zrychlit","zrzavost","zticha","ztratit","zubovina","zubr","zvednout","zvenku","zvesela","zvon","zvrat","zvukovod","zvyk"]')},4573:module=>{"use strict";module.exports=JSON.parse('["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"]')},1848:module=>{"use strict";module.exports=JSON.parse('["abaisser","abandon","abdiquer","abeille","abolir","aborder","aboutir","aboyer","abrasif","abreuver","abriter","abroger","abrupt","absence","absolu","absurde","abusif","abyssal","académie","acajou","acarien","accabler","accepter","acclamer","accolade","accroche","accuser","acerbe","achat","acheter","aciduler","acier","acompte","acquérir","acronyme","acteur","actif","actuel","adepte","adéquat","adhésif","adjectif","adjuger","admettre","admirer","adopter","adorer","adoucir","adresse","adroit","adulte","adverbe","aérer","aéronef","affaire","affecter","affiche","affreux","affubler","agacer","agencer","agile","agiter","agrafer","agréable","agrume","aider","aiguille","ailier","aimable","aisance","ajouter","ajuster","alarmer","alchimie","alerte","algèbre","algue","aliéner","aliment","alléger","alliage","allouer","allumer","alourdir","alpaga","altesse","alvéole","amateur","ambigu","ambre","aménager","amertume","amidon","amiral","amorcer","amour","amovible","amphibie","ampleur","amusant","analyse","anaphore","anarchie","anatomie","ancien","anéantir","angle","angoisse","anguleux","animal","annexer","annonce","annuel","anodin","anomalie","anonyme","anormal","antenne","antidote","anxieux","apaiser","apéritif","aplanir","apologie","appareil","appeler","apporter","appuyer","aquarium","aqueduc","arbitre","arbuste","ardeur","ardoise","argent","arlequin","armature","armement","armoire","armure","arpenter","arracher","arriver","arroser","arsenic","artériel","article","aspect","asphalte","aspirer","assaut","asservir","assiette","associer","assurer","asticot","astre","astuce","atelier","atome","atrium","atroce","attaque","attentif","attirer","attraper","aubaine","auberge","audace","audible","augurer","aurore","automne","autruche","avaler","avancer","avarice","avenir","averse","aveugle","aviateur","avide","avion","aviser","avoine","avouer","avril","axial","axiome","badge","bafouer","bagage","baguette","baignade","balancer","balcon","baleine","balisage","bambin","bancaire","bandage","banlieue","bannière","banquier","barbier","baril","baron","barque","barrage","bassin","bastion","bataille","bateau","batterie","baudrier","bavarder","belette","bélier","belote","bénéfice","berceau","berger","berline","bermuda","besace","besogne","bétail","beurre","biberon","bicycle","bidule","bijou","bilan","bilingue","billard","binaire","biologie","biopsie","biotype","biscuit","bison","bistouri","bitume","bizarre","blafard","blague","blanchir","blessant","blinder","blond","bloquer","blouson","bobard","bobine","boire","boiser","bolide","bonbon","bondir","bonheur","bonifier","bonus","bordure","borne","botte","boucle","boueux","bougie","boulon","bouquin","bourse","boussole","boutique","boxeur","branche","brasier","brave","brebis","brèche","breuvage","bricoler","brigade","brillant","brioche","brique","brochure","broder","bronzer","brousse","broyeur","brume","brusque","brutal","bruyant","buffle","buisson","bulletin","bureau","burin","bustier","butiner","butoir","buvable","buvette","cabanon","cabine","cachette","cadeau","cadre","caféine","caillou","caisson","calculer","calepin","calibre","calmer","calomnie","calvaire","camarade","caméra","camion","campagne","canal","caneton","canon","cantine","canular","capable","caporal","caprice","capsule","capter","capuche","carabine","carbone","caresser","caribou","carnage","carotte","carreau","carton","cascade","casier","casque","cassure","causer","caution","cavalier","caverne","caviar","cédille","ceinture","céleste","cellule","cendrier","censurer","central","cercle","cérébral","cerise","cerner","cerveau","cesser","chagrin","chaise","chaleur","chambre","chance","chapitre","charbon","chasseur","chaton","chausson","chavirer","chemise","chenille","chéquier","chercher","cheval","chien","chiffre","chignon","chimère","chiot","chlorure","chocolat","choisir","chose","chouette","chrome","chute","cigare","cigogne","cimenter","cinéma","cintrer","circuler","cirer","cirque","citerne","citoyen","citron","civil","clairon","clameur","claquer","classe","clavier","client","cligner","climat","clivage","cloche","clonage","cloporte","cobalt","cobra","cocasse","cocotier","coder","codifier","coffre","cogner","cohésion","coiffer","coincer","colère","colibri","colline","colmater","colonel","combat","comédie","commande","compact","concert","conduire","confier","congeler","connoter","consonne","contact","convexe","copain","copie","corail","corbeau","cordage","corniche","corpus","correct","cortège","cosmique","costume","coton","coude","coupure","courage","couteau","couvrir","coyote","crabe","crainte","cravate","crayon","créature","créditer","crémeux","creuser","crevette","cribler","crier","cristal","critère","croire","croquer","crotale","crucial","cruel","crypter","cubique","cueillir","cuillère","cuisine","cuivre","culminer","cultiver","cumuler","cupide","curatif","curseur","cyanure","cycle","cylindre","cynique","daigner","damier","danger","danseur","dauphin","débattre","débiter","déborder","débrider","débutant","décaler","décembre","déchirer","décider","déclarer","décorer","décrire","décupler","dédale","déductif","déesse","défensif","défiler","défrayer","dégager","dégivrer","déglutir","dégrafer","déjeuner","délice","déloger","demander","demeurer","démolir","dénicher","dénouer","dentelle","dénuder","départ","dépenser","déphaser","déplacer","déposer","déranger","dérober","désastre","descente","désert","désigner","désobéir","dessiner","destrier","détacher","détester","détourer","détresse","devancer","devenir","deviner","devoir","diable","dialogue","diamant","dicter","différer","digérer","digital","digne","diluer","dimanche","diminuer","dioxyde","directif","diriger","discuter","disposer","dissiper","distance","divertir","diviser","docile","docteur","dogme","doigt","domaine","domicile","dompter","donateur","donjon","donner","dopamine","dortoir","dorure","dosage","doseur","dossier","dotation","douanier","double","douceur","douter","doyen","dragon","draper","dresser","dribbler","droiture","duperie","duplexe","durable","durcir","dynastie","éblouir","écarter","écharpe","échelle","éclairer","éclipse","éclore","écluse","école","économie","écorce","écouter","écraser","écrémer","écrivain","écrou","écume","écureuil","édifier","éduquer","effacer","effectif","effigie","effort","effrayer","effusion","égaliser","égarer","éjecter","élaborer","élargir","électron","élégant","éléphant","élève","éligible","élitisme","éloge","élucider","éluder","emballer","embellir","embryon","émeraude","émission","emmener","émotion","émouvoir","empereur","employer","emporter","emprise","émulsion","encadrer","enchère","enclave","encoche","endiguer","endosser","endroit","enduire","énergie","enfance","enfermer","enfouir","engager","engin","englober","énigme","enjamber","enjeu","enlever","ennemi","ennuyeux","enrichir","enrobage","enseigne","entasser","entendre","entier","entourer","entraver","énumérer","envahir","enviable","envoyer","enzyme","éolien","épaissir","épargne","épatant","épaule","épicerie","épidémie","épier","épilogue","épine","épisode","épitaphe","époque","épreuve","éprouver","épuisant","équerre","équipe","ériger","érosion","erreur","éruption","escalier","espadon","espèce","espiègle","espoir","esprit","esquiver","essayer","essence","essieu","essorer","estime","estomac","estrade","étagère","étaler","étanche","étatique","éteindre","étendoir","éternel","éthanol","éthique","ethnie","étirer","étoffer","étoile","étonnant","étourdir","étrange","étroit","étude","euphorie","évaluer","évasion","éventail","évidence","éviter","évolutif","évoquer","exact","exagérer","exaucer","exceller","excitant","exclusif","excuse","exécuter","exemple","exercer","exhaler","exhorter","exigence","exiler","exister","exotique","expédier","explorer","exposer","exprimer","exquis","extensif","extraire","exulter","fable","fabuleux","facette","facile","facture","faiblir","falaise","fameux","famille","farceur","farfelu","farine","farouche","fasciner","fatal","fatigue","faucon","fautif","faveur","favori","fébrile","féconder","fédérer","félin","femme","fémur","fendoir","féodal","fermer","féroce","ferveur","festival","feuille","feutre","février","fiasco","ficeler","fictif","fidèle","figure","filature","filetage","filière","filleul","filmer","filou","filtrer","financer","finir","fiole","firme","fissure","fixer","flairer","flamme","flasque","flatteur","fléau","flèche","fleur","flexion","flocon","flore","fluctuer","fluide","fluvial","folie","fonderie","fongible","fontaine","forcer","forgeron","formuler","fortune","fossile","foudre","fougère","fouiller","foulure","fourmi","fragile","fraise","franchir","frapper","frayeur","frégate","freiner","frelon","frémir","frénésie","frère","friable","friction","frisson","frivole","froid","fromage","frontal","frotter","fruit","fugitif","fuite","fureur","furieux","furtif","fusion","futur","gagner","galaxie","galerie","gambader","garantir","gardien","garnir","garrigue","gazelle","gazon","géant","gélatine","gélule","gendarme","général","génie","genou","gentil","géologie","géomètre","géranium","germe","gestuel","geyser","gibier","gicler","girafe","givre","glace","glaive","glisser","globe","gloire","glorieux","golfeur","gomme","gonfler","gorge","gorille","goudron","gouffre","goulot","goupille","gourmand","goutte","graduel","graffiti","graine","grand","grappin","gratuit","gravir","grenat","griffure","griller","grimper","grogner","gronder","grotte","groupe","gruger","grutier","gruyère","guépard","guerrier","guide","guimauve","guitare","gustatif","gymnaste","gyrostat","habitude","hachoir","halte","hameau","hangar","hanneton","haricot","harmonie","harpon","hasard","hélium","hématome","herbe","hérisson","hermine","héron","hésiter","heureux","hiberner","hibou","hilarant","histoire","hiver","homard","hommage","homogène","honneur","honorer","honteux","horde","horizon","horloge","hormone","horrible","houleux","housse","hublot","huileux","humain","humble","humide","humour","hurler","hydromel","hygiène","hymne","hypnose","idylle","ignorer","iguane","illicite","illusion","image","imbiber","imiter","immense","immobile","immuable","impact","impérial","implorer","imposer","imprimer","imputer","incarner","incendie","incident","incliner","incolore","indexer","indice","inductif","inédit","ineptie","inexact","infini","infliger","informer","infusion","ingérer","inhaler","inhiber","injecter","injure","innocent","inoculer","inonder","inscrire","insecte","insigne","insolite","inspirer","instinct","insulter","intact","intense","intime","intrigue","intuitif","inutile","invasion","inventer","inviter","invoquer","ironique","irradier","irréel","irriter","isoler","ivoire","ivresse","jaguar","jaillir","jambe","janvier","jardin","jauger","jaune","javelot","jetable","jeton","jeudi","jeunesse","joindre","joncher","jongler","joueur","jouissif","journal","jovial","joyau","joyeux","jubiler","jugement","junior","jupon","juriste","justice","juteux","juvénile","kayak","kimono","kiosque","label","labial","labourer","lacérer","lactose","lagune","laine","laisser","laitier","lambeau","lamelle","lampe","lanceur","langage","lanterne","lapin","largeur","larme","laurier","lavabo","lavoir","lecture","légal","léger","légume","lessive","lettre","levier","lexique","lézard","liasse","libérer","libre","licence","licorne","liège","lièvre","ligature","ligoter","ligue","limer","limite","limonade","limpide","linéaire","lingot","lionceau","liquide","lisière","lister","lithium","litige","littoral","livreur","logique","lointain","loisir","lombric","loterie","louer","lourd","loutre","louve","loyal","lubie","lucide","lucratif","lueur","lugubre","luisant","lumière","lunaire","lundi","luron","lutter","luxueux","machine","magasin","magenta","magique","maigre","maillon","maintien","mairie","maison","majorer","malaxer","maléfice","malheur","malice","mallette","mammouth","mandater","maniable","manquant","manteau","manuel","marathon","marbre","marchand","mardi","maritime","marqueur","marron","marteler","mascotte","massif","matériel","matière","matraque","maudire","maussade","mauve","maximal","méchant","méconnu","médaille","médecin","méditer","méduse","meilleur","mélange","mélodie","membre","mémoire","menacer","mener","menhir","mensonge","mentor","mercredi","mérite","merle","messager","mesure","métal","météore","méthode","métier","meuble","miauler","microbe","miette","mignon","migrer","milieu","million","mimique","mince","minéral","minimal","minorer","minute","miracle","miroiter","missile","mixte","mobile","moderne","moelleux","mondial","moniteur","monnaie","monotone","monstre","montagne","monument","moqueur","morceau","morsure","mortier","moteur","motif","mouche","moufle","moulin","mousson","mouton","mouvant","multiple","munition","muraille","murène","murmure","muscle","muséum","musicien","mutation","muter","mutuel","myriade","myrtille","mystère","mythique","nageur","nappe","narquois","narrer","natation","nation","nature","naufrage","nautique","navire","nébuleux","nectar","néfaste","négation","négliger","négocier","neige","nerveux","nettoyer","neurone","neutron","neveu","niche","nickel","nitrate","niveau","noble","nocif","nocturne","noirceur","noisette","nomade","nombreux","nommer","normatif","notable","notifier","notoire","nourrir","nouveau","novateur","novembre","novice","nuage","nuancer","nuire","nuisible","numéro","nuptial","nuque","nutritif","obéir","objectif","obliger","obscur","observer","obstacle","obtenir","obturer","occasion","occuper","océan","octobre","octroyer","octupler","oculaire","odeur","odorant","offenser","officier","offrir","ogive","oiseau","oisillon","olfactif","olivier","ombrage","omettre","onctueux","onduler","onéreux","onirique","opale","opaque","opérer","opinion","opportun","opprimer","opter","optique","orageux","orange","orbite","ordonner","oreille","organe","orgueil","orifice","ornement","orque","ortie","osciller","osmose","ossature","otarie","ouragan","ourson","outil","outrager","ouvrage","ovation","oxyde","oxygène","ozone","paisible","palace","palmarès","palourde","palper","panache","panda","pangolin","paniquer","panneau","panorama","pantalon","papaye","papier","papoter","papyrus","paradoxe","parcelle","paresse","parfumer","parler","parole","parrain","parsemer","partager","parure","parvenir","passion","pastèque","paternel","patience","patron","pavillon","pavoiser","payer","paysage","peigne","peintre","pelage","pélican","pelle","pelouse","peluche","pendule","pénétrer","pénible","pensif","pénurie","pépite","péplum","perdrix","perforer","période","permuter","perplexe","persil","perte","peser","pétale","petit","pétrir","peuple","pharaon","phobie","phoque","photon","phrase","physique","piano","pictural","pièce","pierre","pieuvre","pilote","pinceau","pipette","piquer","pirogue","piscine","piston","pivoter","pixel","pizza","placard","plafond","plaisir","planer","plaque","plastron","plateau","pleurer","plexus","pliage","plomb","plonger","pluie","plumage","pochette","poésie","poète","pointe","poirier","poisson","poivre","polaire","policier","pollen","polygone","pommade","pompier","ponctuel","pondérer","poney","portique","position","posséder","posture","potager","poteau","potion","pouce","poulain","poumon","pourpre","poussin","pouvoir","prairie","pratique","précieux","prédire","préfixe","prélude","prénom","présence","prétexte","prévoir","primitif","prince","prison","priver","problème","procéder","prodige","profond","progrès","proie","projeter","prologue","promener","propre","prospère","protéger","prouesse","proverbe","prudence","pruneau","psychose","public","puceron","puiser","pulpe","pulsar","punaise","punitif","pupitre","purifier","puzzle","pyramide","quasar","querelle","question","quiétude","quitter","quotient","racine","raconter","radieux","ragondin","raideur","raisin","ralentir","rallonge","ramasser","rapide","rasage","ratisser","ravager","ravin","rayonner","réactif","réagir","réaliser","réanimer","recevoir","réciter","réclamer","récolter","recruter","reculer","recycler","rédiger","redouter","refaire","réflexe","réformer","refrain","refuge","régalien","région","réglage","régulier","réitérer","rejeter","rejouer","relatif","relever","relief","remarque","remède","remise","remonter","remplir","remuer","renard","renfort","renifler","renoncer","rentrer","renvoi","replier","reporter","reprise","reptile","requin","réserve","résineux","résoudre","respect","rester","résultat","rétablir","retenir","réticule","retomber","retracer","réunion","réussir","revanche","revivre","révolte","révulsif","richesse","rideau","rieur","rigide","rigoler","rincer","riposter","risible","risque","rituel","rival","rivière","rocheux","romance","rompre","ronce","rondin","roseau","rosier","rotatif","rotor","rotule","rouge","rouille","rouleau","routine","royaume","ruban","rubis","ruche","ruelle","rugueux","ruiner","ruisseau","ruser","rustique","rythme","sabler","saboter","sabre","sacoche","safari","sagesse","saisir","salade","salive","salon","saluer","samedi","sanction","sanglier","sarcasme","sardine","saturer","saugrenu","saumon","sauter","sauvage","savant","savonner","scalpel","scandale","scélérat","scénario","sceptre","schéma","science","scinder","score","scrutin","sculpter","séance","sécable","sécher","secouer","sécréter","sédatif","séduire","seigneur","séjour","sélectif","semaine","sembler","semence","séminal","sénateur","sensible","sentence","séparer","séquence","serein","sergent","sérieux","serrure","sérum","service","sésame","sévir","sevrage","sextuple","sidéral","siècle","siéger","siffler","sigle","signal","silence","silicium","simple","sincère","sinistre","siphon","sirop","sismique","situer","skier","social","socle","sodium","soigneux","soldat","soleil","solitude","soluble","sombre","sommeil","somnoler","sonde","songeur","sonnette","sonore","sorcier","sortir","sosie","sottise","soucieux","soudure","souffle","soulever","soupape","source","soutirer","souvenir","spacieux","spatial","spécial","sphère","spiral","stable","station","sternum","stimulus","stipuler","strict","studieux","stupeur","styliste","sublime","substrat","subtil","subvenir","succès","sucre","suffixe","suggérer","suiveur","sulfate","superbe","supplier","surface","suricate","surmener","surprise","sursaut","survie","suspect","syllabe","symbole","symétrie","synapse","syntaxe","système","tabac","tablier","tactile","tailler","talent","talisman","talonner","tambour","tamiser","tangible","tapis","taquiner","tarder","tarif","tartine","tasse","tatami","tatouage","taupe","taureau","taxer","témoin","temporel","tenaille","tendre","teneur","tenir","tension","terminer","terne","terrible","tétine","texte","thème","théorie","thérapie","thorax","tibia","tiède","timide","tirelire","tiroir","tissu","titane","titre","tituber","toboggan","tolérant","tomate","tonique","tonneau","toponyme","torche","tordre","tornade","torpille","torrent","torse","tortue","totem","toucher","tournage","tousser","toxine","traction","trafic","tragique","trahir","train","trancher","travail","trèfle","tremper","trésor","treuil","triage","tribunal","tricoter","trilogie","triomphe","tripler","triturer","trivial","trombone","tronc","tropical","troupeau","tuile","tulipe","tumulte","tunnel","turbine","tuteur","tutoyer","tuyau","tympan","typhon","typique","tyran","ubuesque","ultime","ultrason","unanime","unifier","union","unique","unitaire","univers","uranium","urbain","urticant","usage","usine","usuel","usure","utile","utopie","vacarme","vaccin","vagabond","vague","vaillant","vaincre","vaisseau","valable","valise","vallon","valve","vampire","vanille","vapeur","varier","vaseux","vassal","vaste","vecteur","vedette","végétal","véhicule","veinard","véloce","vendredi","vénérer","venger","venimeux","ventouse","verdure","vérin","vernir","verrou","verser","vertu","veston","vétéran","vétuste","vexant","vexer","viaduc","viande","victoire","vidange","vidéo","vignette","vigueur","vilain","village","vinaigre","violon","vipère","virement","virtuose","virus","visage","viseur","vision","visqueux","visuel","vital","vitesse","viticole","vitrine","vivace","vivipare","vocation","voguer","voile","voisin","voiture","volaille","volcan","voltiger","volume","vorace","vortex","voter","vouloir","voyage","voyelle","wagon","xénon","yacht","zèbre","zénith","zeste","zoologie"]')},2841:module=>{"use strict";module.exports=JSON.parse('["abaco","abbaglio","abbinato","abete","abisso","abolire","abrasivo","abrogato","accadere","accenno","accusato","acetone","achille","acido","acqua","acre","acrilico","acrobata","acuto","adagio","addebito","addome","adeguato","aderire","adipe","adottare","adulare","affabile","affetto","affisso","affranto","aforisma","afoso","africano","agave","agente","agevole","aggancio","agire","agitare","agonismo","agricolo","agrumeto","aguzzo","alabarda","alato","albatro","alberato","albo","albume","alce","alcolico","alettone","alfa","algebra","aliante","alibi","alimento","allagato","allegro","allievo","allodola","allusivo","almeno","alogeno","alpaca","alpestre","altalena","alterno","alticcio","altrove","alunno","alveolo","alzare","amalgama","amanita","amarena","ambito","ambrato","ameba","america","ametista","amico","ammasso","ammenda","ammirare","ammonito","amore","ampio","ampliare","amuleto","anacardo","anagrafe","analista","anarchia","anatra","anca","ancella","ancora","andare","andrea","anello","angelo","angolare","angusto","anima","annegare","annidato","anno","annuncio","anonimo","anticipo","anzi","apatico","apertura","apode","apparire","appetito","appoggio","approdo","appunto","aprile","arabica","arachide","aragosta","araldica","arancio","aratura","arazzo","arbitro","archivio","ardito","arenile","argento","argine","arguto","aria","armonia","arnese","arredato","arringa","arrosto","arsenico","arso","artefice","arzillo","asciutto","ascolto","asepsi","asettico","asfalto","asino","asola","aspirato","aspro","assaggio","asse","assoluto","assurdo","asta","astenuto","astice","astratto","atavico","ateismo","atomico","atono","attesa","attivare","attorno","attrito","attuale","ausilio","austria","autista","autonomo","autunno","avanzato","avere","avvenire","avviso","avvolgere","azione","azoto","azzimo","azzurro","babele","baccano","bacino","baco","badessa","badilata","bagnato","baita","balcone","baldo","balena","ballata","balzano","bambino","bandire","baraonda","barbaro","barca","baritono","barlume","barocco","basilico","basso","batosta","battuto","baule","bava","bavosa","becco","beffa","belgio","belva","benda","benevole","benigno","benzina","bere","berlina","beta","bibita","bici","bidone","bifido","biga","bilancia","bimbo","binocolo","biologo","bipede","bipolare","birbante","birra","biscotto","bisesto","bisnonno","bisonte","bisturi","bizzarro","blando","blatta","bollito","bonifico","bordo","bosco","botanico","bottino","bozzolo","braccio","bradipo","brama","branca","bravura","bretella","brevetto","brezza","briglia","brillante","brindare","broccolo","brodo","bronzina","brullo","bruno","bubbone","buca","budino","buffone","buio","bulbo","buono","burlone","burrasca","bussola","busta","cadetto","caduco","calamaro","calcolo","calesse","calibro","calmo","caloria","cambusa","camerata","camicia","cammino","camola","campale","canapa","candela","cane","canino","canotto","cantina","capace","capello","capitolo","capogiro","cappero","capra","capsula","carapace","carcassa","cardo","carisma","carovana","carretto","cartolina","casaccio","cascata","caserma","caso","cassone","castello","casuale","catasta","catena","catrame","cauto","cavillo","cedibile","cedrata","cefalo","celebre","cellulare","cena","cenone","centesimo","ceramica","cercare","certo","cerume","cervello","cesoia","cespo","ceto","chela","chiaro","chicca","chiedere","chimera","china","chirurgo","chitarra","ciao","ciclismo","cifrare","cigno","cilindro","ciottolo","circa","cirrosi","citrico","cittadino","ciuffo","civetta","civile","classico","clinica","cloro","cocco","codardo","codice","coerente","cognome","collare","colmato","colore","colposo","coltivato","colza","coma","cometa","commando","comodo","computer","comune","conciso","condurre","conferma","congelare","coniuge","connesso","conoscere","consumo","continuo","convegno","coperto","copione","coppia","copricapo","corazza","cordata","coricato","cornice","corolla","corpo","corredo","corsia","cortese","cosmico","costante","cottura","covato","cratere","cravatta","creato","credere","cremoso","crescita","creta","criceto","crinale","crisi","critico","croce","cronaca","crostata","cruciale","crusca","cucire","cuculo","cugino","cullato","cupola","curatore","cursore","curvo","cuscino","custode","dado","daino","dalmata","damerino","daniela","dannoso","danzare","datato","davanti","davvero","debutto","decennio","deciso","declino","decollo","decreto","dedicato","definito","deforme","degno","delegare","delfino","delirio","delta","demenza","denotato","dentro","deposito","derapata","derivare","deroga","descritto","deserto","desiderio","desumere","detersivo","devoto","diametro","dicembre","diedro","difeso","diffuso","digerire","digitale","diluvio","dinamico","dinnanzi","dipinto","diploma","dipolo","diradare","dire","dirotto","dirupo","disagio","discreto","disfare","disgelo","disposto","distanza","disumano","dito","divano","divelto","dividere","divorato","doblone","docente","doganale","dogma","dolce","domato","domenica","dominare","dondolo","dono","dormire","dote","dottore","dovuto","dozzina","drago","druido","dubbio","dubitare","ducale","duna","duomo","duplice","duraturo","ebano","eccesso","ecco","eclissi","economia","edera","edicola","edile","editoria","educare","egemonia","egli","egoismo","egregio","elaborato","elargire","elegante","elencato","eletto","elevare","elfico","elica","elmo","elsa","eluso","emanato","emblema","emesso","emiro","emotivo","emozione","empirico","emulo","endemico","enduro","energia","enfasi","enoteca","entrare","enzima","epatite","epilogo","episodio","epocale","eppure","equatore","erario","erba","erboso","erede","eremita","erigere","ermetico","eroe","erosivo","errante","esagono","esame","esanime","esaudire","esca","esempio","esercito","esibito","esigente","esistere","esito","esofago","esortato","esoso","espanso","espresso","essenza","esso","esteso","estimare","estonia","estroso","esultare","etilico","etnico","etrusco","etto","euclideo","europa","evaso","evidenza","evitato","evoluto","evviva","fabbrica","faccenda","fachiro","falco","famiglia","fanale","fanfara","fango","fantasma","fare","farfalla","farinoso","farmaco","fascia","fastoso","fasullo","faticare","fato","favoloso","febbre","fecola","fede","fegato","felpa","feltro","femmina","fendere","fenomeno","fermento","ferro","fertile","fessura","festivo","fetta","feudo","fiaba","fiducia","fifa","figurato","filo","finanza","finestra","finire","fiore","fiscale","fisico","fiume","flacone","flamenco","flebo","flemma","florido","fluente","fluoro","fobico","focaccia","focoso","foderato","foglio","folata","folclore","folgore","fondente","fonetico","fonia","fontana","forbito","forchetta","foresta","formica","fornaio","foro","fortezza","forzare","fosfato","fosso","fracasso","frana","frassino","fratello","freccetta","frenata","fresco","frigo","frollino","fronde","frugale","frutta","fucilata","fucsia","fuggente","fulmine","fulvo","fumante","fumetto","fumoso","fune","funzione","fuoco","furbo","furgone","furore","fuso","futile","gabbiano","gaffe","galateo","gallina","galoppo","gambero","gamma","garanzia","garbo","garofano","garzone","gasdotto","gasolio","gastrico","gatto","gaudio","gazebo","gazzella","geco","gelatina","gelso","gemello","gemmato","gene","genitore","gennaio","genotipo","gergo","ghepardo","ghiaccio","ghisa","giallo","gilda","ginepro","giocare","gioiello","giorno","giove","girato","girone","gittata","giudizio","giurato","giusto","globulo","glutine","gnomo","gobba","golf","gomito","gommone","gonfio","gonna","governo","gracile","grado","grafico","grammo","grande","grattare","gravoso","grazia","greca","gregge","grifone","grigio","grinza","grotta","gruppo","guadagno","guaio","guanto","guardare","gufo","guidare","ibernato","icona","identico","idillio","idolo","idra","idrico","idrogeno","igiene","ignaro","ignorato","ilare","illeso","illogico","illudere","imballo","imbevuto","imbocco","imbuto","immane","immerso","immolato","impacco","impeto","impiego","importo","impronta","inalare","inarcare","inattivo","incanto","incendio","inchino","incisivo","incluso","incontro","incrocio","incubo","indagine","india","indole","inedito","infatti","infilare","inflitto","ingaggio","ingegno","inglese","ingordo","ingrosso","innesco","inodore","inoltrare","inondato","insano","insetto","insieme","insonnia","insulina","intasato","intero","intonaco","intuito","inumidire","invalido","invece","invito","iperbole","ipnotico","ipotesi","ippica","iride","irlanda","ironico","irrigato","irrorare","isolato","isotopo","isterico","istituto","istrice","italia","iterare","labbro","labirinto","lacca","lacerato","lacrima","lacuna","laddove","lago","lampo","lancetta","lanterna","lardoso","larga","laringe","lastra","latenza","latino","lattuga","lavagna","lavoro","legale","leggero","lembo","lentezza","lenza","leone","lepre","lesivo","lessato","lesto","letterale","leva","levigato","libero","lido","lievito","lilla","limatura","limitare","limpido","lineare","lingua","liquido","lira","lirica","lisca","lite","litigio","livrea","locanda","lode","logica","lombare","londra","longevo","loquace","lorenzo","loto","lotteria","luce","lucidato","lumaca","luminoso","lungo","lupo","luppolo","lusinga","lusso","lutto","macabro","macchina","macero","macinato","madama","magico","maglia","magnete","magro","maiolica","malafede","malgrado","malinteso","malsano","malto","malumore","mana","mancia","mandorla","mangiare","manifesto","mannaro","manovra","mansarda","mantide","manubrio","mappa","maratona","marcire","maretta","marmo","marsupio","maschera","massaia","mastino","materasso","matricola","mattone","maturo","mazurca","meandro","meccanico","mecenate","medesimo","meditare","mega","melassa","melis","melodia","meninge","meno","mensola","mercurio","merenda","merlo","meschino","mese","messere","mestolo","metallo","metodo","mettere","miagolare","mica","micelio","michele","microbo","midollo","miele","migliore","milano","milite","mimosa","minerale","mini","minore","mirino","mirtillo","miscela","missiva","misto","misurare","mitezza","mitigare","mitra","mittente","mnemonico","modello","modifica","modulo","mogano","mogio","mole","molosso","monastero","monco","mondina","monetario","monile","monotono","monsone","montato","monviso","mora","mordere","morsicato","mostro","motivato","motosega","motto","movenza","movimento","mozzo","mucca","mucosa","muffa","mughetto","mugnaio","mulatto","mulinello","multiplo","mummia","munto","muovere","murale","musa","muscolo","musica","mutevole","muto","nababbo","nafta","nanometro","narciso","narice","narrato","nascere","nastrare","naturale","nautica","naviglio","nebulosa","necrosi","negativo","negozio","nemmeno","neofita","neretto","nervo","nessuno","nettuno","neutrale","neve","nevrotico","nicchia","ninfa","nitido","nobile","nocivo","nodo","nome","nomina","nordico","normale","norvegese","nostrano","notare","notizia","notturno","novella","nucleo","nulla","numero","nuovo","nutrire","nuvola","nuziale","oasi","obbedire","obbligo","obelisco","oblio","obolo","obsoleto","occasione","occhio","occidente","occorrere","occultare","ocra","oculato","odierno","odorare","offerta","offrire","offuscato","oggetto","oggi","ognuno","olandese","olfatto","oliato","oliva","ologramma","oltre","omaggio","ombelico","ombra","omega","omissione","ondoso","onere","onice","onnivoro","onorevole","onta","operato","opinione","opposto","oracolo","orafo","ordine","orecchino","orefice","orfano","organico","origine","orizzonte","orma","ormeggio","ornativo","orologio","orrendo","orribile","ortensia","ortica","orzata","orzo","osare","oscurare","osmosi","ospedale","ospite","ossa","ossidare","ostacolo","oste","otite","otre","ottagono","ottimo","ottobre","ovale","ovest","ovino","oviparo","ovocito","ovunque","ovviare","ozio","pacchetto","pace","pacifico","padella","padrone","paese","paga","pagina","palazzina","palesare","pallido","palo","palude","pandoro","pannello","paolo","paonazzo","paprica","parabola","parcella","parere","pargolo","pari","parlato","parola","partire","parvenza","parziale","passivo","pasticca","patacca","patologia","pattume","pavone","peccato","pedalare","pedonale","peggio","peloso","penare","pendice","penisola","pennuto","penombra","pensare","pentola","pepe","pepita","perbene","percorso","perdonato","perforare","pergamena","periodo","permesso","perno","perplesso","persuaso","pertugio","pervaso","pesatore","pesista","peso","pestifero","petalo","pettine","petulante","pezzo","piacere","pianta","piattino","piccino","picozza","piega","pietra","piffero","pigiama","pigolio","pigro","pila","pilifero","pillola","pilota","pimpante","pineta","pinna","pinolo","pioggia","piombo","piramide","piretico","pirite","pirolisi","pitone","pizzico","placebo","planare","plasma","platano","plenario","pochezza","poderoso","podismo","poesia","poggiare","polenta","poligono","pollice","polmonite","polpetta","polso","poltrona","polvere","pomice","pomodoro","ponte","popoloso","porfido","poroso","porpora","porre","portata","posa","positivo","possesso","postulato","potassio","potere","pranzo","prassi","pratica","precluso","predica","prefisso","pregiato","prelievo","premere","prenotare","preparato","presenza","pretesto","prevalso","prima","principe","privato","problema","procura","produrre","profumo","progetto","prolunga","promessa","pronome","proposta","proroga","proteso","prova","prudente","prugna","prurito","psiche","pubblico","pudica","pugilato","pugno","pulce","pulito","pulsante","puntare","pupazzo","pupilla","puro","quadro","qualcosa","quasi","querela","quota","raccolto","raddoppio","radicale","radunato","raffica","ragazzo","ragione","ragno","ramarro","ramingo","ramo","randagio","rantolare","rapato","rapina","rappreso","rasatura","raschiato","rasente","rassegna","rastrello","rata","ravveduto","reale","recepire","recinto","recluta","recondito","recupero","reddito","redimere","regalato","registro","regola","regresso","relazione","remare","remoto","renna","replica","reprimere","reputare","resa","residente","responso","restauro","rete","retina","retorica","rettifica","revocato","riassunto","ribadire","ribelle","ribrezzo","ricarica","ricco","ricevere","riciclato","ricordo","ricreduto","ridicolo","ridurre","rifasare","riflesso","riforma","rifugio","rigare","rigettato","righello","rilassato","rilevato","rimanere","rimbalzo","rimedio","rimorchio","rinascita","rincaro","rinforzo","rinnovo","rinomato","rinsavito","rintocco","rinuncia","rinvenire","riparato","ripetuto","ripieno","riportare","ripresa","ripulire","risata","rischio","riserva","risibile","riso","rispetto","ristoro","risultato","risvolto","ritardo","ritegno","ritmico","ritrovo","riunione","riva","riverso","rivincita","rivolto","rizoma","roba","robotico","robusto","roccia","roco","rodaggio","rodere","roditore","rogito","rollio","romantico","rompere","ronzio","rosolare","rospo","rotante","rotondo","rotula","rovescio","rubizzo","rubrica","ruga","rullino","rumine","rumoroso","ruolo","rupe","russare","rustico","sabato","sabbiare","sabotato","sagoma","salasso","saldatura","salgemma","salivare","salmone","salone","saltare","saluto","salvo","sapere","sapido","saporito","saraceno","sarcasmo","sarto","sassoso","satellite","satira","satollo","saturno","savana","savio","saziato","sbadiglio","sbalzo","sbancato","sbarra","sbattere","sbavare","sbendare","sbirciare","sbloccato","sbocciato","sbrinare","sbruffone","sbuffare","scabroso","scadenza","scala","scambiare","scandalo","scapola","scarso","scatenare","scavato","scelto","scenico","scettro","scheda","schiena","sciarpa","scienza","scindere","scippo","sciroppo","scivolo","sclerare","scodella","scolpito","scomparto","sconforto","scoprire","scorta","scossone","scozzese","scriba","scrollare","scrutinio","scuderia","scultore","scuola","scuro","scusare","sdebitare","sdoganare","seccatura","secondo","sedano","seggiola","segnalato","segregato","seguito","selciato","selettivo","sella","selvaggio","semaforo","sembrare","seme","seminato","sempre","senso","sentire","sepolto","sequenza","serata","serbato","sereno","serio","serpente","serraglio","servire","sestina","setola","settimana","sfacelo","sfaldare","sfamato","sfarzoso","sfaticato","sfera","sfida","sfilato","sfinge","sfocato","sfoderare","sfogo","sfoltire","sforzato","sfratto","sfruttato","sfuggito","sfumare","sfuso","sgabello","sgarbato","sgonfiare","sgorbio","sgrassato","sguardo","sibilo","siccome","sierra","sigla","signore","silenzio","sillaba","simbolo","simpatico","simulato","sinfonia","singolo","sinistro","sino","sintesi","sinusoide","sipario","sisma","sistole","situato","slitta","slogatura","sloveno","smarrito","smemorato","smentito","smeraldo","smilzo","smontare","smottato","smussato","snellire","snervato","snodo","sobbalzo","sobrio","soccorso","sociale","sodale","soffitto","sogno","soldato","solenne","solido","sollazzo","solo","solubile","solvente","somatico","somma","sonda","sonetto","sonnifero","sopire","soppeso","sopra","sorgere","sorpasso","sorriso","sorso","sorteggio","sorvolato","sospiro","sosta","sottile","spada","spalla","spargere","spatola","spavento","spazzola","specie","spedire","spegnere","spelatura","speranza","spessore","spettrale","spezzato","spia","spigoloso","spillato","spinoso","spirale","splendido","sportivo","sposo","spranga","sprecare","spronato","spruzzo","spuntino","squillo","sradicare","srotolato","stabile","stacco","staffa","stagnare","stampato","stantio","starnuto","stasera","statuto","stelo","steppa","sterzo","stiletto","stima","stirpe","stivale","stizzoso","stonato","storico","strappo","stregato","stridulo","strozzare","strutto","stuccare","stufo","stupendo","subentro","succoso","sudore","suggerito","sugo","sultano","suonare","superbo","supporto","surgelato","surrogato","sussurro","sutura","svagare","svedese","sveglio","svelare","svenuto","svezia","sviluppo","svista","svizzera","svolta","svuotare","tabacco","tabulato","tacciare","taciturno","tale","talismano","tampone","tannino","tara","tardivo","targato","tariffa","tarpare","tartaruga","tasto","tattico","taverna","tavolata","tazza","teca","tecnico","telefono","temerario","tempo","temuto","tendone","tenero","tensione","tentacolo","teorema","terme","terrazzo","terzetto","tesi","tesserato","testato","tetro","tettoia","tifare","tigella","timbro","tinto","tipico","tipografo","tiraggio","tiro","titanio","titolo","titubante","tizio","tizzone","toccare","tollerare","tolto","tombola","tomo","tonfo","tonsilla","topazio","topologia","toppa","torba","tornare","torrone","tortora","toscano","tossire","tostatura","totano","trabocco","trachea","trafila","tragedia","tralcio","tramonto","transito","trapano","trarre","trasloco","trattato","trave","treccia","tremolio","trespolo","tributo","tricheco","trifoglio","trillo","trincea","trio","tristezza","triturato","trivella","tromba","trono","troppo","trottola","trovare","truccato","tubatura","tuffato","tulipano","tumulto","tunisia","turbare","turchino","tuta","tutela","ubicato","uccello","uccisore","udire","uditivo","uffa","ufficio","uguale","ulisse","ultimato","umano","umile","umorismo","uncinetto","ungere","ungherese","unicorno","unificato","unisono","unitario","unte","uovo","upupa","uragano","urgenza","urlo","usanza","usato","uscito","usignolo","usuraio","utensile","utilizzo","utopia","vacante","vaccinato","vagabondo","vagliato","valanga","valgo","valico","valletta","valoroso","valutare","valvola","vampata","vangare","vanitoso","vano","vantaggio","vanvera","vapore","varano","varcato","variante","vasca","vedetta","vedova","veduto","vegetale","veicolo","velcro","velina","velluto","veloce","venato","vendemmia","vento","verace","verbale","vergogna","verifica","vero","verruca","verticale","vescica","vessillo","vestale","veterano","vetrina","vetusto","viandante","vibrante","vicenda","vichingo","vicinanza","vidimare","vigilia","vigneto","vigore","vile","villano","vimini","vincitore","viola","vipera","virgola","virologo","virulento","viscoso","visione","vispo","vissuto","visura","vita","vitello","vittima","vivanda","vivido","viziare","voce","voga","volatile","volere","volpe","voragine","vulcano","zampogna","zanna","zappato","zattera","zavorra","zefiro","zelante","zelo","zenzero","zerbino","zibetto","zinco","zircone","zitto","zolla","zotico","zucchero","zufolo","zulu","zuppa"]')},4472:module=>{"use strict";module.exports=JSON.parse('["あいこくしん","あいさつ","あいだ","あおぞら","あかちゃん","あきる","あけがた","あける","あこがれる","あさい","あさひ","あしあと","あじわう","あずかる","あずき","あそぶ","あたえる","あたためる","あたりまえ","あたる","あつい","あつかう","あっしゅく","あつまり","あつめる","あてな","あてはまる","あひる","あぶら","あぶる","あふれる","あまい","あまど","あまやかす","あまり","あみもの","あめりか","あやまる","あゆむ","あらいぐま","あらし","あらすじ","あらためる","あらゆる","あらわす","ありがとう","あわせる","あわてる","あんい","あんがい","あんこ","あんぜん","あんてい","あんない","あんまり","いいだす","いおん","いがい","いがく","いきおい","いきなり","いきもの","いきる","いくじ","いくぶん","いけばな","いけん","いこう","いこく","いこつ","いさましい","いさん","いしき","いじゅう","いじょう","いじわる","いずみ","いずれ","いせい","いせえび","いせかい","いせき","いぜん","いそうろう","いそがしい","いだい","いだく","いたずら","いたみ","いたりあ","いちおう","いちじ","いちど","いちば","いちぶ","いちりゅう","いつか","いっしゅん","いっせい","いっそう","いったん","いっち","いってい","いっぽう","いてざ","いてん","いどう","いとこ","いない","いなか","いねむり","いのち","いのる","いはつ","いばる","いはん","いびき","いひん","いふく","いへん","いほう","いみん","いもうと","いもたれ","いもり","いやがる","いやす","いよかん","いよく","いらい","いらすと","いりぐち","いりょう","いれい","いれもの","いれる","いろえんぴつ","いわい","いわう","いわかん","いわば","いわゆる","いんげんまめ","いんさつ","いんしょう","いんよう","うえき","うえる","うおざ","うがい","うかぶ","うかべる","うきわ","うくらいな","うくれれ","うけたまわる","うけつけ","うけとる","うけもつ","うける","うごかす","うごく","うこん","うさぎ","うしなう","うしろがみ","うすい","うすぎ","うすぐらい","うすめる","うせつ","うちあわせ","うちがわ","うちき","うちゅう","うっかり","うつくしい","うったえる","うつる","うどん","うなぎ","うなじ","うなずく","うなる","うねる","うのう","うぶげ","うぶごえ","うまれる","うめる","うもう","うやまう","うよく","うらがえす","うらぐち","うらない","うりあげ","うりきれ","うるさい","うれしい","うれゆき","うれる","うろこ","うわき","うわさ","うんこう","うんちん","うんてん","うんどう","えいえん","えいが","えいきょう","えいご","えいせい","えいぶん","えいよう","えいわ","えおり","えがお","えがく","えきたい","えくせる","えしゃく","えすて","えつらん","えのぐ","えほうまき","えほん","えまき","えもじ","えもの","えらい","えらぶ","えりあ","えんえん","えんかい","えんぎ","えんげき","えんしゅう","えんぜつ","えんそく","えんちょう","えんとつ","おいかける","おいこす","おいしい","おいつく","おうえん","おうさま","おうじ","おうせつ","おうたい","おうふく","おうべい","おうよう","おえる","おおい","おおう","おおどおり","おおや","おおよそ","おかえり","おかず","おがむ","おかわり","おぎなう","おきる","おくさま","おくじょう","おくりがな","おくる","おくれる","おこす","おこなう","おこる","おさえる","おさない","おさめる","おしいれ","おしえる","おじぎ","おじさん","おしゃれ","おそらく","おそわる","おたがい","おたく","おだやか","おちつく","おっと","おつり","おでかけ","おとしもの","おとなしい","おどり","おどろかす","おばさん","おまいり","おめでとう","おもいで","おもう","おもたい","おもちゃ","おやつ","おやゆび","およぼす","おらんだ","おろす","おんがく","おんけい","おんしゃ","おんせん","おんだん","おんちゅう","おんどけい","かあつ","かいが","がいき","がいけん","がいこう","かいさつ","かいしゃ","かいすいよく","かいぜん","かいぞうど","かいつう","かいてん","かいとう","かいふく","がいへき","かいほう","かいよう","がいらい","かいわ","かえる","かおり","かかえる","かがく","かがし","かがみ","かくご","かくとく","かざる","がぞう","かたい","かたち","がちょう","がっきゅう","がっこう","がっさん","がっしょう","かなざわし","かのう","がはく","かぶか","かほう","かほご","かまう","かまぼこ","かめれおん","かゆい","かようび","からい","かるい","かろう","かわく","かわら","がんか","かんけい","かんこう","かんしゃ","かんそう","かんたん","かんち","がんばる","きあい","きあつ","きいろ","ぎいん","きうい","きうん","きえる","きおう","きおく","きおち","きおん","きかい","きかく","きかんしゃ","ききて","きくばり","きくらげ","きけんせい","きこう","きこえる","きこく","きさい","きさく","きさま","きさらぎ","ぎじかがく","ぎしき","ぎじたいけん","ぎじにってい","ぎじゅつしゃ","きすう","きせい","きせき","きせつ","きそう","きぞく","きぞん","きたえる","きちょう","きつえん","ぎっちり","きつつき","きつね","きてい","きどう","きどく","きない","きなが","きなこ","きぬごし","きねん","きのう","きのした","きはく","きびしい","きひん","きふく","きぶん","きぼう","きほん","きまる","きみつ","きむずかしい","きめる","きもだめし","きもち","きもの","きゃく","きやく","ぎゅうにく","きよう","きょうりゅう","きらい","きらく","きりん","きれい","きれつ","きろく","ぎろん","きわめる","ぎんいろ","きんかくじ","きんじょ","きんようび","ぐあい","くいず","くうかん","くうき","くうぐん","くうこう","ぐうせい","くうそう","ぐうたら","くうふく","くうぼ","くかん","くきょう","くげん","ぐこう","くさい","くさき","くさばな","くさる","くしゃみ","くしょう","くすのき","くすりゆび","くせげ","くせん","ぐたいてき","くださる","くたびれる","くちこみ","くちさき","くつした","ぐっすり","くつろぐ","くとうてん","くどく","くなん","くねくね","くのう","くふう","くみあわせ","くみたてる","くめる","くやくしょ","くらす","くらべる","くるま","くれる","くろう","くわしい","ぐんかん","ぐんしょく","ぐんたい","ぐんて","けあな","けいかく","けいけん","けいこ","けいさつ","げいじゅつ","けいたい","げいのうじん","けいれき","けいろ","けおとす","けおりもの","げきか","げきげん","げきだん","げきちん","げきとつ","げきは","げきやく","げこう","げこくじょう","げざい","けさき","げざん","けしき","けしごむ","けしょう","げすと","けたば","けちゃっぷ","けちらす","けつあつ","けつい","けつえき","けっこん","けつじょ","けっせき","けってい","けつまつ","げつようび","げつれい","けつろん","げどく","けとばす","けとる","けなげ","けなす","けなみ","けぬき","げねつ","けねん","けはい","げひん","けぶかい","げぼく","けまり","けみかる","けむし","けむり","けもの","けらい","けろけろ","けわしい","けんい","けんえつ","けんお","けんか","げんき","けんげん","けんこう","けんさく","けんしゅう","けんすう","げんそう","けんちく","けんてい","けんとう","けんない","けんにん","げんぶつ","けんま","けんみん","けんめい","けんらん","けんり","こあくま","こいぬ","こいびと","ごうい","こうえん","こうおん","こうかん","ごうきゅう","ごうけい","こうこう","こうさい","こうじ","こうすい","ごうせい","こうそく","こうたい","こうちゃ","こうつう","こうてい","こうどう","こうない","こうはい","ごうほう","ごうまん","こうもく","こうりつ","こえる","こおり","ごかい","ごがつ","ごかん","こくご","こくさい","こくとう","こくない","こくはく","こぐま","こけい","こける","ここのか","こころ","こさめ","こしつ","こすう","こせい","こせき","こぜん","こそだて","こたい","こたえる","こたつ","こちょう","こっか","こつこつ","こつばん","こつぶ","こてい","こてん","ことがら","ことし","ことば","ことり","こなごな","こねこね","このまま","このみ","このよ","ごはん","こひつじ","こふう","こふん","こぼれる","ごまあぶら","こまかい","ごますり","こまつな","こまる","こむぎこ","こもじ","こもち","こもの","こもん","こやく","こやま","こゆう","こゆび","こよい","こよう","こりる","これくしょん","ころっけ","こわもて","こわれる","こんいん","こんかい","こんき","こんしゅう","こんすい","こんだて","こんとん","こんなん","こんびに","こんぽん","こんまけ","こんや","こんれい","こんわく","ざいえき","さいかい","さいきん","ざいげん","ざいこ","さいしょ","さいせい","ざいたく","ざいちゅう","さいてき","ざいりょう","さうな","さかいし","さがす","さかな","さかみち","さがる","さぎょう","さくし","さくひん","さくら","さこく","さこつ","さずかる","ざせき","さたん","さつえい","ざつおん","ざっか","ざつがく","さっきょく","ざっし","さつじん","ざっそう","さつたば","さつまいも","さてい","さといも","さとう","さとおや","さとし","さとる","さのう","さばく","さびしい","さべつ","さほう","さほど","さます","さみしい","さみだれ","さむけ","さめる","さやえんどう","さゆう","さよう","さよく","さらだ","ざるそば","さわやか","さわる","さんいん","さんか","さんきゃく","さんこう","さんさい","ざんしょ","さんすう","さんせい","さんそ","さんち","さんま","さんみ","さんらん","しあい","しあげ","しあさって","しあわせ","しいく","しいん","しうち","しえい","しおけ","しかい","しかく","じかん","しごと","しすう","じだい","したうけ","したぎ","したて","したみ","しちょう","しちりん","しっかり","しつじ","しつもん","してい","してき","してつ","じてん","じどう","しなぎれ","しなもの","しなん","しねま","しねん","しのぐ","しのぶ","しはい","しばかり","しはつ","しはらい","しはん","しひょう","しふく","じぶん","しへい","しほう","しほん","しまう","しまる","しみん","しむける","じむしょ","しめい","しめる","しもん","しゃいん","しゃうん","しゃおん","じゃがいも","しやくしょ","しゃくほう","しゃけん","しゃこ","しゃざい","しゃしん","しゃせん","しゃそう","しゃたい","しゃちょう","しゃっきん","じゃま","しゃりん","しゃれい","じゆう","じゅうしょ","しゅくはく","じゅしん","しゅっせき","しゅみ","しゅらば","じゅんばん","しょうかい","しょくたく","しょっけん","しょどう","しょもつ","しらせる","しらべる","しんか","しんこう","じんじゃ","しんせいじ","しんちく","しんりん","すあげ","すあし","すあな","ずあん","すいえい","すいか","すいとう","ずいぶん","すいようび","すうがく","すうじつ","すうせん","すおどり","すきま","すくう","すくない","すける","すごい","すこし","ずさん","すずしい","すすむ","すすめる","すっかり","ずっしり","ずっと","すてき","すてる","すねる","すのこ","すはだ","すばらしい","ずひょう","ずぶぬれ","すぶり","すふれ","すべて","すべる","ずほう","すぼん","すまい","すめし","すもう","すやき","すらすら","するめ","すれちがう","すろっと","すわる","すんぜん","すんぽう","せあぶら","せいかつ","せいげん","せいじ","せいよう","せおう","せかいかん","せきにん","せきむ","せきゆ","せきらんうん","せけん","せこう","せすじ","せたい","せたけ","せっかく","せっきゃく","ぜっく","せっけん","せっこつ","せっさたくま","せつぞく","せつだん","せつでん","せっぱん","せつび","せつぶん","せつめい","せつりつ","せなか","せのび","せはば","せびろ","せぼね","せまい","せまる","せめる","せもたれ","せりふ","ぜんあく","せんい","せんえい","せんか","せんきょ","せんく","せんげん","ぜんご","せんさい","せんしゅ","せんすい","せんせい","せんぞ","せんたく","せんちょう","せんてい","せんとう","せんぬき","せんねん","せんぱい","ぜんぶ","ぜんぽう","せんむ","せんめんじょ","せんもん","せんやく","せんゆう","せんよう","ぜんら","ぜんりゃく","せんれい","せんろ","そあく","そいとげる","そいね","そうがんきょう","そうき","そうご","そうしん","そうだん","そうなん","そうび","そうめん","そうり","そえもの","そえん","そがい","そげき","そこう","そこそこ","そざい","そしな","そせい","そせん","そそぐ","そだてる","そつう","そつえん","そっかん","そつぎょう","そっけつ","そっこう","そっせん","そっと","そとがわ","そとづら","そなえる","そなた","そふぼ","そぼく","そぼろ","そまつ","そまる","そむく","そむりえ","そめる","そもそも","そよかぜ","そらまめ","そろう","そんかい","そんけい","そんざい","そんしつ","そんぞく","そんちょう","ぞんび","ぞんぶん","そんみん","たあい","たいいん","たいうん","たいえき","たいおう","だいがく","たいき","たいぐう","たいけん","たいこ","たいざい","だいじょうぶ","だいすき","たいせつ","たいそう","だいたい","たいちょう","たいてい","だいどころ","たいない","たいねつ","たいのう","たいはん","だいひょう","たいふう","たいへん","たいほ","たいまつばな","たいみんぐ","たいむ","たいめん","たいやき","たいよう","たいら","たいりょく","たいる","たいわん","たうえ","たえる","たおす","たおる","たおれる","たかい","たかね","たきび","たくさん","たこく","たこやき","たさい","たしざん","だじゃれ","たすける","たずさわる","たそがれ","たたかう","たたく","ただしい","たたみ","たちばな","だっかい","だっきゃく","だっこ","だっしゅつ","だったい","たてる","たとえる","たなばた","たにん","たぬき","たのしみ","たはつ","たぶん","たべる","たぼう","たまご","たまる","だむる","ためいき","ためす","ためる","たもつ","たやすい","たよる","たらす","たりきほんがん","たりょう","たりる","たると","たれる","たれんと","たろっと","たわむれる","だんあつ","たんい","たんおん","たんか","たんき","たんけん","たんご","たんさん","たんじょうび","だんせい","たんそく","たんたい","だんち","たんてい","たんとう","だんな","たんにん","だんねつ","たんのう","たんぴん","だんぼう","たんまつ","たんめい","だんれつ","だんろ","だんわ","ちあい","ちあん","ちいき","ちいさい","ちえん","ちかい","ちから","ちきゅう","ちきん","ちけいず","ちけん","ちこく","ちさい","ちしき","ちしりょう","ちせい","ちそう","ちたい","ちたん","ちちおや","ちつじょ","ちてき","ちてん","ちぬき","ちぬり","ちのう","ちひょう","ちへいせん","ちほう","ちまた","ちみつ","ちみどろ","ちめいど","ちゃんこなべ","ちゅうい","ちゆりょく","ちょうし","ちょさくけん","ちらし","ちらみ","ちりがみ","ちりょう","ちるど","ちわわ","ちんたい","ちんもく","ついか","ついたち","つうか","つうじょう","つうはん","つうわ","つかう","つかれる","つくね","つくる","つけね","つける","つごう","つたえる","つづく","つつじ","つつむ","つとめる","つながる","つなみ","つねづね","つのる","つぶす","つまらない","つまる","つみき","つめたい","つもり","つもる","つよい","つるぼ","つるみく","つわもの","つわり","てあし","てあて","てあみ","ていおん","ていか","ていき","ていけい","ていこく","ていさつ","ていし","ていせい","ていたい","ていど","ていねい","ていひょう","ていへん","ていぼう","てうち","ておくれ","てきとう","てくび","でこぼこ","てさぎょう","てさげ","てすり","てそう","てちがい","てちょう","てつがく","てつづき","でっぱ","てつぼう","てつや","でぬかえ","てぬき","てぬぐい","てのひら","てはい","てぶくろ","てふだ","てほどき","てほん","てまえ","てまきずし","てみじか","てみやげ","てらす","てれび","てわけ","てわたし","でんあつ","てんいん","てんかい","てんき","てんぐ","てんけん","てんごく","てんさい","てんし","てんすう","でんち","てんてき","てんとう","てんない","てんぷら","てんぼうだい","てんめつ","てんらんかい","でんりょく","でんわ","どあい","といれ","どうかん","とうきゅう","どうぐ","とうし","とうむぎ","とおい","とおか","とおく","とおす","とおる","とかい","とかす","ときおり","ときどき","とくい","とくしゅう","とくてん","とくに","とくべつ","とけい","とける","とこや","とさか","としょかん","とそう","とたん","とちゅう","とっきゅう","とっくん","とつぜん","とつにゅう","とどける","ととのえる","とない","となえる","となり","とのさま","とばす","どぶがわ","とほう","とまる","とめる","ともだち","ともる","どようび","とらえる","とんかつ","どんぶり","ないかく","ないこう","ないしょ","ないす","ないせん","ないそう","なおす","ながい","なくす","なげる","なこうど","なさけ","なたでここ","なっとう","なつやすみ","ななおし","なにごと","なにもの","なにわ","なのか","なふだ","なまいき","なまえ","なまみ","なみだ","なめらか","なめる","なやむ","ならう","ならび","ならぶ","なれる","なわとび","なわばり","にあう","にいがた","にうけ","におい","にかい","にがて","にきび","にくしみ","にくまん","にげる","にさんかたんそ","にしき","にせもの","にちじょう","にちようび","にっか","にっき","にっけい","にっこう","にっさん","にっしょく","にっすう","にっせき","にってい","になう","にほん","にまめ","にもつ","にやり","にゅういん","にりんしゃ","にわとり","にんい","にんか","にんき","にんげん","にんしき","にんずう","にんそう","にんたい","にんち","にんてい","にんにく","にんぷ","にんまり","にんむ","にんめい","にんよう","ぬいくぎ","ぬかす","ぬぐいとる","ぬぐう","ぬくもり","ぬすむ","ぬまえび","ぬめり","ぬらす","ぬんちゃく","ねあげ","ねいき","ねいる","ねいろ","ねぐせ","ねくたい","ねくら","ねこぜ","ねこむ","ねさげ","ねすごす","ねそべる","ねだん","ねつい","ねっしん","ねつぞう","ねったいぎょ","ねぶそく","ねふだ","ねぼう","ねほりはほり","ねまき","ねまわし","ねみみ","ねむい","ねむたい","ねもと","ねらう","ねわざ","ねんいり","ねんおし","ねんかん","ねんきん","ねんぐ","ねんざ","ねんし","ねんちゃく","ねんど","ねんぴ","ねんぶつ","ねんまつ","ねんりょう","ねんれい","のいず","のおづま","のがす","のきなみ","のこぎり","のこす","のこる","のせる","のぞく","のぞむ","のたまう","のちほど","のっく","のばす","のはら","のべる","のぼる","のみもの","のやま","のらいぬ","のらねこ","のりもの","のりゆき","のれん","のんき","ばあい","はあく","ばあさん","ばいか","ばいく","はいけん","はいご","はいしん","はいすい","はいせん","はいそう","はいち","ばいばい","はいれつ","はえる","はおる","はかい","ばかり","はかる","はくしゅ","はけん","はこぶ","はさみ","はさん","はしご","ばしょ","はしる","はせる","ぱそこん","はそん","はたん","はちみつ","はつおん","はっかく","はづき","はっきり","はっくつ","はっけん","はっこう","はっさん","はっしん","はったつ","はっちゅう","はってん","はっぴょう","はっぽう","はなす","はなび","はにかむ","はぶらし","はみがき","はむかう","はめつ","はやい","はやし","はらう","はろうぃん","はわい","はんい","はんえい","はんおん","はんかく","はんきょう","ばんぐみ","はんこ","はんしゃ","はんすう","はんだん","ぱんち","ぱんつ","はんてい","はんとし","はんのう","はんぱ","はんぶん","はんぺん","はんぼうき","はんめい","はんらん","はんろん","ひいき","ひうん","ひえる","ひかく","ひかり","ひかる","ひかん","ひくい","ひけつ","ひこうき","ひこく","ひさい","ひさしぶり","ひさん","びじゅつかん","ひしょ","ひそか","ひそむ","ひたむき","ひだり","ひたる","ひつぎ","ひっこし","ひっし","ひつじゅひん","ひっす","ひつぜん","ぴったり","ぴっちり","ひつよう","ひてい","ひとごみ","ひなまつり","ひなん","ひねる","ひはん","ひびく","ひひょう","ひほう","ひまわり","ひまん","ひみつ","ひめい","ひめじし","ひやけ","ひやす","ひよう","びょうき","ひらがな","ひらく","ひりつ","ひりょう","ひるま","ひるやすみ","ひれい","ひろい","ひろう","ひろき","ひろゆき","ひんかく","ひんけつ","ひんこん","ひんしゅ","ひんそう","ぴんち","ひんぱん","びんぼう","ふあん","ふいうち","ふうけい","ふうせん","ぷうたろう","ふうとう","ふうふ","ふえる","ふおん","ふかい","ふきん","ふくざつ","ふくぶくろ","ふこう","ふさい","ふしぎ","ふじみ","ふすま","ふせい","ふせぐ","ふそく","ぶたにく","ふたん","ふちょう","ふつう","ふつか","ふっかつ","ふっき","ふっこく","ぶどう","ふとる","ふとん","ふのう","ふはい","ふひょう","ふへん","ふまん","ふみん","ふめつ","ふめん","ふよう","ふりこ","ふりる","ふるい","ふんいき","ぶんがく","ぶんぐ","ふんしつ","ぶんせき","ふんそう","ぶんぽう","へいあん","へいおん","へいがい","へいき","へいげん","へいこう","へいさ","へいしゃ","へいせつ","へいそ","へいたく","へいてん","へいねつ","へいわ","へきが","へこむ","べにいろ","べにしょうが","へらす","へんかん","べんきょう","べんごし","へんさい","へんたい","べんり","ほあん","ほいく","ぼうぎょ","ほうこく","ほうそう","ほうほう","ほうもん","ほうりつ","ほえる","ほおん","ほかん","ほきょう","ぼきん","ほくろ","ほけつ","ほけん","ほこう","ほこる","ほしい","ほしつ","ほしゅ","ほしょう","ほせい","ほそい","ほそく","ほたて","ほたる","ぽちぶくろ","ほっきょく","ほっさ","ほったん","ほとんど","ほめる","ほんい","ほんき","ほんけ","ほんしつ","ほんやく","まいにち","まかい","まかせる","まがる","まける","まこと","まさつ","まじめ","ますく","まぜる","まつり","まとめ","まなぶ","まぬけ","まねく","まほう","まもる","まゆげ","まよう","まろやか","まわす","まわり","まわる","まんが","まんきつ","まんぞく","まんなか","みいら","みうち","みえる","みがく","みかた","みかん","みけん","みこん","みじかい","みすい","みすえる","みせる","みっか","みつかる","みつける","みてい","みとめる","みなと","みなみかさい","みねらる","みのう","みのがす","みほん","みもと","みやげ","みらい","みりょく","みわく","みんか","みんぞく","むいか","むえき","むえん","むかい","むかう","むかえ","むかし","むぎちゃ","むける","むげん","むさぼる","むしあつい","むしば","むじゅん","むしろ","むすう","むすこ","むすぶ","むすめ","むせる","むせん","むちゅう","むなしい","むのう","むやみ","むよう","むらさき","むりょう","むろん","めいあん","めいうん","めいえん","めいかく","めいきょく","めいさい","めいし","めいそう","めいぶつ","めいれい","めいわく","めぐまれる","めざす","めした","めずらしい","めだつ","めまい","めやす","めんきょ","めんせき","めんどう","もうしあげる","もうどうけん","もえる","もくし","もくてき","もくようび","もちろん","もどる","もらう","もんく","もんだい","やおや","やける","やさい","やさしい","やすい","やすたろう","やすみ","やせる","やそう","やたい","やちん","やっと","やっぱり","やぶる","やめる","ややこしい","やよい","やわらかい","ゆうき","ゆうびんきょく","ゆうべ","ゆうめい","ゆけつ","ゆしゅつ","ゆせん","ゆそう","ゆたか","ゆちゃく","ゆでる","ゆにゅう","ゆびわ","ゆらい","ゆれる","ようい","ようか","ようきゅう","ようじ","ようす","ようちえん","よかぜ","よかん","よきん","よくせい","よくぼう","よけい","よごれる","よさん","よしゅう","よそう","よそく","よっか","よてい","よどがわく","よねつ","よやく","よゆう","よろこぶ","よろしい","らいう","らくがき","らくご","らくさつ","らくだ","らしんばん","らせん","らぞく","らたい","らっか","られつ","りえき","りかい","りきさく","りきせつ","りくぐん","りくつ","りけん","りこう","りせい","りそう","りそく","りてん","りねん","りゆう","りゅうがく","りよう","りょうり","りょかん","りょくちゃ","りょこう","りりく","りれき","りろん","りんご","るいけい","るいさい","るいじ","るいせき","るすばん","るりがわら","れいかん","れいぎ","れいせい","れいぞうこ","れいとう","れいぼう","れきし","れきだい","れんあい","れんけい","れんこん","れんさい","れんしゅう","れんぞく","れんらく","ろうか","ろうご","ろうじん","ろうそく","ろくが","ろこつ","ろじうら","ろしゅつ","ろせん","ろてん","ろめん","ろれつ","ろんぎ","ろんぱ","ろんぶん","ろんり","わかす","わかめ","わかやま","わかれる","わしつ","わじまし","わすれもの","わらう","われる"]')},8013:module=>{"use strict";module.exports=JSON.parse('["가격","가끔","가난","가능","가득","가르침","가뭄","가방","가상","가슴","가운데","가을","가이드","가입","가장","가정","가족","가죽","각오","각자","간격","간부","간섭","간장","간접","간판","갈등","갈비","갈색","갈증","감각","감기","감소","감수성","감자","감정","갑자기","강남","강당","강도","강력히","강변","강북","강사","강수량","강아지","강원도","강의","강제","강조","같이","개구리","개나리","개방","개별","개선","개성","개인","객관적","거실","거액","거울","거짓","거품","걱정","건강","건물","건설","건조","건축","걸음","검사","검토","게시판","게임","겨울","견해","결과","결국","결론","결석","결승","결심","결정","결혼","경계","경고","경기","경력","경복궁","경비","경상도","경영","경우","경쟁","경제","경주","경찰","경치","경향","경험","계곡","계단","계란","계산","계속","계약","계절","계층","계획","고객","고구려","고궁","고급","고등학생","고무신","고민","고양이","고장","고전","고집","고춧가루","고통","고향","곡식","골목","골짜기","골프","공간","공개","공격","공군","공급","공기","공동","공무원","공부","공사","공식","공업","공연","공원","공장","공짜","공책","공통","공포","공항","공휴일","과목","과일","과장","과정","과학","관객","관계","관광","관념","관람","관련","관리","관습","관심","관점","관찰","광경","광고","광장","광주","괴로움","굉장히","교과서","교문","교복","교실","교양","교육","교장","교직","교통","교환","교훈","구경","구름","구멍","구별","구분","구석","구성","구속","구역","구입","구청","구체적","국가","국기","국내","국립","국물","국민","국수","국어","국왕","국적","국제","국회","군대","군사","군인","궁극적","권리","권위","권투","귀국","귀신","규정","규칙","균형","그날","그냥","그늘","그러나","그룹","그릇","그림","그제서야","그토록","극복","극히","근거","근교","근래","근로","근무","근본","근원","근육","근처","글씨","글자","금강산","금고","금년","금메달","금액","금연","금요일","금지","긍정적","기간","기관","기념","기능","기독교","기둥","기록","기름","기법","기본","기분","기쁨","기숙사","기술","기억","기업","기온","기운","기원","기적","기준","기침","기혼","기획","긴급","긴장","길이","김밥","김치","김포공항","깍두기","깜빡","깨달음","깨소금","껍질","꼭대기","꽃잎","나들이","나란히","나머지","나물","나침반","나흘","낙엽","난방","날개","날씨","날짜","남녀","남대문","남매","남산","남자","남편","남학생","낭비","낱말","내년","내용","내일","냄비","냄새","냇물","냉동","냉면","냉방","냉장고","넥타이","넷째","노동","노란색","노력","노인","녹음","녹차","녹화","논리","논문","논쟁","놀이","농구","농담","농민","농부","농업","농장","농촌","높이","눈동자","눈물","눈썹","뉴욕","느낌","늑대","능동적","능력","다방","다양성","다음","다이어트","다행","단계","단골","단독","단맛","단순","단어","단위","단점","단체","단추","단편","단풍","달걀","달러","달력","달리","닭고기","담당","담배","담요","담임","답변","답장","당근","당분간","당연히","당장","대규모","대낮","대단히","대답","대도시","대략","대량","대륙","대문","대부분","대신","대응","대장","대전","대접","대중","대책","대출","대충","대통령","대학","대한민국","대합실","대형","덩어리","데이트","도대체","도덕","도둑","도망","도서관","도심","도움","도입","도자기","도저히","도전","도중","도착","독감","독립","독서","독일","독창적","동화책","뒷모습","뒷산","딸아이","마누라","마늘","마당","마라톤","마련","마무리","마사지","마약","마요네즈","마을","마음","마이크","마중","마지막","마찬가지","마찰","마흔","막걸리","막내","막상","만남","만두","만세","만약","만일","만점","만족","만화","많이","말기","말씀","말투","맘대로","망원경","매년","매달","매력","매번","매스컴","매일","매장","맥주","먹이","먼저","먼지","멀리","메일","며느리","며칠","면담","멸치","명단","명령","명예","명의","명절","명칭","명함","모금","모니터","모델","모든","모범","모습","모양","모임","모조리","모집","모퉁이","목걸이","목록","목사","목소리","목숨","목적","목표","몰래","몸매","몸무게","몸살","몸속","몸짓","몸통","몹시","무관심","무궁화","무더위","무덤","무릎","무슨","무엇","무역","무용","무조건","무지개","무척","문구","문득","문법","문서","문제","문학","문화","물가","물건","물결","물고기","물론","물리학","물음","물질","물체","미국","미디어","미사일","미술","미역","미용실","미움","미인","미팅","미혼","민간","민족","민주","믿음","밀가루","밀리미터","밑바닥","바가지","바구니","바나나","바늘","바닥","바닷가","바람","바이러스","바탕","박물관","박사","박수","반대","반드시","반말","반발","반성","반응","반장","반죽","반지","반찬","받침","발가락","발걸음","발견","발달","발레","발목","발바닥","발생","발음","발자국","발전","발톱","발표","밤하늘","밥그릇","밥맛","밥상","밥솥","방금","방면","방문","방바닥","방법","방송","방식","방안","방울","방지","방학","방해","방향","배경","배꼽","배달","배드민턴","백두산","백색","백성","백인","백제","백화점","버릇","버섯","버튼","번개","번역","번지","번호","벌금","벌레","벌써","범위","범인","범죄","법률","법원","법적","법칙","베이징","벨트","변경","변동","변명","변신","변호사","변화","별도","별명","별일","병실","병아리","병원","보관","보너스","보라색","보람","보름","보상","보안","보자기","보장","보전","보존","보통","보편적","보험","복도","복사","복숭아","복습","볶음","본격적","본래","본부","본사","본성","본인","본질","볼펜","봉사","봉지","봉투","부근","부끄러움","부담","부동산","부문","부분","부산","부상","부엌","부인","부작용","부장","부정","부족","부지런히","부친","부탁","부품","부회장","북부","북한","분노","분량","분리","분명","분석","분야","분위기","분필","분홍색","불고기","불과","불교","불꽃","불만","불법","불빛","불안","불이익","불행","브랜드","비극","비난","비닐","비둘기","비디오","비로소","비만","비명","비밀","비바람","비빔밥","비상","비용","비율","비중","비타민","비판","빌딩","빗물","빗방울","빗줄기","빛깔","빨간색","빨래","빨리","사건","사계절","사나이","사냥","사람","사랑","사립","사모님","사물","사방","사상","사생활","사설","사슴","사실","사업","사용","사월","사장","사전","사진","사촌","사춘기","사탕","사투리","사흘","산길","산부인과","산업","산책","살림","살인","살짝","삼계탕","삼국","삼십","삼월","삼촌","상관","상금","상대","상류","상반기","상상","상식","상업","상인","상자","상점","상처","상추","상태","상표","상품","상황","새벽","색깔","색연필","생각","생명","생물","생방송","생산","생선","생신","생일","생활","서랍","서른","서명","서민","서비스","서양","서울","서적","서점","서쪽","서클","석사","석유","선거","선물","선배","선생","선수","선원","선장","선전","선택","선풍기","설거지","설날","설렁탕","설명","설문","설사","설악산","설치","설탕","섭씨","성공","성당","성명","성별","성인","성장","성적","성질","성함","세금","세미나","세상","세월","세종대왕","세탁","센터","센티미터","셋째","소규모","소극적","소금","소나기","소년","소득","소망","소문","소설","소속","소아과","소용","소원","소음","소중히","소지품","소질","소풍","소형","속담","속도","속옷","손가락","손길","손녀","손님","손등","손목","손뼉","손실","손질","손톱","손해","솔직히","솜씨","송아지","송이","송편","쇠고기","쇼핑","수건","수년","수단","수돗물","수동적","수면","수명","수박","수상","수석","수술","수시로","수업","수염","수영","수입","수준","수집","수출","수컷","수필","수학","수험생","수화기","숙녀","숙소","숙제","순간","순서","순수","순식간","순위","숟가락","술병","술집","숫자","스님","스물","스스로","스승","스웨터","스위치","스케이트","스튜디오","스트레스","스포츠","슬쩍","슬픔","습관","습기","승객","승리","승부","승용차","승진","시각","시간","시골","시금치","시나리오","시댁","시리즈","시멘트","시민","시부모","시선","시설","시스템","시아버지","시어머니","시월","시인","시일","시작","시장","시절","시점","시중","시즌","시집","시청","시합","시험","식구","식기","식당","식량","식료품","식물","식빵","식사","식생활","식초","식탁","식품","신고","신규","신념","신문","신발","신비","신사","신세","신용","신제품","신청","신체","신화","실감","실내","실력","실례","실망","실수","실습","실시","실장","실정","실질적","실천","실체","실컷","실태","실패","실험","실현","심리","심부름","심사","심장","심정","심판","쌍둥이","씨름","씨앗","아가씨","아나운서","아드님","아들","아쉬움","아스팔트","아시아","아울러","아저씨","아줌마","아직","아침","아파트","아프리카","아픔","아홉","아흔","악기","악몽","악수","안개","안경","안과","안내","안녕","안동","안방","안부","안주","알루미늄","알코올","암시","암컷","압력","앞날","앞문","애인","애정","액수","앨범","야간","야단","야옹","약간","약국","약속","약수","약점","약품","약혼녀","양념","양력","양말","양배추","양주","양파","어둠","어려움","어른","어젯밤","어쨌든","어쩌다가","어쩐지","언니","언덕","언론","언어","얼굴","얼른","얼음","얼핏","엄마","업무","업종","업체","엉덩이","엉망","엉터리","엊그제","에너지","에어컨","엔진","여건","여고생","여관","여군","여권","여대생","여덟","여동생","여든","여론","여름","여섯","여성","여왕","여인","여전히","여직원","여학생","여행","역사","역시","역할","연결","연구","연극","연기","연락","연설","연세","연속","연습","연애","연예인","연인","연장","연주","연출","연필","연합","연휴","열기","열매","열쇠","열심히","열정","열차","열흘","염려","엽서","영국","영남","영상","영양","영역","영웅","영원히","영하","영향","영혼","영화","옆구리","옆방","옆집","예감","예금","예방","예산","예상","예선","예술","예습","예식장","예약","예전","예절","예정","예컨대","옛날","오늘","오락","오랫동안","오렌지","오로지","오른발","오븐","오십","오염","오월","오전","오직","오징어","오페라","오피스텔","오히려","옥상","옥수수","온갖","온라인","온몸","온종일","온통","올가을","올림픽","올해","옷차림","와이셔츠","와인","완성","완전","왕비","왕자","왜냐하면","왠지","외갓집","외국","외로움","외삼촌","외출","외침","외할머니","왼발","왼손","왼쪽","요금","요일","요즘","요청","용기","용서","용어","우산","우선","우승","우연히","우정","우체국","우편","운동","운명","운반","운전","운행","울산","울음","움직임","웃어른","웃음","워낙","원고","원래","원서","원숭이","원인","원장","원피스","월급","월드컵","월세","월요일","웨이터","위반","위법","위성","위원","위험","위협","윗사람","유난히","유럽","유명","유물","유산","유적","유치원","유학","유행","유형","육군","육상","육십","육체","은행","음력","음료","음반","음성","음식","음악","음주","의견","의논","의문","의복","의식","의심","의외로","의욕","의원","의학","이것","이곳","이념","이놈","이달","이대로","이동","이렇게","이력서","이론적","이름","이민","이발소","이별","이불","이빨","이상","이성","이슬","이야기","이용","이웃","이월","이윽고","이익","이전","이중","이튿날","이틀","이혼","인간","인격","인공","인구","인근","인기","인도","인류","인물","인생","인쇄","인연","인원","인재","인종","인천","인체","인터넷","인하","인형","일곱","일기","일단","일대","일등","일반","일본","일부","일상","일생","일손","일요일","일월","일정","일종","일주일","일찍","일체","일치","일행","일회용","임금","임무","입대","입력","입맛","입사","입술","입시","입원","입장","입학","자가용","자격","자극","자동","자랑","자부심","자식","자신","자연","자원","자율","자전거","자정","자존심","자판","작가","작년","작성","작업","작용","작은딸","작품","잔디","잔뜩","잔치","잘못","잠깐","잠수함","잠시","잠옷","잠자리","잡지","장관","장군","장기간","장래","장례","장르","장마","장면","장모","장미","장비","장사","장소","장식","장애인","장인","장점","장차","장학금","재능","재빨리","재산","재생","재작년","재정","재채기","재판","재학","재활용","저것","저고리","저곳","저녁","저런","저렇게","저번","저울","저절로","저축","적극","적당히","적성","적용","적응","전개","전공","전기","전달","전라도","전망","전문","전반","전부","전세","전시","전용","전자","전쟁","전주","전철","전체","전통","전혀","전후","절대","절망","절반","절약","절차","점검","점수","점심","점원","점점","점차","접근","접시","접촉","젓가락","정거장","정도","정류장","정리","정말","정면","정문","정반대","정보","정부","정비","정상","정성","정오","정원","정장","정지","정치","정확히","제공","제과점","제대로","제목","제발","제법","제삿날","제안","제일","제작","제주도","제출","제품","제한","조각","조건","조금","조깅","조명","조미료","조상","조선","조용히","조절","조정","조직","존댓말","존재","졸업","졸음","종교","종로","종류","종소리","종업원","종종","종합","좌석","죄인","주관적","주름","주말","주머니","주먹","주문","주민","주방","주변","주식","주인","주일","주장","주전자","주택","준비","줄거리","줄기","줄무늬","중간","중계방송","중국","중년","중단","중독","중반","중부","중세","중소기업","중순","중앙","중요","중학교","즉석","즉시","즐거움","증가","증거","증권","증상","증세","지각","지갑","지경","지극히","지금","지급","지능","지름길","지리산","지방","지붕","지식","지역","지우개","지원","지적","지점","지진","지출","직선","직업","직원","직장","진급","진동","진로","진료","진리","진짜","진찰","진출","진통","진행","질문","질병","질서","짐작","집단","집안","집중","짜증","찌꺼기","차남","차라리","차량","차림","차별","차선","차츰","착각","찬물","찬성","참가","참기름","참새","참석","참여","참외","참조","찻잔","창가","창고","창구","창문","창밖","창작","창조","채널","채점","책가방","책방","책상","책임","챔피언","처벌","처음","천국","천둥","천장","천재","천천히","철도","철저히","철학","첫날","첫째","청년","청바지","청소","청춘","체계","체력","체온","체육","체중","체험","초등학생","초반","초밥","초상화","초순","초여름","초원","초저녁","초점","초청","초콜릿","촛불","총각","총리","총장","촬영","최근","최상","최선","최신","최악","최종","추석","추억","추진","추천","추측","축구","축소","축제","축하","출근","출발","출산","출신","출연","출입","출장","출판","충격","충고","충돌","충분히","충청도","취업","취직","취향","치약","친구","친척","칠십","칠월","칠판","침대","침묵","침실","칫솔","칭찬","카메라","카운터","칼국수","캐릭터","캠퍼스","캠페인","커튼","컨디션","컬러","컴퓨터","코끼리","코미디","콘서트","콜라","콤플렉스","콩나물","쾌감","쿠데타","크림","큰길","큰딸","큰소리","큰아들","큰어머니","큰일","큰절","클래식","클럽","킬로","타입","타자기","탁구","탁자","탄생","태권도","태양","태풍","택시","탤런트","터널","터미널","테니스","테스트","테이블","텔레비전","토론","토마토","토요일","통계","통과","통로","통신","통역","통일","통장","통제","통증","통합","통화","퇴근","퇴원","퇴직금","튀김","트럭","특급","특별","특성","특수","특징","특히","튼튼히","티셔츠","파란색","파일","파출소","판결","판단","판매","판사","팔십","팔월","팝송","패션","팩스","팩시밀리","팬티","퍼센트","페인트","편견","편의","편지","편히","평가","평균","평생","평소","평양","평일","평화","포스터","포인트","포장","포함","표면","표정","표준","표현","품목","품질","풍경","풍속","풍습","프랑스","프린터","플라스틱","피곤","피망","피아노","필름","필수","필요","필자","필통","핑계","하느님","하늘","하드웨어","하룻밤","하반기","하숙집","하순","하여튼","하지만","하천","하품","하필","학과","학교","학급","학기","학년","학력","학번","학부모","학비","학생","학술","학습","학용품","학원","학위","학자","학점","한계","한글","한꺼번에","한낮","한눈","한동안","한때","한라산","한마디","한문","한번","한복","한식","한여름","한쪽","할머니","할아버지","할인","함께","함부로","합격","합리적","항공","항구","항상","항의","해결","해군","해답","해당","해물","해석","해설","해수욕장","해안","핵심","핸드백","햄버거","햇볕","햇살","행동","행복","행사","행운","행위","향기","향상","향수","허락","허용","헬기","현관","현금","현대","현상","현실","현장","현재","현지","혈액","협력","형부","형사","형수","형식","형제","형태","형편","혜택","호기심","호남","호랑이","호박","호텔","호흡","혹시","홀로","홈페이지","홍보","홍수","홍차","화면","화분","화살","화요일","화장","화학","확보","확인","확장","확정","환갑","환경","환영","환율","환자","활기","활동","활발히","활용","활짝","회견","회관","회복","회색","회원","회장","회전","횟수","횡단보도","효율적","후반","후춧가루","훈련","훨씬","휴식","휴일","흉내","흐름","흑백","흑인","흔적","흔히","흥미","흥분","희곡","희망","희생","흰색","힘껏"]')},1945:module=>{"use strict";module.exports=JSON.parse('["abacate","abaixo","abalar","abater","abduzir","abelha","aberto","abismo","abotoar","abranger","abreviar","abrigar","abrupto","absinto","absoluto","absurdo","abutre","acabado","acalmar","acampar","acanhar","acaso","aceitar","acelerar","acenar","acervo","acessar","acetona","achatar","acidez","acima","acionado","acirrar","aclamar","aclive","acolhida","acomodar","acoplar","acordar","acumular","acusador","adaptar","adega","adentro","adepto","adequar","aderente","adesivo","adeus","adiante","aditivo","adjetivo","adjunto","admirar","adorar","adquirir","adubo","adverso","advogado","aeronave","afastar","aferir","afetivo","afinador","afivelar","aflito","afluente","afrontar","agachar","agarrar","agasalho","agenciar","agilizar","agiota","agitado","agora","agradar","agreste","agrupar","aguardar","agulha","ajoelhar","ajudar","ajustar","alameda","alarme","alastrar","alavanca","albergue","albino","alcatra","aldeia","alecrim","alegria","alertar","alface","alfinete","algum","alheio","aliar","alicate","alienar","alinhar","aliviar","almofada","alocar","alpiste","alterar","altitude","alucinar","alugar","aluno","alusivo","alvo","amaciar","amador","amarelo","amassar","ambas","ambiente","ameixa","amenizar","amido","amistoso","amizade","amolador","amontoar","amoroso","amostra","amparar","ampliar","ampola","anagrama","analisar","anarquia","anatomia","andaime","anel","anexo","angular","animar","anjo","anomalia","anotado","ansioso","anterior","anuidade","anunciar","anzol","apagador","apalpar","apanhado","apego","apelido","apertada","apesar","apetite","apito","aplauso","aplicada","apoio","apontar","aposta","aprendiz","aprovar","aquecer","arame","aranha","arara","arcada","ardente","areia","arejar","arenito","aresta","argiloso","argola","arma","arquivo","arraial","arrebate","arriscar","arroba","arrumar","arsenal","arterial","artigo","arvoredo","asfaltar","asilado","aspirar","assador","assinar","assoalho","assunto","astral","atacado","atadura","atalho","atarefar","atear","atender","aterro","ateu","atingir","atirador","ativo","atoleiro","atracar","atrevido","atriz","atual","atum","auditor","aumentar","aura","aurora","autismo","autoria","autuar","avaliar","avante","avaria","avental","avesso","aviador","avisar","avulso","axila","azarar","azedo","azeite","azulejo","babar","babosa","bacalhau","bacharel","bacia","bagagem","baiano","bailar","baioneta","bairro","baixista","bajular","baleia","baliza","balsa","banal","bandeira","banho","banir","banquete","barato","barbado","baronesa","barraca","barulho","baseado","bastante","batata","batedor","batida","batom","batucar","baunilha","beber","beijo","beirada","beisebol","beldade","beleza","belga","beliscar","bendito","bengala","benzer","berimbau","berlinda","berro","besouro","bexiga","bezerro","bico","bicudo","bienal","bifocal","bifurcar","bigorna","bilhete","bimestre","bimotor","biologia","biombo","biosfera","bipolar","birrento","biscoito","bisneto","bispo","bissexto","bitola","bizarro","blindado","bloco","bloquear","boato","bobagem","bocado","bocejo","bochecha","boicotar","bolada","boletim","bolha","bolo","bombeiro","bonde","boneco","bonita","borbulha","borda","boreal","borracha","bovino","boxeador","branco","brasa","braveza","breu","briga","brilho","brincar","broa","brochura","bronzear","broto","bruxo","bucha","budismo","bufar","bule","buraco","busca","busto","buzina","cabana","cabelo","cabide","cabo","cabrito","cacau","cacetada","cachorro","cacique","cadastro","cadeado","cafezal","caiaque","caipira","caixote","cajado","caju","calafrio","calcular","caldeira","calibrar","calmante","calota","camada","cambista","camisa","camomila","campanha","camuflar","canavial","cancelar","caneta","canguru","canhoto","canivete","canoa","cansado","cantar","canudo","capacho","capela","capinar","capotar","capricho","captador","capuz","caracol","carbono","cardeal","careca","carimbar","carneiro","carpete","carreira","cartaz","carvalho","casaco","casca","casebre","castelo","casulo","catarata","cativar","caule","causador","cautelar","cavalo","caverna","cebola","cedilha","cegonha","celebrar","celular","cenoura","censo","centeio","cercar","cerrado","certeiro","cerveja","cetim","cevada","chacota","chaleira","chamado","chapada","charme","chatice","chave","chefe","chegada","cheiro","cheque","chicote","chifre","chinelo","chocalho","chover","chumbo","chutar","chuva","cicatriz","ciclone","cidade","cidreira","ciente","cigana","cimento","cinto","cinza","ciranda","circuito","cirurgia","citar","clareza","clero","clicar","clone","clube","coado","coagir","cobaia","cobertor","cobrar","cocada","coelho","coentro","coeso","cogumelo","coibir","coifa","coiote","colar","coleira","colher","colidir","colmeia","colono","coluna","comando","combinar","comentar","comitiva","comover","complexo","comum","concha","condor","conectar","confuso","congelar","conhecer","conjugar","consumir","contrato","convite","cooperar","copeiro","copiador","copo","coquetel","coragem","cordial","corneta","coronha","corporal","correio","cortejo","coruja","corvo","cosseno","costela","cotonete","couro","couve","covil","cozinha","cratera","cravo","creche","credor","creme","crer","crespo","criada","criminal","crioulo","crise","criticar","crosta","crua","cruzeiro","cubano","cueca","cuidado","cujo","culatra","culminar","culpar","cultura","cumprir","cunhado","cupido","curativo","curral","cursar","curto","cuspir","custear","cutelo","damasco","datar","debater","debitar","deboche","debulhar","decalque","decimal","declive","decote","decretar","dedal","dedicado","deduzir","defesa","defumar","degelo","degrau","degustar","deitado","deixar","delator","delegado","delinear","delonga","demanda","demitir","demolido","dentista","depenado","depilar","depois","depressa","depurar","deriva","derramar","desafio","desbotar","descanso","desenho","desfiado","desgaste","desigual","deslize","desmamar","desova","despesa","destaque","desviar","detalhar","detentor","detonar","detrito","deusa","dever","devido","devotado","dezena","diagrama","dialeto","didata","difuso","digitar","dilatado","diluente","diminuir","dinastia","dinheiro","diocese","direto","discreta","disfarce","disparo","disquete","dissipar","distante","ditador","diurno","diverso","divisor","divulgar","dizer","dobrador","dolorido","domador","dominado","donativo","donzela","dormente","dorsal","dosagem","dourado","doutor","drenagem","drible","drogaria","duelar","duende","dueto","duplo","duquesa","durante","duvidoso","eclodir","ecoar","ecologia","edificar","edital","educado","efeito","efetivar","ejetar","elaborar","eleger","eleitor","elenco","elevador","eliminar","elogiar","embargo","embolado","embrulho","embutido","emenda","emergir","emissor","empatia","empenho","empinado","empolgar","emprego","empurrar","emulador","encaixe","encenado","enchente","encontro","endeusar","endossar","enfaixar","enfeite","enfim","engajado","engenho","englobar","engomado","engraxar","enguia","enjoar","enlatar","enquanto","enraizar","enrolado","enrugar","ensaio","enseada","ensino","ensopado","entanto","enteado","entidade","entortar","entrada","entulho","envergar","enviado","envolver","enxame","enxerto","enxofre","enxuto","epiderme","equipar","ereto","erguido","errata","erva","ervilha","esbanjar","esbelto","escama","escola","escrita","escuta","esfinge","esfolar","esfregar","esfumado","esgrima","esmalte","espanto","espelho","espiga","esponja","espreita","espumar","esquerda","estaca","esteira","esticar","estofado","estrela","estudo","esvaziar","etanol","etiqueta","euforia","europeu","evacuar","evaporar","evasivo","eventual","evidente","evoluir","exagero","exalar","examinar","exato","exausto","excesso","excitar","exclamar","executar","exemplo","exibir","exigente","exonerar","expandir","expelir","expirar","explanar","exposto","expresso","expulsar","externo","extinto","extrato","fabricar","fabuloso","faceta","facial","fada","fadiga","faixa","falar","falta","familiar","fandango","fanfarra","fantoche","fardado","farelo","farinha","farofa","farpa","fartura","fatia","fator","favorita","faxina","fazenda","fechado","feijoada","feirante","felino","feminino","fenda","feno","fera","feriado","ferrugem","ferver","festejar","fetal","feudal","fiapo","fibrose","ficar","ficheiro","figurado","fileira","filho","filme","filtrar","firmeza","fisgada","fissura","fita","fivela","fixador","fixo","flacidez","flamingo","flanela","flechada","flora","flutuar","fluxo","focal","focinho","fofocar","fogo","foguete","foice","folgado","folheto","forjar","formiga","forno","forte","fosco","fossa","fragata","fralda","frango","frasco","fraterno","freira","frente","fretar","frieza","friso","fritura","fronha","frustrar","fruteira","fugir","fulano","fuligem","fundar","fungo","funil","furador","furioso","futebol","gabarito","gabinete","gado","gaiato","gaiola","gaivota","galega","galho","galinha","galocha","ganhar","garagem","garfo","gargalo","garimpo","garoupa","garrafa","gasoduto","gasto","gata","gatilho","gaveta","gazela","gelado","geleia","gelo","gemada","gemer","gemido","generoso","gengiva","genial","genoma","genro","geologia","gerador","germinar","gesso","gestor","ginasta","gincana","gingado","girafa","girino","glacial","glicose","global","glorioso","goela","goiaba","golfe","golpear","gordura","gorjeta","gorro","gostoso","goteira","governar","gracejo","gradual","grafite","gralha","grampo","granada","gratuito","graveto","graxa","grego","grelhar","greve","grilo","grisalho","gritaria","grosso","grotesco","grudado","grunhido","gruta","guache","guarani","guaxinim","guerrear","guiar","guincho","guisado","gula","guloso","guru","habitar","harmonia","haste","haver","hectare","herdar","heresia","hesitar","hiato","hibernar","hidratar","hiena","hino","hipismo","hipnose","hipoteca","hoje","holofote","homem","honesto","honrado","hormonal","hospedar","humorado","iate","ideia","idoso","ignorado","igreja","iguana","ileso","ilha","iludido","iluminar","ilustrar","imagem","imediato","imenso","imersivo","iminente","imitador","imortal","impacto","impedir","implante","impor","imprensa","impune","imunizar","inalador","inapto","inativo","incenso","inchar","incidir","incluir","incolor","indeciso","indireto","indutor","ineficaz","inerente","infantil","infestar","infinito","inflamar","informal","infrator","ingerir","inibido","inicial","inimigo","injetar","inocente","inodoro","inovador","inox","inquieto","inscrito","inseto","insistir","inspetor","instalar","insulto","intacto","integral","intimar","intocado","intriga","invasor","inverno","invicto","invocar","iogurte","iraniano","ironizar","irreal","irritado","isca","isento","isolado","isqueiro","italiano","janeiro","jangada","janta","jararaca","jardim","jarro","jasmim","jato","javali","jazida","jejum","joaninha","joelhada","jogador","joia","jornal","jorrar","jovem","juba","judeu","judoca","juiz","julgador","julho","jurado","jurista","juro","justa","labareda","laboral","lacre","lactante","ladrilho","lagarta","lagoa","laje","lamber","lamentar","laminar","lampejo","lanche","lapidar","lapso","laranja","lareira","largura","lasanha","lastro","lateral","latido","lavanda","lavoura","lavrador","laxante","lazer","lealdade","lebre","legado","legendar","legista","leigo","leiloar","leitura","lembrete","leme","lenhador","lentilha","leoa","lesma","leste","letivo","letreiro","levar","leveza","levitar","liberal","libido","liderar","ligar","ligeiro","limitar","limoeiro","limpador","linda","linear","linhagem","liquidez","listagem","lisura","litoral","livro","lixa","lixeira","locador","locutor","lojista","lombo","lona","longe","lontra","lorde","lotado","loteria","loucura","lousa","louvar","luar","lucidez","lucro","luneta","lustre","lutador","luva","macaco","macete","machado","macio","madeira","madrinha","magnata","magreza","maior","mais","malandro","malha","malote","maluco","mamilo","mamoeiro","mamute","manada","mancha","mandato","manequim","manhoso","manivela","manobrar","mansa","manter","manusear","mapeado","maquinar","marcador","maresia","marfim","margem","marinho","marmita","maroto","marquise","marreco","martelo","marujo","mascote","masmorra","massagem","mastigar","matagal","materno","matinal","matutar","maxilar","medalha","medida","medusa","megafone","meiga","melancia","melhor","membro","memorial","menino","menos","mensagem","mental","merecer","mergulho","mesada","mesclar","mesmo","mesquita","mestre","metade","meteoro","metragem","mexer","mexicano","micro","migalha","migrar","milagre","milenar","milhar","mimado","minerar","minhoca","ministro","minoria","miolo","mirante","mirtilo","misturar","mocidade","moderno","modular","moeda","moer","moinho","moita","moldura","moleza","molho","molinete","molusco","montanha","moqueca","morango","morcego","mordomo","morena","mosaico","mosquete","mostarda","motel","motim","moto","motriz","muda","muito","mulata","mulher","multar","mundial","munido","muralha","murcho","muscular","museu","musical","nacional","nadador","naja","namoro","narina","narrado","nascer","nativa","natureza","navalha","navegar","navio","neblina","nebuloso","negativa","negociar","negrito","nervoso","neta","neural","nevasca","nevoeiro","ninar","ninho","nitidez","nivelar","nobreza","noite","noiva","nomear","nominal","nordeste","nortear","notar","noticiar","noturno","novelo","novilho","novo","nublado","nudez","numeral","nupcial","nutrir","nuvem","obcecado","obedecer","objetivo","obrigado","obscuro","obstetra","obter","obturar","ocidente","ocioso","ocorrer","oculista","ocupado","ofegante","ofensiva","oferenda","oficina","ofuscado","ogiva","olaria","oleoso","olhar","oliveira","ombro","omelete","omisso","omitir","ondulado","oneroso","ontem","opcional","operador","oponente","oportuno","oposto","orar","orbitar","ordem","ordinal","orfanato","orgasmo","orgulho","oriental","origem","oriundo","orla","ortodoxo","orvalho","oscilar","ossada","osso","ostentar","otimismo","ousadia","outono","outubro","ouvido","ovelha","ovular","oxidar","oxigenar","pacato","paciente","pacote","pactuar","padaria","padrinho","pagar","pagode","painel","pairar","paisagem","palavra","palestra","palheta","palito","palmada","palpitar","pancada","panela","panfleto","panqueca","pantanal","papagaio","papelada","papiro","parafina","parcial","pardal","parede","partida","pasmo","passado","pastel","patamar","patente","patinar","patrono","paulada","pausar","peculiar","pedalar","pedestre","pediatra","pedra","pegada","peitoral","peixe","pele","pelicano","penca","pendurar","peneira","penhasco","pensador","pente","perceber","perfeito","pergunta","perito","permitir","perna","perplexo","persiana","pertence","peruca","pescado","pesquisa","pessoa","petiscar","piada","picado","piedade","pigmento","pilastra","pilhado","pilotar","pimenta","pincel","pinguim","pinha","pinote","pintar","pioneiro","pipoca","piquete","piranha","pires","pirueta","piscar","pistola","pitanga","pivete","planta","plaqueta","platina","plebeu","plumagem","pluvial","pneu","poda","poeira","poetisa","polegada","policiar","poluente","polvilho","pomar","pomba","ponderar","pontaria","populoso","porta","possuir","postal","pote","poupar","pouso","povoar","praia","prancha","prato","praxe","prece","predador","prefeito","premiar","prensar","preparar","presilha","pretexto","prevenir","prezar","primata","princesa","prisma","privado","processo","produto","profeta","proibido","projeto","prometer","propagar","prosa","protetor","provador","publicar","pudim","pular","pulmonar","pulseira","punhal","punir","pupilo","pureza","puxador","quadra","quantia","quarto","quase","quebrar","queda","queijo","quente","querido","quimono","quina","quiosque","rabanada","rabisco","rachar","racionar","radial","raiar","rainha","raio","raiva","rajada","ralado","ramal","ranger","ranhura","rapadura","rapel","rapidez","raposa","raquete","raridade","rasante","rascunho","rasgar","raspador","rasteira","rasurar","ratazana","ratoeira","realeza","reanimar","reaver","rebaixar","rebelde","rebolar","recado","recente","recheio","recibo","recordar","recrutar","recuar","rede","redimir","redonda","reduzida","reenvio","refinar","refletir","refogar","refresco","refugiar","regalia","regime","regra","reinado","reitor","rejeitar","relativo","remador","remendo","remorso","renovado","reparo","repelir","repleto","repolho","represa","repudiar","requerer","resenha","resfriar","resgatar","residir","resolver","respeito","ressaca","restante","resumir","retalho","reter","retirar","retomada","retratar","revelar","revisor","revolta","riacho","rica","rigidez","rigoroso","rimar","ringue","risada","risco","risonho","robalo","rochedo","rodada","rodeio","rodovia","roedor","roleta","romano","roncar","rosado","roseira","rosto","rota","roteiro","rotina","rotular","rouco","roupa","roxo","rubro","rugido","rugoso","ruivo","rumo","rupestre","russo","sabor","saciar","sacola","sacudir","sadio","safira","saga","sagrada","saibro","salada","saleiro","salgado","saliva","salpicar","salsicha","saltar","salvador","sambar","samurai","sanar","sanfona","sangue","sanidade","sapato","sarda","sargento","sarjeta","saturar","saudade","saxofone","sazonal","secar","secular","seda","sedento","sediado","sedoso","sedutor","segmento","segredo","segundo","seiva","seleto","selvagem","semanal","semente","senador","senhor","sensual","sentado","separado","sereia","seringa","serra","servo","setembro","setor","sigilo","silhueta","silicone","simetria","simpatia","simular","sinal","sincero","singular","sinopse","sintonia","sirene","siri","situado","soberano","sobra","socorro","sogro","soja","solda","soletrar","solteiro","sombrio","sonata","sondar","sonegar","sonhador","sono","soprano","soquete","sorrir","sorteio","sossego","sotaque","soterrar","sovado","sozinho","suavizar","subida","submerso","subsolo","subtrair","sucata","sucesso","suco","sudeste","sufixo","sugador","sugerir","sujeito","sulfato","sumir","suor","superior","suplicar","suposto","suprimir","surdina","surfista","surpresa","surreal","surtir","suspiro","sustento","tabela","tablete","tabuada","tacho","tagarela","talher","talo","talvez","tamanho","tamborim","tampa","tangente","tanto","tapar","tapioca","tardio","tarefa","tarja","tarraxa","tatuagem","taurino","taxativo","taxista","teatral","tecer","tecido","teclado","tedioso","teia","teimar","telefone","telhado","tempero","tenente","tensor","tentar","termal","terno","terreno","tese","tesoura","testado","teto","textura","texugo","tiara","tigela","tijolo","timbrar","timidez","tingido","tinteiro","tiragem","titular","toalha","tocha","tolerar","tolice","tomada","tomilho","tonel","tontura","topete","tora","torcido","torneio","torque","torrada","torto","tostar","touca","toupeira","toxina","trabalho","tracejar","tradutor","trafegar","trajeto","trama","trancar","trapo","traseiro","tratador","travar","treino","tremer","trepidar","trevo","triagem","tribo","triciclo","tridente","trilogia","trindade","triplo","triturar","triunfal","trocar","trombeta","trova","trunfo","truque","tubular","tucano","tudo","tulipa","tupi","turbo","turma","turquesa","tutelar","tutorial","uivar","umbigo","unha","unidade","uniforme","urologia","urso","urtiga","urubu","usado","usina","usufruir","vacina","vadiar","vagaroso","vaidoso","vala","valente","validade","valores","vantagem","vaqueiro","varanda","vareta","varrer","vascular","vasilha","vassoura","vazar","vazio","veado","vedar","vegetar","veicular","veleiro","velhice","veludo","vencedor","vendaval","venerar","ventre","verbal","verdade","vereador","vergonha","vermelho","verniz","versar","vertente","vespa","vestido","vetorial","viaduto","viagem","viajar","viatura","vibrador","videira","vidraria","viela","viga","vigente","vigiar","vigorar","vilarejo","vinco","vinheta","vinil","violeta","virada","virtude","visitar","visto","vitral","viveiro","vizinho","voador","voar","vogal","volante","voleibol","voltagem","volumoso","vontade","vulto","vuvuzela","xadrez","xarope","xeque","xeretar","xerife","xingar","zangado","zarpar","zebu","zelador","zombar","zoologia","zumbido"]')},659:module=>{"use strict";module.exports=JSON.parse('["ábaco","abdomen","abeja","abierto","abogado","abono","aborto","abrazo","abrir","abuelo","abuso","acabar","academia","acceso","acción","aceite","acelga","acento","aceptar","ácido","aclarar","acné","acoger","acoso","activo","acto","actriz","actuar","acudir","acuerdo","acusar","adicto","admitir","adoptar","adorno","aduana","adulto","aéreo","afectar","afición","afinar","afirmar","ágil","agitar","agonía","agosto","agotar","agregar","agrio","agua","agudo","águila","aguja","ahogo","ahorro","aire","aislar","ajedrez","ajeno","ajuste","alacrán","alambre","alarma","alba","álbum","alcalde","aldea","alegre","alejar","alerta","aleta","alfiler","alga","algodón","aliado","aliento","alivio","alma","almeja","almíbar","altar","alteza","altivo","alto","altura","alumno","alzar","amable","amante","amapola","amargo","amasar","ámbar","ámbito","ameno","amigo","amistad","amor","amparo","amplio","ancho","anciano","ancla","andar","andén","anemia","ángulo","anillo","ánimo","anís","anotar","antena","antiguo","antojo","anual","anular","anuncio","añadir","añejo","año","apagar","aparato","apetito","apio","aplicar","apodo","aporte","apoyo","aprender","aprobar","apuesta","apuro","arado","araña","arar","árbitro","árbol","arbusto","archivo","arco","arder","ardilla","arduo","área","árido","aries","armonía","arnés","aroma","arpa","arpón","arreglo","arroz","arruga","arte","artista","asa","asado","asalto","ascenso","asegurar","aseo","asesor","asiento","asilo","asistir","asno","asombro","áspero","astilla","astro","astuto","asumir","asunto","atajo","ataque","atar","atento","ateo","ático","atleta","átomo","atraer","atroz","atún","audaz","audio","auge","aula","aumento","ausente","autor","aval","avance","avaro","ave","avellana","avena","avestruz","avión","aviso","ayer","ayuda","ayuno","azafrán","azar","azote","azúcar","azufre","azul","baba","babor","bache","bahía","baile","bajar","balanza","balcón","balde","bambú","banco","banda","baño","barba","barco","barniz","barro","báscula","bastón","basura","batalla","batería","batir","batuta","baúl","bazar","bebé","bebida","bello","besar","beso","bestia","bicho","bien","bingo","blanco","bloque","blusa","boa","bobina","bobo","boca","bocina","boda","bodega","boina","bola","bolero","bolsa","bomba","bondad","bonito","bono","bonsái","borde","borrar","bosque","bote","botín","bóveda","bozal","bravo","brazo","brecha","breve","brillo","brinco","brisa","broca","broma","bronce","brote","bruja","brusco","bruto","buceo","bucle","bueno","buey","bufanda","bufón","búho","buitre","bulto","burbuja","burla","burro","buscar","butaca","buzón","caballo","cabeza","cabina","cabra","cacao","cadáver","cadena","caer","café","caída","caimán","caja","cajón","cal","calamar","calcio","caldo","calidad","calle","calma","calor","calvo","cama","cambio","camello","camino","campo","cáncer","candil","canela","canguro","canica","canto","caña","cañón","caoba","caos","capaz","capitán","capote","captar","capucha","cara","carbón","cárcel","careta","carga","cariño","carne","carpeta","carro","carta","casa","casco","casero","caspa","castor","catorce","catre","caudal","causa","cazo","cebolla","ceder","cedro","celda","célebre","celoso","célula","cemento","ceniza","centro","cerca","cerdo","cereza","cero","cerrar","certeza","césped","cetro","chacal","chaleco","champú","chancla","chapa","charla","chico","chiste","chivo","choque","choza","chuleta","chupar","ciclón","ciego","cielo","cien","cierto","cifra","cigarro","cima","cinco","cine","cinta","ciprés","circo","ciruela","cisne","cita","ciudad","clamor","clan","claro","clase","clave","cliente","clima","clínica","cobre","cocción","cochino","cocina","coco","código","codo","cofre","coger","cohete","cojín","cojo","cola","colcha","colegio","colgar","colina","collar","colmo","columna","combate","comer","comida","cómodo","compra","conde","conejo","conga","conocer","consejo","contar","copa","copia","corazón","corbata","corcho","cordón","corona","correr","coser","cosmos","costa","cráneo","cráter","crear","crecer","creído","crema","cría","crimen","cripta","crisis","cromo","crónica","croqueta","crudo","cruz","cuadro","cuarto","cuatro","cubo","cubrir","cuchara","cuello","cuento","cuerda","cuesta","cueva","cuidar","culebra","culpa","culto","cumbre","cumplir","cuna","cuneta","cuota","cupón","cúpula","curar","curioso","curso","curva","cutis","dama","danza","dar","dardo","dátil","deber","débil","década","decir","dedo","defensa","definir","dejar","delfín","delgado","delito","demora","denso","dental","deporte","derecho","derrota","desayuno","deseo","desfile","desnudo","destino","desvío","detalle","detener","deuda","día","diablo","diadema","diamante","diana","diario","dibujo","dictar","diente","dieta","diez","difícil","digno","dilema","diluir","dinero","directo","dirigir","disco","diseño","disfraz","diva","divino","doble","doce","dolor","domingo","don","donar","dorado","dormir","dorso","dos","dosis","dragón","droga","ducha","duda","duelo","dueño","dulce","dúo","duque","durar","dureza","duro","ébano","ebrio","echar","eco","ecuador","edad","edición","edificio","editor","educar","efecto","eficaz","eje","ejemplo","elefante","elegir","elemento","elevar","elipse","élite","elixir","elogio","eludir","embudo","emitir","emoción","empate","empeño","empleo","empresa","enano","encargo","enchufe","encía","enemigo","enero","enfado","enfermo","engaño","enigma","enlace","enorme","enredo","ensayo","enseñar","entero","entrar","envase","envío","época","equipo","erizo","escala","escena","escolar","escribir","escudo","esencia","esfera","esfuerzo","espada","espejo","espía","esposa","espuma","esquí","estar","este","estilo","estufa","etapa","eterno","ética","etnia","evadir","evaluar","evento","evitar","exacto","examen","exceso","excusa","exento","exigir","exilio","existir","éxito","experto","explicar","exponer","extremo","fábrica","fábula","fachada","fácil","factor","faena","faja","falda","fallo","falso","faltar","fama","familia","famoso","faraón","farmacia","farol","farsa","fase","fatiga","fauna","favor","fax","febrero","fecha","feliz","feo","feria","feroz","fértil","fervor","festín","fiable","fianza","fiar","fibra","ficción","ficha","fideo","fiebre","fiel","fiera","fiesta","figura","fijar","fijo","fila","filete","filial","filtro","fin","finca","fingir","finito","firma","flaco","flauta","flecha","flor","flota","fluir","flujo","flúor","fobia","foca","fogata","fogón","folio","folleto","fondo","forma","forro","fortuna","forzar","fosa","foto","fracaso","frágil","franja","frase","fraude","freír","freno","fresa","frío","frito","fruta","fuego","fuente","fuerza","fuga","fumar","función","funda","furgón","furia","fusil","fútbol","futuro","gacela","gafas","gaita","gajo","gala","galería","gallo","gamba","ganar","gancho","ganga","ganso","garaje","garza","gasolina","gastar","gato","gavilán","gemelo","gemir","gen","género","genio","gente","geranio","gerente","germen","gesto","gigante","gimnasio","girar","giro","glaciar","globo","gloria","gol","golfo","goloso","golpe","goma","gordo","gorila","gorra","gota","goteo","gozar","grada","gráfico","grano","grasa","gratis","grave","grieta","grillo","gripe","gris","grito","grosor","grúa","grueso","grumo","grupo","guante","guapo","guardia","guerra","guía","guiño","guion","guiso","guitarra","gusano","gustar","haber","hábil","hablar","hacer","hacha","hada","hallar","hamaca","harina","haz","hazaña","hebilla","hebra","hecho","helado","helio","hembra","herir","hermano","héroe","hervir","hielo","hierro","hígado","higiene","hijo","himno","historia","hocico","hogar","hoguera","hoja","hombre","hongo","honor","honra","hora","hormiga","horno","hostil","hoyo","hueco","huelga","huerta","hueso","huevo","huida","huir","humano","húmedo","humilde","humo","hundir","huracán","hurto","icono","ideal","idioma","ídolo","iglesia","iglú","igual","ilegal","ilusión","imagen","imán","imitar","impar","imperio","imponer","impulso","incapaz","índice","inerte","infiel","informe","ingenio","inicio","inmenso","inmune","innato","insecto","instante","interés","íntimo","intuir","inútil","invierno","ira","iris","ironía","isla","islote","jabalí","jabón","jamón","jarabe","jardín","jarra","jaula","jazmín","jefe","jeringa","jinete","jornada","joroba","joven","joya","juerga","jueves","juez","jugador","jugo","juguete","juicio","junco","jungla","junio","juntar","júpiter","jurar","justo","juvenil","juzgar","kilo","koala","labio","lacio","lacra","lado","ladrón","lagarto","lágrima","laguna","laico","lamer","lámina","lámpara","lana","lancha","langosta","lanza","lápiz","largo","larva","lástima","lata","látex","latir","laurel","lavar","lazo","leal","lección","leche","lector","leer","legión","legumbre","lejano","lengua","lento","leña","león","leopardo","lesión","letal","letra","leve","leyenda","libertad","libro","licor","líder","lidiar","lienzo","liga","ligero","lima","límite","limón","limpio","lince","lindo","línea","lingote","lino","linterna","líquido","liso","lista","litera","litio","litro","llaga","llama","llanto","llave","llegar","llenar","llevar","llorar","llover","lluvia","lobo","loción","loco","locura","lógica","logro","lombriz","lomo","lonja","lote","lucha","lucir","lugar","lujo","luna","lunes","lupa","lustro","luto","luz","maceta","macho","madera","madre","maduro","maestro","mafia","magia","mago","maíz","maldad","maleta","malla","malo","mamá","mambo","mamut","manco","mando","manejar","manga","maniquí","manjar","mano","manso","manta","mañana","mapa","máquina","mar","marco","marea","marfil","margen","marido","mármol","marrón","martes","marzo","masa","máscara","masivo","matar","materia","matiz","matriz","máximo","mayor","mazorca","mecha","medalla","medio","médula","mejilla","mejor","melena","melón","memoria","menor","mensaje","mente","menú","mercado","merengue","mérito","mes","mesón","meta","meter","método","metro","mezcla","miedo","miel","miembro","miga","mil","milagro","militar","millón","mimo","mina","minero","mínimo","minuto","miope","mirar","misa","miseria","misil","mismo","mitad","mito","mochila","moción","moda","modelo","moho","mojar","molde","moler","molino","momento","momia","monarca","moneda","monja","monto","moño","morada","morder","moreno","morir","morro","morsa","mortal","mosca","mostrar","motivo","mover","móvil","mozo","mucho","mudar","mueble","muela","muerte","muestra","mugre","mujer","mula","muleta","multa","mundo","muñeca","mural","muro","músculo","museo","musgo","música","muslo","nácar","nación","nadar","naipe","naranja","nariz","narrar","nasal","natal","nativo","natural","náusea","naval","nave","navidad","necio","néctar","negar","negocio","negro","neón","nervio","neto","neutro","nevar","nevera","nicho","nido","niebla","nieto","niñez","niño","nítido","nivel","nobleza","noche","nómina","noria","norma","norte","nota","noticia","novato","novela","novio","nube","nuca","núcleo","nudillo","nudo","nuera","nueve","nuez","nulo","número","nutria","oasis","obeso","obispo","objeto","obra","obrero","observar","obtener","obvio","oca","ocaso","océano","ochenta","ocho","ocio","ocre","octavo","octubre","oculto","ocupar","ocurrir","odiar","odio","odisea","oeste","ofensa","oferta","oficio","ofrecer","ogro","oído","oír","ojo","ola","oleada","olfato","olivo","olla","olmo","olor","olvido","ombligo","onda","onza","opaco","opción","ópera","opinar","oponer","optar","óptica","opuesto","oración","orador","oral","órbita","orca","orden","oreja","órgano","orgía","orgullo","oriente","origen","orilla","oro","orquesta","oruga","osadía","oscuro","osezno","oso","ostra","otoño","otro","oveja","óvulo","óxido","oxígeno","oyente","ozono","pacto","padre","paella","página","pago","país","pájaro","palabra","palco","paleta","pálido","palma","paloma","palpar","pan","panal","pánico","pantera","pañuelo","papá","papel","papilla","paquete","parar","parcela","pared","parir","paro","párpado","parque","párrafo","parte","pasar","paseo","pasión","paso","pasta","pata","patio","patria","pausa","pauta","pavo","payaso","peatón","pecado","pecera","pecho","pedal","pedir","pegar","peine","pelar","peldaño","pelea","peligro","pellejo","pelo","peluca","pena","pensar","peñón","peón","peor","pepino","pequeño","pera","percha","perder","pereza","perfil","perico","perla","permiso","perro","persona","pesa","pesca","pésimo","pestaña","pétalo","petróleo","pez","pezuña","picar","pichón","pie","piedra","pierna","pieza","pijama","pilar","piloto","pimienta","pino","pintor","pinza","piña","piojo","pipa","pirata","pisar","piscina","piso","pista","pitón","pizca","placa","plan","plata","playa","plaza","pleito","pleno","plomo","pluma","plural","pobre","poco","poder","podio","poema","poesía","poeta","polen","policía","pollo","polvo","pomada","pomelo","pomo","pompa","poner","porción","portal","posada","poseer","posible","poste","potencia","potro","pozo","prado","precoz","pregunta","premio","prensa","preso","previo","primo","príncipe","prisión","privar","proa","probar","proceso","producto","proeza","profesor","programa","prole","promesa","pronto","propio","próximo","prueba","público","puchero","pudor","pueblo","puerta","puesto","pulga","pulir","pulmón","pulpo","pulso","puma","punto","puñal","puño","pupa","pupila","puré","quedar","queja","quemar","querer","queso","quieto","química","quince","quitar","rábano","rabia","rabo","ración","radical","raíz","rama","rampa","rancho","rango","rapaz","rápido","rapto","rasgo","raspa","rato","rayo","raza","razón","reacción","realidad","rebaño","rebote","recaer","receta","rechazo","recoger","recreo","recto","recurso","red","redondo","reducir","reflejo","reforma","refrán","refugio","regalo","regir","regla","regreso","rehén","reino","reír","reja","relato","relevo","relieve","relleno","reloj","remar","remedio","remo","rencor","rendir","renta","reparto","repetir","reposo","reptil","res","rescate","resina","respeto","resto","resumen","retiro","retorno","retrato","reunir","revés","revista","rey","rezar","rico","riego","rienda","riesgo","rifa","rígido","rigor","rincón","riñón","río","riqueza","risa","ritmo","rito","rizo","roble","roce","rociar","rodar","rodeo","rodilla","roer","rojizo","rojo","romero","romper","ron","ronco","ronda","ropa","ropero","rosa","rosca","rostro","rotar","rubí","rubor","rudo","rueda","rugir","ruido","ruina","ruleta","rulo","rumbo","rumor","ruptura","ruta","rutina","sábado","saber","sabio","sable","sacar","sagaz","sagrado","sala","saldo","salero","salir","salmón","salón","salsa","salto","salud","salvar","samba","sanción","sandía","sanear","sangre","sanidad","sano","santo","sapo","saque","sardina","sartén","sastre","satán","sauna","saxofón","sección","seco","secreto","secta","sed","seguir","seis","sello","selva","semana","semilla","senda","sensor","señal","señor","separar","sepia","sequía","ser","serie","sermón","servir","sesenta","sesión","seta","setenta","severo","sexo","sexto","sidra","siesta","siete","siglo","signo","sílaba","silbar","silencio","silla","símbolo","simio","sirena","sistema","sitio","situar","sobre","socio","sodio","sol","solapa","soldado","soledad","sólido","soltar","solución","sombra","sondeo","sonido","sonoro","sonrisa","sopa","soplar","soporte","sordo","sorpresa","sorteo","sostén","sótano","suave","subir","suceso","sudor","suegra","suelo","sueño","suerte","sufrir","sujeto","sultán","sumar","superar","suplir","suponer","supremo","sur","surco","sureño","surgir","susto","sutil","tabaco","tabique","tabla","tabú","taco","tacto","tajo","talar","talco","talento","talla","talón","tamaño","tambor","tango","tanque","tapa","tapete","tapia","tapón","taquilla","tarde","tarea","tarifa","tarjeta","tarot","tarro","tarta","tatuaje","tauro","taza","tazón","teatro","techo","tecla","técnica","tejado","tejer","tejido","tela","teléfono","tema","temor","templo","tenaz","tender","tener","tenis","tenso","teoría","terapia","terco","término","ternura","terror","tesis","tesoro","testigo","tetera","texto","tez","tibio","tiburón","tiempo","tienda","tierra","tieso","tigre","tijera","tilde","timbre","tímido","timo","tinta","tío","típico","tipo","tira","tirón","titán","títere","título","tiza","toalla","tobillo","tocar","tocino","todo","toga","toldo","tomar","tono","tonto","topar","tope","toque","tórax","torero","tormenta","torneo","toro","torpedo","torre","torso","tortuga","tos","tosco","toser","tóxico","trabajo","tractor","traer","tráfico","trago","traje","tramo","trance","trato","trauma","trazar","trébol","tregua","treinta","tren","trepar","tres","tribu","trigo","tripa","triste","triunfo","trofeo","trompa","tronco","tropa","trote","trozo","truco","trueno","trufa","tubería","tubo","tuerto","tumba","tumor","túnel","túnica","turbina","turismo","turno","tutor","ubicar","úlcera","umbral","unidad","unir","universo","uno","untar","uña","urbano","urbe","urgente","urna","usar","usuario","útil","utopía","uva","vaca","vacío","vacuna","vagar","vago","vaina","vajilla","vale","válido","valle","valor","válvula","vampiro","vara","variar","varón","vaso","vecino","vector","vehículo","veinte","vejez","vela","velero","veloz","vena","vencer","venda","veneno","vengar","venir","venta","venus","ver","verano","verbo","verde","vereda","verja","verso","verter","vía","viaje","vibrar","vicio","víctima","vida","vídeo","vidrio","viejo","viernes","vigor","vil","villa","vinagre","vino","viñedo","violín","viral","virgo","virtud","visor","víspera","vista","vitamina","viudo","vivaz","vivero","vivir","vivo","volcán","volumen","volver","voraz","votar","voto","voz","vuelo","vulgar","yacer","yate","yegua","yema","yerno","yeso","yodo","yoga","yogur","zafiro","zanja","zapato","zarza","zona","zorro","zumo","zurdo"]')},4946:module=>{"use strict";module.exports=JSON.parse('{"aes-128-ecb":{"cipher":"AES","key":128,"iv":0,"mode":"ECB","type":"block"},"aes-192-ecb":{"cipher":"AES","key":192,"iv":0,"mode":"ECB","type":"block"},"aes-256-ecb":{"cipher":"AES","key":256,"iv":0,"mode":"ECB","type":"block"},"aes-128-cbc":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes-192-cbc":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes-256-cbc":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes128":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes192":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes256":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes-128-cfb":{"cipher":"AES","key":128,"iv":16,"mode":"CFB","type":"stream"},"aes-192-cfb":{"cipher":"AES","key":192,"iv":16,"mode":"CFB","type":"stream"},"aes-256-cfb":{"cipher":"AES","key":256,"iv":16,"mode":"CFB","type":"stream"},"aes-128-cfb8":{"cipher":"AES","key":128,"iv":16,"mode":"CFB8","type":"stream"},"aes-192-cfb8":{"cipher":"AES","key":192,"iv":16,"mode":"CFB8","type":"stream"},"aes-256-cfb8":{"cipher":"AES","key":256,"iv":16,"mode":"CFB8","type":"stream"},"aes-128-cfb1":{"cipher":"AES","key":128,"iv":16,"mode":"CFB1","type":"stream"},"aes-192-cfb1":{"cipher":"AES","key":192,"iv":16,"mode":"CFB1","type":"stream"},"aes-256-cfb1":{"cipher":"AES","key":256,"iv":16,"mode":"CFB1","type":"stream"},"aes-128-ofb":{"cipher":"AES","key":128,"iv":16,"mode":"OFB","type":"stream"},"aes-192-ofb":{"cipher":"AES","key":192,"iv":16,"mode":"OFB","type":"stream"},"aes-256-ofb":{"cipher":"AES","key":256,"iv":16,"mode":"OFB","type":"stream"},"aes-128-ctr":{"cipher":"AES","key":128,"iv":16,"mode":"CTR","type":"stream"},"aes-192-ctr":{"cipher":"AES","key":192,"iv":16,"mode":"CTR","type":"stream"},"aes-256-ctr":{"cipher":"AES","key":256,"iv":16,"mode":"CTR","type":"stream"},"aes-128-gcm":{"cipher":"AES","key":128,"iv":12,"mode":"GCM","type":"auth"},"aes-192-gcm":{"cipher":"AES","key":192,"iv":12,"mode":"GCM","type":"auth"},"aes-256-gcm":{"cipher":"AES","key":256,"iv":12,"mode":"GCM","type":"auth"}}')},5207:module=>{"use strict";module.exports=JSON.parse('{"sha224WithRSAEncryption":{"sign":"rsa","hash":"sha224","id":"302d300d06096086480165030402040500041c"},"RSA-SHA224":{"sign":"ecdsa/rsa","hash":"sha224","id":"302d300d06096086480165030402040500041c"},"sha256WithRSAEncryption":{"sign":"rsa","hash":"sha256","id":"3031300d060960864801650304020105000420"},"RSA-SHA256":{"sign":"ecdsa/rsa","hash":"sha256","id":"3031300d060960864801650304020105000420"},"sha384WithRSAEncryption":{"sign":"rsa","hash":"sha384","id":"3041300d060960864801650304020205000430"},"RSA-SHA384":{"sign":"ecdsa/rsa","hash":"sha384","id":"3041300d060960864801650304020205000430"},"sha512WithRSAEncryption":{"sign":"rsa","hash":"sha512","id":"3051300d060960864801650304020305000440"},"RSA-SHA512":{"sign":"ecdsa/rsa","hash":"sha512","id":"3051300d060960864801650304020305000440"},"RSA-SHA1":{"sign":"rsa","hash":"sha1","id":"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{"sign":"ecdsa","hash":"sha1","id":""},"sha256":{"sign":"ecdsa","hash":"sha256","id":""},"sha224":{"sign":"ecdsa","hash":"sha224","id":""},"sha384":{"sign":"ecdsa","hash":"sha384","id":""},"sha512":{"sign":"ecdsa","hash":"sha512","id":""},"DSA-SHA":{"sign":"dsa","hash":"sha1","id":""},"DSA-SHA1":{"sign":"dsa","hash":"sha1","id":""},"DSA":{"sign":"dsa","hash":"sha1","id":""},"DSA-WITH-SHA224":{"sign":"dsa","hash":"sha224","id":""},"DSA-SHA224":{"sign":"dsa","hash":"sha224","id":""},"DSA-WITH-SHA256":{"sign":"dsa","hash":"sha256","id":""},"DSA-SHA256":{"sign":"dsa","hash":"sha256","id":""},"DSA-WITH-SHA384":{"sign":"dsa","hash":"sha384","id":""},"DSA-SHA384":{"sign":"dsa","hash":"sha384","id":""},"DSA-WITH-SHA512":{"sign":"dsa","hash":"sha512","id":""},"DSA-SHA512":{"sign":"dsa","hash":"sha512","id":""},"DSA-RIPEMD160":{"sign":"dsa","hash":"rmd160","id":""},"ripemd160WithRSA":{"sign":"rsa","hash":"rmd160","id":"3021300906052b2403020105000414"},"RSA-RIPEMD160":{"sign":"rsa","hash":"rmd160","id":"3021300906052b2403020105000414"},"md5WithRSAEncryption":{"sign":"rsa","hash":"md5","id":"3020300c06082a864886f70d020505000410"},"RSA-MD5":{"sign":"rsa","hash":"md5","id":"3020300c06082a864886f70d020505000410"}}')},1308:module=>{"use strict";module.exports=JSON.parse('{"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}')},9799:module=>{"use strict";module.exports=JSON.parse('{"modp1":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},"modp2":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},"modp5":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},"modp14":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},"modp15":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},"modp16":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},"modp17":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},"modp18":{"gen":"02","prime":"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}')},8597:module=>{"use strict";module.exports={i8:"6.5.4"}},2562:module=>{"use strict";module.exports=JSON.parse('{"2.16.840.1.101.3.4.1.1":"aes-128-ecb","2.16.840.1.101.3.4.1.2":"aes-128-cbc","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}')}},__webpack_module_cache__={};function __webpack_require__(moduleId){var cachedModule=__webpack_module_cache__[moduleId];if(void 0!==cachedModule)return cachedModule.exports;var module=__webpack_module_cache__[moduleId]={id:moduleId,loaded:!1,exports:{}};return __webpack_modules__[moduleId].call(module.exports,module,module.exports,__webpack_require__),module.loaded=!0,module.exports}return __webpack_require__.amdO={},__webpack_require__.n=module=>{var getter=module&&module.__esModule?()=>module.default:()=>module;return __webpack_require__.d(getter,{a:getter}),getter},__webpack_require__.d=(exports,definition)=>{for(var key in definition)__webpack_require__.o(definition,key)&&!__webpack_require__.o(exports,key)&&Object.defineProperty(exports,key,{enumerable:!0,get:definition[key]})},__webpack_require__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),__webpack_require__.o=(obj,prop)=>Object.prototype.hasOwnProperty.call(obj,prop),__webpack_require__.r=exports=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(exports,"__esModule",{value:!0})},__webpack_require__.nmd=module=>(module.paths=[],module.children||(module.children=[]),module),__webpack_require__(5590)})())); \ No newline at end of file diff --git a/web/avalanche.js.LICENSE.txt b/web/avalanche.js.LICENSE.txt deleted file mode 100644 index 0db30065c..000000000 --- a/web/avalanche.js.LICENSE.txt +++ /dev/null @@ -1,26 +0,0 @@ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ - -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ - -/** - * [js-sha3]{@link https://github.com/emn178/js-sha3} - * - * @version 0.8.0 - * @author Chen, Yi-Cyuan [emn178@gmail.com] - * @copyright Chen, Yi-Cyuan 2015-2018 - * @license MIT - */ diff --git a/web/index.html b/web/index.html deleted file mode 100644 index a3e7fc914..000000000 --- a/web/index.html +++ /dev/null @@ -1 +0,0 @@ -Caching \ No newline at end of file diff --git a/webpack.config.js b/webpack.config.js deleted file mode 100644 index 1d65f524c..000000000 --- a/webpack.config.js +++ /dev/null @@ -1,67 +0,0 @@ -const path = require("path") -const webpack = require("webpack") -const HtmlWebpackPlugin = require("html-webpack-plugin") -const { CleanWebpackPlugin } = require("clean-webpack-plugin") -const { GitRevisionPlugin } = require("git-revision-webpack-plugin") -const gitRevisionPlugin = new GitRevisionPlugin() -const TerserPlugin = require("terser-webpack-plugin") - -module.exports = { - entry: { - avalanche: "./dist/index.js" - }, - - devServer: { - contentBase: "./dist" - }, - module: { - rules: [ - { - test: /\.tsx?$/, - loader: "ts-loader", - exclude: /node_modules/ - } - ] - }, - resolve: { - extensions: [".tsx", ".ts", ".js"], - fallback: { - stream: require.resolve("stream-browserify"), - crypto: require.resolve("crypto-browserify"), - assert: require.resolve("assert/") - } - }, - output: { - //filename: '[name]-[git-revision-version].js', - filename: "[name].js", - path: path.resolve(__dirname, "web"), - library: "avalanche", - libraryTarget: "umd", - umdNamedDefine: true - }, - plugins: [ - gitRevisionPlugin, - new CleanWebpackPlugin(), - new webpack.DefinePlugin({ - VERSION: JSON.stringify(gitRevisionPlugin.version()), - COMMITHASH: JSON.stringify(gitRevisionPlugin.commithash()), - BRANCH: JSON.stringify(gitRevisionPlugin.branch()) - }), - new HtmlWebpackPlugin({ - title: "Caching" - }) - ], - optimization: { - minimizer: [ - new TerserPlugin({ - terserOptions: { - ecma: 2015, - warnings: false, - mangle: false, - keep_classnames: true, - keep_fnames: true - } - }) - ] - } -} diff --git a/yarn.lock b/yarn.lock index c0c5e5da6..d47a2e452 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,10 +2,15 @@ # yarn lockfile v1 -"@adraffy/ens-normalize@1.8.9": - version "1.8.9" - resolved "https://registry.yarnpkg.com/@adraffy/ens-normalize/-/ens-normalize-1.8.9.tgz#67b3acadebbb551669c9a1da15fac951db795b85" - integrity sha512-93OmGCV0vO8+JQ3FHG+gZk/MPHzzMPDRiCiFcCQNTCnHaaxsacO3ScTPGlu2wX2dOtgfalbchPcw1cOYYjHCYQ== +"@aashutoshrathi/word-wrap@^1.2.3": + version "1.2.6" + resolved "https://registry.yarnpkg.com/@aashutoshrathi/word-wrap/-/word-wrap-1.2.6.tgz#bd9154aec9983f77b3a034ecaa015c2e4201f6cf" + integrity sha512-1Yjs2SvM8TflER/OD3cOjhWWOZb58A2t7wpE2S9XfBYTiIl+XFhQG2bjy4Pu1I+EAlCNUzRDYDdFwFYUKvXcIA== + +"@adraffy/ens-normalize@1.10.1": + version "1.10.1" + resolved "https://registry.yarnpkg.com/@adraffy/ens-normalize/-/ens-normalize-1.10.1.tgz#63430d04bd8c5e74f8d7d049338f1cd9d4f02069" + integrity sha512-96Z2IP3mYmF1Xg2cDm8f1gWGf/HUVedQ3FMifV4kG/PQ4yEP51xDtRAEfhVNt5f/uzpNkZHwWQuUcu6D6K+Ekw== "@ampproject/remapping@^2.1.0": version "2.2.0" @@ -15,38 +20,27 @@ "@jridgewell/gen-mapping" "^0.1.0" "@jridgewell/trace-mapping" "^0.3.9" -"@babel/code-frame@7.12.11": - version "7.12.11" - resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.12.11.tgz#f4ad435aa263db935b8f10f2c552d23fb716a63f" - integrity sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw== - dependencies: - "@babel/highlight" "^7.10.4" - -"@babel/code-frame@^7.0.0", "@babel/code-frame@^7.16.7": - version "7.16.7" - resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.16.7.tgz#44416b6bd7624b998f5b1af5d470856c40138789" - integrity sha512-iAXqUn8IIeBTNd72xsFlgaXHkMBMt6y4HJp1tIaK465CWLT/fG1aqB7ykr95gHHmlBdGbFeWWfyB4NJJ0nmeIg== - dependencies: - "@babel/highlight" "^7.16.7" - -"@babel/code-frame@^7.12.13", "@babel/code-frame@^7.18.6": +"@babel/code-frame@^7.0.0", "@babel/code-frame@^7.12.13", "@babel/code-frame@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.18.6.tgz#3b25d38c89600baa2dcc219edfa88a74eb2c427a" integrity sha512-TDCmlK5eOvH+eH7cdAFlNXeVJqWIQ7gW9tY1GJIpUtFb6CmjVyq2VM3u71bOyR8CRihcCgMUYoDNyLXao3+70Q== dependencies: "@babel/highlight" "^7.18.6" -"@babel/compat-data@^7.17.10": - version "7.17.10" - resolved "https://registry.yarnpkg.com/@babel/compat-data/-/compat-data-7.17.10.tgz#711dc726a492dfc8be8220028b1b92482362baab" - integrity sha512-GZt/TCsG70Ms19gfZO1tM4CVnXsPgEPBCpJu+Qz3L0LUDsY5nZqFZglIoPC1kIYOtNBZlrnFT+klg12vFGZXrw== +"@babel/code-frame@^7.22.13", "@babel/code-frame@^7.23.5": + version "7.23.5" + resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.23.5.tgz#9009b69a8c602293476ad598ff53e4562e15c244" + integrity sha512-CgH3s1a96LipHCmSUmYFPwY7MNx8C3avkq7i4Wl3cfa662ldtUe4VM1TPXX70pfmrlWTb6jLqTYrZyT2ZTJBgA== + dependencies: + "@babel/highlight" "^7.23.4" + chalk "^2.4.2" "@babel/compat-data@^7.20.5": version "7.20.14" resolved "https://registry.yarnpkg.com/@babel/compat-data/-/compat-data-7.20.14.tgz#4106fc8b755f3e3ee0a0a7c27dde5de1d2b2baf8" integrity sha512-0YpKHD6ImkWMEINCyDAD0HLLUH/lPCefG8ld9it8DJB2wnApraKuhgYTvTY1z7UFIfBTGy5LwncZ+5HWWGbhFw== -"@babel/core@^7.11.6": +"@babel/core@^7.11.6", "@babel/core@^7.12.3": version "7.20.12" resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.20.12.tgz#7930db57443c6714ad216953d1356dac0eb8496d" integrity sha512-XsMfHovsUYHFMdrIHkZphTN/2Hzzi78R08NuHfDBehym2VsPDL6Zn/JAD/JQdnRvbSsbQc4mVaU1m6JgtTEElg== @@ -67,36 +61,6 @@ json5 "^2.2.2" semver "^6.3.0" -"@babel/core@^7.12.3": - version "7.17.10" - resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.17.10.tgz#74ef0fbf56b7dfc3f198fc2d927f4f03e12f4b05" - integrity sha512-liKoppandF3ZcBnIYFjfSDHZLKdLHGJRkoWtG8zQyGJBQfIYobpnVGI5+pLBNtS6psFLDzyq8+h5HiVljW9PNA== - dependencies: - "@ampproject/remapping" "^2.1.0" - "@babel/code-frame" "^7.16.7" - "@babel/generator" "^7.17.10" - "@babel/helper-compilation-targets" "^7.17.10" - "@babel/helper-module-transforms" "^7.17.7" - "@babel/helpers" "^7.17.9" - "@babel/parser" "^7.17.10" - "@babel/template" "^7.16.7" - "@babel/traverse" "^7.17.10" - "@babel/types" "^7.17.10" - convert-source-map "^1.7.0" - debug "^4.1.0" - gensync "^1.0.0-beta.2" - json5 "^2.2.1" - semver "^6.3.0" - -"@babel/generator@^7.17.10": - version "7.17.10" - resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.17.10.tgz#c281fa35b0c349bbe9d02916f4ae08fc85ed7189" - integrity sha512-46MJZZo9y3o4kmhBVc7zW7i8dtR1oIK/sdO5NcfcZRhTGYi+KKJRtHNgsU6c4VUcJmUNV/LQdebD/9Dlv4K+Tg== - dependencies: - "@babel/types" "^7.17.10" - "@jridgewell/gen-mapping" "^0.1.0" - jsesc "^2.5.1" - "@babel/generator@^7.20.7", "@babel/generator@^7.7.2": version "7.20.14" resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.20.14.tgz#9fa772c9f86a46c6ac9b321039400712b96f64ce" @@ -106,15 +70,15 @@ "@jridgewell/gen-mapping" "^0.3.2" jsesc "^2.5.1" -"@babel/helper-compilation-targets@^7.17.10": - version "7.17.10" - resolved "https://registry.yarnpkg.com/@babel/helper-compilation-targets/-/helper-compilation-targets-7.17.10.tgz#09c63106d47af93cf31803db6bc49fef354e2ebe" - integrity sha512-gh3RxjWbauw/dFiU/7whjd0qN9K6nPJMqe6+Er7rOavFh0CQUSwhAE3IcTho2rywPJFxej6TUUHDkWcYI6gGqQ== +"@babel/generator@^7.23.6": + version "7.23.6" + resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.23.6.tgz#9e1fca4811c77a10580d17d26b57b036133f3c2e" + integrity sha512-qrSfCYxYQB5owCmGLbl8XRpX1ytXlpueOb0N0UmQwA073KZxejgQTzAmJezxvpwQD9uGtK2shHdi55QT+MbjIw== dependencies: - "@babel/compat-data" "^7.17.10" - "@babel/helper-validator-option" "^7.16.7" - browserslist "^4.20.2" - semver "^6.3.0" + "@babel/types" "^7.23.6" + "@jridgewell/gen-mapping" "^0.3.2" + "@jridgewell/trace-mapping" "^0.3.17" + jsesc "^2.5.1" "@babel/helper-compilation-targets@^7.20.7": version "7.20.7" @@ -127,54 +91,30 @@ lru-cache "^5.1.1" semver "^6.3.0" -"@babel/helper-environment-visitor@^7.16.7": - version "7.16.7" - resolved "https://registry.yarnpkg.com/@babel/helper-environment-visitor/-/helper-environment-visitor-7.16.7.tgz#ff484094a839bde9d89cd63cba017d7aae80ecd7" - integrity sha512-SLLb0AAn6PkUeAfKJCCOl9e1R53pQlGAfc4y4XuMRZfqeMYLE0dM1LMhqbGAlGQY0lfw5/ohoYWAe9V1yibRag== - dependencies: - "@babel/types" "^7.16.7" - "@babel/helper-environment-visitor@^7.18.9": version "7.18.9" resolved "https://registry.yarnpkg.com/@babel/helper-environment-visitor/-/helper-environment-visitor-7.18.9.tgz#0c0cee9b35d2ca190478756865bb3528422f51be" integrity sha512-3r/aACDJ3fhQ/EVgFy0hpj8oHyHpQc+LPtJoY9SzTThAsStm4Ptegq92vqKoE3vD706ZVFWITnMnxucw+S9Ipg== -"@babel/helper-function-name@^7.17.9": - version "7.17.9" - resolved "https://registry.yarnpkg.com/@babel/helper-function-name/-/helper-function-name-7.17.9.tgz#136fcd54bc1da82fcb47565cf16fd8e444b1ff12" - integrity sha512-7cRisGlVtiVqZ0MW0/yFB4atgpGLWEHUVYnb448hZK4x+vih0YO5UoS11XIYtZYqHd0dIPMdUSv8q5K4LdMnIg== - dependencies: - "@babel/template" "^7.16.7" - "@babel/types" "^7.17.0" - -"@babel/helper-function-name@^7.19.0": - version "7.19.0" - resolved "https://registry.yarnpkg.com/@babel/helper-function-name/-/helper-function-name-7.19.0.tgz#941574ed5390682e872e52d3f38ce9d1bef4648c" - integrity sha512-WAwHBINyrpqywkUH0nTnNgI5ina5TFn85HKS0pbPDfxFfhyR/aNQEn4hGi1P1JyT//I0t4OgXUlofzWILRvS5w== - dependencies: - "@babel/template" "^7.18.10" - "@babel/types" "^7.19.0" - -"@babel/helper-hoist-variables@^7.16.7": - version "7.16.7" - resolved "https://registry.yarnpkg.com/@babel/helper-hoist-variables/-/helper-hoist-variables-7.16.7.tgz#86bcb19a77a509c7b77d0e22323ef588fa58c246" - integrity sha512-m04d/0Op34H5v7pbZw6pSKP7weA6lsMvfiIAMeIvkY/R4xQtBSMFEigu9QTZ2qB/9l22vsxtM8a+Q8CzD255fg== - dependencies: - "@babel/types" "^7.16.7" +"@babel/helper-environment-visitor@^7.22.20": + version "7.22.20" + resolved "https://registry.yarnpkg.com/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz#96159db61d34a29dba454c959f5ae4a649ba9167" + integrity sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA== -"@babel/helper-hoist-variables@^7.18.6": - version "7.18.6" - resolved "https://registry.yarnpkg.com/@babel/helper-hoist-variables/-/helper-hoist-variables-7.18.6.tgz#d4d2c8fb4baeaa5c68b99cc8245c56554f926678" - integrity sha512-UlJQPkFqFULIcyW5sbzgbkxn2FKRgwWiRexcuaR8RNJRy8+LLveqPjwZV/bwrLZCN0eUHD/x8D0heK1ozuoo6Q== +"@babel/helper-function-name@^7.23.0": + version "7.23.0" + resolved "https://registry.yarnpkg.com/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz#1f9a3cdbd5b2698a670c30d2735f9af95ed52759" + integrity sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw== dependencies: - "@babel/types" "^7.18.6" + "@babel/template" "^7.22.15" + "@babel/types" "^7.23.0" -"@babel/helper-module-imports@^7.16.7": - version "7.16.7" - resolved "https://registry.yarnpkg.com/@babel/helper-module-imports/-/helper-module-imports-7.16.7.tgz#25612a8091a999704461c8a222d0efec5d091437" - integrity sha512-LVtS6TqjJHFc+nYeITRo6VLXve70xmq7wPhWTqDJusJEgGmkAACWwMiTNrvfoQo6hEhFwAIixNkvB0jPXDL8Wg== +"@babel/helper-hoist-variables@^7.22.5": + version "7.22.5" + resolved "https://registry.yarnpkg.com/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz#c01a007dac05c085914e8fb652b339db50d823bb" + integrity sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw== dependencies: - "@babel/types" "^7.16.7" + "@babel/types" "^7.22.5" "@babel/helper-module-imports@^7.18.6": version "7.18.6" @@ -183,20 +123,6 @@ dependencies: "@babel/types" "^7.18.6" -"@babel/helper-module-transforms@^7.17.7": - version "7.17.7" - resolved "https://registry.yarnpkg.com/@babel/helper-module-transforms/-/helper-module-transforms-7.17.7.tgz#3943c7f777139e7954a5355c815263741a9c1cbd" - integrity sha512-VmZD99F3gNTYB7fJRDTi+u6l/zxY0BE6OIxPSU7a50s6ZUQkHwSDmV92FfM+oCG0pZRVojGYhkR8I0OGeCVREw== - dependencies: - "@babel/helper-environment-visitor" "^7.16.7" - "@babel/helper-module-imports" "^7.16.7" - "@babel/helper-simple-access" "^7.17.7" - "@babel/helper-split-export-declaration" "^7.16.7" - "@babel/helper-validator-identifier" "^7.16.7" - "@babel/template" "^7.16.7" - "@babel/traverse" "^7.17.3" - "@babel/types" "^7.17.0" - "@babel/helper-module-transforms@^7.20.11": version "7.20.11" resolved "https://registry.yarnpkg.com/@babel/helper-module-transforms/-/helper-module-transforms-7.20.11.tgz#df4c7af713c557938c50ea3ad0117a7944b2f1b0" @@ -211,23 +137,11 @@ "@babel/traverse" "^7.20.10" "@babel/types" "^7.20.7" -"@babel/helper-plugin-utils@^7.0.0", "@babel/helper-plugin-utils@^7.10.4", "@babel/helper-plugin-utils@^7.12.13", "@babel/helper-plugin-utils@^7.14.5", "@babel/helper-plugin-utils@^7.8.0": - version "7.16.7" - resolved "https://registry.yarnpkg.com/@babel/helper-plugin-utils/-/helper-plugin-utils-7.16.7.tgz#aa3a8ab4c3cceff8e65eb9e73d87dc4ff320b2f5" - integrity sha512-Qg3Nk7ZxpgMrsox6HreY1ZNKdBq7K72tDSliA6dCl5f007jR4ne8iD5UzuNnCJH2xBf2BEEVGr+/OL6Gdp7RxA== - -"@babel/helper-plugin-utils@^7.18.6", "@babel/helper-plugin-utils@^7.19.0": +"@babel/helper-plugin-utils@^7.0.0", "@babel/helper-plugin-utils@^7.10.4", "@babel/helper-plugin-utils@^7.12.13", "@babel/helper-plugin-utils@^7.14.5", "@babel/helper-plugin-utils@^7.18.6", "@babel/helper-plugin-utils@^7.19.0", "@babel/helper-plugin-utils@^7.8.0": version "7.20.2" resolved "https://registry.yarnpkg.com/@babel/helper-plugin-utils/-/helper-plugin-utils-7.20.2.tgz#d1b9000752b18d0877cff85a5c376ce5c3121629" integrity sha512-8RvlJG2mj4huQ4pZ+rU9lqKi9ZKiRmuvGuM2HlWmkmgOhbs6zEAw6IEiJ5cQqGbDzGZOhwuOQNtZMi/ENLjZoQ== -"@babel/helper-simple-access@^7.17.7": - version "7.17.7" - resolved "https://registry.yarnpkg.com/@babel/helper-simple-access/-/helper-simple-access-7.17.7.tgz#aaa473de92b7987c6dfa7ce9a7d9674724823367" - integrity sha512-txyMCGroZ96i+Pxr3Je3lzEJjqwaRC9buMUgtomcrLe5Nd0+fk1h0LLA+ixUF5OW7AhHuQ7Es1WcQJZmZsz2XA== - dependencies: - "@babel/types" "^7.17.0" - "@babel/helper-simple-access@^7.20.2": version "7.20.2" resolved "https://registry.yarnpkg.com/@babel/helper-simple-access/-/helper-simple-access-7.20.2.tgz#0ab452687fe0c2cfb1e2b9e0015de07fc2d62dd9" @@ -235,13 +149,6 @@ dependencies: "@babel/types" "^7.20.2" -"@babel/helper-split-export-declaration@^7.16.7": - version "7.16.7" - resolved "https://registry.yarnpkg.com/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.16.7.tgz#0b648c0c42da9d3920d85ad585f2778620b8726b" - integrity sha512-xbWoy/PFoxSWazIToT9Sif+jJTlrMcndIsaOKvTA6u7QEo7ilkRZpjew18/W3c7nm8fXdUDXh02VXTbZ0pGDNw== - dependencies: - "@babel/types" "^7.16.7" - "@babel/helper-split-export-declaration@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.18.6.tgz#7367949bc75b20c6d5a5d4a97bba2824ae8ef075" @@ -249,40 +156,38 @@ dependencies: "@babel/types" "^7.18.6" +"@babel/helper-split-export-declaration@^7.22.6": + version "7.22.6" + resolved "https://registry.yarnpkg.com/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.22.6.tgz#322c61b7310c0997fe4c323955667f18fcefb91c" + integrity sha512-AsUnxuLhRYsisFiaJwvp1QF+I3KjD5FOxut14q/GzovUe6orHLesW2C7d754kRm53h5gqrz6sFl6sxc4BVtE/g== + dependencies: + "@babel/types" "^7.22.5" + "@babel/helper-string-parser@^7.19.4": version "7.19.4" resolved "https://registry.yarnpkg.com/@babel/helper-string-parser/-/helper-string-parser-7.19.4.tgz#38d3acb654b4701a9b77fb0615a96f775c3a9e63" integrity sha512-nHtDoQcuqFmwYNYPz3Rah5ph2p8PFeFCsZk9A/48dPc/rGocJ5J3hAAZ7pb76VWX3fZKu+uEr/FhH5jLx7umrw== -"@babel/helper-validator-identifier@^7.16.7": - version "7.16.7" - resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.16.7.tgz#e8c602438c4a8195751243da9031d1607d247cad" - integrity sha512-hsEnFemeiW4D08A5gUAZxLBTXpZ39P+a+DGDsHw1yxqyQ/jzFEnxf5uTEGp+3bzAbNOxU1paTgYS4ECU/IgfDw== +"@babel/helper-string-parser@^7.23.4": + version "7.23.4" + resolved "https://registry.yarnpkg.com/@babel/helper-string-parser/-/helper-string-parser-7.23.4.tgz#9478c707febcbbe1ddb38a3d91a2e054ae622d83" + integrity sha512-803gmbQdqwdf4olxrX4AJyFBV/RTr3rSmOj0rKwesmzlfhYNDEs+/iOcznzpNWlJlIlTJC2QfPFcHB6DlzdVLQ== "@babel/helper-validator-identifier@^7.18.6", "@babel/helper-validator-identifier@^7.19.1": version "7.19.1" resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.19.1.tgz#7eea834cf32901ffdc1a7ee555e2f9c27e249ca2" integrity sha512-awrNfaMtnHUr653GgGEs++LlAvW6w+DcPrOliSMXWCKo597CwL5Acf/wWdNkf/tfEQE3mjkeD1YOVZOUV/od1w== -"@babel/helper-validator-option@^7.16.7": - version "7.16.7" - resolved "https://registry.yarnpkg.com/@babel/helper-validator-option/-/helper-validator-option-7.16.7.tgz#b203ce62ce5fe153899b617c08957de860de4d23" - integrity sha512-TRtenOuRUVo9oIQGPC5G9DgK4743cdxvtOw0weQNpZXaS16SCBi5MNjZF8vba3ETURjZpTbVn7Vvcf2eAwFozQ== +"@babel/helper-validator-identifier@^7.22.20": + version "7.22.20" + resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz#c4ae002c61d2879e724581d96665583dbc1dc0e0" + integrity sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A== "@babel/helper-validator-option@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/helper-validator-option/-/helper-validator-option-7.18.6.tgz#bf0d2b5a509b1f336099e4ff36e1a63aa5db4db8" integrity sha512-XO7gESt5ouv/LRJdrVjkShckw6STTaB7l9BrpBaAHDeF5YZT+01PCwmR0SJHnkW6i8OwW/EVWRShfi4j2x+KQw== -"@babel/helpers@^7.17.9": - version "7.17.9" - resolved "https://registry.yarnpkg.com/@babel/helpers/-/helpers-7.17.9.tgz#b2af120821bfbe44f9907b1826e168e819375a1a" - integrity sha512-cPCt915ShDWUEzEp3+UNRktO2n6v49l5RSnG9M5pS24hA+2FAc5si+Pn1i4VVbQQ+jh+bIZhPFQOJOzbrOYY1Q== - dependencies: - "@babel/template" "^7.16.7" - "@babel/traverse" "^7.17.9" - "@babel/types" "^7.17.0" - "@babel/helpers@^7.20.7": version "7.20.13" resolved "https://registry.yarnpkg.com/@babel/helpers/-/helpers-7.20.13.tgz#e3cb731fb70dc5337134cadc24cbbad31cc87ad2" @@ -292,15 +197,6 @@ "@babel/traverse" "^7.20.13" "@babel/types" "^7.20.7" -"@babel/highlight@^7.10.4", "@babel/highlight@^7.16.7": - version "7.17.9" - resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.17.9.tgz#61b2ee7f32ea0454612def4fccdae0de232b73e3" - integrity sha512-J9PfEKCbFIv2X5bjTMiZu6Vf341N05QIY+d6FvVKynkG1S7G0j3I0QoRtWIrXhZ+/Nlb5Q0MzqL7TokEJ5BNHg== - dependencies: - "@babel/helper-validator-identifier" "^7.16.7" - chalk "^2.0.0" - js-tokens "^4.0.0" - "@babel/highlight@^7.18.6": version "7.18.6" resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.18.6.tgz#81158601e93e2563795adcbfbdf5d64be3f2ecdf" @@ -310,16 +206,25 @@ chalk "^2.0.0" js-tokens "^4.0.0" -"@babel/parser@^7.1.0", "@babel/parser@^7.14.7", "@babel/parser@^7.16.7", "@babel/parser@^7.17.10": - version "7.17.10" - resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.17.10.tgz#873b16db82a8909e0fbd7f115772f4b739f6ce78" - integrity sha512-n2Q6i+fnJqzOaq2VkdXxy2TCPCWQZHiCo0XqmrCvDWcZQKRyZzYi4Z0yxlBuN0w+r2ZHmre+Q087DSrw3pbJDQ== +"@babel/highlight@^7.23.4": + version "7.23.4" + resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.23.4.tgz#edaadf4d8232e1a961432db785091207ead0621b" + integrity sha512-acGdbYSfp2WheJoJm/EBBBLh/ID8KDc64ISZ9DYtBmC8/Q204PZJLHyzeB5qMzJ5trcOkybd78M4x2KWsUq++A== + dependencies: + "@babel/helper-validator-identifier" "^7.22.20" + chalk "^2.4.2" + js-tokens "^4.0.0" -"@babel/parser@^7.20.13", "@babel/parser@^7.20.7": +"@babel/parser@^7.1.0", "@babel/parser@^7.14.7", "@babel/parser@^7.20.7": version "7.20.15" resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.20.15.tgz#eec9f36d8eaf0948bb88c87a46784b5ee9fd0c89" integrity sha512-DI4a1oZuf8wC+oAJA9RW6ga3Zbe8RZFt7kD9i4qAspz3I/yHet1VvC3DiSy/fsUvv5pvJuNPh0LPOdCcqinDPg== +"@babel/parser@^7.22.15", "@babel/parser@^7.23.6": + version "7.23.6" + resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.23.6.tgz#ba1c9e512bda72a47e285ae42aff9d2a635a9e3b" + integrity sha512-Z2uID7YJ7oNvAI20O9X0bblw7Qqs8Q2hFy0R9tAfnfLkp5MW0UH9eUvnDSnFwKZ0AvgS1ucqR4KzvVHgnke1VQ== + "@babel/plugin-syntax-async-generators@^7.8.4": version "7.8.4" resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz#a983fb1aeb2ec3f6ed042a210f640e90e786fe0d" @@ -418,16 +323,14 @@ dependencies: "@babel/helper-plugin-utils" "^7.19.0" -"@babel/template@^7.16.7", "@babel/template@^7.3.3": - version "7.16.7" - resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.16.7.tgz#8d126c8701fde4d66b264b3eba3d96f07666d155" - integrity sha512-I8j/x8kHUrbYRTUxXrrMbfCa7jxkE7tZre39x3kjr9hvI82cK1FfqLygotcWN5kdPGWcLdWMHpSBavse5tWw3w== +"@babel/runtime@^7.13.8": + version "7.20.13" + resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.20.13.tgz#7055ab8a7cff2b8f6058bf6ae45ff84ad2aded4b" + integrity sha512-gt3PKXs0DBoL9xCvOIIZ2NEqAGZqHjAnmVbfQtB620V0uReIQutpel14KcneZuer7UioY8ALKZ7iocavvzTNFA== dependencies: - "@babel/code-frame" "^7.16.7" - "@babel/parser" "^7.16.7" - "@babel/types" "^7.16.7" + regenerator-runtime "^0.13.11" -"@babel/template@^7.18.10", "@babel/template@^7.20.7": +"@babel/template@^7.20.7", "@babel/template@^7.3.3": version "7.20.7" resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.20.7.tgz#a15090c2839a83b02aa996c0b4994005841fd5a8" integrity sha512-8SegXApWe6VoNw0r9JHpSteLKTpTiLZ4rMlGIm9JQ18KiCtyQiAMEazujAHrUS5flrcqYZa75ukev3P6QmUwUw== @@ -436,47 +339,32 @@ "@babel/parser" "^7.20.7" "@babel/types" "^7.20.7" -"@babel/traverse@^7.17.10", "@babel/traverse@^7.17.3", "@babel/traverse@^7.17.9": - version "7.17.10" - resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.17.10.tgz#1ee1a5ac39f4eac844e6cf855b35520e5eb6f8b5" - integrity sha512-VmbrTHQteIdUUQNTb+zE12SHS/xQVIShmBPhlNP12hD5poF2pbITW1Z4172d03HegaQWhLffdkRJYtAzp0AGcw== - dependencies: - "@babel/code-frame" "^7.16.7" - "@babel/generator" "^7.17.10" - "@babel/helper-environment-visitor" "^7.16.7" - "@babel/helper-function-name" "^7.17.9" - "@babel/helper-hoist-variables" "^7.16.7" - "@babel/helper-split-export-declaration" "^7.16.7" - "@babel/parser" "^7.17.10" - "@babel/types" "^7.17.10" - debug "^4.1.0" - globals "^11.1.0" - -"@babel/traverse@^7.20.10", "@babel/traverse@^7.20.12", "@babel/traverse@^7.20.13", "@babel/traverse@^7.7.2": - version "7.20.13" - resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.20.13.tgz#817c1ba13d11accca89478bd5481b2d168d07473" - integrity sha512-kMJXfF0T6DIS9E8cgdLCSAL+cuCK+YEZHWiLK0SXpTo8YRj5lpJu3CDNKiIBCne4m9hhTIqUg6SYTAI39tAiVQ== - dependencies: - "@babel/code-frame" "^7.18.6" - "@babel/generator" "^7.20.7" - "@babel/helper-environment-visitor" "^7.18.9" - "@babel/helper-function-name" "^7.19.0" - "@babel/helper-hoist-variables" "^7.18.6" - "@babel/helper-split-export-declaration" "^7.18.6" - "@babel/parser" "^7.20.13" - "@babel/types" "^7.20.7" - debug "^4.1.0" +"@babel/template@^7.22.15": + version "7.22.15" + resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.22.15.tgz#09576efc3830f0430f4548ef971dde1350ef2f38" + integrity sha512-QPErUVm4uyJa60rkI73qneDacvdvzxshT3kksGqlGWYdOTIUOwJ7RDUL8sGqslY1uXWSL6xMFKEXDS3ox2uF0w== + dependencies: + "@babel/code-frame" "^7.22.13" + "@babel/parser" "^7.22.15" + "@babel/types" "^7.22.15" + +"@babel/traverse@^7.20.10", "@babel/traverse@^7.20.12", "@babel/traverse@^7.20.13": + version "7.23.7" + resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.23.7.tgz#9a7bf285c928cb99b5ead19c3b1ce5b310c9c305" + integrity sha512-tY3mM8rH9jM0YHFGyfC0/xf+SB5eKUu7HPj7/k3fpi9dAlsMc5YbQvDi0Sh2QTPXqMhyaAtzAr807TIyfQrmyg== + dependencies: + "@babel/code-frame" "^7.23.5" + "@babel/generator" "^7.23.6" + "@babel/helper-environment-visitor" "^7.22.20" + "@babel/helper-function-name" "^7.23.0" + "@babel/helper-hoist-variables" "^7.22.5" + "@babel/helper-split-export-declaration" "^7.22.6" + "@babel/parser" "^7.23.6" + "@babel/types" "^7.23.6" + debug "^4.3.1" globals "^11.1.0" -"@babel/types@^7.0.0", "@babel/types@^7.16.7", "@babel/types@^7.17.0", "@babel/types@^7.17.10", "@babel/types@^7.3.0", "@babel/types@^7.3.3": - version "7.17.10" - resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.17.10.tgz#d35d7b4467e439fcf06d195f8100e0fea7fc82c4" - integrity sha512-9O26jG0mBYfGkUYCYZRnBwbVLd1UZOICEr2Em6InB6jVfsAv1GKgwXHmrSg+WFWDmeKTA6vyTZiN8tCSM5Oo3A== - dependencies: - "@babel/helper-validator-identifier" "^7.16.7" - to-fast-properties "^2.0.0" - -"@babel/types@^7.18.6", "@babel/types@^7.19.0", "@babel/types@^7.20.2", "@babel/types@^7.20.7": +"@babel/types@^7.0.0", "@babel/types@^7.18.6", "@babel/types@^7.20.2", "@babel/types@^7.20.7", "@babel/types@^7.3.0", "@babel/types@^7.3.3": version "7.20.7" resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.20.7.tgz#54ec75e252318423fc07fb644dc6a58a64c09b7f" integrity sha512-69OnhBxSSgK0OzTJai4kyPDiKTIe3j+ctaHdIGVbRahTLAT7L3R9oeXHC2aVSuGYt3cVnoAMDmOCgJ2yaiLMvg== @@ -485,6 +373,15 @@ "@babel/helper-validator-identifier" "^7.19.1" to-fast-properties "^2.0.0" +"@babel/types@^7.22.15", "@babel/types@^7.22.5", "@babel/types@^7.23.0", "@babel/types@^7.23.6": + version "7.23.6" + resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.23.6.tgz#be33fdb151e1f5a56877d704492c240fc71c7ccd" + integrity sha512-+uarb83brBzPKN38NX1MkB6vb6+mwvR6amUulqAE7ccQw1pEl+bCia9TbdG1lsnFP7lZySvUn37CHyXQdfTwzg== + dependencies: + "@babel/helper-string-parser" "^7.23.4" + "@babel/helper-validator-identifier" "^7.22.20" + to-fast-properties "^2.0.0" + "@bcoe/v8-coverage@^0.2.3": version "0.2.3" resolved "https://registry.yarnpkg.com/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz#75a2e8b51cb758a7553d6804a5932d7aace75c39" @@ -495,45 +392,292 @@ resolved "https://registry.yarnpkg.com/@colors/colors/-/colors-1.5.0.tgz#bb504579c1cae923e6576a4f5da43d25f97bdbd9" integrity sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ== -"@discoveryjs/json-ext@^0.5.0": - version "0.5.7" - resolved "https://registry.yarnpkg.com/@discoveryjs/json-ext/-/json-ext-0.5.7.tgz#1d572bfbbe14b7704e0ba0f39b74815b84870d70" - integrity sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw== +"@commitlint/cli@17.7.1": + version "17.7.1" + resolved "https://registry.yarnpkg.com/@commitlint/cli/-/cli-17.7.1.tgz#f3ab35bd38d82fcd4ab03ec5a1e9db26d57fe1b0" + integrity sha512-BCm/AT06SNCQtvFv921iNhudOHuY16LswT0R3OeolVGLk8oP+Rk9TfQfgjH7QPMjhvp76bNqGFEcpKojxUNW1g== + dependencies: + "@commitlint/format" "^17.4.4" + "@commitlint/lint" "^17.7.0" + "@commitlint/load" "^17.7.1" + "@commitlint/read" "^17.5.1" + "@commitlint/types" "^17.4.4" + execa "^5.0.0" + lodash.isfunction "^3.0.9" + resolve-from "5.0.0" + resolve-global "1.0.0" + yargs "^17.0.0" + +"@commitlint/config-conventional@17.7.0": + version "17.7.0" + resolved "https://registry.yarnpkg.com/@commitlint/config-conventional/-/config-conventional-17.7.0.tgz#1bbf2bce7851db63c1a8aa8d924277ad4938247e" + integrity sha512-iicqh2o6et+9kWaqsQiEYZzfLbtoWv9uZl8kbI8EGfnc0HeGafQBF7AJ0ylN9D/2kj6txltsdyQs8+2fTMwWEw== + dependencies: + conventional-changelog-conventionalcommits "^6.1.0" + +"@commitlint/config-validator@^17.4.4": + version "17.4.4" + resolved "https://registry.yarnpkg.com/@commitlint/config-validator/-/config-validator-17.4.4.tgz#d0742705719559a101d2ee49c0c514044af6d64d" + integrity sha512-bi0+TstqMiqoBAQDvdEP4AFh0GaKyLFlPPEObgI29utoKEYoPQTvF0EYqIwYYLEoJYhj5GfMIhPHJkTJhagfeg== + dependencies: + "@commitlint/types" "^17.4.4" + ajv "^8.11.0" + +"@commitlint/config-validator@^17.6.7": + version "17.6.7" + resolved "https://registry.yarnpkg.com/@commitlint/config-validator/-/config-validator-17.6.7.tgz#c664d42a1ecf5040a3bb0843845150f55734df41" + integrity sha512-vJSncmnzwMvpr3lIcm0I8YVVDJTzyjy7NZAeXbTXy+MPUdAr9pKyyg7Tx/ebOQ9kqzE6O9WT6jg2164br5UdsQ== + dependencies: + "@commitlint/types" "^17.4.4" + ajv "^8.11.0" + +"@commitlint/ensure@^17.6.7": + version "17.6.7" + resolved "https://registry.yarnpkg.com/@commitlint/ensure/-/ensure-17.6.7.tgz#77a77a0c05e6a1c34589f59e82e6cb937101fc4b" + integrity sha512-mfDJOd1/O/eIb/h4qwXzUxkmskXDL9vNPnZ4AKYKiZALz4vHzwMxBSYtyL2mUIDeU9DRSpEUins8SeKtFkYHSw== + dependencies: + "@commitlint/types" "^17.4.4" + lodash.camelcase "^4.3.0" + lodash.kebabcase "^4.1.1" + lodash.snakecase "^4.1.1" + lodash.startcase "^4.4.0" + lodash.upperfirst "^4.3.1" + +"@commitlint/execute-rule@^17.4.0": + version "17.4.0" + resolved "https://registry.yarnpkg.com/@commitlint/execute-rule/-/execute-rule-17.4.0.tgz#4518e77958893d0a5835babe65bf87e2638f6939" + integrity sha512-LIgYXuCSO5Gvtc0t9bebAMSwd68ewzmqLypqI2Kke1rqOqqDbMpYcYfoPfFlv9eyLIh4jocHWwCK5FS7z9icUA== + +"@commitlint/format@^17.4.4": + version "17.4.4" + resolved "https://registry.yarnpkg.com/@commitlint/format/-/format-17.4.4.tgz#0f6e1b4d7a301c7b1dfd4b6334edd97fc050b9f5" + integrity sha512-+IS7vpC4Gd/x+uyQPTAt3hXs5NxnkqAZ3aqrHd5Bx/R9skyCAWusNlNbw3InDbAK6j166D9asQM8fnmYIa+CXQ== + dependencies: + "@commitlint/types" "^17.4.4" + chalk "^4.1.0" -"@eslint/eslintrc@^0.4.3": - version "0.4.3" - resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-0.4.3.tgz#9e42981ef035beb3dd49add17acb96e8ff6f394c" - integrity sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw== +"@commitlint/is-ignored@^17.7.0": + version "17.7.0" + resolved "https://registry.yarnpkg.com/@commitlint/is-ignored/-/is-ignored-17.7.0.tgz#df9b284420bdb1aed5fdb2be44f4e98cc4826014" + integrity sha512-043rA7m45tyEfW7Zv2vZHF++176MLHH9h70fnPoYlB1slKBeKl8BwNIlnPg4xBdRBVNPaCqvXxWswx2GR4c9Hw== + dependencies: + "@commitlint/types" "^17.4.4" + semver "7.5.4" + +"@commitlint/lint@^17.7.0": + version "17.7.0" + resolved "https://registry.yarnpkg.com/@commitlint/lint/-/lint-17.7.0.tgz#33f831298dc43679e4de6b088aea63d1f884c7e7" + integrity sha512-TCQihm7/uszA5z1Ux1vw+Nf3yHTgicus/+9HiUQk+kRSQawByxZNESeQoX9ujfVd3r4Sa+3fn0JQAguG4xvvbA== + dependencies: + "@commitlint/is-ignored" "^17.7.0" + "@commitlint/parse" "^17.7.0" + "@commitlint/rules" "^17.7.0" + "@commitlint/types" "^17.4.4" + +"@commitlint/load@>6.1.1": + version "17.4.4" + resolved "https://registry.yarnpkg.com/@commitlint/load/-/load-17.4.4.tgz#13fcb553572f265339801cde6dd10ee5eea07f5e" + integrity sha512-z6uFIQ7wfKX5FGBe1AkOF4l/ShOQsaa1ml/nLMkbW7R/xF8galGS7Zh0yHvzVp/srtfS0brC+0bUfQfmpMPFVQ== + dependencies: + "@commitlint/config-validator" "^17.4.4" + "@commitlint/execute-rule" "^17.4.0" + "@commitlint/resolve-extends" "^17.4.4" + "@commitlint/types" "^17.4.4" + "@types/node" "*" + chalk "^4.1.0" + cosmiconfig "^8.0.0" + cosmiconfig-typescript-loader "^4.0.0" + lodash.isplainobject "^4.0.6" + lodash.merge "^4.6.2" + lodash.uniq "^4.5.0" + resolve-from "^5.0.0" + ts-node "^10.8.1" + typescript "^4.6.4" + +"@commitlint/load@^17.7.1": + version "17.7.1" + resolved "https://registry.yarnpkg.com/@commitlint/load/-/load-17.7.1.tgz#0723b11723a20043a304a74960602dead89b5cdd" + integrity sha512-S/QSOjE1ztdogYj61p6n3UbkUvweR17FQ0zDbNtoTLc+Hz7vvfS7ehoTMQ27hPSjVBpp7SzEcOQu081RLjKHJQ== + dependencies: + "@commitlint/config-validator" "^17.6.7" + "@commitlint/execute-rule" "^17.4.0" + "@commitlint/resolve-extends" "^17.6.7" + "@commitlint/types" "^17.4.4" + "@types/node" "20.4.7" + chalk "^4.1.0" + cosmiconfig "^8.0.0" + cosmiconfig-typescript-loader "^4.0.0" + lodash.isplainobject "^4.0.6" + lodash.merge "^4.6.2" + lodash.uniq "^4.5.0" + resolve-from "^5.0.0" + ts-node "^10.8.1" + typescript "^4.6.4 || ^5.0.0" + +"@commitlint/message@^17.4.2": + version "17.4.2" + resolved "https://registry.yarnpkg.com/@commitlint/message/-/message-17.4.2.tgz#f4753a79701ad6db6db21f69076e34de6580e22c" + integrity sha512-3XMNbzB+3bhKA1hSAWPCQA3lNxR4zaeQAQcHj0Hx5sVdO6ryXtgUBGGv+1ZCLMgAPRixuc6en+iNAzZ4NzAa8Q== + +"@commitlint/parse@^17.7.0": + version "17.7.0" + resolved "https://registry.yarnpkg.com/@commitlint/parse/-/parse-17.7.0.tgz#aacb2d189e50ab8454154b1df150aaf20478ae47" + integrity sha512-dIvFNUMCUHqq5Abv80mIEjLVfw8QNuA4DS7OWip4pcK/3h5wggmjVnlwGCDvDChkw2TjK1K6O+tAEV78oxjxag== + dependencies: + "@commitlint/types" "^17.4.4" + conventional-changelog-angular "^6.0.0" + conventional-commits-parser "^4.0.0" + +"@commitlint/read@^17.5.1": + version "17.5.1" + resolved "https://registry.yarnpkg.com/@commitlint/read/-/read-17.5.1.tgz#fec903b766e2c41e3cefa80630040fcaba4f786c" + integrity sha512-7IhfvEvB//p9aYW09YVclHbdf1u7g7QhxeYW9ZHSO8Huzp8Rz7m05aCO1mFG7G8M+7yfFnXB5xOmG18brqQIBg== + dependencies: + "@commitlint/top-level" "^17.4.0" + "@commitlint/types" "^17.4.4" + fs-extra "^11.0.0" + git-raw-commits "^2.0.11" + minimist "^1.2.6" + +"@commitlint/resolve-extends@^17.4.4": + version "17.4.4" + resolved "https://registry.yarnpkg.com/@commitlint/resolve-extends/-/resolve-extends-17.4.4.tgz#8f931467dea8c43b9fe38373e303f7c220de6fdc" + integrity sha512-znXr1S0Rr8adInptHw0JeLgumS11lWbk5xAWFVno+HUFVN45875kUtqjrI6AppmD3JI+4s0uZlqqlkepjJd99A== + dependencies: + "@commitlint/config-validator" "^17.4.4" + "@commitlint/types" "^17.4.4" + import-fresh "^3.0.0" + lodash.mergewith "^4.6.2" + resolve-from "^5.0.0" + resolve-global "^1.0.0" + +"@commitlint/resolve-extends@^17.6.7": + version "17.6.7" + resolved "https://registry.yarnpkg.com/@commitlint/resolve-extends/-/resolve-extends-17.6.7.tgz#9c53a4601c96ab2dd20b90fb35c988639307735d" + integrity sha512-PfeoAwLHtbOaC9bGn/FADN156CqkFz6ZKiVDMjuC2N5N0740Ke56rKU7Wxdwya8R8xzLK9vZzHgNbuGhaOVKIg== + dependencies: + "@commitlint/config-validator" "^17.6.7" + "@commitlint/types" "^17.4.4" + import-fresh "^3.0.0" + lodash.mergewith "^4.6.2" + resolve-from "^5.0.0" + resolve-global "^1.0.0" + +"@commitlint/rules@^17.7.0": + version "17.7.0" + resolved "https://registry.yarnpkg.com/@commitlint/rules/-/rules-17.7.0.tgz#b97a4933c5cba11a659a19ee467f6f000f31533e" + integrity sha512-J3qTh0+ilUE5folSaoK91ByOb8XeQjiGcdIdiB/8UT1/Rd1itKo0ju/eQVGyFzgTMYt8HrDJnGTmNWwcMR1rmA== + dependencies: + "@commitlint/ensure" "^17.6.7" + "@commitlint/message" "^17.4.2" + "@commitlint/to-lines" "^17.4.0" + "@commitlint/types" "^17.4.4" + execa "^5.0.0" + +"@commitlint/to-lines@^17.4.0": + version "17.4.0" + resolved "https://registry.yarnpkg.com/@commitlint/to-lines/-/to-lines-17.4.0.tgz#9bd02e911e7d4eab3fb4a50376c4c6d331e10d8d" + integrity sha512-LcIy/6ZZolsfwDUWfN1mJ+co09soSuNASfKEU5sCmgFCvX5iHwRYLiIuoqXzOVDYOy7E7IcHilr/KS0e5T+0Hg== + +"@commitlint/top-level@^17.4.0": + version "17.4.0" + resolved "https://registry.yarnpkg.com/@commitlint/top-level/-/top-level-17.4.0.tgz#540cac8290044cf846fbdd99f5cc51e8ac5f27d6" + integrity sha512-/1loE/g+dTTQgHnjoCy0AexKAEFyHsR2zRB4NWrZ6lZSMIxAhBJnmCqwao7b4H8888PsfoTBCLBYIw8vGnej8g== + dependencies: + find-up "^5.0.0" + +"@commitlint/types@^17.4.4": + version "17.4.4" + resolved "https://registry.yarnpkg.com/@commitlint/types/-/types-17.4.4.tgz#1416df936e9aad0d6a7bbc979ecc31e55dade662" + integrity sha512-amRN8tRLYOsxRr6mTnGGGvB5EmW/4DDjLMgiwK3CCVEmN6Sr/6xePGEpWaspKkckILuUORCwe6VfDBw6uj4axQ== + dependencies: + chalk "^4.1.0" + +"@cspotcode/source-map-support@^0.8.0": + version "0.8.1" + resolved "https://registry.yarnpkg.com/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz#00629c35a688e05a88b1cda684fb9d5e73f000a1" + integrity sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw== + dependencies: + "@jridgewell/trace-mapping" "0.3.9" + +"@eslint-community/eslint-utils@^4.2.0", "@eslint-community/eslint-utils@^4.4.0": + version "4.4.0" + resolved "https://registry.yarnpkg.com/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz#a23514e8fb9af1269d5f7788aa556798d61c6b59" + integrity sha512-1/sA4dwrzBAyeUoQ6oxahHKmrZvsnLCg4RfxW3ZFGGmQkSNQPFNLV9CUEFQP1x9EYXHTo5p6xdhZM1Ne9p/AfA== + dependencies: + eslint-visitor-keys "^3.3.0" + +"@eslint-community/regexpp@^4.5.1": + version "4.10.0" + resolved "https://registry.yarnpkg.com/@eslint-community/regexpp/-/regexpp-4.10.0.tgz#548f6de556857c8bb73bbee70c35dc82a2e74d63" + integrity sha512-Cu96Sd2By9mCNTx2iyKOmq10v22jUVQv0lQnlGNy16oE9589yE+QADPbrMGCkA51cKZSg3Pu/aTJVTGfL/qjUA== + +"@eslint-community/regexpp@^4.6.1": + version "4.8.1" + resolved "https://registry.yarnpkg.com/@eslint-community/regexpp/-/regexpp-4.8.1.tgz#8c4bb756cc2aa7eaf13cfa5e69c83afb3260c20c" + integrity sha512-PWiOzLIUAjN/w5K17PoF4n6sKBw0gqLHPhywmYHP4t1VFQQVYeb1yWsJwnMVEMl3tUHME7X/SJPZLmtG7XBDxQ== + +"@eslint/eslintrc@^2.1.2": + version "2.1.2" + resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-2.1.2.tgz#c6936b4b328c64496692f76944e755738be62396" + integrity sha512-+wvgpDsrB1YqAMdEUCcnTlpfVBH7Vqn6A/NT3D8WVXFIaKMlErPIZT3oCIAVCOtarRpMtelZLqJeU3t7WY6X6g== dependencies: ajv "^6.12.4" - debug "^4.1.1" - espree "^7.3.0" - globals "^13.9.0" - ignore "^4.0.6" + debug "^4.3.2" + espree "^9.6.0" + globals "^13.19.0" + ignore "^5.2.0" import-fresh "^3.2.1" - js-yaml "^3.13.1" - minimatch "^3.0.4" + js-yaml "^4.1.0" + minimatch "^3.1.2" strip-json-comments "^3.1.1" +"@eslint/js@8.49.0": + version "8.49.0" + resolved "https://registry.yarnpkg.com/@eslint/js/-/js-8.49.0.tgz#86f79756004a97fa4df866835093f1df3d03c333" + integrity sha512-1S8uAY/MTJqVx0SC4epBq+N2yhuwtNwLbJYNZyhL2pO1ZVKn5HFXav5T41Ryzy9K9V7ZId2JB2oy/W4aCd9/2w== + +"@ethereumjs/rlp@5.0.0": + version "5.0.0" + resolved "https://registry.yarnpkg.com/@ethereumjs/rlp/-/rlp-5.0.0.tgz#dd81b32b2237bc32fb1b54534f8ff246a6c89d9b" + integrity sha512-WuS1l7GJmB0n0HsXLozCoEFc9IwYgf3l0gCkKVYgR67puVF1O4OpEaN0hWmm1c+iHUHFCKt1hJrvy5toLg+6ag== + "@gar/promisify@^1.1.3": version "1.1.3" resolved "https://registry.yarnpkg.com/@gar/promisify/-/promisify-1.1.3.tgz#555193ab2e3bb3b6adc3d551c9c030d9e860daf6" integrity sha512-k2Ty1JcVojjJFwrg/ThKi2ujJ7XNLYaFGNB/bWT9wGR+oSMJHMa5w+CUq6p/pVrKeNNgA7pCqEcjSnHVoqJQFw== -"@humanwhocodes/config-array@^0.5.0": - version "0.5.0" - resolved "https://registry.yarnpkg.com/@humanwhocodes/config-array/-/config-array-0.5.0.tgz#1407967d4c6eecd7388f83acf1eaf4d0c6e58ef9" - integrity sha512-FagtKFz74XrTl7y6HCzQpwDfXP0yhxe9lHLD1UZxjvZIcbyRz8zTFF/yYNfSfzU414eDwZ1SrO0Qvtyf+wFMQg== +"@humanwhocodes/config-array@^0.11.11": + version "0.11.11" + resolved "https://registry.yarnpkg.com/@humanwhocodes/config-array/-/config-array-0.11.11.tgz#88a04c570dbbc7dd943e4712429c3df09bc32844" + integrity sha512-N2brEuAadi0CcdeMXUkhbZB84eskAc8MEX1By6qEchoVywSgXPIjou4rYsl0V3Hj0ZnuGycGCjdNgockbzeWNA== dependencies: - "@humanwhocodes/object-schema" "^1.2.0" + "@humanwhocodes/object-schema" "^1.2.1" debug "^4.1.1" - minimatch "^3.0.4" + minimatch "^3.0.5" + +"@humanwhocodes/module-importer@^1.0.1": + version "1.0.1" + resolved "https://registry.yarnpkg.com/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz#af5b2691a22b44be847b0ca81641c5fb6ad0172c" + integrity sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA== -"@humanwhocodes/object-schema@^1.2.0": +"@humanwhocodes/object-schema@^1.2.1": version "1.2.1" resolved "https://registry.yarnpkg.com/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz#b520529ec21d8e5945a1851dfd1c32e94e39ff45" integrity sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA== +"@isaacs/cliui@^8.0.2": + version "8.0.2" + resolved "https://registry.yarnpkg.com/@isaacs/cliui/-/cliui-8.0.2.tgz#b37667b7bc181c168782259bab42474fbf52b550" + integrity sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA== + dependencies: + string-width "^5.1.2" + string-width-cjs "npm:string-width@^4.2.0" + strip-ansi "^7.0.1" + strip-ansi-cjs "npm:strip-ansi@^6.0.1" + wrap-ansi "^8.1.0" + wrap-ansi-cjs "npm:wrap-ansi@^7.0.0" + "@isaacs/string-locale-compare@^1.1.0": version "1.1.0" resolved "https://registry.yarnpkg.com/@isaacs/string-locale-compare/-/string-locale-compare-1.1.0.tgz#291c227e93fd407a96ecd59879a35809120e432b" @@ -555,61 +699,61 @@ resolved "https://registry.yarnpkg.com/@istanbuljs/schema/-/schema-0.1.3.tgz#e45e384e4b8ec16bce2fd903af78450f6bf7ec98" integrity sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA== -"@jest/console@^29.4.3": - version "29.4.3" - resolved "https://registry.yarnpkg.com/@jest/console/-/console-29.4.3.tgz#1f25a99f7f860e4c46423b5b1038262466fadde1" - integrity sha512-W/o/34+wQuXlgqlPYTansOSiBnuxrTv61dEVkA6HNmpcgHLUjfaUbdqt6oVvOzaawwo9IdW9QOtMgQ1ScSZC4A== +"@jest/console@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/console/-/console-29.7.0.tgz#cd4822dbdb84529265c5a2bdb529a3c9cc950ffc" + integrity sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg== dependencies: - "@jest/types" "^29.4.3" + "@jest/types" "^29.6.3" "@types/node" "*" chalk "^4.0.0" - jest-message-util "^29.4.3" - jest-util "^29.4.3" + jest-message-util "^29.7.0" + jest-util "^29.7.0" slash "^3.0.0" -"@jest/core@^29.4.3": - version "29.4.3" - resolved "https://registry.yarnpkg.com/@jest/core/-/core-29.4.3.tgz#829dd65bffdb490de5b0f69e97de8e3b5eadd94b" - integrity sha512-56QvBq60fS4SPZCuM7T+7scNrkGIe7Mr6PVIXUpu48ouvRaWOFqRPV91eifvFM0ay2HmfswXiGf97NGUN5KofQ== +"@jest/core@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/core/-/core-29.7.0.tgz#b6cccc239f30ff36609658c5a5e2291757ce448f" + integrity sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg== dependencies: - "@jest/console" "^29.4.3" - "@jest/reporters" "^29.4.3" - "@jest/test-result" "^29.4.3" - "@jest/transform" "^29.4.3" - "@jest/types" "^29.4.3" + "@jest/console" "^29.7.0" + "@jest/reporters" "^29.7.0" + "@jest/test-result" "^29.7.0" + "@jest/transform" "^29.7.0" + "@jest/types" "^29.6.3" "@types/node" "*" ansi-escapes "^4.2.1" chalk "^4.0.0" ci-info "^3.2.0" exit "^0.1.2" graceful-fs "^4.2.9" - jest-changed-files "^29.4.3" - jest-config "^29.4.3" - jest-haste-map "^29.4.3" - jest-message-util "^29.4.3" - jest-regex-util "^29.4.3" - jest-resolve "^29.4.3" - jest-resolve-dependencies "^29.4.3" - jest-runner "^29.4.3" - jest-runtime "^29.4.3" - jest-snapshot "^29.4.3" - jest-util "^29.4.3" - jest-validate "^29.4.3" - jest-watcher "^29.4.3" + jest-changed-files "^29.7.0" + jest-config "^29.7.0" + jest-haste-map "^29.7.0" + jest-message-util "^29.7.0" + jest-regex-util "^29.6.3" + jest-resolve "^29.7.0" + jest-resolve-dependencies "^29.7.0" + jest-runner "^29.7.0" + jest-runtime "^29.7.0" + jest-snapshot "^29.7.0" + jest-util "^29.7.0" + jest-validate "^29.7.0" + jest-watcher "^29.7.0" micromatch "^4.0.4" - pretty-format "^29.4.3" + pretty-format "^29.7.0" slash "^3.0.0" strip-ansi "^6.0.0" -"@jest/environment@^29.4.3": - version "29.4.3" - resolved "https://registry.yarnpkg.com/@jest/environment/-/environment-29.4.3.tgz#9fe2f3169c3b33815dc4bd3960a064a83eba6548" - integrity sha512-dq5S6408IxIa+lr54zeqce+QgI+CJT4nmmA+1yzFgtcsGK8c/EyiUb9XQOgz3BMKrRDfKseeOaxj2eO8LlD3lA== +"@jest/environment@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/environment/-/environment-29.7.0.tgz#24d61f54ff1f786f3cd4073b4b94416383baf2a7" + integrity sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw== dependencies: - "@jest/fake-timers" "^29.4.3" - "@jest/types" "^29.4.3" + "@jest/fake-timers" "^29.7.0" + "@jest/types" "^29.6.3" "@types/node" "*" - jest-mock "^29.4.3" + jest-mock "^29.7.0" "@jest/expect-utils@^29.4.3": version "29.4.3" @@ -618,47 +762,54 @@ dependencies: jest-get-type "^29.4.3" -"@jest/expect@^29.4.3": - version "29.4.3" - resolved "https://registry.yarnpkg.com/@jest/expect/-/expect-29.4.3.tgz#d31a28492e45a6bcd0f204a81f783fe717045c6e" - integrity sha512-iktRU/YsxEtumI9zsPctYUk7ptpC+AVLLk1Ax3AsA4g1C+8OOnKDkIQBDHtD5hA/+VtgMd5AWI5gNlcAlt2vxQ== +"@jest/expect-utils@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/expect-utils/-/expect-utils-29.7.0.tgz#023efe5d26a8a70f21677d0a1afc0f0a44e3a1c6" + integrity sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA== dependencies: - expect "^29.4.3" - jest-snapshot "^29.4.3" + jest-get-type "^29.6.3" -"@jest/fake-timers@^29.4.3": - version "29.4.3" - resolved "https://registry.yarnpkg.com/@jest/fake-timers/-/fake-timers-29.4.3.tgz#31e982638c60fa657d310d4b9d24e023064027b0" - integrity sha512-4Hote2MGcCTWSD2gwl0dwbCpBRHhE6olYEuTj8FMowdg3oQWNKr2YuxenPQYZ7+PfqPY1k98wKDU4Z+Hvd4Tiw== +"@jest/expect@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/expect/-/expect-29.7.0.tgz#76a3edb0cb753b70dfbfe23283510d3d45432bf2" + integrity sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ== dependencies: - "@jest/types" "^29.4.3" + expect "^29.7.0" + jest-snapshot "^29.7.0" + +"@jest/fake-timers@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/fake-timers/-/fake-timers-29.7.0.tgz#fd91bf1fffb16d7d0d24a426ab1a47a49881a565" + integrity sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ== + dependencies: + "@jest/types" "^29.6.3" "@sinonjs/fake-timers" "^10.0.2" "@types/node" "*" - jest-message-util "^29.4.3" - jest-mock "^29.4.3" - jest-util "^29.4.3" + jest-message-util "^29.7.0" + jest-mock "^29.7.0" + jest-util "^29.7.0" -"@jest/globals@^29.4.3": - version "29.4.3" - resolved "https://registry.yarnpkg.com/@jest/globals/-/globals-29.4.3.tgz#63a2c4200d11bc6d46f12bbe25b07f771fce9279" - integrity sha512-8BQ/5EzfOLG7AaMcDh7yFCbfRLtsc+09E1RQmRBI4D6QQk4m6NSK/MXo+3bJrBN0yU8A2/VIcqhvsOLFmziioA== +"@jest/globals@29.7.0", "@jest/globals@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/globals/-/globals-29.7.0.tgz#8d9290f9ec47ff772607fa864ca1d5a2efae1d4d" + integrity sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ== dependencies: - "@jest/environment" "^29.4.3" - "@jest/expect" "^29.4.3" - "@jest/types" "^29.4.3" - jest-mock "^29.4.3" + "@jest/environment" "^29.7.0" + "@jest/expect" "^29.7.0" + "@jest/types" "^29.6.3" + jest-mock "^29.7.0" -"@jest/reporters@^29.4.3": - version "29.4.3" - resolved "https://registry.yarnpkg.com/@jest/reporters/-/reporters-29.4.3.tgz#0a68a0c0f20554760cc2e5443177a0018969e353" - integrity sha512-sr2I7BmOjJhyqj9ANC6CTLsL4emMoka7HkQpcoMRlhCbQJjz2zsRzw0BDPiPyEFDXAbxKgGFYuQZiSJ1Y6YoTg== +"@jest/reporters@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/reporters/-/reporters-29.7.0.tgz#04b262ecb3b8faa83b0b3d321623972393e8f4c7" + integrity sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg== dependencies: "@bcoe/v8-coverage" "^0.2.3" - "@jest/console" "^29.4.3" - "@jest/test-result" "^29.4.3" - "@jest/transform" "^29.4.3" - "@jest/types" "^29.4.3" - "@jridgewell/trace-mapping" "^0.3.15" + "@jest/console" "^29.7.0" + "@jest/test-result" "^29.7.0" + "@jest/transform" "^29.7.0" + "@jest/types" "^29.6.3" + "@jridgewell/trace-mapping" "^0.3.18" "@types/node" "*" chalk "^4.0.0" collect-v8-coverage "^1.0.0" @@ -666,13 +817,13 @@ glob "^7.1.3" graceful-fs "^4.2.9" istanbul-lib-coverage "^3.0.0" - istanbul-lib-instrument "^5.1.0" + istanbul-lib-instrument "^6.0.0" istanbul-lib-report "^3.0.0" istanbul-lib-source-maps "^4.0.0" istanbul-reports "^3.1.3" - jest-message-util "^29.4.3" - jest-util "^29.4.3" - jest-worker "^29.4.3" + jest-message-util "^29.7.0" + jest-util "^29.7.0" + jest-worker "^29.7.0" slash "^3.0.0" string-length "^4.0.1" strip-ansi "^6.0.0" @@ -685,51 +836,58 @@ dependencies: "@sinclair/typebox" "^0.25.16" -"@jest/source-map@^29.4.3": - version "29.4.3" - resolved "https://registry.yarnpkg.com/@jest/source-map/-/source-map-29.4.3.tgz#ff8d05cbfff875d4a791ab679b4333df47951d20" - integrity sha512-qyt/mb6rLyd9j1jUts4EQncvS6Yy3PM9HghnNv86QBlV+zdL2inCdK1tuVlL+J+lpiw2BI67qXOrX3UurBqQ1w== +"@jest/schemas@^29.6.3": + version "29.6.3" + resolved "https://registry.yarnpkg.com/@jest/schemas/-/schemas-29.6.3.tgz#430b5ce8a4e0044a7e3819663305a7b3091c8e03" + integrity sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA== dependencies: - "@jridgewell/trace-mapping" "^0.3.15" + "@sinclair/typebox" "^0.27.8" + +"@jest/source-map@^29.6.3": + version "29.6.3" + resolved "https://registry.yarnpkg.com/@jest/source-map/-/source-map-29.6.3.tgz#d90ba772095cf37a34a5eb9413f1b562a08554c4" + integrity sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw== + dependencies: + "@jridgewell/trace-mapping" "^0.3.18" callsites "^3.0.0" graceful-fs "^4.2.9" -"@jest/test-result@^29.4.3": - version "29.4.3" - resolved "https://registry.yarnpkg.com/@jest/test-result/-/test-result-29.4.3.tgz#e13d973d16c8c7cc0c597082d5f3b9e7f796ccb8" - integrity sha512-Oi4u9NfBolMq9MASPwuWTlC5WvmNRwI4S8YrQg5R5Gi47DYlBe3sh7ILTqi/LGrK1XUE4XY9KZcQJTH1WJCLLA== +"@jest/test-result@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/test-result/-/test-result-29.7.0.tgz#8db9a80aa1a097bb2262572686734baed9b1657c" + integrity sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA== dependencies: - "@jest/console" "^29.4.3" - "@jest/types" "^29.4.3" + "@jest/console" "^29.7.0" + "@jest/types" "^29.6.3" "@types/istanbul-lib-coverage" "^2.0.0" collect-v8-coverage "^1.0.0" -"@jest/test-sequencer@^29.4.3": - version "29.4.3" - resolved "https://registry.yarnpkg.com/@jest/test-sequencer/-/test-sequencer-29.4.3.tgz#0862e876a22993385a0f3e7ea1cc126f208a2898" - integrity sha512-yi/t2nES4GB4G0mjLc0RInCq/cNr9dNwJxcGg8sslajua5Kb4kmozAc+qPLzplhBgfw1vLItbjyHzUN92UXicw== +"@jest/test-sequencer@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/test-sequencer/-/test-sequencer-29.7.0.tgz#6cef977ce1d39834a3aea887a1726628a6f072ce" + integrity sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw== dependencies: - "@jest/test-result" "^29.4.3" + "@jest/test-result" "^29.7.0" graceful-fs "^4.2.9" - jest-haste-map "^29.4.3" + jest-haste-map "^29.7.0" slash "^3.0.0" -"@jest/transform@^29.4.3": - version "29.4.3" - resolved "https://registry.yarnpkg.com/@jest/transform/-/transform-29.4.3.tgz#f7d17eac9cb5bb2e1222ea199c7c7e0835e0c037" - integrity sha512-8u0+fBGWolDshsFgPQJESkDa72da/EVwvL+II0trN2DR66wMwiQ9/CihaGfHdlLGFzbBZwMykFtxuwFdZqlKwg== +"@jest/transform@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/transform/-/transform-29.7.0.tgz#df2dd9c346c7d7768b8a06639994640c642e284c" + integrity sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw== dependencies: "@babel/core" "^7.11.6" - "@jest/types" "^29.4.3" - "@jridgewell/trace-mapping" "^0.3.15" + "@jest/types" "^29.6.3" + "@jridgewell/trace-mapping" "^0.3.18" babel-plugin-istanbul "^6.1.1" chalk "^4.0.0" convert-source-map "^2.0.0" fast-json-stable-stringify "^2.1.0" graceful-fs "^4.2.9" - jest-haste-map "^29.4.3" - jest-regex-util "^29.4.3" - jest-util "^29.4.3" + jest-haste-map "^29.7.0" + jest-regex-util "^29.6.3" + jest-util "^29.7.0" micromatch "^4.0.4" pirates "^4.0.4" slash "^3.0.0" @@ -747,6 +905,18 @@ "@types/yargs" "^17.0.8" chalk "^4.0.0" +"@jest/types@^29.6.3": + version "29.6.3" + resolved "https://registry.yarnpkg.com/@jest/types/-/types-29.6.3.tgz#1131f8cf634e7e84c5e77bab12f052af585fba59" + integrity sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw== + dependencies: + "@jest/schemas" "^29.6.3" + "@types/istanbul-lib-coverage" "^2.0.0" + "@types/istanbul-reports" "^3.0.0" + "@types/node" "*" + "@types/yargs" "^17.0.8" + chalk "^4.0.0" + "@jridgewell/gen-mapping@^0.1.0": version "0.1.1" resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.1.1.tgz#e5d2e450306a9491e3bd77e323e38d7aff315996" @@ -769,12 +939,12 @@ resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz#2203b118c157721addfe69d47b70465463066d78" integrity sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w== -"@jridgewell/set-array@^1.0.0": - version "1.1.0" - resolved "https://registry.yarnpkg.com/@jridgewell/set-array/-/set-array-1.1.0.tgz#1179863356ac8fbea64a5a4bcde93a4871012c01" - integrity sha512-SfJxIxNVYLTsKwzB3MoOQ1yxf4w/E6MdkvTgrgAt1bfxjSrLUoHMKrDOykwN14q65waezZIdqDneUIPh4/sKxg== +"@jridgewell/resolve-uri@^3.1.0": + version "3.1.1" + resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz#c08679063f279615a3326583ba3a90d1d82cc721" + integrity sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA== -"@jridgewell/set-array@^1.0.1": +"@jridgewell/set-array@^1.0.0", "@jridgewell/set-array@^1.0.1": version "1.1.2" resolved "https://registry.yarnpkg.com/@jridgewell/set-array/-/set-array-1.1.2.tgz#7c6cf998d6d20b914c0a55a91ae928ff25965e72" integrity sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw== @@ -787,12 +957,33 @@ "@jridgewell/gen-mapping" "^0.3.0" "@jridgewell/trace-mapping" "^0.3.9" +"@jridgewell/source-map@^0.3.3": + version "0.3.5" + resolved "https://registry.yarnpkg.com/@jridgewell/source-map/-/source-map-0.3.5.tgz#a3bb4d5c6825aab0d281268f47f6ad5853431e91" + integrity sha512-UTYAUj/wviwdsMfzoSJspJxbkH5o1snzwX0//0ENX1u/55kkZZkcTZP6u9bwKGkv+dkk9at4m1Cpt0uY80kcpQ== + dependencies: + "@jridgewell/gen-mapping" "^0.3.0" + "@jridgewell/trace-mapping" "^0.3.9" + "@jridgewell/sourcemap-codec@1.4.14", "@jridgewell/sourcemap-codec@^1.4.10": version "1.4.14" resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz#add4c98d341472a289190b424efbdb096991bb24" integrity sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw== -"@jridgewell/trace-mapping@^0.3.12", "@jridgewell/trace-mapping@^0.3.15": +"@jridgewell/sourcemap-codec@^1.4.14": + version "1.4.15" + resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz#d7c6e6755c78567a951e04ab52ef0fd26de59f32" + integrity sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg== + +"@jridgewell/trace-mapping@0.3.9": + version "0.3.9" + resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz#6534fd5933a53ba7cbf3a17615e273a0d1273ff9" + integrity sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ== + dependencies: + "@jridgewell/resolve-uri" "^3.0.3" + "@jridgewell/sourcemap-codec" "^1.4.10" + +"@jridgewell/trace-mapping@^0.3.12", "@jridgewell/trace-mapping@^0.3.9": version "0.3.17" resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.17.tgz#793041277af9073b0951a7fe0f0d8c4c98c36985" integrity sha512-MCNzAp77qzKca9+W/+I0+sEpaUnZoeasnghNeVc41VZCEKaCH73Vq3BZZ/SzWIgrqE4H4ceI+p+b6C0mHf9T4g== @@ -800,28 +991,42 @@ "@jridgewell/resolve-uri" "3.1.0" "@jridgewell/sourcemap-codec" "1.4.14" -"@jridgewell/trace-mapping@^0.3.14", "@jridgewell/trace-mapping@^0.3.9": - version "0.3.15" - resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.15.tgz#aba35c48a38d3fd84b37e66c9c0423f9744f9774" - integrity sha512-oWZNOULl+UbhsgB51uuZzglikfIKSUBO/M9W2OfEjn7cmqoAiCgmv9lyACTUacZwBz0ITnJ2NqjU8Tx0DHL88g== +"@jridgewell/trace-mapping@^0.3.17", "@jridgewell/trace-mapping@^0.3.18": + version "0.3.21" + resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.21.tgz#5dc1df7b3dc4a6209e503a924e1ca56097a2bb15" + integrity sha512-SRfKmRe1KvYnxjEMtxEr+J4HIeMX5YBg/qhRHpxEIGjhX1rshcHlnFUE9K0GazhVKWM7B+nARSkV8LuvJdJ5/g== dependencies: - "@jridgewell/resolve-uri" "^3.0.3" - "@jridgewell/sourcemap-codec" "^1.4.10" + "@jridgewell/resolve-uri" "^3.1.0" + "@jridgewell/sourcemap-codec" "^1.4.14" -"@noble/hashes@1.1.2": - version "1.1.2" - resolved "https://registry.yarnpkg.com/@noble/hashes/-/hashes-1.1.2.tgz#e9e035b9b166ca0af657a7848eb2718f0f22f183" - integrity sha512-KYRCASVTv6aeUi1tsF8/vpyR7zpfs3FUzy2Jqm+MU+LmUKhQ0y2FpfwqkCcxSg2ua4GALJd8k2R76WxwZGbQpA== - -"@noble/hashes@^1.2.0": +"@noble/curves@1.2.0": version "1.2.0" - resolved "https://registry.yarnpkg.com/@noble/hashes/-/hashes-1.2.0.tgz#a3150eeb09cc7ab207ebf6d7b9ad311a9bdbed12" - integrity sha512-FZfhjEDbT5GRswV3C6uvLPHMiVD6lQBmpoX5+eSiPaMTXte/IKqI5dykDxzZB/WBeK/CDuQRBWarPdi3FNY2zQ== + resolved "https://registry.yarnpkg.com/@noble/curves/-/curves-1.2.0.tgz#92d7e12e4e49b23105a2555c6984d41733d65c35" + integrity sha512-oYclrNgRaM9SsBUBVbb8M6DTV7ZHRTKugureoYEncY5c65HOmRzvSiTE3y5CYaPYJA/GVkrhXEoF0M3Ya9PMnw== + dependencies: + "@noble/hashes" "1.3.2" + +"@noble/curves@~1.3.0": + version "1.3.0" + resolved "https://registry.yarnpkg.com/@noble/curves/-/curves-1.3.0.tgz#01be46da4fd195822dab821e72f71bf4aeec635e" + integrity sha512-t01iSXPuN+Eqzb4eBX0S5oubSqXbK/xXa1Ne18Hj8f9pStxztHCE2gfboSp/dZRLSqfuLpRK2nDXDK+W9puocA== + dependencies: + "@noble/hashes" "1.3.3" + +"@noble/hashes@1.3.2": + version "1.3.2" + resolved "https://registry.yarnpkg.com/@noble/hashes/-/hashes-1.3.2.tgz#6f26dbc8fbc7205873ce3cee2f690eba0d421b39" + integrity sha512-MVC8EAQp7MvEcm30KWENFjgR+Mkmf+D189XJTkFIlwohU5hcBbn1ZkKq7KVTi2Hme3PMGF390DaL52beVrIihQ== -"@noble/secp256k1@1.7.1": - version "1.7.1" - resolved "https://registry.yarnpkg.com/@noble/secp256k1/-/secp256k1-1.7.1.tgz#b251c70f824ce3ca7f8dc3df08d58f005cc0507c" - integrity sha512-hOUk6AyBFmqVrv7k5WAw/LpszxVbj9gGN4JRkIX52fdFAj1UA61KXmZDvqVEm+pOyec3+fIeZB02LYa/pWOArw== +"@noble/hashes@1.3.3", "@noble/hashes@~1.3.3": + version "1.3.3" + resolved "https://registry.yarnpkg.com/@noble/hashes/-/hashes-1.3.3.tgz#39908da56a4adc270147bb07968bf3b16cfe1699" + integrity sha512-V7/fPHgl+jsVPXqqeOzT8egNj2iBIVt+ECeMMG8TdcnTikP3oaBtUVqpT/gYCR68aEBJSF+XbYUxStjbFMqIIA== + +"@noble/secp256k1@2.0.0": + version "2.0.0" + resolved "https://registry.yarnpkg.com/@noble/secp256k1/-/secp256k1-2.0.0.tgz#c214269d45e0233ad6a8ae5104655453636e253d" + integrity sha512-rUGBd95e2a45rlmFTqQJYEFA4/gdIARFfuTuTqLglz0PZ6AKyzyXsEZZq7UZn8hZsvaBgpCzKKBJizT2cJERXw== "@nodelib/fs.scandir@2.1.5": version "2.1.5" @@ -836,7 +1041,7 @@ resolved "https://registry.yarnpkg.com/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz#5bd262af94e9d25bd1e71b05deed44876a222e8b" integrity sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A== -"@nodelib/fs.walk@^1.2.3": +"@nodelib/fs.walk@^1.2.3", "@nodelib/fs.walk@^1.2.8": version "1.2.8" resolved "https://registry.yarnpkg.com/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz#e95737e8bb6746ddedf69c556953494f196fe69a" integrity sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg== @@ -844,76 +1049,130 @@ "@nodelib/fs.scandir" "2.1.5" fastq "^1.6.0" -"@npmcli/arborist@^5.6.3": - version "5.6.3" - resolved "https://registry.yarnpkg.com/@npmcli/arborist/-/arborist-5.6.3.tgz#40810080272e097b4a7a4f56108f4a31638a9874" - integrity sha512-/7hbqEM6YuRjwTcQXkK1+xKslEblY5kFQe0tZ7jKyMlIR6x4iOmhLErIkBBGtTKvYxRKdpcxnFXjCobg3UqmsA== +"@npmcli/agent@^2.0.0": + version "2.2.1" + resolved "https://registry.yarnpkg.com/@npmcli/agent/-/agent-2.2.1.tgz#8aa677d0a4136d57524336a35d5679aedf2d56f7" + integrity sha512-H4FrOVtNyWC8MUwL3UfjOsAihHvT1Pe8POj3JvjXhSTJipsZMtgUALCT4mGyYZNxymkUfOw3PUj6dE4QPp6osQ== + dependencies: + agent-base "^7.1.0" + http-proxy-agent "^7.0.0" + https-proxy-agent "^7.0.1" + lru-cache "^10.0.1" + socks-proxy-agent "^8.0.1" + +"@npmcli/arborist@^6.2.6": + version "6.2.6" + resolved "https://registry.yarnpkg.com/@npmcli/arborist/-/arborist-6.2.6.tgz#3b5d4cc9517c26252d3dd01bbd940ced93aec1bd" + integrity sha512-fkKRY8Y8EHs9tydcuZMn6G1JhZfcoWDXgJzaRiZRJf+WFA1MqOS5IWL2wMjGUtF2V/vMVWWgBT1O4TEKpJK9PQ== dependencies: "@isaacs/string-locale-compare" "^1.1.0" - "@npmcli/installed-package-contents" "^1.0.7" - "@npmcli/map-workspaces" "^2.0.3" - "@npmcli/metavuln-calculator" "^3.0.1" - "@npmcli/move-file" "^2.0.0" - "@npmcli/name-from-folder" "^1.0.1" - "@npmcli/node-gyp" "^2.0.0" - "@npmcli/package-json" "^2.0.0" - "@npmcli/query" "^1.2.0" - "@npmcli/run-script" "^4.1.3" - bin-links "^3.0.3" - cacache "^16.1.3" + "@npmcli/fs" "^3.1.0" + "@npmcli/installed-package-contents" "^2.0.2" + "@npmcli/map-workspaces" "^3.0.2" + "@npmcli/metavuln-calculator" "^5.0.0" + "@npmcli/name-from-folder" "^2.0.0" + "@npmcli/node-gyp" "^3.0.0" + "@npmcli/package-json" "^3.0.0" + "@npmcli/query" "^3.0.0" + "@npmcli/run-script" "^6.0.0" + bin-links "^4.0.1" + cacache "^17.0.4" common-ancestor-path "^1.0.1" - hosted-git-info "^5.2.1" - json-parse-even-better-errors "^2.3.1" + hosted-git-info "^6.1.1" + json-parse-even-better-errors "^3.0.0" json-stringify-nice "^1.1.4" - minimatch "^5.1.0" - mkdirp "^1.0.4" - mkdirp-infer-owner "^2.0.0" - nopt "^6.0.0" - npm-install-checks "^5.0.0" - npm-package-arg "^9.0.0" - npm-pick-manifest "^7.0.2" - npm-registry-fetch "^13.0.0" - npmlog "^6.0.2" - pacote "^13.6.1" - parse-conflict-json "^2.0.1" - proc-log "^2.0.0" + minimatch "^7.4.2" + nopt "^7.0.0" + npm-install-checks "^6.0.0" + npm-package-arg "^10.1.0" + npm-pick-manifest "^8.0.1" + npm-registry-fetch "^14.0.3" + npmlog "^7.0.1" + pacote "^15.0.8" + parse-conflict-json "^3.0.0" + proc-log "^3.0.0" promise-all-reject-late "^1.0.0" promise-call-limit "^1.0.1" - read-package-json-fast "^2.0.2" - readdir-scoped-modules "^1.1.0" - rimraf "^3.0.2" + read-package-json-fast "^3.0.2" semver "^7.3.7" - ssri "^9.0.0" - treeverse "^2.0.0" + ssri "^10.0.1" + treeverse "^3.0.0" walk-up-path "^1.0.0" -"@npmcli/ci-detect@^2.0.0": - version "2.0.0" - resolved "https://registry.yarnpkg.com/@npmcli/ci-detect/-/ci-detect-2.0.0.tgz#e63c91bcd4185ac1e85720a34fc48e164ece5b89" - integrity sha512-8yQtQ9ArHh/TzdUDKQwEvwCgpDuhSWTDAbiKMl3854PcT+Dk4UmWaiawuFTLy9n5twzXOBXVflWe+90/ffXQrA== +"@npmcli/arborist@^7.2.1": + version "7.3.1" + resolved "https://registry.yarnpkg.com/@npmcli/arborist/-/arborist-7.3.1.tgz#7f3f9bed8981584b040483a2f4b126fabcd06674" + integrity sha512-qjMywu8clYczZE2SlLZWVOujAyiJEHHSEzapIXpuMURRH/tfY0KPKvGPyjvV041QsGN3tsWeaTUHcOi59wscSw== + dependencies: + "@isaacs/string-locale-compare" "^1.1.0" + "@npmcli/fs" "^3.1.0" + "@npmcli/installed-package-contents" "^2.0.2" + "@npmcli/map-workspaces" "^3.0.2" + "@npmcli/metavuln-calculator" "^7.0.0" + "@npmcli/name-from-folder" "^2.0.0" + "@npmcli/node-gyp" "^3.0.0" + "@npmcli/package-json" "^5.0.0" + "@npmcli/query" "^3.0.1" + "@npmcli/run-script" "^7.0.2" + bin-links "^4.0.1" + cacache "^18.0.0" + common-ancestor-path "^1.0.1" + hosted-git-info "^7.0.1" + json-parse-even-better-errors "^3.0.0" + json-stringify-nice "^1.1.4" + minimatch "^9.0.0" + nopt "^7.0.0" + npm-install-checks "^6.2.0" + npm-package-arg "^11.0.1" + npm-pick-manifest "^9.0.0" + npm-registry-fetch "^16.0.0" + npmlog "^7.0.1" + pacote "^17.0.4" + parse-conflict-json "^3.0.0" + proc-log "^3.0.0" + promise-all-reject-late "^1.0.0" + promise-call-limit "^3.0.1" + read-package-json-fast "^3.0.2" + semver "^7.3.7" + ssri "^10.0.5" + treeverse "^3.0.0" + walk-up-path "^3.0.1" -"@npmcli/config@^4.2.1": - version "4.2.2" - resolved "https://registry.yarnpkg.com/@npmcli/config/-/config-4.2.2.tgz#2e3334dda84f48d059309c53d152e66b05ca24b7" - integrity sha512-5GNcLd+0c4bYBnFop53+26CO5GQP0R9YcxlernohpHDWdIgzUg9I0+GEMk3sNHnLntATVU39d283A4OO+W402w== +"@npmcli/config@^6.1.5": + version "6.1.5" + resolved "https://registry.yarnpkg.com/@npmcli/config/-/config-6.1.5.tgz#79f6e84dbe13f0ad14133898cb4cb904cab7097a" + integrity sha512-nUjJ4+Xo2/XWoq5wsF9ajRtm5xADlLjtyBQGdGlWFRgHpYggZtxQP1XteM6SvEQsHI3P9vDyLGIYO0MlNrQZwQ== dependencies: - "@npmcli/map-workspaces" "^2.0.2" + "@npmcli/map-workspaces" "^3.0.2" ini "^3.0.0" - mkdirp-infer-owner "^2.0.0" - nopt "^6.0.0" - proc-log "^2.0.0" - read-package-json-fast "^2.0.3" + nopt "^7.0.0" + proc-log "^3.0.0" + read-package-json-fast "^3.0.2" semver "^7.3.5" walk-up-path "^1.0.0" -"@npmcli/disparity-colors@^2.0.0": - version "2.0.0" - resolved "https://registry.yarnpkg.com/@npmcli/disparity-colors/-/disparity-colors-2.0.0.tgz#cb518166ee21573b96241a3613fef70acb2a60ba" - integrity sha512-FFXGrIjhvd2qSZ8iS0yDvbI7nbjdyT2VNO7wotosjYZM2p2r8PN3B7Om3M5NO9KqW/OVzfzLB3L0V5Vo5QXC7A== +"@npmcli/config@^8.0.2": + version "8.1.0" + resolved "https://registry.yarnpkg.com/@npmcli/config/-/config-8.1.0.tgz#2c7f6f80d78b9c18d8a70ae7c5fdb481be727bb0" + integrity sha512-61LNEybTFaa9Z/f8y6X9s2Blc75aijZK67LxqC5xicBcfkw8M/88nYrRXGXxAUKm6GRlxTZ216dp1UK2+TbaYw== + dependencies: + "@npmcli/map-workspaces" "^3.0.2" + ci-info "^4.0.0" + ini "^4.1.0" + nopt "^7.0.0" + proc-log "^3.0.0" + read-package-json-fast "^3.0.2" + semver "^7.3.5" + walk-up-path "^3.0.1" + +"@npmcli/disparity-colors@^3.0.0": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@npmcli/disparity-colors/-/disparity-colors-3.0.0.tgz#60ea8c6eb5ba9de2d1950e15b06205b2c3ab7833" + integrity sha512-5R/z157/f20Fi0Ou4ZttL51V0xz0EdPEOauFtPCEYOLInDBRCj1/TxOJ5aGTrtShxEshN2d+hXb9ZKSi5RLBcg== dependencies: ansi-styles "^4.3.0" -"@npmcli/fs@^2.1.0", "@npmcli/fs@^2.1.1": +"@npmcli/fs@^2.1.0": version "2.1.2" resolved "https://registry.yarnpkg.com/@npmcli/fs/-/fs-2.1.2.tgz#a9e2541a4a2fec2e69c29b35e6060973da79b865" integrity sha512-yOJKRvohFOaLqipNtwYB9WugyZKhC/DZC4VYPmpaCzDBrA8YpK3qHZ8/HGscMnE4GqbkLNuVcCnxkeQEdGt6LQ== @@ -921,47 +1180,102 @@ "@gar/promisify" "^1.1.3" semver "^7.3.5" -"@npmcli/git@^3.0.0": - version "3.0.2" - resolved "https://registry.yarnpkg.com/@npmcli/git/-/git-3.0.2.tgz#5c5de6b4d70474cf2d09af149ce42e4e1dacb931" - integrity sha512-CAcd08y3DWBJqJDpfuVL0uijlq5oaXaOJEKHKc4wqrjd00gkvTZB+nFuLn+doOOKddaQS9JfqtNoFCO2LCvA3w== +"@npmcli/fs@^3.1.0": + version "3.1.0" + resolved "https://registry.yarnpkg.com/@npmcli/fs/-/fs-3.1.0.tgz#233d43a25a91d68c3a863ba0da6a3f00924a173e" + integrity sha512-7kZUAaLscfgbwBQRbvdMYaZOWyMEcPTH/tJjnyAWJ/dvvs9Ef+CERx/qJb9GExJpl1qipaDGn7KqHnFGGixd0w== + dependencies: + semver "^7.3.5" + +"@npmcli/git@^4.0.0": + version "4.0.3" + resolved "https://registry.yarnpkg.com/@npmcli/git/-/git-4.0.3.tgz#354db5fe1f29696303638e191d8538ee9b01b4bb" + integrity sha512-8cXNkDIbnXPVbhXMmQ7/bklCAjtmPaXfI9aEM4iH+xSuEHINLMHhlfESvVwdqmHJRJkR48vNJTSUvoF6GRPSFA== dependencies: - "@npmcli/promise-spawn" "^3.0.0" + "@npmcli/promise-spawn" "^6.0.0" lru-cache "^7.4.4" mkdirp "^1.0.4" - npm-pick-manifest "^7.0.0" - proc-log "^2.0.0" + npm-pick-manifest "^8.0.0" + proc-log "^3.0.0" promise-inflight "^1.0.1" promise-retry "^2.0.1" semver "^7.3.5" - which "^2.0.2" + which "^3.0.0" -"@npmcli/installed-package-contents@^1.0.7": - version "1.0.7" - resolved "https://registry.yarnpkg.com/@npmcli/installed-package-contents/-/installed-package-contents-1.0.7.tgz#ab7408c6147911b970a8abe261ce512232a3f4fa" - integrity sha512-9rufe0wnJusCQoLpV9ZPKIVP55itrM5BxOXs10DmdbRfgWtHy1LDyskbwRnBghuB0PrF7pNPOqREVtpz4HqzKw== +"@npmcli/git@^4.0.1": + version "4.0.4" + resolved "https://registry.yarnpkg.com/@npmcli/git/-/git-4.0.4.tgz#cdf74f21b1d440c0756fb28159d935129d9daa33" + integrity sha512-5yZghx+u5M47LghaybLCkdSyFzV/w4OuH12d96HO389Ik9CDsLaDZJVynSGGVJOLn6gy/k7Dz5XYcplM3uxXRg== dependencies: - npm-bundled "^1.1.1" - npm-normalize-package-bin "^1.0.1" + "@npmcli/promise-spawn" "^6.0.0" + lru-cache "^7.4.4" + npm-pick-manifest "^8.0.0" + proc-log "^3.0.0" + promise-inflight "^1.0.1" + promise-retry "^2.0.1" + semver "^7.3.5" + which "^3.0.0" -"@npmcli/map-workspaces@^2.0.2", "@npmcli/map-workspaces@^2.0.3": - version "2.0.4" - resolved "https://registry.yarnpkg.com/@npmcli/map-workspaces/-/map-workspaces-2.0.4.tgz#9e5e8ab655215a262aefabf139782b894e0504fc" - integrity sha512-bMo0aAfwhVwqoVM5UzX1DJnlvVvzDCHae821jv48L1EsrYwfOZChlqWYXEtto/+BkBXetPbEWgau++/brh4oVg== +"@npmcli/git@^5.0.0", "@npmcli/git@^5.0.3": + version "5.0.4" + resolved "https://registry.yarnpkg.com/@npmcli/git/-/git-5.0.4.tgz#d18c50f99649e6e89e8b427318134f582498700c" + integrity sha512-nr6/WezNzuYUppzXRaYu/W4aT5rLxdXqEFupbh6e/ovlYFQ8hpu1UUPV3Ir/YTl+74iXl2ZOMlGzudh9ZPUchQ== dependencies: - "@npmcli/name-from-folder" "^1.0.1" - glob "^8.0.1" - minimatch "^5.0.1" - read-package-json-fast "^2.0.3" + "@npmcli/promise-spawn" "^7.0.0" + lru-cache "^10.0.1" + npm-pick-manifest "^9.0.0" + proc-log "^3.0.0" + promise-inflight "^1.0.1" + promise-retry "^2.0.1" + semver "^7.3.5" + which "^4.0.0" -"@npmcli/metavuln-calculator@^3.0.1": - version "3.1.1" - resolved "https://registry.yarnpkg.com/@npmcli/metavuln-calculator/-/metavuln-calculator-3.1.1.tgz#9359bd72b400f8353f6a28a25c8457b562602622" - integrity sha512-n69ygIaqAedecLeVH3KnO39M6ZHiJ2dEv5A7DGvcqCB8q17BGUgW8QaanIkbWUo2aYGZqJaOORTLAlIvKjNDKA== +"@npmcli/installed-package-contents@^2.0.1", "@npmcli/installed-package-contents@^2.0.2": + version "2.0.2" + resolved "https://registry.yarnpkg.com/@npmcli/installed-package-contents/-/installed-package-contents-2.0.2.tgz#bfd817eccd9e8df200919e73f57f9e3d9e4f9e33" + integrity sha512-xACzLPhnfD51GKvTOOuNX2/V4G4mz9/1I2MfDoye9kBM3RYe5g2YbscsaGoTlaWqkxeiapBWyseULVKpSVHtKQ== + dependencies: + npm-bundled "^3.0.0" + npm-normalize-package-bin "^3.0.0" + +"@npmcli/map-workspaces@^3.0.2", "@npmcli/map-workspaces@^3.0.3": + version "3.0.3" + resolved "https://registry.yarnpkg.com/@npmcli/map-workspaces/-/map-workspaces-3.0.3.tgz#476944b63cd1f65bf83c6fdc7f4ca7be56906b1f" + integrity sha512-HlCvFuTzw4UNoKyZdqiNrln+qMF71QJkxy2dsusV8QQdoa89e2TF4dATCzBxbl4zzRzdDoWWyP5ADVrNAH9cRQ== + dependencies: + "@npmcli/name-from-folder" "^2.0.0" + glob "^9.3.1" + minimatch "^7.4.2" + read-package-json-fast "^3.0.0" + +"@npmcli/map-workspaces@^3.0.4": + version "3.0.4" + resolved "https://registry.yarnpkg.com/@npmcli/map-workspaces/-/map-workspaces-3.0.4.tgz#15ad7d854292e484f7ba04bc30187a8320dba799" + integrity sha512-Z0TbvXkRbacjFFLpVpV0e2mheCh+WzQpcqL+4xp49uNJOxOnIAPZyXtUxZ5Qn3QBTGKA11Exjd9a5411rBrhDg== dependencies: - cacache "^16.0.0" - json-parse-even-better-errors "^2.3.1" - pacote "^13.0.3" + "@npmcli/name-from-folder" "^2.0.0" + glob "^10.2.2" + minimatch "^9.0.0" + read-package-json-fast "^3.0.0" + +"@npmcli/metavuln-calculator@^5.0.0": + version "5.0.0" + resolved "https://registry.yarnpkg.com/@npmcli/metavuln-calculator/-/metavuln-calculator-5.0.0.tgz#917c3be49ebed0b424b07f38060b929127e4c499" + integrity sha512-BBFQx4M12wiEuVwCgtX/Depx0B/+NHMwDWOlXT41/Pdy5W/1Fenk+hibUlMSrFWwASbX+fY90UbILAEIYH02/A== + dependencies: + cacache "^17.0.0" + json-parse-even-better-errors "^3.0.0" + pacote "^15.0.0" + semver "^7.3.5" + +"@npmcli/metavuln-calculator@^7.0.0": + version "7.0.0" + resolved "https://registry.yarnpkg.com/@npmcli/metavuln-calculator/-/metavuln-calculator-7.0.0.tgz#fb59245926d7f677db904177f9aca15ac883d6cb" + integrity sha512-Pw0tyX02VkpqlIQlG2TeiJNsdrecYeUU0ubZZa9pi3N37GCsxI+en43u4hYFdq+eSx1A9a9vwFAUyqEtKFsbHQ== + dependencies: + cacache "^18.0.0" + json-parse-even-better-errors "^3.0.0" + pacote "^17.0.0" semver "^7.3.5" "@npmcli/move-file@^2.0.0": @@ -972,49 +1286,85 @@ mkdirp "^1.0.4" rimraf "^3.0.2" -"@npmcli/name-from-folder@^1.0.1": - version "1.0.1" - resolved "https://registry.yarnpkg.com/@npmcli/name-from-folder/-/name-from-folder-1.0.1.tgz#77ecd0a4fcb772ba6fe927e2e2e155fbec2e6b1a" - integrity sha512-qq3oEfcLFwNfEYOQ8HLimRGKlD8WSeGEdtUa7hmzpR8Sa7haL1KVQrvgO6wqMjhWFFVjgtrh1gIxDz+P8sjUaA== - -"@npmcli/node-gyp@^2.0.0": +"@npmcli/name-from-folder@^2.0.0": version "2.0.0" - resolved "https://registry.yarnpkg.com/@npmcli/node-gyp/-/node-gyp-2.0.0.tgz#8c20e53e34e9078d18815c1d2dda6f2420d75e35" - integrity sha512-doNI35wIe3bBaEgrlPfdJPaCpUR89pJWep4Hq3aRdh6gKazIVWfs0jHttvSSoq47ZXgC7h73kDsUl8AoIQUB+A== + resolved "https://registry.yarnpkg.com/@npmcli/name-from-folder/-/name-from-folder-2.0.0.tgz#c44d3a7c6d5c184bb6036f4d5995eee298945815" + integrity sha512-pwK+BfEBZJbKdNYpHHRTNBwBoqrN/iIMO0AiGvYsp3Hoaq0WbgGSWQR6SCldZovoDpY3yje5lkFUe6gsDgJ2vg== -"@npmcli/package-json@^2.0.0": - version "2.0.0" - resolved "https://registry.yarnpkg.com/@npmcli/package-json/-/package-json-2.0.0.tgz#3bbcf4677e21055adbe673d9f08c9f9cde942e4a" - integrity sha512-42jnZ6yl16GzjWSH7vtrmWyJDGVa/LXPdpN2rcUWolFjc9ON2N3uz0qdBbQACfmhuJZ2lbKYtmK5qx68ZPLHMA== +"@npmcli/node-gyp@^3.0.0": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@npmcli/node-gyp/-/node-gyp-3.0.0.tgz#101b2d0490ef1aa20ed460e4c0813f0db560545a" + integrity sha512-gp8pRXC2oOxu0DUE1/M3bYtb1b3/DbJ5aM113+XJBgfXdussRAsX0YOrOhdd8WvnAR6auDBvJomGAkLKA5ydxA== + +"@npmcli/package-json@^3.0.0": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@npmcli/package-json/-/package-json-3.0.0.tgz#c9219a197e1be8dbf43c4ef8767a72277c0533b6" + integrity sha512-NnuPuM97xfiCpbTEJYtEuKz6CFbpUHtaT0+5via5pQeI25omvQDFbp1GcGJ/c4zvL/WX0qbde6YiLgfZbWFgvg== + dependencies: + json-parse-even-better-errors "^3.0.0" + +"@npmcli/package-json@^5.0.0": + version "5.0.0" + resolved "https://registry.yarnpkg.com/@npmcli/package-json/-/package-json-5.0.0.tgz#77d0f8b17096763ccbd8af03b7117ba6e34d6e91" + integrity sha512-OI2zdYBLhQ7kpNPaJxiflofYIpkNLi+lnGdzqUOfRmCF3r2l1nadcjtCYMJKv/Utm/ZtlffaUuTiAktPHbc17g== + dependencies: + "@npmcli/git" "^5.0.0" + glob "^10.2.2" + hosted-git-info "^7.0.0" + json-parse-even-better-errors "^3.0.0" + normalize-package-data "^6.0.0" + proc-log "^3.0.0" + semver "^7.5.3" + +"@npmcli/promise-spawn@^6.0.0", "@npmcli/promise-spawn@^6.0.1": + version "6.0.2" + resolved "https://registry.yarnpkg.com/@npmcli/promise-spawn/-/promise-spawn-6.0.2.tgz#c8bc4fa2bd0f01cb979d8798ba038f314cfa70f2" + integrity sha512-gGq0NJkIGSwdbUt4yhdF8ZrmkGKVz9vAdVzpOfnom+V8PLSmSOVhZwbNvZZS1EYcJN5hzzKBxmmVVAInM6HQLg== + dependencies: + which "^3.0.0" + +"@npmcli/promise-spawn@^7.0.0", "@npmcli/promise-spawn@^7.0.1": + version "7.0.1" + resolved "https://registry.yarnpkg.com/@npmcli/promise-spawn/-/promise-spawn-7.0.1.tgz#a836de2f42a2245d629cf6fbb8dd6c74c74c55af" + integrity sha512-P4KkF9jX3y+7yFUxgcUdDtLy+t4OlDGuEBLNs57AZsfSfg+uV6MLndqGpnl4831ggaEdXwR50XFoZP4VFtHolg== dependencies: - json-parse-even-better-errors "^2.3.1" + which "^4.0.0" -"@npmcli/promise-spawn@^3.0.0": +"@npmcli/query@^3.0.0": version "3.0.0" - resolved "https://registry.yarnpkg.com/@npmcli/promise-spawn/-/promise-spawn-3.0.0.tgz#53283b5f18f855c6925f23c24e67c911501ef573" - integrity sha512-s9SgS+p3a9Eohe68cSI3fi+hpcZUmXq5P7w0kMlAsWVtR7XbK3ptkZqKT2cK1zLDObJ3sR+8P59sJE0w/KTL1g== + resolved "https://registry.yarnpkg.com/@npmcli/query/-/query-3.0.0.tgz#51a0dfb85811e04f244171f164b6bc83b36113a7" + integrity sha512-MFNDSJNgsLZIEBVZ0Q9w9K7o07j5N4o4yjtdz2uEpuCZlXGMuPENiRaFYk0vRqAA64qVuUQwC05g27fRtfUgnA== dependencies: - infer-owner "^1.0.4" + postcss-selector-parser "^6.0.10" -"@npmcli/query@^1.2.0": - version "1.2.0" - resolved "https://registry.yarnpkg.com/@npmcli/query/-/query-1.2.0.tgz#46468d583cf013aa92102970700f9555314aabe4" - integrity sha512-uWglsUM3PjBLgTSmZ3/vygeGdvWEIZ3wTUnzGFbprC/RtvQSaT+GAXu1DXmSFj2bD3oOZdcRm1xdzsV2z1YWdw== +"@npmcli/query@^3.0.1": + version "3.0.1" + resolved "https://registry.yarnpkg.com/@npmcli/query/-/query-3.0.1.tgz#77d63ceb7d27ed748da3cc8b50d45fc341448ed6" + integrity sha512-0jE8iHBogf/+bFDj+ju6/UMLbJ39c8h6nSe6qile+dB7PJ0iV3gNqcb2vtt6WWCBrxv9uAjzUT/8vroluulidA== dependencies: - npm-package-arg "^9.1.0" postcss-selector-parser "^6.0.10" - semver "^7.3.7" -"@npmcli/run-script@^4.1.0", "@npmcli/run-script@^4.1.3", "@npmcli/run-script@^4.2.0", "@npmcli/run-script@^4.2.1": - version "4.2.1" - resolved "https://registry.yarnpkg.com/@npmcli/run-script/-/run-script-4.2.1.tgz#c07c5c71bc1c70a5f2a06b0d4da976641609b946" - integrity sha512-7dqywvVudPSrRCW5nTHpHgeWnbBtz8cFkOuKrecm6ih+oO9ciydhWt6OF7HlqupRRmB8Q/gECVdB9LMfToJbRg== +"@npmcli/run-script@^6.0.0": + version "6.0.0" + resolved "https://registry.yarnpkg.com/@npmcli/run-script/-/run-script-6.0.0.tgz#f89e322c729e26ae29db6cc8cc76559074aac208" + integrity sha512-ql+AbRur1TeOdl1FY+RAwGW9fcr4ZwiVKabdvm93mujGREVuVLbdkXRJDrkTXSdCjaxYydr1wlA2v67jxWG5BQ== dependencies: - "@npmcli/node-gyp" "^2.0.0" - "@npmcli/promise-spawn" "^3.0.0" + "@npmcli/node-gyp" "^3.0.0" + "@npmcli/promise-spawn" "^6.0.0" node-gyp "^9.0.0" - read-package-json-fast "^2.0.3" - which "^2.0.2" + read-package-json-fast "^3.0.0" + which "^3.0.0" + +"@npmcli/run-script@^7.0.0", "@npmcli/run-script@^7.0.2", "@npmcli/run-script@^7.0.4": + version "7.0.4" + resolved "https://registry.yarnpkg.com/@npmcli/run-script/-/run-script-7.0.4.tgz#9f29aaf4bfcf57f7de2a9e28d1ef091d14b2e6eb" + integrity sha512-9ApYM/3+rBt9V80aYg6tZfzj3UWdiYyCt7gJUD1VJKvWF5nwKDSICXbYIQbspFTq6TOpbsEtIC0LArB8d9PFmg== + dependencies: + "@npmcli/node-gyp" "^3.0.0" + "@npmcli/package-json" "^5.0.0" + "@npmcli/promise-spawn" "^7.0.0" + node-gyp "^10.0.0" + which "^4.0.0" "@octokit/auth-token@^3.0.0": version "3.0.3" @@ -1023,6 +1373,11 @@ dependencies: "@octokit/types" "^9.0.0" +"@octokit/auth-token@^4.0.0": + version "4.0.0" + resolved "https://registry.yarnpkg.com/@octokit/auth-token/-/auth-token-4.0.0.tgz#40d203ea827b9f17f42a29c6afb93b7745ef80c7" + integrity sha512-tY/msAuJo6ARbK6SPIxZrPBms3xPbfwBrulZe0Wtr/DIY9lje2HeV1uoebShn6mx7SjCHif6EjMvoREj+gZ+SA== + "@octokit/core@^4.1.0": version "4.2.0" resolved "https://registry.yarnpkg.com/@octokit/core/-/core-4.2.0.tgz#8c253ba9605aca605bc46187c34fcccae6a96648" @@ -1036,6 +1391,19 @@ before-after-hook "^2.2.0" universal-user-agent "^6.0.0" +"@octokit/core@^5.0.0": + version "5.0.2" + resolved "https://registry.yarnpkg.com/@octokit/core/-/core-5.0.2.tgz#ae7c5d61fdd98ba348a27c3cc510879a130b1234" + integrity sha512-cZUy1gUvd4vttMic7C0lwPed8IYXWYp8kHIMatyhY8t8n3Cpw2ILczkV5pGMPqef7v0bLo0pOHrEHarsau2Ydg== + dependencies: + "@octokit/auth-token" "^4.0.0" + "@octokit/graphql" "^7.0.0" + "@octokit/request" "^8.0.2" + "@octokit/request-error" "^5.0.0" + "@octokit/types" "^12.0.0" + before-after-hook "^2.2.0" + universal-user-agent "^6.0.0" + "@octokit/endpoint@^7.0.0": version "7.0.5" resolved "https://registry.yarnpkg.com/@octokit/endpoint/-/endpoint-7.0.5.tgz#2bb2a911c12c50f10014183f5d596ce30ac67dd1" @@ -1045,6 +1413,14 @@ is-plain-object "^5.0.0" universal-user-agent "^6.0.0" +"@octokit/endpoint@^9.0.0": + version "9.0.4" + resolved "https://registry.yarnpkg.com/@octokit/endpoint/-/endpoint-9.0.4.tgz#8afda5ad1ffc3073d08f2b450964c610b821d1ea" + integrity sha512-DWPLtr1Kz3tv8L0UvXTDP1fNwM0S+z6EJpRcvH66orY6Eld4XBMCSYsaWp4xIm61jTWxK68BrR7ibO+vSDnZqw== + dependencies: + "@octokit/types" "^12.0.0" + universal-user-agent "^6.0.0" + "@octokit/graphql@^5.0.0": version "5.0.5" resolved "https://registry.yarnpkg.com/@octokit/graphql/-/graphql-5.0.5.tgz#a4cb3ea73f83b861893a6370ee82abb36e81afd2" @@ -1054,11 +1430,25 @@ "@octokit/types" "^9.0.0" universal-user-agent "^6.0.0" +"@octokit/graphql@^7.0.0": + version "7.0.2" + resolved "https://registry.yarnpkg.com/@octokit/graphql/-/graphql-7.0.2.tgz#3df14b9968192f9060d94ed9e3aa9780a76e7f99" + integrity sha512-OJ2iGMtj5Tg3s6RaXH22cJcxXRi7Y3EBqbHTBRq+PQAqfaS8f/236fUrWhfSn8P4jovyzqucxme7/vWSSZBX2Q== + dependencies: + "@octokit/request" "^8.0.1" + "@octokit/types" "^12.0.0" + universal-user-agent "^6.0.0" + "@octokit/openapi-types@^16.0.0": version "16.0.0" resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-16.0.0.tgz#d92838a6cd9fb4639ca875ddb3437f1045cc625e" integrity sha512-JbFWOqTJVLHZSUUoF4FzAZKYtqdxWu9Z5m2QQnOyEa04fOFljvyh7D3GYKbfuaSWisqehImiVIMG4eyJeP5VEA== +"@octokit/openapi-types@^19.1.0": + version "19.1.0" + resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-19.1.0.tgz#75ec7e64743870fc73e1ab4bc6ec252ecdd624dc" + integrity sha512-6G+ywGClliGQwRsjvqVYpklIfa7oRPA0vyhPQG/1Feh+B+wU0vGH1JiJ5T25d3g1JZYBHzR2qefLi9x8Gt+cpw== + "@octokit/plugin-paginate-rest@^6.0.0": version "6.0.0" resolved "https://registry.yarnpkg.com/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-6.0.0.tgz#f34b5a7d9416019126042cd7d7b811e006c0d561" @@ -1066,6 +1456,13 @@ dependencies: "@octokit/types" "^9.0.0" +"@octokit/plugin-paginate-rest@^9.0.0": + version "9.1.5" + resolved "https://registry.yarnpkg.com/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-9.1.5.tgz#1705bcef4dcde1f4015ee58a63dc61b68648f480" + integrity sha512-WKTQXxK+bu49qzwv4qKbMMRXej1DU2gq017euWyKVudA6MldaSSQuxtz+vGbhxV4CjxpUxjZu6rM2wfc1FiWVg== + dependencies: + "@octokit/types" "^12.4.0" + "@octokit/plugin-request-log@^1.0.4": version "1.0.4" resolved "https://registry.yarnpkg.com/@octokit/plugin-request-log/-/plugin-request-log-1.0.4.tgz#5e50ed7083a613816b1e4a28aeec5fb7f1462e85" @@ -1079,6 +1476,23 @@ "@octokit/types" "^9.0.0" deprecation "^2.3.1" +"@octokit/plugin-retry@^6.0.0": + version "6.0.1" + resolved "https://registry.yarnpkg.com/@octokit/plugin-retry/-/plugin-retry-6.0.1.tgz#3257404f7cc418e1c1f13a7f2012c1db848b7693" + integrity sha512-SKs+Tz9oj0g4p28qkZwl/topGcb0k0qPNX/i7vBKmDsjoeqnVfFUquqrE/O9oJY7+oLzdCtkiWSXLpLjvl6uog== + dependencies: + "@octokit/request-error" "^5.0.0" + "@octokit/types" "^12.0.0" + bottleneck "^2.15.3" + +"@octokit/plugin-throttling@^8.0.0": + version "8.1.3" + resolved "https://registry.yarnpkg.com/@octokit/plugin-throttling/-/plugin-throttling-8.1.3.tgz#7fb0e001c0cb9383c6be07740b8ec326ed990f6b" + integrity sha512-pfyqaqpc0EXh5Cn4HX9lWYsZ4gGbjnSmUILeu4u2gnuM50K/wIk9s1Pxt3lVeVwekmITgN/nJdoh43Ka+vye8A== + dependencies: + "@octokit/types" "^12.2.0" + bottleneck "^2.15.3" + "@octokit/request-error@^3.0.0": version "3.0.3" resolved "https://registry.yarnpkg.com/@octokit/request-error/-/request-error-3.0.3.tgz#ef3dd08b8e964e53e55d471acfe00baa892b9c69" @@ -1088,6 +1502,15 @@ deprecation "^2.0.0" once "^1.4.0" +"@octokit/request-error@^5.0.0": + version "5.0.1" + resolved "https://registry.yarnpkg.com/@octokit/request-error/-/request-error-5.0.1.tgz#277e3ce3b540b41525e07ba24c5ef5e868a72db9" + integrity sha512-X7pnyTMV7MgtGmiXBwmO6M5kIPrntOXdyKZLigNfQWSEQzVxR4a4vo49vJjTWX70mPndj8KhfT4Dx+2Ng3vnBQ== + dependencies: + "@octokit/types" "^12.0.0" + deprecation "^2.0.0" + once "^1.4.0" + "@octokit/request@^6.0.0": version "6.2.3" resolved "https://registry.yarnpkg.com/@octokit/request/-/request-6.2.3.tgz#76d5d6d44da5c8d406620a4c285d280ae310bdb4" @@ -1100,6 +1523,16 @@ node-fetch "^2.6.7" universal-user-agent "^6.0.0" +"@octokit/request@^8.0.1", "@octokit/request@^8.0.2": + version "8.1.6" + resolved "https://registry.yarnpkg.com/@octokit/request/-/request-8.1.6.tgz#a76a859c30421737a3918b40973c2ff369009571" + integrity sha512-YhPaGml3ncZC1NfXpP3WZ7iliL1ap6tLkAp6MvbK2fTTPytzVUyUesBBogcdMm86uRYO5rHaM1xIWxigWZ17MQ== + dependencies: + "@octokit/endpoint" "^9.0.0" + "@octokit/request-error" "^5.0.0" + "@octokit/types" "^12.0.0" + universal-user-agent "^6.0.0" + "@octokit/rest@^19.0.0": version "19.0.7" resolved "https://registry.yarnpkg.com/@octokit/rest/-/rest-19.0.7.tgz#d2e21b4995ab96ae5bfae50b4969da7e04e0bb70" @@ -1110,6 +1543,13 @@ "@octokit/plugin-request-log" "^1.0.4" "@octokit/plugin-rest-endpoint-methods" "^7.0.0" +"@octokit/types@^12.0.0", "@octokit/types@^12.2.0", "@octokit/types@^12.4.0": + version "12.4.0" + resolved "https://registry.yarnpkg.com/@octokit/types/-/types-12.4.0.tgz#8f97b601e91ce6b9776ed8152217e77a71be7aac" + integrity sha512-FLWs/AvZllw/AGVs+nJ+ELCDZZJk+kY0zMen118xhL2zD0s1etIUHm1odgjP7epxYU1ln7SZxEUWYop5bhsdgQ== + dependencies: + "@octokit/openapi-types" "^19.1.0" + "@octokit/types@^9.0.0": version "9.0.0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-9.0.0.tgz#6050db04ddf4188ec92d60e4da1a2ce0633ff635" @@ -1117,6 +1557,11 @@ dependencies: "@octokit/openapi-types" "^16.0.0" +"@pkgjs/parseargs@^0.11.0": + version "0.11.0" + resolved "https://registry.yarnpkg.com/@pkgjs/parseargs/-/parseargs-0.11.0.tgz#a77ea742fab25775145434eb1d2328cf5013ac33" + integrity sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg== + "@pnpm/network.ca-file@^1.0.1": version "1.0.2" resolved "https://registry.yarnpkg.com/@pnpm/network.ca-file/-/network.ca-file-1.0.2.tgz#2ab05e09c1af0cdf2fcf5035bea1484e222f7983" @@ -1132,16 +1577,137 @@ "@pnpm/network.ca-file" "^1.0.1" config-chain "^1.1.11" -"@semantic-release/changelog@6.0.2": - version "6.0.2" - resolved "https://registry.yarnpkg.com/@semantic-release/changelog/-/changelog-6.0.2.tgz#fdcdbd368788c8fcc69c4af29bf2064f4afb45f4" - integrity sha512-jHqfTkoPbDEOAgAP18mGP53IxeMwxTISN+GwTRy9uLu58UjARoZU8ScCgWGeO2WPkEsm57H8AkyY02W2ntIlIw== +"@rollup/plugin-node-resolve@15.2.3": + version "15.2.3" + resolved "https://registry.yarnpkg.com/@rollup/plugin-node-resolve/-/plugin-node-resolve-15.2.3.tgz#e5e0b059bd85ca57489492f295ce88c2d4b0daf9" + integrity sha512-j/lym8nf5E21LwBT4Df1VD6hRO2L2iwUeUmP7litikRsVp1H6NWx20NEp0Y7su+7XGc476GnXXc4kFeZNGmaSQ== + dependencies: + "@rollup/pluginutils" "^5.0.1" + "@types/resolve" "1.20.2" + deepmerge "^4.2.2" + is-builtin-module "^3.2.1" + is-module "^1.0.0" + resolve "^1.22.1" + +"@rollup/plugin-terser@0.4.3": + version "0.4.3" + resolved "https://registry.yarnpkg.com/@rollup/plugin-terser/-/plugin-terser-0.4.3.tgz#c2bde2fe3a85e45fa68a454d48f4e73e57f98b30" + integrity sha512-EF0oejTMtkyhrkwCdg0HJ0IpkcaVg1MMSf2olHb2Jp+1mnLM04OhjpJWGma4HobiDTF0WCyViWuvadyE9ch2XA== + dependencies: + serialize-javascript "^6.0.1" + smob "^1.0.0" + terser "^5.17.4" + +"@rollup/plugin-typescript@11.1.6": + version "11.1.6" + resolved "https://registry.yarnpkg.com/@rollup/plugin-typescript/-/plugin-typescript-11.1.6.tgz#724237d5ec12609ec01429f619d2a3e7d4d1b22b" + integrity sha512-R92yOmIACgYdJ7dJ97p4K69I8gg6IEHt8M7dUBxN3W6nrO8uUxX5ixl0yU/N3aZTi8WhPuICvOHXQvF6FaykAA== + dependencies: + "@rollup/pluginutils" "^5.1.0" + resolve "^1.22.1" + +"@rollup/pluginutils@^5.0.1", "@rollup/pluginutils@^5.1.0": + version "5.1.0" + resolved "https://registry.yarnpkg.com/@rollup/pluginutils/-/pluginutils-5.1.0.tgz#7e53eddc8c7f483a4ad0b94afb1f7f5fd3c771e0" + integrity sha512-XTIWOPPcpvyKI6L1NHo0lFlCyznUEyPmPY1mc3KpPVDYulHSTvyeLNVW00QTLIAFNhR3kYnJTQHeGqU4M3n09g== + dependencies: + "@types/estree" "^1.0.0" + estree-walker "^2.0.2" + picomatch "^2.3.1" + +"@rollup/rollup-android-arm-eabi@4.9.6": + version "4.9.6" + resolved "https://registry.yarnpkg.com/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.9.6.tgz#66b8d9cb2b3a474d115500f9ebaf43e2126fe496" + integrity sha512-MVNXSSYN6QXOulbHpLMKYi60ppyO13W9my1qogeiAqtjb2yR4LSmfU2+POvDkLzhjYLXz9Rf9+9a3zFHW1Lecg== + +"@rollup/rollup-android-arm64@4.9.6": + version "4.9.6" + resolved "https://registry.yarnpkg.com/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.9.6.tgz#46327d5b86420d2307946bec1535fdf00356e47d" + integrity sha512-T14aNLpqJ5wzKNf5jEDpv5zgyIqcpn1MlwCrUXLrwoADr2RkWA0vOWP4XxbO9aiO3dvMCQICZdKeDrFl7UMClw== + +"@rollup/rollup-darwin-arm64@4.9.6": + version "4.9.6" + resolved "https://registry.yarnpkg.com/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.9.6.tgz#166987224d2f8b1e2fd28ee90c447d52271d5e90" + integrity sha512-CqNNAyhRkTbo8VVZ5R85X73H3R5NX9ONnKbXuHisGWC0qRbTTxnF1U4V9NafzJbgGM0sHZpdO83pLPzq8uOZFw== + +"@rollup/rollup-darwin-x64@4.9.6": + version "4.9.6" + resolved "https://registry.yarnpkg.com/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.9.6.tgz#a2e6e096f74ccea6e2f174454c26aef6bcdd1274" + integrity sha512-zRDtdJuRvA1dc9Mp6BWYqAsU5oeLixdfUvkTHuiYOHwqYuQ4YgSmi6+/lPvSsqc/I0Omw3DdICx4Tfacdzmhog== + +"@rollup/rollup-linux-arm-gnueabihf@4.9.6": + version "4.9.6" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.9.6.tgz#09fcd4c55a2d6160c5865fec708a8e5287f30515" + integrity sha512-oNk8YXDDnNyG4qlNb6is1ojTOGL/tRhbbKeE/YuccItzerEZT68Z9gHrY3ROh7axDc974+zYAPxK5SH0j/G+QQ== + +"@rollup/rollup-linux-arm64-gnu@4.9.6": + version "4.9.6" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.9.6.tgz#19a3c0b6315c747ca9acf86e9b710cc2440f83c9" + integrity sha512-Z3O60yxPtuCYobrtzjo0wlmvDdx2qZfeAWTyfOjEDqd08kthDKexLpV97KfAeUXPosENKd8uyJMRDfFMxcYkDQ== + +"@rollup/rollup-linux-arm64-musl@4.9.6": + version "4.9.6" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.9.6.tgz#94aaf95fdaf2ad9335983a4552759f98e6b2e850" + integrity sha512-gpiG0qQJNdYEVad+1iAsGAbgAnZ8j07FapmnIAQgODKcOTjLEWM9sRb+MbQyVsYCnA0Im6M6QIq6ax7liws6eQ== + +"@rollup/rollup-linux-riscv64-gnu@4.9.6": + version "4.9.6" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.9.6.tgz#160510e63f4b12618af4013bddf1761cf9fc9880" + integrity sha512-+uCOcvVmFUYvVDr27aiyun9WgZk0tXe7ThuzoUTAukZJOwS5MrGbmSlNOhx1j80GdpqbOty05XqSl5w4dQvcOA== + +"@rollup/rollup-linux-x64-gnu@4.9.6": + version "4.9.6" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.9.6.tgz#5ac5d068ce0726bd0a96ca260d5bd93721c0cb98" + integrity sha512-HUNqM32dGzfBKuaDUBqFB7tP6VMN74eLZ33Q9Y1TBqRDn+qDonkAUyKWwF9BR9unV7QUzffLnz9GrnKvMqC/fw== + +"@rollup/rollup-linux-x64-musl@4.9.6": + version "4.9.6" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.9.6.tgz#bafa759ab43e8eab9edf242a8259ffb4f2a57a5d" + integrity sha512-ch7M+9Tr5R4FK40FHQk8VnML0Szi2KRujUgHXd/HjuH9ifH72GUmw6lStZBo3c3GB82vHa0ZoUfjfcM7JiiMrQ== + +"@rollup/rollup-win32-arm64-msvc@4.9.6": + version "4.9.6" + resolved "https://registry.yarnpkg.com/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.9.6.tgz#1cc3416682e5a20d8f088f26657e6e47f8db468e" + integrity sha512-VD6qnR99dhmTQ1mJhIzXsRcTBvTjbfbGGwKAHcu+52cVl15AC/kplkhxzW/uT0Xl62Y/meBKDZvoJSJN+vTeGA== + +"@rollup/rollup-win32-ia32-msvc@4.9.6": + version "4.9.6" + resolved "https://registry.yarnpkg.com/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.9.6.tgz#7d2251e1aa5e8a1e47c86891fe4547a939503461" + integrity sha512-J9AFDq/xiRI58eR2NIDfyVmTYGyIZmRcvcAoJ48oDld/NTR8wyiPUu2X/v1navJ+N/FGg68LEbX3Ejd6l8B7MQ== + +"@rollup/rollup-win32-x64-msvc@4.9.6": + version "4.9.6" + resolved "https://registry.yarnpkg.com/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.9.6.tgz#2c1fb69e02a3f1506f52698cfdc3a8b6386df9a6" + integrity sha512-jqzNLhNDvIZOrt69Ce4UjGRpXJBzhUBzawMwnaDAwyHriki3XollsewxWzOzz+4yOFDkuJHtTsZFwMxhYJWmLQ== + +"@scure/base@1.1.5", "@scure/base@~1.1.5": + version "1.1.5" + resolved "https://registry.yarnpkg.com/@scure/base/-/base-1.1.5.tgz#1d85d17269fe97694b9c592552dd9e5e33552157" + integrity sha512-Brj9FiG2W1MRQSTB212YVPRrcbjkv48FoZi/u4l/zds/ieRrqsh7aUf6CLwkAq61oKXr/ZlTzlY66gLIj3TFTQ== + +"@semantic-release/changelog@6.0.3": + version "6.0.3" + resolved "https://registry.yarnpkg.com/@semantic-release/changelog/-/changelog-6.0.3.tgz#6195630ecbeccad174461de727d5f975abc23eeb" + integrity sha512-dZuR5qByyfe3Y03TpmCvAxCyTnp7r5XwtHRf/8vD9EAn4ZWbavUX8adMtXYzE86EVh0gyLA7lm5yW4IV30XUag== dependencies: "@semantic-release/error" "^3.0.0" aggregate-error "^3.0.0" fs-extra "^11.0.0" lodash "^4.17.4" +"@semantic-release/commit-analyzer@11.1.0": + version "11.1.0" + resolved "https://registry.yarnpkg.com/@semantic-release/commit-analyzer/-/commit-analyzer-11.1.0.tgz#dd24663c4e1e7c218f53de73f5c639eb2d5a077e" + integrity sha512-cXNTbv3nXR2hlzHjAMgbuiQVtvWHTlwwISt60B+4NZv01y/QRY7p2HcJm8Eh2StzcTJoNnflvKjHH/cjFS7d5g== + dependencies: + conventional-changelog-angular "^7.0.0" + conventional-commits-filter "^4.0.0" + conventional-commits-parser "^5.0.0" + debug "^4.0.0" + import-from-esm "^1.0.3" + lodash-es "^4.17.21" + micromatch "^4.0.2" + "@semantic-release/commit-analyzer@^9.0.2": version "9.0.2" resolved "https://registry.yarnpkg.com/@semantic-release/commit-analyzer/-/commit-analyzer-9.0.2.tgz#a78e54f9834193b55f1073fa6258eecc9a545e03" @@ -1160,6 +1726,11 @@ resolved "https://registry.yarnpkg.com/@semantic-release/error/-/error-3.0.0.tgz#30a3b97bbb5844d695eb22f9d3aa40f6a92770c2" integrity sha512-5hiM4Un+tpl4cKw3lV4UgzJj+SmfNIDCLLw0TepzQxz9ZGV5ixnqkzIVF+3tp0ZHgcMKE+VNGHJjEeyFG2dcSw== +"@semantic-release/error@^4.0.0": + version "4.0.0" + resolved "https://registry.yarnpkg.com/@semantic-release/error/-/error-4.0.0.tgz#692810288239637f74396976a9340fbc0aa9f6f9" + integrity sha512-mgdxrHTLOjOddRVYIYDo0fR3/v61GNN1YGkfbrjuIKg/uMgCd+Qzo3UAXJ+woLQQpos4pl5Esuw5A7AoNlzjUQ== + "@semantic-release/git@10.0.1": version "10.0.1" resolved "https://registry.yarnpkg.com/@semantic-release/git/-/git-10.0.1.tgz#c646e55d67fae623875bf3a06a634dd434904498" @@ -1174,6 +1745,28 @@ micromatch "^4.0.0" p-reduce "^2.0.0" +"@semantic-release/github@9.2.6": + version "9.2.6" + resolved "https://registry.yarnpkg.com/@semantic-release/github/-/github-9.2.6.tgz#0b0b00ab3ab0486cd3aecb4ae2f9f9cf2edd8eae" + integrity sha512-shi+Lrf6exeNZF+sBhK+P011LSbhmIAoUEgEY6SsxF8irJ+J2stwI5jkyDQ+4gzYyDImzV6LCKdYB9FXnQRWKA== + dependencies: + "@octokit/core" "^5.0.0" + "@octokit/plugin-paginate-rest" "^9.0.0" + "@octokit/plugin-retry" "^6.0.0" + "@octokit/plugin-throttling" "^8.0.0" + "@semantic-release/error" "^4.0.0" + aggregate-error "^5.0.0" + debug "^4.3.4" + dir-glob "^3.0.1" + globby "^14.0.0" + http-proxy-agent "^7.0.0" + https-proxy-agent "^7.0.0" + issue-parser "^6.0.0" + lodash-es "^4.17.21" + mime "^4.0.0" + p-filter "^4.0.0" + url-join "^5.0.0" + "@semantic-release/github@^8.0.0": version "8.0.7" resolved "https://registry.yarnpkg.com/@semantic-release/github/-/github-8.0.7.tgz#643aee7a5cdd2acd3ae643bb90ad4ac796901de6" @@ -1196,24 +1789,43 @@ p-retry "^4.0.0" url-join "^4.0.0" -"@semantic-release/npm@^9.0.0": - version "9.0.2" - resolved "https://registry.yarnpkg.com/@semantic-release/npm/-/npm-9.0.2.tgz#0f0903b4df6e93ef237372146bc376087fed4e1d" - integrity sha512-zgsynF6McdzxPnFet+a4iO9HpAlARXOM5adz7VGVCvj0ne8wtL2ZOQoDV2wZPDmdEotDIbVeJjafhelZjs9j6g== +"@semantic-release/npm@11.0.2": + version "11.0.2" + resolved "https://registry.yarnpkg.com/@semantic-release/npm/-/npm-11.0.2.tgz#6d50046df286572718484c9a66b2095277e2f650" + integrity sha512-owtf3RjyPvRE63iUKZ5/xO4uqjRpVQDUB9+nnXj0xwfIeM9pRl+cG+zGDzdftR4m3f2s4Wyf3SexW+kF5DFtWA== + dependencies: + "@semantic-release/error" "^4.0.0" + aggregate-error "^5.0.0" + execa "^8.0.0" + fs-extra "^11.0.0" + lodash-es "^4.17.21" + nerf-dart "^1.0.0" + normalize-url "^8.0.0" + npm "^10.0.0" + rc "^1.2.8" + read-pkg "^9.0.0" + registry-auth-token "^5.0.0" + semver "^7.1.2" + tempy "^3.0.0" + +"@semantic-release/npm@^10.0.2": + version "10.0.2" + resolved "https://registry.yarnpkg.com/@semantic-release/npm/-/npm-10.0.2.tgz#2e3e79a3dae5a12c67e7c314904e536834a87304" + integrity sha512-Mo0XoBza4pUapxiBhLLYXeSZ9tkuHDUd/WvMbpilwuPRfJDnQXMqx5tBVon8d2mBk8JXmXpqB+ExhlWJmVT40A== dependencies: "@semantic-release/error" "^3.0.0" - aggregate-error "^3.0.0" - execa "^5.0.0" + aggregate-error "^4.0.1" + execa "^7.0.0" fs-extra "^11.0.0" - lodash "^4.17.15" + lodash-es "^4.17.21" nerf-dart "^1.0.0" - normalize-url "^6.0.0" - npm "^8.3.0" + normalize-url "^8.0.0" + npm "^9.5.0" rc "^1.2.8" - read-pkg "^5.0.0" + read-pkg "^7.0.0" registry-auth-token "^5.0.0" semver "^7.1.2" - tempy "^1.0.0" + tempy "^3.0.0" "@semantic-release/release-notes-generator@^10.0.0": version "10.0.3" @@ -1231,11 +1843,65 @@ lodash "^4.17.4" read-pkg-up "^7.0.0" +"@sigstore/bundle@^2.1.1": + version "2.1.1" + resolved "https://registry.yarnpkg.com/@sigstore/bundle/-/bundle-2.1.1.tgz#7fad9a1728939301607103722ac6f2a083d2f09a" + integrity sha512-v3/iS+1nufZdKQ5iAlQKcCsoh0jffQyABvYIxKsZQFWc4ubuGjwZklFHpDgV6O6T7vvV78SW5NHI91HFKEcxKg== + dependencies: + "@sigstore/protobuf-specs" "^0.2.1" + +"@sigstore/core@^1.0.0": + version "1.0.0" + resolved "https://registry.yarnpkg.com/@sigstore/core/-/core-1.0.0.tgz#0fcdb32d191d4145a70cb837061185353b3b08e3" + integrity sha512-dW2qjbWLRKGu6MIDUTBuJwXCnR8zivcSpf5inUzk7y84zqy/dji0/uahppoIgMoKeR+6pUZucrwHfkQQtiG9Rw== + +"@sigstore/protobuf-specs@^0.2.1": + version "0.2.1" + resolved "https://registry.yarnpkg.com/@sigstore/protobuf-specs/-/protobuf-specs-0.2.1.tgz#be9ef4f3c38052c43bd399d3f792c97ff9e2277b" + integrity sha512-XTWVxnWJu+c1oCshMLwnKvz8ZQJJDVOlciMfgpJBQbThVjKTCG8dwyhgLngBD2KN0ap9F/gOV8rFDEx8uh7R2A== + +"@sigstore/sign@^2.2.2": + version "2.2.2" + resolved "https://registry.yarnpkg.com/@sigstore/sign/-/sign-2.2.2.tgz#a958388fd20a7c367e20dd3604de3b47cc0b2b47" + integrity sha512-mAifqvvGOCkb5BJ5d/SRrVP5+kKCGxtcHuti6lgqZalIfNxikxlJMMptOqFp9+xV5LAnJMSaMWtzvcgNZ3PlPA== + dependencies: + "@sigstore/bundle" "^2.1.1" + "@sigstore/core" "^1.0.0" + "@sigstore/protobuf-specs" "^0.2.1" + make-fetch-happen "^13.0.0" + +"@sigstore/tuf@^2.3.0": + version "2.3.0" + resolved "https://registry.yarnpkg.com/@sigstore/tuf/-/tuf-2.3.0.tgz#de64925ea10b16f3a7e77535d91eaf22be4dd904" + integrity sha512-S98jo9cpJwO1mtQ+2zY7bOdcYyfVYCUaofCG6wWRzk3pxKHVAkSfshkfecto2+LKsx7Ovtqbgb2LS8zTRhxJ9Q== + dependencies: + "@sigstore/protobuf-specs" "^0.2.1" + tuf-js "^2.2.0" + +"@sigstore/verify@^1.0.0": + version "1.0.0" + resolved "https://registry.yarnpkg.com/@sigstore/verify/-/verify-1.0.0.tgz#0d41688710703fa4252bd25b973234dee5547cdf" + integrity sha512-sRU6nblDBQ4pVTWni019Kij+XQj4RP75WXN5z3qHk81dt/L8A7r3v8RgRInTup4/Jf90WNods9CcbnWj7zJ26w== + dependencies: + "@sigstore/bundle" "^2.1.1" + "@sigstore/core" "^1.0.0" + "@sigstore/protobuf-specs" "^0.2.1" + "@sinclair/typebox@^0.25.16": version "0.25.23" resolved "https://registry.yarnpkg.com/@sinclair/typebox/-/typebox-0.25.23.tgz#1c15b0d2b872d89cc0f47c7243eacb447df8b8bd" integrity sha512-VEB8ygeP42CFLWyAJhN5OklpxUliqdNEUcXb4xZ/CINqtYGTjL5ukluKdKzQ0iWdUxyQ7B0539PAUhHKrCNWSQ== +"@sinclair/typebox@^0.27.8": + version "0.27.8" + resolved "https://registry.yarnpkg.com/@sinclair/typebox/-/typebox-0.27.8.tgz#6667fac16c436b5434a387a34dedb013198f6e6e" + integrity sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA== + +"@sindresorhus/merge-streams@^1.0.0": + version "1.0.0" + resolved "https://registry.yarnpkg.com/@sindresorhus/merge-streams/-/merge-streams-1.0.0.tgz#9cd84cc15bc865a5ca35fcaae198eb899f7b5c90" + integrity sha512-rUV5WyJrJLoloD4NDN1V1+LDMDWOa4OTsT4yYJwQNpTU6FWxkxHpL7eu4w+DmiH8x/EAM1otkPE1+LaspIbplw== + "@sinonjs/commons@^2.0.0": version "2.0.0" resolved "https://registry.yarnpkg.com/@sinonjs/commons/-/commons-2.0.0.tgz#fd4ca5b063554307e8327b4564bd56d3b73924a3" @@ -1255,6 +1921,46 @@ resolved "https://registry.yarnpkg.com/@tootallnate/once/-/once-2.0.0.tgz#f544a148d3ab35801c1f633a7441fd87c2e484bf" integrity sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A== +"@tsconfig/node10@^1.0.7": + version "1.0.9" + resolved "https://registry.yarnpkg.com/@tsconfig/node10/-/node10-1.0.9.tgz#df4907fc07a886922637b15e02d4cebc4c0021b2" + integrity sha512-jNsYVVxU8v5g43Erja32laIDHXeoNvFEpX33OK4d6hljo3jDhCBDhx5dhCCTMWUojscpAagGiRkBKxpdl9fxqA== + +"@tsconfig/node12@^1.0.7": + version "1.0.11" + resolved "https://registry.yarnpkg.com/@tsconfig/node12/-/node12-1.0.11.tgz#ee3def1f27d9ed66dac6e46a295cffb0152e058d" + integrity sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag== + +"@tsconfig/node14@^1.0.0": + version "1.0.3" + resolved "https://registry.yarnpkg.com/@tsconfig/node14/-/node14-1.0.3.tgz#e4386316284f00b98435bf40f72f75a09dabf6c1" + integrity sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow== + +"@tsconfig/node16@^1.0.2": + version "1.0.3" + resolved "https://registry.yarnpkg.com/@tsconfig/node16/-/node16-1.0.3.tgz#472eaab5f15c1ffdd7f8628bd4c4f753995ec79e" + integrity sha512-yOlFc+7UtL/89t2ZhjPvvB/DeAr3r+Dq58IgzsFkOAvVC6NMJXmCGjbptdXdR9qsX7pKcTL+s87FtYREi2dEEQ== + +"@tufjs/canonical-json@2.0.0": + version "2.0.0" + resolved "https://registry.yarnpkg.com/@tufjs/canonical-json/-/canonical-json-2.0.0.tgz#a52f61a3d7374833fca945b2549bc30a2dd40d0a" + integrity sha512-yVtV8zsdo8qFHe+/3kw81dSLyF7D576A5cCFCi4X7B39tWT7SekaEFUnvnWJHz+9qO7qJTah1JbrDjWKqFtdWA== + +"@tufjs/models@1.0.0": + version "1.0.0" + resolved "https://registry.yarnpkg.com/@tufjs/models/-/models-1.0.0.tgz#5a5784e8770b7d014b5f87bff35af1f71fdebf1f" + integrity sha512-RRMu4uMxWnZlxaIBxahSb2IssFZiu188sndesZflWOe1cA/qUqtemSIoBWbuVKPvvdktapImWNnKpBcc+VrCQw== + dependencies: + minimatch "^6.1.0" + +"@tufjs/models@2.0.0": + version "2.0.0" + resolved "https://registry.yarnpkg.com/@tufjs/models/-/models-2.0.0.tgz#c7ab241cf11dd29deb213d6817dabb8c99ce0863" + integrity sha512-c8nj8BaOExmZKO2DXhDfegyhSGcG9E/mPN3U13L+/PsoWm1uaGiHHjxqSHQiasDBQwDA3aHuw9+9spYAP1qvvg== + dependencies: + "@tufjs/canonical-json" "2.0.0" + minimatch "^9.0.3" + "@types/babel__core@^7.1.14": version "7.20.0" resolved "https://registry.yarnpkg.com/@types/babel__core/-/babel__core-7.20.0.tgz#61bc5a4cae505ce98e1e36c5445e4bee060d8891" @@ -1282,61 +1988,16 @@ "@babel/types" "^7.0.0" "@types/babel__traverse@*", "@types/babel__traverse@^7.0.6": - version "7.17.1" - resolved "https://registry.yarnpkg.com/@types/babel__traverse/-/babel__traverse-7.17.1.tgz#1a0e73e8c28c7e832656db372b779bfd2ef37314" - integrity sha512-kVzjari1s2YVi77D3w1yuvohV2idweYXMCDzqBiVNN63TcDWrIlTVOYpqVrvbbyOE/IyzBoTKF0fdnLPEORFxA== + version "7.18.3" + resolved "https://registry.yarnpkg.com/@types/babel__traverse/-/babel__traverse-7.18.3.tgz#dfc508a85781e5698d5b33443416b6268c4b3e8d" + integrity sha512-1kbcJ40lLB7MHsj39U4Sh1uTd2E7rLEa79kmDpI6cy+XiXsteB3POdQomoq4FxszMrO3ZYchkhYJw7A2862b3w== dependencies: "@babel/types" "^7.3.0" -"@types/bech32@1.1.4": - version "1.1.4" - resolved "https://registry.yarnpkg.com/@types/bech32/-/bech32-1.1.4.tgz#501590d41c81a5f1802e39d6be450e89ec6d75d6" - integrity sha512-LWSo7sw6NFc9u7HpMK6aPRa7lNw3NKYAEEQCvdFFLkMCgwzv+0/CySQeqdL9hUIsirThQJ4u6ax/0uKEN63Z2g== - dependencies: - bech32 "*" - -"@types/bn.js@5.1.1": - version "5.1.1" - resolved "https://registry.yarnpkg.com/@types/bn.js/-/bn.js-5.1.1.tgz#b51e1b55920a4ca26e9285ff79936bbdec910682" - integrity sha512-qNrYbZqMx0uJAfKnKclPh+dTwK33KfLHYqtyODwd5HnXOjnkhc4qgn3BrK6RWyGZm5+sIFE7Q7Vz6QQtJB7w7g== - dependencies: - "@types/node" "*" - -"@types/create-hash@1.2.2": - version "1.2.2" - resolved "https://registry.yarnpkg.com/@types/create-hash/-/create-hash-1.2.2.tgz#e87247083df8478f6b83655592bde0d709028235" - integrity sha512-Fg8/kfMJObbETFU/Tn+Y0jieYewryLrbKwLCEIwPyklZZVY2qB+64KFjhplGSw+cseZosfFXctXO+PyIYD8iZQ== - dependencies: - "@types/node" "*" - -"@types/eslint-scope@^3.7.3": - version "3.7.3" - resolved "https://registry.yarnpkg.com/@types/eslint-scope/-/eslint-scope-3.7.3.tgz#125b88504b61e3c8bc6f870882003253005c3224" - integrity sha512-PB3ldyrcnAicT35TWPs5IcwKD8S333HMaa2VVv4+wdvebJkjWuW/xESoB8IwRcog8HYVYamb1g/R31Qv5Bx03g== - dependencies: - "@types/eslint" "*" - "@types/estree" "*" - -"@types/eslint@*": - version "8.4.2" - resolved "https://registry.yarnpkg.com/@types/eslint/-/eslint-8.4.2.tgz#48f2ac58ab9c631cb68845c3d956b28f79fad575" - integrity sha512-Z1nseZON+GEnFjJc04sv4NSALGjhFwy6K0HXt7qsn5ArfAKtb63dXNJHf+1YW6IpOIYRBGUbu3GwJdj8DGnCjA== - dependencies: - "@types/estree" "*" - "@types/json-schema" "*" - -"@types/estree@*", "@types/estree@^0.0.51": - version "0.0.51" - resolved "https://registry.yarnpkg.com/@types/estree/-/estree-0.0.51.tgz#cfd70924a25a3fd32b218e5e420e6897e1ac4f40" - integrity sha512-CuPgU6f3eT/XgKKPqKd/gLZV1Xmvf1a2R5POBOGQa6uv82xpls89HU5zKeVoyR8XzHd1RGNOlQlvUe3CFkjWNQ== - -"@types/glob@^7.1.1": - version "7.2.0" - resolved "https://registry.yarnpkg.com/@types/glob/-/glob-7.2.0.tgz#bc1b5bf3aa92f25bd5dd39f35c57361bdce5b2eb" - integrity sha512-ZUxbzKl0IfJILTS6t7ip5fQQM/J3TJYubDm3nMbgubNNYS62eXeUpoLUC8/7fJNiFYHTrGPQn7hspDUzIHX3UA== - dependencies: - "@types/minimatch" "*" - "@types/node" "*" +"@types/estree@1.0.5", "@types/estree@^1.0.0": + version "1.0.5" + resolved "https://registry.yarnpkg.com/@types/estree/-/estree-1.0.5.tgz#a6ce3e556e00fd9895dd872dd172ad0d4bd687f4" + integrity sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw== "@types/graceful-fs@^4.1.3": version "4.1.6" @@ -1345,18 +2006,6 @@ dependencies: "@types/node" "*" -"@types/hdkey@2.0.1": - version "2.0.1" - resolved "https://registry.yarnpkg.com/@types/hdkey/-/hdkey-2.0.1.tgz#ab46597562d977b229704c7f19949953b936b6a3" - integrity sha512-4s6jhP0BT3sWBaRo0BfA3BpFllQvuRlXUzIqnuvSNmPhmMCZYjhrDe31nJb8kJLc0ZVdqj9Ep9eH2RGBNCK9Sw== - dependencies: - "@types/node" "*" - -"@types/html-minifier-terser@^6.0.0": - version "6.1.0" - resolved "https://registry.yarnpkg.com/@types/html-minifier-terser/-/html-minifier-terser-6.1.0.tgz#4fc33a00c1d0c16987b1a20cf92d20614c55ac35" - integrity sha512-oh/6byDPnL1zeNXFrDXFLyZjkr1MsBG667IM792caf1L2UPOOMf65NFzjUH/ltyfwjAGfs1rsX1eftK0jC/KIg== - "@types/istanbul-lib-coverage@*", "@types/istanbul-lib-coverage@^2.0.0", "@types/istanbul-lib-coverage@^2.0.1": version "2.0.4" resolved "https://registry.yarnpkg.com/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.4.tgz#8467d4b3c087805d63580480890791277ce35c44" @@ -1376,63 +2025,65 @@ dependencies: "@types/istanbul-lib-report" "*" -"@types/jest@29.4.0": - version "29.4.0" - resolved "https://registry.yarnpkg.com/@types/jest/-/jest-29.4.0.tgz#a8444ad1704493e84dbf07bb05990b275b3b9206" - integrity sha512-VaywcGQ9tPorCX/Jkkni7RWGFfI11whqzs8dvxF41P17Z+z872thvEvlIbznjPJ02kl1HMX3LmLOonsj2n7HeQ== +"@types/jest@29.5.11": + version "29.5.11" + resolved "https://registry.yarnpkg.com/@types/jest/-/jest-29.5.11.tgz#0c13aa0da7d0929f078ab080ae5d4ced80fa2f2c" + integrity sha512-S2mHmYIVe13vrm6q4kN6fLYYAka15ALQki/vgDC3mIukEOx8WJlv0kQPM+d4w8Gp6u0uSdKND04IlTXBv0rwnQ== dependencies: expect "^29.0.0" pretty-format "^29.0.0" -"@types/json-schema@*", "@types/json-schema@^7.0.8", "@types/json-schema@^7.0.9": - version "7.0.11" - resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.11.tgz#d421b6c527a3037f7c84433fd2c4229e016863d3" - integrity sha512-wOuvG1SN4Us4rez+tylwwwCV1psiNVOkJeM3AUWUNWg/jDQY2+HE/444y5gc+jBmRqASOm2Oeh5c1axHobwRKQ== - -"@types/minimatch@*": - version "3.0.5" - resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-3.0.5.tgz#1001cc5e6a3704b83c236027e77f2f58ea010f40" - integrity sha512-Klz949h02Gz2uZCMGwDUSDS1YBlTdDDgbWHi+81l29tQALUtvz4rAYi5uoVhE5Lagoq6DeqAUlbrHvW/mXDgdQ== +"@types/json-schema@^7.0.12": + version "7.0.15" + resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.15.tgz#596a1747233694d50f6ad8a7869fcb6f56cf5841" + integrity sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA== "@types/minimist@^1.2.0": version "1.2.2" resolved "https://registry.yarnpkg.com/@types/minimist/-/minimist-1.2.2.tgz#ee771e2ba4b3dc5b372935d549fd9617bf345b8c" integrity sha512-jhuKLIRrhvCPLqwPcx6INqmKeiA5EWrsCOPhrlFSrbrmU4ZMPjj5Ul/oLCMDO98XRUIwVm78xICz4EPCektzeQ== -"@types/node@*": - version "17.0.31" - resolved "https://registry.yarnpkg.com/@types/node/-/node-17.0.31.tgz#a5bb84ecfa27eec5e1c802c6bbf8139bdb163a5d" - integrity sha512-AR0x5HbXGqkEx9CadRH3EBYx/VkiUgZIhP4wvPn/+5KIsgpNoyFaRlVe0Zlx9gRtg8fA06a9tskE2MSN7TcG4Q== +"@types/node@*", "@types/node@20.4.7": + version "20.4.7" + resolved "https://registry.yarnpkg.com/@types/node/-/node-20.4.7.tgz#74d323a93f1391a63477b27b9aec56669c98b2ab" + integrity sha512-bUBrPjEry2QUTsnuEjzjbS7voGWCc30W0qzgMf90GPeDGFRakvrz47ju+oqDAKCXLUCe39u57/ORMl/O/04/9g== + +"@types/node@18.15.13": + version "18.15.13" + resolved "https://registry.yarnpkg.com/@types/node/-/node-18.15.13.tgz#f64277c341150c979e42b00e4ac289290c9df469" + integrity sha512-N+0kuo9KgrUQ1Sn/ifDXsvg0TTleP7rIy4zOBGECxAljqvqfqpTfzx0Q1NUedOixRMBfe2Whhb056a42cWs26Q== -"@types/node@18.14.2": - version "18.14.2" - resolved "https://registry.yarnpkg.com/@types/node/-/node-18.14.2.tgz#c076ed1d7b6095078ad3cf21dfeea951842778b1" - integrity sha512-1uEQxww3DaghA0RxqHx0O0ppVlo43pJhepY51OxuQIKHpjbnYLA7vcdwioNPzIqmC2u3I/dmylcqjlh0e7AyUA== +"@types/node@20.11.10": + version "20.11.10" + resolved "https://registry.yarnpkg.com/@types/node/-/node-20.11.10.tgz#6c3de8974d65c362f82ee29db6b5adf4205462f9" + integrity sha512-rZEfe/hJSGYmdfX9tvcPMYeYPW2sNl50nsw4jZmRcaG0HIAb0WYEpsB05GOb53vjqpyE9GUhlDQ4jLSoB5q9kg== + dependencies: + undici-types "~5.26.4" -"@types/normalize-package-data@^2.4.0": +"@types/normalize-package-data@^2.4.0", "@types/normalize-package-data@^2.4.1": version "2.4.1" resolved "https://registry.yarnpkg.com/@types/normalize-package-data/-/normalize-package-data-2.4.1.tgz#d3357479a0fdfdd5907fe67e17e0a85c906e1301" integrity sha512-Gj7cI7z+98M282Tqmp2K5EIsoouUEzbBJhQQzDE3jSIRk6r9gsz0oUokqIUR4u1R3dMHo0pDHM7sNOHyhulypw== -"@types/parse-json@^4.0.0": - version "4.0.0" - resolved "https://registry.yarnpkg.com/@types/parse-json/-/parse-json-4.0.0.tgz#2f8bb441434d163b35fb8ffdccd7138927ffb8c0" - integrity sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA== +"@types/normalize-package-data@^2.4.3": + version "2.4.4" + resolved "https://registry.yarnpkg.com/@types/normalize-package-data/-/normalize-package-data-2.4.4.tgz#56e2cc26c397c038fab0e3a917a12d5c5909e901" + integrity sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA== -"@types/prettier@^2.1.5": - version "2.7.2" - resolved "https://registry.yarnpkg.com/@types/prettier/-/prettier-2.7.2.tgz#6c2324641cc4ba050a8c710b2b251b377581fbf0" - integrity sha512-KufADq8uQqo1pYKVIYzfKbJfBAc0sOeXqGbFaSpv8MRmC/zXgowNZmFcbngndGk922QDmOASEXUZCaY48gs4cg== +"@types/resolve@1.20.2": + version "1.20.2" + resolved "https://registry.yarnpkg.com/@types/resolve/-/resolve-1.20.2.tgz#97d26e00cd4a0423b4af620abecf3e6f442b7975" + integrity sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q== "@types/retry@0.12.0": version "0.12.0" resolved "https://registry.yarnpkg.com/@types/retry/-/retry-0.12.0.tgz#2b35eccfcee7d38cd72ad99232fbd58bffb3c84d" integrity sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA== -"@types/semver@^7.3.12": - version "7.3.13" - resolved "https://registry.yarnpkg.com/@types/semver/-/semver-7.3.13.tgz#da4bfd73f49bd541d28920ab0e2bf0ee80f71c91" - integrity sha512-21cFJr9z3g5dW8B0CVI9g2O9beqaThGQ6ZFBqHfwhzLDKUxaqTIy3vnfah/UPkfOiF2pLq+tGz+W8RyCskuslw== +"@types/semver@^7.5.0": + version "7.5.6" + resolved "https://registry.yarnpkg.com/@types/semver/-/semver-7.5.6.tgz#c65b2bfce1bec346582c07724e3f8c1017a20339" + integrity sha512-dn1l8LaMea/IjDoHNd9J52uBbInB796CDffS6VdIxvqYCPSG0V0DzHp76GpaWnlhg88uYyPbXCDIowa86ybd5A== "@types/stack-utils@^2.0.0": version "2.0.1" @@ -1451,239 +2102,93 @@ dependencies: "@types/yargs-parser" "*" -"@typescript-eslint/eslint-plugin@5.54.0": - version "5.54.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.54.0.tgz#2c821ad81b2c786d142279a8292090f77d1881f4" - integrity sha512-+hSN9BdSr629RF02d7mMtXhAJvDTyCbprNYJKrXETlul/Aml6YZwd90XioVbjejQeHbb3R8Dg0CkRgoJDxo8aw== +"@typescript-eslint/eslint-plugin@6.18.1": + version "6.18.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.18.1.tgz#0df881a47da1c1a9774f39495f5f7052f86b72e0" + integrity sha512-nISDRYnnIpk7VCFrGcu1rnZfM1Dh9LRHnfgdkjcbi/l7g16VYRri3TjXi9Ir4lOZSw5N/gnV/3H7jIPQ8Q4daA== dependencies: - "@typescript-eslint/scope-manager" "5.54.0" - "@typescript-eslint/type-utils" "5.54.0" - "@typescript-eslint/utils" "5.54.0" + "@eslint-community/regexpp" "^4.5.1" + "@typescript-eslint/scope-manager" "6.18.1" + "@typescript-eslint/type-utils" "6.18.1" + "@typescript-eslint/utils" "6.18.1" + "@typescript-eslint/visitor-keys" "6.18.1" debug "^4.3.4" - grapheme-splitter "^1.0.4" - ignore "^5.2.0" - natural-compare-lite "^1.4.0" - regexpp "^3.2.0" - semver "^7.3.7" - tsutils "^3.21.0" - -"@typescript-eslint/parser@5.54.0": - version "5.54.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-5.54.0.tgz#def186eb1b1dbd0439df0dacc44fb6d8d5c417fe" - integrity sha512-aAVL3Mu2qTi+h/r04WI/5PfNWvO6pdhpeMRWk9R7rEV4mwJNzoWf5CCU5vDKBsPIFQFjEq1xg7XBI2rjiMXQbQ== - dependencies: - "@typescript-eslint/scope-manager" "5.54.0" - "@typescript-eslint/types" "5.54.0" - "@typescript-eslint/typescript-estree" "5.54.0" + graphemer "^1.4.0" + ignore "^5.2.4" + natural-compare "^1.4.0" + semver "^7.5.4" + ts-api-utils "^1.0.1" + +"@typescript-eslint/parser@6.18.1": + version "6.18.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-6.18.1.tgz#3c3987e186b38c77b30b6bfa5edf7c98ae2ec9d3" + integrity sha512-zct/MdJnVaRRNy9e84XnVtRv9Vf91/qqe+hZJtKanjojud4wAVy/7lXxJmMyX6X6J+xc6c//YEWvpeif8cAhWA== + dependencies: + "@typescript-eslint/scope-manager" "6.18.1" + "@typescript-eslint/types" "6.18.1" + "@typescript-eslint/typescript-estree" "6.18.1" + "@typescript-eslint/visitor-keys" "6.18.1" debug "^4.3.4" -"@typescript-eslint/scope-manager@5.54.0": - version "5.54.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-5.54.0.tgz#74b28ac9a3fc8166f04e806c957adb8c1fd00536" - integrity sha512-VTPYNZ7vaWtYna9M4oD42zENOBrb+ZYyCNdFs949GcN8Miwn37b8b7eMj+EZaq7VK9fx0Jd+JhmkhjFhvnovhg== +"@typescript-eslint/scope-manager@6.18.1": + version "6.18.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-6.18.1.tgz#28c31c60f6e5827996aa3560a538693cb4bd3848" + integrity sha512-BgdBwXPFmZzaZUuw6wKiHKIovms97a7eTImjkXCZE04TGHysG+0hDQPmygyvgtkoB/aOQwSM/nWv3LzrOIQOBw== dependencies: - "@typescript-eslint/types" "5.54.0" - "@typescript-eslint/visitor-keys" "5.54.0" + "@typescript-eslint/types" "6.18.1" + "@typescript-eslint/visitor-keys" "6.18.1" -"@typescript-eslint/type-utils@5.54.0": - version "5.54.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/type-utils/-/type-utils-5.54.0.tgz#390717216eb61393a0cad2995da154b613ba7b26" - integrity sha512-WI+WMJ8+oS+LyflqsD4nlXMsVdzTMYTxl16myXPaCXnSgc7LWwMsjxQFZCK/rVmTZ3FN71Ct78ehO9bRC7erYQ== +"@typescript-eslint/type-utils@6.18.1": + version "6.18.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/type-utils/-/type-utils-6.18.1.tgz#115cf535f8b39db8301677199ce51151e2daee96" + integrity sha512-wyOSKhuzHeU/5pcRDP2G2Ndci+4g653V43gXTpt4nbyoIOAASkGDA9JIAgbQCdCkcr1MvpSYWzxTz0olCn8+/Q== dependencies: - "@typescript-eslint/typescript-estree" "5.54.0" - "@typescript-eslint/utils" "5.54.0" + "@typescript-eslint/typescript-estree" "6.18.1" + "@typescript-eslint/utils" "6.18.1" debug "^4.3.4" - tsutils "^3.21.0" + ts-api-utils "^1.0.1" -"@typescript-eslint/types@5.54.0": - version "5.54.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-5.54.0.tgz#7d519df01f50739254d89378e0dcac504cab2740" - integrity sha512-nExy+fDCBEgqblasfeE3aQ3NuafBUxZxgxXcYfzYRZFHdVvk5q60KhCSkG0noHgHRo/xQ/BOzURLZAafFpTkmQ== +"@typescript-eslint/types@6.18.1": + version "6.18.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-6.18.1.tgz#91617d8080bcd99ac355d9157079970d1d49fefc" + integrity sha512-4TuMAe+tc5oA7wwfqMtB0Y5OrREPF1GeJBAjqwgZh1lEMH5PJQgWgHGfYufVB51LtjD+peZylmeyxUXPfENLCw== -"@typescript-eslint/typescript-estree@5.54.0": - version "5.54.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-5.54.0.tgz#f6f3440cabee8a43a0b25fa498213ebb61fdfe99" - integrity sha512-X2rJG97Wj/VRo5YxJ8Qx26Zqf0RRKsVHd4sav8NElhbZzhpBI8jU54i6hfo9eheumj4oO4dcRN1B/zIVEqR/MQ== +"@typescript-eslint/typescript-estree@6.18.1": + version "6.18.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-6.18.1.tgz#a12b6440175b4cbc9d09ab3c4966c6b245215ab4" + integrity sha512-fv9B94UAhywPRhUeeV/v+3SBDvcPiLxRZJw/xZeeGgRLQZ6rLMG+8krrJUyIf6s1ecWTzlsbp0rlw7n9sjufHA== dependencies: - "@typescript-eslint/types" "5.54.0" - "@typescript-eslint/visitor-keys" "5.54.0" + "@typescript-eslint/types" "6.18.1" + "@typescript-eslint/visitor-keys" "6.18.1" debug "^4.3.4" globby "^11.1.0" is-glob "^4.0.3" - semver "^7.3.7" - tsutils "^3.21.0" - -"@typescript-eslint/utils@5.54.0": - version "5.54.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/utils/-/utils-5.54.0.tgz#3db758aae078be7b54b8ea8ea4537ff6cd3fbc21" - integrity sha512-cuwm8D/Z/7AuyAeJ+T0r4WZmlnlxQ8wt7C7fLpFlKMR+dY6QO79Cq1WpJhvZbMA4ZeZGHiRWnht7ZJ8qkdAunw== - dependencies: - "@types/json-schema" "^7.0.9" - "@types/semver" "^7.3.12" - "@typescript-eslint/scope-manager" "5.54.0" - "@typescript-eslint/types" "5.54.0" - "@typescript-eslint/typescript-estree" "5.54.0" - eslint-scope "^5.1.1" - eslint-utils "^3.0.0" - semver "^7.3.7" - -"@typescript-eslint/visitor-keys@5.54.0": - version "5.54.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-5.54.0.tgz#846878afbf0cd67c19cfa8d75947383d4490db8f" - integrity sha512-xu4wT7aRCakGINTLGeyGqDn+78BwFlggwBjnHa1ar/KaGagnmwLYmlrXIrgAaQ3AE1Vd6nLfKASm7LrFHNbKGA== - dependencies: - "@typescript-eslint/types" "5.54.0" - eslint-visitor-keys "^3.3.0" - -"@webassemblyjs/ast@1.11.1": - version "1.11.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/ast/-/ast-1.11.1.tgz#2bfd767eae1a6996f432ff7e8d7fc75679c0b6a7" - integrity sha512-ukBh14qFLjxTQNTXocdyksN5QdM28S1CxHt2rdskFyL+xFV7VremuBLVbmCePj+URalXBENx/9Lm7lnhihtCSw== - dependencies: - "@webassemblyjs/helper-numbers" "1.11.1" - "@webassemblyjs/helper-wasm-bytecode" "1.11.1" - -"@webassemblyjs/floating-point-hex-parser@1.11.1": - version "1.11.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.11.1.tgz#f6c61a705f0fd7a6aecaa4e8198f23d9dc179e4f" - integrity sha512-iGRfyc5Bq+NnNuX8b5hwBrRjzf0ocrJPI6GWFodBFzmFnyvrQ83SHKhmilCU/8Jv67i4GJZBMhEzltxzcNagtQ== - -"@webassemblyjs/helper-api-error@1.11.1": - version "1.11.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-api-error/-/helper-api-error-1.11.1.tgz#1a63192d8788e5c012800ba6a7a46c705288fd16" - integrity sha512-RlhS8CBCXfRUR/cwo2ho9bkheSXG0+NwooXcc3PAILALf2QLdFyj7KGsKRbVc95hZnhnERon4kW/D3SZpp6Tcg== - -"@webassemblyjs/helper-buffer@1.11.1": - version "1.11.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-buffer/-/helper-buffer-1.11.1.tgz#832a900eb444884cde9a7cad467f81500f5e5ab5" - integrity sha512-gwikF65aDNeeXa8JxXa2BAk+REjSyhrNC9ZwdT0f8jc4dQQeDQ7G4m0f2QCLPJiMTTO6wfDmRmj/pW0PsUvIcA== - -"@webassemblyjs/helper-numbers@1.11.1": - version "1.11.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-numbers/-/helper-numbers-1.11.1.tgz#64d81da219fbbba1e3bd1bfc74f6e8c4e10a62ae" - integrity sha512-vDkbxiB8zfnPdNK9Rajcey5C0w+QJugEglN0of+kmO8l7lDb77AnlKYQF7aarZuCrv+l0UvqL+68gSDr3k9LPQ== - dependencies: - "@webassemblyjs/floating-point-hex-parser" "1.11.1" - "@webassemblyjs/helper-api-error" "1.11.1" - "@xtuc/long" "4.2.2" - -"@webassemblyjs/helper-wasm-bytecode@1.11.1": - version "1.11.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.11.1.tgz#f328241e41e7b199d0b20c18e88429c4433295e1" - integrity sha512-PvpoOGiJwXeTrSf/qfudJhwlvDQxFgelbMqtq52WWiXC6Xgg1IREdngmPN3bs4RoO83PnL/nFrxucXj1+BX62Q== - -"@webassemblyjs/helper-wasm-section@1.11.1": - version "1.11.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.11.1.tgz#21ee065a7b635f319e738f0dd73bfbda281c097a" - integrity sha512-10P9No29rYX1j7F3EVPX3JvGPQPae+AomuSTPiF9eBQeChHI6iqjMIwR9JmOJXwpnn/oVGDk7I5IlskuMwU/pg== - dependencies: - "@webassemblyjs/ast" "1.11.1" - "@webassemblyjs/helper-buffer" "1.11.1" - "@webassemblyjs/helper-wasm-bytecode" "1.11.1" - "@webassemblyjs/wasm-gen" "1.11.1" - -"@webassemblyjs/ieee754@1.11.1": - version "1.11.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/ieee754/-/ieee754-1.11.1.tgz#963929e9bbd05709e7e12243a099180812992614" - integrity sha512-hJ87QIPtAMKbFq6CGTkZYJivEwZDbQUgYd3qKSadTNOhVY7p+gfP6Sr0lLRVTaG1JjFj+r3YchoqRYxNH3M0GQ== - dependencies: - "@xtuc/ieee754" "^1.2.0" - -"@webassemblyjs/leb128@1.11.1": - version "1.11.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/leb128/-/leb128-1.11.1.tgz#ce814b45574e93d76bae1fb2644ab9cdd9527aa5" - integrity sha512-BJ2P0hNZ0u+Th1YZXJpzW6miwqQUGcIHT1G/sf72gLVD9DZ5AdYTqPNbHZh6K1M5VmKvFXwGSWZADz+qBWxeRw== - dependencies: - "@xtuc/long" "4.2.2" - -"@webassemblyjs/utf8@1.11.1": - version "1.11.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/utf8/-/utf8-1.11.1.tgz#d1f8b764369e7c6e6bae350e854dec9a59f0a3ff" - integrity sha512-9kqcxAEdMhiwQkHpkNiorZzqpGrodQQ2IGrHHxCy+Ozng0ofyMA0lTqiLkVs1uzTRejX+/O0EOT7KxqVPuXosQ== - -"@webassemblyjs/wasm-edit@1.11.1": - version "1.11.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-edit/-/wasm-edit-1.11.1.tgz#ad206ebf4bf95a058ce9880a8c092c5dec8193d6" - integrity sha512-g+RsupUC1aTHfR8CDgnsVRVZFJqdkFHpsHMfJuWQzWU3tvnLC07UqHICfP+4XyL2tnr1amvl1Sdp06TnYCmVkA== - dependencies: - "@webassemblyjs/ast" "1.11.1" - "@webassemblyjs/helper-buffer" "1.11.1" - "@webassemblyjs/helper-wasm-bytecode" "1.11.1" - "@webassemblyjs/helper-wasm-section" "1.11.1" - "@webassemblyjs/wasm-gen" "1.11.1" - "@webassemblyjs/wasm-opt" "1.11.1" - "@webassemblyjs/wasm-parser" "1.11.1" - "@webassemblyjs/wast-printer" "1.11.1" - -"@webassemblyjs/wasm-gen@1.11.1": - version "1.11.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-gen/-/wasm-gen-1.11.1.tgz#86c5ea304849759b7d88c47a32f4f039ae3c8f76" - integrity sha512-F7QqKXwwNlMmsulj6+O7r4mmtAlCWfO/0HdgOxSklZfQcDu0TpLiD1mRt/zF25Bk59FIjEuGAIyn5ei4yMfLhA== - dependencies: - "@webassemblyjs/ast" "1.11.1" - "@webassemblyjs/helper-wasm-bytecode" "1.11.1" - "@webassemblyjs/ieee754" "1.11.1" - "@webassemblyjs/leb128" "1.11.1" - "@webassemblyjs/utf8" "1.11.1" - -"@webassemblyjs/wasm-opt@1.11.1": - version "1.11.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-opt/-/wasm-opt-1.11.1.tgz#657b4c2202f4cf3b345f8a4c6461c8c2418985f2" - integrity sha512-VqnkNqnZlU5EB64pp1l7hdm3hmQw7Vgqa0KF/KCNO9sIpI6Fk6brDEiX+iCOYrvMuBWDws0NkTOxYEb85XQHHw== - dependencies: - "@webassemblyjs/ast" "1.11.1" - "@webassemblyjs/helper-buffer" "1.11.1" - "@webassemblyjs/wasm-gen" "1.11.1" - "@webassemblyjs/wasm-parser" "1.11.1" - -"@webassemblyjs/wasm-parser@1.11.1": - version "1.11.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/wasm-parser/-/wasm-parser-1.11.1.tgz#86ca734534f417e9bd3c67c7a1c75d8be41fb199" - integrity sha512-rrBujw+dJu32gYB7/Lup6UhdkPx9S9SnobZzRVL7VcBH9Bt9bCBLEuX/YXOOtBsOZ4NQrRykKhffRWHvigQvOA== - dependencies: - "@webassemblyjs/ast" "1.11.1" - "@webassemblyjs/helper-api-error" "1.11.1" - "@webassemblyjs/helper-wasm-bytecode" "1.11.1" - "@webassemblyjs/ieee754" "1.11.1" - "@webassemblyjs/leb128" "1.11.1" - "@webassemblyjs/utf8" "1.11.1" - -"@webassemblyjs/wast-printer@1.11.1": - version "1.11.1" - resolved "https://registry.yarnpkg.com/@webassemblyjs/wast-printer/-/wast-printer-1.11.1.tgz#d0c73beda8eec5426f10ae8ef55cee5e7084c2f0" - integrity sha512-IQboUWM4eKzWW+N/jij2sRatKMh99QEelo3Eb2q0qXkvPRISAj8Qxtmw5itwqK+TTkBuUIE45AxYPToqPtL5gg== - dependencies: - "@webassemblyjs/ast" "1.11.1" - "@xtuc/long" "4.2.2" - -"@webpack-cli/configtest@^1.2.0": - version "1.2.0" - resolved "https://registry.yarnpkg.com/@webpack-cli/configtest/-/configtest-1.2.0.tgz#7b20ce1c12533912c3b217ea68262365fa29a6f5" - integrity sha512-4FB8Tj6xyVkyqjj1OaTqCjXYULB9FMkqQ8yGrZjRDrYh0nOE+7Lhs45WioWQQMV+ceFlE368Ukhe6xdvJM9Egg== - -"@webpack-cli/info@^1.5.0": - version "1.5.0" - resolved "https://registry.yarnpkg.com/@webpack-cli/info/-/info-1.5.0.tgz#6c78c13c5874852d6e2dd17f08a41f3fe4c261b1" - integrity sha512-e8tSXZpw2hPl2uMJY6fsMswaok5FdlGNRTktvFk2sD8RjH0hE2+XistawJx1vmKteh4NmGmNUrp+Tb2w+udPcQ== - dependencies: - envinfo "^7.7.3" - -"@webpack-cli/serve@^1.7.0": - version "1.7.0" - resolved "https://registry.yarnpkg.com/@webpack-cli/serve/-/serve-1.7.0.tgz#e1993689ac42d2b16e9194376cfb6753f6254db1" - integrity sha512-oxnCNGj88fL+xzV+dacXs44HcDwf1ovs3AuEzvP7mqXw7fQntqIhQ1BRmynh4qEKQSSSRSWVyXRjmTbZIX9V2Q== - -"@xtuc/ieee754@^1.2.0": - version "1.2.0" - resolved "https://registry.yarnpkg.com/@xtuc/ieee754/-/ieee754-1.2.0.tgz#eef014a3145ae477a1cbc00cd1e552336dceb790" - integrity sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA== - -"@xtuc/long@4.2.2": - version "4.2.2" - resolved "https://registry.yarnpkg.com/@xtuc/long/-/long-4.2.2.tgz#d291c6a4e97989b5c61d9acf396ae4fe133a718d" - integrity sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ== - -JSONStream@^1.0.4: + minimatch "9.0.3" + semver "^7.5.4" + ts-api-utils "^1.0.1" + +"@typescript-eslint/utils@6.18.1": + version "6.18.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/utils/-/utils-6.18.1.tgz#3451cfe2e56babb6ac657e10b6703393d4b82955" + integrity sha512-zZmTuVZvD1wpoceHvoQpOiewmWu3uP9FuTWo8vqpy2ffsmfCE8mklRPi+vmnIYAIk9t/4kOThri2QCDgor+OpQ== + dependencies: + "@eslint-community/eslint-utils" "^4.4.0" + "@types/json-schema" "^7.0.12" + "@types/semver" "^7.5.0" + "@typescript-eslint/scope-manager" "6.18.1" + "@typescript-eslint/types" "6.18.1" + "@typescript-eslint/typescript-estree" "6.18.1" + semver "^7.5.4" + +"@typescript-eslint/visitor-keys@6.18.1": + version "6.18.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-6.18.1.tgz#704d789bda2565a15475e7d22f145b8fe77443f4" + integrity sha512-/kvt0C5lRqGoCfsbmm7/CwMqoSkY3zzHLIjdhHZQW3VFrnz7ATecOHR7nb7V+xn4286MBxfnQfQhAmCI0u+bJA== + dependencies: + "@typescript-eslint/types" "6.18.1" + eslint-visitor-keys "^3.4.1" + +JSONStream@^1.0.4, JSONStream@^1.3.5: version "1.3.5" resolved "https://registry.yarnpkg.com/JSONStream/-/JSONStream-1.3.5.tgz#3208c1f08d3a4d99261ab64f92302bc15e111ca0" integrity sha512-E+iruNOY8VV9s4JEbe1aNEm6MiszPRr/UfcHMz0TQh1BXSxHK+ASV1R6W4HpjBhSeS+54PIsAMCBmwD06LLsqQ== @@ -1691,35 +2196,42 @@ JSONStream@^1.0.4: jsonparse "^1.2.0" through ">=2.2.7 <3" -abbrev@^1.0.0, abbrev@~1.1.1: +abbrev@^1.0.0: version "1.1.1" resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-1.1.1.tgz#f8f2c887ad10bf67f634f005b6987fed3179aac8" integrity sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q== -acorn-import-assertions@^1.7.6: - version "1.8.0" - resolved "https://registry.yarnpkg.com/acorn-import-assertions/-/acorn-import-assertions-1.8.0.tgz#ba2b5939ce62c238db6d93d81c9b111b29b855e9" - integrity sha512-m7VZ3jwz4eK6A4Vtt8Ew1/mNbP24u0FhdyfA7fSvnJR6LMdfOYnmuIrrJAgrYfYJ10F/otaHTtrtrtmHdMNzEw== +abbrev@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-2.0.0.tgz#cf59829b8b4f03f89dda2771cb7f3653828c89bf" + integrity sha512-6/mh1E2u2YgEsCHdY0Yx5oW+61gZU+1vXaoiHHrpKeuRNNgFvS+/jrwHiQhB5apAf5oB7UB7E19ol2R2LKH8hQ== + +abort-controller@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/abort-controller/-/abort-controller-3.0.0.tgz#eaf54d53b62bae4138e809ca225c8439a6efb392" + integrity sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg== + dependencies: + event-target-shim "^5.0.0" -acorn-jsx@^5.3.1: +acorn-jsx@^5.3.2: version "5.3.2" resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.3.2.tgz#7ed5bb55908b3b2f1bc55c6af1653bada7f07937" integrity sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ== -acorn@^7.4.0: - version "7.4.1" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-7.4.1.tgz#feaed255973d2e77555b83dbc08851a6c63520fa" - integrity sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A== +acorn-walk@^8.1.1: + version "8.2.0" + resolved "https://registry.yarnpkg.com/acorn-walk/-/acorn-walk-8.2.0.tgz#741210f2e2426454508853a2f44d0ab83b7f69c1" + integrity sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA== -acorn@^8.5.0, acorn@^8.7.1: - version "8.8.0" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.8.0.tgz#88c0187620435c7f6015803f5539dae05a9dbea8" - integrity sha512-QOxyigPVrpZ2GXT+PFyZTl6TtOFc5egxHIP9IlQ+RbupQuX4RkT/Bee4/kQuC02Xkzg84JcT7oLYtDIQxp+v7w== +acorn@^8.4.1, acorn@^8.5.0, acorn@^8.8.2, acorn@^8.9.0: + version "8.10.0" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.10.0.tgz#8be5b3907a67221a81ab23c7889c4c5526b62ec5" + integrity sha512-F0SAmZ8iUtS//m8DmCTA0jlh6TDKkHQyK6xc6V4KDTyZKA9dnvX9/3sRTVQrWm79glUAZbnmmNcdYwUIHWVybw== -aes-js@4.0.0-beta.3: - version "4.0.0-beta.3" - resolved "https://registry.yarnpkg.com/aes-js/-/aes-js-4.0.0-beta.3.tgz#da2253f0ff03a0b3a9e445c8cbdf78e7fda7d48c" - integrity sha512-/xJX0/VTPcbc5xQE2VUP91y1xN8q/rDfhEzLm+vLc3hYvb5+qHCnpJRuFcrKn63zumK/sCwYYzhG8HP78JYSTA== +aes-js@4.0.0-beta.5: + version "4.0.0-beta.5" + resolved "https://registry.yarnpkg.com/aes-js/-/aes-js-4.0.0-beta.5.tgz#8d2452c52adedebc3a3e28465d858c11ca315873" + integrity sha512-G965FqalsNyrPqgEGON7nIx1e/OVENSgiEIzyC63haUMuvNnwIgIjMs52hlTCKhkBny7A2ORNlfY9Zu+jmGk1Q== agent-base@6, agent-base@^6.0.2: version "6.0.2" @@ -1728,6 +2240,13 @@ agent-base@6, agent-base@^6.0.2: dependencies: debug "4" +agent-base@^7.0.2, agent-base@^7.1.0: + version "7.1.0" + resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-7.1.0.tgz#536802b76bc0b34aa50195eb2442276d613e3434" + integrity sha512-o/zjMZRhJxny7OyEF+Op8X+efiELC7k7yOjMzgfzVqOzXqkBkWI79YoTdOtsuWd5BWhAGAuOY/Xa6xpiaWXiNg== + dependencies: + debug "^4.3.4" + agentkeepalive@^4.2.1: version "4.2.1" resolved "https://registry.yarnpkg.com/agentkeepalive/-/agentkeepalive-4.2.1.tgz#a7975cbb9f83b367f06c90cc51ff28fe7d499717" @@ -1745,12 +2264,23 @@ aggregate-error@^3.0.0: clean-stack "^2.0.0" indent-string "^4.0.0" -ajv-keywords@^3.5.2: - version "3.5.2" - resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-3.5.2.tgz#31f29da5ab6e00d1c2d329acf7b5929614d5014d" - integrity sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ== +aggregate-error@^4.0.1: + version "4.0.1" + resolved "https://registry.yarnpkg.com/aggregate-error/-/aggregate-error-4.0.1.tgz#25091fe1573b9e0be892aeda15c7c66a545f758e" + integrity sha512-0poP0T7el6Vq3rstR8Mn4V/IQrpBLO6POkUSrN7RhyY+GF/InCFShQzsQ39T25gkHhLgSLByyAz+Kjb+c2L98w== + dependencies: + clean-stack "^4.0.0" + indent-string "^5.0.0" + +aggregate-error@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/aggregate-error/-/aggregate-error-5.0.0.tgz#ffe15045d7521c51c9d618e3d7f37c13f29b3fd3" + integrity sha512-gOsf2YwSlleG6IjRYG2A7k0HmBMEo6qVNk9Bp/EaLgAJT5ngH6PXbqa4ItvnEwCm/velL5jAnQgsHsWnjhGmvw== + dependencies: + clean-stack "^5.2.0" + indent-string "^5.0.0" -ajv@^6.10.0, ajv@^6.12.4, ajv@^6.12.5: +ajv@^6.12.4: version "6.12.6" resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.12.6.tgz#baf5a62e802b07d977034586f8c3baf5adf26df4" integrity sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g== @@ -1760,22 +2290,24 @@ ajv@^6.10.0, ajv@^6.12.4, ajv@^6.12.5: json-schema-traverse "^0.4.1" uri-js "^4.2.2" -ajv@^8.0.1: - version "8.11.0" - resolved "https://registry.yarnpkg.com/ajv/-/ajv-8.11.0.tgz#977e91dd96ca669f54a11e23e378e33b884a565f" - integrity sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg== +ajv@^8.11.0: + version "8.12.0" + resolved "https://registry.yarnpkg.com/ajv/-/ajv-8.12.0.tgz#d1a0527323e22f53562c567c00991577dfbe19d1" + integrity sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA== dependencies: fast-deep-equal "^3.1.1" json-schema-traverse "^1.0.0" require-from-string "^2.0.2" uri-js "^4.2.2" -ansi-colors@^4.1.1: - version "4.1.1" - resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-4.1.1.tgz#cbb9ae256bf750af1eab344f229aa27fe94ba348" - integrity sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA== +ansi-align@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/ansi-align/-/ansi-align-3.0.1.tgz#0cdf12e111ace773a86e9a1fad1225c43cb19a59" + integrity sha512-IOfwwBF5iczOjp/WeY4YxyjqAFMQoZufdQWDd19SEExbVLNXqvpzSJ/M7Za4/sCPmQ0+GRquoA7bGcINcxew6w== + dependencies: + string-width "^4.1.0" -ansi-escapes@^4.2.1, ansi-escapes@^4.3.0: +ansi-escapes@^4.2.1: version "4.3.2" resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-4.3.2.tgz#6b2291d1db7d98b6521d5f1efa42d0f3a9feb65e" integrity sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ== @@ -1789,6 +2321,13 @@ ansi-escapes@^5.0.0: dependencies: type-fest "^1.0.2" +ansi-escapes@^6.2.0: + version "6.2.0" + resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-6.2.0.tgz#8a13ce75286f417f1963487d86ba9f90dccf9947" + integrity sha512-kzRaCqXnpzWs+3z5ABPQiVke+iq0KXkHo8xiWV4RPTi5Yli0l97BEQuhXV1s7+aSU/fu1kUuxgS4MsQ0fRuygw== + dependencies: + type-fest "^3.0.0" + ansi-regex@^5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304" @@ -1799,11 +2338,6 @@ ansi-regex@^6.0.1: resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-6.0.1.tgz#3183e38fae9a65d7cb5e53945cd5897d0260a06a" integrity sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA== -ansi-sequence-parser@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/ansi-sequence-parser/-/ansi-sequence-parser-1.1.0.tgz#4d790f31236ac20366b23b3916b789e1bde39aed" - integrity sha512-lEm8mt52to2fT8GhciPCGeCXACSz2UwIN4X2e2LJSnZ5uAbn2/dsYdOmUXq0AtWS5cpAupysIneExOgH0Vd2TQ== - ansi-styles@^3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" @@ -1823,7 +2357,7 @@ ansi-styles@^5.0.0: resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-5.2.0.tgz#07449690ad45777d1924ac2abb2fc8895dba836b" integrity sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA== -ansi-styles@^6.0.0: +ansi-styles@^6.0.0, ansi-styles@^6.1.0, ansi-styles@^6.2.1: version "6.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-6.2.1.tgz#0e62320cf99c21afff3b3012192546aacbfb05c5" integrity sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug== @@ -1834,9 +2368,9 @@ ansicolors@~0.3.2: integrity sha512-QXu7BPrP29VllRxH8GwB7x5iX5qWKAAMLqKQGWTeLWVlNHNOpVMJ91dsxQAIWXpjuW5wqvxu3Jd/nRjrJ+0pqg== anymatch@^3.0.3: - version "3.1.2" - resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.2.tgz#c0557c096af32f106198f4f4e2a383537e378716" - integrity sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg== + version "3.1.3" + resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.3.tgz#790c58b19ba1720a84205b57c618d5ad8524973e" + integrity sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw== dependencies: normalize-path "^3.0.0" picomatch "^2.0.4" @@ -1859,6 +2393,19 @@ are-we-there-yet@^3.0.0: delegates "^1.0.0" readable-stream "^3.6.0" +are-we-there-yet@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/are-we-there-yet/-/are-we-there-yet-4.0.0.tgz#3ff397dc14f08b52dd8b2a64d3cee154ab8760d2" + integrity sha512-nSXlV+u3vtVjRgihdTzbfWYzxPWGo424zPgQbHD0ZqIla3jqYAewDcvee0Ua2hjS5IfTAmjGlx1Jf0PKwjZDEw== + dependencies: + delegates "^1.0.0" + readable-stream "^4.1.0" + +arg@^4.1.0: + version "4.1.3" + resolved "https://registry.yarnpkg.com/arg/-/arg-4.1.3.tgz#269fc7ad5b8e42cb63c896d5666017261c144089" + integrity sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA== + argparse@^1.0.7: version "1.0.10" resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" @@ -1866,6 +2413,11 @@ argparse@^1.0.7: dependencies: sprintf-js "~1.0.2" +argparse@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38" + integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== + argv-formatter@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/argv-formatter/-/argv-formatter-1.0.0.tgz#a0ca0cbc29a5b73e836eebe1cbf6c5e0e4eb82f9" @@ -1876,85 +2428,30 @@ array-ify@^1.0.0: resolved "https://registry.yarnpkg.com/array-ify/-/array-ify-1.0.0.tgz#9e528762b4a9066ad163a6962a364418e9626ece" integrity sha512-c5AMf34bKdvPhQ7tBGhqkgKNUzMr4WUs+WDtC2ZUGOUncbxKMTvqxYctiseW3+L4bA8ec+GcZ6/A/FW4m8ukng== -array-union@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/array-union/-/array-union-1.0.2.tgz#9a34410e4f4e3da23dea375be5be70f24778ec39" - integrity sha1-mjRBDk9OPaI96jdb5b5w8kd47Dk= - dependencies: - array-uniq "^1.0.1" - array-union@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/array-union/-/array-union-2.1.0.tgz#b798420adbeb1de828d84acd8a2e23d3efe85e8d" integrity sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw== -array-uniq@^1.0.1: - version "1.0.3" - resolved "https://registry.yarnpkg.com/array-uniq/-/array-uniq-1.0.3.tgz#af6ac877a25cc7f74e058894753858dfdb24fdb6" - integrity sha1-r2rId6Jcx/dOBYiUdThY39sk/bY= - arrify@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/arrify/-/arrify-1.0.1.tgz#898508da2226f380df904728456849c1501a4b0d" integrity sha512-3CYzex9M9FGQjCGMGyi6/31c8GJbgb0qGyrx5HWxPd0aCwh4cB2YjMb2Xf9UuoogrMrlO9cTqnB5rI5GHZTcUA== -asap@^2.0.0: - version "2.0.6" - resolved "https://registry.yarnpkg.com/asap/-/asap-2.0.6.tgz#e50347611d7e690943208bbdafebcbc2fb866d46" - integrity sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA== - -asn1.js@^5.2.0: - version "5.4.1" - resolved "https://registry.yarnpkg.com/asn1.js/-/asn1.js-5.4.1.tgz#11a980b84ebb91781ce35b0fdc2ee294e3783f07" - integrity sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA== - dependencies: - bn.js "^4.0.0" - inherits "^2.0.1" - minimalistic-assert "^1.0.0" - safer-buffer "^2.1.0" - -assert@2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/assert/-/assert-2.0.0.tgz#95fc1c616d48713510680f2eaf2d10dd22e02d32" - integrity sha512-se5Cd+js9dXJnu6Ag2JFc00t+HmHOen+8Q+L7O9zI0PqQXr20uk2J0XQqMxZEeo5U50o8Nvmmx7dZrl+Ufr35A== - dependencies: - es6-object-assign "^1.1.0" - is-nan "^1.2.1" - object-is "^1.0.1" - util "^0.12.0" - -astral-regex@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/astral-regex/-/astral-regex-2.0.0.tgz#483143c567aeed4785759c0865786dc77d7d2e31" - integrity sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ== - -asynckit@^0.4.0: - version "0.4.0" - resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" - integrity sha1-x57Zf380y48robyXkLzDZkdLS3k= - -available-typed-arrays@^1.0.5: - version "1.0.5" - resolved "https://registry.yarnpkg.com/available-typed-arrays/-/available-typed-arrays-1.0.5.tgz#92f95616501069d07d10edb2fc37d3e1c65123b7" - integrity sha512-DMD0KiN46eipeziST1LPP/STfDU0sufISXmjSgvVsoU2tqxctQeASejWcfNtxYKqETM1UxQ8sp2OrSBWpHY6sw== - -axios@0.27.2: - version "0.27.2" - resolved "https://registry.yarnpkg.com/axios/-/axios-0.27.2.tgz#207658cc8621606e586c85db4b41a750e756d972" - integrity sha512-t+yRIyySRTp/wua5xEr+z1q60QmLq8ABsS5O9Me1AsE5dfKqgnCFzwiCZZ/cGNd1lq4/7akDWMxdhVlucjmnOQ== - dependencies: - follow-redirects "^1.14.9" - form-data "^4.0.0" +at-least-node@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/at-least-node/-/at-least-node-1.0.0.tgz#602cd4b46e844ad4effc92a8011a3c46e0238dc2" + integrity sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg== -babel-jest@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/babel-jest/-/babel-jest-29.4.3.tgz#478b84d430972b277ad67dd631be94abea676792" - integrity sha512-o45Wyn32svZE+LnMVWv/Z4x0SwtLbh4FyGcYtR20kIWd+rdrDZ9Fzq8Ml3MYLD+mZvEdzCjZsCnYZ2jpJyQ+Nw== +babel-jest@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/babel-jest/-/babel-jest-29.7.0.tgz#f4369919225b684c56085998ac63dbd05be020d5" + integrity sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg== dependencies: - "@jest/transform" "^29.4.3" + "@jest/transform" "^29.7.0" "@types/babel__core" "^7.1.14" babel-plugin-istanbul "^6.1.1" - babel-preset-jest "^29.4.3" + babel-preset-jest "^29.6.3" chalk "^4.0.0" graceful-fs "^4.2.9" slash "^3.0.0" @@ -1970,10 +2467,10 @@ babel-plugin-istanbul@^6.1.1: istanbul-lib-instrument "^5.0.4" test-exclude "^6.0.0" -babel-plugin-jest-hoist@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.4.3.tgz#ad1dfb5d31940957e00410ef7d9b2aa94b216101" - integrity sha512-mB6q2q3oahKphy5V7CpnNqZOCkxxZ9aokf1eh82Dy3jQmg4xvM1tGrh5y6BQUJh4a3Pj9+eLfwvAZ7VNKg7H8Q== +babel-plugin-jest-hoist@^29.6.3: + version "29.6.3" + resolved "https://registry.yarnpkg.com/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz#aadbe943464182a8922c3c927c3067ff40d24626" + integrity sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg== dependencies: "@babel/template" "^7.3.3" "@babel/types" "^7.3.3" @@ -1998,12 +2495,12 @@ babel-preset-current-node-syntax@^1.0.0: "@babel/plugin-syntax-optional-chaining" "^7.8.3" "@babel/plugin-syntax-top-level-await" "^7.8.3" -babel-preset-jest@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/babel-preset-jest/-/babel-preset-jest-29.4.3.tgz#bb926b66ae253b69c6e3ef87511b8bb5c53c5b52" - integrity sha512-gWx6COtSuma6n9bw+8/F+2PCXrIgxV/D1TJFnp6OyBK2cxPWg0K9p/sriNYeifKjpUkMViWQ09DSWtzJQRETsw== +babel-preset-jest@^29.6.3: + version "29.6.3" + resolved "https://registry.yarnpkg.com/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz#fa05fa510e7d493896d7b0dd2033601c840f171c" + integrity sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA== dependencies: - babel-plugin-jest-hoist "^29.4.3" + babel-plugin-jest-hoist "^29.6.3" babel-preset-current-node-syntax "^1.0.0" balanced-match@^1.0.0: @@ -2011,81 +2508,63 @@ balanced-match@^1.0.0: resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== -base-x@^3.0.2: - version "3.0.9" - resolved "https://registry.yarnpkg.com/base-x/-/base-x-3.0.9.tgz#6349aaabb58526332de9f60995e548a53fe21320" - integrity sha512-H7JU6iBHTal1gp56aKoaa//YUxEaAOUiydvrV/pILqIHXTtqxSkATOnDA2u+jZ/61sD+L/412+7kzXRtWukhpQ== - dependencies: - safe-buffer "^5.0.1" - base64-js@^1.3.1: version "1.5.1" resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a" integrity sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA== -bech32@*, bech32@2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/bech32/-/bech32-2.0.0.tgz#078d3686535075c8c79709f054b1b226a133b355" - integrity sha512-LcknSilhIGatDAsY1ak2I8VtGaHNhgMSYVxFrGLXv+xLHytaKZKcaUJJUE7qmBr7h33o5YQwP55pMI0xmkpJwg== - before-after-hook@^2.2.0: version "2.2.3" resolved "https://registry.yarnpkg.com/before-after-hook/-/before-after-hook-2.2.3.tgz#c51e809c81a4e354084422b9b26bad88249c517c" integrity sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ== -bin-links@^3.0.3: - version "3.0.3" - resolved "https://registry.yarnpkg.com/bin-links/-/bin-links-3.0.3.tgz#3842711ef3db2cd9f16a5f404a996a12db355a6e" - integrity sha512-zKdnMPWEdh4F5INR07/eBrodC7QrF5JKvqskjz/ZZRXg5YSAZIbn8zGhbhUrElzHBZ2fvEQdOU59RHcTG3GiwA== +bin-links@^4.0.1: + version "4.0.1" + resolved "https://registry.yarnpkg.com/bin-links/-/bin-links-4.0.1.tgz#afeb0549e642f61ff889b58ea2f8dca78fb9d8d3" + integrity sha512-bmFEM39CyX336ZGGRsGPlc6jZHriIoHacOQcTt72MktIjpPhZoP4te2jOyUXF3BLILmJ8aNLncoPVeIIFlrDeA== dependencies: - cmd-shim "^5.0.0" - mkdirp-infer-owner "^2.0.0" - npm-normalize-package-bin "^2.0.0" - read-cmd-shim "^3.0.0" - rimraf "^3.0.0" - write-file-atomic "^4.0.0" + cmd-shim "^6.0.0" + npm-normalize-package-bin "^3.0.0" + read-cmd-shim "^4.0.0" + write-file-atomic "^5.0.0" binary-extensions@^2.2.0: version "2.2.0" resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-2.2.0.tgz#75f502eeaf9ffde42fc98829645be4ea76bd9e2d" integrity sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA== -bip39@3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/bip39/-/bip39-3.1.0.tgz#c55a418deaf48826a6ceb34ac55b3ee1577e18a3" - integrity sha512-c9kiwdk45Do5GL0vJMe7tS95VjCii65mYAH7DfWl3uW8AVzXKQVUm64i3hzVybBDMp9r7j9iNxR85+ul8MdN/A== +bl@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/bl/-/bl-4.1.0.tgz#451535264182bec2fbbc83a62ab98cf11d9f7b3a" + integrity sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w== dependencies: - "@noble/hashes" "^1.2.0" - -bn.js@5.2.1: - version "5.2.1" - resolved "https://registry.yarnpkg.com/bn.js/-/bn.js-5.2.1.tgz#0bc527a6a0d18d0aa8d5b0538ce4a77dccfa7b70" - integrity sha512-eXRvHzWyYPBuB4NBy0cmYQjGitUrtqwbvlzP3G6VFnNRbsZQIxQ10PbKKHt8gZ/HW/D/747aDl+QkDqg3KQLMQ== - -bn.js@^4.0.0, bn.js@^4.1.0, bn.js@^4.11.9: - version "4.12.0" - resolved "https://registry.yarnpkg.com/bn.js/-/bn.js-4.12.0.tgz#775b3f278efbb9718eec7361f483fb36fbbfea88" - integrity sha512-c98Bf3tPniI+scsdk237ku1Dc3ujXQTSgyiPUDEOe7tRkhrqridvh8klBv0HCEso1OLOYcHuCv/cS6DNxKH+ZA== - -bn.js@^5.0.0, bn.js@^5.1.1: - version "5.2.0" - resolved "https://registry.yarnpkg.com/bn.js/-/bn.js-5.2.0.tgz#358860674396c6997771a9d051fcc1b57d4ae002" - integrity sha512-D7iWRBvnZE8ecXiLj/9wbxH7Tk79fAh8IHaTNq1RWRixsS02W+5qS+iE9yq6RYl0asXx5tw0bLhmT5pIfbSquw== - -boolbase@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/boolbase/-/boolbase-1.0.0.tgz#68dff5fbe60c51eb37725ea9e3ed310dcc1e776e" - integrity sha1-aN/1++YMUes3cl6p4+0xDcwed24= + buffer "^5.5.0" + inherits "^2.0.4" + readable-stream "^3.4.0" -bottleneck@^2.18.1: +bottleneck@^2.15.3, bottleneck@^2.18.1: version "2.19.5" resolved "https://registry.yarnpkg.com/bottleneck/-/bottleneck-2.19.5.tgz#5df0b90f59fd47656ebe63c78a98419205cadd91" integrity sha512-VHiNCbI1lKdl44tGrhNfU3lup0Tj/ZBMJB5/2ZbNXRCPuRCO7ed2mgcK4r17y+KB2EfuYuRaVlwNbAeaWGSpbw== -brace-expansion@^1.1.7: - version "1.1.11" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" - integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== +boxen@^5.0.0: + version "5.1.2" + resolved "https://registry.yarnpkg.com/boxen/-/boxen-5.1.2.tgz#788cb686fc83c1f486dfa8a40c68fc2b831d2b50" + integrity sha512-9gYgQKXx+1nP8mP7CzFyaUARhg7D3n1dF/FnErWmu9l6JvGpNUN278h0aSb+QjoiKSWG+iZ3uHrcqk0qrY9RQQ== + dependencies: + ansi-align "^3.0.0" + camelcase "^6.2.0" + chalk "^4.1.0" + cli-boxes "^2.2.1" + string-width "^4.2.2" + type-fest "^0.20.2" + widest-line "^3.1.0" + wrap-ansi "^7.0.0" + +brace-expansion@^1.1.7: + version "1.1.11" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" + integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== dependencies: balanced-match "^1.0.0" concat-map "0.0.1" @@ -2104,75 +2583,12 @@ braces@^3.0.2: dependencies: fill-range "^7.0.1" -brorand@^1.0.1, brorand@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/brorand/-/brorand-1.1.0.tgz#12c25efe40a45e3c323eb8675a0a0ce57b22371f" - integrity sha1-EsJe/kCkXjwyPrhnWgoM5XsiNx8= - -browserify-aes@^1.0.0, browserify-aes@^1.0.4: - version "1.2.0" - resolved "https://registry.yarnpkg.com/browserify-aes/-/browserify-aes-1.2.0.tgz#326734642f403dabc3003209853bb70ad428ef48" - integrity sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA== - dependencies: - buffer-xor "^1.0.3" - cipher-base "^1.0.0" - create-hash "^1.1.0" - evp_bytestokey "^1.0.3" - inherits "^2.0.1" - safe-buffer "^5.0.1" - -browserify-cipher@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/browserify-cipher/-/browserify-cipher-1.0.1.tgz#8d6474c1b870bfdabcd3bcfcc1934a10e94f15f0" - integrity sha512-sPhkz0ARKbf4rRQt2hTpAHqn47X3llLkUGn+xEJzLjwY8LRs2p0v7ljvI5EyoRO/mexrNunNECisZs+gw2zz1w== - dependencies: - browserify-aes "^1.0.4" - browserify-des "^1.0.0" - evp_bytestokey "^1.0.0" - -browserify-des@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/browserify-des/-/browserify-des-1.0.2.tgz#3af4f1f59839403572f1c66204375f7a7f703e9c" - integrity sha512-BioO1xf3hFwz4kc6iBhI3ieDFompMhrMlnDFC4/0/vd5MokpuAc3R+LYbwTA9A5Yc9pq9UYPqffKpW2ObuwX5A== - dependencies: - cipher-base "^1.0.1" - des.js "^1.0.0" - inherits "^2.0.1" - safe-buffer "^5.1.2" - -browserify-rsa@^4.0.0, browserify-rsa@^4.0.1: - version "4.1.0" - resolved "https://registry.yarnpkg.com/browserify-rsa/-/browserify-rsa-4.1.0.tgz#b2fd06b5b75ae297f7ce2dc651f918f5be158c8d" - integrity sha512-AdEER0Hkspgno2aR97SAf6vi0y0k8NuOpGnVH3O99rcA5Q6sh8QxcngtHuJ6uXwnfAXNM4Gn1Gb7/MV1+Ymbog== - dependencies: - bn.js "^5.0.0" - randombytes "^2.0.1" - -browserify-sign@^4.0.0: - version "4.2.1" - resolved "https://registry.yarnpkg.com/browserify-sign/-/browserify-sign-4.2.1.tgz#eaf4add46dd54be3bb3b36c0cf15abbeba7956c3" - integrity sha512-/vrA5fguVAKKAVTNJjgSm1tRQDHUU6DbwO9IROu/0WAzC8PKhucDSh18J0RMvVeHAn5puMd+QHC2erPRNf8lmg== - dependencies: - bn.js "^5.1.1" - browserify-rsa "^4.0.1" - create-hash "^1.2.0" - create-hmac "^1.1.7" - elliptic "^6.5.3" - inherits "^2.0.4" - parse-asn1 "^5.1.5" - readable-stream "^3.6.0" - safe-buffer "^5.2.0" - -browserslist@^4.14.5, browserslist@^4.20.2: - version "4.20.3" - resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.20.3.tgz#eb7572f49ec430e054f56d52ff0ebe9be915f8bf" - integrity sha512-NBhymBQl1zM0Y5dQT/O+xiLP9/rzOIQdKM/eMJBAq7yBgaB6krIYLGejrwVYnSHZdqjscB1SPuAjHwxjvN6Wdg== +brotli-size@4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/brotli-size/-/brotli-size-4.0.0.tgz#a05ee3faad3c0e700a2f2da826ba6b4d76e69e5e" + integrity sha512-uA9fOtlTRC0iqKfzff1W34DXUA3GyVqbUaeo3Rw3d4gd1eavKVCETXrn3NzO74W+UVkG3UHu8WxUi+XvKI/huA== dependencies: - caniuse-lite "^1.0.30001332" - electron-to-chromium "^1.4.118" - escalade "^3.1.1" - node-releases "^2.0.3" - picocolors "^1.0.0" + duplexer "0.1.1" browserslist@^4.21.3: version "4.21.5" @@ -2191,22 +2607,6 @@ bs-logger@0.x: dependencies: fast-json-stable-stringify "2.x" -bs58@^4.0.0: - version "4.0.1" - resolved "https://registry.yarnpkg.com/bs58/-/bs58-4.0.1.tgz#be161e76c354f6f788ae4071f63f34e8c4f0a42a" - integrity sha1-vhYedsNU9veIrkBx9j806MTwpCo= - dependencies: - base-x "^3.0.2" - -bs58check@^2.1.2: - version "2.1.2" - resolved "https://registry.yarnpkg.com/bs58check/-/bs58check-2.1.2.tgz#53b018291228d82a5aa08e7d796fdafda54aebfc" - integrity sha512-0TS1jicxdU09dwJMNZtVAfzPi6Q6QeN0pM1Fkzrjn+XYHvzMKPU3pHVpva+769iNVSfIYWf7LJ6WR+BuuMf8cA== - dependencies: - bs58 "^4.0.0" - create-hash "^1.1.0" - safe-buffer "^5.1.2" - bser@2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/bser/-/bser-2.1.1.tgz#e6787da20ece9d07998533cfd9de6f5c38f4bc05" @@ -2219,12 +2619,15 @@ buffer-from@^1.0.0: resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.2.tgz#2b146a6fd72e80b4f55d255f35ed59a3a9a41bd5" integrity sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ== -buffer-xor@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/buffer-xor/-/buffer-xor-1.0.3.tgz#26e61ed1422fb70dd42e6e36729ed51d855fe8d9" - integrity sha1-JuYe0UIvtw3ULm42cp7VHYVf6Nk= +buffer@^5.5.0: + version "5.7.1" + resolved "https://registry.yarnpkg.com/buffer/-/buffer-5.7.1.tgz#ba62e7c13133053582197160851a8f648e99eed0" + integrity sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ== + dependencies: + base64-js "^1.3.1" + ieee754 "^1.1.13" -buffer@6.0.3: +buffer@^6.0.3: version "6.0.3" resolved "https://registry.yarnpkg.com/buffer/-/buffer-6.0.3.tgz#2ace578459cc8fbe2a70aaa8f52ee63b6a74c6c6" integrity sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA== @@ -2232,6 +2635,11 @@ buffer@6.0.3: base64-js "^1.3.1" ieee754 "^1.2.1" +builtin-modules@^3.3.0: + version "3.3.0" + resolved "https://registry.yarnpkg.com/builtin-modules/-/builtin-modules-3.3.0.tgz#cae62812b89801e9656336e46223e030386be7b6" + integrity sha512-zhaCDicdLuWN5UbN5IMnFqNMhNfo919sH85y2/ea+5Yg9TsTkeZxpL+JLbp6cgYFS4sRLp3YV4S6yDuqVWHYOw== + builtins@^5.0.0: version "5.0.1" resolved "https://registry.yarnpkg.com/builtins/-/builtins-5.0.1.tgz#87f6db9ab0458be728564fa81d876d8d74552fa9" @@ -2239,7 +2647,7 @@ builtins@^5.0.0: dependencies: semver "^7.0.0" -cacache@^16.0.0, cacache@^16.1.0, cacache@^16.1.3: +cacache@^16.1.0: version "16.1.3" resolved "https://registry.yarnpkg.com/cacache/-/cacache-16.1.3.tgz#a02b9f34ecfaf9a78c9f4bc16fceb94d5d67a38e" integrity sha512-/+Emcj9DAXxX4cwlLmRI9c166RuL3w30zp4R7Joiv2cQTtTtA+jeuCAjH3ZlGnYS3tKENSrKhAzVVP9GVyzeYQ== @@ -2263,27 +2671,72 @@ cacache@^16.0.0, cacache@^16.1.0, cacache@^16.1.3: tar "^6.1.11" unique-filename "^2.0.0" -call-bind@^1.0.0, call-bind@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/call-bind/-/call-bind-1.0.2.tgz#b1d4e89e688119c3c9a903ad30abb2f6a919be3c" - integrity sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA== +cacache@^17.0.0: + version "17.0.4" + resolved "https://registry.yarnpkg.com/cacache/-/cacache-17.0.4.tgz#5023ed892ba8843e3b7361c26d0ada37e146290c" + integrity sha512-Z/nL3gU+zTUjz5pCA5vVjYM8pmaw2kxM7JEiE0fv3w77Wj+sFbi70CrBruUWH0uNcEdvLDixFpgA2JM4F4DBjA== dependencies: - function-bind "^1.1.1" - get-intrinsic "^1.0.2" + "@npmcli/fs" "^3.1.0" + fs-minipass "^3.0.0" + glob "^8.0.1" + lru-cache "^7.7.1" + minipass "^4.0.0" + minipass-collect "^1.0.2" + minipass-flush "^1.0.5" + minipass-pipeline "^1.2.4" + p-map "^4.0.0" + promise-inflight "^1.0.1" + ssri "^10.0.0" + tar "^6.1.11" + unique-filename "^3.0.0" + +cacache@^17.0.4, cacache@^17.0.5: + version "17.0.5" + resolved "https://registry.yarnpkg.com/cacache/-/cacache-17.0.5.tgz#6dbec26c11f1f6a2b558bc11ed3316577c339ebc" + integrity sha512-Y/PRQevNSsjAPWykl9aeGz8Pr+OI6BYM9fYDNMvOkuUiG9IhG4LEmaYrZZZvioMUEQ+cBCxT0v8wrnCURccyKA== + dependencies: + "@npmcli/fs" "^3.1.0" + fs-minipass "^3.0.0" + glob "^9.3.1" + lru-cache "^7.7.1" + minipass "^4.0.0" + minipass-collect "^1.0.2" + minipass-flush "^1.0.5" + minipass-pipeline "^1.2.4" + p-map "^4.0.0" + promise-inflight "^1.0.1" + ssri "^10.0.0" + tar "^6.1.11" + unique-filename "^3.0.0" + +cacache@^18.0.0, cacache@^18.0.2: + version "18.0.2" + resolved "https://registry.yarnpkg.com/cacache/-/cacache-18.0.2.tgz#fd527ea0f03a603be5c0da5805635f8eef00c60c" + integrity sha512-r3NU8h/P+4lVUHfeRw1dtgQYar3DZMm4/cm2bZgOvrFC/su7budSOeqh52VJIC4U4iG1WWwV6vRW0znqBvxNuw== + dependencies: + "@npmcli/fs" "^3.1.0" + fs-minipass "^3.0.0" + glob "^10.2.2" + lru-cache "^10.0.1" + minipass "^7.0.3" + minipass-collect "^2.0.1" + minipass-flush "^1.0.5" + minipass-pipeline "^1.2.4" + p-map "^4.0.0" + ssri "^10.0.0" + tar "^6.1.11" + unique-filename "^3.0.0" + +cachedir@2.3.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/cachedir/-/cachedir-2.3.0.tgz#0c75892a052198f0b21c7c1804d8331edfcae0e8" + integrity sha512-A+Fezp4zxnit6FanDmv9EqXNAi3vt9DWp51/71UEhXukb7QUuvtv9344h91dyAxuTLoSYJFU299qzR3tzwPAhw== callsites@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/callsites/-/callsites-3.1.0.tgz#b3630abd8943432f54b3f0519238e33cd7df2f73" integrity sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ== -camel-case@^4.1.2: - version "4.1.2" - resolved "https://registry.yarnpkg.com/camel-case/-/camel-case-4.1.2.tgz#9728072a954f805228225a6deea6b38461e1bd5a" - integrity sha512-gxGWBrTT1JuMx6R+o5PTXMmUnhnVzLQ9SNutD4YqKtI6ap897t3tKECYla6gCWEkplXnlNybEkZg9GEGxKFCgw== - dependencies: - pascal-case "^3.1.2" - tslib "^2.0.3" - camelcase-keys@^6.2.2: version "6.2.2" resolved "https://registry.yarnpkg.com/camelcase-keys/-/camelcase-keys-6.2.2.tgz#5e755d6ba51aa223ec7d3d52f25778210f9dc3c0" @@ -2303,11 +2756,6 @@ camelcase@^6.2.0: resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-6.3.0.tgz#5685b95eb209ac9c0c177467778c9c84df58ba9a" integrity sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA== -caniuse-lite@^1.0.30001332: - version "1.0.30001335" - resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001335.tgz#899254a0b70579e5a957c32dced79f0727c61f2a" - integrity sha512-ddP1Tgm7z2iIxu6QTtbZUv6HJxSaV/PZeSrWFZtbY4JZ69tOeNhBCl3HyRQgeNZKE5AOn1kpV7fhljigy0Ty3w== - caniuse-lite@^1.0.30001449: version "1.0.30001456" resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001456.tgz#734ec1dbfa4f3abe6e435b78ecf40d68e8c32ce4" @@ -2321,7 +2769,12 @@ cardinal@^2.1.1: ansicolors "~0.3.2" redeyed "~2.1.0" -chalk@^2.0.0, chalk@^2.3.2: +chalk@5.3.0, chalk@^5.0.0, chalk@^5.3.0: + version "5.3.0" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-5.3.0.tgz#67c20a7ebef70e7f3970a01f90fa210cb6860385" + integrity sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w== + +chalk@^2.0.0, chalk@^2.3.2, chalk@^2.4.1, chalk@^2.4.2: version "2.4.2" resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424" integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== @@ -2330,7 +2783,7 @@ chalk@^2.0.0, chalk@^2.3.2: escape-string-regexp "^1.0.5" supports-color "^5.3.0" -chalk@^4.0.0, chalk@^4.1.0, chalk@^4.1.2: +chalk@^4.0.0, chalk@^4.1.0, chalk@^4.1.1, chalk@^4.1.2: version "4.1.2" resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.2.tgz#aac4e2b7734a740867aeb16bf02aad556a1e7a01" integrity sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA== @@ -2338,31 +2791,38 @@ chalk@^4.0.0, chalk@^4.1.0, chalk@^4.1.2: ansi-styles "^4.1.0" supports-color "^7.1.0" -chalk@^5.0.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-5.2.0.tgz#249623b7d66869c673699fb66d65723e54dfcfb3" - integrity sha512-ree3Gqw/nazQAPuJJEy+avdl7QfZMcUvmHIKgEZkGL+xOBzRvup5Hxo6LHuMceSxOabuJLJm5Yp/92R9eMmMvA== - char-regex@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/char-regex/-/char-regex-1.0.2.tgz#d744358226217f981ed58f479b1d6bcc29545dcf" integrity sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw== +chardet@^0.7.0: + version "0.7.0" + resolved "https://registry.yarnpkg.com/chardet/-/chardet-0.7.0.tgz#90094849f0937f2eedc2425d0d28a9e5f0cbad9e" + integrity sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA== + chownr@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/chownr/-/chownr-2.0.0.tgz#15bfbe53d2eab4cf70f18a8cd68ebe5b3cb1dece" integrity sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ== -chrome-trace-event@^1.0.2: - version "1.0.3" - resolved "https://registry.yarnpkg.com/chrome-trace-event/-/chrome-trace-event-1.0.3.tgz#1015eced4741e15d06664a957dbbf50d041e26ac" - integrity sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg== - -ci-info@^3.2.0: +ci-info@^3.2.0, ci-info@^3.6.1, ci-info@^3.7.1, ci-info@^3.8.0: version "3.8.0" resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-3.8.0.tgz#81408265a5380c929f0bc665d62256628ce9ef91" integrity sha512-eXTggHWSooYhq49F2opQhuHWgzucfF2YgODK4e1566GQs5BIfP30B0oenwBJHfWxAs2fyPB1s7Mg949zLf61Yw== +ci-info@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-4.0.0.tgz#65466f8b280fc019b9f50a5388115d17a63a44f2" + integrity sha512-TdHqgGf9odd8SXNuxtUBVx8Nv+qZOejE6qyqiy5NtbYYQOeFa6zmHkxlPzmaLxWWHsU6nJmB7AETdVPi+2NBUg== + +cidr-regex@4.0.3: + version "4.0.3" + resolved "https://registry.yarnpkg.com/cidr-regex/-/cidr-regex-4.0.3.tgz#07b52c9762d1ff546a50740e92fc2b5b13a6d871" + integrity sha512-HOwDIy/rhKeMf6uOzxtv7FAbrz8zPjmVKfSpM+U7/bNBXC5rtOyr758jxcptiSx6ZZn5LOhPJT5WWxPAGDV8dw== + dependencies: + ip-regex "^5.0.0" + cidr-regex@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/cidr-regex/-/cidr-regex-3.1.1.tgz#ba1972c57c66f61875f18fd7dd487469770b571d" @@ -2370,37 +2830,34 @@ cidr-regex@^3.1.1: dependencies: ip-regex "^4.1.0" -cipher-base@^1.0.0, cipher-base@^1.0.1, cipher-base@^1.0.3: - version "1.0.4" - resolved "https://registry.yarnpkg.com/cipher-base/-/cipher-base-1.0.4.tgz#8760e4ecc272f4c363532f926d874aae2c1397de" - integrity sha512-Kkht5ye6ZGmwv40uUDZztayT2ThLQGfnj/T71N/XzeZeo3nf8foyW7zGTsPYkEya3m5f3cAypH+qe7YOrM1U2Q== - dependencies: - inherits "^2.0.1" - safe-buffer "^5.0.1" - cjs-module-lexer@^1.0.0: version "1.2.2" resolved "https://registry.yarnpkg.com/cjs-module-lexer/-/cjs-module-lexer-1.2.2.tgz#9f84ba3244a512f3a54e5277e8eef4c489864e40" integrity sha512-cOU9usZw8/dXIXKtwa8pM0OTJQuJkxMN6w30csNRUerHfeQ5R6U3kkU/FtJeIf3M202OHfY2U8ccInBG7/xogA== -clean-css@^5.2.2: - version "5.3.0" - resolved "https://registry.yarnpkg.com/clean-css/-/clean-css-5.3.0.tgz#ad3d8238d5f3549e83d5f87205189494bc7cbb59" - integrity sha512-YYuuxv4H/iNb1Z/5IbMRoxgrzjWGhOEFfd+groZ5dMCVkpENiMZmwspdrzBo9286JjM1gZJPAyL7ZIdzuvu2AQ== - dependencies: - source-map "~0.6.0" - clean-stack@^2.0.0: version "2.2.0" resolved "https://registry.yarnpkg.com/clean-stack/-/clean-stack-2.2.0.tgz#ee8472dbb129e727b31e8a10a427dee9dfe4008b" integrity sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A== -clean-webpack-plugin@4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/clean-webpack-plugin/-/clean-webpack-plugin-4.0.0.tgz#72947d4403d452f38ed61a9ff0ada8122aacd729" - integrity sha512-WuWE1nyTNAyW5T7oNyys2EN0cfP2fdRxhxnIQWiAp0bMabPdHhoGxM8A6YL2GhqwgrPnnaemVE7nv5XJ2Fhh2w== +clean-stack@^4.0.0: + version "4.2.0" + resolved "https://registry.yarnpkg.com/clean-stack/-/clean-stack-4.2.0.tgz#c464e4cde4ac789f4e0735c5d75beb49d7b30b31" + integrity sha512-LYv6XPxoyODi36Dp976riBtSY27VmFo+MKqEU9QCCWyTrdEPDog+RWA7xQWHi6Vbp61j5c4cdzzX1NidnwtUWg== + dependencies: + escape-string-regexp "5.0.0" + +clean-stack@^5.2.0: + version "5.2.0" + resolved "https://registry.yarnpkg.com/clean-stack/-/clean-stack-5.2.0.tgz#c7a0c91939c7caace30a3bf254e8a8ac276d1189" + integrity sha512-TyUIUJgdFnCISzG5zu3291TAsE77ddchd0bepon1VVQrKLGKFED4iXFEDQ24mIPdPBbyE16PK3F8MYE1CmcBEQ== dependencies: - del "^4.1.1" + escape-string-regexp "5.0.0" + +cli-boxes@^2.2.1: + version "2.2.1" + resolved "https://registry.yarnpkg.com/cli-boxes/-/cli-boxes-2.2.1.tgz#ddd5035d25094fce220e9cab40a45840a440318f" + integrity sha512-y4coMcylgSCdVinjiDBuR8PCC2bLjyGTwEmPb9NHR/QaNU6EUOXcTY/s6VjGMD6ENSEaeQYHCY0GNGS5jfMwPw== cli-columns@^4.0.0: version "4.0.0" @@ -2417,7 +2874,19 @@ cli-cursor@^3.1.0: dependencies: restore-cursor "^3.1.0" -cli-table3@^0.6.1, cli-table3@^0.6.2: +cli-cursor@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/cli-cursor/-/cli-cursor-4.0.0.tgz#3cecfe3734bf4fe02a8361cbdc0f6fe28c6a57ea" + integrity sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg== + dependencies: + restore-cursor "^4.0.0" + +cli-spinners@^2.5.0: + version "2.7.0" + resolved "https://registry.yarnpkg.com/cli-spinners/-/cli-spinners-2.7.0.tgz#f815fd30b5f9eaac02db604c7a231ed7cb2f797a" + integrity sha512-qu3pN8Y3qHNgE2AFweciB1IfMnmZ/fsNTEE+NOFjmGB2F/7rLhnhzppvpCnN4FovtP26k8lHyy9ptEbNwWFLzw== + +cli-table3@^0.6.1, cli-table3@^0.6.3: version "0.6.3" resolved "https://registry.yarnpkg.com/cli-table3/-/cli-table3-0.6.3.tgz#61ab765aac156b52f222954ffc607a6f01dbeeb2" integrity sha512-w5Jac5SykAeZJKntOxJCrm63Eg5/4dhMWIcuTbo9rpE+brgaSZo0RuNJZeOyMgsUdhDeojvgyQLmjI+K50ZGyg== @@ -2426,30 +2895,18 @@ cli-table3@^0.6.1, cli-table3@^0.6.2: optionalDependencies: "@colors/colors" "1.5.0" -cli-truncate@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/cli-truncate/-/cli-truncate-2.1.0.tgz#c39e28bf05edcde5be3b98992a22deed5a2b93c7" - integrity sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg== - dependencies: - slice-ansi "^3.0.0" - string-width "^4.2.0" - -cli-truncate@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/cli-truncate/-/cli-truncate-3.1.0.tgz#3f23ab12535e3d73e839bb43e73c9de487db1389" - integrity sha512-wfOBkjXteqSnI59oPcJkcPl/ZmwvMMOj340qUIY1SKZCv0B9Cf4D4fAucRkIKQmsIuYK3x1rrgU7MeGRruiuiA== +cli-truncate@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/cli-truncate/-/cli-truncate-4.0.0.tgz#6cc28a2924fee9e25ce91e973db56c7066e6172a" + integrity sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA== dependencies: slice-ansi "^5.0.0" - string-width "^5.0.0" + string-width "^7.0.0" -cliui@^7.0.2: - version "7.0.4" - resolved "https://registry.yarnpkg.com/cliui/-/cliui-7.0.4.tgz#a0265ee655476fc807aea9df3df8df7783808b4f" - integrity sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ== - dependencies: - string-width "^4.2.0" - strip-ansi "^6.0.0" - wrap-ansi "^7.0.0" +cli-width@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/cli-width/-/cli-width-3.0.0.tgz#a2f48437a2caa9a22436e794bf071ec9e61cedf6" + integrity sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw== cliui@^8.0.1: version "8.0.1" @@ -2460,31 +2917,20 @@ cliui@^8.0.1: strip-ansi "^6.0.1" wrap-ansi "^7.0.0" -clone-deep@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/clone-deep/-/clone-deep-4.0.1.tgz#c19fd9bdbbf85942b4fd979c84dcf7d5f07c2387" - integrity sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ== - dependencies: - is-plain-object "^2.0.4" - kind-of "^6.0.2" - shallow-clone "^3.0.0" - clone@^1.0.2: version "1.0.4" resolved "https://registry.yarnpkg.com/clone/-/clone-1.0.4.tgz#da309cc263df15994c688ca902179ca3c7cd7c7e" integrity sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg== -cmd-shim@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/cmd-shim/-/cmd-shim-5.0.0.tgz#8d0aaa1a6b0708630694c4dbde070ed94c707724" - integrity sha512-qkCtZ59BidfEwHltnJwkyVZn+XQojdAySM1D1gSeh11Z4pW1Kpolkyo53L5noc0nrxmIvyFwTmJRo4xs7FFLPw== - dependencies: - mkdirp-infer-owner "^2.0.0" +cmd-shim@^6.0.0: + version "6.0.1" + resolved "https://registry.yarnpkg.com/cmd-shim/-/cmd-shim-6.0.1.tgz#a65878080548e1dca760b3aea1e21ed05194da9d" + integrity sha512-S9iI9y0nKR4hwEQsVWpyxld/6kRfGepGfzff83FcaiEBpmvlbA2nnGe7Cylgrx2f/p1P5S5wpRm9oL8z1PbS3Q== co@^4.6.0: version "4.6.0" resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184" - integrity sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ= + integrity sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ== collect-v8-coverage@^1.0.0: version "1.0.1" @@ -2508,7 +2954,7 @@ color-convert@^2.0.1: color-name@1.1.3: version "1.1.3" resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25" - integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU= + integrity sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw== color-name@~1.1.4: version "1.1.4" @@ -2520,15 +2966,15 @@ color-support@^1.1.3: resolved "https://registry.yarnpkg.com/color-support/-/color-support-1.1.3.tgz#93834379a1cc9a0c61f82f52f0d04322251bd5a2" integrity sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg== -colorette@^2.0.14: - version "2.0.16" - resolved "https://registry.yarnpkg.com/colorette/-/colorette-2.0.16.tgz#713b9af84fdb000139f04546bd4a93f62a5085da" - integrity sha512-hUewv7oMjCp+wkBv5Rm0v87eJhq4woh5rSR+42YSQJKecCqgIqNkZ6lAlQms/BwHPJA5NKMRlpxPRv0n8HQW6g== +colorette@^2.0.20: + version "2.0.20" + resolved "https://registry.yarnpkg.com/colorette/-/colorette-2.0.20.tgz#9eb793e6833067f7235902fcd3b09917a000a95a" + integrity sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w== -colorette@^2.0.19: - version "2.0.19" - resolved "https://registry.yarnpkg.com/colorette/-/colorette-2.0.19.tgz#cdf044f47ad41a0f4b56b3a0d5b4e6e1a2d5a798" - integrity sha512-3tlv/dIP7FWvj3BsbHrGLJ6l/oKh1O3TcgBqMn+yyCagOxc23fyzDS6HypQbgxWbkpDnf52p1LuR4eWDQ/K9WQ== +colors@1.4.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/colors/-/colors-1.4.0.tgz#c50491479d4c1bdaed2c9ced32cf7c7dc2360f78" + integrity sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA== columnify@^1.6.0: version "1.6.0" @@ -2538,32 +2984,35 @@ columnify@^1.6.0: strip-ansi "^6.0.1" wcwidth "^1.0.0" -combined-stream@^1.0.8: - version "1.0.8" - resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f" - integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg== - dependencies: - delayed-stream "~1.0.0" +commander@11.1.0: + version "11.1.0" + resolved "https://registry.yarnpkg.com/commander/-/commander-11.1.0.tgz#62fdce76006a68e5c1ab3314dc92e800eb83d906" + integrity sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ== -commander@^2.20.0, commander@^2.20.3: +commander@^2.20.0: version "2.20.3" resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== -commander@^7.0.0: - version "7.2.0" - resolved "https://registry.yarnpkg.com/commander/-/commander-7.2.0.tgz#a36cb57d0b501ce108e4d20559a150a391d97ab7" - integrity sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw== - -commander@^8.3.0: - version "8.3.0" - resolved "https://registry.yarnpkg.com/commander/-/commander-8.3.0.tgz#4837ea1b2da67b9c616a67afbb0fafee567bca66" - integrity sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww== - -commander@^9.4.1: - version "9.5.0" - resolved "https://registry.yarnpkg.com/commander/-/commander-9.5.0.tgz#bc08d1eb5cedf7ccb797a96199d41c7bc3e60d30" - integrity sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ== +commitizen@4.3.0, commitizen@^4.0.3: + version "4.3.0" + resolved "https://registry.yarnpkg.com/commitizen/-/commitizen-4.3.0.tgz#0d056c542a2d2b1f9b9aba981aa32575b2849924" + integrity sha512-H0iNtClNEhT0fotHvGV3E9tDejDeS04sN1veIebsKYGMuGscFaswRoYJKmT3eW85eIJAs0F28bG2+a/9wCOfPw== + dependencies: + cachedir "2.3.0" + cz-conventional-changelog "3.3.0" + dedent "0.7.0" + detect-indent "6.1.0" + find-node-modules "^2.1.2" + find-root "1.1.0" + fs-extra "9.1.0" + glob "7.2.3" + inquirer "8.2.5" + is-utf8 "^0.2.1" + lodash "4.17.21" + minimist "1.2.7" + strip-bom "4.0.0" + strip-json-comments "3.1.1" common-ancestor-path@^1.0.1: version "1.0.1" @@ -2581,7 +3030,7 @@ compare-func@^2.0.0: concat-map@0.0.1: version "0.0.1" resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" - integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s= + integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg== config-chain@^1.1.11: version "1.1.13" @@ -2604,6 +3053,27 @@ conventional-changelog-angular@^5.0.0: compare-func "^2.0.0" q "^1.5.1" +conventional-changelog-angular@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/conventional-changelog-angular/-/conventional-changelog-angular-6.0.0.tgz#a9a9494c28b7165889144fd5b91573c4aa9ca541" + integrity sha512-6qLgrBF4gueoC7AFVHu51nHL9pF9FRjXrH+ceVf7WmAfH3gs+gEYOkvxhjMPjZu57I4AGUGoNTY8V7Hrgf1uqg== + dependencies: + compare-func "^2.0.0" + +conventional-changelog-angular@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/conventional-changelog-angular/-/conventional-changelog-angular-7.0.0.tgz#5eec8edbff15aa9b1680a8dcfbd53e2d7eb2ba7a" + integrity sha512-ROjNchA9LgfNMTTFSIWPzebCwOGFdgkEq45EnvvrmSLvCtAw0HSmrCs7/ty+wAeYUZyNay0YMUNYFTRL72PkBQ== + dependencies: + compare-func "^2.0.0" + +conventional-changelog-conventionalcommits@^6.1.0: + version "6.1.0" + resolved "https://registry.yarnpkg.com/conventional-changelog-conventionalcommits/-/conventional-changelog-conventionalcommits-6.1.0.tgz#3bad05f4eea64e423d3d90fc50c17d2c8cf17652" + integrity sha512-3cS3GEtR78zTfMzk0AizXKKIdN4OvSh7ibNz6/DPbhWWQu7LqE/8+/GqSodV+sywUR2gpJAdP/1JFf4XtN7Zpw== + dependencies: + compare-func "^2.0.0" + conventional-changelog-writer@^5.0.0: version "5.0.1" resolved "https://registry.yarnpkg.com/conventional-changelog-writer/-/conventional-changelog-writer-5.0.1.tgz#e0757072f045fe03d91da6343c843029e702f359" @@ -2619,6 +3089,11 @@ conventional-changelog-writer@^5.0.0: split "^1.0.0" through2 "^4.0.0" +conventional-commit-types@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/conventional-commit-types/-/conventional-commit-types-3.0.0.tgz#7c9214e58eae93e85dd66dbfbafe7e4fffa2365b" + integrity sha512-SmmCYnOniSsAa9GqWOeLqc179lfr5TRu5b4QFDkbsrJ5TZjPJx85wtOr3zn+1dbeNiXDKGPbZ72IKbPhLXh/Lg== + conventional-commits-filter@^2.0.0, conventional-commits-filter@^2.0.7: version "2.0.7" resolved "https://registry.yarnpkg.com/conventional-commits-filter/-/conventional-commits-filter-2.0.7.tgz#f8d9b4f182fce00c9af7139da49365b136c8a0b3" @@ -2627,6 +3102,11 @@ conventional-commits-filter@^2.0.0, conventional-commits-filter@^2.0.7: lodash.ismatch "^4.4.0" modify-values "^1.0.0" +conventional-commits-filter@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/conventional-commits-filter/-/conventional-commits-filter-4.0.0.tgz#845d713e48dc7d1520b84ec182e2773c10c7bf7f" + integrity sha512-rnpnibcSOdFcdclpFwWa+pPlZJhXE7l+XK04zxhbWrhgpR96h33QLz8hITTXbcYICxVr3HZFtbtUAQ+4LdBo9A== + conventional-commits-parser@^3.2.3: version "3.2.4" resolved "https://registry.yarnpkg.com/conventional-commits-parser/-/conventional-commits-parser-3.2.4.tgz#a7d3b77758a202a9b2293d2112a8d8052c740972" @@ -2639,12 +3119,30 @@ conventional-commits-parser@^3.2.3: split2 "^3.0.0" through2 "^4.0.0" -convert-source-map@^1.6.0, convert-source-map@^1.7.0: - version "1.8.0" - resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.8.0.tgz#f3373c32d21b4d780dd8004514684fb791ca4369" - integrity sha512-+OQdjP49zViI/6i7nIJpA8rAl4sV/JdPfU9nZs3VqOwGIgizICvuN2ru6fMd+4llL0tar18UYJXfZ/TWtmhUjA== +conventional-commits-parser@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/conventional-commits-parser/-/conventional-commits-parser-4.0.0.tgz#02ae1178a381304839bce7cea9da5f1b549ae505" + integrity sha512-WRv5j1FsVM5FISJkoYMR6tPk07fkKT0UodruX4je86V4owk451yjXAKzKAPOs9l7y59E2viHUS9eQ+dfUA9NSg== dependencies: - safe-buffer "~5.1.1" + JSONStream "^1.3.5" + is-text-path "^1.0.1" + meow "^8.1.2" + split2 "^3.2.2" + +conventional-commits-parser@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/conventional-commits-parser/-/conventional-commits-parser-5.0.0.tgz#57f3594b81ad54d40c1b4280f04554df28627d9a" + integrity sha512-ZPMl0ZJbw74iS9LuX9YIAiW8pfM5p3yh2o/NbXHbkFuZzY5jvdi5jFycEOkmBW5H5I7nA+D6f3UcsCLP2vvSEA== + dependencies: + JSONStream "^1.3.5" + is-text-path "^2.0.0" + meow "^12.0.1" + split2 "^4.0.0" + +convert-source-map@^1.6.0, convert-source-map@^1.7.0: + version "1.9.0" + resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.9.0.tgz#7faae62353fb4213366d0ca98358d22e8368b05f" + integrity sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A== convert-source-map@^2.0.0: version "2.0.0" @@ -2656,49 +3154,40 @@ core-util-is@~1.0.0: resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.3.tgz#a6042d3634c2b27e9328f837b965fac83808db85" integrity sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ== -cosmiconfig@^7.0.0: - version "7.1.0" - resolved "https://registry.yarnpkg.com/cosmiconfig/-/cosmiconfig-7.1.0.tgz#1443b9afa596b670082ea46cbd8f6a62b84635f6" - integrity sha512-AdmX6xUzdNASswsFtmwSt7Vj8po9IuqXm0UXz7QKPuEUmPB4XyjGfaAr2PSuELMwkRMVH1EpIkX5bTZGRB3eCA== +cosmiconfig-typescript-loader@^4.0.0: + version "4.3.0" + resolved "https://registry.yarnpkg.com/cosmiconfig-typescript-loader/-/cosmiconfig-typescript-loader-4.3.0.tgz#c4259ce474c9df0f32274ed162c0447c951ef073" + integrity sha512-NTxV1MFfZDLPiBMjxbHRwSh5LaLcPMwNdCutmnHJCKoVnlvldPWlllonKwrsRJ5pYZBIBGRWWU2tfvzxgeSW5Q== + +cosmiconfig@^8.0.0: + version "8.0.0" + resolved "https://registry.yarnpkg.com/cosmiconfig/-/cosmiconfig-8.0.0.tgz#e9feae014eab580f858f8a0288f38997a7bebe97" + integrity sha512-da1EafcpH6b/TD8vDRaWV7xFINlHlF6zKsGwS1TsuVJTZRkquaS5HTMq7uq6h31619QjbsYl21gVDOm32KM1vQ== dependencies: - "@types/parse-json" "^4.0.0" import-fresh "^3.2.1" + js-yaml "^4.1.0" parse-json "^5.0.0" path-type "^4.0.0" - yaml "^1.10.0" - -create-ecdh@^4.0.0: - version "4.0.4" - resolved "https://registry.yarnpkg.com/create-ecdh/-/create-ecdh-4.0.4.tgz#d6e7f4bffa66736085a0762fd3a632684dabcc4e" - integrity sha512-mf+TCx8wWc9VpuxfP2ht0iSISLZnt0JgWlrOKZiNqyUZWnjIaCIVNQArMHnCZKfEYRg6IM7A+NeJoN8gf/Ws0A== - dependencies: - bn.js "^4.1.0" - elliptic "^6.5.3" -create-hash@1.2.0, create-hash@^1.1.0, create-hash@^1.1.2, create-hash@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/create-hash/-/create-hash-1.2.0.tgz#889078af11a63756bcfb59bd221996be3a9ef196" - integrity sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg== +create-jest@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/create-jest/-/create-jest-29.7.0.tgz#a355c5b3cb1e1af02ba177fe7afd7feee49a5320" + integrity sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q== dependencies: - cipher-base "^1.0.1" - inherits "^2.0.1" - md5.js "^1.3.4" - ripemd160 "^2.0.1" - sha.js "^2.4.0" + "@jest/types" "^29.6.3" + chalk "^4.0.0" + exit "^0.1.2" + graceful-fs "^4.2.9" + jest-config "^29.7.0" + jest-util "^29.7.0" + prompts "^2.0.1" -create-hmac@^1.1.0, create-hmac@^1.1.4, create-hmac@^1.1.7: - version "1.1.7" - resolved "https://registry.yarnpkg.com/create-hmac/-/create-hmac-1.1.7.tgz#69170c78b3ab957147b2b8b04572e47ead2243ff" - integrity sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg== - dependencies: - cipher-base "^1.0.3" - create-hash "^1.1.0" - inherits "^2.0.1" - ripemd160 "^2.0.0" - safe-buffer "^5.0.1" - sha.js "^2.4.8" +create-require@^1.1.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/create-require/-/create-require-1.1.1.tgz#c1d7e8f1e5f6cfc9ff65f9cd352d37348756c333" + integrity sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ== -cross-spawn@^7.0.2, cross-spawn@^7.0.3: +cross-spawn@^7.0.0, cross-spawn@^7.0.2, cross-spawn@^7.0.3: version "7.0.3" resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.3.tgz#f73a85b9d5d41d045551c177e2882d4ac85728a6" integrity sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w== @@ -2707,71 +3196,54 @@ cross-spawn@^7.0.2, cross-spawn@^7.0.3: shebang-command "^2.0.0" which "^2.0.1" -crypto-browserify@3.12.0: - version "3.12.0" - resolved "https://registry.yarnpkg.com/crypto-browserify/-/crypto-browserify-3.12.0.tgz#396cf9f3137f03e4b8e532c58f698254e00f80ec" - integrity sha512-fz4spIh+znjO2VjL+IdhEpRJ3YN6sMzITSBijk6FK2UvTqruSQW+/cCZTSNsMiZNvUeq0CqurF+dAbyiGOY6Wg== - dependencies: - browserify-cipher "^1.0.0" - browserify-sign "^4.0.0" - create-ecdh "^4.0.0" - create-hash "^1.1.0" - create-hmac "^1.1.0" - diffie-hellman "^5.0.0" - inherits "^2.0.1" - pbkdf2 "^3.0.3" - public-encrypt "^4.0.0" - randombytes "^2.0.0" - randomfill "^1.0.3" - -crypto-random-string@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/crypto-random-string/-/crypto-random-string-2.0.0.tgz#ef2a7a966ec11083388369baa02ebead229b30d5" - integrity sha512-v1plID3y9r/lPhviJ1wrXpLeyUIGAZ2SHNYTEapm7/8A9nLPoyvVp3RK/EPFqn5kEznyWgYZNsRtYYIWbuG8KA== - -css-select@^4.1.3: - version "4.3.0" - resolved "https://registry.yarnpkg.com/css-select/-/css-select-4.3.0.tgz#db7129b2846662fd8628cfc496abb2b59e41529b" - integrity sha512-wPpOYtnsVontu2mODhA19JrqWxNsfdatRKd64kmpRbQgh1KtItko5sTnEpPdpSaJszTOhEMlF/RPz28qj4HqhQ== +crypto-random-string@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/crypto-random-string/-/crypto-random-string-4.0.0.tgz#5a3cc53d7dd86183df5da0312816ceeeb5bb1fc2" + integrity sha512-x8dy3RnvYdlUcPOjkEHqozhiwzKNSq7GcPuXFbnyMOCHxX8V3OgIg/pYuabl2sbUPfIJaeAQB7PMOK8DFIdoRA== dependencies: - boolbase "^1.0.0" - css-what "^6.0.1" - domhandler "^4.3.1" - domutils "^2.8.0" - nth-check "^2.0.1" - -css-what@^6.0.1: - version "6.1.0" - resolved "https://registry.yarnpkg.com/css-what/-/css-what-6.1.0.tgz#fb5effcf76f1ddea2c81bdfaa4de44e79bac70f4" - integrity sha512-HTUrgRJ7r4dsZKU6GjmpfRK1O76h97Z8MfS1G0FozR+oF2kG6Vfe8JE6zwrkbxigziPHinCJ+gCPjA9EaBDtRw== + type-fest "^1.0.1" cssesc@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/cssesc/-/cssesc-3.0.0.tgz#37741919903b868565e1c09ea747445cd18983ee" integrity sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg== -cssfilter@0.0.10: - version "0.0.10" - resolved "https://registry.yarnpkg.com/cssfilter/-/cssfilter-0.0.10.tgz#c6d2672632a2e5c83e013e6864a42ce8defd20ae" - integrity sha1-xtJnJjKi5cg+AT5oZKQs6N79IK4= +cz-conventional-changelog@3.3.0: + version "3.3.0" + resolved "https://registry.yarnpkg.com/cz-conventional-changelog/-/cz-conventional-changelog-3.3.0.tgz#9246947c90404149b3fe2cf7ee91acad3b7d22d2" + integrity sha512-U466fIzU5U22eES5lTNiNbZ+d8dfcHcssH4o7QsdWaCcRs/feIPCxKYSWkYBNs5mny7MvEfwpTLWjvbm94hecw== + dependencies: + chalk "^2.4.1" + commitizen "^4.0.3" + conventional-commit-types "^3.0.0" + lodash.map "^4.5.1" + longest "^2.0.1" + word-wrap "^1.0.3" + optionalDependencies: + "@commitlint/load" ">6.1.1" + +dargs@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/dargs/-/dargs-7.0.0.tgz#04015c41de0bcb69ec84050f3d9be0caf8d6d5cc" + integrity sha512-2iy1EkLdlBzQGvbweYRFxmFath8+K7+AKB0TlhHWkNuH+TmovaMH/Wp7V7R4u7f4SnX3OgLsU9t1NI9ioDnUpg== + +data-uri-to-buffer@^4.0.0: + version "4.0.1" + resolved "https://registry.yarnpkg.com/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz#d8feb2b2881e6a4f58c2e08acfd0e2834e26222e" + integrity sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A== dateformat@^3.0.0: version "3.0.3" resolved "https://registry.yarnpkg.com/dateformat/-/dateformat-3.0.3.tgz#a6e37499a4d9a9cf85ef5872044d62901c9889ae" integrity sha512-jyCETtSl3VMZMWeRo7iY1FL19ges1t55hMo5yaam4Jrsm5EPL89UQkoQRyiI+Yf4k8r2ZpdngkV8hr1lIdjb3Q== -debug@4, debug@^4.0.0, debug@^4.0.1, debug@^4.1.0, debug@^4.1.1, debug@^4.3.3, debug@^4.3.4: +debug@4, debug@4.3.4, debug@^4.0.0, debug@^4.1.0, debug@^4.1.1, debug@^4.3.1, debug@^4.3.2, debug@^4.3.3, debug@^4.3.4: version "4.3.4" resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865" integrity sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ== dependencies: ms "2.1.2" -debuglog@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/debuglog/-/debuglog-1.0.1.tgz#aa24ffb9ac3df9a2351837cfb2d279360cd78492" - integrity sha512-syBZ+rnAK3EgMsH2aYEOLUW7mZSY9Gb+0wUMCFsZvcmiz+HigA0LOcq/HoQqVuGG+EKykunc7QG2bzrponfaSw== - decamelize-keys@^1.1.0: version "1.1.1" resolved "https://registry.yarnpkg.com/decamelize-keys/-/decamelize-keys-1.1.1.tgz#04a2d523b2f18d80d0158a43b895d56dff8d19d8" @@ -2785,11 +3257,16 @@ decamelize@^1.1.0: resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" integrity sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA== -dedent@^0.7.0: +dedent@0.7.0: version "0.7.0" resolved "https://registry.yarnpkg.com/dedent/-/dedent-0.7.0.tgz#2495ddbaf6eb874abb0e1be9df22d2e5a544326c" integrity sha512-Q6fKUPqnAHAyhiUgFU7BUzLiv0kd8saH9al7tnu5Q/okj6dnupxyTgFIBjVzJATdfIAm9NAsvXNzjaKa+bxVyA== +dedent@^1.0.0: + version "1.5.1" + resolved "https://registry.yarnpkg.com/dedent/-/dedent-1.5.1.tgz#4f3fc94c8b711e9bb2800d185cd6ad20f2a90aff" + integrity sha512-+LxW+KLWxu3HW3M2w2ympwtqPrqYRzU8fqi6Fhd18fBALe15blJPI/I4+UHveMVG6lJqB4JNd4UG0S5cnVHwIg== + deep-extend@^0.6.0: version "0.6.0" resolved "https://registry.yarnpkg.com/deep-extend/-/deep-extend-0.6.0.tgz#c4fa7c95404a17a9c3e8ca7e1537312b736330ac" @@ -2801,9 +3278,9 @@ deep-is@^0.1.3: integrity sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ== deepmerge@^4.2.2: - version "4.2.2" - resolved "https://registry.yarnpkg.com/deepmerge/-/deepmerge-4.2.2.tgz#44d2ea3679b8f4d4ffba33f03d865fc1e7bf4955" - integrity sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg== + version "4.3.0" + resolved "https://registry.yarnpkg.com/deepmerge/-/deepmerge-4.3.0.tgz#65491893ec47756d44719ae520e0e2609233b59b" + integrity sha512-z2wJZXrmeHdvYJp/Ux55wIjqo81G5Bp4c+oELTW+7ar6SogWHajt5a9gO3s3IDaGSAXjDk0vlQKN3rms8ab3og== defaults@^1.0.3: version "1.0.4" @@ -2812,46 +3289,6 @@ defaults@^1.0.3: dependencies: clone "^1.0.2" -define-properties@^1.1.3, define-properties@^1.1.4: - version "1.1.4" - resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.1.4.tgz#0b14d7bd7fbeb2f3572c3a7eda80ea5d57fb05b1" - integrity sha512-uckOqKcfaVvtBdsVkdPv3XjveQJsNQqmhXgRi8uhvWWuPYZCNlzT8qAyblUgNoXdHdjMTzAqeGjAoli8f+bzPA== - dependencies: - has-property-descriptors "^1.0.0" - object-keys "^1.1.1" - -del@^4.1.1: - version "4.1.1" - resolved "https://registry.yarnpkg.com/del/-/del-4.1.1.tgz#9e8f117222ea44a31ff3a156c049b99052a9f0b4" - integrity sha512-QwGuEUouP2kVwQenAsOof5Fv8K9t3D8Ca8NxcXKrIpEHjTXK5J2nXLdP+ALI1cgv8wj7KuwBhTwBkOZSJKM5XQ== - dependencies: - "@types/glob" "^7.1.1" - globby "^6.1.0" - is-path-cwd "^2.0.0" - is-path-in-cwd "^2.0.0" - p-map "^2.0.0" - pify "^4.0.1" - rimraf "^2.6.3" - -del@^6.0.0: - version "6.1.1" - resolved "https://registry.yarnpkg.com/del/-/del-6.1.1.tgz#3b70314f1ec0aa325c6b14eb36b95786671edb7a" - integrity sha512-ua8BhapfP0JUJKC/zV9yHHDW/rDoDxP4Zhn3AkA6/xT6gY7jYXJiaeyBZznYVujhZZET+UgcbZiQ7sN3WqcImg== - dependencies: - globby "^11.0.1" - graceful-fs "^4.2.4" - is-glob "^4.0.1" - is-path-cwd "^2.2.0" - is-path-inside "^3.0.2" - p-map "^4.0.0" - rimraf "^3.0.2" - slash "^3.0.0" - -delayed-stream@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" - integrity sha1-3zrhmayt+31ECqrgsp4icrJOxhk= - delegates@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/delegates/-/delegates-1.0.0.tgz#84c6e159b81904fdca59a0ef44cd870d31250f9a" @@ -2867,46 +3304,41 @@ deprecation@^2.0.0, deprecation@^2.3.1: resolved "https://registry.yarnpkg.com/deprecation/-/deprecation-2.3.1.tgz#6368cbdb40abf3373b525ac87e4a260c3a700919" integrity sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ== -des.js@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/des.js/-/des.js-1.0.1.tgz#5382142e1bdc53f85d86d53e5f4aa7deb91e0843" - integrity sha512-Q0I4pfFrv2VPd34/vfLrFOoRmlYj3OV50i7fskps1jZWK1kApMWWT9G6RRUeYedLcBDIhnSDaUvJMb3AhUlaEA== - dependencies: - inherits "^2.0.1" - minimalistic-assert "^1.0.0" +detect-file@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/detect-file/-/detect-file-1.0.0.tgz#f0d66d03672a825cb1b73bdb3fe62310c8e552b7" + integrity sha512-DtCOLG98P007x7wiiOmfI0fi3eIKyWiLTGJ2MDnVi/E04lWGbf+JzrRHMm0rgIIZJGtHpKpbVgLWHrv8xXpc3Q== + +detect-indent@6.1.0: + version "6.1.0" + resolved "https://registry.yarnpkg.com/detect-indent/-/detect-indent-6.1.0.tgz#592485ebbbf6b3b1ab2be175c8393d04ca0d57e6" + integrity sha512-reYkTUJAZb9gUuZ2RvVCNhVHdg62RHnJ7WJl8ftMi4diZ6NWlciOzQN88pUhSELEwflJht4oQDv0F0BMlwaYtA== detect-newline@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/detect-newline/-/detect-newline-3.1.0.tgz#576f5dfc63ae1a192ff192d8ad3af6308991b651" integrity sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA== -dezalgo@^1.0.0: - version "1.0.4" - resolved "https://registry.yarnpkg.com/dezalgo/-/dezalgo-1.0.4.tgz#751235260469084c132157dfa857f386d4c33d81" - integrity sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig== - dependencies: - asap "^2.0.0" - wrappy "1" - diff-sequences@^29.4.3: version "29.4.3" resolved "https://registry.yarnpkg.com/diff-sequences/-/diff-sequences-29.4.3.tgz#9314bc1fabe09267ffeca9cbafc457d8499a13f2" integrity sha512-ofrBgwpPhCD85kMKtE9RYFFq6OC1A89oW2vvgWZNCwxrUpRUILopY7lsYyMDSjc8g6U6aiO0Qubg6r4Wgt5ZnA== +diff-sequences@^29.6.3: + version "29.6.3" + resolved "https://registry.yarnpkg.com/diff-sequences/-/diff-sequences-29.6.3.tgz#4deaf894d11407c51efc8418012f9e70b84ea921" + integrity sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q== + +diff@^4.0.1: + version "4.0.2" + resolved "https://registry.yarnpkg.com/diff/-/diff-4.0.2.tgz#60f3aecb89d5fae520c11aa19efc2bb982aade7d" + integrity sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A== + diff@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/diff/-/diff-5.1.0.tgz#bc52d298c5ea8df9194800224445ed43ffc87e40" integrity sha512-D+mk+qE8VC/PAUrlAU34N+VfXev0ghe5ywmpqrawphmVZc1bEfn56uo9qpyGp1p4xpzOHkSW4ztBd6L7Xx4ACw== -diffie-hellman@^5.0.0: - version "5.0.3" - resolved "https://registry.yarnpkg.com/diffie-hellman/-/diffie-hellman-5.0.3.tgz#40e8ee98f55a2149607146921c63e1ae5f3d2875" - integrity sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg== - dependencies: - bn.js "^4.1.0" - miller-rabin "^4.0.0" - randombytes "^2.0.0" - dir-glob@^3.0.0, dir-glob@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/dir-glob/-/dir-glob-3.0.1.tgz#56dbf73d992a4a93ba1584f4534063fd2e41717f" @@ -2921,51 +3353,6 @@ doctrine@^3.0.0: dependencies: esutils "^2.0.2" -dom-converter@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/dom-converter/-/dom-converter-0.2.0.tgz#6721a9daee2e293682955b6afe416771627bb768" - integrity sha512-gd3ypIPfOMr9h5jIKq8E3sHOTCjeirnl0WK5ZdS1AW0Odt0b1PaWaHdJ4Qk4klv+YB9aJBS7mESXjFoDQPu6DA== - dependencies: - utila "~0.4" - -dom-serializer@^1.0.1: - version "1.4.1" - resolved "https://registry.yarnpkg.com/dom-serializer/-/dom-serializer-1.4.1.tgz#de5d41b1aea290215dc45a6dae8adcf1d32e2d30" - integrity sha512-VHwB3KfrcOOkelEG2ZOfxqLZdfkil8PtJi4P8N2MMXucZq2yLp75ClViUlOVwyoHEDjYU433Aq+5zWP61+RGag== - dependencies: - domelementtype "^2.0.1" - domhandler "^4.2.0" - entities "^2.0.0" - -domelementtype@^2.0.1, domelementtype@^2.2.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/domelementtype/-/domelementtype-2.3.0.tgz#5c45e8e869952626331d7aab326d01daf65d589d" - integrity sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw== - -domhandler@^4.0.0, domhandler@^4.2.0, domhandler@^4.3.1: - version "4.3.1" - resolved "https://registry.yarnpkg.com/domhandler/-/domhandler-4.3.1.tgz#8d792033416f59d68bc03a5aa7b018c1ca89279c" - integrity sha512-GrwoxYN+uWlzO8uhUXRl0P+kHE4GtVPfYzVLcUxPL7KNdHKj66vvlhiweIHqYYXWlw+T8iLMp42Lm67ghw4WMQ== - dependencies: - domelementtype "^2.2.0" - -domutils@^2.5.2, domutils@^2.8.0: - version "2.8.0" - resolved "https://registry.yarnpkg.com/domutils/-/domutils-2.8.0.tgz#4437def5db6e2d1f5d6ee859bd95ca7d02048135" - integrity sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A== - dependencies: - dom-serializer "^1.0.1" - domelementtype "^2.2.0" - domhandler "^4.2.0" - -dot-case@^3.0.4: - version "3.0.4" - resolved "https://registry.yarnpkg.com/dot-case/-/dot-case-3.0.4.tgz#9b2b670d00a431667a8a75ba29cd1b98809ce751" - integrity sha512-Kv5nKlh6yRrdrGvxeJ2e5y2eRUpkUosIW4A2AS38zwSz27zu7ufDwQPi5Jhs3XAlGNetl3bmnGhQsMtkKJnj3w== - dependencies: - no-case "^3.0.4" - tslib "^2.0.3" - dot-prop@^5.1.0: version "5.3.0" resolved "https://registry.yarnpkg.com/dot-prop/-/dot-prop-5.3.0.tgz#90ccce708cd9cd82cc4dc8c3ddd9abdd55b20e88" @@ -2973,6 +3360,11 @@ dot-prop@^5.1.0: dependencies: is-obj "^2.0.0" +dotenv@16.4.2: + version "16.4.2" + resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-16.4.2.tgz#7ca798f89ae2011846bbdbf6470785307754120d" + integrity sha512-rZSSFxke7d9nYQ5NeMIwp5PP+f8wXgKNljpOb7KtH6SKW1cEqcXAz9VSJYVLKe7Jhup/gUYOkaeSVyK8GJ+nBg== + duplexer2@~0.1.0: version "0.1.4" resolved "https://registry.yarnpkg.com/duplexer2/-/duplexer2-0.1.4.tgz#8b12dab878c0d69e3e7891051662a32fc6bddcc1" @@ -2980,39 +3372,36 @@ duplexer2@~0.1.0: dependencies: readable-stream "^2.0.2" +duplexer@0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/duplexer/-/duplexer-0.1.1.tgz#ace6ff808c1ce66b57d1ebf97977acb02334cfc1" + integrity sha512-sxNZ+ljy+RA1maXoUReeqBBpBC6RLKmg5ewzV+x+mSETmWNoKdZN6vcQjpFROemza23hGFskJtFNoUWUaQ+R4Q== + +duplexer@^0.1.2: + version "0.1.2" + resolved "https://registry.yarnpkg.com/duplexer/-/duplexer-0.1.2.tgz#3abe43aef3835f8ae077d136ddce0f276b0400e6" + integrity sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg== + eastasianwidth@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/eastasianwidth/-/eastasianwidth-0.2.0.tgz#696ce2ec0aa0e6ea93a397ffcf24aa7840c827cb" integrity sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA== -electron-to-chromium@^1.4.118: - version "1.4.132" - resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.132.tgz#b64599eb018221e52e2e4129de103b03a413c55d" - integrity sha512-JYdZUw/1068NWN+SwXQ7w6Ue0bWYGihvSUNNQwurvcDV/SM7vSiGZ3NuFvFgoEiCs4kB8xs3cX2an3wB7d4TBw== - electron-to-chromium@^1.4.284: version "1.4.301" resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.301.tgz#175d9fa1509a5b062752c6db321051e610fe2eae" integrity sha512-bz00ASIIDjcgszZKuEA1JEFhbDjqUNbQ/PEhNEl1wbixzYpeTp2H2QWjsQvAL2T1wJBdOwCF5hE896BoMwYKrA== -elliptic@6.5.4, elliptic@^6.5.3, elliptic@^6.5.4: - version "6.5.4" - resolved "https://registry.yarnpkg.com/elliptic/-/elliptic-6.5.4.tgz#da37cebd31e79a1367e941b592ed1fbebd58abbb" - integrity sha512-iLhC6ULemrljPZb+QutR5TQGB+pdW6KGD5RSegS+8sorOZT+rdQFbsQFJgvN3eRqNALqJer4oQ16YvJHlU8hzQ== - dependencies: - bn.js "^4.11.9" - brorand "^1.1.0" - hash.js "^1.0.0" - hmac-drbg "^1.0.1" - inherits "^2.0.4" - minimalistic-assert "^1.0.1" - minimalistic-crypto-utils "^1.0.1" - emittery@^0.13.1: version "0.13.1" resolved "https://registry.yarnpkg.com/emittery/-/emittery-0.13.1.tgz#c04b8c3457490e0847ae51fced3af52d338e3dad" integrity sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ== +emoji-regex@^10.3.0: + version "10.3.0" + resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-10.3.0.tgz#76998b9268409eb3dae3de989254d456e70cfe23" + integrity sha512-QpLs9D9v9kArv4lfDEgg1X/gN5XLnf/A6l9cs8SPZLRZR3ZkY9+kwIQTxm+fsSej5UMYGE8fdoaZVIBlqG0XTw== + emoji-regex@^8.0.0: version "8.0.0" resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" @@ -3030,45 +3419,19 @@ encoding@^0.1.13: dependencies: iconv-lite "^0.6.2" -enhanced-resolve@^5.0.0, enhanced-resolve@^5.10.0: - version "5.10.0" - resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-5.10.0.tgz#0dc579c3bb2a1032e357ac45b8f3a6f3ad4fb1e6" - integrity sha512-T0yTFjdpldGY8PmuXXR0PyQ1ufZpEGiHVrp7zHKB7jdR4qlmZHhONVM5AQOAWXuF/w3dnHbEQVrNptJgt7F+cQ== - dependencies: - graceful-fs "^4.2.4" - tapable "^2.2.0" - -enquirer@^2.3.5: - version "2.3.6" - resolved "https://registry.yarnpkg.com/enquirer/-/enquirer-2.3.6.tgz#2a7fe5dd634a1e4125a975ec994ff5456dc3734d" - integrity sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg== +env-ci@^9.0.0: + version "9.0.0" + resolved "https://registry.yarnpkg.com/env-ci/-/env-ci-9.0.0.tgz#53df706b4b841f5f05413402ef82049eba8e4af3" + integrity sha512-Q3cjr1tX9xwigprw4G8M3o7PIOO/1LYji6TyGsbD1WfMmD23etZvhgmPXJqkP788yH4dgSSK7oaIMuaayUJIfg== dependencies: - ansi-colors "^4.1.1" - -entities@^2.0.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/entities/-/entities-2.2.0.tgz#098dc90ebb83d8dffa089d55256b351d34c4da55" - integrity sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A== - -env-ci@^5.0.0: - version "5.5.0" - resolved "https://registry.yarnpkg.com/env-ci/-/env-ci-5.5.0.tgz#43364e3554d261a586dec707bc32be81112b545f" - integrity sha512-o0JdWIbOLP+WJKIUt36hz1ImQQFuN92nhsfTkHHap+J8CiI8WgGpH/a9jEGHh4/TU5BUUGjlnKXNoDb57+ne+A== - dependencies: - execa "^5.0.0" - fromentries "^1.3.2" - java-properties "^1.0.0" + execa "^7.0.0" + java-properties "^1.0.2" env-paths@^2.2.0: version "2.2.1" resolved "https://registry.yarnpkg.com/env-paths/-/env-paths-2.2.1.tgz#420399d416ce1fbe9bc0a07c62fa68d67fd0f8f2" integrity sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A== -envinfo@^7.7.3: - version "7.8.1" - resolved "https://registry.yarnpkg.com/envinfo/-/envinfo-7.8.1.tgz#06377e3e5f4d379fea7ac592d5ad8927e0c4d475" - integrity sha512-/o+BXHmB7ocbHEAs6F2EnG0ogybVVUdkRunTT2glZU9XAaGmhqskrvKwqXuDfNjEO0LZKWdejEEpnq8aM0tOaw== - err-code@^2.0.2: version "2.0.3" resolved "https://registry.yarnpkg.com/err-code/-/err-code-2.0.3.tgz#23c2f3b756ffdfc608d30e27c9a941024807e7f9" @@ -3081,60 +3444,20 @@ error-ex@^1.3.1: dependencies: is-arrayish "^0.2.1" -es-abstract@^1.18.5, es-abstract@^1.19.5: - version "1.19.5" - resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.19.5.tgz#a2cb01eb87f724e815b278b0dd0d00f36ca9a7f1" - integrity sha512-Aa2G2+Rd3b6kxEUKTF4TaW67czBLyAv3z7VOhYRU50YBx+bbsYZ9xQP4lMNazePuFlybXI0V4MruPos7qUo5fA== - dependencies: - call-bind "^1.0.2" - es-to-primitive "^1.2.1" - function-bind "^1.1.1" - get-intrinsic "^1.1.1" - get-symbol-description "^1.0.0" - has "^1.0.3" - has-symbols "^1.0.3" - internal-slot "^1.0.3" - is-callable "^1.2.4" - is-negative-zero "^2.0.2" - is-regex "^1.1.4" - is-shared-array-buffer "^1.0.2" - is-string "^1.0.7" - is-weakref "^1.0.2" - object-inspect "^1.12.0" - object-keys "^1.1.1" - object.assign "^4.1.2" - string.prototype.trimend "^1.0.4" - string.prototype.trimstart "^1.0.4" - unbox-primitive "^1.0.1" - -es-module-lexer@^0.9.0: - version "0.9.3" - resolved "https://registry.yarnpkg.com/es-module-lexer/-/es-module-lexer-0.9.3.tgz#6f13db00cc38417137daf74366f535c8eb438f19" - integrity sha512-1HQ2M2sPtxwnvOvT1ZClHyQDiggdNjURWpY2we6aMKCQiUVxTmVs2UYPLIrD84sS+kMdUwfBSylbJPwNnBrnHQ== - -es-to-primitive@^1.2.1: - version "1.2.1" - resolved "https://registry.yarnpkg.com/es-to-primitive/-/es-to-primitive-1.2.1.tgz#e55cd4c9cdc188bcefb03b366c736323fc5c898a" - integrity sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA== - dependencies: - is-callable "^1.1.4" - is-date-object "^1.0.1" - is-symbol "^1.0.2" - -es6-object-assign@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/es6-object-assign/-/es6-object-assign-1.1.0.tgz#c2c3582656247c39ea107cb1e6652b6f9f24523c" - integrity sha1-wsNYJlYkfDnqEHyx5mUrb58kUjw= - escalade@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/escalade/-/escalade-3.1.1.tgz#d8cfdc7000965c5a0174b4a82eaa5c0552742e40" integrity sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw== +escape-string-regexp@5.0.0, escape-string-regexp@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz#4683126b500b61762f2dbebace1806e8be31b1c8" + integrity sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw== + escape-string-regexp@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" - integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= + integrity sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg== escape-string-regexp@^2.0.0: version "2.0.0" @@ -3146,10 +3469,10 @@ escape-string-regexp@^4.0.0: resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34" integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA== -eslint-config-prettier@8.6.0: - version "8.6.0" - resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-8.6.0.tgz#dec1d29ab728f4fa63061774e1672ac4e363d207" - integrity sha512-bAF0eLpLVqP5oEVUFKpMA+NnRFICwn9X8B5jrR9FcqnYBuPbqWEjTEspPWMj5ye6czoSLDweCzSo3Ko7gGrZaA== +eslint-config-prettier@9.1.0: + version "9.1.0" + resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-9.1.0.tgz#31af3d94578645966c082fcb71a5846d3c94867f" + integrity sha512-NSWl5BFQWEPi1j4TjVNItzYV7dZXZ+wP6I6ZhrBGpChQhZRUaElihE9uRRkcbRnNb76UMKDF3r+WTmNcGPKsqw== eslint-plugin-prettier@4.2.1: version "4.2.1" @@ -3158,114 +3481,85 @@ eslint-plugin-prettier@4.2.1: dependencies: prettier-linter-helpers "^1.0.0" -eslint-plugin-security@1.7.1: - version "1.7.1" - resolved "https://registry.yarnpkg.com/eslint-plugin-security/-/eslint-plugin-security-1.7.1.tgz#0e9c4a471f6e4d3ca16413c7a4a51f3966ba16e4" - integrity sha512-sMStceig8AFglhhT2LqlU5r+/fn9OwsA72O5bBuQVTssPCdQAOQzL+oMn/ZcpeUY6KcNfLJArgcrsSULNjYYdQ== - dependencies: - safe-regex "^2.1.1" - -eslint-scope@5.1.1, eslint-scope@^5.1.1: - version "5.1.1" - resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-5.1.1.tgz#e786e59a66cb92b3f6c1fb0d508aab174848f48c" - integrity sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw== +eslint-scope@^7.2.2: + version "7.2.2" + resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-7.2.2.tgz#deb4f92563390f32006894af62a22dba1c46423f" + integrity sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg== dependencies: esrecurse "^4.3.0" - estraverse "^4.1.1" - -eslint-utils@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-2.1.0.tgz#d2de5e03424e707dc10c74068ddedae708741b27" - integrity sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg== - dependencies: - eslint-visitor-keys "^1.1.0" - -eslint-utils@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-3.0.0.tgz#8aebaface7345bb33559db0a1f13a1d2d48c3672" - integrity sha512-uuQC43IGctw68pJA1RgbQS8/NP7rch6Cwd4j3ZBtgo4/8Flj4eGE7ZYSZRN3iq5pVUv6GPdW5Z1RFleo84uLDA== - dependencies: - eslint-visitor-keys "^2.0.0" - -eslint-visitor-keys@^1.1.0, eslint-visitor-keys@^1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz#30ebd1ef7c2fdff01c3a4f151044af25fab0523e" - integrity sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ== - -eslint-visitor-keys@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-2.1.0.tgz#f65328259305927392c938ed44eb0a5c9b2bd303" - integrity sha512-0rSmRBzXgDzIsD6mGdJgevzgezI534Cer5L/vyMX0kHzT/jiB43jRhd9YUlMGYLQy2zprNmoT8qasCGtY+QaKw== + estraverse "^5.2.0" eslint-visitor-keys@^3.3.0: version "3.3.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-3.3.0.tgz#f6480fa6b1f30efe2d1968aa8ac745b862469826" integrity sha512-mQ+suqKJVyeuwGYHAdjMFqjCyfl8+Ldnxuyp3ldiMBFKkvytrXUZWaiPCEav8qDHKty44bD+qV1IP4T+w+xXRA== -eslint@7.32.0: - version "7.32.0" - resolved "https://registry.yarnpkg.com/eslint/-/eslint-7.32.0.tgz#c6d328a14be3fb08c8d1d21e12c02fdb7a2a812d" - integrity sha512-VHZ8gX+EDfz+97jGcgyGCyRia/dPOd6Xh9yPv8Bl1+SoaIwD+a/vlrOmGRUyOYu7MwUhc7CxqeaDZU13S4+EpA== - dependencies: - "@babel/code-frame" "7.12.11" - "@eslint/eslintrc" "^0.4.3" - "@humanwhocodes/config-array" "^0.5.0" - ajv "^6.10.0" +eslint-visitor-keys@^3.4.1, eslint-visitor-keys@^3.4.3: + version "3.4.3" + resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz#0cd72fe8550e3c2eae156a96a4dddcd1c8ac5800" + integrity sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag== + +eslint@8.49.0: + version "8.49.0" + resolved "https://registry.yarnpkg.com/eslint/-/eslint-8.49.0.tgz#09d80a89bdb4edee2efcf6964623af1054bf6d42" + integrity sha512-jw03ENfm6VJI0jA9U+8H5zfl5b+FvuU3YYvZRdZHOlU2ggJkxrlkJH4HcDrZpj6YwD8kuYqvQM8LyesoazrSOQ== + dependencies: + "@eslint-community/eslint-utils" "^4.2.0" + "@eslint-community/regexpp" "^4.6.1" + "@eslint/eslintrc" "^2.1.2" + "@eslint/js" "8.49.0" + "@humanwhocodes/config-array" "^0.11.11" + "@humanwhocodes/module-importer" "^1.0.1" + "@nodelib/fs.walk" "^1.2.8" + ajv "^6.12.4" chalk "^4.0.0" cross-spawn "^7.0.2" - debug "^4.0.1" + debug "^4.3.2" doctrine "^3.0.0" - enquirer "^2.3.5" escape-string-regexp "^4.0.0" - eslint-scope "^5.1.1" - eslint-utils "^2.1.0" - eslint-visitor-keys "^2.0.0" - espree "^7.3.1" - esquery "^1.4.0" + eslint-scope "^7.2.2" + eslint-visitor-keys "^3.4.3" + espree "^9.6.1" + esquery "^1.4.2" esutils "^2.0.2" fast-deep-equal "^3.1.3" file-entry-cache "^6.0.1" - functional-red-black-tree "^1.0.1" - glob-parent "^5.1.2" - globals "^13.6.0" - ignore "^4.0.6" - import-fresh "^3.0.0" + find-up "^5.0.0" + glob-parent "^6.0.2" + globals "^13.19.0" + graphemer "^1.4.0" + ignore "^5.2.0" imurmurhash "^0.1.4" is-glob "^4.0.0" - js-yaml "^3.13.1" + is-path-inside "^3.0.3" + js-yaml "^4.1.0" json-stable-stringify-without-jsonify "^1.0.1" levn "^0.4.1" lodash.merge "^4.6.2" - minimatch "^3.0.4" + minimatch "^3.1.2" natural-compare "^1.4.0" - optionator "^0.9.1" - progress "^2.0.0" - regexpp "^3.1.0" - semver "^7.2.1" - strip-ansi "^6.0.0" - strip-json-comments "^3.1.0" - table "^6.0.9" + optionator "^0.9.3" + strip-ansi "^6.0.1" text-table "^0.2.0" - v8-compile-cache "^2.0.3" -espree@^7.3.0, espree@^7.3.1: - version "7.3.1" - resolved "https://registry.yarnpkg.com/espree/-/espree-7.3.1.tgz#f2df330b752c6f55019f8bd89b7660039c1bbbb6" - integrity sha512-v3JCNCE64umkFpmkFGqzVKsOT0tN1Zr+ueqLZfpV1Ob8e+CEgPWa+OxCoGH3tnhimMKIaBm4m/vaRpJ/krRz2g== +espree@^9.6.0, espree@^9.6.1: + version "9.6.1" + resolved "https://registry.yarnpkg.com/espree/-/espree-9.6.1.tgz#a2a17b8e434690a5432f2f8018ce71d331a48c6f" + integrity sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ== dependencies: - acorn "^7.4.0" - acorn-jsx "^5.3.1" - eslint-visitor-keys "^1.3.0" + acorn "^8.9.0" + acorn-jsx "^5.3.2" + eslint-visitor-keys "^3.4.1" esprima@^4.0.0, esprima@~4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71" integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A== -esquery@^1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.4.0.tgz#2148ffc38b82e8c7057dfed48425b3e61f0f24a5" - integrity sha512-cCDispWt5vHHtwMY2YrAQ4ibFkAL8RbH5YGBnZBc90MolvvfkkQcJro/aZiAQUlQ3qgrYS6D6v8Gc5G5CQsc9w== +esquery@^1.4.2: + version "1.5.0" + resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.5.0.tgz#6ce17738de8577694edd7361c57182ac8cb0db0b" + integrity sha512-YQLXUplAwJgCydQ78IMJywZCceoqk1oH01OERdSAJc/7U2AylwjhSCLDEtqwg811idIS/9fIU5GjG73IgjKMVg== dependencies: estraverse "^5.1.0" @@ -3276,45 +3570,63 @@ esrecurse@^4.3.0: dependencies: estraverse "^5.2.0" -estraverse@^4.1.1: - version "4.3.0" - resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-4.3.0.tgz#398ad3f3c5a24948be7725e83d11a7de28cdbd1d" - integrity sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw== - estraverse@^5.1.0, estraverse@^5.2.0: version "5.3.0" resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-5.3.0.tgz#2eea5290702f26ab8fe5370370ff86c965d21123" integrity sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA== +estree-walker@^2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/estree-walker/-/estree-walker-2.0.2.tgz#52f010178c2a4c117a7757cfe942adb7d2da4cac" + integrity sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w== + esutils@^2.0.2: version "2.0.3" resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64" integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g== -ethers@6.0.8: - version "6.0.8" - resolved "https://registry.yarnpkg.com/ethers/-/ethers-6.0.8.tgz#a02e31f2771b66ecab6c731c1141b30d9de09174" - integrity sha512-j5smdMwn4t4vEARcfUv54mTJ2NMCorYLL51wPjFInEnrRr2SF5Sl9a7Z4DXS8UO1fBJVGHnjDDrF1b7msY3f7Q== +ethers@6.11.0: + version "6.11.0" + resolved "https://registry.yarnpkg.com/ethers/-/ethers-6.11.0.tgz#6d3e884ad36454c29d4662ae49439d5d04556c66" + integrity sha512-kPHNTnhVWiWU6AVo6CAeTjXEK24SpCXyZvwG9ROFjT0Vlux0EOhWKBAeC+45iDj80QNJTYaT1SDEmeunT0vDNw== dependencies: - "@adraffy/ens-normalize" "1.8.9" - "@noble/hashes" "1.1.2" - "@noble/secp256k1" "1.7.1" - aes-js "4.0.0-beta.3" + "@adraffy/ens-normalize" "1.10.1" + "@noble/curves" "1.2.0" + "@noble/hashes" "1.3.2" + "@types/node" "18.15.13" + aes-js "4.0.0-beta.5" tslib "2.4.0" ws "8.5.0" -events@^3.2.0: +event-target-shim@^5.0.0: + version "5.0.1" + resolved "https://registry.yarnpkg.com/event-target-shim/-/event-target-shim-5.0.1.tgz#5d4d3ebdf9583d63a5333ce2deb7480ab2b05789" + integrity sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ== + +eventemitter3@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/eventemitter3/-/eventemitter3-5.0.1.tgz#53f5ffd0a492ac800721bb42c66b841de96423c4" + integrity sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA== + +events@^3.3.0: version "3.3.0" resolved "https://registry.yarnpkg.com/events/-/events-3.3.0.tgz#31a95ad0a924e2d2c419a813aeb2c4e878ea7400" integrity sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q== -evp_bytestokey@^1.0.0, evp_bytestokey@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz#7fcbdb198dc71959432efe13842684e0525acb02" - integrity sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA== +execa@8.0.1, execa@^8.0.0: + version "8.0.1" + resolved "https://registry.yarnpkg.com/execa/-/execa-8.0.1.tgz#51f6a5943b580f963c3ca9c6321796db8cc39b8c" + integrity sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg== dependencies: - md5.js "^1.3.4" - safe-buffer "^5.1.1" + cross-spawn "^7.0.3" + get-stream "^8.0.1" + human-signals "^5.0.0" + is-stream "^3.0.0" + merge-stream "^2.0.0" + npm-run-path "^5.1.0" + onetime "^6.0.0" + signal-exit "^4.1.0" + strip-final-newline "^3.0.0" execa@^5.0.0: version "5.1.1" @@ -3331,14 +3643,14 @@ execa@^5.0.0: signal-exit "^3.0.3" strip-final-newline "^2.0.0" -execa@^6.1.0: - version "6.1.0" - resolved "https://registry.yarnpkg.com/execa/-/execa-6.1.0.tgz#cea16dee211ff011246556388effa0818394fb20" - integrity sha512-QVWlX2e50heYJcCPG0iWtf8r0xjEYfz/OYLGDYH+IyjWezzPNxz63qNFOu0l4YftGWuizFVZHHs8PrLU5p2IDA== +execa@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/execa/-/execa-7.0.0.tgz#2a44e20e73797f6c2df23889927972386157d7e4" + integrity sha512-tQbH0pH/8LHTnwTrsKWideqi6rFB/QNUawEwrn+WHyz7PX1Tuz2u7wfTvbaNBdP5JD5LVWxNo8/A8CHNZ3bV6g== dependencies: cross-spawn "^7.0.3" get-stream "^6.0.1" - human-signals "^3.0.1" + human-signals "^4.3.0" is-stream "^3.0.0" merge-stream "^2.0.0" npm-run-path "^5.1.0" @@ -3349,9 +3661,16 @@ execa@^6.1.0: exit@^0.1.2: version "0.1.2" resolved "https://registry.yarnpkg.com/exit/-/exit-0.1.2.tgz#0632638f8d877cc82107d30a0fff1a17cba1cd0c" - integrity sha1-BjJjj42HfMghB9MKD/8aF8uhzQw= + integrity sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ== + +expand-tilde@^2.0.0, expand-tilde@^2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/expand-tilde/-/expand-tilde-2.0.2.tgz#97e801aa052df02454de46b02bf621642cdc8502" + integrity sha512-A5EmesHW6rfnZ9ysHQjPdJRni0SRar0tjtG5MNtm9n5TUvsYU8oozprtRD4AqHxcZWWlVuAmQo2nWKfN9oyjTw== + dependencies: + homedir-polyfill "^1.0.1" -expect@^29.0.0, expect@^29.4.3: +expect@^29.0.0: version "29.4.3" resolved "https://registry.yarnpkg.com/expect/-/expect-29.4.3.tgz#5e47757316df744fe3b8926c3ae8a3ebdafff7fe" integrity sha512-uC05+Q7eXECFpgDrHdXA4k2rpMyStAYPItEDLyQDo5Ta7fVkJnNA/4zh/OIVkVVNZ1oOK1PipQoyNjuZ6sz6Dg== @@ -3362,6 +3681,31 @@ expect@^29.0.0, expect@^29.4.3: jest-message-util "^29.4.3" jest-util "^29.4.3" +expect@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/expect/-/expect-29.7.0.tgz#578874590dcb3214514084c08115d8aee61e11bc" + integrity sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw== + dependencies: + "@jest/expect-utils" "^29.7.0" + jest-get-type "^29.6.3" + jest-matcher-utils "^29.7.0" + jest-message-util "^29.7.0" + jest-util "^29.7.0" + +exponential-backoff@^3.1.1: + version "3.1.1" + resolved "https://registry.yarnpkg.com/exponential-backoff/-/exponential-backoff-3.1.1.tgz#64ac7526fe341ab18a39016cd22c787d01e00bf6" + integrity sha512-dX7e/LHVJ6W3DE1MHWi9S1EYzDESENfLrYohG2G++ovZrYOkm4Knwa0mc1cn84xJOR4KEU0WSchhLbd0UklbHw== + +external-editor@^3.0.3: + version "3.1.0" + resolved "https://registry.yarnpkg.com/external-editor/-/external-editor-3.1.0.tgz#cb03f740befae03ea4d283caed2741a83f335495" + integrity sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew== + dependencies: + chardet "^0.7.0" + iconv-lite "^0.4.24" + tmp "^0.0.33" + fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3: version "3.1.3" resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" @@ -3373,9 +3717,20 @@ fast-diff@^1.1.2: integrity sha512-xJuoT5+L99XlZ8twedaRf6Ax2TgQVxvgZOYoPKqZufmJib0tL2tegPBOZb1pVNgIhlqDlA0eO0c3wBvQcmzx4w== fast-glob@^3.2.9: - version "3.2.11" - resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.2.11.tgz#a1172ad95ceb8a16e20caa5c5e56480e5129c1d9" - integrity sha512-xrO3+1bxSo3ZVHAnqzyuewYT6aMFHRAd4Kcs92MAonjwQZLsK9d0SF1IyQ3k5PoirxTW0Oe/RqFgMQ6TcNE5Ew== + version "3.2.12" + resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.2.12.tgz#7f39ec99c2e6ab030337142da9e0c18f37afae80" + integrity sha512-DVj4CQIYYow0BlaelwK1pHl5n5cRSJfM60UA0zK891sVInoPri2Ekj7+e1CT3/3qxXenpI+nBBmQAcJPJgaj4w== + dependencies: + "@nodelib/fs.stat" "^2.0.2" + "@nodelib/fs.walk" "^1.2.3" + glob-parent "^5.1.2" + merge2 "^1.3.0" + micromatch "^4.0.4" + +fast-glob@^3.3.2: + version "3.3.2" + resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.3.2.tgz#a904501e57cfdd2ffcded45e99a54fef55e46129" + integrity sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow== dependencies: "@nodelib/fs.stat" "^2.0.2" "@nodelib/fs.walk" "^1.2.3" @@ -3391,27 +3746,35 @@ fast-json-stable-stringify@2.x, fast-json-stable-stringify@^2.0.0, fast-json-sta fast-levenshtein@^2.0.6: version "2.0.6" resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917" - integrity sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc= + integrity sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw== -fastest-levenshtein@^1.0.12: - version "1.0.12" - resolved "https://registry.yarnpkg.com/fastest-levenshtein/-/fastest-levenshtein-1.0.12.tgz#9990f7d3a88cc5a9ffd1f1745745251700d497e2" - integrity sha512-On2N+BpYJ15xIC974QNVuYGMOlEVt4s0EOI3wwMqOmK1fdDY+FN/zltPV8vosq4ad4c/gJ1KHScUn/6AWIgiow== +fastest-levenshtein@^1.0.16: + version "1.0.16" + resolved "https://registry.yarnpkg.com/fastest-levenshtein/-/fastest-levenshtein-1.0.16.tgz#210e61b6ff181de91ea9b3d1b84fdedd47e034e5" + integrity sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg== fastq@^1.6.0: - version "1.13.0" - resolved "https://registry.yarnpkg.com/fastq/-/fastq-1.13.0.tgz#616760f88a7526bdfc596b7cab8c18938c36b98c" - integrity sha512-YpkpUnK8od0o1hmeSc7UUs/eB/vIPWJYjKck2QKIzAf71Vm1AAQ3EbuZB3g2JIy+pg+ERD0vqI79KyZiB2e2Nw== + version "1.15.0" + resolved "https://registry.yarnpkg.com/fastq/-/fastq-1.15.0.tgz#d04d07c6a2a68fe4599fea8d2e103a937fae6b3a" + integrity sha512-wBrocU2LCXXa+lWBt8RoIRD89Fi8OdABODa/kEnyeyjS5aZO5/GNvI5sEINADqP/h8M29UHTHUb53sUu5Ihqdw== dependencies: reusify "^1.0.4" fb-watchman@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/fb-watchman/-/fb-watchman-2.0.1.tgz#fc84fb39d2709cf3ff6d743706157bb5708a8a85" - integrity sha512-DkPJKQeY6kKwmuMretBhr7G6Vodr7bFwDYTXIkfG1gjvNpaxBTQV3PbXg6bR1c1UP4jPOX0jHUbbHANL9vRjVg== + version "2.0.2" + resolved "https://registry.yarnpkg.com/fb-watchman/-/fb-watchman-2.0.2.tgz#e9524ee6b5c77e9e5001af0f85f3adbb8623255c" + integrity sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA== dependencies: bser "2.1.1" +fetch-blob@^3.1.2, fetch-blob@^3.1.4: + version "3.2.0" + resolved "https://registry.yarnpkg.com/fetch-blob/-/fetch-blob-3.2.0.tgz#f09b8d4bbd45adc6f0c20b7e787e793e309dcce9" + integrity sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ== + dependencies: + node-domexception "^1.0.0" + web-streams-polyfill "^3.0.3" + figures@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/figures/-/figures-2.0.0.tgz#3ab1a2d2a62c8bfb431a0c94cb797a2fce27c962" @@ -3426,6 +3789,14 @@ figures@^3.0.0: dependencies: escape-string-regexp "^1.0.5" +figures@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/figures/-/figures-5.0.0.tgz#126cd055052dea699f8a54e8c9450e6ecfc44d5f" + integrity sha512-ej8ksPF4x6e5wvK9yevct0UCXh8TTFlWGVLlgjZuoBH1HwjIfKE/IdL5mq89sFA7zELi1VhKpmtDnrs7zWyeyg== + dependencies: + escape-string-regexp "^5.0.0" + is-unicode-supported "^1.2.0" + file-entry-cache@^6.0.1: version "6.0.1" resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-6.0.1.tgz#211b2dd9659cb0394b073e7323ac3c933d522027" @@ -3433,6 +3804,11 @@ file-entry-cache@^6.0.1: dependencies: flat-cache "^3.0.4" +filesize@^6.1.0: + version "6.4.0" + resolved "https://registry.yarnpkg.com/filesize/-/filesize-6.4.0.tgz#914f50471dd66fdca3cefe628bd0cde4ef769bcd" + integrity sha512-mjFIpOHC4jbfcTfoh4rkWpI31mF7viw9ikj/JyLoKzqlwG/YsefKfvYlYhdYdg/9mtK2z1AzgN/0LvVQ3zdlSQ== + fill-range@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.0.1.tgz#1919a6a7c75fe38b2c7c77e5198535da9acdda40" @@ -3440,6 +3816,19 @@ fill-range@^7.0.1: dependencies: to-regex-range "^5.0.1" +find-node-modules@^2.1.2: + version "2.1.3" + resolved "https://registry.yarnpkg.com/find-node-modules/-/find-node-modules-2.1.3.tgz#3c976cff2ca29ee94b4f9eafc613987fc4c0ee44" + integrity sha512-UC2I2+nx1ZuOBclWVNdcnbDR5dlrOdVb7xNjmT/lHE+LsgztWks3dG7boJ37yTS/venXw84B/mAW9uHVoC5QRg== + dependencies: + findup-sync "^4.0.0" + merge "^2.1.1" + +find-root@1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/find-root/-/find-root-1.1.0.tgz#abcfc8ba76f708c42a97b3d685b7e9450bfb9ce4" + integrity sha512-NKfW6bec6GfKc0SGx1e07QZY9PE99u0Bft/0rzSD5k3sO/vwkVUpDUKVm5Gpp5Ue3YfShPFTX2070tDs5kB9Ng== + find-up@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/find-up/-/find-up-2.1.0.tgz#45d1b7e506c717ddd482775a2b77920a3c0c57a7" @@ -3455,12 +3844,38 @@ find-up@^4.0.0, find-up@^4.1.0: locate-path "^5.0.0" path-exists "^4.0.0" -find-versions@^4.0.0: +find-up@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/find-up/-/find-up-5.0.0.tgz#4c92819ecb7083561e4f4a240a86be5198f536fc" + integrity sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng== + dependencies: + locate-path "^6.0.0" + path-exists "^4.0.0" + +find-up@^6.3.0: + version "6.3.0" + resolved "https://registry.yarnpkg.com/find-up/-/find-up-6.3.0.tgz#2abab3d3280b2dc7ac10199ef324c4e002c8c790" + integrity sha512-v2ZsoEuVHYy8ZIlYqwPe/39Cy+cFDzp4dXPaxNvkEuouymu+2Jbz0PxpKarJHYJTmv2HWT3O382qY8l4jMWthw== + dependencies: + locate-path "^7.1.0" + path-exists "^5.0.0" + +find-versions@^5.1.0: + version "5.1.0" + resolved "https://registry.yarnpkg.com/find-versions/-/find-versions-5.1.0.tgz#973f6739ce20f5e439a27eba8542a4b236c8e685" + integrity sha512-+iwzCJ7C5v5KgcBuueqVoNiHVoQpwiUK5XFLjf0affFTep+Wcw93tPvmb8tqujDNmzhBDPddnWV/qgWSXgq+Hg== + dependencies: + semver-regex "^4.0.5" + +findup-sync@^4.0.0: version "4.0.0" - resolved "https://registry.yarnpkg.com/find-versions/-/find-versions-4.0.0.tgz#3c57e573bf97769b8cb8df16934b627915da4965" - integrity sha512-wgpWy002tA+wgmO27buH/9KzyEOQnKsG/R0yrcjPT9BOFm0zRBVQbZ95nRGXWMywS8YR5knRbpohio0bcJABxQ== + resolved "https://registry.yarnpkg.com/findup-sync/-/findup-sync-4.0.0.tgz#956c9cdde804052b881b428512905c4a5f2cdef0" + integrity sha512-6jvvn/12IC4quLBL1KNokxC7wWTvYncaVUYSoxWw7YykPLuRrnv4qdHcSOywOI5RpkOVGeQRtWM8/q+G6W6qfQ== dependencies: - semver-regex "^3.1.2" + detect-file "^1.0.0" + is-glob "^4.0.0" + micromatch "^4.0.2" + resolve-dir "^1.0.1" flat-cache@^3.0.4: version "3.0.4" @@ -3471,28 +3886,24 @@ flat-cache@^3.0.4: rimraf "^3.0.2" flatted@^3.1.0: - version "3.2.5" - resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.2.5.tgz#76c8584f4fc843db64702a6bd04ab7a8bd666da3" - integrity sha512-WIWGi2L3DyTUvUrwRKgGi9TwxQMUEqPOPQBVi71R96jZXJdFskXEmf54BoZaS1kknGODoIGASGEzBUYdyMCBJg== - -follow-redirects@^1.14.9: - version "1.15.0" - resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.15.0.tgz#06441868281c86d0dda4ad8bdaead2d02dca89d4" - integrity sha512-aExlJShTV4qOUOL7yF1U5tvLCB0xQuudbf6toyYA0E/acBNw71mvjFTnLaRp50aQaYocMR0a/RMMBIHeZnGyjQ== + version "3.2.7" + resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.2.7.tgz#609f39207cb614b89d0765b477cb2d437fbf9787" + integrity sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ== -foreach@^2.0.5: - version "2.0.5" - resolved "https://registry.yarnpkg.com/foreach/-/foreach-2.0.5.tgz#0bee005018aeb260d0a3af3ae658dd0136ec1b99" - integrity sha1-C+4AUBiusmDQo6865ljdATbsG5k= +foreground-child@^3.1.0: + version "3.1.1" + resolved "https://registry.yarnpkg.com/foreground-child/-/foreground-child-3.1.1.tgz#1d173e776d75d2772fed08efe4a0de1ea1b12d0d" + integrity sha512-TMKDUnIte6bfb5nWv7V/caI169OHgvwjb7V4WkeUvbQQdjr5rWKqHFiKWb/fcOwB+CzBT+qbWjvj+DVwRskpIg== + dependencies: + cross-spawn "^7.0.0" + signal-exit "^4.0.1" -form-data@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/form-data/-/form-data-4.0.0.tgz#93919daeaf361ee529584b9b31664dc12c9fa452" - integrity sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww== +formdata-polyfill@^4.0.10: + version "4.0.10" + resolved "https://registry.yarnpkg.com/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz#24807c31c9d402e002ab3d8c720144ceb8848423" + integrity sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g== dependencies: - asynckit "^0.4.0" - combined-stream "^1.0.8" - mime-types "^2.1.12" + fetch-blob "^3.1.2" from2@^2.3.0: version "2.3.0" @@ -3502,10 +3913,15 @@ from2@^2.3.0: inherits "^2.0.1" readable-stream "^2.0.0" -fromentries@^1.3.2: - version "1.3.2" - resolved "https://registry.yarnpkg.com/fromentries/-/fromentries-1.3.2.tgz#e4bca6808816bf8f93b52750f1127f5a6fd86e3a" - integrity sha512-cHEpEQHUg0f8XdtZCc2ZAhrHzKzT0MrFUTcvx+hfxYu7rGMDc5SKoXFh+n4YigxsHXRzc6OrCshdR1bWH6HHyg== +fs-extra@9.1.0: + version "9.1.0" + resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-9.1.0.tgz#5954460c764a8da2094ba3554bf839e6b9a7c86d" + integrity sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ== + dependencies: + at-least-node "^1.0.0" + graceful-fs "^4.2.0" + jsonfile "^6.0.1" + universalify "^2.0.0" fs-extra@^11.0.0: version "11.1.0" @@ -3523,12 +3939,26 @@ fs-minipass@^2.0.0, fs-minipass@^2.1.0: dependencies: minipass "^3.0.0" +fs-minipass@^3.0.0, fs-minipass@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/fs-minipass/-/fs-minipass-3.0.1.tgz#853809af15b6d03e27638d1ab6432e6b378b085d" + integrity sha512-MhaJDcFRTuLidHrIttu0RDGyyXs/IYHVmlcxfLAEFIWjc1vdLAkdwT7Ace2u7DbitWC0toKMl5eJZRYNVreIMw== + dependencies: + minipass "^4.0.0" + +fs-minipass@^3.0.3: + version "3.0.3" + resolved "https://registry.yarnpkg.com/fs-minipass/-/fs-minipass-3.0.3.tgz#79a85981c4dc120065e96f62086bf6f9dc26cc54" + integrity sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw== + dependencies: + minipass "^7.0.3" + fs.realpath@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" - integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= + integrity sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw== -fsevents@^2.3.2: +fsevents@^2.3.2, fsevents@~2.3.2: version "2.3.2" resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.2.tgz#8a526f78b8fdf4623b709e0b975c52c24c02fd1a" integrity sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA== @@ -3538,11 +3968,6 @@ function-bind@^1.1.1: resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d" integrity sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A== -functional-red-black-tree@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz#1b0ab3bd553b2a0d6399d29c0e3ea0b252078327" - integrity sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc= - gauge@^4.0.3: version "4.0.4" resolved "https://registry.yarnpkg.com/gauge/-/gauge-4.0.4.tgz#52ff0652f2bbf607a989793d53b751bef2328dce" @@ -3557,6 +3982,20 @@ gauge@^4.0.3: strip-ansi "^6.0.1" wide-align "^1.1.5" +gauge@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/gauge/-/gauge-5.0.0.tgz#e270ca9d97dae84abf64e5277ef1ebddc7dd1e2f" + integrity sha512-0s5T5eciEG7Q3ugkxAkFtaDhrrhXsCRivA5y8C9WMHWuI8UlMOJg7+Iwf7Mccii+Dfs3H5jHepU0joPVyQU0Lw== + dependencies: + aproba "^1.0.3 || ^2.0.0" + color-support "^1.1.3" + console-control-strings "^1.1.0" + has-unicode "^2.0.1" + signal-exit "^3.0.7" + string-width "^4.2.3" + strip-ansi "^6.0.1" + wide-align "^1.1.5" + gensync@^1.0.0-beta.2: version "1.0.0-beta.2" resolved "https://registry.yarnpkg.com/gensync/-/gensync-1.0.0-beta.2.tgz#32a6ee76c3d7f52d46b2b1ae5d93fea8580a25e0" @@ -3567,14 +4006,10 @@ get-caller-file@^2.0.5: resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e" integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg== -get-intrinsic@^1.0.2, get-intrinsic@^1.1.0, get-intrinsic@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.1.1.tgz#15f59f376f855c446963948f0d24cd3637b4abc6" - integrity sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q== - dependencies: - function-bind "^1.1.1" - has "^1.0.3" - has-symbols "^1.0.1" +get-east-asian-width@^1.0.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/get-east-asian-width/-/get-east-asian-width-1.2.0.tgz#5e6ebd9baee6fb8b7b6bd505221065f0cd91f64e" + integrity sha512-2nk+7SIVb14QrgXFHcm84tD4bKQz0RxPuMT8Ag5KPOq7J5fEmAg0UbXdTOSHqNuHSU28k55qnceesxXRZGzKWA== get-package-type@^0.1.0: version "0.1.0" @@ -3586,13 +4021,10 @@ get-stream@^6.0.0, get-stream@^6.0.1: resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-6.0.1.tgz#a262d8eef67aced57c2852ad6167526a43cbf7b7" integrity sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg== -get-symbol-description@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/get-symbol-description/-/get-symbol-description-1.0.0.tgz#7fdb81c900101fbd564dd5f1a30af5aadc1e58d6" - integrity sha512-2EmdH1YvIQiZpltCNgkuiUnyukzxM/R6NDJX31Ke3BG1Nq5b0S2PhX59UKi9vZpPDQVdqn+1IcaAwnzTT5vCjw== - dependencies: - call-bind "^1.0.2" - get-intrinsic "^1.1.1" +get-stream@^8.0.1: + version "8.0.1" + resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-8.0.1.tgz#def9dfd71742cd7754a7761ed43749a27d02eca2" + integrity sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA== git-log-parser@^1.2.0: version "1.2.0" @@ -3606,10 +4038,16 @@ git-log-parser@^1.2.0: through2 "~2.0.0" traverse "~0.6.6" -git-revision-webpack-plugin@5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/git-revision-webpack-plugin/-/git-revision-webpack-plugin-5.0.0.tgz#0683a6a110ece618499880431cd89e1eb597b536" - integrity sha512-RptQN/4UKcEPkCBmRy8kLPo5i8MnF8+XfAgFYN9gbwmKLTLx4YHsQw726H+C5+sIGDixDkmGL3IxPA2gKo+u4w== +git-raw-commits@^2.0.11: + version "2.0.11" + resolved "https://registry.yarnpkg.com/git-raw-commits/-/git-raw-commits-2.0.11.tgz#bc3576638071d18655e1cc60d7f524920008d723" + integrity sha512-VnctFhw+xfj8Va1xtfEqCUD2XDrbAPSJx+hSrE5K7fGdjZruW7XV+QOrN7LF/RJyvspRiD2I0asWsxFp0ya26A== + dependencies: + dargs "^7.0.0" + lodash "^4.17.15" + meow "^8.0.0" + split2 "^3.0.0" + through2 "^4.0.0" glob-parent@^5.1.2: version "5.1.2" @@ -3618,23 +4056,36 @@ glob-parent@^5.1.2: dependencies: is-glob "^4.0.1" -glob-to-regexp@^0.4.1: - version "0.4.1" - resolved "https://registry.yarnpkg.com/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz#c75297087c851b9a578bd217dd59a92f59fe546e" - integrity sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw== +glob-parent@^6.0.2: + version "6.0.2" + resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-6.0.2.tgz#6d237d99083950c79290f24c7642a3de9a28f9e3" + integrity sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A== + dependencies: + is-glob "^4.0.3" -glob@^7.0.3, glob@^7.1.3, glob@^7.1.4: - version "7.2.0" - resolved "https://registry.yarnpkg.com/glob/-/glob-7.2.0.tgz#d15535af7732e02e948f4c41628bd910293f6023" - integrity sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q== +glob@7.2.3, glob@^7.1.3, glob@^7.1.4: + version "7.2.3" + resolved "https://registry.yarnpkg.com/glob/-/glob-7.2.3.tgz#b8df0fb802bbfa8e89bd1d938b4e16578ed44f2b" + integrity sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q== dependencies: fs.realpath "^1.0.0" inflight "^1.0.4" inherits "2" - minimatch "^3.0.4" + minimatch "^3.1.1" once "^1.3.0" path-is-absolute "^1.0.0" +glob@^10.2.2, glob@^10.3.10: + version "10.3.10" + resolved "https://registry.yarnpkg.com/glob/-/glob-10.3.10.tgz#0351ebb809fd187fe421ab96af83d3a70715df4b" + integrity sha512-fa46+tv1Ak0UPK1TOy/pZrIybNNt4HCv7SDzwyfiOZkvZLEbjsZkJBPtDHVshZjbecAoAGSC20MjLDG/qr679g== + dependencies: + foreground-child "^3.1.0" + jackspeak "^2.3.5" + minimatch "^9.0.1" + minipass "^5.0.0 || ^6.0.2 || ^7.0.0" + path-scurry "^1.10.1" + glob@^8.0.1: version "8.1.0" resolved "https://registry.yarnpkg.com/glob/-/glob-8.1.0.tgz#d388f656593ef708ee3e34640fdfb99a9fd1c33e" @@ -3646,19 +4097,56 @@ glob@^8.0.1: minimatch "^5.0.1" once "^1.3.0" +glob@^9.3.0, glob@^9.3.1: + version "9.3.4" + resolved "https://registry.yarnpkg.com/glob/-/glob-9.3.4.tgz#e75dee24891a80c25cc7ee1dd327e126b98679af" + integrity sha512-qaSc49hojMOv1EPM4EuyITjDSgSKI0rthoHnvE81tcOi1SCVndHko7auqxdQ14eiQG2NDBJBE86+2xIrbIvrbA== + dependencies: + fs.realpath "^1.0.0" + minimatch "^8.0.2" + minipass "^4.2.4" + path-scurry "^1.6.1" + +global-dirs@^0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/global-dirs/-/global-dirs-0.1.1.tgz#b319c0dd4607f353f3be9cca4c72fc148c49f445" + integrity sha512-NknMLn7F2J7aflwFOlGdNIuCDpN3VGoSoB+aap3KABFWbHVn1TCgFC+np23J8W2BiZbjfEw3BFBycSMv1AFblg== + dependencies: + ini "^1.3.4" + +global-modules@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/global-modules/-/global-modules-1.0.0.tgz#6d770f0eb523ac78164d72b5e71a8877265cc3ea" + integrity sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg== + dependencies: + global-prefix "^1.0.1" + is-windows "^1.0.1" + resolve-dir "^1.0.0" + +global-prefix@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/global-prefix/-/global-prefix-1.0.2.tgz#dbf743c6c14992593c655568cb66ed32c0122ebe" + integrity sha512-5lsx1NUDHtSjfg0eHlmYvZKv8/nVqX4ckFbM+FrGcQ+04KWcWFo9P5MxPZYSzUvyzmdTbI7Eix8Q4IbELDqzKg== + dependencies: + expand-tilde "^2.0.2" + homedir-polyfill "^1.0.1" + ini "^1.3.4" + is-windows "^1.0.1" + which "^1.2.14" + globals@^11.1.0: version "11.12.0" resolved "https://registry.yarnpkg.com/globals/-/globals-11.12.0.tgz#ab8795338868a0babd8525758018c2a7eb95c42e" integrity sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA== -globals@^13.6.0, globals@^13.9.0: - version "13.13.0" - resolved "https://registry.yarnpkg.com/globals/-/globals-13.13.0.tgz#ac32261060d8070e2719dd6998406e27d2b5727b" - integrity sha512-EQ7Q18AJlPwp3vUDL4mKA0KXrXyNIQyWon6T6XQiBQF0XHvRsiCSrWmmeATpUzdJN2HhWZU6Pdl0a9zdep5p6A== +globals@^13.19.0: + version "13.20.0" + resolved "https://registry.yarnpkg.com/globals/-/globals-13.20.0.tgz#ea276a1e508ffd4f1612888f9d1bad1e2717bf82" + integrity sha512-Qg5QtVkCy/kv3FUSlu4ukeZDVf9ee0iXLAUYX13gbR17bnejFTzr4iS9bY7kwCf1NztRNm1t91fjOiyx4CSwPQ== dependencies: type-fest "^0.20.2" -globby@^11.0.0, globby@^11.0.1, globby@^11.1.0: +globby@^11.0.0, globby@^11.1.0: version "11.1.0" resolved "https://registry.yarnpkg.com/globby/-/globby-11.1.0.tgz#bd4be98bb042f83d796f7e3811991fbe82a0d34b" integrity sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g== @@ -3670,26 +4158,39 @@ globby@^11.0.0, globby@^11.0.1, globby@^11.1.0: merge2 "^1.4.1" slash "^3.0.0" -globby@^6.1.0: - version "6.1.0" - resolved "https://registry.yarnpkg.com/globby/-/globby-6.1.0.tgz#f5a6d70e8395e21c858fb0489d64df02424d506c" - integrity sha1-9abXDoOV4hyFj7BInWTfAkJNUGw= +globby@^14.0.0: + version "14.0.0" + resolved "https://registry.yarnpkg.com/globby/-/globby-14.0.0.tgz#ea9c062a3614e33f516804e778590fcf055256b9" + integrity sha512-/1WM/LNHRAOH9lZta77uGbq0dAEQM+XjNesWwhlERDVenqothRbnzTrL3/LrIoEPPjeUHC3vrS6TwoyxeHs7MQ== dependencies: - array-union "^1.0.1" - glob "^7.0.3" - object-assign "^4.0.1" - pify "^2.0.0" - pinkie-promise "^2.0.0" + "@sindresorhus/merge-streams" "^1.0.0" + fast-glob "^3.3.2" + ignore "^5.2.4" + path-type "^5.0.0" + slash "^5.1.0" + unicorn-magic "^0.1.0" -graceful-fs@4.2.10, graceful-fs@^4.1.2, graceful-fs@^4.1.6, graceful-fs@^4.2.0, graceful-fs@^4.2.10, graceful-fs@^4.2.4, graceful-fs@^4.2.6, graceful-fs@^4.2.9: +graceful-fs@4.2.10, graceful-fs@^4.1.2, graceful-fs@^4.1.6, graceful-fs@^4.2.0, graceful-fs@^4.2.6, graceful-fs@^4.2.9: version "4.2.10" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.10.tgz#147d3a006da4ca3ce14728c7aefc287c367d7a6c" integrity sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA== -grapheme-splitter@^1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/grapheme-splitter/-/grapheme-splitter-1.0.4.tgz#9cf3a665c6247479896834af35cf1dbb4400767e" - integrity sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ== +graceful-fs@^4.2.11: + version "4.2.11" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.11.tgz#4183e4e8bf08bb6e05bbb2f7d2e0c8f712ca40e3" + integrity sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ== + +graphemer@^1.4.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/graphemer/-/graphemer-1.4.0.tgz#fb2f1d55e0e3a1849aeffc90c4fa0dd53a0e66c6" + integrity sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag== + +gzip-size@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/gzip-size/-/gzip-size-6.0.0.tgz#065367fd50c239c0671cbcbad5be3e2eeb10e462" + integrity sha512-ax7ZYomf6jqPTQ4+XCpUGyXKHk5WweS+e05MBO4/y3WJ5RkmPXNKvX+bx1behVILVwr6JSQvZAku021CHPXG3Q== + dependencies: + duplexer "^0.1.2" handlebars@^4.7.7: version "4.7.7" @@ -3708,40 +4209,16 @@ hard-rejection@^2.1.0: resolved "https://registry.yarnpkg.com/hard-rejection/-/hard-rejection-2.1.0.tgz#1c6eda5c1685c63942766d79bb40ae773cecd883" integrity sha512-VIZB+ibDhx7ObhAe7OVtoEbuP4h/MuOTHJ+J8h/eBXotJYl0fBgR72xDFCKgIh22OJZIOVNxBMWuhAr10r8HdA== -has-bigints@^1.0.1, has-bigints@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/has-bigints/-/has-bigints-1.0.2.tgz#0871bd3e3d51626f6ca0966668ba35d5602d6eaa" - integrity sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ== - has-flag@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" - integrity sha1-tdRU3CGZriJWmfNGfloH87lVuv0= + integrity sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw== has-flag@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b" integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ== -has-property-descriptors@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/has-property-descriptors/-/has-property-descriptors-1.0.0.tgz#610708600606d36961ed04c196193b6a607fa861" - integrity sha512-62DVLZGoiEBDHQyqG4w9xCuZ7eJEwNmJRWw2VY84Oedb7WFcA27fiEVe8oUQx9hAUJ4ekurquucTGwsyO1XGdQ== - dependencies: - get-intrinsic "^1.1.1" - -has-symbols@^1.0.1, has-symbols@^1.0.2, has-symbols@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.3.tgz#bb7b2c4349251dce87b125f7bdf874aa7c8b39f8" - integrity sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A== - -has-tostringtag@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/has-tostringtag/-/has-tostringtag-1.0.0.tgz#7e133818a7d394734f941e73c3d3f9291e658b25" - integrity sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ== - dependencies: - has-symbols "^1.0.2" - has-unicode@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/has-unicode/-/has-unicode-2.0.1.tgz#e0e6fe6a28cf51138855e086d1691e771de2a8b9" @@ -3754,111 +4231,50 @@ has@^1.0.3: dependencies: function-bind "^1.1.1" -hash-base@^3.0.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/hash-base/-/hash-base-3.1.0.tgz#55c381d9e06e1d2997a883b4a3fddfe7f0d3af33" - integrity sha512-1nmYp/rhMDiE7AYkDw+lLwlAzz0AntGIe51F3RfFfEqyQ3feY2eI/NcwC6umIQVOASPMsWJLJScWKSSvzL9IVA== - dependencies: - inherits "^2.0.4" - readable-stream "^3.6.0" - safe-buffer "^5.2.0" - -hash.js@^1.0.0, hash.js@^1.0.3: - version "1.1.7" - resolved "https://registry.yarnpkg.com/hash.js/-/hash.js-1.1.7.tgz#0babca538e8d4ee4a0f8988d68866537a003cf42" - integrity sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA== - dependencies: - inherits "^2.0.3" - minimalistic-assert "^1.0.1" - -hdkey@2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/hdkey/-/hdkey-2.1.0.tgz#755b30b73f54e93c31919c1b2f19205a8e57cb92" - integrity sha512-i9Wzi0Dy49bNS4tXXeGeu0vIcn86xXdPQUpEYg+SO1YiO8HtomjmmRMaRyqL0r59QfcD4PfVbSF3qmsWFwAemA== - dependencies: - bs58check "^2.1.2" - ripemd160 "^2.0.2" - safe-buffer "^5.1.1" - secp256k1 "^4.0.0" - -he@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/he/-/he-1.2.0.tgz#84ae65fa7eafb165fddb61566ae14baf05664f0f" - integrity sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw== - -hmac-drbg@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/hmac-drbg/-/hmac-drbg-1.0.1.tgz#d2745701025a6c775a6c545793ed502fc0c649a1" - integrity sha1-0nRXAQJabHdabFRXk+1QL8DGSaE= +homedir-polyfill@^1.0.1: + version "1.0.3" + resolved "https://registry.yarnpkg.com/homedir-polyfill/-/homedir-polyfill-1.0.3.tgz#743298cef4e5af3e194161fbadcc2151d3a058e8" + integrity sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA== dependencies: - hash.js "^1.0.3" - minimalistic-assert "^1.0.0" - minimalistic-crypto-utils "^1.0.1" + parse-passwd "^1.0.0" -hook-std@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/hook-std/-/hook-std-2.0.0.tgz#ff9aafdebb6a989a354f729bb6445cf4a3a7077c" - integrity sha512-zZ6T5WcuBMIUVh49iPQS9t977t7C0l7OtHrpeMb5uk48JdflRX0NSFvCekfYNmGQETnLq9W/isMyHl69kxGi8g== +hook-std@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/hook-std/-/hook-std-3.0.0.tgz#47038a01981e07ce9d83a6a3b2eb98cad0f7bd58" + integrity sha512-jHRQzjSDzMtFy34AGj1DN+vq54WVuhSvKgrHf0OMiFQTwDD4L/qqofVEWjLOBMTn5+lCD3fPg32W9yOfnEJTTw== hosted-git-info@^2.1.4: version "2.8.9" resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.9.tgz#dffc0bf9a21c02209090f2aa69429e1414daf3f9" integrity sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw== -hosted-git-info@^4.0.0, hosted-git-info@^4.0.1: +hosted-git-info@^4.0.1: version "4.1.0" resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-4.1.0.tgz#827b82867e9ff1c8d0c4d9d53880397d2c86d224" integrity sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA== dependencies: lru-cache "^6.0.0" -hosted-git-info@^5.0.0, hosted-git-info@^5.2.1: - version "5.2.1" - resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-5.2.1.tgz#0ba1c97178ef91f3ab30842ae63d6a272341156f" - integrity sha512-xIcQYMnhcx2Nr4JTjsFmwwnr9vldugPy9uVm0o87bjqqWMv9GaqsTeT+i99wTl0mk1uLxJtHxLb8kymqTENQsw== +hosted-git-info@^6.0.0, hosted-git-info@^6.1.1: + version "6.1.1" + resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-6.1.1.tgz#629442c7889a69c05de604d52996b74fe6f26d58" + integrity sha512-r0EI+HBMcXadMrugk0GCQ+6BQV39PiWAZVfq7oIckeGiN7sjRGyQxPdft3nQekFTCQbYxLBH+/axZMeH8UX6+w== dependencies: lru-cache "^7.5.1" +hosted-git-info@^7.0.0, hosted-git-info@^7.0.1: + version "7.0.1" + resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-7.0.1.tgz#9985fcb2700467fecf7f33a4d4874e30680b5322" + integrity sha512-+K84LB1DYwMHoHSgaOY/Jfhw3ucPmSET5v98Ke/HdNSw4a0UktWzyW1mjhjpuxxTqOOsfWT/7iVshHmVZ4IpOA== + dependencies: + lru-cache "^10.0.1" + html-escaper@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/html-escaper/-/html-escaper-2.0.2.tgz#dfd60027da36a36dfcbe236262c00a5822681453" integrity sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg== -html-minifier-terser@^6.0.2: - version "6.1.0" - resolved "https://registry.yarnpkg.com/html-minifier-terser/-/html-minifier-terser-6.1.0.tgz#bfc818934cc07918f6b3669f5774ecdfd48f32ab" - integrity sha512-YXxSlJBZTP7RS3tWnQw74ooKa6L9b9i9QYXY21eUEvhZ3u9XLfv6OnFsQq6RxkhHygsaUMvYsZRV5rU/OVNZxw== - dependencies: - camel-case "^4.1.2" - clean-css "^5.2.2" - commander "^8.3.0" - he "^1.2.0" - param-case "^3.0.4" - relateurl "^0.2.7" - terser "^5.10.0" - -html-webpack-plugin@5.5.0: - version "5.5.0" - resolved "https://registry.yarnpkg.com/html-webpack-plugin/-/html-webpack-plugin-5.5.0.tgz#c3911936f57681c1f9f4d8b68c158cd9dfe52f50" - integrity sha512-sy88PC2cRTVxvETRgUHFrL4No3UxvcH8G1NepGhqaTT+GXN2kTamqasot0inS5hXeg1cMbFDt27zzo9p35lZVw== - dependencies: - "@types/html-minifier-terser" "^6.0.0" - html-minifier-terser "^6.0.2" - lodash "^4.17.21" - pretty-error "^4.0.0" - tapable "^2.0.0" - -htmlparser2@^6.1.0: - version "6.1.0" - resolved "https://registry.yarnpkg.com/htmlparser2/-/htmlparser2-6.1.0.tgz#c4d762b6c3371a05dbe65e94ae43a9f845fb8fb7" - integrity sha512-gyyPk6rgonLFEDGoeRgQNaEUvdJ4ktTmmUh/h2t7s+M8oPpIPxgNACWa+6ESR57kXstwqPiCut0V8NRpcwgU7A== - dependencies: - domelementtype "^2.0.1" - domhandler "^4.0.0" - domutils "^2.5.2" - entities "^2.0.0" - -http-cache-semantics@^4.1.0: +http-cache-semantics@4.1.1, http-cache-semantics@^4.1.0, http-cache-semantics@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz#abe02fcb2985460bf0323be664436ec3476a6d5a" integrity sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ== @@ -3872,6 +4288,14 @@ http-proxy-agent@^5.0.0: agent-base "6" debug "4" +http-proxy-agent@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/http-proxy-agent/-/http-proxy-agent-7.0.0.tgz#e9096c5afd071a3fce56e6252bb321583c124673" + integrity sha512-+ZT+iBxVUQ1asugqnD6oWoRiS25AkjNfG085dKJGtGxkdwLQrMKU5wJr2bOOFAXzKcTuqq+7fZlTMgG3SRfIYQ== + dependencies: + agent-base "^7.1.0" + debug "^4.3.4" + https-proxy-agent@^5.0.0: version "5.0.1" resolved "https://registry.yarnpkg.com/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz#c59ef224a04fe8b754f3db0063a25ea30d0005d6" @@ -3880,15 +4304,28 @@ https-proxy-agent@^5.0.0: agent-base "6" debug "4" +https-proxy-agent@^7.0.0, https-proxy-agent@^7.0.1: + version "7.0.2" + resolved "https://registry.yarnpkg.com/https-proxy-agent/-/https-proxy-agent-7.0.2.tgz#e2645b846b90e96c6e6f347fb5b2e41f1590b09b" + integrity sha512-NmLNjm6ucYwtcUmL7JQC1ZQ57LmHP4lT15FQ8D61nak1rO6DH+fz5qNK2Ap5UN4ZapYICE3/0KodcLYSPsPbaA== + dependencies: + agent-base "^7.0.2" + debug "4" + human-signals@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-2.1.0.tgz#dc91fcba42e4d06e4abaed33b3e7a3c02f514ea0" integrity sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw== -human-signals@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-3.0.1.tgz#c740920859dafa50e5a3222da9d3bf4bb0e5eef5" - integrity sha512-rQLskxnM/5OCldHo+wNXbpVgDn5A17CUoKX+7Sokwaknlq7CdSnphy0W39GU8dw59XiCXmFXDg4fRuckQRKewQ== +human-signals@^4.3.0: + version "4.3.0" + resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-4.3.0.tgz#2095c3cd5afae40049403d4b811235b03879db50" + integrity sha512-zyzVyMjpGBX2+6cDVZeFPCdtOtdsxOeseRhB9tkQ6xXmGUNrcnBzdEKPy3VPNYz+4gy1oukVOXcrJCunSyc6QQ== + +human-signals@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-5.0.0.tgz#42665a284f9ae0dade3ba41ebc37eb4b852f3a28" + integrity sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ== humanize-ms@^1.2.1: version "1.2.1" @@ -3902,6 +4339,13 @@ husky@8.0.3: resolved "https://registry.yarnpkg.com/husky/-/husky-8.0.3.tgz#4936d7212e46d1dea28fef29bb3a108872cd9184" integrity sha512-+dQSyqPh4x1hlO1swXBiNb2HzTDN1I2IGLQx1GrBuiqFJfoMrnZWwVmatvSiO+Iz8fBUnf+lekwNo4c2LlXItg== +iconv-lite@^0.4.24: + version "0.4.24" + resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.24.tgz#2022b4b25fbddc21d2f524974a474aafe733908b" + integrity sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA== + dependencies: + safer-buffer ">= 2.1.2 < 3" + iconv-lite@^0.6.2: version "0.6.3" resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.6.3.tgz#a52f80bf38da1952eb5c681790719871a1a72501" @@ -3909,27 +4353,34 @@ iconv-lite@^0.6.2: dependencies: safer-buffer ">= 2.1.2 < 3.0.0" -ieee754@^1.2.1: +ieee754@^1.1.13, ieee754@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352" integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA== -ignore-walk@^5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/ignore-walk/-/ignore-walk-5.0.1.tgz#5f199e23e1288f518d90358d461387788a154776" - integrity sha512-yemi4pMf51WKT7khInJqAvsIGzoqYXblnsz0ql8tM+yi1EKYTY1evX4NAbJrLL/Aanr2HyZeluqU+Oi7MGHokw== +ignore-walk@^6.0.0: + version "6.0.1" + resolved "https://registry.yarnpkg.com/ignore-walk/-/ignore-walk-6.0.1.tgz#f05e232992ebf25fef13613668fea99857e7e8cf" + integrity sha512-/c8MxUAqpRccq+LyDOecwF+9KqajueJHh8fz7g3YqjMZt+NSfJzx05zrKiXwa2sKwFCzaiZ5qUVfRj0pmxixEA== dependencies: - minimatch "^5.0.1" + minimatch "^6.1.6" -ignore@^4.0.6: - version "4.0.6" - resolved "https://registry.yarnpkg.com/ignore/-/ignore-4.0.6.tgz#750e3db5862087b4737ebac8207ffd1ef27b25fc" - integrity sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg== +ignore-walk@^6.0.4: + version "6.0.4" + resolved "https://registry.yarnpkg.com/ignore-walk/-/ignore-walk-6.0.4.tgz#89950be94b4f522225eb63a13c56badb639190e9" + integrity sha512-t7sv42WkwFkyKbivUCglsQW5YWMskWtbEf4MNKX5u/CCWHKSPzN4FtBQGsQZgCLbxOzpVlcbWVK5KB3auIOjSw== + dependencies: + minimatch "^9.0.0" ignore@^5.2.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.2.0.tgz#6d3bac8fa7fe0d45d9f9be7bac2fc279577e345a" - integrity sha512-CmxgYGiEPCLhfLnpPp1MoRmifwEIOgjcHXxOBjv7mY96c+eWScsOP9c112ZyLdWHi0FxHjI+4uVhKYp/gcdRmQ== + version "5.2.4" + resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.2.4.tgz#a291c0c6178ff1b960befe47fcdec301674a6324" + integrity sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ== + +ignore@^5.2.4: + version "5.3.0" + resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.3.0.tgz#67418ae40d34d6999c95ff56016759c718c82f78" + integrity sha512-g7dmpshy+gD7mh88OC9NwSGTKoc3kyLAZQRU1mt53Aw/vnvfXnbC+F/7F7QoYVKbV+KNvJx8wArewKy1vXMtlg== import-fresh@^3.0.0, import-fresh@^3.2.1: version "3.3.0" @@ -3939,6 +4390,14 @@ import-fresh@^3.0.0, import-fresh@^3.2.1: parent-module "^1.0.0" resolve-from "^4.0.0" +import-from-esm@^1.0.3: + version "1.3.3" + resolved "https://registry.yarnpkg.com/import-from-esm/-/import-from-esm-1.3.3.tgz#eea1c4ad86a54bf425b3b71fca56d50215ccc6b7" + integrity sha512-U3Qt/CyfFpTUv6LOP2jRTLYjphH6zg3okMfHbyqRa/W2w6hr8OsJWVggNlR4jxuojQy81TgTJTxgSkyoteRGMQ== + dependencies: + debug "^4.3.4" + import-meta-resolve "^4.0.0" + import-from@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/import-from/-/import-from-4.0.0.tgz#2710b8d66817d232e16f4166e319248d3d5492e2" @@ -3952,16 +4411,31 @@ import-local@^3.0.2: pkg-dir "^4.2.0" resolve-cwd "^3.0.0" +import-meta-resolve@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/import-meta-resolve/-/import-meta-resolve-4.0.0.tgz#0b1195915689f60ab00f830af0f15cc841e8919e" + integrity sha512-okYUR7ZQPH+efeuMJGlq4f8ubUgO50kByRPyt/Cy1Io4PSRsPjxME+YlVaCOx+NIToW7hCsZNFJyTPFFKepRSA== + imurmurhash@^0.1.4: version "0.1.4" resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea" - integrity sha1-khi5srkoojixPcT7a21XbyMUU+o= + integrity sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA== indent-string@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/indent-string/-/indent-string-4.0.0.tgz#624f8f4497d619b2d9768531d58f4122854d7251" integrity sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg== +indent-string@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/indent-string/-/indent-string-5.0.0.tgz#4fd2980fccaf8622d14c64d694f4cf33c81951a5" + integrity sha512-m6FAo/spmsW2Ab2fU35JTYwtOKa2yAwXSwgjSv1TJzh4Mh7mC3lzAOVLBprb72XsTrgkEIsl7YrFNAiDiRhIGg== + +index-to-position@^0.1.2: + version "0.1.2" + resolved "https://registry.yarnpkg.com/index-to-position/-/index-to-position-0.1.2.tgz#e11bfe995ca4d8eddb1ec43274488f3c201a7f09" + integrity sha512-MWDKS3AS1bGCHLBA2VLImJz42f7bJh8wQsTGCzI3j519/CASStoDONUBVz2I/VID0MpiX3SGSnbOD2xUalbE5g== + infer-owner@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/infer-owner/-/infer-owner-1.0.4.tgz#c4cefcaa8e51051c2a40ba2ce8a3d27295af9467" @@ -3970,12 +4444,12 @@ infer-owner@^1.0.4: inflight@^1.0.4: version "1.0.6" resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" - integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk= + integrity sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA== dependencies: once "^1.3.0" wrappy "1" -inherits@2, inherits@^2.0.1, inherits@^2.0.3, inherits@^2.0.4, inherits@~2.0.3, inherits@~2.0.4: +inherits@2, inherits@^2.0.1, inherits@^2.0.3, inherits@^2.0.4, inherits@~2.0.3: version "2.0.4" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== @@ -3990,32 +4464,57 @@ ini@^3.0.0, ini@^3.0.1: resolved "https://registry.yarnpkg.com/ini/-/ini-3.0.1.tgz#c76ec81007875bc44d544ff7a11a55d12294102d" integrity sha512-it4HyVAUTKBc6m8e1iXWvXSTdndF7HbdN713+kvLrymxTaU4AUBWrJ4vEooP+V7fexnVD3LKcBshjGGPefSMUQ== -init-package-json@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/init-package-json/-/init-package-json-3.0.2.tgz#f5bc9bac93f2bdc005778bc2271be642fecfcd69" - integrity sha512-YhlQPEjNFqlGdzrBfDNRLhvoSgX7iQRgSxgsNknRQ9ITXFT7UMfVMWhBTOh2Y+25lRnGrv5Xz8yZwQ3ACR6T3A== +ini@^4.1.0, ini@^4.1.1: + version "4.1.1" + resolved "https://registry.yarnpkg.com/ini/-/ini-4.1.1.tgz#d95b3d843b1e906e56d6747d5447904ff50ce7a1" + integrity sha512-QQnnxNyfvmHFIsj7gkPcYymR8Jdw/o7mp5ZFihxn6h8Ci6fh3Dx4E1gPjpQEpIuPo9XVNY/ZUwh4BPMjGyL01g== + +init-package-json@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/init-package-json/-/init-package-json-5.0.0.tgz#030cf0ea9c84cfc1b0dc2e898b45d171393e4b40" + integrity sha512-kBhlSheBfYmq3e0L1ii+VKe3zBTLL5lDCDWR+f9dLmEGSB3MqLlMlsolubSsyI88Bg6EA+BIMlomAnQ1SwgQBw== dependencies: - npm-package-arg "^9.0.1" - promzard "^0.3.0" - read "^1.0.7" - read-package-json "^5.0.0" + npm-package-arg "^10.0.0" + promzard "^1.0.0" + read "^2.0.0" + read-package-json "^6.0.0" semver "^7.3.5" validate-npm-package-license "^3.0.4" - validate-npm-package-name "^4.0.0" + validate-npm-package-name "^5.0.0" -internal-slot@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/internal-slot/-/internal-slot-1.0.3.tgz#7347e307deeea2faac2ac6205d4bc7d34967f59c" - integrity sha512-O0DB1JC/sPyZl7cIo78n5dR7eUSwwpYPiXRhTzNxZVAMUuB8vlnRFyLxdrVToks6XPLVnFfbzaVd5WLjhgg+vA== +init-package-json@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/init-package-json/-/init-package-json-6.0.0.tgz#7d4daeaacc72be300c616481e5c155d5048a18b4" + integrity sha512-AmXD+Aht5iZGo/y1KUtZSUQ1SltesXHxQuc7qeNz0eUGx/8WgkHeeQLSFdM8l9YpmnnamGIbAxVdAs2xoLRKRQ== dependencies: - get-intrinsic "^1.1.0" - has "^1.0.3" - side-channel "^1.0.4" + npm-package-arg "^11.0.0" + promzard "^1.0.0" + read "^2.0.0" + read-package-json "^7.0.0" + semver "^7.3.5" + validate-npm-package-license "^3.0.4" + validate-npm-package-name "^5.0.0" -interpret@^2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/interpret/-/interpret-2.2.0.tgz#1a78a0b5965c40a5416d007ad6f50ad27c417df9" - integrity sha512-Ju0Bz/cEia55xDwUWEa8+olFpCiQoypjnQySseKtmjNrnps3P+xfpUmGr90T7yjlVJmOtybRvPXhKMbHr+fWnw== +inquirer@8.2.5: + version "8.2.5" + resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-8.2.5.tgz#d8654a7542c35a9b9e069d27e2df4858784d54f8" + integrity sha512-QAgPDQMEgrDssk1XiwwHoOGYF9BAbUcc1+j+FhEvaOt8/cKRqyLn0U5qA6F74fGhTMGxf92pOvPBeh29jQJDTQ== + dependencies: + ansi-escapes "^4.2.1" + chalk "^4.1.1" + cli-cursor "^3.1.0" + cli-width "^3.0.0" + external-editor "^3.0.3" + figures "^3.0.0" + lodash "^4.17.21" + mute-stream "0.0.8" + ora "^5.4.1" + run-async "^2.4.0" + rxjs "^7.5.5" + string-width "^4.1.0" + strip-ansi "^6.0.0" + through "^2.3.6" + wrap-ansi "^7.0.0" into-stream@^6.0.0: version "6.0.0" @@ -4025,48 +4524,40 @@ into-stream@^6.0.0: from2 "^2.3.0" p-is-promise "^3.0.0" +ip-address@^9.0.5: + version "9.0.5" + resolved "https://registry.yarnpkg.com/ip-address/-/ip-address-9.0.5.tgz#117a960819b08780c3bd1f14ef3c1cc1d3f3ea5a" + integrity sha512-zHtQzGojZXTwZTHQqra+ETKd4Sn3vgi7uBmlPoXVWZqYvuKmtI0l/VZTjqGmJY9x88GGOaZ9+G9ES8hC4T4X8g== + dependencies: + jsbn "1.1.0" + sprintf-js "^1.1.3" + ip-regex@^4.1.0: version "4.3.0" resolved "https://registry.yarnpkg.com/ip-regex/-/ip-regex-4.3.0.tgz#687275ab0f57fa76978ff8f4dddc8a23d5990db5" integrity sha512-B9ZWJxHHOHUhUjCPrMpLD4xEq35bUTClHM1S6CBU5ixQnkZmwipwgc96vAd7AAGM9TGHvJR+Uss+/Ak6UphK+Q== +ip-regex@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/ip-regex/-/ip-regex-5.0.0.tgz#cd313b2ae9c80c07bd3851e12bf4fa4dc5480632" + integrity sha512-fOCG6lhoKKakwv+C6KdsOnGvgXnmgfmp0myi3bcNwj3qfwPAxRKWEuFhvEFF7ceYIz6+1jRZ+yguLFAmUNPEfw== + ip@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/ip/-/ip-2.0.0.tgz#4cf4ab182fee2314c75ede1276f8c80b479936da" integrity sha512-WKa+XuLG1A1R0UWhl2+1XQSi+fZWMsYKffMZTTYsiZaUD8k2yDAj5atimTUD2TZkyCkNEeYE5NhFZmupOGtjYQ== -is-arguments@^1.0.4: - version "1.1.1" - resolved "https://registry.yarnpkg.com/is-arguments/-/is-arguments-1.1.1.tgz#15b3f88fda01f2a97fec84ca761a560f123efa9b" - integrity sha512-8Q7EARjzEnKpt/PCD7e1cgUS0a6X8u5tdSiMqXhojOdoV9TsMsiO+9VLC5vAmO8N7/GmXn7yjR8qnA6bVAEzfA== - dependencies: - call-bind "^1.0.2" - has-tostringtag "^1.0.0" - is-arrayish@^0.2.1: version "0.2.1" resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d" - integrity sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0= - -is-bigint@^1.0.1: - version "1.0.4" - resolved "https://registry.yarnpkg.com/is-bigint/-/is-bigint-1.0.4.tgz#08147a1875bc2b32005d41ccd8291dffc6691df3" - integrity sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg== - dependencies: - has-bigints "^1.0.1" + integrity sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg== -is-boolean-object@^1.1.0: - version "1.1.2" - resolved "https://registry.yarnpkg.com/is-boolean-object/-/is-boolean-object-1.1.2.tgz#5c6dc200246dd9321ae4b885a114bb1f75f63719" - integrity sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA== +is-builtin-module@^3.2.1: + version "3.2.1" + resolved "https://registry.yarnpkg.com/is-builtin-module/-/is-builtin-module-3.2.1.tgz#f03271717d8654cfcaf07ab0463faa3571581169" + integrity sha512-BSLE3HnV2syZ0FK0iMA/yUGplUeMmNz4AW5fnTunbCIqZi4vG3WjJT9FHMy5D69xmAYBHXQhJdALdpwVxV501A== dependencies: - call-bind "^1.0.2" - has-tostringtag "^1.0.0" - -is-callable@^1.1.4, is-callable@^1.2.4: - version "1.2.4" - resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.2.4.tgz#47301d58dd0259407865547853df6d61fe471945" - integrity sha512-nsuwtxZfMX67Oryl9LCQ+upnC0Z0BgpwntpS89m1H/TLF0zNfzfLMV/9Wa/6MZsj0acpEjAO0KF1xT6ZdLl95w== + builtin-modules "^3.3.0" is-cidr@^4.0.2: version "4.0.2" @@ -4075,31 +4566,24 @@ is-cidr@^4.0.2: dependencies: cidr-regex "^3.1.1" -is-core-module@^2.5.0, is-core-module@^2.9.0: +is-cidr@^5.0.3: + version "5.0.3" + resolved "https://registry.yarnpkg.com/is-cidr/-/is-cidr-5.0.3.tgz#fcf817c0146dd4a318f27938af89e98a9b21bdd5" + integrity sha512-lKkM0tmz07dAxNsr8Ii9MGreExa9ZR34N9j8mTG5op824kcwBqinZPowNjcVWWc7j+jR8XAMMItOmBkniN0jOA== + dependencies: + cidr-regex "4.0.3" + +is-core-module@^2.5.0, is-core-module@^2.8.1, is-core-module@^2.9.0: version "2.11.0" resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.11.0.tgz#ad4cb3e3863e814523c96f3f58d26cc570ff0144" integrity sha512-RRjxlvLDkD1YJwDbroBHMb+cukurkDWNyHx7D3oNB5x9rb5ogcksMC5wHCadcXoo67gVr/+3GFySh3134zi6rw== dependencies: has "^1.0.3" -is-core-module@^2.8.1: - version "2.9.0" - resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.9.0.tgz#e1c34429cd51c6dd9e09e0799e396e27b19a9c69" - integrity sha512-+5FPy5PnwmO3lvfMb0AsoPaBG+5KHUI0wYFXOtYPnVVVspTFUuMZNfNaNVRt3FZadstu2c8x23vykRW/NBoU6A== - dependencies: - has "^1.0.3" - -is-date-object@^1.0.1: - version "1.0.5" - resolved "https://registry.yarnpkg.com/is-date-object/-/is-date-object-1.0.5.tgz#0841d5536e724c25597bf6ea62e1bd38298df31f" - integrity sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ== - dependencies: - has-tostringtag "^1.0.0" - is-extglob@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" - integrity sha1-qIwCU1eR8C7TfHahueqXc8gz+MI= + integrity sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ== is-fullwidth-code-point@^3.0.0: version "3.0.0" @@ -4111,18 +4595,18 @@ is-fullwidth-code-point@^4.0.0: resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz#fae3167c729e7463f8461ce512b080a49268aa88" integrity sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ== +is-fullwidth-code-point@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-5.0.0.tgz#9609efced7c2f97da7b60145ef481c787c7ba704" + integrity sha512-OVa3u9kkBbw7b8Xw5F9P+D/T9X+Z4+JruYVNapTjPYZYUznQ5YfWeFkOj606XYYW8yugTfC8Pj0hYqvi4ryAhA== + dependencies: + get-east-asian-width "^1.0.0" + is-generator-fn@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/is-generator-fn/-/is-generator-fn-2.1.0.tgz#7d140adc389aaf3011a8f2a2a4cfa6faadffb118" integrity sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ== -is-generator-function@^1.0.7: - version "1.0.10" - resolved "https://registry.yarnpkg.com/is-generator-function/-/is-generator-function-1.0.10.tgz#f1558baf1ac17e0deea7c0415c438351ff2b3c72" - integrity sha512-jsEjy9l3yiXEQ+PsXdmBwEPcOxaXWLspKdplFUVI9vq1iZgIekeC0L167qeu86czQaxed3q/Uzuw0swL0irL8A== - dependencies: - has-tostringtag "^1.0.0" - is-glob@^4.0.0, is-glob@^4.0.1, is-glob@^4.0.3: version "4.0.3" resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.3.tgz#64f61e42cbbb2eec2071a9dac0b28ba1e65d5084" @@ -4130,30 +4614,20 @@ is-glob@^4.0.0, is-glob@^4.0.1, is-glob@^4.0.3: dependencies: is-extglob "^2.1.1" +is-interactive@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-interactive/-/is-interactive-1.0.0.tgz#cea6e6ae5c870a7b0a0004070b7b587e0252912e" + integrity sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w== + is-lambda@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/is-lambda/-/is-lambda-1.0.1.tgz#3d9877899e6a53efc0160504cde15f82e6f061d5" integrity sha512-z7CMFGNrENq5iFB9Bqo64Xk6Y9sg+epq1myIcdHaGnbMTYOxvzsEtdYqQUylB7LxfkvgrrjP32T6Ywciio9UIQ== -is-nan@^1.2.1: - version "1.3.2" - resolved "https://registry.yarnpkg.com/is-nan/-/is-nan-1.3.2.tgz#043a54adea31748b55b6cd4e09aadafa69bd9e1d" - integrity sha512-E+zBKpQ2t6MEo1VsonYmluk9NxGrbzpeeLC2xIViuO2EjU2xsXsBPwTr3Ykv9l08UYEVEdWeRZNouaZqF6RN0w== - dependencies: - call-bind "^1.0.0" - define-properties "^1.1.3" - -is-negative-zero@^2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/is-negative-zero/-/is-negative-zero-2.0.2.tgz#7bf6f03a28003b8b3965de3ac26f664d765f3150" - integrity sha512-dqJvarLawXsFbNDeJW7zAz8ItJ9cd28YufuuFzh0G8pNHjJMnY08Dv7sYX2uF5UpQOwieAeOExEYAWWfu7ZZUA== - -is-number-object@^1.0.4: - version "1.0.7" - resolved "https://registry.yarnpkg.com/is-number-object/-/is-number-object-1.0.7.tgz#59d50ada4c45251784e9904f5246c742f07a42fc" - integrity sha512-k1U0IRzLMo7ZlYIfzRu23Oh6MiIFasgpb9X76eqfFZAqwH44UI4KTBvBYIZ1dSL9ZzChTB9ShHfLkR4pdW5krQ== - dependencies: - has-tostringtag "^1.0.0" +is-module@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-module/-/is-module-1.0.0.tgz#3258fb69f78c14d5b815d664336b4cffb6441591" + integrity sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g== is-number@^7.0.0: version "7.0.0" @@ -4165,26 +4639,7 @@ is-obj@^2.0.0: resolved "https://registry.yarnpkg.com/is-obj/-/is-obj-2.0.0.tgz#473fb05d973705e3fd9620545018ca8e22ef4982" integrity sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w== -is-path-cwd@^2.0.0, is-path-cwd@^2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/is-path-cwd/-/is-path-cwd-2.2.0.tgz#67d43b82664a7b5191fd9119127eb300048a9fdb" - integrity sha512-w942bTcih8fdJPJmQHFzkS76NEP8Kzzvmw92cXsazb8intwLqPibPPdXf4ANdKV3rYMuuQYGIWtvz9JilB3NFQ== - -is-path-in-cwd@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/is-path-in-cwd/-/is-path-in-cwd-2.1.0.tgz#bfe2dca26c69f397265a4009963602935a053acb" - integrity sha512-rNocXHgipO+rvnP6dk3zI20RpOtrAM/kzbB258Uw5BWr3TpXi861yzjo16Dn4hUox07iw5AyeMLHWsujkjzvRQ== - dependencies: - is-path-inside "^2.1.0" - -is-path-inside@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/is-path-inside/-/is-path-inside-2.1.0.tgz#7c9810587d659a40d27bcdb4d5616eab059494b2" - integrity sha512-wiyhTzfDWsvwAW53OBWF5zuvaOGlZ6PwYxAbPVDhpm+gM09xKQGjBq/8uYN12aDvMxnAnq3dxTyoSoRNmg5YFg== - dependencies: - path-is-inside "^1.0.2" - -is-path-inside@^3.0.2: +is-path-inside@^3.0.3: version "3.0.3" resolved "https://registry.yarnpkg.com/is-path-inside/-/is-path-inside-3.0.3.tgz#d231362e53a07ff2b0e0ea7fed049161ffd16283" integrity sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ== @@ -4194,33 +4649,11 @@ is-plain-obj@^1.1.0: resolved "https://registry.yarnpkg.com/is-plain-obj/-/is-plain-obj-1.1.0.tgz#71a50c8429dfca773c92a390a4a03b39fcd51d3e" integrity sha512-yvkRyxmFKEOQ4pNXCmJG5AEQNlXJS5LaONXo5/cLdTZdWvsZ1ioJEonLGAosKlMWE8lwUy/bJzMjcw8az73+Fg== -is-plain-object@^2.0.4: - version "2.0.4" - resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677" - integrity sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og== - dependencies: - isobject "^3.0.1" - is-plain-object@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-5.0.0.tgz#4427f50ab3429e9025ea7d52e9043a9ef4159344" integrity sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q== -is-regex@^1.1.4: - version "1.1.4" - resolved "https://registry.yarnpkg.com/is-regex/-/is-regex-1.1.4.tgz#eef5663cd59fa4c0ae339505323df6854bb15958" - integrity sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg== - dependencies: - call-bind "^1.0.2" - has-tostringtag "^1.0.0" - -is-shared-array-buffer@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/is-shared-array-buffer/-/is-shared-array-buffer-1.0.2.tgz#8f259c573b60b6a32d4058a1a07430c0a7344c79" - integrity sha512-sqN2UDu1/0y6uvXyStCOzyhAjCSlHceFoMKJW8W9EU9cvic/QdsZ0kEU93HEy3IUEFZIiH/3w+AH/UQbPHNdhA== - dependencies: - call-bind "^1.0.2" - is-stream@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-2.0.1.tgz#fac1e3d53b97ad5a9d0ae9cef2389f5810a5c077" @@ -4231,20 +4664,6 @@ is-stream@^3.0.0: resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-3.0.0.tgz#e6bfd7aa6bef69f4f472ce9bb681e3e57b4319ac" integrity sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA== -is-string@^1.0.5, is-string@^1.0.7: - version "1.0.7" - resolved "https://registry.yarnpkg.com/is-string/-/is-string-1.0.7.tgz#0dd12bf2006f255bb58f695110eff7491eebc0fd" - integrity sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg== - dependencies: - has-tostringtag "^1.0.0" - -is-symbol@^1.0.2, is-symbol@^1.0.3: - version "1.0.4" - resolved "https://registry.yarnpkg.com/is-symbol/-/is-symbol-1.0.4.tgz#a6dac93b635b063ca6872236de88910a57af139c" - integrity sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg== - dependencies: - has-symbols "^1.0.2" - is-text-path@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/is-text-path/-/is-text-path-1.0.1.tgz#4e1aa0fb51bfbcb3e92688001397202c1775b66e" @@ -4252,23 +4671,32 @@ is-text-path@^1.0.1: dependencies: text-extensions "^1.0.0" -is-typed-array@^1.1.3, is-typed-array@^1.1.7: - version "1.1.8" - resolved "https://registry.yarnpkg.com/is-typed-array/-/is-typed-array-1.1.8.tgz#cbaa6585dc7db43318bc5b89523ea384a6f65e79" - integrity sha512-HqH41TNZq2fgtGT8WHVFVJhBVGuY3AnP3Q36K8JKXUxSxRgk/d+7NjmwG2vo2mYmXK8UYZKu0qH8bVP5gEisjA== +is-text-path@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/is-text-path/-/is-text-path-2.0.0.tgz#b2484e2b720a633feb2e85b67dc193ff72c75636" + integrity sha512-+oDTluR6WEjdXEJMnC2z6A4FRwFoYuvShVVEGsS7ewc0UTi2QtAKMDJuL4BDEVt+5T7MjFo12RP8ghOM75oKJw== dependencies: - available-typed-arrays "^1.0.5" - call-bind "^1.0.2" - es-abstract "^1.18.5" - foreach "^2.0.5" - has-tostringtag "^1.0.0" + text-extensions "^2.0.0" + +is-unicode-supported@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz#3f26c76a809593b52bfa2ecb5710ed2779b522a7" + integrity sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw== + +is-unicode-supported@^1.2.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/is-unicode-supported/-/is-unicode-supported-1.3.0.tgz#d824984b616c292a2e198207d4a609983842f714" + integrity sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ== -is-weakref@^1.0.2: +is-utf8@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/is-utf8/-/is-utf8-0.2.1.tgz#4b0da1442104d1b336340e80797e865cf39f7d72" + integrity sha512-rMYPYvCzsXywIsldgLaSoPlw5PfoB/ssr7hY4pLfcodrA5M/eArza1a9VmTiNIBNMjOGr1Ow9mTyU2o69U6U9Q== + +is-windows@^1.0.1: version "1.0.2" - resolved "https://registry.yarnpkg.com/is-weakref/-/is-weakref-1.0.2.tgz#9529f383a9338205e89765e0392efc2f100f06f2" - integrity sha512-qctsuLZmIQ0+vSSMfoVvyFe2+GSEvnmZ2ezTup1SBse9+twCCeial6EEi3Nc2KFcf6+qz2FBPnjXsk8xhKSaPQ== - dependencies: - call-bind "^1.0.2" + resolved "https://registry.yarnpkg.com/is-windows/-/is-windows-1.0.2.tgz#d1850eb9791ecd18e6182ce12a30f396634bb19d" + integrity sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA== isarray@~1.0.0: version "1.0.0" @@ -4278,17 +4706,12 @@ isarray@~1.0.0: isexe@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" - integrity sha1-6PvzdNxVb/iUehDcsFctYz8s+hA= + integrity sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw== -isobject@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df" - integrity sha1-TkMekrEalzFjaqH5yNHMvP2reN8= - -isomorphic-ws@5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/isomorphic-ws/-/isomorphic-ws-5.0.0.tgz#e5529148912ecb9b451b46ed44d53dae1ce04bbf" - integrity sha512-muId7Zzn9ywDsyXgTIafTry2sV3nySZeUDe6YedVd1Hvuuep5AsIlqK+XefWpYTyJG5e503F2xIuT2lcU6rCSw== +isexe@^3.1.1: + version "3.1.1" + resolved "https://registry.yarnpkg.com/isexe/-/isexe-3.1.1.tgz#4a407e2bd78ddfb14bea0c27c6f7072dde775f0d" + integrity sha512-LpB/54B+/2J5hqQ7imZHfdU31OlgQqx7ZicVlkm9kzg9/w8GKLEcFfJl/t7DCEDueOyBAD6zCCwTO6Fzs0NoEQ== issue-parser@^6.0.0: version "6.0.0" @@ -4307,9 +4730,9 @@ istanbul-lib-coverage@^3.0.0, istanbul-lib-coverage@^3.2.0: integrity sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw== istanbul-lib-instrument@^5.0.4: - version "5.2.0" - resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.0.tgz#31d18bdd127f825dd02ea7bfdfd906f8ab840e9f" - integrity sha512-6Lthe1hqXHBNsqvgDzGO6l03XNeu3CrG4RqQ1KM9+l5+jNGpEJfIELx1NS3SEHmJQA8np/u+E4EPRKRiu6m19A== + version "5.2.1" + resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz#d10c8885c2125574e1c231cacadf955675e1ce3d" + integrity sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg== dependencies: "@babel/core" "^7.12.3" "@babel/parser" "^7.14.7" @@ -4317,16 +4740,16 @@ istanbul-lib-instrument@^5.0.4: istanbul-lib-coverage "^3.2.0" semver "^6.3.0" -istanbul-lib-instrument@^5.1.0: - version "5.2.1" - resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz#d10c8885c2125574e1c231cacadf955675e1ce3d" - integrity sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg== +istanbul-lib-instrument@^6.0.0: + version "6.0.1" + resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.1.tgz#71e87707e8041428732518c6fb5211761753fbdf" + integrity sha512-EAMEJBsYuyyztxMxW3g7ugGPkrZsV57v0Hmv3mm1uQsmB+QnZuepg731CRaIgeUVSdmsTngOkSnauNF8p7FIhA== dependencies: "@babel/core" "^7.12.3" "@babel/parser" "^7.14.7" "@istanbuljs/schema" "^0.1.2" istanbul-lib-coverage "^3.2.0" - semver "^6.3.0" + semver "^7.5.4" istanbul-lib-report@^3.0.0: version "3.0.0" @@ -4354,87 +4777,97 @@ istanbul-reports@^3.1.3: html-escaper "^2.0.0" istanbul-lib-report "^3.0.0" -java-properties@^1.0.0: +jackspeak@^2.3.5: + version "2.3.6" + resolved "https://registry.yarnpkg.com/jackspeak/-/jackspeak-2.3.6.tgz#647ecc472238aee4b06ac0e461acc21a8c505ca8" + integrity sha512-N3yCS/NegsOBokc8GAdM8UcmfsKiSS8cipheD/nivzr700H+nsMOxJjQnvwOcRYVuFkdH0wGUvW2WbXGmrZGbQ== + dependencies: + "@isaacs/cliui" "^8.0.2" + optionalDependencies: + "@pkgjs/parseargs" "^0.11.0" + +java-properties@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/java-properties/-/java-properties-1.0.2.tgz#ccd1fa73907438a5b5c38982269d0e771fe78211" integrity sha512-qjdpeo2yKlYTH7nFdK0vbZWuTCesk4o63v5iVOlhMQPfuIZQfW/HI35SjfhA+4qpg36rnFSvUK5b1m+ckIblQQ== -jest-changed-files@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest-changed-files/-/jest-changed-files-29.4.3.tgz#7961fe32536b9b6d5c28dfa0abcfab31abcf50a7" - integrity sha512-Vn5cLuWuwmi2GNNbokPOEcvrXGSGrqVnPEZV7rC6P7ck07Dyw9RFnvWglnupSh+hGys0ajGtw/bc2ZgweljQoQ== +jest-changed-files@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-changed-files/-/jest-changed-files-29.7.0.tgz#1c06d07e77c78e1585d020424dedc10d6e17ac3a" + integrity sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w== dependencies: execa "^5.0.0" + jest-util "^29.7.0" p-limit "^3.1.0" -jest-circus@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest-circus/-/jest-circus-29.4.3.tgz#fff7be1cf5f06224dd36a857d52a9efeb005ba04" - integrity sha512-Vw/bVvcexmdJ7MLmgdT3ZjkJ3LKu8IlpefYokxiqoZy6OCQ2VAm6Vk3t/qHiAGUXbdbJKJWnc8gH3ypTbB/OBw== +jest-circus@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-circus/-/jest-circus-29.7.0.tgz#b6817a45fcc835d8b16d5962d0c026473ee3668a" + integrity sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw== dependencies: - "@jest/environment" "^29.4.3" - "@jest/expect" "^29.4.3" - "@jest/test-result" "^29.4.3" - "@jest/types" "^29.4.3" + "@jest/environment" "^29.7.0" + "@jest/expect" "^29.7.0" + "@jest/test-result" "^29.7.0" + "@jest/types" "^29.6.3" "@types/node" "*" chalk "^4.0.0" co "^4.6.0" - dedent "^0.7.0" + dedent "^1.0.0" is-generator-fn "^2.0.0" - jest-each "^29.4.3" - jest-matcher-utils "^29.4.3" - jest-message-util "^29.4.3" - jest-runtime "^29.4.3" - jest-snapshot "^29.4.3" - jest-util "^29.4.3" + jest-each "^29.7.0" + jest-matcher-utils "^29.7.0" + jest-message-util "^29.7.0" + jest-runtime "^29.7.0" + jest-snapshot "^29.7.0" + jest-util "^29.7.0" p-limit "^3.1.0" - pretty-format "^29.4.3" + pretty-format "^29.7.0" + pure-rand "^6.0.0" slash "^3.0.0" stack-utils "^2.0.3" -jest-cli@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest-cli/-/jest-cli-29.4.3.tgz#fe31fdd0c90c765f392b8b7c97e4845071cd2163" - integrity sha512-PiiAPuFNfWWolCE6t3ZrDXQc6OsAuM3/tVW0u27UWc1KE+n/HSn5dSE6B2juqN7WP+PP0jAcnKtGmI4u8GMYCg== +jest-cli@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-cli/-/jest-cli-29.7.0.tgz#5592c940798e0cae677eec169264f2d839a37995" + integrity sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg== dependencies: - "@jest/core" "^29.4.3" - "@jest/test-result" "^29.4.3" - "@jest/types" "^29.4.3" + "@jest/core" "^29.7.0" + "@jest/test-result" "^29.7.0" + "@jest/types" "^29.6.3" chalk "^4.0.0" + create-jest "^29.7.0" exit "^0.1.2" - graceful-fs "^4.2.9" import-local "^3.0.2" - jest-config "^29.4.3" - jest-util "^29.4.3" - jest-validate "^29.4.3" - prompts "^2.0.1" + jest-config "^29.7.0" + jest-util "^29.7.0" + jest-validate "^29.7.0" yargs "^17.3.1" -jest-config@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest-config/-/jest-config-29.4.3.tgz#fca9cdfe6298ae6d04beef1624064d455347c978" - integrity sha512-eCIpqhGnIjdUCXGtLhz4gdDoxKSWXKjzNcc5r+0S1GKOp2fwOipx5mRcwa9GB/ArsxJ1jlj2lmlD9bZAsBxaWQ== +jest-config@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-config/-/jest-config-29.7.0.tgz#bcbda8806dbcc01b1e316a46bb74085a84b0245f" + integrity sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ== dependencies: "@babel/core" "^7.11.6" - "@jest/test-sequencer" "^29.4.3" - "@jest/types" "^29.4.3" - babel-jest "^29.4.3" + "@jest/test-sequencer" "^29.7.0" + "@jest/types" "^29.6.3" + babel-jest "^29.7.0" chalk "^4.0.0" ci-info "^3.2.0" deepmerge "^4.2.2" glob "^7.1.3" graceful-fs "^4.2.9" - jest-circus "^29.4.3" - jest-environment-node "^29.4.3" - jest-get-type "^29.4.3" - jest-regex-util "^29.4.3" - jest-resolve "^29.4.3" - jest-runner "^29.4.3" - jest-util "^29.4.3" - jest-validate "^29.4.3" + jest-circus "^29.7.0" + jest-environment-node "^29.7.0" + jest-get-type "^29.6.3" + jest-regex-util "^29.6.3" + jest-resolve "^29.7.0" + jest-runner "^29.7.0" + jest-util "^29.7.0" + jest-validate "^29.7.0" micromatch "^4.0.4" parse-json "^5.2.0" - pretty-format "^29.4.3" + pretty-format "^29.7.0" slash "^3.0.0" strip-json-comments "^3.1.1" @@ -4448,67 +4881,82 @@ jest-diff@^29.4.3: jest-get-type "^29.4.3" pretty-format "^29.4.3" -jest-docblock@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest-docblock/-/jest-docblock-29.4.3.tgz#90505aa89514a1c7dceeac1123df79e414636ea8" - integrity sha512-fzdTftThczeSD9nZ3fzA/4KkHtnmllawWrXO69vtI+L9WjEIuXWs4AmyME7lN5hU7dB0sHhuPfcKofRsUb/2Fg== +jest-diff@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-diff/-/jest-diff-29.7.0.tgz#017934a66ebb7ecf6f205e84699be10afd70458a" + integrity sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw== dependencies: - detect-newline "^3.0.0" + chalk "^4.0.0" + diff-sequences "^29.6.3" + jest-get-type "^29.6.3" + pretty-format "^29.7.0" -jest-each@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest-each/-/jest-each-29.4.3.tgz#a434c199a2f6151c5e3dc80b2d54586bdaa72819" - integrity sha512-1ElHNAnKcbJb/b+L+7j0/w7bDvljw4gTv1wL9fYOczeJrbTbkMGQ5iQPFJ3eFQH19VPTx1IyfePdqSpePKss7Q== +jest-docblock@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-docblock/-/jest-docblock-29.7.0.tgz#8fddb6adc3cdc955c93e2a87f61cfd350d5d119a" + integrity sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g== dependencies: - "@jest/types" "^29.4.3" - chalk "^4.0.0" - jest-get-type "^29.4.3" - jest-util "^29.4.3" - pretty-format "^29.4.3" + detect-newline "^3.0.0" -jest-environment-node@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest-environment-node/-/jest-environment-node-29.4.3.tgz#579c4132af478befc1889ddc43c2413a9cdbe014" - integrity sha512-gAiEnSKF104fsGDXNkwk49jD/0N0Bqu2K9+aMQXA6avzsA9H3Fiv1PW2D+gzbOSR705bWd2wJZRFEFpV0tXISg== +jest-each@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-each/-/jest-each-29.7.0.tgz#162a9b3f2328bdd991beaabffbb74745e56577d1" + integrity sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ== dependencies: - "@jest/environment" "^29.4.3" - "@jest/fake-timers" "^29.4.3" - "@jest/types" "^29.4.3" + "@jest/types" "^29.6.3" + chalk "^4.0.0" + jest-get-type "^29.6.3" + jest-util "^29.7.0" + pretty-format "^29.7.0" + +jest-environment-node@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-environment-node/-/jest-environment-node-29.7.0.tgz#0b93e111dda8ec120bc8300e6d1fb9576e164376" + integrity sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw== + dependencies: + "@jest/environment" "^29.7.0" + "@jest/fake-timers" "^29.7.0" + "@jest/types" "^29.6.3" "@types/node" "*" - jest-mock "^29.4.3" - jest-util "^29.4.3" + jest-mock "^29.7.0" + jest-util "^29.7.0" jest-get-type@^29.4.3: version "29.4.3" resolved "https://registry.yarnpkg.com/jest-get-type/-/jest-get-type-29.4.3.tgz#1ab7a5207c995161100b5187159ca82dd48b3dd5" integrity sha512-J5Xez4nRRMjk8emnTpWrlkyb9pfRQQanDrvWHhsR1+VUfbwxi30eVcZFlcdGInRibU4G5LwHXpI7IRHU0CY+gg== -jest-haste-map@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest-haste-map/-/jest-haste-map-29.4.3.tgz#085a44283269e7ace0645c63a57af0d2af6942e2" - integrity sha512-eZIgAS8tvm5IZMtKlR8Y+feEOMfo2pSQkmNbufdbMzMSn9nitgGxF1waM/+LbryO3OkMcKS98SUb+j/cQxp/vQ== +jest-get-type@^29.6.3: + version "29.6.3" + resolved "https://registry.yarnpkg.com/jest-get-type/-/jest-get-type-29.6.3.tgz#36f499fdcea197c1045a127319c0481723908fd1" + integrity sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw== + +jest-haste-map@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-haste-map/-/jest-haste-map-29.7.0.tgz#3c2396524482f5a0506376e6c858c3bbcc17b104" + integrity sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA== dependencies: - "@jest/types" "^29.4.3" + "@jest/types" "^29.6.3" "@types/graceful-fs" "^4.1.3" "@types/node" "*" anymatch "^3.0.3" fb-watchman "^2.0.0" graceful-fs "^4.2.9" - jest-regex-util "^29.4.3" - jest-util "^29.4.3" - jest-worker "^29.4.3" + jest-regex-util "^29.6.3" + jest-util "^29.7.0" + jest-worker "^29.7.0" micromatch "^4.0.4" walker "^1.0.8" optionalDependencies: fsevents "^2.3.2" -jest-leak-detector@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest-leak-detector/-/jest-leak-detector-29.4.3.tgz#2b35191d6b35aa0256e63a9b79b0f949249cf23a" - integrity sha512-9yw4VC1v2NspMMeV3daQ1yXPNxMgCzwq9BocCwYrRgXe4uaEJPAN0ZK37nFBhcy3cUwEVstFecFLaTHpF7NiGA== +jest-leak-detector@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-leak-detector/-/jest-leak-detector-29.7.0.tgz#5b7ec0dadfdfec0ca383dc9aa016d36b5ea4c728" + integrity sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw== dependencies: - jest-get-type "^29.4.3" - pretty-format "^29.4.3" + jest-get-type "^29.6.3" + pretty-format "^29.7.0" jest-matcher-utils@^29.4.3: version "29.4.3" @@ -4520,6 +4968,16 @@ jest-matcher-utils@^29.4.3: jest-get-type "^29.4.3" pretty-format "^29.4.3" +jest-matcher-utils@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz#ae8fec79ff249fd592ce80e3ee474e83a6c44f12" + integrity sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g== + dependencies: + chalk "^4.0.0" + jest-diff "^29.7.0" + jest-get-type "^29.6.3" + pretty-format "^29.7.0" + jest-message-util@^29.4.3: version "29.4.3" resolved "https://registry.yarnpkg.com/jest-message-util/-/jest-message-util-29.4.3.tgz#65b5280c0fdc9419503b49d4f48d4999d481cb5b" @@ -4535,139 +4993,143 @@ jest-message-util@^29.4.3: slash "^3.0.0" stack-utils "^2.0.3" -jest-mock-axios@4.5.0: - version "4.5.0" - resolved "https://registry.yarnpkg.com/jest-mock-axios/-/jest-mock-axios-4.5.0.tgz#9862bcbea6c0f9c42bc8a125169eaeea514b2f56" - integrity sha512-AVrXkFS4psXtuR63J3SFOIpn6VQJHb3khuWJG+yKmSOAvY3jltAkBivV99QTWE+BA6kBYGGUojk6AGE177F8Gw== +jest-message-util@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-message-util/-/jest-message-util-29.7.0.tgz#8bc392e204e95dfe7564abbe72a404e28e51f7f3" + integrity sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w== dependencies: - synchronous-promise "^2.0.15" + "@babel/code-frame" "^7.12.13" + "@jest/types" "^29.6.3" + "@types/stack-utils" "^2.0.0" + chalk "^4.0.0" + graceful-fs "^4.2.9" + micromatch "^4.0.4" + pretty-format "^29.7.0" + slash "^3.0.0" + stack-utils "^2.0.3" -jest-mock@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest-mock/-/jest-mock-29.4.3.tgz#23d84a20a74cdfff0510fdbeefb841ed57b0fe7e" - integrity sha512-LjFgMg+xed9BdkPMyIJh+r3KeHt1klXPJYBULXVVAkbTaaKjPX1o1uVCAZADMEp/kOxGTwy/Ot8XbvgItOrHEg== +jest-mock@29.7.0, jest-mock@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-mock/-/jest-mock-29.7.0.tgz#4e836cf60e99c6fcfabe9f99d017f3fdd50a6347" + integrity sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw== dependencies: - "@jest/types" "^29.4.3" + "@jest/types" "^29.6.3" "@types/node" "*" - jest-util "^29.4.3" + jest-util "^29.7.0" jest-pnp-resolver@^1.2.2: - version "1.2.2" - resolved "https://registry.yarnpkg.com/jest-pnp-resolver/-/jest-pnp-resolver-1.2.2.tgz#b704ac0ae028a89108a4d040b3f919dfddc8e33c" - integrity sha512-olV41bKSMm8BdnuMsewT4jqlZ8+3TCARAXjZGT9jcoSnrfUnRCqnMoF9XEeoWjbzObpqF9dRhHQj0Xb9QdF6/w== + version "1.2.3" + resolved "https://registry.yarnpkg.com/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz#930b1546164d4ad5937d5540e711d4d38d4cad2e" + integrity sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w== -jest-regex-util@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest-regex-util/-/jest-regex-util-29.4.3.tgz#a42616141e0cae052cfa32c169945d00c0aa0bb8" - integrity sha512-O4FglZaMmWXbGHSQInfXewIsd1LMn9p3ZXB/6r4FOkyhX2/iP/soMG98jGvk/A3HAN78+5VWcBGO0BJAPRh4kg== +jest-regex-util@^29.6.3: + version "29.6.3" + resolved "https://registry.yarnpkg.com/jest-regex-util/-/jest-regex-util-29.6.3.tgz#4a556d9c776af68e1c5f48194f4d0327d24e8a52" + integrity sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg== -jest-resolve-dependencies@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest-resolve-dependencies/-/jest-resolve-dependencies-29.4.3.tgz#9ad7f23839a6d88cef91416bda9393a6e9fd1da5" - integrity sha512-uvKMZAQ3nmXLH7O8WAOhS5l0iWyT3WmnJBdmIHiV5tBbdaDZ1wqtNX04FONGoaFvSOSHBJxnwAVnSn1WHdGVaw== +jest-resolve-dependencies@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-resolve-dependencies/-/jest-resolve-dependencies-29.7.0.tgz#1b04f2c095f37fc776ff40803dc92921b1e88428" + integrity sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA== dependencies: - jest-regex-util "^29.4.3" - jest-snapshot "^29.4.3" + jest-regex-util "^29.6.3" + jest-snapshot "^29.7.0" -jest-resolve@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest-resolve/-/jest-resolve-29.4.3.tgz#3c5b5c984fa8a763edf9b3639700e1c7900538e2" - integrity sha512-GPokE1tzguRyT7dkxBim4wSx6E45S3bOQ7ZdKEG+Qj0Oac9+6AwJPCk0TZh5Vu0xzeX4afpb+eDmgbmZFFwpOw== +jest-resolve@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-resolve/-/jest-resolve-29.7.0.tgz#64d6a8992dd26f635ab0c01e5eef4399c6bcbc30" + integrity sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA== dependencies: chalk "^4.0.0" graceful-fs "^4.2.9" - jest-haste-map "^29.4.3" + jest-haste-map "^29.7.0" jest-pnp-resolver "^1.2.2" - jest-util "^29.4.3" - jest-validate "^29.4.3" + jest-util "^29.7.0" + jest-validate "^29.7.0" resolve "^1.20.0" resolve.exports "^2.0.0" slash "^3.0.0" -jest-runner@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest-runner/-/jest-runner-29.4.3.tgz#68dc82c68645eda12bea42b5beece6527d7c1e5e" - integrity sha512-GWPTEiGmtHZv1KKeWlTX9SIFuK19uLXlRQU43ceOQ2hIfA5yPEJC7AMkvFKpdCHx6pNEdOD+2+8zbniEi3v3gA== +jest-runner@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-runner/-/jest-runner-29.7.0.tgz#809af072d408a53dcfd2e849a4c976d3132f718e" + integrity sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ== dependencies: - "@jest/console" "^29.4.3" - "@jest/environment" "^29.4.3" - "@jest/test-result" "^29.4.3" - "@jest/transform" "^29.4.3" - "@jest/types" "^29.4.3" + "@jest/console" "^29.7.0" + "@jest/environment" "^29.7.0" + "@jest/test-result" "^29.7.0" + "@jest/transform" "^29.7.0" + "@jest/types" "^29.6.3" "@types/node" "*" chalk "^4.0.0" emittery "^0.13.1" graceful-fs "^4.2.9" - jest-docblock "^29.4.3" - jest-environment-node "^29.4.3" - jest-haste-map "^29.4.3" - jest-leak-detector "^29.4.3" - jest-message-util "^29.4.3" - jest-resolve "^29.4.3" - jest-runtime "^29.4.3" - jest-util "^29.4.3" - jest-watcher "^29.4.3" - jest-worker "^29.4.3" + jest-docblock "^29.7.0" + jest-environment-node "^29.7.0" + jest-haste-map "^29.7.0" + jest-leak-detector "^29.7.0" + jest-message-util "^29.7.0" + jest-resolve "^29.7.0" + jest-runtime "^29.7.0" + jest-util "^29.7.0" + jest-watcher "^29.7.0" + jest-worker "^29.7.0" p-limit "^3.1.0" source-map-support "0.5.13" -jest-runtime@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest-runtime/-/jest-runtime-29.4.3.tgz#f25db9874dcf35a3ab27fdaabca426666cc745bf" - integrity sha512-F5bHvxSH+LvLV24vVB3L8K467dt3y3dio6V3W89dUz9nzvTpqd/HcT9zfYKL2aZPvD63vQFgLvaUX/UpUhrP6Q== - dependencies: - "@jest/environment" "^29.4.3" - "@jest/fake-timers" "^29.4.3" - "@jest/globals" "^29.4.3" - "@jest/source-map" "^29.4.3" - "@jest/test-result" "^29.4.3" - "@jest/transform" "^29.4.3" - "@jest/types" "^29.4.3" +jest-runtime@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-runtime/-/jest-runtime-29.7.0.tgz#efecb3141cf7d3767a3a0cc8f7c9990587d3d817" + integrity sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ== + dependencies: + "@jest/environment" "^29.7.0" + "@jest/fake-timers" "^29.7.0" + "@jest/globals" "^29.7.0" + "@jest/source-map" "^29.6.3" + "@jest/test-result" "^29.7.0" + "@jest/transform" "^29.7.0" + "@jest/types" "^29.6.3" "@types/node" "*" chalk "^4.0.0" cjs-module-lexer "^1.0.0" collect-v8-coverage "^1.0.0" glob "^7.1.3" graceful-fs "^4.2.9" - jest-haste-map "^29.4.3" - jest-message-util "^29.4.3" - jest-mock "^29.4.3" - jest-regex-util "^29.4.3" - jest-resolve "^29.4.3" - jest-snapshot "^29.4.3" - jest-util "^29.4.3" + jest-haste-map "^29.7.0" + jest-message-util "^29.7.0" + jest-mock "^29.7.0" + jest-regex-util "^29.6.3" + jest-resolve "^29.7.0" + jest-snapshot "^29.7.0" + jest-util "^29.7.0" slash "^3.0.0" strip-bom "^4.0.0" -jest-snapshot@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest-snapshot/-/jest-snapshot-29.4.3.tgz#183d309371450d9c4a3de7567ed2151eb0e91145" - integrity sha512-NGlsqL0jLPDW91dz304QTM/SNO99lpcSYYAjNiX0Ou+sSGgkanKBcSjCfp/pqmiiO1nQaOyLp6XQddAzRcx3Xw== +jest-snapshot@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-snapshot/-/jest-snapshot-29.7.0.tgz#c2c574c3f51865da1bb329036778a69bf88a6be5" + integrity sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw== dependencies: "@babel/core" "^7.11.6" "@babel/generator" "^7.7.2" "@babel/plugin-syntax-jsx" "^7.7.2" "@babel/plugin-syntax-typescript" "^7.7.2" - "@babel/traverse" "^7.7.2" "@babel/types" "^7.3.3" - "@jest/expect-utils" "^29.4.3" - "@jest/transform" "^29.4.3" - "@jest/types" "^29.4.3" - "@types/babel__traverse" "^7.0.6" - "@types/prettier" "^2.1.5" + "@jest/expect-utils" "^29.7.0" + "@jest/transform" "^29.7.0" + "@jest/types" "^29.6.3" babel-preset-current-node-syntax "^1.0.0" chalk "^4.0.0" - expect "^29.4.3" + expect "^29.7.0" graceful-fs "^4.2.9" - jest-diff "^29.4.3" - jest-get-type "^29.4.3" - jest-haste-map "^29.4.3" - jest-matcher-utils "^29.4.3" - jest-message-util "^29.4.3" - jest-util "^29.4.3" + jest-diff "^29.7.0" + jest-get-type "^29.6.3" + jest-matcher-utils "^29.7.0" + jest-message-util "^29.7.0" + jest-util "^29.7.0" natural-compare "^1.4.0" - pretty-format "^29.4.3" - semver "^7.3.5" + pretty-format "^29.7.0" + semver "^7.5.3" jest-util@^29.0.0, jest-util@^29.4.3: version "29.4.3" @@ -4681,60 +5143,63 @@ jest-util@^29.0.0, jest-util@^29.4.3: graceful-fs "^4.2.9" picomatch "^2.2.3" -jest-validate@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest-validate/-/jest-validate-29.4.3.tgz#a13849dec4f9e95446a7080ad5758f58fa88642f" - integrity sha512-J3u5v7aPQoXPzaar6GndAVhdQcZr/3osWSgTeKg5v574I9ybX/dTyH0AJFb5XgXIB7faVhf+rS7t4p3lL9qFaw== +jest-util@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-util/-/jest-util-29.7.0.tgz#23c2b62bfb22be82b44de98055802ff3710fc0bc" + integrity sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA== dependencies: - "@jest/types" "^29.4.3" + "@jest/types" "^29.6.3" + "@types/node" "*" + chalk "^4.0.0" + ci-info "^3.2.0" + graceful-fs "^4.2.9" + picomatch "^2.2.3" + +jest-validate@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-validate/-/jest-validate-29.7.0.tgz#7bf705511c64da591d46b15fce41400d52147d9c" + integrity sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw== + dependencies: + "@jest/types" "^29.6.3" camelcase "^6.2.0" chalk "^4.0.0" - jest-get-type "^29.4.3" + jest-get-type "^29.6.3" leven "^3.1.0" - pretty-format "^29.4.3" + pretty-format "^29.7.0" -jest-watcher@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest-watcher/-/jest-watcher-29.4.3.tgz#e503baa774f0c2f8f3c8db98a22ebf885f19c384" - integrity sha512-zwlXH3DN3iksoIZNk73etl1HzKyi5FuQdYLnkQKm5BW4n8HpoG59xSwpVdFrnh60iRRaRBGw0gcymIxjJENPcA== +jest-watcher@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-watcher/-/jest-watcher-29.7.0.tgz#7810d30d619c3a62093223ce6bb359ca1b28a2f2" + integrity sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g== dependencies: - "@jest/test-result" "^29.4.3" - "@jest/types" "^29.4.3" + "@jest/test-result" "^29.7.0" + "@jest/types" "^29.6.3" "@types/node" "*" ansi-escapes "^4.2.1" chalk "^4.0.0" emittery "^0.13.1" - jest-util "^29.4.3" + jest-util "^29.7.0" string-length "^4.0.1" -jest-worker@^27.4.5: - version "27.5.1" - resolved "https://registry.yarnpkg.com/jest-worker/-/jest-worker-27.5.1.tgz#8d146f0900e8973b106b6f73cc1e9a8cb86f8db0" - integrity sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg== - dependencies: - "@types/node" "*" - merge-stream "^2.0.0" - supports-color "^8.0.0" - -jest-worker@^29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest-worker/-/jest-worker-29.4.3.tgz#9a4023e1ea1d306034237c7133d7da4240e8934e" - integrity sha512-GLHN/GTAAMEy5BFdvpUfzr9Dr80zQqBrh0fz1mtRMe05hqP45+HfQltu7oTBfduD0UeZs09d+maFtFYAXFWvAA== +jest-worker@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-worker/-/jest-worker-29.7.0.tgz#acad073acbbaeb7262bd5389e1bcf43e10058d4a" + integrity sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw== dependencies: "@types/node" "*" - jest-util "^29.4.3" + jest-util "^29.7.0" merge-stream "^2.0.0" supports-color "^8.0.0" -jest@29.4.3: - version "29.4.3" - resolved "https://registry.yarnpkg.com/jest/-/jest-29.4.3.tgz#1b8be541666c6feb99990fd98adac4737e6e6386" - integrity sha512-XvK65feuEFGZT8OO0fB/QAQS+LGHvQpaadkH5p47/j3Ocqq3xf2pK9R+G0GzgfuhXVxEv76qCOOcMb5efLk6PA== +jest@29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest/-/jest-29.7.0.tgz#994676fc24177f088f1c5e3737f5697204ff2613" + integrity sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw== dependencies: - "@jest/core" "^29.4.3" - "@jest/types" "^29.4.3" + "@jest/core" "^29.7.0" + "@jest/types" "^29.6.3" import-local "^3.0.2" - jest-cli "^29.4.3" + jest-cli "^29.7.0" js-tokens@^4.0.0: version "4.0.0" @@ -4749,6 +5214,18 @@ js-yaml@^3.13.1: argparse "^1.0.7" esprima "^4.0.0" +js-yaml@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.1.0.tgz#c1fb65f8f5017901cdd2c951864ba18458a10602" + integrity sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA== + dependencies: + argparse "^2.0.1" + +jsbn@1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-1.1.0.tgz#b01307cb29b618a1ed26ec79e911f803c4da0040" + integrity sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A== + jsesc@^2.5.1: version "2.5.2" resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-2.5.2.tgz#80564d2e483dacf6e8ef209650a67df3f0c283a4" @@ -4759,11 +5236,21 @@ json-parse-better-errors@^1.0.1: resolved "https://registry.yarnpkg.com/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz#bb867cfb3450e69107c131d1c514bab3dc8bcaa9" integrity sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw== -json-parse-even-better-errors@^2.3.0, json-parse-even-better-errors@^2.3.1: +json-parse-even-better-errors@^2.3.0: version "2.3.1" resolved "https://registry.yarnpkg.com/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz#7c47805a94319928e05777405dc12e1f7a4ee02d" integrity sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w== +json-parse-even-better-errors@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/json-parse-even-better-errors/-/json-parse-even-better-errors-3.0.0.tgz#2cb2ee33069a78870a0c7e3da560026b89669cf7" + integrity sha512-iZbGHafX/59r39gPwVPRBGw0QQKnA7tte5pSMrhWOW7swGsVvVTjmfyAV9pNqk8YGT7tRCdxRu8uzcgZwoDooA== + +json-parse-even-better-errors@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/json-parse-even-better-errors/-/json-parse-even-better-errors-3.0.1.tgz#02bb29fb5da90b5444581749c22cedd3597c6cb0" + integrity sha512-aatBvbL26wVUCLmbWdCpeu9iF5wOyWpagiKkInA+kfws3sWdBrTnsvN2CKcyCYyUrc7rebNBlK6+kteg7ksecg== + json-schema-traverse@^0.4.1: version "0.4.1" resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz#69f6a87d9513ab8bb8fe63bdb0979c448e684660" @@ -4777,7 +5264,7 @@ json-schema-traverse@^1.0.0: json-stable-stringify-without-jsonify@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz#9db7b59496ad3f3cfef30a75142d2d930ad72651" - integrity sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE= + integrity sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw== json-stringify-nice@^1.1.4: version "1.1.4" @@ -4789,16 +5276,11 @@ json-stringify-safe@^5.0.1: resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb" integrity sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA== -json5@2.2.3, json5@^2.2.1, json5@^2.2.2, json5@^2.2.3: +json5@2.2.3, json5@^2.2.2, json5@^2.2.3: version "2.2.3" resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.3.tgz#78cd6f1a19bdc12b73db5ad0c61efd66c1e29283" integrity sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg== -jsonc-parser@^3.2.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/jsonc-parser/-/jsonc-parser-3.2.0.tgz#31ff3f4c2b9793f89c67212627c51c6394f88e76" - integrity sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w== - jsonfile@^6.0.1: version "6.1.0" resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-6.1.0.tgz#bc55b2634793c679ec6403094eb13698a6ec0aae" @@ -4818,12 +5300,12 @@ just-diff-apply@^5.2.0: resolved "https://registry.yarnpkg.com/just-diff-apply/-/just-diff-apply-5.5.0.tgz#771c2ca9fa69f3d2b54e7c3f5c1dfcbcc47f9f0f" integrity sha512-OYTthRfSh55WOItVqwpefPtNt2VdKsq5AnAK6apdtR6yCH8pr0CmSr710J0Mf+WdQy7K/OzMy7K2MgAfdQURDw== -just-diff@^5.0.1: - version "5.2.0" - resolved "https://registry.yarnpkg.com/just-diff/-/just-diff-5.2.0.tgz#60dca55891cf24cd4a094e33504660692348a241" - integrity sha512-6ufhP9SHjb7jibNFrNxyFZ6od3g+An6Ai9mhGRvcYe8UJlH0prseN64M+6ZBBUoKYHZsitDP42gAJ8+eVWr3lw== +just-diff@^6.0.0: + version "6.0.2" + resolved "https://registry.yarnpkg.com/just-diff/-/just-diff-6.0.2.tgz#03b65908543ac0521caf6d8eb85035f7d27ea285" + integrity sha512-S59eriX5u3/QhMNq3v/gm8Kd0w8OS6Tz2FS1NG4blv+z0MuQcBRJyFWjdovM0Rad4/P4aUPFtnkNjMjyMlMSYA== -kind-of@^6.0.2, kind-of@^6.0.3: +kind-of@^6.0.3: version "6.0.3" resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd" integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw== @@ -4846,161 +5328,270 @@ levn@^0.4.1: prelude-ls "^1.2.1" type-check "~0.4.0" -libnpmaccess@^6.0.4: - version "6.0.4" - resolved "https://registry.yarnpkg.com/libnpmaccess/-/libnpmaccess-6.0.4.tgz#2dd158bd8a071817e2207d3b201d37cf1ad6ae6b" - integrity sha512-qZ3wcfIyUoW0+qSFkMBovcTrSGJ3ZeyvpR7d5N9pEYv/kXs8sHP2wiqEIXBKLFrZlmM0kR0RJD7mtfLngtlLag== +libnpmaccess@^7.0.2: + version "7.0.2" + resolved "https://registry.yarnpkg.com/libnpmaccess/-/libnpmaccess-7.0.2.tgz#7f056c8c933dd9c8ba771fa6493556b53c5aac52" + integrity sha512-vHBVMw1JFMTgEk15zRsJuSAg7QtGGHpUSEfnbcRL1/gTBag9iEfJbyjpDmdJmwMhvpoLoNBtdAUCdGnaP32hhw== dependencies: - aproba "^2.0.0" - minipass "^3.1.1" - npm-package-arg "^9.0.1" - npm-registry-fetch "^13.0.0" + npm-package-arg "^10.1.0" + npm-registry-fetch "^14.0.3" -libnpmdiff@^4.0.5: - version "4.0.5" - resolved "https://registry.yarnpkg.com/libnpmdiff/-/libnpmdiff-4.0.5.tgz#ffaf93fa9440ea759444b8830fdb5c661b09a7c0" - integrity sha512-9fICQIzmH892UwHHPmb+Seup50UIBWcMIK2FdxvlXm9b4kc1nSH0b/BuY1mORJQtB6ydPMnn+BLzOTmd/SKJmw== +libnpmaccess@^8.0.1: + version "8.0.2" + resolved "https://registry.yarnpkg.com/libnpmaccess/-/libnpmaccess-8.0.2.tgz#a13a72fd5b71a1063ea54973fa56d61ec38f718f" + integrity sha512-4K+nsg3OYt4rjryP/3D5zGWluLbZaKozwj6YdtvAyxNhLhUrjCoyxHVoL5AkTJcAnjsd6/ATei52QPVvpSX9Ug== dependencies: - "@npmcli/disparity-colors" "^2.0.0" - "@npmcli/installed-package-contents" "^1.0.7" - binary-extensions "^2.2.0" - diff "^5.1.0" - minimatch "^5.0.1" - npm-package-arg "^9.0.1" - pacote "^13.6.1" - tar "^6.1.0" + npm-package-arg "^11.0.1" + npm-registry-fetch "^16.0.0" -libnpmexec@^4.0.14: - version "4.0.14" - resolved "https://registry.yarnpkg.com/libnpmexec/-/libnpmexec-4.0.14.tgz#9ad44232434b374e477eb2c2e4548baaf698f773" - integrity sha512-dwmzv2K29SdoAHBOa7QR6CfQbFG/PiZDRF6HZrlI6C4DLt2hNgOHTFaUGOpqE2C+YGu0ZwYTDywxRe0eOnf0ZA== +libnpmdiff@^5.0.14: + version "5.0.14" + resolved "https://registry.yarnpkg.com/libnpmdiff/-/libnpmdiff-5.0.14.tgz#162c2a12d0940b023eed09356ccd23cf97daec5f" + integrity sha512-B4s9U8iJ+1s3gSqHOlnTEi3oeH69i+/ZFOfZW2PyNRXhzm53BrS2etPOY/omiXu/yaIf4xm12qBHnSWC51myCQ== dependencies: - "@npmcli/arborist" "^5.6.3" - "@npmcli/ci-detect" "^2.0.0" - "@npmcli/fs" "^2.1.1" - "@npmcli/run-script" "^4.2.0" + "@npmcli/arborist" "^6.2.6" + "@npmcli/disparity-colors" "^3.0.0" + "@npmcli/installed-package-contents" "^2.0.2" + binary-extensions "^2.2.0" + diff "^5.1.0" + minimatch "^7.4.2" + npm-package-arg "^10.1.0" + pacote "^15.0.8" + tar "^6.1.13" + +libnpmdiff@^6.0.3: + version "6.0.6" + resolved "https://registry.yarnpkg.com/libnpmdiff/-/libnpmdiff-6.0.6.tgz#0fd846b979a6c40efcfdac8807241dae7a4ffc47" + integrity sha512-t+SpjT096MLtPKR/h3VqrxnYK3zhAaA0UZZLzNNXhvjPDJ5H5yk9SUwSkEjyBtQlNKyxrMXUjcitqJCC53BIlA== + dependencies: + "@npmcli/arborist" "^7.2.1" + "@npmcli/disparity-colors" "^3.0.0" + "@npmcli/installed-package-contents" "^2.0.2" + binary-extensions "^2.2.0" + diff "^5.1.0" + minimatch "^9.0.0" + npm-package-arg "^11.0.1" + pacote "^17.0.4" + tar "^6.2.0" + +libnpmexec@^5.0.14: + version "5.0.14" + resolved "https://registry.yarnpkg.com/libnpmexec/-/libnpmexec-5.0.14.tgz#005286e36dea59b4760a25d9c46f36961123b57a" + integrity sha512-O6ohaphY0bWCXF/djz/T4qnRUigERoTB7IfxGoVbYlIXgkFpDEk/UJVWje5dhbru3+sUBBTV8+CYfQTwo33sRg== + dependencies: + "@npmcli/arborist" "^6.2.6" + "@npmcli/run-script" "^6.0.0" chalk "^4.1.0" - mkdirp-infer-owner "^2.0.0" - npm-package-arg "^9.0.1" - npmlog "^6.0.2" - pacote "^13.6.1" - proc-log "^2.0.0" - read "^1.0.7" - read-package-json-fast "^2.0.2" + ci-info "^3.7.1" + npm-package-arg "^10.1.0" + npmlog "^7.0.1" + pacote "^15.0.8" + proc-log "^3.0.0" + read "^2.0.0" + read-package-json-fast "^3.0.2" semver "^7.3.7" walk-up-path "^1.0.0" -libnpmfund@^3.0.5: - version "3.0.5" - resolved "https://registry.yarnpkg.com/libnpmfund/-/libnpmfund-3.0.5.tgz#817f9e2120889beb483d9ba8eda142bb84293e4e" - integrity sha512-KdeRoG/dem8H3PcEU2/0SKi3ip7AWwczgS72y/3PE+PBrz/s/G52FNIA9jeLnBirkLC0sOyQHfeM3b7e24ZM+g== +libnpmexec@^7.0.4: + version "7.0.7" + resolved "https://registry.yarnpkg.com/libnpmexec/-/libnpmexec-7.0.7.tgz#ffa67bfbb06f8881ada989d0aa5094e2033f4194" + integrity sha512-pkca7D8s84GqLQf8wh7QKWXUlUKc+BQlwztzCqjWqxVNYjl2sF+WRGB1cmVFBshJ82tm2etWkpmxmkrHus4uJQ== + dependencies: + "@npmcli/arborist" "^7.2.1" + "@npmcli/run-script" "^7.0.2" + ci-info "^4.0.0" + npm-package-arg "^11.0.1" + npmlog "^7.0.1" + pacote "^17.0.4" + proc-log "^3.0.0" + read "^2.0.0" + read-package-json-fast "^3.0.2" + semver "^7.3.7" + walk-up-path "^3.0.1" + +libnpmfund@^4.0.14: + version "4.0.14" + resolved "https://registry.yarnpkg.com/libnpmfund/-/libnpmfund-4.0.14.tgz#65c335210b0ae7ef354fd72a00f5ab0fed8a4d76" + integrity sha512-oRFVW/2bWSNNIDPpwhs9ljvzHSmm+VJ41Q09y1wY+zBvKI0pZ62cah/InaWDo/ntpWNT5wFA7RKXojC9Qs5ubA== + dependencies: + "@npmcli/arborist" "^6.2.6" + +libnpmfund@^5.0.1: + version "5.0.4" + resolved "https://registry.yarnpkg.com/libnpmfund/-/libnpmfund-5.0.4.tgz#f2eac5227ffc0cbd3931021f6597e67d3659d7fb" + integrity sha512-nmS7giJ/4q/44fXG4b/A6GM/+g6nMguPGm7LdPGh5JsnXrf61sJCO+e3aAzyuPPLMI81oVP1c7Nd9y3/2OLzYQ== dependencies: - "@npmcli/arborist" "^5.6.3" + "@npmcli/arborist" "^7.2.1" -libnpmhook@^8.0.4: - version "8.0.4" - resolved "https://registry.yarnpkg.com/libnpmhook/-/libnpmhook-8.0.4.tgz#6c58e5fe763ff5d600ae9c20457ea9a69d1f7d87" - integrity sha512-nuD6e+Nx0OprjEi0wOeqASMl6QIH235th/Du2/8upK3evByFhzIgdfOeP1OhstavW4xtsl0hk5Vw4fAWWuSUgA== +libnpmhook@^10.0.0: + version "10.0.1" + resolved "https://registry.yarnpkg.com/libnpmhook/-/libnpmhook-10.0.1.tgz#3cb9516645f0d6891b4a59c72ffe026bdbb9bd6b" + integrity sha512-FnXCweDpoAko6mnLPSW8qrRYicjfh+GrvY5PuYHQRPvaW4BFtHDUmK3K3aYx4yD3TeGAKpj4IigrEDfUfWuSkA== dependencies: aproba "^2.0.0" - npm-registry-fetch "^13.0.0" + npm-registry-fetch "^16.0.0" -libnpmorg@^4.0.4: - version "4.0.4" - resolved "https://registry.yarnpkg.com/libnpmorg/-/libnpmorg-4.0.4.tgz#2a01d49372cf0df90d79a61e69bddaf2ed704311" - integrity sha512-1bTpD7iub1rDCsgiBguhJhiDufLQuc8DEti20euqsXz9O0ncXVpCYqf2SMmHR4GEdmAvAj2r7FMiyA9zGdaTpA== +libnpmhook@^9.0.3: + version "9.0.3" + resolved "https://registry.yarnpkg.com/libnpmhook/-/libnpmhook-9.0.3.tgz#5dbd6a146feb7e11993d36a26f750ae2347bb1d9" + integrity sha512-wMZe58sI7KLhg0+nUWZW5KdMfjNNcOIIbkoP19BDHYoUF9El7eeUWkGNxUGzpHkPKiGoQ1z/v6CYin4deebeuw== dependencies: aproba "^2.0.0" - npm-registry-fetch "^13.0.0" + npm-registry-fetch "^14.0.3" -libnpmpack@^4.1.3: - version "4.1.3" - resolved "https://registry.yarnpkg.com/libnpmpack/-/libnpmpack-4.1.3.tgz#025cfe39829acd8260662bf259e3a9331fc1e4b2" - integrity sha512-rYP4X++ME3ZiFO+2iN3YnXJ4LB4Gsd0z5cgszWJZxaEpDN4lRIXirSyynGNsN/hn4taqnlxD+3DPlFDShvRM8w== +libnpmorg@^5.0.3: + version "5.0.3" + resolved "https://registry.yarnpkg.com/libnpmorg/-/libnpmorg-5.0.3.tgz#bd0a11d7a84b5f5c14689fb1e244fbb540700d63" + integrity sha512-QCLLB2oKCCwdiedQRcsj5eHAyYXM7vICM5f0gB9aRQzyVzx57S3anBIzhEUOhJxq6cWKtXRfkR5GsCxHEJ0CxA== dependencies: - "@npmcli/run-script" "^4.1.3" - npm-package-arg "^9.0.1" - pacote "^13.6.1" + aproba "^2.0.0" + npm-registry-fetch "^14.0.3" -libnpmpublish@^6.0.5: - version "6.0.5" - resolved "https://registry.yarnpkg.com/libnpmpublish/-/libnpmpublish-6.0.5.tgz#5a894f3de2e267d62f86be2a508e362599b5a4b1" - integrity sha512-LUR08JKSviZiqrYTDfywvtnsnxr+tOvBU0BF8H+9frt7HMvc6Qn6F8Ubm72g5hDTHbq8qupKfDvDAln2TVPvFg== +libnpmorg@^6.0.1: + version "6.0.2" + resolved "https://registry.yarnpkg.com/libnpmorg/-/libnpmorg-6.0.2.tgz#6e5e37ecc5a391082e83c599512689c78e60dc70" + integrity sha512-zK4r6cjVsfXf7hWzWGB6R0LBJidVhKaeMWMZL/1eyZS6ixxAxVijfsPacoEnBRCFaXsNjAtwV3b2RCmYU6+usA== dependencies: - normalize-package-data "^4.0.0" - npm-package-arg "^9.0.1" - npm-registry-fetch "^13.0.0" + aproba "^2.0.0" + npm-registry-fetch "^16.0.0" + +libnpmpack@^5.0.14: + version "5.0.14" + resolved "https://registry.yarnpkg.com/libnpmpack/-/libnpmpack-5.0.14.tgz#a0bd93cc5d8c80a4c4c6cab8c19902aa3ce2153b" + integrity sha512-uJxdDaVY/lzR4JfucBKlCvbvheRJxc3ekymTnudo6rrWdpsrLESBsv0GLO+kF33n4BvZ6jjBz3+kZV66Xh97DA== + dependencies: + "@npmcli/arborist" "^6.2.6" + "@npmcli/run-script" "^6.0.0" + npm-package-arg "^10.1.0" + pacote "^15.0.8" + +libnpmpack@^6.0.3: + version "6.0.6" + resolved "https://registry.yarnpkg.com/libnpmpack/-/libnpmpack-6.0.6.tgz#8e14a04edc0feacb36705c448ef5d9fe81a6791e" + integrity sha512-9gcvl9kklG65wjV5t4Q51+19DsG40UtNdcfdWdn7yWbdBLMj9CgAiFF17DE3YeQp3oTngs9+HT+k1p1kX3Y8aA== + dependencies: + "@npmcli/arborist" "^7.2.1" + "@npmcli/run-script" "^7.0.2" + npm-package-arg "^11.0.1" + pacote "^17.0.4" + +libnpmpublish@^7.1.3: + version "7.1.3" + resolved "https://registry.yarnpkg.com/libnpmpublish/-/libnpmpublish-7.1.3.tgz#98e1b0a41cc8addfb7a8aee241e57e0034b877c4" + integrity sha512-Ek/pCn90CphbpeQ3Jrd/TtQNsvBjwHnB1gtxrWiZQNCed7hTMlSSQzYhnZeipAXvxxQkH3Ebf34/60Hw2JyV+g== + dependencies: + ci-info "^3.6.1" + normalize-package-data "^5.0.0" + npm-package-arg "^10.1.0" + npm-registry-fetch "^14.0.3" + proc-log "^3.0.0" semver "^7.3.7" - ssri "^9.0.0" + sigstore "^1.0.0" + ssri "^10.0.1" + +libnpmpublish@^9.0.2: + version "9.0.4" + resolved "https://registry.yarnpkg.com/libnpmpublish/-/libnpmpublish-9.0.4.tgz#0222c14578088ca9a758585c36d8133b828c87ad" + integrity sha512-330o6pVsCCg77jQ/+kidyG/RiohXYQKpqmzOC4BjUDWcimb+mXptRBh1Kvy27/Zb/CStZLVrfgGc6tXf5+PE3Q== + dependencies: + ci-info "^4.0.0" + normalize-package-data "^6.0.0" + npm-package-arg "^11.0.1" + npm-registry-fetch "^16.0.0" + proc-log "^3.0.0" + semver "^7.3.7" + sigstore "^2.2.0" + ssri "^10.0.5" -libnpmsearch@^5.0.4: - version "5.0.4" - resolved "https://registry.yarnpkg.com/libnpmsearch/-/libnpmsearch-5.0.4.tgz#b32aa2b23051c00cdcc0912274d0d416e6655d81" - integrity sha512-XHDmsvpN5+pufvGnfLRqpy218gcGGbbbXR6wPrDJyd1em6agKdYByzU5ccskDHH9iVm2UeLydpDsW1ksYuU0cg== +libnpmsearch@^6.0.2: + version "6.0.2" + resolved "https://registry.yarnpkg.com/libnpmsearch/-/libnpmsearch-6.0.2.tgz#b6a531a312855dd3bf84dd273b1033dd09b4cbec" + integrity sha512-p+5BF19AvnVg8mcIQhy6yWhI6jHQRVMYaIaKeITEfYAffWsqbottA/WZdMtHL76hViC6SFM1WdclM1w5eAIa1g== dependencies: - npm-registry-fetch "^13.0.0" + npm-registry-fetch "^14.0.3" -libnpmteam@^4.0.4: - version "4.0.4" - resolved "https://registry.yarnpkg.com/libnpmteam/-/libnpmteam-4.0.4.tgz#ac26068808d93b1051d926457db14e4b3ff669ef" - integrity sha512-rzKSwi6MLzwwevbM/vl+BBQTErgn24tCfgPUdzBlszrw3j5necOu7WnTzgvZMDv6maGUwec6Ut1rxszOgH0l+Q== +libnpmsearch@^7.0.0: + version "7.0.1" + resolved "https://registry.yarnpkg.com/libnpmsearch/-/libnpmsearch-7.0.1.tgz#8fa803a8e5837a33ce750a8cc1c70820d728b91d" + integrity sha512-XyKi6Y94t6PGd5Lk2Ma3+fgiHWD3KSCvXmHOrcLkAOEP7oUejbNjL0Bb/HUDZXgBj6gP1Qk7pJ6jZPFBc2hmXQ== + dependencies: + npm-registry-fetch "^16.0.0" + +libnpmteam@^5.0.3: + version "5.0.3" + resolved "https://registry.yarnpkg.com/libnpmteam/-/libnpmteam-5.0.3.tgz#196657e9d87c0cc914c44fee588ad2b838074a3c" + integrity sha512-7XOGhi45s+ml6TyrhJUTyrErcoDMKGKfEtiTEco4ofU7BGGAUOalVztKMVLLJgJOOXdIAIlzCHqkTXEuSiyCiA== dependencies: aproba "^2.0.0" - npm-registry-fetch "^13.0.0" + npm-registry-fetch "^14.0.3" -libnpmversion@^3.0.7: - version "3.0.7" - resolved "https://registry.yarnpkg.com/libnpmversion/-/libnpmversion-3.0.7.tgz#e4c6c07ee28cf351ce1e2293a5ac9922b09ea94d" - integrity sha512-O0L4eNMUIMQ+effi1HsZPKp2N6wecwqGqB8PvkvmLPWN7EsdabdzAVG48nv0p/OjlbIai5KQg/L+qMMfCA4ZjA== +libnpmteam@^6.0.0: + version "6.0.1" + resolved "https://registry.yarnpkg.com/libnpmteam/-/libnpmteam-6.0.1.tgz#daa1b2e7e4ccef0469bdef661737ca823b53468b" + integrity sha512-1YytqVk1gSkKFNMe4kkCKN49y5rlABrRSx5TrYShQtt2Lb4uQaed49dGE7Ue8TJGxbIkHzvyyVtb3PBiGACVqw== + dependencies: + aproba "^2.0.0" + npm-registry-fetch "^16.0.0" + +libnpmversion@^4.0.2: + version "4.0.2" + resolved "https://registry.yarnpkg.com/libnpmversion/-/libnpmversion-4.0.2.tgz#cad9cd1b287fcf9576a64edfe71491b49a65d06f" + integrity sha512-n1X70mFHv8Piy4yos+MFWUARSkTbyV5cdsHScaIkuwYvRAF/s2VtYScDzWB4Oe8uNEuGNdjiRR1E/Dh1tMvv6g== dependencies: - "@npmcli/git" "^3.0.0" - "@npmcli/run-script" "^4.1.3" - json-parse-even-better-errors "^2.3.1" - proc-log "^2.0.0" + "@npmcli/git" "^4.0.1" + "@npmcli/run-script" "^6.0.0" + json-parse-even-better-errors "^3.0.0" + proc-log "^3.0.0" semver "^7.3.7" -lilconfig@2.0.6: - version "2.0.6" - resolved "https://registry.yarnpkg.com/lilconfig/-/lilconfig-2.0.6.tgz#32a384558bd58af3d4c6e077dd1ad1d397bc69d4" - integrity sha512-9JROoBW7pobfsx+Sq2JsASvCo6Pfo6WWoUW79HuB1BCoBXD4PLWJPqDF6fNj67pqBYTbAHkE57M1kS/+L1neOg== +libnpmversion@^5.0.1: + version "5.0.2" + resolved "https://registry.yarnpkg.com/libnpmversion/-/libnpmversion-5.0.2.tgz#aea7b09bc270c778cbc8be7bf02e4b60566989cf" + integrity sha512-6JBnLhd6SYgKRekJ4cotxpURLGbEtKxzw+a8p5o+wNwrveJPMH8yW/HKjeewyHzWmxzzwn9EQ3TkF2onkrwstA== + dependencies: + "@npmcli/git" "^5.0.3" + "@npmcli/run-script" "^7.0.2" + json-parse-even-better-errors "^3.0.0" + proc-log "^3.0.0" + semver "^7.3.7" + +lilconfig@3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/lilconfig/-/lilconfig-3.0.0.tgz#f8067feb033b5b74dab4602a5f5029420be749bc" + integrity sha512-K2U4W2Ff5ibV7j7ydLr+zLAkIg5JJ4lPn1Ltsdt+Tz/IjQ8buJ55pZAxoP34lqIiwtF9iAvtLv3JGv7CAyAg+g== lines-and-columns@^1.1.6: version "1.2.4" resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-1.2.4.tgz#eca284f75d2965079309dc0ad9255abb2ebc1632" integrity sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg== -lint-staged@13.1.2: - version "13.1.2" - resolved "https://registry.yarnpkg.com/lint-staged/-/lint-staged-13.1.2.tgz#443636a0cfd834d5518d57d228130dc04c83d6fb" - integrity sha512-K9b4FPbWkpnupvK3WXZLbgu9pchUJ6N7TtVZjbaPsoizkqFUDkUReUL25xdrCljJs7uLUF3tZ7nVPeo/6lp+6w== +lint-staged@15.2.2: + version "15.2.2" + resolved "https://registry.yarnpkg.com/lint-staged/-/lint-staged-15.2.2.tgz#ad7cbb5b3ab70e043fa05bff82a09ed286bc4c5f" + integrity sha512-TiTt93OPh1OZOsb5B7k96A/ATl2AjIZo+vnzFZ6oHK5FuTk63ByDtxGQpHm+kFETjEWqgkF95M8FRXKR/LEBcw== + dependencies: + chalk "5.3.0" + commander "11.1.0" + debug "4.3.4" + execa "8.0.1" + lilconfig "3.0.0" + listr2 "8.0.1" + micromatch "4.0.5" + pidtree "0.6.0" + string-argv "0.3.2" + yaml "2.3.4" + +listr2@8.0.1: + version "8.0.1" + resolved "https://registry.yarnpkg.com/listr2/-/listr2-8.0.1.tgz#4d3f50ae6cec3c62bdf0e94f5c2c9edebd4b9c34" + integrity sha512-ovJXBXkKGfq+CwmKTjluEqFi3p4h8xvkxGQQAQan22YCgef4KZ1mKGjzfGh6PL6AW5Csw0QiQPNuQyH+6Xk3hA== dependencies: - cli-truncate "^3.1.0" - colorette "^2.0.19" - commander "^9.4.1" - debug "^4.3.4" - execa "^6.1.0" - lilconfig "2.0.6" - listr2 "^5.0.5" - micromatch "^4.0.5" - normalize-path "^3.0.0" - object-inspect "^1.12.2" - pidtree "^0.6.0" - string-argv "^0.3.1" - yaml "^2.1.3" - -listr2@^5.0.5: - version "5.0.7" - resolved "https://registry.yarnpkg.com/listr2/-/listr2-5.0.7.tgz#de69ccc4caf6bea7da03c74f7a2ffecf3904bd53" - integrity sha512-MD+qXHPmtivrHIDRwPYdfNkrzqDiuaKU/rfBcec3WMyMF3xylQj3jMq344OtvQxz7zaCFViRAeqlr2AFhPvXHw== - dependencies: - cli-truncate "^2.1.0" - colorette "^2.0.19" - log-update "^4.0.0" - p-map "^4.0.0" + cli-truncate "^4.0.0" + colorette "^2.0.20" + eventemitter3 "^5.0.1" + log-update "^6.0.0" rfdc "^1.3.0" - rxjs "^7.8.0" - through "^2.3.8" - wrap-ansi "^7.0.0" + wrap-ansi "^9.0.0" load-json-file@^4.0.0: version "4.0.0" @@ -5012,11 +5603,6 @@ load-json-file@^4.0.0: pify "^3.0.0" strip-bom "^3.0.0" -loader-runner@^4.2.0: - version "4.3.0" - resolved "https://registry.yarnpkg.com/loader-runner/-/loader-runner-4.3.0.tgz#c1b4a163b99f614830353b16755e7149ac2314e1" - integrity sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg== - locate-path@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-2.0.0.tgz#2b568b265eec944c6d9c0de9c3dbbbca0354cd8e" @@ -5032,6 +5618,30 @@ locate-path@^5.0.0: dependencies: p-locate "^4.1.0" +locate-path@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-6.0.0.tgz#55321eb309febbc59c4801d931a72452a681d286" + integrity sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw== + dependencies: + p-locate "^5.0.0" + +locate-path@^7.1.0: + version "7.2.0" + resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-7.2.0.tgz#69cb1779bd90b35ab1e771e1f2f89a202c2a8a8a" + integrity sha512-gvVijfZvn7R+2qyPX8mAuKcFGDf6Nc61GdvGafQsHL0sBIxfKzA+usWn4GFC/bk+QdwPUD4kWFJLhElipq+0VA== + dependencies: + p-locate "^6.0.0" + +lodash-es@^4.17.21: + version "4.17.21" + resolved "https://registry.yarnpkg.com/lodash-es/-/lodash-es-4.17.21.tgz#43e626c46e6591b7750beb2b50117390c609e3ee" + integrity sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw== + +lodash.camelcase@^4.3.0: + version "4.3.0" + resolved "https://registry.yarnpkg.com/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz#b28aa6288a2b9fc651035c7711f65ab6190331a6" + integrity sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA== + lodash.capitalize@^4.2.1: version "4.2.1" resolved "https://registry.yarnpkg.com/lodash.capitalize/-/lodash.capitalize-4.2.1.tgz#f826c9b4e2a8511d84e3aca29db05e1a4f3b72a9" @@ -5042,6 +5652,11 @@ lodash.escaperegexp@^4.1.2: resolved "https://registry.yarnpkg.com/lodash.escaperegexp/-/lodash.escaperegexp-4.1.2.tgz#64762c48618082518ac3df4ccf5d5886dae20347" integrity sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw== +lodash.isfunction@^3.0.9: + version "3.0.9" + resolved "https://registry.yarnpkg.com/lodash.isfunction/-/lodash.isfunction-3.0.9.tgz#06de25df4db327ac931981d1bdb067e5af68d051" + integrity sha512-AirXNj15uRIMMPihnkInB4i3NHeb4iBtNg9WRWuK2o31S+ePwwNmDPaTL3o7dTJ+VXNZim7rFs4rxN4YU1oUJw== + lodash.ismatch@^4.4.0: version "4.4.0" resolved "https://registry.yarnpkg.com/lodash.ismatch/-/lodash.ismatch-4.4.0.tgz#756cb5150ca3ba6f11085a78849645f188f85f37" @@ -5057,6 +5672,16 @@ lodash.isstring@^4.0.1: resolved "https://registry.yarnpkg.com/lodash.isstring/-/lodash.isstring-4.0.1.tgz#d527dfb5456eca7cc9bb95d5daeaf88ba54a5451" integrity sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw== +lodash.kebabcase@^4.1.1: + version "4.1.1" + resolved "https://registry.yarnpkg.com/lodash.kebabcase/-/lodash.kebabcase-4.1.1.tgz#8489b1cb0d29ff88195cceca448ff6d6cc295c36" + integrity sha512-N8XRTIMMqqDgSy4VLKPnJ/+hpGZN+PHQiJnSenYqPaVV/NCqEogTnAdZLQiGKhxX+JCs8waWq2t1XHWKOmlY8g== + +lodash.map@^4.5.1: + version "4.6.0" + resolved "https://registry.yarnpkg.com/lodash.map/-/lodash.map-4.6.0.tgz#771ec7839e3473d9c4cde28b19394c3562f4f6d3" + integrity sha512-worNHGKLDetmcEYDvh2stPCrrQRkP20E4l0iIS7F8EvzMqBBi7ltvFN5m1HvTf1P7Jk1txKhvFcmYsCr8O2F1Q== + lodash.memoize@4.x: version "4.1.2" resolved "https://registry.yarnpkg.com/lodash.memoize/-/lodash.memoize-4.1.2.tgz#bcc6c49a42a2840ed997f323eada5ecd182e0bfe" @@ -5067,37 +5692,69 @@ lodash.merge@^4.6.2: resolved "https://registry.yarnpkg.com/lodash.merge/-/lodash.merge-4.6.2.tgz#558aa53b43b661e1925a0afdfa36a9a1085fe57a" integrity sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ== -lodash.truncate@^4.4.2: - version "4.4.2" - resolved "https://registry.yarnpkg.com/lodash.truncate/-/lodash.truncate-4.4.2.tgz#5a350da0b1113b837ecfffd5812cbe58d6eae193" - integrity sha1-WjUNoLERO4N+z//VgSy+WNbq4ZM= +lodash.mergewith@^4.6.2: + version "4.6.2" + resolved "https://registry.yarnpkg.com/lodash.mergewith/-/lodash.mergewith-4.6.2.tgz#617121f89ac55f59047c7aec1ccd6654c6590f55" + integrity sha512-GK3g5RPZWTRSeLSpgP8Xhra+pnjBC56q9FZYe1d5RN3TJ35dbkGy3YqBSMbyCrlbi+CM9Z3Jk5yTL7RCsqboyQ== + +lodash.snakecase@^4.1.1: + version "4.1.1" + resolved "https://registry.yarnpkg.com/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz#39d714a35357147837aefd64b5dcbb16becd8f8d" + integrity sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw== + +lodash.startcase@^4.4.0: + version "4.4.0" + resolved "https://registry.yarnpkg.com/lodash.startcase/-/lodash.startcase-4.4.0.tgz#9436e34ed26093ed7ffae1936144350915d9add8" + integrity sha512-+WKqsK294HMSc2jEbNgpHpd0JfIBhp7rEV4aqXWqFr6AlXov+SlcgB1Fv01y2kGe3Gc8nMW7VA0SrGuSkRfIEg== + +lodash.uniq@^4.5.0: + version "4.5.0" + resolved "https://registry.yarnpkg.com/lodash.uniq/-/lodash.uniq-4.5.0.tgz#d0225373aeb652adc1bc82e4945339a842754773" + integrity sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ== lodash.uniqby@^4.7.0: version "4.7.0" resolved "https://registry.yarnpkg.com/lodash.uniqby/-/lodash.uniqby-4.7.0.tgz#d99c07a669e9e6d24e1362dfe266c67616af1302" integrity sha512-e/zcLx6CSbmaEgFHCA7BnoQKyCtKMxnuWrJygbwPs/AIn+IMKl66L8/s+wBUn5LRw2pZx3bUHibiV1b6aTWIww== -lodash@^4.1.2, lodash@^4.17.15, lodash@^4.17.20, lodash@^4.17.21, lodash@^4.17.4: +lodash.upperfirst@^4.3.1: + version "4.3.1" + resolved "https://registry.yarnpkg.com/lodash.upperfirst/-/lodash.upperfirst-4.3.1.tgz#1365edf431480481ef0d1c68957a5ed99d49f7ce" + integrity sha512-sReKOYJIJf74dhJONhU4e0/shzi1trVbSWDOhKYE5XV2O+H7Sb2Dihwuc7xWxVl+DgFPyTqIN3zMfT9cq5iWDg== + +lodash@4.17.21, lodash@^4.17.15, lodash@^4.17.21, lodash@^4.17.4: version "4.17.21" resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.21.tgz#679591c564c3bffaae8454cf0b3df370c3d6911c" integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg== -log-update@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/log-update/-/log-update-4.0.0.tgz#589ecd352471f2a1c0c570287543a64dfd20e0a1" - integrity sha512-9fkkDevMefjg0mmzWFBW8YkFP91OrizzkW3diF7CpG+S2EYdy4+TVfGwz1zeF8x7hCx1ovSPTOE9Ngib74qqUg== +log-symbols@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-4.1.0.tgz#3fbdbb95b4683ac9fc785111e792e558d4abd503" + integrity sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg== dependencies: - ansi-escapes "^4.3.0" - cli-cursor "^3.1.0" - slice-ansi "^4.0.0" - wrap-ansi "^6.2.0" + chalk "^4.1.0" + is-unicode-supported "^0.1.0" -lower-case@^2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/lower-case/-/lower-case-2.0.2.tgz#6fa237c63dbdc4a82ca0fd882e4722dc5e634e28" - integrity sha512-7fm3l3NAF9WfN6W3JOmf5drwpVqX78JtoGJ3A6W0a6ZnldM41w2fV5D490psKFTpMds8TJse/eHLFFsNHHjHgg== +log-update@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/log-update/-/log-update-6.0.0.tgz#0ddeb7ac6ad658c944c1de902993fce7c33f5e59" + integrity sha512-niTvB4gqvtof056rRIrTZvjNYE4rCUzO6X/X+kYjd7WFxXeJ0NwEFnRxX6ehkvv3jTwrXnNdtAak5XYZuIyPFw== dependencies: - tslib "^2.0.3" + ansi-escapes "^6.2.0" + cli-cursor "^4.0.0" + slice-ansi "^7.0.0" + strip-ansi "^7.1.0" + wrap-ansi "^9.0.0" + +longest@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/longest/-/longest-2.0.1.tgz#781e183296aa94f6d4d916dc335d0d17aefa23f8" + integrity sha512-Ajzxb8CM6WAnFjgiloPsI3bF+WCxcvhdIG3KNA2KN962+tdBsHcuQ4k4qX/EcS/2CRkcc0iAkR956Nib6aXU/Q== + +lru-cache@^10.0.1, "lru-cache@^9.1.1 || ^10.0.0": + version "10.2.0" + resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-10.2.0.tgz#0bd445ca57363465900f4d1f9bd8db343a4d95c3" + integrity sha512-2bIM8x+VAf6JT4bKAljS1qUWgMsqZRPGJS6FSahIMPVvctcNhyVp7AJu7quxOW9jwkryBReKZY5tY5JYv2n/7Q== lru-cache@^5.1.1: version "5.1.1" @@ -5113,15 +5770,15 @@ lru-cache@^6.0.0: dependencies: yallist "^4.0.0" -lru-cache@^7.4.4, lru-cache@^7.5.1, lru-cache@^7.7.1: - version "7.16.1" - resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-7.16.1.tgz#7acea16fecd9ed11430e78443c2bb81a06d3dea9" - integrity sha512-9kkuMZHnLH/8qXARvYSjNvq8S1GYFFzynQTAfKeaJ0sIrR3PUPuu37Z+EiIANiZBvpfTf2B5y8ecDLSMWlLv+w== +lru-cache@^7.14.1: + version "7.18.3" + resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-7.18.3.tgz#f793896e0fd0e954a59dfdd82f0773808df6aa89" + integrity sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA== -lunr@^2.3.9: - version "2.3.9" - resolved "https://registry.yarnpkg.com/lunr/-/lunr-2.3.9.tgz#18b123142832337dd6e964df1a5a7707b25d35e1" - integrity sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow== +lru-cache@^7.4.4, lru-cache@^7.5.1, lru-cache@^7.7.1: + version "7.16.0" + resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-7.16.0.tgz#b1b946cff368d3f3c569cc3d6a5ba8f90435160f" + integrity sha512-VJBdeMa9Bz27NNlx+DI/YXGQtXdjUU+9gdfN1rYfra7vtTjhodl5tVNmR42bo+ORHuDqDT+lGAUAb+lzvY42Bw== make-dir@^3.0.0: version "3.1.0" @@ -5130,12 +5787,12 @@ make-dir@^3.0.0: dependencies: semver "^6.0.0" -make-error@1.x: +make-error@1.x, make-error@^1.1.1: version "1.3.6" resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.6.tgz#2eb2e37ea9b67c4891f684a1394799af484cf7a2" integrity sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw== -make-fetch-happen@^10.0.3, make-fetch-happen@^10.0.6, make-fetch-happen@^10.2.0: +make-fetch-happen@^10.0.3: version "10.2.1" resolved "https://registry.yarnpkg.com/make-fetch-happen/-/make-fetch-happen-10.2.1.tgz#f5e3835c5e9817b617f2770870d9492d28678164" integrity sha512-NgOPbRiaQM10DYXvN3/hhGVI2M5MtITFryzBGxHM5p4wnFxsVCbxkrBrDsk+EZ5OB4jEOT7AjDxtdF+KVEFT7w== @@ -5157,6 +5814,44 @@ make-fetch-happen@^10.0.3, make-fetch-happen@^10.0.6, make-fetch-happen@^10.2.0: socks-proxy-agent "^7.0.0" ssri "^9.0.0" +make-fetch-happen@^11.0.0, make-fetch-happen@^11.0.1, make-fetch-happen@^11.0.3: + version "11.0.3" + resolved "https://registry.yarnpkg.com/make-fetch-happen/-/make-fetch-happen-11.0.3.tgz#ed83dd3685b97f75607156d2721848f6eca561b9" + integrity sha512-oPLh5m10lRNNZDjJ2kP8UpboUx2uFXVaVweVe/lWut4iHWcQEmfqSVJt2ihZsFI8HbpwyyocaXbCAWf0g1ukIA== + dependencies: + agentkeepalive "^4.2.1" + cacache "^17.0.0" + http-cache-semantics "^4.1.1" + http-proxy-agent "^5.0.0" + https-proxy-agent "^5.0.0" + is-lambda "^1.0.1" + lru-cache "^7.7.1" + minipass "^4.0.0" + minipass-fetch "^3.0.0" + minipass-flush "^1.0.5" + minipass-pipeline "^1.2.4" + negotiator "^0.6.3" + promise-retry "^2.0.1" + socks-proxy-agent "^7.0.0" + ssri "^10.0.0" + +make-fetch-happen@^13.0.0: + version "13.0.0" + resolved "https://registry.yarnpkg.com/make-fetch-happen/-/make-fetch-happen-13.0.0.tgz#705d6f6cbd7faecb8eac2432f551e49475bfedf0" + integrity sha512-7ThobcL8brtGo9CavByQrQi+23aIfgYU++wg4B87AIS8Rb2ZBt/MEaDqzA00Xwv/jUjAjYkLHjVolYuTLKda2A== + dependencies: + "@npmcli/agent" "^2.0.0" + cacache "^18.0.0" + http-cache-semantics "^4.1.1" + is-lambda "^1.0.1" + minipass "^7.0.2" + minipass-fetch "^3.0.0" + minipass-flush "^1.0.5" + minipass-pipeline "^1.2.4" + negotiator "^0.6.3" + promise-retry "^2.0.1" + ssri "^10.0.0" + makeerror@1.0.12: version "1.0.12" resolved "https://registry.yarnpkg.com/makeerror/-/makeerror-1.0.12.tgz#3e5dd2079a82e812e983cc6610c4a2cb0eaa801a" @@ -5174,7 +5869,7 @@ map-obj@^4.0.0: resolved "https://registry.yarnpkg.com/map-obj/-/map-obj-4.3.0.tgz#9304f906e93faae70880da102a9f1df0ea8bb05a" integrity sha512-hdN1wVrZbb29eBGiGjJbeP8JbKjq1urkHJ/LIP/NY48MZ1QVXUsQBV1G1zvYFHn1XE06cwjBsOI2K3Ulnj1YXQ== -marked-terminal@^5.0.0: +marked-terminal@^5.1.1: version "5.1.1" resolved "https://registry.yarnpkg.com/marked-terminal/-/marked-terminal-5.1.1.tgz#d2edc2991841d893ee943b44b40b2ee9518b4d9f" integrity sha512-+cKTOx9P4l7HwINYhzbrBSyzgxO2HaHKGZGuB1orZsMIgXYaJyfidT81VXRdpelW/PcHEWxywscePVgI/oUF6g== @@ -5186,21 +5881,17 @@ marked-terminal@^5.0.0: node-emoji "^1.11.0" supports-hyperlinks "^2.2.0" -marked@^4.0.10, marked@^4.2.12: +marked@^4.1.0: version "4.2.12" resolved "https://registry.yarnpkg.com/marked/-/marked-4.2.12.tgz#d69a64e21d71b06250da995dcd065c11083bebb5" integrity sha512-yr8hSKa3Fv4D3jdZmtMMPghgVt6TWbk86WQaWhDloQjRSQhMMYCAro7jP7VDJrjjdV8pxVxMssXS8B8Y5DZ5aw== -md5.js@^1.3.4: - version "1.3.5" - resolved "https://registry.yarnpkg.com/md5.js/-/md5.js-1.3.5.tgz#b5d07b8e3216e3e27cd728d72f70d1e6a342005f" - integrity sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg== - dependencies: - hash-base "^3.0.0" - inherits "^2.0.1" - safe-buffer "^5.1.2" +meow@^12.0.1: + version "12.1.1" + resolved "https://registry.yarnpkg.com/meow/-/meow-12.1.1.tgz#e558dddbab12477b69b2e9a2728c327f191bace6" + integrity sha512-BhXM0Au22RwUneMPwSCnyhTOizdWoIEPU9sp0Aqa1PnDMR5Wv2FGXYDjuzJEIX+Eo2Rb8xuYe5jrnm5QowQFkw== -meow@^8.0.0: +meow@^8.0.0, meow@^8.1.2: version "8.1.2" resolved "https://registry.yarnpkg.com/meow/-/meow-8.1.2.tgz#bcbe45bda0ee1729d350c03cffc8395a36c4e897" integrity sha512-r85E3NdZ+mpYk1C6RjPFEMSE+s1iZMuHtsHAqY0DT3jZczl0diWUZ8g6oU7h0M9cD2EL+PzaYghhCLzR0ZNn5Q== @@ -5227,7 +5918,30 @@ merge2@^1.3.0, merge2@^1.4.1: resolved "https://registry.yarnpkg.com/merge2/-/merge2-1.4.1.tgz#4368892f885e907455a6fd7dc55c0c9d404990ae" integrity sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg== -micromatch@^4.0.0, micromatch@^4.0.2, micromatch@^4.0.4, micromatch@^4.0.5: +merge@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/merge/-/merge-2.1.1.tgz#59ef4bf7e0b3e879186436e8481c06a6c162ca98" + integrity sha512-jz+Cfrg9GWOZbQAnDQ4hlVnQky+341Yk5ru8bZSe6sIDTCIg8n9i/u7hSQGSVOF3C7lH6mGtqjkiT9G4wFLL0w== + +micro-eth-signer@0.7.2: + version "0.7.2" + resolved "https://registry.yarnpkg.com/micro-eth-signer/-/micro-eth-signer-0.7.2.tgz#e07b6524ce47a75d80752eaba69823396529b2a2" + integrity sha512-uFH23nqPNdg2KZ9ZdvLG4GO3bTAOWRhwGTsecY4Et2IdQOJ26x6inu8lJ9oyslnYL/0o1vnETCGhMimMvO0SqQ== + dependencies: + "@ethereumjs/rlp" "5.0.0" + "@noble/curves" "~1.3.0" + "@noble/hashes" "~1.3.3" + "@scure/base" "~1.1.5" + micro-packed "~0.5.1" + +micro-packed@~0.5.1: + version "0.5.1" + resolved "https://registry.yarnpkg.com/micro-packed/-/micro-packed-0.5.1.tgz#871965e69b9e34372226972031b22208f6f80145" + integrity sha512-VjBHcsMAVfivjCZPnqAEEkcihPBbNd39KLEMH76ksL3ORKSZE04gkrtsAmXtaTor67PmTO5h0Rq9+j3PA4zNrw== + dependencies: + "@scure/base" "~1.1.5" + +micromatch@4.0.5, micromatch@^4.0.0, micromatch@^4.0.2, micromatch@^4.0.4: version "4.0.5" resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.5.tgz#bc8999a7cbbf77cdc89f132f6e467051b49090c6" integrity sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA== @@ -5235,31 +5949,16 @@ micromatch@^4.0.0, micromatch@^4.0.2, micromatch@^4.0.4, micromatch@^4.0.5: braces "^3.0.2" picomatch "^2.3.1" -miller-rabin@^4.0.0: - version "4.0.1" - resolved "https://registry.yarnpkg.com/miller-rabin/-/miller-rabin-4.0.1.tgz#f080351c865b0dc562a8462966daa53543c78a4d" - integrity sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA== - dependencies: - bn.js "^4.0.0" - brorand "^1.0.1" - -mime-db@1.52.0: - version "1.52.0" - resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.52.0.tgz#bbabcdc02859f4987301c856e3387ce5ec43bf70" - integrity sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg== - -mime-types@^2.1.12, mime-types@^2.1.27: - version "2.1.35" - resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.35.tgz#381a871b62a734450660ae3deee44813f70d959a" - integrity sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw== - dependencies: - mime-db "1.52.0" - mime@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/mime/-/mime-3.0.0.tgz#b374550dca3a0c18443b0c950a6a58f1931cf7a7" integrity sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A== +mime@^4.0.0: + version "4.0.1" + resolved "https://registry.yarnpkg.com/mime/-/mime-4.0.1.tgz#ad7563d1bfe30253ad97dedfae2b1009d01b9470" + integrity sha512-5lZ5tyrIfliMXzFtkYyekWbtRXObT9OWa8IwQ5uxTBDHucNNwniRqo0yInflj+iYi5CBa6qxadGzGarDfuEOxA== + mimic-fn@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-2.1.0.tgz#7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b" @@ -5275,34 +5974,45 @@ min-indent@^1.0.0: resolved "https://registry.yarnpkg.com/min-indent/-/min-indent-1.0.1.tgz#a63f681673b30571fbe8bc25686ae746eefa9869" integrity sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg== -minimalistic-assert@^1.0.0, minimalistic-assert@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz#2e194de044626d4a10e7f7fbc00ce73e83e4d5c7" - integrity sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A== - -minimalistic-crypto-utils@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz#f6c00c1c0b082246e5c4d99dfb8c7c083b2b582a" - integrity sha1-9sAMHAsIIkblxNmd+4x8CDsrWCo= +minimatch@9.0.3, minimatch@^9.0.0, minimatch@^9.0.1, minimatch@^9.0.3: + version "9.0.3" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-9.0.3.tgz#a6e00c3de44c3a542bfaae70abfc22420a6da825" + integrity sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg== + dependencies: + brace-expansion "^2.0.1" -minimatch@^3.0.4: +minimatch@^3.0.4, minimatch@^3.0.5, minimatch@^3.1.1, minimatch@^3.1.2: version "3.1.2" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.2.tgz#19cd194bfd3e428f049a70817c038d89ab4be35b" integrity sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw== dependencies: brace-expansion "^1.1.7" -minimatch@^5.0.1, minimatch@^5.1.0: +minimatch@^5.0.1: version "5.1.6" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-5.1.6.tgz#1cfcb8cf5522ea69952cd2af95ae09477f122a96" integrity sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g== dependencies: brace-expansion "^2.0.1" -minimatch@^7.1.3: - version "7.3.0" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-7.3.0.tgz#cfb7337e7460308e7147c58250fa0dee3da7929c" - integrity sha512-WaMDuhKa7a6zKiwplR1AOz+zGvJba24k5VU1Cy6NhEguavT2YRlHxuINUgTas4wiS6fwBpYq4TcA1XIECSntyw== +minimatch@^6.1.0, minimatch@^6.1.6: + version "6.2.0" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-6.2.0.tgz#2b70fd13294178c69c04dfc05aebdb97a4e79e42" + integrity sha512-sauLxniAmvnhhRjFwPNnJKaPFYyddAgbYdeUpHULtCT/GhzdCx/MDNy+Y40lBxTQUrMzDE8e0S43Z5uqfO0REg== + dependencies: + brace-expansion "^2.0.1" + +minimatch@^7.4.2, minimatch@^7.4.3: + version "7.4.5" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-7.4.5.tgz#e721f2a6faba6846f3b891ccff9966dcf728813e" + integrity sha512-OzOamaOmNBJZUv2qqY1OSWa+++4YPpOkLgkc0w30Oov5ufKlWWXnFUl0l4dgmSv5Shq/zRVkEOXAe2NaqO4l5Q== + dependencies: + brace-expansion "^2.0.1" + +minimatch@^8.0.2: + version "8.0.3" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-8.0.3.tgz#0415cb9bb0c1d8ac758c8a673eb1d288e13f5e75" + integrity sha512-tEEvU9TkZgnFDCtpnrEYnPsjT7iUx42aXfs4bzmQ5sMA09/6hZY0jeZcGkXyDagiBOvkUjNo8Viom+Me6+2x7g== dependencies: brace-expansion "^2.0.1" @@ -5315,16 +6025,16 @@ minimist-options@4.1.0: is-plain-obj "^1.1.0" kind-of "^6.0.3" -minimist@^1.2.0: +minimist@1.2.7: + version "1.2.7" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.7.tgz#daa1c4d91f507390437c6a8bc01078e7000c4d18" + integrity sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g== + +minimist@^1.2.0, minimist@^1.2.5, minimist@^1.2.6: version "1.2.8" resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.8.tgz#c1a464e7693302e082a075cee0c057741ac4772c" integrity sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA== -minimist@^1.2.5: - version "1.2.6" - resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.6.tgz#8637a5b759ea0d6e98702cfb3a9283323c93af44" - integrity sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q== - minipass-collect@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/minipass-collect/-/minipass-collect-1.0.2.tgz#22b813bf745dc6edba2576b940022ad6edc8c617" @@ -5332,6 +6042,13 @@ minipass-collect@^1.0.2: dependencies: minipass "^3.0.0" +minipass-collect@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/minipass-collect/-/minipass-collect-2.0.1.tgz#1621bc77e12258a12c60d34e2276ec5c20680863" + integrity sha512-D7V8PO9oaz7PWGLbCACuI1qEOsq7UKfLotx/C0Aet43fCUB/wfQ7DYeq2oR/svFJGYDHPr38SHATeaj/ZoKHKw== + dependencies: + minipass "^7.0.3" + minipass-fetch@^2.0.3: version "2.1.2" resolved "https://registry.yarnpkg.com/minipass-fetch/-/minipass-fetch-2.1.2.tgz#95560b50c472d81a3bc76f20ede80eaed76d8add" @@ -5343,6 +6060,17 @@ minipass-fetch@^2.0.3: optionalDependencies: encoding "^0.1.13" +minipass-fetch@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/minipass-fetch/-/minipass-fetch-3.0.1.tgz#bae3789f668d82ffae3ea47edc6b78b8283b3656" + integrity sha512-t9/wowtf7DYkwz8cfMSt0rMwiyNIBXf5CKZ3S5ZMqRqMYT0oLTp0x1WorMI9WTwvaPg21r1JbFxJMum8JrLGfw== + dependencies: + minipass "^4.0.0" + minipass-sized "^1.0.3" + minizlib "^2.1.2" + optionalDependencies: + encoding "^0.1.13" + minipass-flush@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/minipass-flush/-/minipass-flush-1.0.5.tgz#82e7135d7e89a50ffe64610a787953c4c4cbb373" @@ -5384,6 +6112,21 @@ minipass@^4.0.0: resolved "https://registry.yarnpkg.com/minipass/-/minipass-4.0.3.tgz#00bfbaf1e16e35e804f4aa31a7c1f6b8d9f0ee72" integrity sha512-OW2r4sQ0sI+z5ckEt5c1Tri4xTgZwYDxpE54eqWlQloQRoWtXjqt9udJ5Z4dSv7wK+nfFI7FRXyCpBSft+gpFw== +minipass@^4.0.2, minipass@^4.2.4, minipass@^4.2.5: + version "4.2.5" + resolved "https://registry.yarnpkg.com/minipass/-/minipass-4.2.5.tgz#9e0e5256f1e3513f8c34691dd68549e85b2c8ceb" + integrity sha512-+yQl7SX3bIT83Lhb4BVorMAHVuqsskxRdlmO9kTpyukp8vsm2Sn/fUOV9xlnG8/a5JsypJzap21lz/y3FBMJ8Q== + +minipass@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/minipass/-/minipass-5.0.0.tgz#3e9788ffb90b694a5d0ec94479a45b5d8738133d" + integrity sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ== + +"minipass@^5.0.0 || ^6.0.2 || ^7.0.0", minipass@^7.0.2, minipass@^7.0.3, minipass@^7.0.4: + version "7.0.4" + resolved "https://registry.yarnpkg.com/minipass/-/minipass-7.0.4.tgz#dbce03740f50a4786ba994c1fb908844d27b038c" + integrity sha512-jYofLM5Dam9279rdkWzqHozUo4ybjdZmCsDHePy5V/PbBcVMiSZR97gmAy45aqi8CK1lG2ECd356FU86avfwUQ== + minizlib@^2.1.1, minizlib@^2.1.2: version "2.1.2" resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-2.1.2.tgz#e90d3466ba209b932451508a11ce3d3632145931" @@ -5392,15 +6135,6 @@ minizlib@^2.1.1, minizlib@^2.1.2: minipass "^3.0.0" yallist "^4.0.0" -mkdirp-infer-owner@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/mkdirp-infer-owner/-/mkdirp-infer-owner-2.0.0.tgz#55d3b368e7d89065c38f32fd38e638f0ab61d316" - integrity sha512-sdqtiFt3lkOaYvTXSRIUjkIdPTcxgv5+fgqYE/5qgwdw12cOrAuzzgzvVExIkH/ul1oeHN3bCLOWSG3XOqbKKw== - dependencies: - chownr "^2.0.0" - infer-owner "^1.0.4" - mkdirp "^1.0.3" - mkdirp@^1.0.3, mkdirp@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e" @@ -5421,27 +6155,27 @@ ms@^2.0.0, ms@^2.1.2: resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== -mute-stream@~0.0.4: +mute-stream@0.0.8: version "0.0.8" resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-0.0.8.tgz#1630c42b2251ff81e2a283de96a5497ea92e5e0d" integrity sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA== -natural-compare-lite@^1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/natural-compare-lite/-/natural-compare-lite-1.4.0.tgz#17b09581988979fddafe0201e931ba933c96cbb4" - integrity sha512-Tj+HTDSJJKaZnfiuw+iaF9skdPpTo2GtEly5JHnWV/hfv2Qj/9RKsGISQtLh2ox3l5EAGw487hnBee0sIJ6v2g== +mute-stream@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-1.0.0.tgz#e31bd9fe62f0aed23520aa4324ea6671531e013e" + integrity sha512-avsJQhyd+680gKXyG/sQc0nXaC6rBkPOfyHYcFb9+hdkqQkR9bdnkJ0AMZhke0oesPqIO+mFFJ+IdBc7mst4IA== natural-compare@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" - integrity sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc= + integrity sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw== negotiator@^0.6.3: version "0.6.3" resolved "https://registry.yarnpkg.com/negotiator/-/negotiator-0.6.3.tgz#58e323a72fedc0d6f9cd4d31fe49f51479590ccd" integrity sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg== -neo-async@^2.6.0, neo-async@^2.6.2: +neo-async@^2.6.0: version "2.6.2" resolved "https://registry.yarnpkg.com/neo-async/-/neo-async-2.6.2.tgz#b4aafb93e3aeb2d8174ca53cf163ab7d7308305f" integrity sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw== @@ -5449,20 +6183,12 @@ neo-async@^2.6.0, neo-async@^2.6.2: nerf-dart@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/nerf-dart/-/nerf-dart-1.0.0.tgz#e6dab7febf5ad816ea81cf5c629c5a0ebde72c1a" - integrity sha512-EZSPZB70jiVsivaBLYDCyntd5eH8NTSMOn3rB+HxwdmKThGELLdYv8qVIMWvZEFy9w8ZZpW9h9OB32l1rGtj7g== - -no-case@^3.0.4: - version "3.0.4" - resolved "https://registry.yarnpkg.com/no-case/-/no-case-3.0.4.tgz#d361fd5c9800f558551a8369fc0dcd4662b6124d" - integrity sha512-fgAN3jGAh+RoxUGZHTSOLJIqUc2wmoBwGR4tbpNAKmmovFoWq0OdRkb0VkldReO2a2iBT/OEulG9XSUc10r3zg== - dependencies: - lower-case "^2.0.2" - tslib "^2.0.3" + integrity sha512-EZSPZB70jiVsivaBLYDCyntd5eH8NTSMOn3rB+HxwdmKThGELLdYv8qVIMWvZEFy9w8ZZpW9h9OB32l1rGtj7g== -node-addon-api@^2.0.0: - version "2.0.2" - resolved "https://registry.yarnpkg.com/node-addon-api/-/node-addon-api-2.0.2.tgz#432cfa82962ce494b132e9d72a15b29f71ff5d32" - integrity sha512-Ntyt4AIXyaLIuMHF6IOoTakB3K+RWxwtsHNRxllEoA6vPwP9o4866g6YWDLUdnucilZhmkxiHwHr11gAENw+QA== +node-domexception@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/node-domexception/-/node-domexception-1.0.0.tgz#6888db46a1f71c0b76b3f7555016b63fe64766e5" + integrity sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ== node-emoji@^1.11.0: version "1.11.0" @@ -5471,6 +6197,15 @@ node-emoji@^1.11.0: dependencies: lodash "^4.17.21" +node-fetch@3.3.2: + version "3.3.2" + resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-3.3.2.tgz#d1e889bacdf733b4ff3b2b243eb7a12866a0b78b" + integrity sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA== + dependencies: + data-uri-to-buffer "^4.0.0" + fetch-blob "^3.1.4" + formdata-polyfill "^4.0.10" + node-fetch@^2.6.7: version "2.6.9" resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.9.tgz#7c7f744b5cc6eb5fd404e0c7a9fec630a55657e6" @@ -5478,12 +6213,23 @@ node-fetch@^2.6.7: dependencies: whatwg-url "^5.0.0" -node-gyp-build@^4.2.0: - version "4.4.0" - resolved "https://registry.yarnpkg.com/node-gyp-build/-/node-gyp-build-4.4.0.tgz#42e99687ce87ddeaf3a10b99dc06abc11021f3f4" - integrity sha512-amJnQCcgtRVw9SvoebO3BKGESClrfXGCUTX9hSn1OuGQTQBOZmVd0Z0OlecpuRksKvbsUqALE8jls/ErClAPuQ== +node-gyp@^10.0.0, node-gyp@^10.0.1: + version "10.0.1" + resolved "https://registry.yarnpkg.com/node-gyp/-/node-gyp-10.0.1.tgz#205514fc19e5830fa991e4a689f9e81af377a966" + integrity sha512-gg3/bHehQfZivQVfqIyy8wTdSymF9yTyP4CJifK73imyNMU8AIGQE2pUa7dNWfmMeG9cDVF2eehiRMv0LC1iAg== + dependencies: + env-paths "^2.2.0" + exponential-backoff "^3.1.1" + glob "^10.3.10" + graceful-fs "^4.2.6" + make-fetch-happen "^13.0.0" + nopt "^7.0.0" + proc-log "^3.0.0" + semver "^7.3.5" + tar "^6.1.2" + which "^4.0.0" -node-gyp@^9.0.0, node-gyp@^9.1.0: +node-gyp@^9.0.0, node-gyp@^9.3.1: version "9.3.1" resolved "https://registry.yarnpkg.com/node-gyp/-/node-gyp-9.3.1.tgz#1e19f5f290afcc9c46973d68700cbd21a96192e4" integrity sha512-4Q16ZCqq3g8awk6UplT7AuxQ35XN4R/yf/+wSAwcBUAjg7l58RTactWaP8fIDTi0FzI7YcVLujwExakZlfWkXg== @@ -5502,12 +6248,7 @@ node-gyp@^9.0.0, node-gyp@^9.1.0: node-int64@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/node-int64/-/node-int64-0.4.0.tgz#87a9065cdb355d3182d8f94ce11188b825c68a3b" - integrity sha1-h6kGXNs1XTGC2PlM4RGIuCXGijs= - -node-releases@^2.0.3: - version "2.0.4" - resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.4.tgz#f38252370c43854dc48aa431c766c6c398f40476" - integrity sha512-gbMzqQtTtDz/00jQzZ21PQzdI9PyLYqUSvD0p3naOhX4odFji0ZxYdnVwPTxmSwkmxhcFImpozceidSG+AgoPQ== + integrity sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw== node-releases@^2.0.8: version "2.0.10" @@ -5521,6 +6262,20 @@ nopt@^6.0.0: dependencies: abbrev "^1.0.0" +nopt@^7.0.0, nopt@^7.1.0: + version "7.1.0" + resolved "https://registry.yarnpkg.com/nopt/-/nopt-7.1.0.tgz#91f6a3366182176e72ecab93a09c19b63b485f28" + integrity sha512-ZFPLe9Iu0tnx7oWhFxAo4s7QTn8+NNDDxYNaKLjE7Dp0tbakQ3M1QhQzsnzXHQBTUO3K9BmwaxnyO8Ayn2I95Q== + dependencies: + abbrev "^2.0.0" + +nopt@^7.2.0: + version "7.2.0" + resolved "https://registry.yarnpkg.com/nopt/-/nopt-7.2.0.tgz#067378c68116f602f552876194fd11f1292503d7" + integrity sha512-CVDtwCdhYIvnAzFoJ6NJ6dX3oga9/HyciQDnG1vQDjSLMeKLJ4A93ZqYKDrgYSr1FBY5/hMYC+2VCi24pgpkGA== + dependencies: + abbrev "^2.0.0" + normalize-package-data@^2.5.0: version "2.5.0" resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.5.0.tgz#e66db1838b200c1dfc233225d12cb36520e234a8" @@ -5531,7 +6286,7 @@ normalize-package-data@^2.5.0: semver "2 || 3 || 4 || 5" validate-npm-package-license "^3.0.1" -normalize-package-data@^3.0.0: +normalize-package-data@^3.0.0, normalize-package-data@^3.0.2: version "3.0.3" resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-3.0.3.tgz#dbcc3e2da59509a0983422884cd172eefdfa525e" integrity sha512-p2W1sgqij3zMMyRC067Dg16bfzVH+w7hyegmpIvZ4JNjqtGOVAIvLmjBx3yP7YTe9vKJgkoNOPjwQGogDoMXFA== @@ -5541,12 +6296,22 @@ normalize-package-data@^3.0.0: semver "^7.3.4" validate-npm-package-license "^3.0.1" -normalize-package-data@^4.0.0: - version "4.0.1" - resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-4.0.1.tgz#b46b24e0616d06cadf9d5718b29b6d445a82a62c" - integrity sha512-EBk5QKKuocMJhB3BILuKhmaPjI8vNRSpIfO9woLC6NyHVkKKdVEdAO1mrT0ZfxNR1lKwCcTkuZfmGIFdizZ8Pg== +normalize-package-data@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-5.0.0.tgz#abcb8d7e724c40d88462b84982f7cbf6859b4588" + integrity sha512-h9iPVIfrVZ9wVYQnxFgtw1ugSvGEMOlyPWWtm8BMJhnwyEL/FLbYbTY3V3PpjI/BUK67n9PEWDu6eHzu1fB15Q== + dependencies: + hosted-git-info "^6.0.0" + is-core-module "^2.8.1" + semver "^7.3.5" + validate-npm-package-license "^3.0.4" + +normalize-package-data@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-6.0.0.tgz#68a96b3c11edd462af7189c837b6b1064a484196" + integrity sha512-UL7ELRVxYBHBgYEtZCXjxuD5vPxnmvMGq0jp/dGPKKrN7tfsBh2IY7TlJ15WWwdjRWD3RJbnsygUurTK3xkPkg== dependencies: - hosted-git-info "^5.0.0" + hosted-git-info "^7.0.0" is-core-module "^2.8.1" semver "^7.3.5" validate-npm-package-license "^3.0.4" @@ -5556,99 +6321,151 @@ normalize-path@^3.0.0: resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== -normalize-url@^6.0.0: - version "6.1.0" - resolved "https://registry.yarnpkg.com/normalize-url/-/normalize-url-6.1.0.tgz#40d0885b535deffe3f3147bec877d05fe4c5668a" - integrity sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A== +normalize-url@^8.0.0: + version "8.0.0" + resolved "https://registry.yarnpkg.com/normalize-url/-/normalize-url-8.0.0.tgz#593dbd284f743e8dcf6a5ddf8fadff149c82701a" + integrity sha512-uVFpKhj5MheNBJRTiMZ9pE/7hD1QTeEvugSJW/OmLzAp78PB5O6adfMNTvmfKhXBkvCzC+rqifWcVYpGFwTjnw== -npm-audit-report@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/npm-audit-report/-/npm-audit-report-3.0.0.tgz#1bf3e531208b5f77347c8d00c3d9badf5be30cd6" - integrity sha512-tWQzfbwz1sc4244Bx2BVELw0EmZlCsCF0X93RDcmmwhonCsPMoEviYsi+32R+mdRvOWXolPce9zo64n2xgPESw== +npm-audit-report@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/npm-audit-report/-/npm-audit-report-4.0.0.tgz#dfffdb6464a7799d3d30e067ae1943982cf45f69" + integrity sha512-k2o5476sLrp94b6Gl819YzlS7LAdb8lgE6yQCysBEji5E3WoUdRve6tiVMLKAPPdLfItU4kOSUycWS5HFTrbug== dependencies: chalk "^4.0.0" -npm-bundled@^1.1.1: - version "1.1.2" - resolved "https://registry.yarnpkg.com/npm-bundled/-/npm-bundled-1.1.2.tgz#944c78789bd739035b70baa2ca5cc32b8d860bc1" - integrity sha512-x5DHup0SuyQcmL3s7Rx/YQ8sbw/Hzg0rj48eN0dV7hf5cmQq5PXIeioroH3raV1QC1yh3uTYuMThvEQF3iKgGQ== +npm-audit-report@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/npm-audit-report/-/npm-audit-report-5.0.0.tgz#83ac14aeff249484bde81eff53c3771d5048cf95" + integrity sha512-EkXrzat7zERmUhHaoren1YhTxFwsOu5jypE84k6632SXTHcQE1z8V51GC6GVZt8LxkC+tbBcKMUBZAgk8SUSbw== + +npm-bundled@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/npm-bundled/-/npm-bundled-3.0.0.tgz#7e8e2f8bb26b794265028491be60321a25a39db7" + integrity sha512-Vq0eyEQy+elFpzsKjMss9kxqb9tG3YHg4dsyWuUENuzvSUWe1TCnW/vV9FkhvBk/brEDoDiVd+M1Btosa6ImdQ== dependencies: - npm-normalize-package-bin "^1.0.1" + npm-normalize-package-bin "^3.0.0" -npm-bundled@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/npm-bundled/-/npm-bundled-2.0.1.tgz#94113f7eb342cd7a67de1e789f896b04d2c600f4" - integrity sha512-gZLxXdjEzE/+mOstGDqR6b0EkhJ+kM6fxM6vUuckuctuVPh80Q6pw/rSZj9s4Gex9GxWtIicO1pc8DB9KZWudw== +npm-install-checks@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/npm-install-checks/-/npm-install-checks-6.0.0.tgz#9a021d8e8b3956d61fd265c2eda4735bcd3d9b83" + integrity sha512-SBU9oFglRVZnfElwAtF14NivyulDqF1VKqqwNsFW9HDcbHMAPHpRSsVFgKuwFGq/hVvWZExz62Th0kvxn/XE7Q== dependencies: - npm-normalize-package-bin "^2.0.0" + semver "^7.1.1" -npm-install-checks@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/npm-install-checks/-/npm-install-checks-5.0.0.tgz#5ff27d209a4e3542b8ac6b0c1db6063506248234" - integrity sha512-65lUsMI8ztHCxFz5ckCEC44DRvEGdZX5usQFriauxHEwt7upv1FKaQEmAtU0YnOAdwuNWCmk64xYiQABNrEyLA== +npm-install-checks@^6.1.0: + version "6.1.0" + resolved "https://registry.yarnpkg.com/npm-install-checks/-/npm-install-checks-6.1.0.tgz#7221210d9d746a40c37bf6c9b6c7a39f85e92998" + integrity sha512-udSGENih/5xKh3Ex+L0PtZcOt0Pa+6ppDLnpG5D49/EhMja3LupaY9E/DtJTxyFBwE09ot7Fc+H4DywnZNWTVA== dependencies: semver "^7.1.1" -npm-normalize-package-bin@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/npm-normalize-package-bin/-/npm-normalize-package-bin-1.0.1.tgz#6e79a41f23fd235c0623218228da7d9c23b8f6e2" - integrity sha512-EPfafl6JL5/rU+ot6P3gRSCpPDW5VmIzX959Ob1+ySFUuuYHWHekXpwdUZcKP5C+DS4GEtdJluwBjnsNDl+fSA== +npm-install-checks@^6.2.0, npm-install-checks@^6.3.0: + version "6.3.0" + resolved "https://registry.yarnpkg.com/npm-install-checks/-/npm-install-checks-6.3.0.tgz#046552d8920e801fa9f919cad569545d60e826fe" + integrity sha512-W29RiK/xtpCGqn6f3ixfRYGk+zRyr+Ew9F2E20BfXxT5/euLdA/Nm7fO7OeTGuAmTs30cpgInyJ0cYe708YTZw== + dependencies: + semver "^7.1.1" -npm-normalize-package-bin@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/npm-normalize-package-bin/-/npm-normalize-package-bin-2.0.0.tgz#9447a1adaaf89d8ad0abe24c6c84ad614a675fff" - integrity sha512-awzfKUO7v0FscrSpRoogyNm0sajikhBWpU0QMrW09AMi9n1PoKU6WaIqUzuJSQnpciZZmJ/jMZ2Egfmb/9LiWQ== +npm-normalize-package-bin@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/npm-normalize-package-bin/-/npm-normalize-package-bin-3.0.0.tgz#6097436adb4ef09e2628b59a7882576fe53ce485" + integrity sha512-g+DPQSkusnk7HYXr75NtzkIP4+N81i3RPsGFidF3DzHd9MT9wWngmqoeg/fnHFz5MNdtG4w03s+QnhewSLTT2Q== -npm-package-arg@^9.0.0, npm-package-arg@^9.0.1, npm-package-arg@^9.1.0: - version "9.1.2" - resolved "https://registry.yarnpkg.com/npm-package-arg/-/npm-package-arg-9.1.2.tgz#fc8acecb00235f42270dda446f36926ddd9ac2bc" - integrity sha512-pzd9rLEx4TfNJkovvlBSLGhq31gGu2QDexFPWT19yCDh0JgnRhlBLNo5759N0AJmBk+kQ9Y/hXoLnlgFD+ukmg== +npm-package-arg@^10.0.0, npm-package-arg@^10.1.0: + version "10.1.0" + resolved "https://registry.yarnpkg.com/npm-package-arg/-/npm-package-arg-10.1.0.tgz#827d1260a683806685d17193073cc152d3c7e9b1" + integrity sha512-uFyyCEmgBfZTtrKk/5xDfHp6+MdrqGotX/VoOyEEl3mBwiEE5FlBaePanazJSVMPT7vKepcjYBY2ztg9A3yPIA== dependencies: - hosted-git-info "^5.0.0" - proc-log "^2.0.1" + hosted-git-info "^6.0.0" + proc-log "^3.0.0" semver "^7.3.5" - validate-npm-package-name "^4.0.0" + validate-npm-package-name "^5.0.0" -npm-packlist@^5.1.0: - version "5.1.3" - resolved "https://registry.yarnpkg.com/npm-packlist/-/npm-packlist-5.1.3.tgz#69d253e6fd664b9058b85005905012e00e69274b" - integrity sha512-263/0NGrn32YFYi4J533qzrQ/krmmrWwhKkzwTuM4f/07ug51odoaNjUexxO4vxlzURHcmYMH1QjvHjsNDKLVg== +npm-package-arg@^11.0.0, npm-package-arg@^11.0.1: + version "11.0.1" + resolved "https://registry.yarnpkg.com/npm-package-arg/-/npm-package-arg-11.0.1.tgz#f208b0022c29240a1c532a449bdde3f0a4708ebc" + integrity sha512-M7s1BD4NxdAvBKUPqqRW957Xwcl/4Zvo8Aj+ANrzvIPzGJZElrH7Z//rSaec2ORcND6FHHLnZeY8qgTpXDMFQQ== dependencies: - glob "^8.0.1" - ignore-walk "^5.0.1" - npm-bundled "^2.0.0" - npm-normalize-package-bin "^2.0.0" + hosted-git-info "^7.0.0" + proc-log "^3.0.0" + semver "^7.3.5" + validate-npm-package-name "^5.0.0" -npm-pick-manifest@^7.0.0, npm-pick-manifest@^7.0.2: - version "7.0.2" - resolved "https://registry.yarnpkg.com/npm-pick-manifest/-/npm-pick-manifest-7.0.2.tgz#1d372b4e7ea7c6712316c0e99388a73ed3496e84" - integrity sha512-gk37SyRmlIjvTfcYl6RzDbSmS9Y4TOBXfsPnoYqTHARNgWbyDiCSMLUpmALDj4jjcTZpURiEfsSHJj9k7EV4Rw== +npm-packlist@^7.0.0: + version "7.0.4" + resolved "https://registry.yarnpkg.com/npm-packlist/-/npm-packlist-7.0.4.tgz#033bf74110eb74daf2910dc75144411999c5ff32" + integrity sha512-d6RGEuRrNS5/N84iglPivjaJPxhDbZmlbTwTDX2IbcRHG5bZCdtysYMhwiPvcF4GisXHGn7xsxv+GQ7T/02M5Q== + dependencies: + ignore-walk "^6.0.0" + +npm-packlist@^8.0.0: + version "8.0.2" + resolved "https://registry.yarnpkg.com/npm-packlist/-/npm-packlist-8.0.2.tgz#5b8d1d906d96d21c85ebbeed2cf54147477c8478" + integrity sha512-shYrPFIS/JLP4oQmAwDyk5HcyysKW8/JLTEA32S0Z5TzvpaeeX2yMFfoK1fjEBnCBvVyIB/Jj/GBFdm0wsgzbA== + dependencies: + ignore-walk "^6.0.4" + +npm-pick-manifest@^8.0.0, npm-pick-manifest@^8.0.1: + version "8.0.1" + resolved "https://registry.yarnpkg.com/npm-pick-manifest/-/npm-pick-manifest-8.0.1.tgz#c6acd97d1ad4c5dbb80eac7b386b03ffeb289e5f" + integrity sha512-mRtvlBjTsJvfCCdmPtiu2bdlx8d/KXtF7yNXNWe7G0Z36qWA9Ny5zXsI2PfBZEv7SXgoxTmNaTzGSbbzDZChoA== dependencies: - npm-install-checks "^5.0.0" - npm-normalize-package-bin "^2.0.0" - npm-package-arg "^9.0.0" + npm-install-checks "^6.0.0" + npm-normalize-package-bin "^3.0.0" + npm-package-arg "^10.0.0" semver "^7.3.5" -npm-profile@^6.2.0: - version "6.2.1" - resolved "https://registry.yarnpkg.com/npm-profile/-/npm-profile-6.2.1.tgz#975c31ec75a6ae029ab5b8820ffdcbae3a1e3d5e" - integrity sha512-Tlu13duByHyDd4Xy0PgroxzxnBYWbGGL5aZifNp8cx2DxUrHSoETXtPKg38aRPsBWMRfDtvcvVfJNasj7oImQQ== +npm-pick-manifest@^9.0.0: + version "9.0.0" + resolved "https://registry.yarnpkg.com/npm-pick-manifest/-/npm-pick-manifest-9.0.0.tgz#f87a4c134504a2c7931f2bb8733126e3c3bb7e8f" + integrity sha512-VfvRSs/b6n9ol4Qb+bDwNGUXutpy76x6MARw/XssevE0TnctIKcmklJZM5Z7nqs5z5aW+0S63pgCNbpkUNNXBg== dependencies: - npm-registry-fetch "^13.0.1" - proc-log "^2.0.0" + npm-install-checks "^6.0.0" + npm-normalize-package-bin "^3.0.0" + npm-package-arg "^11.0.0" + semver "^7.3.5" -npm-registry-fetch@^13.0.0, npm-registry-fetch@^13.0.1, npm-registry-fetch@^13.3.1: - version "13.3.1" - resolved "https://registry.yarnpkg.com/npm-registry-fetch/-/npm-registry-fetch-13.3.1.tgz#bb078b5fa6c52774116ae501ba1af2a33166af7e" - integrity sha512-eukJPi++DKRTjSBRcDZSDDsGqRK3ehbxfFUcgaRd0Yp6kRwOwh2WVn0r+8rMB4nnuzvAk6rQVzl6K5CkYOmnvw== +npm-profile@^7.0.1: + version "7.0.1" + resolved "https://registry.yarnpkg.com/npm-profile/-/npm-profile-7.0.1.tgz#a37dae08b22e662ece2c6e08946f9fcd9fdef663" + integrity sha512-VReArOY/fCx5dWL66cbJ2OMogTQAVVQA//8jjmjkarboki3V7UJ0XbGFW+khRwiAJFQjuH0Bqr/yF7Y5RZdkMQ== dependencies: - make-fetch-happen "^10.0.6" - minipass "^3.1.6" - minipass-fetch "^2.0.3" + npm-registry-fetch "^14.0.0" + proc-log "^3.0.0" + +npm-profile@^9.0.0: + version "9.0.0" + resolved "https://registry.yarnpkg.com/npm-profile/-/npm-profile-9.0.0.tgz#ffcfa4e3e1b1cb44b17c192f75b44b24b4aae645" + integrity sha512-qv43ixsJ7vndzfxD3XsPNu1Njck6dhO7q1efksTo+0DiOQysKSOsIhK/qDD1/xO2o+2jDOA4Rv/zOJ9KQFs9nw== + dependencies: + npm-registry-fetch "^16.0.0" + proc-log "^3.0.0" + +npm-registry-fetch@^14.0.0, npm-registry-fetch@^14.0.3: + version "14.0.3" + resolved "https://registry.yarnpkg.com/npm-registry-fetch/-/npm-registry-fetch-14.0.3.tgz#8545e321c2b36d2c6fe6e009e77e9f0e527f547b" + integrity sha512-YaeRbVNpnWvsGOjX2wk5s85XJ7l1qQBGAp724h8e2CZFFhMSuw9enom7K1mWVUtvXO1uUSFIAPofQK0pPN0ZcA== + dependencies: + make-fetch-happen "^11.0.0" + minipass "^4.0.0" + minipass-fetch "^3.0.0" + minipass-json-stream "^1.0.1" + minizlib "^2.1.2" + npm-package-arg "^10.0.0" + proc-log "^3.0.0" + +npm-registry-fetch@^16.0.0, npm-registry-fetch@^16.1.0: + version "16.1.0" + resolved "https://registry.yarnpkg.com/npm-registry-fetch/-/npm-registry-fetch-16.1.0.tgz#10227b7b36c97bc1cf2902a24e4f710cfe62803c" + integrity sha512-PQCELXKt8Azvxnt5Y85GseQDJJlglTFM9L9U9gkv2y4e9s0k3GVDdOx3YoB6gm2Do0hlkzC39iCGXby+Wve1Bw== + dependencies: + make-fetch-happen "^13.0.0" + minipass "^7.0.2" + minipass-fetch "^3.0.0" minipass-json-stream "^1.0.1" minizlib "^2.1.2" - npm-package-arg "^9.0.1" - proc-log "^2.0.0" + npm-package-arg "^11.0.0" + proc-log "^3.0.0" npm-run-path@^4.0.1: version "4.0.1" @@ -5664,91 +6481,160 @@ npm-run-path@^5.1.0: dependencies: path-key "^4.0.0" -npm-user-validate@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/npm-user-validate/-/npm-user-validate-1.0.1.tgz#31428fc5475fe8416023f178c0ab47935ad8c561" - integrity sha512-uQwcd/tY+h1jnEaze6cdX/LrhWhoBxfSknxentoqmIuStxUExxjWd3ULMLFPiFUrZKbOVMowH6Jq2FRWfmhcEw== +npm-user-validate@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/npm-user-validate/-/npm-user-validate-2.0.0.tgz#7b69bbbff6f7992a1d9a8968d52fd6b6db5431b6" + integrity sha512-sSWeqAYJ2dUPStJB+AEj0DyLRltr/f6YNcvCA7phkB8/RMLMnVsQ41GMwHo/ERZLYNDsyB2wPm7pZo1mqPOl7Q== -npm@^8.3.0: - version "8.19.4" - resolved "https://registry.yarnpkg.com/npm/-/npm-8.19.4.tgz#65ad6a2dfdd157a4ef4467fb86e8dcd35a43493f" - integrity sha512-3HANl8i9DKnUA89P4KEgVNN28EjSeDCmvEqbzOAuxCFDzdBZzjUl99zgnGpOUumvW5lvJo2HKcjrsc+tfyv1Hw== +npm@^10.0.0: + version "10.4.0" + resolved "https://registry.yarnpkg.com/npm/-/npm-10.4.0.tgz#904025b4d932cfaed8799e644a1c5ae7f02729fc" + integrity sha512-RS7Mx0OVfXlOcQLRePuDIYdFCVBPCNapWHplDK+mh7GDdP/Tvor4ocuybRRPSvfcRb2vjRJt1fHCqw3cr8qACQ== dependencies: "@isaacs/string-locale-compare" "^1.1.0" - "@npmcli/arborist" "^5.6.3" - "@npmcli/ci-detect" "^2.0.0" - "@npmcli/config" "^4.2.1" - "@npmcli/fs" "^2.1.0" - "@npmcli/map-workspaces" "^2.0.3" - "@npmcli/package-json" "^2.0.0" - "@npmcli/run-script" "^4.2.1" - abbrev "~1.1.1" + "@npmcli/arborist" "^7.2.1" + "@npmcli/config" "^8.0.2" + "@npmcli/fs" "^3.1.0" + "@npmcli/map-workspaces" "^3.0.4" + "@npmcli/package-json" "^5.0.0" + "@npmcli/promise-spawn" "^7.0.1" + "@npmcli/run-script" "^7.0.4" + "@sigstore/tuf" "^2.3.0" + abbrev "^2.0.0" + archy "~1.0.0" + cacache "^18.0.2" + chalk "^5.3.0" + ci-info "^4.0.0" + cli-columns "^4.0.0" + cli-table3 "^0.6.3" + columnify "^1.6.0" + fastest-levenshtein "^1.0.16" + fs-minipass "^3.0.3" + glob "^10.3.10" + graceful-fs "^4.2.11" + hosted-git-info "^7.0.1" + ini "^4.1.1" + init-package-json "^6.0.0" + is-cidr "^5.0.3" + json-parse-even-better-errors "^3.0.1" + libnpmaccess "^8.0.1" + libnpmdiff "^6.0.3" + libnpmexec "^7.0.4" + libnpmfund "^5.0.1" + libnpmhook "^10.0.0" + libnpmorg "^6.0.1" + libnpmpack "^6.0.3" + libnpmpublish "^9.0.2" + libnpmsearch "^7.0.0" + libnpmteam "^6.0.0" + libnpmversion "^5.0.1" + make-fetch-happen "^13.0.0" + minimatch "^9.0.3" + minipass "^7.0.4" + minipass-pipeline "^1.2.4" + ms "^2.1.2" + node-gyp "^10.0.1" + nopt "^7.2.0" + normalize-package-data "^6.0.0" + npm-audit-report "^5.0.0" + npm-install-checks "^6.3.0" + npm-package-arg "^11.0.1" + npm-pick-manifest "^9.0.0" + npm-profile "^9.0.0" + npm-registry-fetch "^16.1.0" + npm-user-validate "^2.0.0" + npmlog "^7.0.1" + p-map "^4.0.0" + pacote "^17.0.6" + parse-conflict-json "^3.0.1" + proc-log "^3.0.0" + qrcode-terminal "^0.12.0" + read "^2.1.0" + semver "^7.5.4" + spdx-expression-parse "^3.0.1" + ssri "^10.0.5" + supports-color "^9.4.0" + tar "^6.2.0" + text-table "~0.2.0" + tiny-relative-date "^1.3.0" + treeverse "^3.0.0" + validate-npm-package-name "^5.0.0" + which "^4.0.0" + write-file-atomic "^5.0.1" + +npm@^9.5.0: + version "9.6.3" + resolved "https://registry.yarnpkg.com/npm/-/npm-9.6.3.tgz#671355e34f4396ca7d722618996c95d3774d9fa0" + integrity sha512-KMAw6cJF5JGPJz/NtsU8H1sMqb34qPGnSMaSWrVO8bzxOdAXJNAtDXATvLl0lflrImIze1FZCqocM8wdIu3Sfg== + dependencies: + "@isaacs/string-locale-compare" "^1.1.0" + "@npmcli/arborist" "^6.2.6" + "@npmcli/config" "^6.1.5" + "@npmcli/map-workspaces" "^3.0.3" + "@npmcli/package-json" "^3.0.0" + "@npmcli/run-script" "^6.0.0" + abbrev "^2.0.0" archy "~1.0.0" - cacache "^16.1.3" + cacache "^17.0.5" chalk "^4.1.2" - chownr "^2.0.0" + ci-info "^3.8.0" cli-columns "^4.0.0" - cli-table3 "^0.6.2" + cli-table3 "^0.6.3" columnify "^1.6.0" - fastest-levenshtein "^1.0.12" - fs-minipass "^2.1.0" - glob "^8.0.1" - graceful-fs "^4.2.10" - hosted-git-info "^5.2.1" + fastest-levenshtein "^1.0.16" + fs-minipass "^3.0.1" + glob "^9.3.1" + graceful-fs "^4.2.11" + hosted-git-info "^6.1.1" ini "^3.0.1" - init-package-json "^3.0.2" + init-package-json "^5.0.0" is-cidr "^4.0.2" - json-parse-even-better-errors "^2.3.1" - libnpmaccess "^6.0.4" - libnpmdiff "^4.0.5" - libnpmexec "^4.0.14" - libnpmfund "^3.0.5" - libnpmhook "^8.0.4" - libnpmorg "^4.0.4" - libnpmpack "^4.1.3" - libnpmpublish "^6.0.5" - libnpmsearch "^5.0.4" - libnpmteam "^4.0.4" - libnpmversion "^3.0.7" - make-fetch-happen "^10.2.0" - minimatch "^5.1.0" - minipass "^3.1.6" + json-parse-even-better-errors "^3.0.0" + libnpmaccess "^7.0.2" + libnpmdiff "^5.0.14" + libnpmexec "^5.0.14" + libnpmfund "^4.0.14" + libnpmhook "^9.0.3" + libnpmorg "^5.0.3" + libnpmpack "^5.0.14" + libnpmpublish "^7.1.3" + libnpmsearch "^6.0.2" + libnpmteam "^5.0.3" + libnpmversion "^4.0.2" + make-fetch-happen "^11.0.3" + minimatch "^7.4.3" + minipass "^4.2.5" minipass-pipeline "^1.2.4" - mkdirp "^1.0.4" - mkdirp-infer-owner "^2.0.0" ms "^2.1.2" - node-gyp "^9.1.0" - nopt "^6.0.0" - npm-audit-report "^3.0.0" - npm-install-checks "^5.0.0" - npm-package-arg "^9.1.0" - npm-pick-manifest "^7.0.2" - npm-profile "^6.2.0" - npm-registry-fetch "^13.3.1" - npm-user-validate "^1.0.1" - npmlog "^6.0.2" - opener "^1.5.2" + node-gyp "^9.3.1" + nopt "^7.1.0" + npm-audit-report "^4.0.0" + npm-install-checks "^6.1.0" + npm-package-arg "^10.1.0" + npm-pick-manifest "^8.0.1" + npm-profile "^7.0.1" + npm-registry-fetch "^14.0.3" + npm-user-validate "^2.0.0" + npmlog "^7.0.1" p-map "^4.0.0" - pacote "^13.6.2" - parse-conflict-json "^2.0.2" - proc-log "^2.0.1" + pacote "^15.1.1" + parse-conflict-json "^3.0.1" + proc-log "^3.0.0" qrcode-terminal "^0.12.0" - read "~1.0.7" - read-package-json "^5.0.2" - read-package-json-fast "^2.0.3" - readdir-scoped-modules "^1.1.0" - rimraf "^3.0.2" - semver "^7.3.7" - ssri "^9.0.1" - tar "^6.1.11" + read "^2.0.0" + read-package-json "^6.0.1" + read-package-json-fast "^3.0.2" + semver "^7.3.8" + ssri "^10.0.1" + tar "^6.1.13" text-table "~0.2.0" tiny-relative-date "^1.3.0" - treeverse "^2.0.0" - validate-npm-package-name "^4.0.0" - which "^2.0.2" - write-file-atomic "^4.0.1" + treeverse "^3.0.0" + validate-npm-package-name "^5.0.0" + which "^3.0.0" + write-file-atomic "^5.0.0" -npmlog@^6.0.0, npmlog@^6.0.2: +npmlog@^6.0.0: version "6.0.2" resolved "https://registry.yarnpkg.com/npmlog/-/npmlog-6.0.2.tgz#c8166017a42f2dea92d6453168dd865186a70830" integrity sha512-/vBvz5Jfr9dT/aFWd0FIRf+T/Q2WBsLENygUaFUqstqsycmZAP/t5BvFJTK0viFmSUxiUKTUplWy5vt+rvKIxg== @@ -5758,55 +6644,20 @@ npmlog@^6.0.0, npmlog@^6.0.2: gauge "^4.0.3" set-blocking "^2.0.0" -nth-check@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/nth-check/-/nth-check-2.0.1.tgz#2efe162f5c3da06a28959fbd3db75dbeea9f0fc2" - integrity sha512-it1vE95zF6dTT9lBsYbxvqh0Soy4SPowchj0UBGj/V6cTPnXXtQOPUbhZ6CmGzAD/rW22LQK6E96pcdJXk4A4w== - dependencies: - boolbase "^1.0.0" - -object-assign@^4.0.1: - version "4.1.1" - resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" - integrity sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM= - -object-inspect@^1.12.0, object-inspect@^1.9.0: - version "1.12.0" - resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.12.0.tgz#6e2c120e868fd1fd18cb4f18c31741d0d6e776f0" - integrity sha512-Ho2z80bVIvJloH+YzRmpZVQe87+qASmBUKZDWgx9cu+KDrX2ZDH/3tMy+gXbZETVGs2M8YdxObOh7XAtim9Y0g== - -object-inspect@^1.12.2: - version "1.12.3" - resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.12.3.tgz#ba62dffd67ee256c8c086dfae69e016cd1f198b9" - integrity sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g== - -object-is@^1.0.1: - version "1.1.5" - resolved "https://registry.yarnpkg.com/object-is/-/object-is-1.1.5.tgz#b9deeaa5fc7f1846a0faecdceec138e5778f53ac" - integrity sha512-3cyDsyHgtmi7I7DfSSI2LDp6SK2lwvtbg0p0R1e0RvTqF5ceGx+K2dfSjm1bKDMVCFEDAQvy+o8c6a7VujOddw== - dependencies: - call-bind "^1.0.2" - define-properties "^1.1.3" - -object-keys@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.1.1.tgz#1c47f272df277f3b1daf061677d9c82e2322c60e" - integrity sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA== - -object.assign@^4.1.2: - version "4.1.2" - resolved "https://registry.yarnpkg.com/object.assign/-/object.assign-4.1.2.tgz#0ed54a342eceb37b38ff76eb831a0e788cb63940" - integrity sha512-ixT2L5THXsApyiUPYKmW+2EHpXXe5Ii3M+f4e+aJFAHao5amFRW6J0OO6c/LU8Be47utCx2GL89hxGB6XSmKuQ== +npmlog@^7.0.1: + version "7.0.1" + resolved "https://registry.yarnpkg.com/npmlog/-/npmlog-7.0.1.tgz#7372151a01ccb095c47d8bf1d0771a4ff1f53ac8" + integrity sha512-uJ0YFk/mCQpLBt+bxN88AKd+gyqZvZDbtiNxk6Waqcj2aPRyfVx8ITawkyQynxUagInjdYT1+qj4NfA5KJJUxg== dependencies: - call-bind "^1.0.0" - define-properties "^1.1.3" - has-symbols "^1.0.1" - object-keys "^1.1.1" + are-we-there-yet "^4.0.0" + console-control-strings "^1.1.0" + gauge "^5.0.0" + set-blocking "^2.0.0" once@^1.3.0, once@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" - integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= + integrity sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w== dependencies: wrappy "1" @@ -5824,27 +6675,42 @@ onetime@^6.0.0: dependencies: mimic-fn "^4.0.0" -opener@^1.5.2: - version "1.5.2" - resolved "https://registry.yarnpkg.com/opener/-/opener-1.5.2.tgz#5d37e1f35077b9dcac4301372271afdeb2a13598" - integrity sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A== - -optionator@^0.9.1: - version "0.9.1" - resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.9.1.tgz#4f236a6373dae0566a6d43e1326674f50c291499" - integrity sha512-74RlY5FCnhq4jRxVUPKDaRwrVNXMqsGsiW6AJw4XK8hmtm10wC0ypZBLw5IIp85NZMr91+qd1RvvENwg7jjRFw== +optionator@^0.9.3: + version "0.9.3" + resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.9.3.tgz#007397d44ed1872fdc6ed31360190f81814e2c64" + integrity sha512-JjCoypp+jKn1ttEFExxhetCKeJt9zhAgAve5FXHixTvFDW/5aEktX9bufBKLRRMdU7bNtpLfcGu94B3cdEJgjg== dependencies: + "@aashutoshrathi/word-wrap" "^1.2.3" deep-is "^0.1.3" fast-levenshtein "^2.0.6" levn "^0.4.1" prelude-ls "^1.2.1" type-check "^0.4.0" - word-wrap "^1.2.3" -p-each-series@^2.1.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/p-each-series/-/p-each-series-2.2.0.tgz#105ab0357ce72b202a8a8b94933672657b5e2a9a" - integrity sha512-ycIL2+1V32th+8scbpTvyHNaHe02z0sjgh91XXjAk+ZeXoPN4Z46DVUnzdso0aX4KckKw0FNNFHdjZ2UsZvxiA== +ora@^5.4.1: + version "5.4.1" + resolved "https://registry.yarnpkg.com/ora/-/ora-5.4.1.tgz#1b2678426af4ac4a509008e5e4ac9e9959db9e18" + integrity sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ== + dependencies: + bl "^4.1.0" + chalk "^4.1.0" + cli-cursor "^3.1.0" + cli-spinners "^2.5.0" + is-interactive "^1.0.0" + is-unicode-supported "^0.1.0" + log-symbols "^4.1.0" + strip-ansi "^6.0.0" + wcwidth "^1.0.1" + +os-tmpdir@~1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" + integrity sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g== + +p-each-series@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/p-each-series/-/p-each-series-3.0.0.tgz#d1aed5e96ef29864c897367a7d2a628fdc960806" + integrity sha512-lastgtAdoH9YaLyDa5i5z64q+kzOcQHsQ5SsZJD3q0VEyI8mq872S3geuNbRUQLVAE9siMfgKrpj7MloKFHruw== p-filter@^2.0.0: version "2.1.0" @@ -5853,6 +6719,13 @@ p-filter@^2.0.0: dependencies: p-map "^2.0.0" +p-filter@^4.0.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/p-filter/-/p-filter-4.1.0.tgz#fe0aa794e2dfad8ecf595a39a245484fcd09c6e4" + integrity sha512-37/tPdZ3oJwHaS3gNJdenCDB3Tz26i9sjhnguBtvN0vYlRIiDNnvTWkuh+0hETV9rLPdJ3rlL3yVOYPIAnM8rw== + dependencies: + p-map "^7.0.1" + p-is-promise@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/p-is-promise/-/p-is-promise-3.0.0.tgz#58e78c7dfe2e163cf2a04ff869e7c1dba64a5971" @@ -5872,13 +6745,20 @@ p-limit@^2.2.0: dependencies: p-try "^2.0.0" -p-limit@^3.1.0: +p-limit@^3.0.2, p-limit@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-3.1.0.tgz#e1daccbe78d0d1388ca18c64fea38e3e57e3706b" integrity sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ== dependencies: yocto-queue "^0.1.0" +p-limit@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-4.0.0.tgz#914af6544ed32bfa54670b061cafcbd04984b644" + integrity sha512-5b0R4txpzjPWVw/cXXUResoD4hb6U/x9BH08L7nw+GN1sezDzPdxeRvpc9c433fZhBan/wusjbCsqwqm4EIBIQ== + dependencies: + yocto-queue "^1.0.0" + p-locate@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-2.0.0.tgz#20a0103b222a70c8fd39cc2e580680f3dde5ec43" @@ -5893,6 +6773,20 @@ p-locate@^4.1.0: dependencies: p-limit "^2.2.0" +p-locate@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-5.0.0.tgz#83c8315c6785005e3bd021839411c9e110e6d834" + integrity sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw== + dependencies: + p-limit "^3.0.2" + +p-locate@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-6.0.0.tgz#3da9a49d4934b901089dca3302fa65dc5a05c04f" + integrity sha512-wPrq66Llhl7/4AGC6I+cqxT07LhXvWL08LNXz1fENOw0Ap4sRZZ/gZpTTJ5jpurzzzfS2W/Ge9BY3LgLjCShcw== + dependencies: + p-limit "^4.0.0" + p-map@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/p-map/-/p-map-2.1.0.tgz#310928feef9c9ecc65b68b17693018a665cea175" @@ -5905,11 +6799,21 @@ p-map@^4.0.0: dependencies: aggregate-error "^3.0.0" +p-map@^7.0.1: + version "7.0.1" + resolved "https://registry.yarnpkg.com/p-map/-/p-map-7.0.1.tgz#1faf994e597160f7851882926bfccabc1d226f80" + integrity sha512-2wnaR0XL/FDOj+TgpDuRb2KTjLnu3Fma6b1ZUwGY7LcqenMcvP/YFpjpbPKY6WVGsbuJZRuoUz8iPrt8ORnAFw== + p-reduce@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/p-reduce/-/p-reduce-2.1.0.tgz#09408da49507c6c274faa31f28df334bc712b64a" integrity sha512-2USApvnsutq8uoxZBGbbWM0JIYLiEMJ9RlaN7fAzVNb9OZN0SHjjTTfIcb667XynS5Y1VhwDJVDa72TnPzAYWw== +p-reduce@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/p-reduce/-/p-reduce-3.0.0.tgz#f11773794792974bd1f7a14c72934248abff4160" + integrity sha512-xsrIUgI0Kn6iyDYm9StOpOeK29XM1aboGji26+QEortiFST1hGZaUQOLhtEbqHErPpGW/aSz6allwK2qcptp0Q== + p-retry@^4.0.0: version "4.6.2" resolved "https://registry.yarnpkg.com/p-retry/-/p-retry-4.6.2.tgz#9baae7184057edd4e17231cee04264106e092a16" @@ -5928,40 +6832,53 @@ p-try@^2.0.0: resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6" integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ== -pacote@^13.0.3, pacote@^13.6.1, pacote@^13.6.2: - version "13.6.2" - resolved "https://registry.yarnpkg.com/pacote/-/pacote-13.6.2.tgz#0d444ba3618ab3e5cd330b451c22967bbd0ca48a" - integrity sha512-Gu8fU3GsvOPkak2CkbojR7vjs3k3P9cA6uazKTHdsdV0gpCEQq2opelnEv30KRQWgVzP5Vd/5umjcedma3MKtg== - dependencies: - "@npmcli/git" "^3.0.0" - "@npmcli/installed-package-contents" "^1.0.7" - "@npmcli/promise-spawn" "^3.0.0" - "@npmcli/run-script" "^4.1.0" - cacache "^16.0.0" - chownr "^2.0.0" - fs-minipass "^2.1.0" - infer-owner "^1.0.4" - minipass "^3.1.6" - mkdirp "^1.0.4" - npm-package-arg "^9.0.0" - npm-packlist "^5.1.0" - npm-pick-manifest "^7.0.0" - npm-registry-fetch "^13.0.1" - proc-log "^2.0.0" +pacote@^15.0.0, pacote@^15.0.8, pacote@^15.1.1: + version "15.1.1" + resolved "https://registry.yarnpkg.com/pacote/-/pacote-15.1.1.tgz#94d8c6e0605e04d427610b3aacb0357073978348" + integrity sha512-eeqEe77QrA6auZxNHIp+1TzHQ0HBKf5V6c8zcaYZ134EJe1lCi+fjXATkNiEEfbG+e50nu02GLvUtmZcGOYabQ== + dependencies: + "@npmcli/git" "^4.0.0" + "@npmcli/installed-package-contents" "^2.0.1" + "@npmcli/promise-spawn" "^6.0.1" + "@npmcli/run-script" "^6.0.0" + cacache "^17.0.0" + fs-minipass "^3.0.0" + minipass "^4.0.0" + npm-package-arg "^10.0.0" + npm-packlist "^7.0.0" + npm-pick-manifest "^8.0.0" + npm-registry-fetch "^14.0.0" + proc-log "^3.0.0" promise-retry "^2.0.1" - read-package-json "^5.0.0" - read-package-json-fast "^2.0.3" - rimraf "^3.0.2" - ssri "^9.0.0" + read-package-json "^6.0.0" + read-package-json-fast "^3.0.0" + sigstore "^1.0.0" + ssri "^10.0.0" tar "^6.1.11" -param-case@^3.0.4: - version "3.0.4" - resolved "https://registry.yarnpkg.com/param-case/-/param-case-3.0.4.tgz#7d17fe4aa12bde34d4a77d91acfb6219caad01c5" - integrity sha512-RXlj7zCYokReqWpOPH9oYivUzLYZ5vAPIfEmCTNViosC78F8F0H9y7T7gG2M39ymgutxF5gcFEsyZQSph9Bp3A== - dependencies: - dot-case "^3.0.4" - tslib "^2.0.3" +pacote@^17.0.0, pacote@^17.0.4, pacote@^17.0.6: + version "17.0.6" + resolved "https://registry.yarnpkg.com/pacote/-/pacote-17.0.6.tgz#874bb59cda5d44ab784d0b6530fcb4a7d9b76a60" + integrity sha512-cJKrW21VRE8vVTRskJo78c/RCvwJCn1f4qgfxL4w77SOWrTCRcmfkYHlHtS0gqpgjv3zhXflRtgsrUCX5xwNnQ== + dependencies: + "@npmcli/git" "^5.0.0" + "@npmcli/installed-package-contents" "^2.0.1" + "@npmcli/promise-spawn" "^7.0.0" + "@npmcli/run-script" "^7.0.0" + cacache "^18.0.0" + fs-minipass "^3.0.0" + minipass "^7.0.2" + npm-package-arg "^11.0.0" + npm-packlist "^8.0.0" + npm-pick-manifest "^9.0.0" + npm-registry-fetch "^16.0.0" + proc-log "^3.0.0" + promise-retry "^2.0.1" + read-package-json "^7.0.0" + read-package-json-fast "^3.0.0" + sigstore "^2.2.0" + ssri "^10.0.0" + tar "^6.1.11" parent-module@^1.0.0: version "1.0.1" @@ -5970,24 +6887,13 @@ parent-module@^1.0.0: dependencies: callsites "^3.0.0" -parse-asn1@^5.0.0, parse-asn1@^5.1.5: - version "5.1.6" - resolved "https://registry.yarnpkg.com/parse-asn1/-/parse-asn1-5.1.6.tgz#385080a3ec13cb62a62d39409cb3e88844cdaed4" - integrity sha512-RnZRo1EPU6JBnra2vGHj0yhp6ebyjBZpmUCLHWiFhxlzvBCCpAuZ7elsBp1PVAbQN0/04VD/19rfzlBSwLstMw== - dependencies: - asn1.js "^5.2.0" - browserify-aes "^1.0.0" - evp_bytestokey "^1.0.0" - pbkdf2 "^3.0.3" - safe-buffer "^5.1.1" - -parse-conflict-json@^2.0.1, parse-conflict-json@^2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/parse-conflict-json/-/parse-conflict-json-2.0.2.tgz#3d05bc8ffe07d39600dc6436c6aefe382033d323" - integrity sha512-jDbRGb00TAPFsKWCpZZOT93SxVP9nONOSgES3AevqRq/CHvavEBvKAjxX9p5Y5F0RZLxH9Ufd9+RwtCsa+lFDA== +parse-conflict-json@^3.0.0, parse-conflict-json@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/parse-conflict-json/-/parse-conflict-json-3.0.1.tgz#67dc55312781e62aa2ddb91452c7606d1969960c" + integrity sha512-01TvEktc68vwbJOtWZluyWeVGWjP+bZwXtPDMQVbBKzbJ/vZBif0L69KH1+cHv1SZ6e0FKLvjyHe8mqsIqYOmw== dependencies: - json-parse-even-better-errors "^2.3.1" - just-diff "^5.0.1" + json-parse-even-better-errors "^3.0.0" + just-diff "^6.0.0" just-diff-apply "^5.2.0" parse-json@^4.0.0: @@ -6008,13 +6914,19 @@ parse-json@^5.0.0, parse-json@^5.2.0: json-parse-even-better-errors "^2.3.0" lines-and-columns "^1.1.6" -pascal-case@^3.1.2: - version "3.1.2" - resolved "https://registry.yarnpkg.com/pascal-case/-/pascal-case-3.1.2.tgz#b48e0ef2b98e205e7c1dae747d0b1508237660eb" - integrity sha512-uWlGT3YSnK9x3BQJaOdcZwrnV6hPpd8jFH1/ucpiLRPh/2zCVJKS19E4GvYHvaCcACn3foXZ0cLB9Wrx1KGe5g== +parse-json@^8.0.0: + version "8.1.0" + resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-8.1.0.tgz#91cdc7728004e955af9cb734de5684733b24a717" + integrity sha512-rum1bPifK5SSar35Z6EKZuYPJx85pkNaFrxBK3mwdfSJ1/WKbYrjoW/zTPSjRRamfmVX1ACBIdFAO0VRErW/EA== dependencies: - no-case "^3.0.4" - tslib "^2.0.3" + "@babel/code-frame" "^7.22.13" + index-to-position "^0.1.2" + type-fest "^4.7.1" + +parse-passwd@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/parse-passwd/-/parse-passwd-1.0.0.tgz#6d5b934a456993b23d37f40a382d6f1666a8e5c6" + integrity sha512-1Y1A//QUXEZK7YKz+rD9WydcE1+EuPr6ZBgKecAB8tmoW6UFv0NREVJe1p+jRxtThkcbbKkfwIbWJe/IeE6m2Q== path-exists@^3.0.0: version "3.0.0" @@ -6026,15 +6938,15 @@ path-exists@^4.0.0: resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-4.0.0.tgz#513bdbe2d3b95d7762e8c1137efa195c6c61b5b3" integrity sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w== +path-exists@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-5.0.0.tgz#a6aad9489200b21fab31e49cf09277e5116fb9e7" + integrity sha512-RjhtfwJOxzcFmNOi6ltcbcu4Iu+FL3zEj83dk4kAS+fVpTxXLO1b38RvJgT/0QwvV/L3aY9TAnyv0EOqW4GoMQ== + path-is-absolute@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" - integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18= - -path-is-inside@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/path-is-inside/-/path-is-inside-1.0.2.tgz#365417dede44430d1c11af61027facf074bdfc53" - integrity sha1-NlQX3t5EQw0cEa9hAn+s8HS9/FM= + integrity sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg== path-key@^3.0.0, path-key@^3.1.0: version "3.1.1" @@ -6051,21 +6963,31 @@ path-parse@^1.0.7: resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.7.tgz#fbc114b60ca42b30d9daf5858e4bd68bbedb6735" integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw== +path-scurry@^1.10.1: + version "1.10.1" + resolved "https://registry.yarnpkg.com/path-scurry/-/path-scurry-1.10.1.tgz#9ba6bf5aa8500fe9fd67df4f0d9483b2b0bfc698" + integrity sha512-MkhCqzzBEpPvxxQ71Md0b1Kk51W01lrYvlMzSUaIzNsODdd7mqhiimSZlr+VegAz5Z6Vzt9Xg2ttE//XBhH3EQ== + dependencies: + lru-cache "^9.1.1 || ^10.0.0" + minipass "^5.0.0 || ^6.0.2 || ^7.0.0" + +path-scurry@^1.6.1: + version "1.6.3" + resolved "https://registry.yarnpkg.com/path-scurry/-/path-scurry-1.6.3.tgz#4eba7183d64ef88b63c7d330bddc3ba279dc6c40" + integrity sha512-RAmB+n30SlN+HnNx6EbcpoDy9nwdpcGPnEKrJnu6GZoDWBdIjo1UQMVtW2ybtC7LC2oKLcMq8y5g8WnKLiod9g== + dependencies: + lru-cache "^7.14.1" + minipass "^4.0.2" + path-type@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b" integrity sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw== -pbkdf2@^3.0.3: - version "3.1.2" - resolved "https://registry.yarnpkg.com/pbkdf2/-/pbkdf2-3.1.2.tgz#dd822aa0887580e52f1a039dc3eda108efae3075" - integrity sha512-iuh7L6jA7JEGu2WxDwtQP1ddOpaJNC4KlDEFfdQajSGgGPNi4OyDc2R7QnbY2bR9QjBVGwgvTdNJZoE7RaxUMA== - dependencies: - create-hash "^1.1.2" - create-hmac "^1.1.4" - ripemd160 "^2.0.1" - safe-buffer "^5.0.1" - sha.js "^2.4.8" +path-type@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/path-type/-/path-type-5.0.0.tgz#14b01ed7aea7ddf9c7c3f46181d4d04f9c785bb8" + integrity sha512-5HviZNaZcfqP95rwpv+1HDgUamezbqdSYTyzjTvwtJSnIH+3vnbmWsItli8OFEndS984VT55M3jduxZbX351gg== picocolors@^1.0.0: version "1.0.0" @@ -6077,38 +6999,16 @@ picomatch@^2.0.4, picomatch@^2.2.3, picomatch@^2.3.1: resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42" integrity sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA== -pidtree@^0.6.0: +pidtree@0.6.0: version "0.6.0" resolved "https://registry.yarnpkg.com/pidtree/-/pidtree-0.6.0.tgz#90ad7b6d42d5841e69e0a2419ef38f8883aa057c" integrity sha512-eG2dWTVw5bzqGRztnHExczNxt5VGsE6OwTeCG3fdUf9KBsZzO3R5OIIIzWR+iZA0NtZ+RDVdaoE2dK1cn6jH4g== -pify@^2.0.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c" - integrity sha1-7RQaasBDqEnqWISY59yosVMw6Qw= - pify@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/pify/-/pify-3.0.0.tgz#e5a4acd2c101fdf3d9a4d07f0dbc4db49dd28176" integrity sha512-C3FsVNH1udSEX48gGX1xfvwTWfsYWj5U+8/uK15BGzIGrKoUpghX8hWZwa/OFnakBiiVNmBvemTJR5mcy7iPcg== -pify@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/pify/-/pify-4.0.1.tgz#4b2cd25c50d598735c50292224fd8c6df41e3231" - integrity sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g== - -pinkie-promise@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/pinkie-promise/-/pinkie-promise-2.0.1.tgz#2135d6dfa7a358c069ac9b178776288228450ffa" - integrity sha1-ITXW36ejWMBprJsXh3YogihFD/o= - dependencies: - pinkie "^2.0.0" - -pinkie@^2.0.0: - version "2.0.4" - resolved "https://registry.yarnpkg.com/pinkie/-/pinkie-2.0.4.tgz#72556b80cfa0d48a974e80e77248e80ed4f7f870" - integrity sha1-clVrgM+g1IqXToDnckjoDtT3+HA= - pirates@^4.0.4: version "4.0.5" resolved "https://registry.yarnpkg.com/pirates/-/pirates-4.0.5.tgz#feec352ea5c3268fb23a37c702ab1699f35a5f3b" @@ -6149,18 +7049,10 @@ prettier-linter-helpers@^1.0.0: dependencies: fast-diff "^1.1.2" -prettier@2.8.4: - version "2.8.4" - resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.8.4.tgz#34dd2595629bfbb79d344ac4a91ff948694463c3" - integrity sha512-vIS4Rlc2FNh0BySk3Wkd6xmwxB0FpOndW5fisM5H8hsZSxU2VWVB5CWIkIjWvrHjIhxk2g3bfMKM87zNTrZddw== - -pretty-error@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/pretty-error/-/pretty-error-4.0.0.tgz#90a703f46dd7234adb46d0f84823e9d1cb8f10d6" - integrity sha512-AoJ5YMAcXKYxKhuJGdcvse+Voc6v1RgnsR3nWcYU7q4t6z0Q6T86sv5Zq8VIRbOWWFpvdGE83LtdSMNd+6Y0xw== - dependencies: - lodash "^4.17.20" - renderkid "^3.0.0" +prettier@2.8.7: + version "2.8.7" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.8.7.tgz#bb79fc8729308549d28fe3a98fce73d2c0656450" + integrity sha512-yPngTo3aXUUmyuTjeTUT75txrf+aMh9FiD7q9ZE/i6r0bPb22g4FsE6Y338PQX1bmfy08i9QQCB7/rcUAVntfw== pretty-format@^29.0.0, pretty-format@^29.4.3: version "29.4.3" @@ -6171,20 +7063,29 @@ pretty-format@^29.0.0, pretty-format@^29.4.3: ansi-styles "^5.0.0" react-is "^18.0.0" -proc-log@^2.0.0, proc-log@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/proc-log/-/proc-log-2.0.1.tgz#8f3f69a1f608de27878f91f5c688b225391cb685" - integrity sha512-Kcmo2FhfDTXdcbfDH76N7uBYHINxc/8GW7UAVuVP9I+Va3uHSerrnKV6dLooga/gh7GlgzuCCr/eoldnL1muGw== +pretty-format@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-29.7.0.tgz#ca42c758310f365bfa71a0bda0a807160b776812" + integrity sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ== + dependencies: + "@jest/schemas" "^29.6.3" + ansi-styles "^5.0.0" + react-is "^18.0.0" + +proc-log@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/proc-log/-/proc-log-3.0.0.tgz#fb05ef83ccd64fd7b20bbe9c8c1070fc08338dd8" + integrity sha512-++Vn7NS4Xf9NacaU9Xq3URUuqZETPsf8L4j5/ckhaRYsfPeRyzGw+iDjFhV/Jr3uNmTvvddEJFWh5R1gRgUH8A== process-nextick-args@~2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz#7820d9b16120cc55ca9ae7792680ae7dba6d7fe2" integrity sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag== -progress@^2.0.0: - version "2.0.3" - resolved "https://registry.yarnpkg.com/progress/-/progress-2.0.3.tgz#7e8cf8d8f5b8f239c1bc68beb4eb78567d572ef8" - integrity sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA== +process@^0.11.10: + version "0.11.10" + resolved "https://registry.yarnpkg.com/process/-/process-0.11.10.tgz#7332300e840161bda3e69a1d1d91a7d4bc16f182" + integrity sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A== promise-all-reject-late@^1.0.0: version "1.0.1" @@ -6196,6 +7097,11 @@ promise-call-limit@^1.0.1: resolved "https://registry.yarnpkg.com/promise-call-limit/-/promise-call-limit-1.0.1.tgz#4bdee03aeb85674385ca934da7114e9bcd3c6e24" integrity sha512-3+hgaa19jzCGLuSCbieeRsu5C2joKfYn8pY6JAuXFRVfF4IO+L7UPpFWNTeWT9pM7uhskvbPPd/oEOktCn317Q== +promise-call-limit@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/promise-call-limit/-/promise-call-limit-3.0.1.tgz#3570f7a3f2aaaf8e703623a552cd74749688cf19" + integrity sha512-utl+0x8gIDasV5X+PI5qWEPqH6fJS0pFtQ/4gZ95xfEFb/89dmh+/b895TbFDBLiafBvxD/PGTKfvxl4kH/pQg== + promise-inflight@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/promise-inflight/-/promise-inflight-1.0.1.tgz#98472870bf228132fcbdd868129bad12c3c029e3" @@ -6217,34 +7123,27 @@ prompts@^2.0.1: kleur "^3.0.3" sisteransi "^1.0.5" -promzard@^0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/promzard/-/promzard-0.3.0.tgz#26a5d6ee8c7dee4cb12208305acfb93ba382a9ee" - integrity sha512-JZeYqd7UAcHCwI+sTOeUDYkvEU+1bQ7iE0UT1MgB/tERkAPkesW46MrpIySzODi+owTjZtiF8Ay5j9m60KmMBw== +promzard@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/promzard/-/promzard-1.0.0.tgz#3246f8e6c9895a77c0549cefb65828ac0f6c006b" + integrity sha512-KQVDEubSUHGSt5xLakaToDFrSoZhStB8dXLzk2xvwR67gJktrHFvpR63oZgHyK19WKbHFLXJqCPXdVR3aBP8Ig== dependencies: - read "1" + read "^2.0.0" proto-list@~1.2.1: version "1.2.4" resolved "https://registry.yarnpkg.com/proto-list/-/proto-list-1.2.4.tgz#212d5bfe1318306a420f6402b8e26ff39647a849" integrity sha512-vtK/94akxsTMhe0/cbfpR+syPuszcuwhqVjJq26CuNDgFGj682oRBXOP5MJpv2r7JtE8MsiepGIqvvOTBwn2vA== -public-encrypt@^4.0.0: - version "4.0.3" - resolved "https://registry.yarnpkg.com/public-encrypt/-/public-encrypt-4.0.3.tgz#4fcc9d77a07e48ba7527e7cbe0de33d0701331e0" - integrity sha512-zVpa8oKZSz5bTMTFClc1fQOnyyEzpl5ozpi1B5YcvBrdohMjH2rfsBtyXcuNuwjsDIXmBYlF2N5FlJYhR29t8Q== - dependencies: - bn.js "^4.1.0" - browserify-rsa "^4.0.0" - create-hash "^1.1.0" - parse-asn1 "^5.0.0" - randombytes "^2.0.1" - safe-buffer "^5.1.2" - punycode@^2.1.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.1.1.tgz#b58b010ac40c22c5657616c8d2c2c02c7bf479ec" - integrity sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A== + version "2.3.0" + resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.3.0.tgz#f67fa67c94da8f4d0cfff981aee4118064199b8f" + integrity sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA== + +pure-rand@^6.0.0: + version "6.0.1" + resolved "https://registry.yarnpkg.com/pure-rand/-/pure-rand-6.0.1.tgz#31207dddd15d43f299fdcdb2f572df65030c19af" + integrity sha512-t+x1zEHDjBwkDGY5v5ApnZ/utcd4XYDiJsaQQoptTXgUXX95sDg1elCdJghzicm7n2mbCBJ3uYWr6M22SO19rg== q@^1.5.1: version "1.5.1" @@ -6266,21 +7165,13 @@ quick-lru@^4.0.1: resolved "https://registry.yarnpkg.com/quick-lru/-/quick-lru-4.0.1.tgz#5b8878f113a58217848c6482026c73e1ba57727f" integrity sha512-ARhCpm70fzdcvNQfPoy49IaanKkTlRWF2JMzqhcJbhSFRZv7nPTvZJdcY7301IPmvW+/p0RgIWnQDLJxifsQ7g== -randombytes@^2.0.0, randombytes@^2.0.1, randombytes@^2.0.5, randombytes@^2.1.0: +randombytes@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/randombytes/-/randombytes-2.1.0.tgz#df6f84372f0270dc65cdf6291349ab7a473d4f2a" integrity sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ== dependencies: safe-buffer "^5.1.0" -randomfill@^1.0.3: - version "1.0.4" - resolved "https://registry.yarnpkg.com/randomfill/-/randomfill-1.0.4.tgz#c92196fc86ab42be983f1bf31778224931d61458" - integrity sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw== - dependencies: - randombytes "^2.0.5" - safe-buffer "^5.1.0" - rc@^1.2.8: version "1.2.8" resolved "https://registry.yarnpkg.com/rc/-/rc-1.2.8.tgz#cd924bf5200a075b83c188cd6b9e211b7fc0d3ed" @@ -6296,28 +7187,48 @@ react-is@^18.0.0: resolved "https://registry.yarnpkg.com/react-is/-/react-is-18.2.0.tgz#199431eeaaa2e09f86427efbb4f1473edb47609b" integrity sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w== -read-cmd-shim@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/read-cmd-shim/-/read-cmd-shim-3.0.1.tgz#868c235ec59d1de2db69e11aec885bc095aea087" - integrity sha512-kEmDUoYf/CDy8yZbLTmhB1X9kkjf9Q80PCNsDMb7ufrGd6zZSQA1+UyjrO+pZm5K/S4OXCWJeiIt1JA8kAsa6g== +read-cmd-shim@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/read-cmd-shim/-/read-cmd-shim-4.0.0.tgz#640a08b473a49043e394ae0c7a34dd822c73b9bb" + integrity sha512-yILWifhaSEEytfXI76kB9xEEiG1AiozaCJZ83A87ytjRiN+jVibXjedjCRNjoZviinhG+4UkalO3mWTd8u5O0Q== -read-package-json-fast@^2.0.2, read-package-json-fast@^2.0.3: - version "2.0.3" - resolved "https://registry.yarnpkg.com/read-package-json-fast/-/read-package-json-fast-2.0.3.tgz#323ca529630da82cb34b36cc0b996693c98c2b83" - integrity sha512-W/BKtbL+dUjTuRL2vziuYhp76s5HZ9qQhd/dKfWIZveD0O40453QNyZhC0e63lqZrAQ4jiOapVoeJ7JrszenQQ== +read-package-json-fast@^3.0.0, read-package-json-fast@^3.0.2: + version "3.0.2" + resolved "https://registry.yarnpkg.com/read-package-json-fast/-/read-package-json-fast-3.0.2.tgz#394908a9725dc7a5f14e70c8e7556dff1d2b1049" + integrity sha512-0J+Msgym3vrLOUB3hzQCuZHII0xkNGCtz/HJH9xZshwv9DbDwkw1KaE3gx/e2J5rpEY5rtOy6cyhKOPrkP7FZw== dependencies: - json-parse-even-better-errors "^2.3.0" - npm-normalize-package-bin "^1.0.1" + json-parse-even-better-errors "^3.0.0" + npm-normalize-package-bin "^3.0.0" -read-package-json@^5.0.0, read-package-json@^5.0.2: - version "5.0.2" - resolved "https://registry.yarnpkg.com/read-package-json/-/read-package-json-5.0.2.tgz#b8779ccfd169f523b67208a89cc912e3f663f3fa" - integrity sha512-BSzugrt4kQ/Z0krro8zhTwV1Kd79ue25IhNN/VtHFy1mG/6Tluyi+msc0UpwaoQzxSHa28mntAjIZY6kEgfR9Q== +read-package-json@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/read-package-json/-/read-package-json-6.0.0.tgz#6a741841ad72a40e77a82b9c3c8c10e865bbc519" + integrity sha512-b/9jxWJ8EwogJPpv99ma+QwtqB7FSl3+V6UXS7Aaay8/5VwMY50oIFooY1UKXMWpfNCM6T/PoGqa5GD1g9xf9w== dependencies: glob "^8.0.1" - json-parse-even-better-errors "^2.3.1" - normalize-package-data "^4.0.0" - npm-normalize-package-bin "^2.0.0" + json-parse-even-better-errors "^3.0.0" + normalize-package-data "^5.0.0" + npm-normalize-package-bin "^3.0.0" + +read-package-json@^6.0.1: + version "6.0.1" + resolved "https://registry.yarnpkg.com/read-package-json/-/read-package-json-6.0.1.tgz#566cb06bc05dbddefba4607e9096d5a9efbcd836" + integrity sha512-AaHqXxfAVa+fNL07x8iAghfKOds/XXsu7zoouIVsbm7PEbQ3nMWXlvjcbrNLjElnUHWQtAo4QEa0RXuvD4XlpA== + dependencies: + glob "^9.3.0" + json-parse-even-better-errors "^3.0.0" + normalize-package-data "^5.0.0" + npm-normalize-package-bin "^3.0.0" + +read-package-json@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/read-package-json/-/read-package-json-7.0.0.tgz#d605c9dcf6bc5856da24204aa4e9518ee9714be0" + integrity sha512-uL4Z10OKV4p6vbdvIXB+OzhInYtIozl/VxUBPgNkBuUi2DeRonnuspmaVAMcrkmfjKGNmRndyQAbE7/AmzGwFg== + dependencies: + glob "^10.2.2" + json-parse-even-better-errors "^3.0.0" + normalize-package-data "^6.0.0" + npm-normalize-package-bin "^3.0.0" read-pkg-up@^7.0.0, read-pkg-up@^7.0.1: version "7.0.1" @@ -6328,7 +7239,16 @@ read-pkg-up@^7.0.0, read-pkg-up@^7.0.1: read-pkg "^5.2.0" type-fest "^0.8.1" -read-pkg@^5.0.0, read-pkg@^5.2.0: +read-pkg-up@^9.1.0: + version "9.1.0" + resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-9.1.0.tgz#38ca48e0bc6c6b260464b14aad9bcd4e5b1fbdc3" + integrity sha512-vaMRR1AC1nrd5CQM0PhlRsO5oc2AAigqr7cCrZ/MW/Rsaflz4RlgzkpL4qoU/z1F6wrbd85iFv1OQj/y5RdGvg== + dependencies: + find-up "^6.3.0" + read-pkg "^7.1.0" + type-fest "^2.5.0" + +read-pkg@^5.2.0: version "5.2.0" resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-5.2.0.tgz#7bf295438ca5a33e56cd30e053b34ee7250c93cc" integrity sha512-Ug69mNOpfvKDAc2Q8DRpMjjzdtrnv9HcSMX+4VsZxD1aZ6ZzrIE7rlzXBtWTyhULSMKg076AW6WR5iZpD0JiOg== @@ -6338,14 +7258,42 @@ read-pkg@^5.0.0, read-pkg@^5.2.0: parse-json "^5.0.0" type-fest "^0.6.0" -read@1, read@^1.0.7, read@~1.0.7: - version "1.0.7" - resolved "https://registry.yarnpkg.com/read/-/read-1.0.7.tgz#b3da19bd052431a97671d44a42634adf710b40c4" - integrity sha512-rSOKNYUmaxy0om1BNjMN4ezNT6VKK+2xF4GBhc81mkH7L60i6dp8qPYrkndNLT3QPphoII3maL9PVC9XmhHwVQ== +read-pkg@^7.0.0, read-pkg@^7.1.0: + version "7.1.0" + resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-7.1.0.tgz#438b4caed1ad656ba359b3e00fd094f3c427a43e" + integrity sha512-5iOehe+WF75IccPc30bWTbpdDQLOCc3Uu8bi3Dte3Eueij81yx1Mrufk8qBx/YAbR4uL1FdUr+7BKXDwEtisXg== + dependencies: + "@types/normalize-package-data" "^2.4.1" + normalize-package-data "^3.0.2" + parse-json "^5.2.0" + type-fest "^2.0.0" + +read-pkg@^9.0.0: + version "9.0.1" + resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-9.0.1.tgz#b1b81fb15104f5dbb121b6bbdee9bbc9739f569b" + integrity sha512-9viLL4/n1BJUCT1NXVTdS1jtm80yDEgR5T4yCelII49Mbj0v1rZdKqj7zCiYdbB0CuCgdrvHcNogAKTFPBocFA== + dependencies: + "@types/normalize-package-data" "^2.4.3" + normalize-package-data "^6.0.0" + parse-json "^8.0.0" + type-fest "^4.6.0" + unicorn-magic "^0.1.0" + +read@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/read/-/read-2.0.0.tgz#1d469a7321088e53b86ca77bf60a609e02f4eed8" + integrity sha512-88JMmpeeRYzW9gvIpYyXlYadWanW4vB2CYtDDVBfbRpbSogUNjTWEBXxJXMIVFSLjWVdCcdcIjI3+VV3Z2e9mw== dependencies: - mute-stream "~0.0.4" + mute-stream "~1.0.0" -readable-stream@3, readable-stream@^3.0.0, readable-stream@^3.5.0, readable-stream@^3.6.0: +read@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/read/-/read-2.1.0.tgz#69409372c54fe3381092bc363a00650b6ac37218" + integrity sha512-bvxi1QLJHcaywCAEsAk4DG3nVoqiY2Csps3qzWalhj5hFqRn1d/OixkFXtLO1PrgHUcAP0FNaSY/5GYNfENFFQ== + dependencies: + mute-stream "~1.0.0" + +readable-stream@3, readable-stream@^3.0.0, readable-stream@^3.4.0, readable-stream@^3.6.0: version "3.6.0" resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.0.tgz#337bbda3adc0706bd3e024426a286d4b4b2c9198" integrity sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA== @@ -6367,22 +7315,15 @@ readable-stream@^2.0.0, readable-stream@^2.0.2, readable-stream@~2.3.6: string_decoder "~1.1.1" util-deprecate "~1.0.1" -readdir-scoped-modules@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/readdir-scoped-modules/-/readdir-scoped-modules-1.1.0.tgz#8d45407b4f870a0dcaebc0e28670d18e74514309" - integrity sha512-asaikDeqAQg7JifRsZn1NJZXo9E+VwlyCfbkZhwyISinqk5zNS6266HS5kah6P0SaQKGF6SkNnZVHUzHFYxYDw== - dependencies: - debuglog "^1.0.1" - dezalgo "^1.0.0" - graceful-fs "^4.1.2" - once "^1.3.0" - -rechoir@^0.7.0: - version "0.7.1" - resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.7.1.tgz#9478a96a1ca135b5e88fc027f03ee92d6c645686" - integrity sha512-/njmZ8s1wVeR6pjTZ+0nCnv8SpZNRMT2D1RLOJQESlYFDBvwpTA4KWJpZ+sBJ4+vhjILRcK7JIFdGCdxEAAitg== +readable-stream@^4.1.0: + version "4.3.0" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-4.3.0.tgz#0914d0c72db03b316c9733bb3461d64a3cc50cba" + integrity sha512-MuEnA0lbSi7JS8XM+WNJlWZkHAAdm7gETHdFK//Q/mChGyj2akEFtdLZh32jSdkWGbRwCW9pn6g3LWDdDeZnBQ== dependencies: - resolve "^1.9.0" + abort-controller "^3.0.0" + buffer "^6.0.3" + events "^3.3.0" + process "^0.11.10" redent@^3.0.0: version "3.0.0" @@ -6399,15 +7340,10 @@ redeyed@~2.1.0: dependencies: esprima "~4.0.0" -regexp-tree@~0.1.1: - version "0.1.24" - resolved "https://registry.yarnpkg.com/regexp-tree/-/regexp-tree-0.1.24.tgz#3d6fa238450a4d66e5bc9c4c14bb720e2196829d" - integrity sha512-s2aEVuLhvnVJW6s/iPgEGK6R+/xngd2jNQ+xy4bXNDKxZKJH6jpPHY6kVeVv1IeLCHgswRj+Kl3ELaDjG6V1iw== - -regexpp@^3.1.0, regexpp@^3.2.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.2.0.tgz#0425a2768d8f23bad70ca4b90461fa2f1213e1b2" - integrity sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg== +regenerator-runtime@^0.13.11: + version "0.13.11" + resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz#f6dca3e7ceec20590d07ada785636a90cdca17f9" + integrity sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg== registry-auth-token@^5.0.0: version "5.0.1" @@ -6416,26 +7352,10 @@ registry-auth-token@^5.0.0: dependencies: "@pnpm/npm-conf" "^1.0.4" -relateurl@^0.2.7: - version "0.2.7" - resolved "https://registry.yarnpkg.com/relateurl/-/relateurl-0.2.7.tgz#54dbf377e51440aca90a4cd274600d3ff2d888a9" - integrity sha1-VNvzd+UUQKypCkzSdGANP/LYiKk= - -renderkid@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/renderkid/-/renderkid-3.0.0.tgz#5fd823e4d6951d37358ecc9a58b1f06836b6268a" - integrity sha512-q/7VIQA8lmM1hF+jn+sFSPWGlMkSAeNYcPLmDQx2zzuiDfaLrOmumR8iaUKlenFgh0XRPIUeSPlH3A+AW3Z5pg== - dependencies: - css-select "^4.1.3" - dom-converter "^0.2.0" - htmlparser2 "^6.1.0" - lodash "^4.17.21" - strip-ansi "^6.0.1" - require-directory@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" - integrity sha1-jGStX9MNqxyXbiNE/+f3kqam30I= + integrity sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q== require-from-string@^2.0.2: version "2.0.2" @@ -6449,22 +7369,37 @@ resolve-cwd@^3.0.0: dependencies: resolve-from "^5.0.0" +resolve-dir@^1.0.0, resolve-dir@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/resolve-dir/-/resolve-dir-1.0.1.tgz#79a40644c362be82f26effe739c9bb5382046f43" + integrity sha512-R7uiTjECzvOsWSfdM0QKFNBVFcK27aHOUwdvK53BcW8zqnGdYp0Fbj82cy54+2A4P2tFM22J5kRfe1R+lM/1yg== + dependencies: + expand-tilde "^2.0.0" + global-modules "^1.0.0" + +resolve-from@5.0.0, resolve-from@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-5.0.0.tgz#c35225843df8f776df21c57557bc087e9dfdfc69" + integrity sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw== + resolve-from@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-4.0.0.tgz#4abcd852ad32dd7baabfe9b40e00a36db5f392e6" integrity sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g== -resolve-from@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-5.0.0.tgz#c35225843df8f776df21c57557bc087e9dfdfc69" - integrity sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw== +resolve-global@1.0.0, resolve-global@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/resolve-global/-/resolve-global-1.0.0.tgz#a2a79df4af2ca3f49bf77ef9ddacd322dad19255" + integrity sha512-zFa12V4OLtT5XUX/Q4VLvTfBf+Ok0SPc1FNGM/z9ctUdiU618qwKpWnd0CHs3+RqROfyEg/DhuHbMWYqcgljEw== + dependencies: + global-dirs "^0.1.1" resolve.exports@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/resolve.exports/-/resolve.exports-2.0.0.tgz#c1a0028c2d166ec2fbf7d0644584927e76e7400e" integrity sha512-6K/gDlqgQscOlg9fSRpWstA8sYe8rbELsSTNpx+3kTrsVCzvSl0zIvRErM7fdl9ERWDsKnrLnwB+Ne89918XOg== -resolve@^1.10.0, resolve@^1.20.0: +resolve@^1.10.0, resolve@^1.20.0, resolve@^1.22.1: version "1.22.1" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.1.tgz#27cb2ebb53f91abb49470a928bba7558066ac177" integrity sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw== @@ -6473,15 +7408,6 @@ resolve@^1.10.0, resolve@^1.20.0: path-parse "^1.0.7" supports-preserve-symlinks-flag "^1.0.0" -resolve@^1.9.0: - version "1.22.0" - resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.0.tgz#5e0b8c67c15df57a89bdbabe603a002f21731198" - integrity sha512-Hhtrw0nLeSrFQ7phPp4OOcVjLPIeMnRlr5mcnVuMe7M/7eBn98A3hmFRLoFo3DLZkivSYwhRUJTyPyWAk56WLw== - dependencies: - is-core-module "^2.8.1" - path-parse "^1.0.7" - supports-preserve-symlinks-flag "^1.0.0" - restore-cursor@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-3.1.0.tgz#39f67c54b3a7a58cea5236d95cf0034239631f7e" @@ -6490,6 +7416,14 @@ restore-cursor@^3.1.0: onetime "^5.1.0" signal-exit "^3.0.2" +restore-cursor@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/restore-cursor/-/restore-cursor-4.0.0.tgz#519560a4318975096def6e609d44100edaa4ccb9" + integrity sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg== + dependencies: + onetime "^5.1.0" + signal-exit "^3.0.2" + retry@^0.12.0: version "0.12.0" resolved "https://registry.yarnpkg.com/retry/-/retry-0.12.0.tgz#1b42a6266a21f07421d1b0b54b7dc167b01c013b" @@ -6510,27 +7444,53 @@ rfdc@^1.3.0: resolved "https://registry.yarnpkg.com/rfdc/-/rfdc-1.3.0.tgz#d0b7c441ab2720d05dc4cf26e01c89631d9da08b" integrity sha512-V2hovdzFbOi77/WajaSMXk2OLm+xNIeQdMMuB7icj7bk6zi2F8GGAxigcnDFpJHbNyNcgyJDiP+8nOrY5cZGrA== -rimraf@^2.6.3: - version "2.7.1" - resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.7.1.tgz#35797f13a7fdadc566142c29d4f07ccad483e3ec" - integrity sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w== - dependencies: - glob "^7.1.3" - -rimraf@^3.0.0, rimraf@^3.0.2: +rimraf@^3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-3.0.2.tgz#f1a5402ba6220ad52cc1282bac1ae3aa49fd061a" integrity sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA== dependencies: glob "^7.1.3" -ripemd160@^2.0.0, ripemd160@^2.0.1, ripemd160@^2.0.2: - version "2.0.2" - resolved "https://registry.yarnpkg.com/ripemd160/-/ripemd160-2.0.2.tgz#a1c1a6f624751577ba5d07914cbc92850585890c" - integrity sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA== - dependencies: - hash-base "^3.0.0" - inherits "^2.0.1" +rollup-plugin-filesize@10.0.0: + version "10.0.0" + resolved "https://registry.yarnpkg.com/rollup-plugin-filesize/-/rollup-plugin-filesize-10.0.0.tgz#fe5af99e5194fd379f1797b0c87549feaf407f82" + integrity sha512-JAYYhzCcmGjmCzo3LEHSDE3RAPHKIeBdpqRhiyZSv5o/3wFhktUOzYAWg/uUKyEu5dEaVaql6UOmaqHx1qKrZA== + dependencies: + "@babel/runtime" "^7.13.8" + boxen "^5.0.0" + brotli-size "4.0.0" + colors "1.4.0" + filesize "^6.1.0" + gzip-size "^6.0.0" + pacote "^15.1.1" + terser "^5.6.0" + +rollup@4.9.6: + version "4.9.6" + resolved "https://registry.yarnpkg.com/rollup/-/rollup-4.9.6.tgz#4515facb0318ecca254a2ee1315e22e09efc50a0" + integrity sha512-05lzkCS2uASX0CiLFybYfVkwNbKZG5NFQ6Go0VWyogFTXXbR039UVsegViTntkk4OglHBdF54ccApXRRuXRbsg== + dependencies: + "@types/estree" "1.0.5" + optionalDependencies: + "@rollup/rollup-android-arm-eabi" "4.9.6" + "@rollup/rollup-android-arm64" "4.9.6" + "@rollup/rollup-darwin-arm64" "4.9.6" + "@rollup/rollup-darwin-x64" "4.9.6" + "@rollup/rollup-linux-arm-gnueabihf" "4.9.6" + "@rollup/rollup-linux-arm64-gnu" "4.9.6" + "@rollup/rollup-linux-arm64-musl" "4.9.6" + "@rollup/rollup-linux-riscv64-gnu" "4.9.6" + "@rollup/rollup-linux-x64-gnu" "4.9.6" + "@rollup/rollup-linux-x64-musl" "4.9.6" + "@rollup/rollup-win32-arm64-msvc" "4.9.6" + "@rollup/rollup-win32-ia32-msvc" "4.9.6" + "@rollup/rollup-win32-x64-msvc" "4.9.6" + fsevents "~2.3.2" + +run-async@^2.4.0: + version "2.4.1" + resolved "https://registry.yarnpkg.com/run-async/-/run-async-2.4.1.tgz#8440eccf99ea3e70bd409d49aab88e10c189a455" + integrity sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ== run-parallel@^1.1.9: version "1.2.0" @@ -6539,14 +7499,14 @@ run-parallel@^1.1.9: dependencies: queue-microtask "^1.2.2" -rxjs@^7.8.0: +rxjs@^7.5.5: version "7.8.0" resolved "https://registry.yarnpkg.com/rxjs/-/rxjs-7.8.0.tgz#90a938862a82888ff4c7359811a595e14e1e09a4" integrity sha512-F2+gxDshqmIub1KdvZkaEfGDwLNpPvk9Fs6LD/MyQxNgMds/WH9OdDDXOmxUZpME+iSK3rQCctkL0DYyytUqMg== dependencies: tslib "^2.1.0" -safe-buffer@^5.0.1, safe-buffer@^5.1.0, safe-buffer@^5.1.1, safe-buffer@^5.1.2, safe-buffer@^5.2.0, safe-buffer@~5.2.0: +safe-buffer@^5.1.0, safe-buffer@~5.2.0: version "5.2.1" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== @@ -6556,91 +7516,66 @@ safe-buffer@~5.1.0, safe-buffer@~5.1.1: resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g== -safe-regex@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/safe-regex/-/safe-regex-2.1.1.tgz#f7128f00d056e2fe5c11e81a1324dd974aadced2" - integrity sha512-rx+x8AMzKb5Q5lQ95Zoi6ZbJqwCLkqi3XuJXp5P3rT8OEc6sZCJG5AE5dU3lsgRr/F4Bs31jSlVN+j5KrsGu9A== - dependencies: - regexp-tree "~0.1.1" - -"safer-buffer@>= 2.1.2 < 3.0.0", safer-buffer@^2.1.0: +"safer-buffer@>= 2.1.2 < 3", "safer-buffer@>= 2.1.2 < 3.0.0": version "2.1.2" resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== -schema-utils@^3.1.0, schema-utils@^3.1.1: - version "3.1.1" - resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-3.1.1.tgz#bc74c4b6b6995c1d88f76a8b77bea7219e0c8281" - integrity sha512-Y5PQxS4ITlC+EahLuXaY86TXfR7Dc5lw294alXOq86JAHCihAIZfqv8nNCWvaEJvaC51uN9hbLGeV0cFBdH+Fw== - dependencies: - "@types/json-schema" "^7.0.8" - ajv "^6.12.5" - ajv-keywords "^3.5.2" - -secp256k1@^4.0.0: - version "4.0.3" - resolved "https://registry.yarnpkg.com/secp256k1/-/secp256k1-4.0.3.tgz#c4559ecd1b8d3c1827ed2d1b94190d69ce267303" - integrity sha512-NLZVf+ROMxwtEj3Xa562qgv2BK5e2WNmXPiOdVIPLgs6lyTzMvBq0aWTYMI5XCP9jZMVKOcqZLw/Wc4vDkuxhA== - dependencies: - elliptic "^6.5.4" - node-addon-api "^2.0.0" - node-gyp-build "^4.2.0" - -semantic-release@19.0.5: - version "19.0.5" - resolved "https://registry.yarnpkg.com/semantic-release/-/semantic-release-19.0.5.tgz#d7fab4b33fc20f1288eafd6c441e5d0938e5e174" - integrity sha512-NMPKdfpXTnPn49FDogMBi36SiBfXkSOJqCkk0E4iWOY1tusvvgBwqUmxTX1kmlT6kIYed9YwNKD1sfPpqa5yaA== +semantic-release@21.0.1: + version "21.0.1" + resolved "https://registry.yarnpkg.com/semantic-release/-/semantic-release-21.0.1.tgz#f2cb0eb1d0b1883efdac2883ec40342ac5c6ff30" + integrity sha512-UhGxTUXHJQCBFgEQRZszLOHDpMduDSHGq3Q+30Bu+g0GbXh/EW508+kuFHezP5m0mN8xINW8hooiR3dzSV5ZLA== dependencies: "@semantic-release/commit-analyzer" "^9.0.2" "@semantic-release/error" "^3.0.0" "@semantic-release/github" "^8.0.0" - "@semantic-release/npm" "^9.0.0" + "@semantic-release/npm" "^10.0.2" "@semantic-release/release-notes-generator" "^10.0.0" - aggregate-error "^3.0.0" - cosmiconfig "^7.0.0" + aggregate-error "^4.0.1" + cosmiconfig "^8.0.0" debug "^4.0.0" - env-ci "^5.0.0" - execa "^5.0.0" - figures "^3.0.0" - find-versions "^4.0.0" + env-ci "^9.0.0" + execa "^7.0.0" + figures "^5.0.0" + find-versions "^5.1.0" get-stream "^6.0.0" git-log-parser "^1.2.0" - hook-std "^2.0.0" - hosted-git-info "^4.0.0" - lodash "^4.17.21" - marked "^4.0.10" - marked-terminal "^5.0.0" + hook-std "^3.0.0" + hosted-git-info "^6.0.0" + lodash-es "^4.17.21" + marked "^4.1.0" + marked-terminal "^5.1.1" micromatch "^4.0.2" - p-each-series "^2.1.0" - p-reduce "^2.0.0" - read-pkg-up "^7.0.0" + p-each-series "^3.0.0" + p-reduce "^3.0.0" + read-pkg-up "^9.1.0" resolve-from "^5.0.0" semver "^7.3.2" - semver-diff "^3.1.1" + semver-diff "^4.0.0" signale "^1.2.1" - yargs "^16.2.0" + yargs "^17.5.1" -semver-diff@^3.1.1: - version "3.1.1" - resolved "https://registry.yarnpkg.com/semver-diff/-/semver-diff-3.1.1.tgz#05f77ce59f325e00e2706afd67bb506ddb1ca32b" - integrity sha512-GX0Ix/CJcHyB8c4ykpHGIAvLyOwOobtM/8d+TQkAd81/bEjgPHrfba41Vpesr7jX/t8Uh+R3EX9eAS5be+jQYg== +semver-diff@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/semver-diff/-/semver-diff-4.0.0.tgz#3afcf5ed6d62259f5c72d0d5d50dffbdc9680df5" + integrity sha512-0Ju4+6A8iOnpL/Thra7dZsSlOHYAHIeMxfhWQRI1/VLcT3WDBZKKtQt/QkBOsiIN9ZpuvHE6cGZ0x4glCMmfiA== dependencies: - semver "^6.3.0" + semver "^7.3.5" -semver-regex@^3.1.2: - version "3.1.4" - resolved "https://registry.yarnpkg.com/semver-regex/-/semver-regex-3.1.4.tgz#13053c0d4aa11d070a2f2872b6b1e3ae1e1971b4" - integrity sha512-6IiqeZNgq01qGf0TId0t3NvKzSvUsjcpdEO3AQNeIjR6A2+ckTnQlDpl4qu1bjRv0RzN3FP9hzFmws3lKqRWkA== +semver-regex@^4.0.5: + version "4.0.5" + resolved "https://registry.yarnpkg.com/semver-regex/-/semver-regex-4.0.5.tgz#fbfa36c7ba70461311f5debcb3928821eb4f9180" + integrity sha512-hunMQrEy1T6Jr2uEVjrAIqjwWcQTgOAcIM52C8MY1EZSD3DDNft04XzvYKPqjED65bNVVko0YI38nYeEHCX3yw== "semver@2 || 3 || 4 || 5": version "5.7.1" resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7" integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ== -semver@7.x, semver@^7.1.1, semver@^7.2.1, semver@^7.3.4, semver@^7.3.5: - version "7.3.7" - resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.7.tgz#12c5b649afdbf9049707796e22a4028814ce523f" - integrity sha512-QlYTucUYOews+WeEujDoEGziz4K6c47V/Bd+LjSSYcA94p+DmINdf7ncaUinThfvZyu13lN9OY1XDxt8C0Tw0g== +semver@7.5.4, semver@^7.0.0, semver@^7.1.1, semver@^7.1.2, semver@^7.3.2, semver@^7.3.4, semver@^7.3.5, semver@^7.3.7, semver@^7.3.8, semver@^7.5.3, semver@^7.5.4: + version "7.5.4" + resolved "https://registry.yarnpkg.com/semver/-/semver-7.5.4.tgz#483986ec4ed38e1c6c48c34894a9182dbff68a6e" + integrity sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA== dependencies: lru-cache "^6.0.0" @@ -6649,17 +7584,10 @@ semver@^6.0.0, semver@^6.3.0: resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.0.tgz#ee0a64c8af5e8ceea67687b133761e1becbd1d3d" integrity sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw== -semver@^7.0.0, semver@^7.1.2, semver@^7.3.2, semver@^7.3.7: - version "7.3.8" - resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.8.tgz#07a78feafb3f7b32347d725e33de7e2a2df67798" - integrity sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A== - dependencies: - lru-cache "^6.0.0" - -serialize-javascript@^6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-6.0.0.tgz#efae5d88f45d7924141da8b5c3a7a7e663fefeb8" - integrity sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag== +serialize-javascript@^6.0.1: + version "6.0.1" + resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-6.0.1.tgz#b206efb27c3da0b0ab6b52f48d170b7996458e5c" + integrity sha512-owoXEFjWRllis8/M1Q+Cw5k8ZH40e3zhp/ovX+Xr/vi1qj6QesbyXXViFbpNvWvPNAD62SutwEXavefrLJWj7w== dependencies: randombytes "^2.1.0" @@ -6668,21 +7596,6 @@ set-blocking@^2.0.0: resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7" integrity sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw== -sha.js@^2.4.0, sha.js@^2.4.8: - version "2.4.11" - resolved "https://registry.yarnpkg.com/sha.js/-/sha.js-2.4.11.tgz#37a5cf0b81ecbc6943de109ba2960d1b26584ae7" - integrity sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ== - dependencies: - inherits "^2.0.1" - safe-buffer "^5.0.1" - -shallow-clone@^3.0.0: - version "3.0.1" - resolved "https://registry.yarnpkg.com/shallow-clone/-/shallow-clone-3.0.1.tgz#8f2981ad92531f55035b01fb230769a40e02efa3" - integrity sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA== - dependencies: - kind-of "^6.0.2" - shebang-command@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea" @@ -6695,30 +7608,16 @@ shebang-regex@^3.0.0: resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172" integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== -shiki@^0.14.1: - version "0.14.1" - resolved "https://registry.yarnpkg.com/shiki/-/shiki-0.14.1.tgz#9fbe082d0a8aa2ad63df4fbf2ee11ec924aa7ee1" - integrity sha512-+Jz4nBkCBe0mEDqo1eKRcCdjRtrCjozmcbTUjbPTX7OOJfEbTZzlUWlZtGe3Gb5oV1/jnojhG//YZc3rs9zSEw== - dependencies: - ansi-sequence-parser "^1.1.0" - jsonc-parser "^3.2.0" - vscode-oniguruma "^1.7.0" - vscode-textmate "^8.0.0" - -side-channel@^1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.0.4.tgz#efce5c8fdc104ee751b25c58d4290011fa5ea2cf" - integrity sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw== - dependencies: - call-bind "^1.0.0" - get-intrinsic "^1.0.2" - object-inspect "^1.9.0" - signal-exit@^3.0.2, signal-exit@^3.0.3, signal-exit@^3.0.7: version "3.0.7" resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.7.tgz#a9a1767f8af84155114eaabd73f99273c8f59ad9" integrity sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ== +signal-exit@^4.0.1, signal-exit@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-4.1.0.tgz#952188c1cbd546070e2dd20d0f41c0ae0530cb04" + integrity sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw== + signale@^1.2.1: version "1.4.0" resolved "https://registry.yarnpkg.com/signale/-/signale-1.4.0.tgz#c4be58302fb0262ac00fc3d886a7c113759042f1" @@ -6728,6 +7627,26 @@ signale@^1.2.1: figures "^2.0.0" pkg-conf "^2.1.0" +sigstore@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/sigstore/-/sigstore-1.0.0.tgz#3c7a8bbacf99d0f978276bd29bd94911006b72c7" + integrity sha512-e+qfbn/zf1+rCza/BhIA//Awmf0v1pa5HQS8Xk8iXrn9bgytytVLqYD0P7NSqZ6IELTgq+tcDvLPkQjNHyWLNg== + dependencies: + make-fetch-happen "^11.0.1" + tuf-js "^1.0.0" + +sigstore@^2.2.0: + version "2.2.1" + resolved "https://registry.yarnpkg.com/sigstore/-/sigstore-2.2.1.tgz#a0f9f6b7f39aef5d9b3d659cd14b99a502fb44b0" + integrity sha512-OBBSKvmjr4DCyUb+IC2p7wooOCsCNwaqvCilTJVNPo0y8lJl+LsCrfz4LtMwnw3Gn+8frt816wi1+DWZTUCpBQ== + dependencies: + "@sigstore/bundle" "^2.1.1" + "@sigstore/core" "^1.0.0" + "@sigstore/protobuf-specs" "^0.2.1" + "@sigstore/sign" "^2.2.2" + "@sigstore/tuf" "^2.3.0" + "@sigstore/verify" "^1.0.0" + sisteransi@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/sisteransi/-/sisteransi-1.0.5.tgz#134d681297756437cc05ca01370d3a7a571075ed" @@ -6738,23 +7657,10 @@ slash@^3.0.0: resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634" integrity sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q== -slice-ansi@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-3.0.0.tgz#31ddc10930a1b7e0b67b08c96c2f49b77a789787" - integrity sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ== - dependencies: - ansi-styles "^4.0.0" - astral-regex "^2.0.0" - is-fullwidth-code-point "^3.0.0" - -slice-ansi@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-4.0.0.tgz#500e8dd0fd55b05815086255b3195adf2a45fe6b" - integrity sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ== - dependencies: - ansi-styles "^4.0.0" - astral-regex "^2.0.0" - is-fullwidth-code-point "^3.0.0" +slash@^5.1.0: + version "5.1.0" + resolved "https://registry.yarnpkg.com/slash/-/slash-5.1.0.tgz#be3adddcdf09ac38eebe8dcdc7b1a57a75b095ce" + integrity sha512-ZA6oR3T/pEyuqwMgAKT0/hAv8oAXckzbkmR0UkUosQ+Mc4RxGoJkRmwHgHufaenlyAgE1Mxgpdcrf75y6XcnDg== slice-ansi@^5.0.0: version "5.0.0" @@ -6764,11 +7670,24 @@ slice-ansi@^5.0.0: ansi-styles "^6.0.0" is-fullwidth-code-point "^4.0.0" +slice-ansi@^7.0.0: + version "7.1.0" + resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-7.1.0.tgz#cd6b4655e298a8d1bdeb04250a433094b347b9a9" + integrity sha512-bSiSngZ/jWeX93BqeIAbImyTbEihizcwNjFoRUIY/T1wWQsfsm2Vw1agPKylXvQTU7iASGdHhyqRlqQzfz+Htg== + dependencies: + ansi-styles "^6.2.1" + is-fullwidth-code-point "^5.0.0" + smart-buffer@^4.2.0: version "4.2.0" resolved "https://registry.yarnpkg.com/smart-buffer/-/smart-buffer-4.2.0.tgz#6e1d71fa4f18c05f7d0ff216dd16a481d0e8d9ae" integrity sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg== +smob@^1.0.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/smob/-/smob-1.4.0.tgz#ac9751fe54b1fc1fc8286a628d4e7f824273b95a" + integrity sha512-MqR3fVulhjWuRNSMydnTlweu38UhQ0HXM4buStD/S3mc/BzX3CuM9OmhyQpmtYCvoYdl5ris6TI0ZqH355Ymqg== + socks-proxy-agent@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/socks-proxy-agent/-/socks-proxy-agent-7.0.0.tgz#dc069ecf34436621acb41e3efa66ca1b5fed15b6" @@ -6778,6 +7697,15 @@ socks-proxy-agent@^7.0.0: debug "^4.3.3" socks "^2.6.2" +socks-proxy-agent@^8.0.1: + version "8.0.2" + resolved "https://registry.yarnpkg.com/socks-proxy-agent/-/socks-proxy-agent-8.0.2.tgz#5acbd7be7baf18c46a3f293a840109a430a640ad" + integrity sha512-8zuqoLv1aP/66PHF5TqwJ7Czm3Yv32urJQHrVyhD7mmA6d61Zv8cIXQYPTWwmg6qlupnPvs/QKDmfa4P/qct2g== + dependencies: + agent-base "^7.0.2" + debug "^4.3.4" + socks "^2.7.1" + socks@^2.6.2: version "2.7.1" resolved "https://registry.yarnpkg.com/socks/-/socks-2.7.1.tgz#d8e651247178fde79c0663043e07240196857d55" @@ -6786,6 +7714,14 @@ socks@^2.6.2: ip "^2.0.0" smart-buffer "^4.2.0" +socks@^2.7.1: + version "2.7.3" + resolved "https://registry.yarnpkg.com/socks/-/socks-2.7.3.tgz#7d8a75d7ce845c0a96f710917174dba0d543a785" + integrity sha512-vfuYK48HXCTFD03G/1/zkIls3Ebr2YNa4qU9gHDZdblHLiqhJrJGkY3+0Nx0JpN9qBhJbVObc1CNciT1bIZJxw== + dependencies: + ip-address "^9.0.5" + smart-buffer "^4.2.0" + source-map-support@0.5.13: version "0.5.13" resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.13.tgz#31b24a9c2e73c2de85066c0feb7d44767ed52932" @@ -6802,7 +7738,7 @@ source-map-support@~0.5.20: buffer-from "^1.0.0" source-map "^0.6.0" -source-map@^0.6.0, source-map@^0.6.1, source-map@~0.6.0: +source-map@^0.6.0, source-map@^0.6.1: version "0.6.1" resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== @@ -6825,7 +7761,7 @@ spdx-exceptions@^2.1.0: resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz#3f28ce1a77a00372683eade4a433183527a2163d" integrity sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A== -spdx-expression-parse@^3.0.0: +spdx-expression-parse@^3.0.0, spdx-expression-parse@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz#cf70f50482eefdc98e3ce0a6833e4a53ceeba679" integrity sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q== @@ -6838,13 +7774,18 @@ spdx-license-ids@^3.0.0: resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-3.0.12.tgz#69077835abe2710b65f03969898b6637b505a779" integrity sha512-rr+VVSXtRhO4OHbXUiAF7xW3Bo9DuuF6C5jH+q/x15j2jniycgKbxU09Hr0WqlSLUs4i4ltHGXqTe7VHclYWyA== -split2@^3.0.0: +split2@^3.0.0, split2@^3.2.2: version "3.2.2" resolved "https://registry.yarnpkg.com/split2/-/split2-3.2.2.tgz#bf2cf2a37d838312c249c89206fd7a17dd12365f" integrity sha512-9NThjpgZnifTkJpzTZ7Eue85S49QwpNhZTq6GRJwObb6jnLFNGB7Qm73V5HewTROPyxD0C29xqmaI68bQtV+hg== dependencies: readable-stream "^3.0.0" +split2@^4.0.0: + version "4.2.0" + resolved "https://registry.yarnpkg.com/split2/-/split2-4.2.0.tgz#c9c5920904d148bab0b9f67145f245a86aadbfa4" + integrity sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg== + split2@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/split2/-/split2-1.0.0.tgz#52e2e221d88c75f9a73f90556e263ff96772b314" @@ -6859,12 +7800,31 @@ split@^1.0.0: dependencies: through "2" +sprintf-js@^1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.1.3.tgz#4914b903a2f8b685d17fdf78a70e917e872e444a" + integrity sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA== + sprintf-js@~1.0.2: version "1.0.3" resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" - integrity sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw= + integrity sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g== + +ssri@^10.0.0, ssri@^10.0.1: + version "10.0.1" + resolved "https://registry.yarnpkg.com/ssri/-/ssri-10.0.1.tgz#c61f85894bbc6929fc3746f05e31cf5b44c030d5" + integrity sha512-WVy6di9DlPOeBWEjMScpNipeSX2jIZBGEn5Uuo8Q7aIuFEuDX0pw8RxcOjlD1TWP4obi24ki7m/13+nFpcbXrw== + dependencies: + minipass "^4.0.0" + +ssri@^10.0.5: + version "10.0.5" + resolved "https://registry.yarnpkg.com/ssri/-/ssri-10.0.5.tgz#e49efcd6e36385196cb515d3a2ad6c3f0265ef8c" + integrity sha512-bSf16tAFkGeRlUNDjXu8FzaMQt6g2HZJrun7mtMbIPOddxt3GLMSz5VWUWcqTJUPfLEaDIepGxv+bYQW49596A== + dependencies: + minipass "^7.0.3" -ssri@^9.0.0, ssri@^9.0.1: +ssri@^9.0.0: version "9.0.1" resolved "https://registry.yarnpkg.com/ssri/-/ssri-9.0.1.tgz#544d4c357a8d7b71a19700074b6883fcb4eae057" integrity sha512-o57Wcn66jMQvfHG1FlYbWeZWW/dHZhJXjpIcTfXldXEk5nz5lStPo3mK0OJQfGR3RbZUlbISexbljkJzuEj/8Q== @@ -6878,19 +7838,6 @@ stack-utils@^2.0.3: dependencies: escape-string-regexp "^2.0.0" -store2@2.14.2: - version "2.14.2" - resolved "https://registry.yarnpkg.com/store2/-/store2-2.14.2.tgz#56138d200f9fe5f582ad63bc2704dbc0e4a45068" - integrity sha512-siT1RiqlfQnGqgT/YzXVUNsom9S0H1OX+dpdGN1xkyYATo4I6sep5NmsRD/40s3IIOvlCq6akxkqG82urIZW1w== - -stream-browserify@3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/stream-browserify/-/stream-browserify-3.0.0.tgz#22b0a2850cdf6503e73085da1fc7b7d0c2122f2f" - integrity sha512-H73RAHsVBapbim0tU2JwwOiXUj+fikfiaoYAKHF3VJfA0pe2BCzkhAHBlLG6REzE+2WNZcxOXjK7lkso+9euLA== - dependencies: - inherits "~2.0.4" - readable-stream "^3.5.0" - stream-combiner2@~1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/stream-combiner2/-/stream-combiner2-1.1.1.tgz#fb4d8a1420ea362764e21ad4780397bebcb41cbe" @@ -6899,10 +7846,10 @@ stream-combiner2@~1.1.1: duplexer2 "~0.1.0" readable-stream "^2.0.2" -string-argv@^0.3.1: - version "0.3.1" - resolved "https://registry.yarnpkg.com/string-argv/-/string-argv-0.3.1.tgz#95e2fbec0427ae19184935f816d74aaa4c5c19da" - integrity sha512-a1uQGz7IyVy9YwhqjZIZu1c8JO8dNIe20xBmSS6qu9kv++k3JGzCVmprbNN5Kn+BgzD5E7YYwg1CcjuJMRNsvg== +string-argv@0.3.2: + version "0.3.2" + resolved "https://registry.yarnpkg.com/string-argv/-/string-argv-0.3.2.tgz#2b6d0ef24b656274d957d54e0a4bbf6153dc02b6" + integrity sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q== string-length@^4.0.1: version "4.0.2" @@ -6912,7 +7859,7 @@ string-length@^4.0.1: char-regex "^1.0.2" strip-ansi "^6.0.0" -"string-width@^1.0.2 || 2 || 3 || 4", string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3: +"string-width-cjs@npm:string-width@^4.2.0", "string-width@^1.0.2 || 2 || 3 || 4", string-width@^4.0.0, string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.2, string-width@^4.2.3: version "4.2.3" resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== @@ -6921,7 +7868,7 @@ string-length@^4.0.1: is-fullwidth-code-point "^3.0.0" strip-ansi "^6.0.1" -string-width@^5.0.0: +string-width@^5.0.1, string-width@^5.1.2: version "5.1.2" resolved "https://registry.yarnpkg.com/string-width/-/string-width-5.1.2.tgz#14f8daec6d81e7221d2a357e668cab73bdbca794" integrity sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA== @@ -6930,23 +7877,14 @@ string-width@^5.0.0: emoji-regex "^9.2.2" strip-ansi "^7.0.1" -string.prototype.trimend@^1.0.4: - version "1.0.5" - resolved "https://registry.yarnpkg.com/string.prototype.trimend/-/string.prototype.trimend-1.0.5.tgz#914a65baaab25fbdd4ee291ca7dde57e869cb8d0" - integrity sha512-I7RGvmjV4pJ7O3kdf+LXFpVfdNOxtCW/2C8f6jNiW4+PQchwxkCDzlk1/7p+Wl4bqFIZeF47qAHXLuHHWKAxog== - dependencies: - call-bind "^1.0.2" - define-properties "^1.1.4" - es-abstract "^1.19.5" - -string.prototype.trimstart@^1.0.4: - version "1.0.5" - resolved "https://registry.yarnpkg.com/string.prototype.trimstart/-/string.prototype.trimstart-1.0.5.tgz#5466d93ba58cfa2134839f81d7f42437e8c01fef" - integrity sha512-THx16TJCGlsN0o6dl2o6ncWUsdgnLRSA23rRE5pyGBw/mLr3Ej/R2LaqCtgP8VNMGZsvMWnf9ooZPyY2bHvUFg== +string-width@^7.0.0: + version "7.1.0" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-7.1.0.tgz#d994252935224729ea3719c49f7206dc9c46550a" + integrity sha512-SEIJCWiX7Kg4c129n48aDRwLbFb2LJmXXFrWBG4NGaRtMQ3myKPKbwrD1BKqQn74oCoNMBVrfDEr5M9YxCsrkw== dependencies: - call-bind "^1.0.2" - define-properties "^1.1.4" - es-abstract "^1.19.5" + emoji-regex "^10.3.0" + get-east-asian-width "^1.0.0" + strip-ansi "^7.1.0" string_decoder@^1.1.1: version "1.3.0" @@ -6962,30 +7900,30 @@ string_decoder@~1.1.1: dependencies: safe-buffer "~5.1.0" -strip-ansi@^6.0.0, strip-ansi@^6.0.1: +"strip-ansi-cjs@npm:strip-ansi@^6.0.1", strip-ansi@^6.0.0, strip-ansi@^6.0.1: version "6.0.1" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== dependencies: ansi-regex "^5.0.1" -strip-ansi@^7.0.1: - version "7.0.1" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.0.1.tgz#61740a08ce36b61e50e65653f07060d000975fb2" - integrity sha512-cXNxvT8dFNRVfhVME3JAe98mkXDYN2O1l7jmcwMnOslDeESg1rF/OZMtK0nRAhiari1unG5cD4jG3rapUAkLbw== +strip-ansi@^7.0.1, strip-ansi@^7.1.0: + version "7.1.0" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.1.0.tgz#d5b6568ca689d8561370b0707685d22434faff45" + integrity sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ== dependencies: ansi-regex "^6.0.1" +strip-bom@4.0.0, strip-bom@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-4.0.0.tgz#9c3505c1db45bcedca3d9cf7a16f5c5aa3901878" + integrity sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w== + strip-bom@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3" integrity sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA== -strip-bom@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-4.0.0.tgz#9c3505c1db45bcedca3d9cf7a16f5c5aa3901878" - integrity sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w== - strip-final-newline@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/strip-final-newline/-/strip-final-newline-2.0.0.tgz#89b852fb2fcbe936f6f4b3187afb0a12c1ab58ad" @@ -7003,7 +7941,7 @@ strip-indent@^3.0.0: dependencies: min-indent "^1.0.0" -strip-json-comments@^3.1.0, strip-json-comments@^3.1.1: +strip-json-comments@3.1.1, strip-json-comments@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006" integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== @@ -7034,6 +7972,11 @@ supports-color@^8.0.0: dependencies: has-flag "^4.0.0" +supports-color@^9.4.0: + version "9.4.0" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-9.4.0.tgz#17bfcf686288f531db3dea3215510621ccb55954" + integrity sha512-VL+lNrEoIXww1coLPOmiEmK/0sGigko5COxI09KzHc2VJXJsQ37UaQ+8quuxjDeA7+KnLGTWRyOXSLLR2Wb4jw== + supports-hyperlinks@^2.2.0: version "2.3.0" resolved "https://registry.yarnpkg.com/supports-hyperlinks/-/supports-hyperlinks-2.3.0.tgz#3943544347c1ff90b15effb03fc14ae45ec10624" @@ -7047,28 +7990,7 @@ supports-preserve-symlinks-flag@^1.0.0: resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09" integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w== -synchronous-promise@^2.0.15: - version "2.0.15" - resolved "https://registry.yarnpkg.com/synchronous-promise/-/synchronous-promise-2.0.15.tgz#07ca1822b9de0001f5ff73595f3d08c4f720eb8e" - integrity sha512-k8uzYIkIVwmT+TcglpdN50pS2y1BDcUnBPK9iJeGu0Pl1lOI8pD6wtzgw91Pjpe+RxtTncw32tLxs/R0yNL2Mg== - -table@^6.0.9: - version "6.8.0" - resolved "https://registry.yarnpkg.com/table/-/table-6.8.0.tgz#87e28f14fa4321c3377ba286f07b79b281a3b3ca" - integrity sha512-s/fitrbVeEyHKFa7mFdkuQMWlH1Wgw/yEXMt5xACT4ZpzWFluehAxRtUUQKPuWhaLAWhFcVx6w3oC8VKaUfPGA== - dependencies: - ajv "^8.0.1" - lodash.truncate "^4.4.2" - slice-ansi "^4.0.0" - string-width "^4.2.3" - strip-ansi "^6.0.1" - -tapable@^2.0.0, tapable@^2.1.1, tapable@^2.2.0: - version "2.2.1" - resolved "https://registry.yarnpkg.com/tapable/-/tapable-2.2.1.tgz#1967a73ef4060a82f12ab96af86d52fdb76eeca0" - integrity sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ== - -tar@^6.1.0, tar@^6.1.11, tar@^6.1.2: +tar@^6.1.11, tar@^6.1.13, tar@^6.1.2: version "6.1.13" resolved "https://registry.yarnpkg.com/tar/-/tar-6.1.13.tgz#46e22529000f612180601a6fe0680e7da508847b" integrity sha512-jdIBIN6LTIe2jqzay/2vtYLlBHa3JF42ot3h1dW8Q0PaAG4v8rm0cvpVePtau5C6OKXGGcgO9q2AMNSWxiLqKw== @@ -7080,37 +8002,47 @@ tar@^6.1.0, tar@^6.1.11, tar@^6.1.2: mkdirp "^1.0.3" yallist "^4.0.0" +tar@^6.2.0: + version "6.2.0" + resolved "https://registry.yarnpkg.com/tar/-/tar-6.2.0.tgz#b14ce49a79cb1cd23bc9b016302dea5474493f73" + integrity sha512-/Wo7DcT0u5HUV486xg675HtjNd3BXZ6xDbzsCUZPt5iw8bTQ63bP0Raut3mvro9u+CUyq7YQd8Cx55fsZXxqLQ== + dependencies: + chownr "^2.0.0" + fs-minipass "^2.0.0" + minipass "^5.0.0" + minizlib "^2.1.1" + mkdirp "^1.0.3" + yallist "^4.0.0" + temp-dir@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/temp-dir/-/temp-dir-2.0.0.tgz#bde92b05bdfeb1516e804c9c00ad45177f31321e" integrity sha512-aoBAniQmmwtcKp/7BzsH8Cxzv8OL736p7v1ihGb5e9DJ9kTwGWHrQrVB5+lfVDzfGrdRzXch+ig7LHaY1JTOrg== -tempy@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/tempy/-/tempy-1.0.1.tgz#30fe901fd869cfb36ee2bd999805aa72fbb035de" - integrity sha512-biM9brNqxSc04Ee71hzFbryD11nX7VPhQQY32AdDmjFvodsRFz/3ufeoTZ6uYkRFfGo188tENcASNs3vTdsM0w== +tempy@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/tempy/-/tempy-3.0.0.tgz#a6c0a15f5534a820e92c3e1369f1c1e87ebd6b68" + integrity sha512-B2I9X7+o2wOaW4r/CWMkpOO9mdiTRCxXNgob6iGvPmfPWgH/KyUD6Uy5crtWBxIBe3YrNZKR2lSzv1JJKWD4vA== dependencies: - del "^6.0.0" - is-stream "^2.0.0" + is-stream "^3.0.0" temp-dir "^2.0.0" - type-fest "^0.16.0" - unique-string "^2.0.0" + type-fest "^2.12.2" + unique-string "^3.0.0" -terser-webpack-plugin@5.3.6, terser-webpack-plugin@^5.1.3: - version "5.3.6" - resolved "https://registry.yarnpkg.com/terser-webpack-plugin/-/terser-webpack-plugin-5.3.6.tgz#5590aec31aa3c6f771ce1b1acca60639eab3195c" - integrity sha512-kfLFk+PoLUQIbLmB1+PZDMRSZS99Mp+/MHqDNmMA6tOItzRt+Npe3E+fsMs5mfcM0wCtrrdU387UnV+vnSffXQ== +terser@^5.17.4: + version "5.19.4" + resolved "https://registry.yarnpkg.com/terser/-/terser-5.19.4.tgz#941426fa482bf9b40a0308ab2b3cd0cf7c775ebd" + integrity sha512-6p1DjHeuluwxDXcuT9VR8p64klWJKo1ILiy19s6C9+0Bh2+NWTX6nD9EPppiER4ICkHDVB1RkVpin/YW2nQn/g== dependencies: - "@jridgewell/trace-mapping" "^0.3.14" - jest-worker "^27.4.5" - schema-utils "^3.1.1" - serialize-javascript "^6.0.0" - terser "^5.14.1" + "@jridgewell/source-map" "^0.3.3" + acorn "^8.8.2" + commander "^2.20.0" + source-map-support "~0.5.20" -terser@^5.10.0, terser@^5.14.1: - version "5.14.2" - resolved "https://registry.yarnpkg.com/terser/-/terser-5.14.2.tgz#9ac9f22b06994d736174f4091aa368db896f1c10" - integrity sha512-oL0rGeM/WFQCUd0y2QrWxYnq7tfSuKBiqTjRPWrRgB46WD/kiwHwF8T23z78H6Q6kGCuuHcPB+KULHRdxvVGQA== +terser@^5.6.0: + version "5.16.4" + resolved "https://registry.yarnpkg.com/terser/-/terser-5.16.4.tgz#51284b440b93242291a98f2a9903c024cfb70e6e" + integrity sha512-5yEGuZ3DZradbogeYQ1NaGz7rXVBDWujWlx1PT8efXO6Txn+eWbfKqB2bTDVmFXmePFkoLU6XI8UektMIEA0ug== dependencies: "@jridgewell/source-map" "^0.3.2" acorn "^8.5.0" @@ -7131,10 +8063,15 @@ text-extensions@^1.0.0: resolved "https://registry.yarnpkg.com/text-extensions/-/text-extensions-1.9.0.tgz#1853e45fee39c945ce6f6c36b2d659b5aabc2a26" integrity sha512-wiBrwC1EhBelW12Zy26JeOUkQ5mRu+5o8rpsJk5+2t+Y5vE7e842qtZDQ2g1NpX/29HdyFeJ4nSIhI47ENSxlQ== +text-extensions@^2.0.0: + version "2.4.0" + resolved "https://registry.yarnpkg.com/text-extensions/-/text-extensions-2.4.0.tgz#a1cfcc50cf34da41bfd047cc744f804d1680ea34" + integrity sha512-te/NtwBwfiNRLf9Ijqx3T0nlqZiQ2XrrtBvu+cLL8ZRrGkO0NHTug8MYFKyoSrv/sHTaSKfilUkizV6XhxMJ3g== + text-table@^0.2.0, text-table@~0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4" - integrity sha1-f17oI66AUgfACvLfSoTsP8+lcLQ= + integrity sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw== through2@^4.0.0: version "4.0.2" @@ -7151,7 +8088,7 @@ through2@~2.0.0: readable-stream "~2.3.6" xtend "~4.0.1" -through@2, "through@>=2.2.7 <3", through@^2.3.8: +through@2, "through@>=2.2.7 <3", through@^2.3.6: version "2.3.8" resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" integrity sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg== @@ -7161,6 +8098,13 @@ tiny-relative-date@^1.3.0: resolved "https://registry.yarnpkg.com/tiny-relative-date/-/tiny-relative-date-1.3.0.tgz#fa08aad501ed730f31cc043181d995c39a935e07" integrity sha512-MOQHpzllWxDCHHaDno30hhLfbouoYlOI8YlMNtvKe1zXbjEVhbcEovQxvZrPvtiYW630GQDoMMarCnjfyfHA+A== +tmp@^0.0.33: + version "0.0.33" + resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.0.33.tgz#6d34335889768d21b2bcda0aa277ced3b1bfadf9" + integrity sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw== + dependencies: + os-tmpdir "~1.0.2" + tmpl@1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/tmpl/-/tmpl-1.0.5.tgz#8683e0b902bb9c20c4f726e3c0b69f36518c07cc" @@ -7169,7 +8113,7 @@ tmpl@1.0.5: to-fast-properties@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/to-fast-properties/-/to-fast-properties-2.0.0.tgz#dc5e698cbd079265bc73e0377681a4e4e83f616e" - integrity sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4= + integrity sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog== to-regex-range@^5.0.1: version "5.0.1" @@ -7188,20 +8132,25 @@ traverse@~0.6.6: resolved "https://registry.yarnpkg.com/traverse/-/traverse-0.6.7.tgz#46961cd2d57dd8706c36664acde06a248f1173fe" integrity sha512-/y956gpUo9ZNCb99YjxG7OaslxZWHfCHAUUfshwqOXmxUIvqLjVO581BT+gM59+QV9tFe6/CGG53tsA1Y7RSdg== -treeverse@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/treeverse/-/treeverse-2.0.0.tgz#036dcef04bc3fd79a9b79a68d4da03e882d8a9ca" - integrity sha512-N5gJCkLu1aXccpOTtqV6ddSEi6ZmGkh3hjmbu1IjcavJK4qyOVQmi0myQKM7z5jVGmD68SJoliaVrMmVObhj6A== +treeverse@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/treeverse/-/treeverse-3.0.0.tgz#dd82de9eb602115c6ebd77a574aae67003cb48c8" + integrity sha512-gcANaAnd2QDZFmHFEOF4k7uc1J/6a6z3DJMd/QwEyxLoKGiptJRwid582r7QIsFlFMIZ3SnxfS52S4hm2DHkuQ== trim-newlines@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/trim-newlines/-/trim-newlines-3.0.1.tgz#260a5d962d8b752425b32f3a7db0dcacd176c144" integrity sha512-c1PTsA3tYrIsLGkJkzHF+w9F2EyxfXGo4UyJc4pFL++FMjnq0HJS69T3M7d//gKrFKwy429bouPescbjecU+Zw== -ts-jest@29.0.5: - version "29.0.5" - resolved "https://registry.yarnpkg.com/ts-jest/-/ts-jest-29.0.5.tgz#c5557dcec8fe434fcb8b70c3e21c6b143bfce066" - integrity sha512-PL3UciSgIpQ7f6XjVOmbi96vmDHUqAyqDr8YxzopDqX3kfgYtX1cuNeBjP+L9sFXi6nzsGGA6R3fP3DDDJyrxA== +ts-api-utils@^1.0.1: + version "1.0.3" + resolved "https://registry.yarnpkg.com/ts-api-utils/-/ts-api-utils-1.0.3.tgz#f12c1c781d04427313dbac808f453f050e54a331" + integrity sha512-wNMeqtMz5NtwpT/UZGY5alT+VoKdSsOOP/kqHFcUW1P/VRhH2wJ48+DN2WwUliNbQ976ETwDL0Ifd2VVvgonvg== + +ts-jest@29.1.2: + version "29.1.2" + resolved "https://registry.yarnpkg.com/ts-jest/-/ts-jest-29.1.2.tgz#7613d8c81c43c8cb312c6904027257e814c40e09" + integrity sha512-br6GJoH/WUX4pu7FbZXuWGKGNDuU7b8Uj77g/Sp7puZV6EXzuByl6JrECvm0MzVzSTkSHWTihsXt+5XYER5b+g== dependencies: bs-logger "0.x" fast-json-stable-stringify "2.x" @@ -7209,40 +8158,54 @@ ts-jest@29.0.5: json5 "^2.2.3" lodash.memoize "4.x" make-error "1.x" - semver "7.x" + semver "^7.5.3" yargs-parser "^21.0.1" -ts-loader@9.4.2: - version "9.4.2" - resolved "https://registry.yarnpkg.com/ts-loader/-/ts-loader-9.4.2.tgz#80a45eee92dd5170b900b3d00abcfa14949aeb78" - integrity sha512-OmlC4WVmFv5I0PpaxYb+qGeGOdm5giHU7HwDDUjw59emP2UYMHy9fFSDcYgSNoH8sXcj4hGCSEhlDZ9ULeDraA== - dependencies: - chalk "^4.1.0" - enhanced-resolve "^5.0.0" - micromatch "^4.0.0" - semver "^7.3.4" - -tslib@2.4.0, tslib@^2.0.3: +ts-node@10.9.2, ts-node@^10.8.1: + version "10.9.2" + resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-10.9.2.tgz#70f021c9e185bccdca820e26dc413805c101c71f" + integrity sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ== + dependencies: + "@cspotcode/source-map-support" "^0.8.0" + "@tsconfig/node10" "^1.0.7" + "@tsconfig/node12" "^1.0.7" + "@tsconfig/node14" "^1.0.0" + "@tsconfig/node16" "^1.0.2" + acorn "^8.4.1" + acorn-walk "^8.1.1" + arg "^4.1.0" + create-require "^1.1.0" + diff "^4.0.1" + make-error "^1.1.1" + v8-compile-cache-lib "^3.0.1" + yn "3.1.1" + +tslib@2.4.0: version "2.4.0" resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.4.0.tgz#7cecaa7f073ce680a05847aa77be941098f36dc3" integrity sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ== -tslib@^1.8.1: - version "1.14.1" - resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00" - integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg== - tslib@^2.1.0: version "2.5.0" resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.5.0.tgz#42bfed86f5787aeb41d031866c8f402429e0fddf" integrity sha512-336iVw3rtn2BUK7ORdIAHTyxHGRIHVReokCR3XjbckJMK7ms8FysBfhLR8IXnAgy7T0PTPNBWKiH514FOW/WSg== -tsutils@^3.21.0: - version "3.21.0" - resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-3.21.0.tgz#b48717d394cea6c1e096983eed58e9d61715b623" - integrity sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA== +tuf-js@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/tuf-js/-/tuf-js-1.1.0.tgz#25dd680bce9e3819e1fe4640d85186f862efb827" + integrity sha512-Tsqlm419OAlrkCE6rsf1WuPvww44vfK1ZHz+Uq9Mpq5JiV5qnJ9LLItvsbM9OipIIeSG3rydVBS4BmD40ts2uA== + dependencies: + "@tufjs/models" "1.0.0" + make-fetch-happen "^11.0.1" + +tuf-js@^2.2.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/tuf-js/-/tuf-js-2.2.0.tgz#4daaa8620ba7545501d04dfa933c98abbcc959b9" + integrity sha512-ZSDngmP1z6zw+FIkIBjvOp/II/mIub/O7Pp12j1WNsiCpg5R5wAc//i555bBQsE44O94btLt0xM/Zr2LQjwdCg== dependencies: - tslib "^1.8.1" + "@tufjs/models" "2.0.0" + debug "^4.3.4" + make-fetch-happen "^13.0.0" type-check@^0.4.0, type-check@~0.4.0: version "0.4.0" @@ -7256,11 +8219,6 @@ type-detect@4.0.8: resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c" integrity sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g== -type-fest@^0.16.0: - version "0.16.0" - resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.16.0.tgz#3240b891a78b0deae910dbeb86553e552a148860" - integrity sha512-eaBzG6MxNzEn9kiwvtre90cXaNLkmadMWa1zQMs3XORCXNbsH/OewwbxC5ia9dCxIxnTAsSxXJaa/p5y8DlvJg== - type-fest@^0.18.0: version "0.18.1" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.18.1.tgz#db4bc151a4a2cf4eebf9add5db75508db6cc841f" @@ -7286,55 +8244,50 @@ type-fest@^0.8.1: resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.8.1.tgz#09e249ebde851d3b1e48d27c105444667f17b83d" integrity sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA== -type-fest@^1.0.2: +type-fest@^1.0.1, type-fest@^1.0.2: version "1.4.0" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-1.4.0.tgz#e9fb813fe3bf1744ec359d55d1affefa76f14be1" integrity sha512-yGSza74xk0UG8k+pLh5oeoYirvIiWo5t0/o3zHHAO2tRDiZcxWP7fywNlXhqb6/r6sWvwi+RsyQMWhVLe4BVuA== -typedoc-plugin-external-module-name@4.0.6: - version "4.0.6" - resolved "https://registry.yarnpkg.com/typedoc-plugin-external-module-name/-/typedoc-plugin-external-module-name-4.0.6.tgz#bfc13260267c35a7bd5282d7e0a8b7cddb94c575" - integrity sha512-WqJW5gbfeQD7VA96p5eRFkVlPPGXfpaAo7M/sNOeBwSBTRylKYX15kAVaGP6iM/VhXtDagTMyKhwG97sENfKHA== - dependencies: - lodash "^4.1.2" - semver "^7.1.1" +type-fest@^2.0.0, type-fest@^2.12.2, type-fest@^2.5.0: + version "2.19.0" + resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-2.19.0.tgz#88068015bb33036a598b952e55e9311a60fd3a9b" + integrity sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA== -typedoc-plugin-markdown@3.14.0: - version "3.14.0" - resolved "https://registry.yarnpkg.com/typedoc-plugin-markdown/-/typedoc-plugin-markdown-3.14.0.tgz#17b99ee3ab0d21046d253f185f7669e80d0d7891" - integrity sha512-UyQLkLRkfTFhLdhSf3RRpA3nNInGn+k6sll2vRXjflaMNwQAAiB61SYbisNZTg16t4K1dt1bPQMMGLrxS0GZ0Q== - dependencies: - handlebars "^4.7.7" +type-fest@^3.0.0: + version "3.13.1" + resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-3.13.1.tgz#bb744c1f0678bea7543a2d1ec24e83e68e8c8706" + integrity sha512-tLq3bSNx+xSpwvAJnzrK0Ep5CLNWjvFTOp71URMaAEWBfRb9nnJiBoUe0tF8bI4ZFO3omgBR6NvnbzVUT3Ly4g== -typedoc@0.23.26: - version "0.23.26" - resolved "https://registry.yarnpkg.com/typedoc/-/typedoc-0.23.26.tgz#ae082683698bad68757d8fe619242a56d6b5bf36" - integrity sha512-5m4KwR5tOLnk0OtMaRn9IdbeRM32uPemN9kur7YK9wFqx8U0CYrvO9aVq6ysdZSV1c824BTm+BuQl2Ze/k1HtA== - dependencies: - lunr "^2.3.9" - marked "^4.2.12" - minimatch "^7.1.3" - shiki "^0.14.1" +type-fest@^4.6.0, type-fest@^4.7.1: + version "4.10.2" + resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-4.10.2.tgz#3abdb144d93c5750432aac0d73d3e85fcab45738" + integrity sha512-anpAG63wSpdEbLwOqH8L84urkL6PiVIov3EMmgIhhThevh9aiMQov+6Btx0wldNcvm4wV+e2/Rt1QdDwKHFbHw== + +typescript@5.3.3, "typescript@^4.6.4 || ^5.0.0": + version "5.3.3" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.3.3.tgz#b3ce6ba258e72e6305ba66f5c9b452aaee3ffe37" + integrity sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw== -typescript@4.9.5: +typescript@^4.6.4: version "4.9.5" resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.9.5.tgz#095979f9bcc0d09da324d58d03ce8f8374cbe65a" integrity sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g== uglify-js@^3.1.4: - version "3.15.4" - resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-3.15.4.tgz#fa95c257e88f85614915b906204b9623d4fa340d" - integrity sha512-vMOPGDuvXecPs34V74qDKk4iJ/SN4vL3Ow/23ixafENYvtrNvtbcgUeugTcUGRGsOF/5fU8/NYSL5Hyb3l1OJA== + version "3.17.4" + resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-3.17.4.tgz#61678cf5fa3f5b7eb789bb345df29afb8257c22c" + integrity sha512-T9q82TJI9e/C1TAxYvfb16xO120tMVFZrGA3f9/P4424DNu6ypK103y0GPFVa17yotwSyZW5iYXgjYHkGrJW/g== -unbox-primitive@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/unbox-primitive/-/unbox-primitive-1.0.2.tgz#29032021057d5e6cdbd08c5129c226dff8ed6f9e" - integrity sha512-61pPlCD9h51VoreyJ0BReideM3MDKMKnh6+V9L08331ipq6Q8OFXZYiqP6n/tbHx4s5I9uRhcye6BrbkizkBDw== - dependencies: - call-bind "^1.0.2" - has-bigints "^1.0.2" - has-symbols "^1.0.3" - which-boxed-primitive "^1.0.2" +undici-types@~5.26.4: + version "5.26.5" + resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-5.26.5.tgz#bcd539893d00b56e964fd2657a4866b221a65617" + integrity sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA== + +unicorn-magic@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/unicorn-magic/-/unicorn-magic-0.1.0.tgz#1bb9a51c823aaf9d73a8bfcd3d1a23dde94b0ce4" + integrity sha512-lRfVq8fE8gz6QMBuDM6a+LO3IAzTi05H6gCVaUpir2E1Rwpo4ZUog45KpNXKC/Mn3Yb9UDuHumeFTo9iV/D9FQ== unique-filename@^2.0.0: version "2.0.1" @@ -7343,6 +8296,13 @@ unique-filename@^2.0.0: dependencies: unique-slug "^3.0.0" +unique-filename@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/unique-filename/-/unique-filename-3.0.0.tgz#48ba7a5a16849f5080d26c760c86cf5cf05770ea" + integrity sha512-afXhuC55wkAmZ0P18QsVE6kp8JaxrEokN2HGIoIVv2ijHQd419H0+6EigAFcIzXeMIkcIkNBpB3L/DXB3cTS/g== + dependencies: + unique-slug "^4.0.0" + unique-slug@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/unique-slug/-/unique-slug-3.0.0.tgz#6d347cf57c8a7a7a6044aabd0e2d74e4d76dc7c9" @@ -7350,12 +8310,19 @@ unique-slug@^3.0.0: dependencies: imurmurhash "^0.1.4" -unique-string@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/unique-string/-/unique-string-2.0.0.tgz#39c6451f81afb2749de2b233e3f7c5e8843bd89d" - integrity sha512-uNaeirEPvpZWSgzwsPGtU2zVSTrn/8L5q/IexZmH0eH6SA73CmAA5U4GwORTxQAZs95TAXLNqeLoPPNO5gZfWg== +unique-slug@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/unique-slug/-/unique-slug-4.0.0.tgz#6bae6bb16be91351badd24cdce741f892a6532e3" + integrity sha512-WrcA6AyEfqDX5bWige/4NQfPZMtASNVxdmWR76WESYQVAACSgWcR6e9i0mofqqBxYFtL4oAxPIptY73/0YE1DQ== + dependencies: + imurmurhash "^0.1.4" + +unique-string@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/unique-string/-/unique-string-3.0.0.tgz#84a1c377aff5fd7a8bc6b55d8244b2bd90d75b9a" + integrity sha512-VGXBUVwxKMBUznyffQweQABPRRW1vHZAbadFZud4pLFAqRGvv/96vafgjWFqzourzr8YonlQiPgH0YCJfawoGQ== dependencies: - crypto-random-string "^2.0.0" + crypto-random-string "^4.0.0" universal-user-agent@^6.0.0: version "6.0.0" @@ -7387,32 +8354,20 @@ url-join@^4.0.0: resolved "https://registry.yarnpkg.com/url-join/-/url-join-4.0.1.tgz#b642e21a2646808ffa178c4c5fda39844e12cde7" integrity sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA== +url-join@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/url-join/-/url-join-5.0.0.tgz#c2f1e5cbd95fa91082a93b58a1f42fecb4bdbcf1" + integrity sha512-n2huDr9h9yzd6exQVnH/jU5mr+Pfx08LRXXZhkLLetAMESRj+anQsTAh940iMrIetKAmry9coFuZQ2jY8/p3WA== + util-deprecate@^1.0.1, util-deprecate@^1.0.2, util-deprecate@~1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" - integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8= - -util@^0.12.0: - version "0.12.4" - resolved "https://registry.yarnpkg.com/util/-/util-0.12.4.tgz#66121a31420df8f01ca0c464be15dfa1d1850253" - integrity sha512-bxZ9qtSlGUWSOy9Qa9Xgk11kSslpuZwaxCg4sNIDj6FLucDab2JxnHwyNTCpHMtK1MjoQiWQ6DiUMZYbSrO+Sw== - dependencies: - inherits "^2.0.3" - is-arguments "^1.0.4" - is-generator-function "^1.0.7" - is-typed-array "^1.1.3" - safe-buffer "^5.1.2" - which-typed-array "^1.1.2" - -utila@~0.4: - version "0.4.0" - resolved "https://registry.yarnpkg.com/utila/-/utila-0.4.0.tgz#8a16a05d445657a3aea5eecc5b12a4fa5379772c" - integrity sha1-ihagXURWV6Oupe7MWxKk+lN5dyw= + integrity sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw== -v8-compile-cache@^2.0.3: - version "2.3.0" - resolved "https://registry.yarnpkg.com/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz#2de19618c66dc247dcfb6f99338035d8245a2cee" - integrity sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA== +v8-compile-cache-lib@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz#6336e8d71965cb3d35a1bbb7868445a7c05264bf" + integrity sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg== v8-to-istanbul@^9.0.1: version "9.1.0" @@ -7431,28 +8386,23 @@ validate-npm-package-license@^3.0.1, validate-npm-package-license@^3.0.4: spdx-correct "^3.0.0" spdx-expression-parse "^3.0.0" -validate-npm-package-name@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/validate-npm-package-name/-/validate-npm-package-name-4.0.0.tgz#fe8f1c50ac20afdb86f177da85b3600f0ac0d747" - integrity sha512-mzR0L8ZDktZjpX4OB46KT+56MAhl4EIazWP/+G/HPGuvfdaqg4YsCdtOm6U9+LOFyYDoh4dpnpxZRB9MQQns5Q== +validate-npm-package-name@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/validate-npm-package-name/-/validate-npm-package-name-5.0.0.tgz#f16afd48318e6f90a1ec101377fa0384cfc8c713" + integrity sha512-YuKoXDAhBYxY7SfOKxHBDoSyENFeW5VvIIQp2TGQuit8gpK6MnWaQelBKxso72DoxTZfZdcP3W90LqpSkgPzLQ== dependencies: builtins "^5.0.0" -vscode-oniguruma@^1.7.0: - version "1.7.0" - resolved "https://registry.yarnpkg.com/vscode-oniguruma/-/vscode-oniguruma-1.7.0.tgz#439bfad8fe71abd7798338d1cd3dc53a8beea94b" - integrity sha512-L9WMGRfrjOhgHSdOYgCt/yRMsXzLDJSL7BPrOZt73gU0iWO4mpqzqQzOz5srxqTvMBaR0XZTSrVWo4j55Rc6cA== - -vscode-textmate@^8.0.0: - version "8.0.0" - resolved "https://registry.yarnpkg.com/vscode-textmate/-/vscode-textmate-8.0.0.tgz#2c7a3b1163ef0441097e0b5d6389cd5504b59e5d" - integrity sha512-AFbieoL7a5LMqcnOF04ji+rpXadgOXnZsxQr//r83kLPr7biP7am3g9zbaZIaBGwBRWeSvoMD4mgPdX3e4NWBg== - walk-up-path@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/walk-up-path/-/walk-up-path-1.0.0.tgz#d4745e893dd5fd0dbb58dd0a4c6a33d9c9fec53e" integrity sha512-hwj/qMDUEjCU5h0xr90KGCf0tg0/LgJbmOWgrWKYlcJZM7XvquvUJZ0G/HMGr7F7OQMOUuPHWP9JpriinkAlkg== +walk-up-path@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/walk-up-path/-/walk-up-path-3.0.1.tgz#c8d78d5375b4966c717eb17ada73dbd41490e886" + integrity sha512-9YlCL/ynK3CTlrSRrDxZvUauLzAswPCrsaCgilqFevUYpeEW0/3ScEjaa3kbW/T0ghhkEr7mv+fpjqn1Y1YuTA== + walker@^1.0.8: version "1.0.8" resolved "https://registry.yarnpkg.com/walker/-/walker-1.0.8.tgz#bd498db477afe573dc04185f011d3ab8a8d7653f" @@ -7460,87 +8410,23 @@ walker@^1.0.8: dependencies: makeerror "1.0.12" -watchpack@^2.4.0: - version "2.4.0" - resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-2.4.0.tgz#fa33032374962c78113f93c7f2fb4c54c9862a5d" - integrity sha512-Lcvm7MGST/4fup+ifyKi2hjyIAwcdI4HRgtvTpIUxBRhB+RFtUh8XtDOxUfctVCnhVi+QQj49i91OyvzkJl6cg== - dependencies: - glob-to-regexp "^0.4.1" - graceful-fs "^4.1.2" - -wcwidth@^1.0.0: +wcwidth@^1.0.0, wcwidth@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/wcwidth/-/wcwidth-1.0.1.tgz#f0b0dcf915bc5ff1528afadb2c0e17b532da2fe8" integrity sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg== dependencies: defaults "^1.0.3" +web-streams-polyfill@^3.0.3: + version "3.3.2" + resolved "https://registry.yarnpkg.com/web-streams-polyfill/-/web-streams-polyfill-3.3.2.tgz#32e26522e05128203a7de59519be3c648004343b" + integrity sha512-3pRGuxRF5gpuZc0W+EpwQRmCD7gRqcDOMt688KmdlDAgAyaB1XlN0zq2njfDNm44XVdIouE7pZ6GzbdyH47uIQ== + webidl-conversions@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz#24534275e2a7bc6be7bc86611cc16ae0a5654871" integrity sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ== -webpack-cli@4.10.0: - version "4.10.0" - resolved "https://registry.yarnpkg.com/webpack-cli/-/webpack-cli-4.10.0.tgz#37c1d69c8d85214c5a65e589378f53aec64dab31" - integrity sha512-NLhDfH/h4O6UOy+0LSso42xvYypClINuMNBVVzX4vX98TmTaTUxwRbXdhucbFMd2qLaCTcLq/PdYrvi8onw90w== - dependencies: - "@discoveryjs/json-ext" "^0.5.0" - "@webpack-cli/configtest" "^1.2.0" - "@webpack-cli/info" "^1.5.0" - "@webpack-cli/serve" "^1.7.0" - colorette "^2.0.14" - commander "^7.0.0" - cross-spawn "^7.0.3" - fastest-levenshtein "^1.0.12" - import-local "^3.0.2" - interpret "^2.2.0" - rechoir "^0.7.0" - webpack-merge "^5.7.3" - -webpack-merge@^5.7.3: - version "5.8.0" - resolved "https://registry.yarnpkg.com/webpack-merge/-/webpack-merge-5.8.0.tgz#2b39dbf22af87776ad744c390223731d30a68f61" - integrity sha512-/SaI7xY0831XwP6kzuwhKWVKDP9t1QY1h65lAFLbZqMPIuYcD9QAW4u9STIbU9kaJbPBB/geU/gLr1wDjOhQ+Q== - dependencies: - clone-deep "^4.0.1" - wildcard "^2.0.0" - -webpack-sources@^3.2.3: - version "3.2.3" - resolved "https://registry.yarnpkg.com/webpack-sources/-/webpack-sources-3.2.3.tgz#2d4daab8451fd4b240cc27055ff6a0c2ccea0cde" - integrity sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w== - -webpack@5.74.0: - version "5.74.0" - resolved "https://registry.yarnpkg.com/webpack/-/webpack-5.74.0.tgz#02a5dac19a17e0bb47093f2be67c695102a55980" - integrity sha512-A2InDwnhhGN4LYctJj6M1JEaGL7Luj6LOmyBHjcI8529cm5p6VXiTIW2sn6ffvEAKmveLzvu4jrihwXtPojlAA== - dependencies: - "@types/eslint-scope" "^3.7.3" - "@types/estree" "^0.0.51" - "@webassemblyjs/ast" "1.11.1" - "@webassemblyjs/wasm-edit" "1.11.1" - "@webassemblyjs/wasm-parser" "1.11.1" - acorn "^8.7.1" - acorn-import-assertions "^1.7.6" - browserslist "^4.14.5" - chrome-trace-event "^1.0.2" - enhanced-resolve "^5.10.0" - es-module-lexer "^0.9.0" - eslint-scope "5.1.1" - events "^3.2.0" - glob-to-regexp "^0.4.1" - graceful-fs "^4.2.9" - json-parse-even-better-errors "^2.3.1" - loader-runner "^4.2.0" - mime-types "^2.1.27" - neo-async "^2.6.2" - schema-utils "^3.1.0" - tapable "^2.1.1" - terser-webpack-plugin "^5.1.3" - watchpack "^2.4.0" - webpack-sources "^3.2.3" - whatwg-url@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-5.0.0.tgz#966454e8765462e37644d3626f6742ce8b70965d" @@ -7549,28 +8435,12 @@ whatwg-url@^5.0.0: tr46 "~0.0.3" webidl-conversions "^3.0.0" -which-boxed-primitive@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz#13757bc89b209b049fe5d86430e21cf40a89a8e6" - integrity sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg== - dependencies: - is-bigint "^1.0.1" - is-boolean-object "^1.1.0" - is-number-object "^1.0.4" - is-string "^1.0.5" - is-symbol "^1.0.3" - -which-typed-array@^1.1.2: - version "1.1.7" - resolved "https://registry.yarnpkg.com/which-typed-array/-/which-typed-array-1.1.7.tgz#2761799b9a22d4b8660b3c1b40abaa7739691793" - integrity sha512-vjxaB4nfDqwKI0ws7wZpxIlde1XrLX5uB0ZjpfshgmapJMD7jJWhZI+yToJTqaFByF0eNBcYxbjmCzoRP7CfEw== - dependencies: - available-typed-arrays "^1.0.5" - call-bind "^1.0.2" - es-abstract "^1.18.5" - foreach "^2.0.5" - has-tostringtag "^1.0.0" - is-typed-array "^1.1.7" +which@^1.2.14: + version "1.3.1" + resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a" + integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ== + dependencies: + isexe "^2.0.0" which@^2.0.1, which@^2.0.2: version "2.0.2" @@ -7579,6 +8449,20 @@ which@^2.0.1, which@^2.0.2: dependencies: isexe "^2.0.0" +which@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/which/-/which-3.0.0.tgz#a9efd016db59728758a390d23f1687b6e8f59f8e" + integrity sha512-nla//68K9NU6yRiwDY/Q8aU6siKlSs64aEC7+IV56QoAuyQT2ovsJcgGYGyqMOmI/CGN1BOR6mM5EN0FBO+zyQ== + dependencies: + isexe "^2.0.0" + +which@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/which/-/which-4.0.0.tgz#cd60b5e74503a3fbcfbf6cd6b4138a8bae644c1a" + integrity sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg== + dependencies: + isexe "^3.1.1" + wide-align@^1.1.5: version "1.1.5" resolved "https://registry.yarnpkg.com/wide-align/-/wide-align-1.1.5.tgz#df1d4c206854369ecf3c9a4898f1b23fbd9d15d3" @@ -7586,31 +8470,24 @@ wide-align@^1.1.5: dependencies: string-width "^1.0.2 || 2 || 3 || 4" -wildcard@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/wildcard/-/wildcard-2.0.0.tgz#a77d20e5200c6faaac979e4b3aadc7b3dd7f8fec" - integrity sha512-JcKqAHLPxcdb9KM49dufGXn2x3ssnfjbcaQdLlfZsL9rH9wgDQjUtDxbo8NE0F6SFvydeu1VhZe7hZuHsB2/pw== +widest-line@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/widest-line/-/widest-line-3.1.0.tgz#8292333bbf66cb45ff0de1603b136b7ae1496eca" + integrity sha512-NsmoXalsWVDMGupxZ5R08ka9flZjjiLvHVAWYOKtiKM8ujtZWr9cRffak+uSE48+Ob8ObalXpwyeUiyDD6QFgg== + dependencies: + string-width "^4.0.0" -word-wrap@^1.2.3: - version "1.2.3" - resolved "https://registry.yarnpkg.com/word-wrap/-/word-wrap-1.2.3.tgz#610636f6b1f703891bd34771ccb17fb93b47079c" - integrity sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ== +word-wrap@^1.0.3: + version "1.2.4" + resolved "https://registry.yarnpkg.com/word-wrap/-/word-wrap-1.2.4.tgz#cb4b50ec9aca570abd1f52f33cd45b6c61739a9f" + integrity sha512-2V81OA4ugVo5pRo46hAoD2ivUJx8jXmWXfUkY4KFNw0hEptvN0QfH3K4nHiwzGeKl5rFKedV48QVoqYavy4YpA== wordwrap@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-1.0.0.tgz#27584810891456a4171c8d0226441ade90cbcaeb" - integrity sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus= - -wrap-ansi@^6.2.0: - version "6.2.0" - resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-6.2.0.tgz#e9393ba07102e6c91a3b221478f0257cd2856e53" - integrity sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA== - dependencies: - ansi-styles "^4.0.0" - string-width "^4.1.0" - strip-ansi "^6.0.0" + integrity sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q== -wrap-ansi@^7.0.0: +"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0", wrap-ansi@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== @@ -7619,12 +8496,30 @@ wrap-ansi@^7.0.0: string-width "^4.1.0" strip-ansi "^6.0.0" +wrap-ansi@^8.1.0: + version "8.1.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-8.1.0.tgz#56dc22368ee570face1b49819975d9b9a5ead214" + integrity sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ== + dependencies: + ansi-styles "^6.1.0" + string-width "^5.0.1" + strip-ansi "^7.0.1" + +wrap-ansi@^9.0.0: + version "9.0.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-9.0.0.tgz#1a3dc8b70d85eeb8398ddfb1e4a02cd186e58b3e" + integrity sha512-G8ura3S+3Z2G+mkgNRq8dqaFZAuxfsxpBB8OCTGRTCtp+l/v9nbFNmCUP1BZMts3G1142MsZfn6eeUKrr4PD1Q== + dependencies: + ansi-styles "^6.2.1" + string-width "^7.0.0" + strip-ansi "^7.1.0" + wrappy@1: version "1.0.2" resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" - integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8= + integrity sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ== -write-file-atomic@^4.0.0, write-file-atomic@^4.0.1, write-file-atomic@^4.0.2: +write-file-atomic@^4.0.2: version "4.0.2" resolved "https://registry.yarnpkg.com/write-file-atomic/-/write-file-atomic-4.0.2.tgz#a9df01ae5b77858a027fd2e80768ee433555fcfd" integrity sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg== @@ -7632,24 +8527,27 @@ write-file-atomic@^4.0.0, write-file-atomic@^4.0.1, write-file-atomic@^4.0.2: imurmurhash "^0.1.4" signal-exit "^3.0.7" -ws@8.12.1: - version "8.12.1" - resolved "https://registry.yarnpkg.com/ws/-/ws-8.12.1.tgz#c51e583d79140b5e42e39be48c934131942d4a8f" - integrity sha512-1qo+M9Ba+xNhPB+YTWUlK6M17brTut5EXbcBaMRN5pH5dFrXz7lzz1ChFSUq3bOUl8yEvSenhHmYUNJxFzdJew== +write-file-atomic@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/write-file-atomic/-/write-file-atomic-5.0.0.tgz#54303f117e109bf3d540261125c8ea5a7320fab0" + integrity sha512-R7NYMnHSlV42K54lwY9lvW6MnSm1HSJqZL3xiSgi9E7//FYaI74r2G0rd+/X6VAMkHEdzxQaU5HUOXWUz5kA/w== + dependencies: + imurmurhash "^0.1.4" + signal-exit "^3.0.7" + +write-file-atomic@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/write-file-atomic/-/write-file-atomic-5.0.1.tgz#68df4717c55c6fa4281a7860b4c2ba0a6d2b11e7" + integrity sha512-+QU2zd6OTD8XWIJCbffaiQeH9U73qIqafo1x6V1snCWYGJf6cVE0cDR4D8xRzcEnfI21IFrUPzPGtcPf8AC+Rw== + dependencies: + imurmurhash "^0.1.4" + signal-exit "^4.0.1" ws@8.5.0: version "8.5.0" resolved "https://registry.yarnpkg.com/ws/-/ws-8.5.0.tgz#bfb4be96600757fe5382de12c670dab984a1ed4f" integrity sha512-BWX0SWVgLPzYwF8lTzEy1egjhS4S4OEAHfsO8o65WOVsrnSRGaSiUaa9e0ggGlkMTtBlmOpEXiie9RUcBO86qg== -xss@1.0.14: - version "1.0.14" - resolved "https://registry.yarnpkg.com/xss/-/xss-1.0.14.tgz#4f3efbde75ad0d82e9921cc3c95e6590dd336694" - integrity sha512-og7TEJhXvn1a7kzZGQ7ETjdQVS2UfZyTlsEdDOqvQF7GoxNfY+0YLCzBy1kPdsDDx4QuNAonQPddpsn6Xl/7sw== - dependencies: - commander "^2.20.3" - cssfilter "0.0.10" - xtend@~4.0.1: version "4.0.2" resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.2.tgz#bb72779f5fa465186b1f438f674fa347fdb5db54" @@ -7670,17 +8568,12 @@ yallist@^4.0.0: resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72" integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A== -yaml@^1.10.0: - version "1.10.2" - resolved "https://registry.yarnpkg.com/yaml/-/yaml-1.10.2.tgz#2301c5ffbf12b467de8da2333a459e29e7920e4b" - integrity sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg== - -yaml@^2.1.3: - version "2.2.1" - resolved "https://registry.yarnpkg.com/yaml/-/yaml-2.2.1.tgz#3014bf0482dcd15147aa8e56109ce8632cd60ce4" - integrity sha512-e0WHiYql7+9wr4cWMx3TVQrNwejKaEe7/rHNmQmqRjazfOP5W8PB6Jpebb5o6fIapbz9o9+2ipcaTM2ZwDI6lw== +yaml@2.3.4: + version "2.3.4" + resolved "https://registry.yarnpkg.com/yaml/-/yaml-2.3.4.tgz#53fc1d514be80aabf386dc6001eb29bf3b7523b2" + integrity sha512-8aAvwVUSHpfEqTQ4w/KMlf3HcRdt50E5ODIQJBw1fQ5RL34xabzxtUlzTXVqc4rkZsPbvrXKWnABCD7kWSmocA== -yargs-parser@^20.2.2, yargs-parser@^20.2.3: +yargs-parser@^20.2.3: version "20.2.9" resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-20.2.9.tgz#2eb7dc3b0289718fc295f362753845c41a0c94ee" integrity sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w== @@ -7690,20 +8583,20 @@ yargs-parser@^21.0.1, yargs-parser@^21.1.1: resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-21.1.1.tgz#9096bceebf990d21bb31fa9516e0ede294a77d35" integrity sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw== -yargs@^16.2.0: - version "16.2.0" - resolved "https://registry.yarnpkg.com/yargs/-/yargs-16.2.0.tgz#1c82bf0f6b6a66eafce7ef30e376f49a12477f66" - integrity sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw== +yargs@^17.0.0: + version "17.7.1" + resolved "https://registry.yarnpkg.com/yargs/-/yargs-17.7.1.tgz#34a77645201d1a8fc5213ace787c220eabbd0967" + integrity sha512-cwiTb08Xuv5fqF4AovYacTFNxk62th7LKJ6BL9IGUpTJrWoU7/7WdQGTP2SjKf1dUNBGzDd28p/Yfs/GI6JrLw== dependencies: - cliui "^7.0.2" + cliui "^8.0.1" escalade "^3.1.1" get-caller-file "^2.0.5" require-directory "^2.1.1" - string-width "^4.2.0" + string-width "^4.2.3" y18n "^5.0.5" - yargs-parser "^20.2.2" + yargs-parser "^21.1.1" -yargs@^17.3.1: +yargs@^17.3.1, yargs@^17.5.1: version "17.7.0" resolved "https://registry.yarnpkg.com/yargs/-/yargs-17.7.0.tgz#b21e9af1e0a619a2a9c67b1133219b2975a07985" integrity sha512-dwqOPg5trmrre9+v8SUo2q/hAwyKoVfu8OC1xPHKJGNdxAvPl4sKxL4vBnh3bQz/ZvvGAFeA5H3ou2kcOY8sQQ== @@ -7716,7 +8609,17 @@ yargs@^17.3.1: y18n "^5.0.5" yargs-parser "^21.1.1" +yn@3.1.1: + version "3.1.1" + resolved "https://registry.yarnpkg.com/yn/-/yn-3.1.1.tgz#1e87401a09d767c1d5eab26a6e4c185182d2eb50" + integrity sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q== + yocto-queue@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/yocto-queue/-/yocto-queue-0.1.0.tgz#0294eb3dee05028d31ee1a5fa2c556a6aaf10a1b" integrity sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q== + +yocto-queue@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/yocto-queue/-/yocto-queue-1.0.0.tgz#7f816433fb2cbc511ec8bf7d263c3b58a1a3c251" + integrity sha512-9bnSc/HEW2uRy67wc+T8UwauLuPJVn28jb+GtJY16iiKWyvmYJRXVT4UamsAEGQfPohgr2q4Tq0sQbQlxTfi1g==