From 1c4baba403a4b4829f4800958a2be52aa37749fe Mon Sep 17 00:00:00 2001 From: Mathieu Geukens Date: Sun, 29 Nov 2026 08:42:36 +0100 Subject: [PATCH 1/3] chore: replace ESLint with oxlint and add oxfmt ESLint 8, typescript-eslint 7 and the deprecated airbnb-typescript config are replaced by oxlint for linting and oxfmt for formatting. The lint rules that have an oxlint equivalent and do not need type information carry over. The formatting rules are replaced by oxfmt. No longer enforced: - Type-aware rules (only-throw-error, return-await, dot-notation, no-implied-eval). These can return once the tsconfig no longer uses moduleResolution "node" and baseUrl (#478). - naming-convention and lines-between-class-members, which have no equivalent in oxlint or oxfmt. - max-len as a hard limit. oxfmt wraps code at 125 characters but does not flag long comments or other lines it cannot break. - Style in fixture files, which oxfmt ignores (they are still linted). Refs #303 Co-Authored-By: Claude Fable 5.2 --- .cspell.json | 1 - .eslintignore | 7 - .eslintrc.cjs | 50 - .gitignore | 3 - .oxfmtrc.json | 15 + .oxlintrc.json | 31 + AGENTS.md | 8 +- examples/package.json | 3 +- examples/testing-suite/package.json | 2 +- package.json | 9 +- packages/cashc/package.json | 4 +- .../fixtures/bitauth-script.fixture.ts | 2 - packages/cashscript/package.json | 3 +- .../cashscript/src/libauth-template/utils.ts | 2 - .../cashscript/src/test/JestExtensions.ts | 1 - .../cashscript/src/test/VitestExtensions.ts | 1 - packages/utils/package.json | 3 +- pnpm-lock.yaml | 2668 +++-------------- 18 files changed, 513 insertions(+), 2300 deletions(-) delete mode 100644 .eslintignore delete mode 100644 .eslintrc.cjs create mode 100644 .oxfmtrc.json create mode 100644 .oxlintrc.json diff --git a/.cspell.json b/.cspell.json index 7aa777404..543c3affc 100644 --- a/.cspell.json +++ b/.cspell.json @@ -65,7 +65,6 @@ "electrum", "electrumx", "equalverify", - "eslintignore", "esnext", "ethereum", "ethereum's", diff --git a/.eslintignore b/.eslintignore deleted file mode 100644 index 687b50927..000000000 --- a/.eslintignore +++ /dev/null @@ -1,7 +0,0 @@ -**/dist/ -**/node_modules/ -**/grammar/ -/website/ -*.js -*.cjs -examples/webapp diff --git a/.eslintrc.cjs b/.eslintrc.cjs deleted file mode 100644 index ce36e0295..000000000 --- a/.eslintrc.cjs +++ /dev/null @@ -1,50 +0,0 @@ -const path = require('path'); - -module.exports = { - root: true, - parser: '@typescript-eslint/parser', - plugins: ['@typescript-eslint', 'import'], - extends: ['airbnb-typescript/base'], - parserOptions: { - project: path.join(__dirname, 'tsconfig.json'), - ecmaVersion: 2021, // Allows for the parsing of modern ECMAScript features - sourceType: 'module', // Allows for the use of imports - extraFileExtensions: ['.cjs'], - }, - rules: { - 'max-len': ['error', { code: 125, ignoreStrings: true, ignoreTemplateLiterals: true }], - 'import/no-cycle': 0, // Needed for AST -> AstVisitor -> AST - 'class-methods-use-this': 0, // I don't like this rule - 'no-underscore-dangle': 0, // antlr automatically uses this - 'no-param-reassign': 0, // Makes visitors returning the node object easier - '@typescript-eslint/lines-between-class-members': [ // Makes defining interfaces / abstract classes easier - 'error', - 'always', - { exceptAfterSingleLine: true } - ], - 'no-useless-constructor': 0, // Empty Typescript constructors are not useless - 'no-empty-function': 0, // Empty Typescript constructors are not useless - '@typescript-eslint/no-use-before-define': 0, // Makes it possible to read code top-down - 'no-console': 0, // I want to print stuff - 'no-unused-expressions': 'off', // Turn off to use typescript equivalent - '@typescript-eslint/no-unused-expressions': [ // Short circuiting is pretty cool - 'error', - { allowShortCircuit: true } - ], - '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }], // Ignore unused variables that start with an underscore - 'import/prefer-default-export': 0, // Useful when creating util files that may get expanded - 'import/no-extraneous-dependencies': 0, // This gives weird errors - 'no-bitwise': 0, // Need to use bitwise operators - 'no-restricted-syntax': 0, // Sometimes for...of loops are useful cause they can `break` - 'no-await-in-loop': 0, // Await in loops is sometimes needed - '@typescript-eslint/explicit-function-return-type': [ // Strict interface definitions - 'error', - { allowExpressions: true } - ], - 'max-classes-per-file': 0, // Multiple classes in one file are allowed (e.g. Errors) - '@typescript-eslint/no-redeclare': 0, // I sometimes name variables an types the same - 'linebreak-style': 0, // Ignore linebreak lints https://stackoverflow.com/a/43008668/1129108 - 'import/extensions': ['error', 'ignorePackages'], // ESM requires file extensions - '@typescript-eslint/only-throw-error': 'error', // We should only throw Error objects - }, -} diff --git a/.gitignore b/.gitignore index 81ae1016b..0b0e8f1da 100644 --- a/.gitignore +++ b/.gitignore @@ -66,9 +66,6 @@ typings/ # Optional npm cache directory .npm -# Optional eslint cache -.eslintcache - # Optional REPL history .node_repl_history diff --git a/.oxfmtrc.json b/.oxfmtrc.json new file mode 100644 index 000000000..edb5b7314 --- /dev/null +++ b/.oxfmtrc.json @@ -0,0 +1,15 @@ +{ + "$schema": "./node_modules/oxfmt/configuration_schema.json", + "printWidth": 125, + "singleQuote": true, + "trailingComma": "all", + "ignorePatterns": [ + "**/dist/**", + "**/grammar/**", + "**/fixture/**", + "**/fixtures/**", + "**/import-fixtures/**", + "**/fixtures.ts", + "**/*.fixture.ts" + ] +} diff --git a/.oxlintrc.json b/.oxlintrc.json new file mode 100644 index 000000000..1feaaee24 --- /dev/null +++ b/.oxlintrc.json @@ -0,0 +1,31 @@ +{ + "$schema": "./node_modules/oxlint/configuration_schema.json", + "plugins": ["typescript", "import"], + "categories": { + "correctness": "off" + }, + "ignorePatterns": [ + "**/dist/**", + "**/node_modules/**", + "**/grammar/**", + "website/**", + "examples/webapp/**", + "**/*.js", + "**/*.cjs" + ], + "rules": { + "default-param-last": "error", + "no-array-constructor": "error", + "no-dupe-class-members": "error", + "no-empty-function": ["error", { "allow": ["arrowFunctions", "functions", "methods"] }], + "no-loop-func": "error", + "no-loss-of-precision": "error", + "no-shadow": "error", + "no-throw-literal": "error", + "no-unused-expressions": ["error", { "allowShortCircuit": true }], + "no-useless-constructor": "error", + "no-unused-vars": ["error", { "argsIgnorePattern": "^_", "caughtErrors": "none" }], + "import/extensions": ["error", "ignorePackages"], + "typescript/explicit-function-return-type": ["error", { "allowExpressions": true }] + } +} diff --git a/AGENTS.md b/AGENTS.md index 4e867e032..1d954c637 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,9 +30,13 @@ pnpm test -t 'test name from it/describe block' # Run a single test file directly pnpm vitest run packages/utils/test/source-map.test.ts -# Lint all packages +# Lint all packages (uses oxlint) pnpm lint +# Format all packages (uses oxfmt), or only check formatting +pnpm format +pnpm format:check + # Spellcheck pnpm spellcheck @@ -89,7 +93,7 @@ Shared between compiler and SDK: ## Code Conventions - **ESM modules** — all packages use ES modules; file extensions required in imports (e.g., `./foo.js`) -- **Max line length**: 125 characters (strings and template literals exempt) +- **Formatting** is handled by oxfmt (`pnpm format`): 125 character print width, single quotes, trailing commas - **Explicit return types** on functions (expressions exempt) - **Keep nested code to a minimum** — use helper functions to keep code DRY and readable - Prefer writing code in a way that reads top-down, from the main entry point to the leaves. diff --git a/examples/package.json b/examples/package.json index 55e5cf5b3..3882d0dec 100644 --- a/examples/package.json +++ b/examples/package.json @@ -8,7 +8,7 @@ "author": "Rosco Kalis ", "license": "MIT", "scripts": { - "lint": "eslint . --ext .ts --ignore-path ../.eslintignore" + "lint": "oxlint -c ../.oxlintrc.json" }, "dependencies": { "@bitauth/libauth": "^3.1.0-next.8", @@ -16,7 +16,6 @@ "@types/node": "^24.13.3", "cashc": "workspace:^", "cashscript": "workspace:^", - "eslint": "^8.56.0", "typescript": "^5.9.2" } } diff --git a/examples/testing-suite/package.json b/examples/testing-suite/package.json index 764c5fba8..651fdccab 100644 --- a/examples/testing-suite/package.json +++ b/examples/testing-suite/package.json @@ -13,7 +13,7 @@ }, "scripts": { "compile": "tsx tasks/compile.ts", - "lint": "eslint . --ext .ts --ignore-path ../../.eslintignore", + "lint": "oxlint -c ../../.oxlintrc.json", "test": "vitest run" }, "dependencies": { diff --git a/package.json b/package.json index eeff8fa41..87b99399a 100644 --- a/package.json +++ b/package.json @@ -5,12 +5,9 @@ "packageManager": "pnpm@12.25.1", "devDependencies": { "@types/node": "^24", - "@typescript-eslint/eslint-plugin": "^7.0.0", - "@typescript-eslint/parser": "^7.0.0", "cspell": "^10.0.1", - "eslint": "^8.54.0", - "eslint-config-airbnb-typescript": "^18.0.0", - "eslint-plugin-import": "^2.31.0", + "oxfmt": "0.81.0", + "oxlint": "1.96.0", "tsx": "^4.23.12", "typescript": "^5.9.2", "vite": "^8.3.0", @@ -19,6 +16,8 @@ "scripts": { "test": "pnpm -r --filter './packages/*' run test", "lint": "pnpm -r --filter './packages/*' run lint", + "format": "oxfmt \"packages/*/*.ts\" \"packages/*/src/**/*.ts\" \"packages/*/test/**/*.ts\"", + "format:check": "oxfmt --check \"packages/*/*.ts\" \"packages/*/src/**/*.ts\" \"packages/*/test/**/*.ts\"", "examples": "tsx examples/p2pkh.ts && tsx examples/transfer_with_timeout.ts && tsx examples/hodl_vault.ts", "postinstall": "pnpm build", "spellcheck": "cspell lint '**' --no-progress --must-find-files", diff --git a/packages/cashc/package.json b/packages/cashc/package.json index ed9af4dbf..e9b1c00a3 100644 --- a/packages/cashc/package.json +++ b/packages/cashc/package.json @@ -41,7 +41,7 @@ "build": "pnpm clean && pnpm compile", "clean": "rm -rf ./dist", "compile": "tsc -p tsconfig.build.json", - "lint": "eslint . --ext .ts --ignore-path ../../.eslintignore", + "lint": "oxlint -c ../../.oxlintrc.json", "prepack": "pnpm build", "prepublishOnly": "pnpm test && pnpm lint", "test": "vitest run" @@ -57,8 +57,6 @@ "@types/node": "^24.13.3", "@types/semver": "^7.8.0", "@vitest/coverage-v8": "^5.0.1", - "eslint": "^8.54.0", - "eslint-plugin-import": "^2.31.0", "tsx": "^4.23.12", "typescript": "^5.9.2", "vitest": "^5.0.1" diff --git a/packages/cashc/test/bitauth-script/fixtures/bitauth-script.fixture.ts b/packages/cashc/test/bitauth-script/fixtures/bitauth-script.fixture.ts index 94a3bde9d..5fb0a9ddf 100644 --- a/packages/cashc/test/bitauth-script/fixtures/bitauth-script.fixture.ts +++ b/packages/cashc/test/bitauth-script/fixtures/bitauth-script.fixture.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-len */ - import { InternalCompilerOptions } from '../../../src/internal.js'; export interface Fixture { diff --git a/packages/cashscript/package.json b/packages/cashscript/package.json index d6441181b..36d480a5f 100644 --- a/packages/cashscript/package.json +++ b/packages/cashscript/package.json @@ -35,7 +35,7 @@ "build": "pnpm clean && pnpm compile", "clean": "rm -rf ./dist", "compile": "tsc -p tsconfig.build.json", - "lint": "eslint . --ext .ts --ignore-path ../../.eslintignore", + "lint": "oxlint -c ../../.oxlintrc.json", "prepack": "pnpm build", "prepublishOnly": "pnpm test && pnpm lint", "test": "vitest run" @@ -51,7 +51,6 @@ "@types/semver": "^7.8.0", "@vitest/coverage-v8": "^5.0.1", "cashc": "workspace:^", - "eslint": "^8.54.0", "p-queue": "^9.1.2", "p-retry": "^8.0.0", "typescript": "^5.9.2", diff --git a/packages/cashscript/src/libauth-template/utils.ts b/packages/cashscript/src/libauth-template/utils.ts index 7e3f0bea2..bca72a597 100644 --- a/packages/cashscript/src/libauth-template/utils.ts +++ b/packages/cashscript/src/libauth-template/utils.ts @@ -25,13 +25,11 @@ import { Contract } from '../Contract.js'; export const DEFAULT_VM_TARGET = VmTarget.BCH_2026_05; -/* eslint-disable @typescript-eslint/indent */ export type VM = AuthenticationVirtualMachine< ResolvedTransactionCommon, AuthenticationProgramCommon, AuthenticationProgramStateCommon >; -/* eslint-enable @typescript-eslint/indent */ export const createVirtualMachine = (vmTarget: VmTarget): VM => { switch (vmTarget) { diff --git a/packages/cashscript/src/test/JestExtensions.ts b/packages/cashscript/src/test/JestExtensions.ts index 86a095c53..862c8ca3e 100644 --- a/packages/cashscript/src/test/JestExtensions.ts +++ b/packages/cashscript/src/test/JestExtensions.ts @@ -2,7 +2,6 @@ import './TestExtensions.js'; declare global { namespace jest { - // eslint-disable-next-line interface Matchers { toLog(value?: RegExp | string): Promise; toFailRequireWith(value: RegExp | string): Promise; diff --git a/packages/cashscript/src/test/VitestExtensions.ts b/packages/cashscript/src/test/VitestExtensions.ts index b25020415..2d146a7b1 100644 --- a/packages/cashscript/src/test/VitestExtensions.ts +++ b/packages/cashscript/src/test/VitestExtensions.ts @@ -2,7 +2,6 @@ import './TestExtensions.js'; // The type parameters have to match the ones of Vitest's own Matchers interface for the declarations to merge declare module 'vitest' { - // eslint-disable-next-line @typescript-eslint/no-unused-vars interface Matchers = void | Promise, T = unknown> { toLog(value?: RegExp | string): R; toFailRequireWith(value: RegExp | string): R; diff --git a/packages/utils/package.json b/packages/utils/package.json index 55a40c877..87f9372d6 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -34,7 +34,7 @@ "build": "pnpm clean && pnpm compile", "clean": "rm -rf ./dist", "compile": "tsc -p tsconfig.build.json", - "lint": "eslint . --ext .ts --ignore-path ../../.eslintignore", + "lint": "oxlint -c ../../.oxlintrc.json", "prepack": "pnpm build", "prepublishOnly": "pnpm test && pnpm lint", "test": "vitest run" @@ -44,7 +44,6 @@ }, "devDependencies": { "@vitest/coverage-v8": "^5.0.1", - "eslint": "^8.54.0", "typescript": "^5.9.2", "vitest": "^5.0.1" } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f9b721e37..edeb9c137 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -191,24 +191,15 @@ importers: '@types/node': specifier: ^24 version: 24.13.3 - '@typescript-eslint/eslint-plugin': - specifier: ^7.0.0 - version: 7.18.0(@typescript-eslint/parser@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2))(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2) - '@typescript-eslint/parser': - specifier: ^7.0.0 - version: 7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2) cspell: specifier: ^10.0.1 version: 10.0.1 - eslint: - specifier: ^8.54.0 - version: 8.57.0(supports-color@7.2.0) - eslint-config-airbnb-typescript: - specifier: ^18.0.0 - version: 18.0.0(@typescript-eslint/eslint-plugin@7.18.0(@typescript-eslint/parser@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2))(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2))(@typescript-eslint/parser@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2))(eslint-plugin-import@2.31.0(@typescript-eslint/parser@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2))(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0))(eslint@8.57.0(supports-color@7.2.0)) - eslint-plugin-import: - specifier: ^2.31.0 - version: 2.31.0(@typescript-eslint/parser@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2))(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0) + oxfmt: + specifier: 0.81.0 + version: 0.81.0 + oxlint: + specifier: 1.96.0 + version: 1.96.0 tsx: specifier: ^4.23.12 version: 4.23.12 @@ -239,9 +230,6 @@ importers: cashscript: specifier: workspace:^ version: link:../packages/cashscript - eslint: - specifier: ^8.56.0 - version: 8.57.0(supports-color@7.2.0) typescript: specifier: ^5.9.2 version: 5.9.2 @@ -298,12 +286,6 @@ importers: '@vitest/coverage-v8': specifier: ^5.0.1 version: 5.0.1(vitest@5.0.1) - eslint: - specifier: ^8.54.0 - version: 8.57.0(supports-color@7.2.0) - eslint-plugin-import: - specifier: ^2.31.0 - version: 2.31.0(@typescript-eslint/parser@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2))(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0) tsx: specifier: ^4.23.12 version: 4.23.12 @@ -324,7 +306,7 @@ importers: version: link:../utils '@electrum-cash/network': specifier: ^4.4.0 - version: 4.4.0(supports-color@7.2.0) + version: 4.4.0 fflate: specifier: ^0.8.3 version: 0.8.3 @@ -341,9 +323,6 @@ importers: cashc: specifier: workspace:^ version: link:../cashc - eslint: - specifier: ^8.54.0 - version: 8.57.0(supports-color@7.2.0) p-queue: specifier: ^9.1.2 version: 9.1.2 @@ -366,9 +345,6 @@ importers: '@vitest/coverage-v8': specifier: ^5.0.1 version: 5.0.1(vitest@5.0.1) - eslint: - specifier: ^8.54.0 - version: 8.57.0(supports-color@7.2.0) typescript: specifier: ^5.9.2 version: 5.9.2 @@ -805,37 +781,6 @@ packages: cpu: [x64] os: [win32] - '@eslint-community/eslint-utils@4.4.0': - resolution: {integrity: sha512-1/sA4dwrzBAyeUoQ6oxahHKmrZvsnLCg4RfxW3ZFGGmQkSNQPFNLV9CUEFQP1x9EYXHTo5p6xdhZM1Ne9p/AfA==} - engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} - peerDependencies: - eslint: ^6.0.0 || ^7.0.0 || >=8.0.0 - - '@eslint-community/regexpp@4.11.0': - resolution: {integrity: sha512-G/M/tIiMrTAxEWRfLfQJMmGNX28IxBg4PBz8XqQhqUHLFI6TL2htpIB1iQCj144V5ee/JaKyT9/WZ0MGZWfA7A==} - engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} - - '@eslint/eslintrc@2.1.4': - resolution: {integrity: sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==} - engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} - - '@eslint/js@8.57.0': - resolution: {integrity: sha512-Ys+3g2TaW7gADOJzPt83SJtCDhMjndcDMFVQ/Tj9iA1BfJzFKD9mAUXT3OenpuPHbI6P/myECxRJrofUsDx/5g==} - engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} - - '@humanwhocodes/config-array@0.11.14': - resolution: {integrity: sha512-3T8LkOmg45BV5FICb15QQMsyUSWrQ8AygVfC7ZG32zOalnqrilm018ZVCw0eapXux8FtA33q8PSRSstjee3jSg==} - engines: {node: '>=10.10.0'} - deprecated: Use @eslint/config-array instead - - '@humanwhocodes/module-importer@1.0.1': - resolution: {integrity: sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==} - engines: {node: '>=12.22'} - - '@humanwhocodes/object-schema@2.0.3': - resolution: {integrity: sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==} - deprecated: Use @eslint/object-schema instead - '@jridgewell/resolve-uri@3.1.2': resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} engines: {node: '>=6.0.0'} @@ -851,20 +796,252 @@ packages: peerDependencies: ws: ^8.21.3 - '@nodelib/fs.scandir@2.1.5': - resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==} - engines: {node: '>= 8'} + '@oxc-project/types@0.151.0': + resolution: {integrity: sha512-J1yXrIlNDZVzE3ada310xeAw7nH8yCAyLPuUIsjKatFPmfn5bS1oW+cM+QsGOtVWd5nhSpbwZWx/rue+r5Z+PA==} + + '@oxfmt/binding-android-arm-eabi@0.81.0': + resolution: {integrity: sha512-wlb5bszpOCKBg52In0Hrqz8zdzjQ8hQtZjdnfC3rZp2ondwPqUwwXuBZku0h6FEvK08DnZhzztB+DvtmmHrByg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@oxfmt/binding-android-arm64@0.81.0': + resolution: {integrity: sha512-JMHJYkgpIJSeY+pIi2LAm+Qj61xIdqkbI5RAISITWxT8gzuqR0DkA1ZEgIZ+0B/ydTtGQv/+y4CFHDOgwgJwfA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@oxfmt/binding-darwin-arm64@0.81.0': + resolution: {integrity: sha512-/ovt9o0S8CHKhhHjy179vzBg95P5O+brn1/1G02k2JFoABFauJMwlDw/iMScs6WXA1VgPJgTrvc9iiZd1VwO6w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] - '@nodelib/fs.stat@2.0.5': - resolution: {integrity: sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==} - engines: {node: '>= 8'} + '@oxfmt/binding-darwin-x64@0.81.0': + resolution: {integrity: sha512-SbUD/zbob0DVePxtZgoWV0pX5fViC2F12jobjoptW7sl3P0bQhbnD3+9wsd2XcbbwbabK1zSu0MT7FFxiETl+Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] - '@nodelib/fs.walk@1.2.8': - resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==} - engines: {node: '>= 8'} + '@oxfmt/binding-freebsd-x64@0.81.0': + resolution: {integrity: sha512-u+IgTRPHPYFUUPIVHHecRufdEAH2Q6S57P6KUq1p9/Kqyq3TZcQzg9a2o0ideJKmvI+JBldrB/t5nYYXteEOng==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] - '@oxc-project/types@0.151.0': - resolution: {integrity: sha512-J1yXrIlNDZVzE3ada310xeAw7nH8yCAyLPuUIsjKatFPmfn5bS1oW+cM+QsGOtVWd5nhSpbwZWx/rue+r5Z+PA==} + '@oxfmt/binding-linux-arm-gnueabihf@0.81.0': + resolution: {integrity: sha512-xLvphnc/ZrGKNHAvk7XjbOGZodn4vPs+cvguo/hrmF62ZF0XS8Myu/YaSKL+/97E6DZSnelQRlgoOkCSRyofaw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxfmt/binding-linux-arm-musleabihf@0.81.0': + resolution: {integrity: sha512-N1212QKzbPFcryiPmvCH1u1yAocySPd/zauCJzojKvCReNSB4P6qRqlGZGJc0WbXJBVr63pEn148pkshEvU0UQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxfmt/binding-linux-arm64-gnu@0.81.0': + resolution: {integrity: sha512-KfdloRQ14KE9pucAQw57jKyNLgpPQPXMTCvmUXDzdQa8ovMXHBzijkiazSObzR3jw27Rj7PiaBqZt2gFtDVrrQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@oxfmt/binding-linux-arm64-musl@0.81.0': + resolution: {integrity: sha512-x2ByQdlMcs1uPKGD9PvBNwnAuuemOJxjlYYYGOB4+zz/JCKbaB00WT1BjDjqEciYHiiqcLkZmjG3FNPHSyCzag==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@oxfmt/binding-linux-ppc64-gnu@0.81.0': + resolution: {integrity: sha512-YQ1NpjKIox5MZqngqW/2kI6m9FDOQPsLoPod90igYGHCFIwcPmcqGGAlKvVcYl5+5iX+YwLL30BmZDnKUL8pBA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@oxfmt/binding-linux-riscv64-gnu@0.81.0': + resolution: {integrity: sha512-ZUgG05Q7jTvFeNeLvWHTBRIV4WHIXevLz39OkkDI+uTisEF1znDpWSNwgGVLcVxT3TcdIeoTaf7MfrROOtnemg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@oxfmt/binding-linux-riscv64-musl@0.81.0': + resolution: {integrity: sha512-4QJhg7Tl6mc1WAcOKUomxVT+laKbxJjDaNGWzkRWTATmA1l4w4c0XqraIZBvM29VXlGQj+PvseLcSk9XFr2Hbw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@oxfmt/binding-linux-s390x-gnu@0.81.0': + resolution: {integrity: sha512-rbSQY9K1pS6v8JCJJNR1FE+qPSOLRnIS8HUVapi210M/FbrmWV/3in+S1wtA72YY0izcB7AuY7Wg3kQUQdziww==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@oxfmt/binding-linux-x64-gnu@0.81.0': + resolution: {integrity: sha512-BhYZ9V/2G/yce6mY2cvraetgy37sdwwXFoUhwdb2rruz9wnQY1qD42CIbgV5Yu43oNz1OhJ6EVK0Iw0dLyoUMQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@oxfmt/binding-linux-x64-musl@0.81.0': + resolution: {integrity: sha512-IF01AJK7EMc5TWDVf8KCFVNI8HCjzsoycLD18iSbJR4mZ1FMqkbPOKPWuwKCYaXav20lvcz8+GRdDPlJhGZ2PQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@oxfmt/binding-openharmony-arm64@0.81.0': + resolution: {integrity: sha512-tYZOH03aUtKOOAauAmo45d0ZRUmwIGmcn/mtc19YyqmrAs5iR61T5gjDjq1X70aBDcz+4D+sE8SR3Q0yiqZklQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@oxfmt/binding-win32-arm64-msvc@0.81.0': + resolution: {integrity: sha512-Z7Ia6NuCmgN3Y8/tLuXDoHkm7osNLF8Gux20UrLaO4kYTXNl7X6kbA1umxyyXy/OJqrIzg/CdczDJKRlg5hXhg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@oxfmt/binding-win32-ia32-msvc@0.81.0': + resolution: {integrity: sha512-E0ybKSoI35U9gC8N4STxzZyVmTYT6I1dMTwnPH2hsu/oFPW+R4gmdx3W4sLN4eOXMKub6Zk3Wl1Xf2cS+WBagg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ia32] + os: [win32] + + '@oxfmt/binding-win32-x64-msvc@0.81.0': + resolution: {integrity: sha512-fAGnOILTfcJfgVasE/T3FuxBqSsoXtaQxmpuFvxmIRqW5AyA8nWsAJbrB3SCP8C8WyMLfz9agHhHGFtb50Otsw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@oxlint/binding-android-arm-eabi@1.96.0': + resolution: {integrity: sha512-SCINGNIfxMCeONnTjTQdm27XYY3zWv5olN/RIJmoTbMgphJ8JkZMeivswWqPdjwYpTAuskGNpHbevtECumuIxg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@oxlint/binding-android-arm64@1.96.0': + resolution: {integrity: sha512-jmRRp4pThMoYheXzhDrEMOHMU6X0geGSzJznkF2xhE9l0aViXNBvZrWasR5WLc3FXlc0rQAtV/o9mH1wosXZGQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@oxlint/binding-darwin-arm64@1.96.0': + resolution: {integrity: sha512-RxRoSJY2xa9/dKRzPv1rLn36OvaCwu7Qg9o+NhrSIP7FkLWackAkfbf+5bcgIC5H1r78sdWUvVAIDJKDdfkXPg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@oxlint/binding-darwin-x64@1.96.0': + resolution: {integrity: sha512-pokl9aeRHG0ke37GooIG/Jjd5bIFx9TDZ9//JkO0KDROJ3MIGz+KD9/hlq6siE40+auswpyaolZ4xNqzaX1VWw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@oxlint/binding-freebsd-x64@1.96.0': + resolution: {integrity: sha512-zV8oqk0kzAFa8hsiBXz431E9DvYZuhIOveTKk7bgKmeYy1KixJ//iwdBMvD6+IGq0HAxxX2eCAbdzecC2Qsrpw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@oxlint/binding-linux-arm-gnueabihf@1.96.0': + resolution: {integrity: sha512-hT4CHT09eiWrwIikLjqiQrcjF1lASaRrJR4rGwXhHQcXC8Z5ohkDOy897tV/+UK/RkDvhtX3YOV3LGultcJTxg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxlint/binding-linux-arm-musleabihf@1.96.0': + resolution: {integrity: sha512-ro+mX13ijz/Z2IIstN3TnPjoOzMZmvvS6xj/RIkyWZJveU/W5WkuFkISb81M7dxVDywHNUUljs9kGXL+ZpCkAA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxlint/binding-linux-arm64-gnu@1.96.0': + resolution: {integrity: sha512-kpJqgwJ4xCzg0HiZr0IqPumqoskk7z9m+epDKC8cxuC6sS5GeX0u8XpuotC7BKto0htzq+AmpZ6/LPIqOJ2J2w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-arm64-musl@1.96.0': + resolution: {integrity: sha512-sPqrWFuk8IsDx5ftGQVCaxRfnR95b3aXFQrknHDsb0W6UGYkhmhU6ZcirV/9Etyf44dAYo3ZMyA30bRow1sz5w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@oxlint/binding-linux-ppc64-gnu@1.96.0': + resolution: {integrity: sha512-41bcNpgz0TDw2bPseL18MWtiyxrkadp5XVqRPr3TmGSDO2NpXdrHQ3UbXOiSpi5Dko7H22iNg9kcl/q/TZrcWA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-riscv64-gnu@1.96.0': + resolution: {integrity: sha512-XsuYByplvx4CjLwBTDNiWEB3Igk1NVgg0jqndZA9Op59ssCqO9PYZmg8af+GMOfrOtpdiFiGnogi0PfvCihGrg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-riscv64-musl@1.96.0': + resolution: {integrity: sha512-J+JcvoObB6gsi3TxaY8tu0gc2ZEcxYbKz7t0N85RurdEU1ubXHTJqKOe8D5aH3KPSmlT3+8f81UhVI4qF4WoUQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@oxlint/binding-linux-s390x-gnu@1.96.0': + resolution: {integrity: sha512-wON5n7KlNpVWMhzYt9G3Ew2iuL6hHt0LV69dg51quv78mx7jOWFZp/+2ny2vARWl1542RRSip70hb7DAj2yy+Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-x64-gnu@1.96.0': + resolution: {integrity: sha512-AURdLIDjJvUK1XjWtnQI6TJs8F3SAQOFsDeL3QQChNwKAWbCZmT4jjflXMb6hjTY6NS1mnP1Z2sWz/yLI1BvTg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-x64-musl@1.96.0': + resolution: {integrity: sha512-4+qtiKtCov+b8psbs4/O3nOtNh40bZN/QYxjjmOgV7OHmcD8rBwJqV4AeeXGZ/pSUCGNYGm1sQtiy4AAhJ5xqQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@oxlint/binding-openharmony-arm64@1.96.0': + resolution: {integrity: sha512-eYZmZlTFgwz3c0+nLlZc+QdFTJJQ9B98vvLSk8LPJm+edhhiuLOe6jIUiLWwc52s95GKz5US05cAsVd8e5BzOA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@oxlint/binding-win32-arm64-msvc@1.96.0': + resolution: {integrity: sha512-elsIvBZeDYDO3swjXGBh8kGrsVrlcDNv6X2+ASA7q02UPuAWjH5F8urTa2d32c+f7l9MFohMokdWZ82pV+oZ9Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@oxlint/binding-win32-ia32-msvc@1.96.0': + resolution: {integrity: sha512-Sl6tX5MdGZ886jSHmeg71ijhtsELauPl4ii4pfAtrQV3W7uj+v5QF1eAZB74KySWt6sdZuNDyjfhaKGaCf6NWA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ia32] + os: [win32] + + '@oxlint/binding-win32-x64-msvc@1.96.0': + resolution: {integrity: sha512-gLx6y/CsxfNZdfBfSLbVHB75AHDfV2/XdilDqPgh7oNRL6y72s75TCbMt500km+Mk5izFYNYXX8+LYR6U4n/zA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] '@rolldown/binding-android-arm-eabi@1.2.10': resolution: {integrity: sha512-bp9svZb+QurZeh+8H4BhrZkifEB0YBNvTVzNSJnJQkj4NrRwmQoDUCGP0vSN7PbvLeM7l1tK6GXL8mrTiH2myg==} @@ -965,9 +1142,6 @@ packages: '@rolldown/pluginutils@1.0.1': resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} - '@rtsao/scc@1.1.0': - resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==} - '@types/chai@5.2.2': resolution: {integrity: sha512-8kB30R7Hwqf40JPiKhVzodJs2Qc1ZJ5zuT3uzw5Hq/dhNCl3G3l83jfpdI1e20BP348+fV7VIL/+FxaXkqBmWg==} @@ -977,9 +1151,6 @@ packages: '@types/estree@1.0.8': resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==} - '@types/json5@0.0.29': - resolution: {integrity: sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==} - '@types/node@24.13.3': resolution: {integrity: sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==} @@ -989,68 +1160,6 @@ packages: '@types/ws@8.5.14': resolution: {integrity: sha512-bd/YFLW+URhBzMXurx7lWByOu+xzU9+kb3RboOteXYDfW+tr+JZa99OyNmPINEGB/ahzKrEuc8rcv4gnpJmxTw==} - '@typescript-eslint/eslint-plugin@7.18.0': - resolution: {integrity: sha512-94EQTWZ40mzBc42ATNIBimBEDltSJ9RQHCC8vc/PDbxi4k8dVwUAv4o98dk50M1zB+JGFxp43FP7f8+FP8R6Sw==} - engines: {node: ^18.18.0 || >=20.0.0} - peerDependencies: - '@typescript-eslint/parser': ^7.0.0 - eslint: ^8.56.0 - typescript: '*' - peerDependenciesMeta: - typescript: - optional: true - - '@typescript-eslint/parser@7.18.0': - resolution: {integrity: sha512-4Z+L8I2OqhZV8qA132M4wNL30ypZGYOQVBfMgxDH/K5UX0PNqTu1c6za9ST5r9+tavvHiTWmBnKzpCJ/GlVFtg==} - engines: {node: ^18.18.0 || >=20.0.0} - peerDependencies: - eslint: ^8.56.0 - typescript: '*' - peerDependenciesMeta: - typescript: - optional: true - - '@typescript-eslint/scope-manager@7.18.0': - resolution: {integrity: sha512-jjhdIE/FPF2B7Z1uzc6i3oWKbGcHb87Qw7AWj6jmEqNOfDFbJWtjt/XfwCpvNkpGWlcJaog5vTR+VV8+w9JflA==} - engines: {node: ^18.18.0 || >=20.0.0} - - '@typescript-eslint/type-utils@7.18.0': - resolution: {integrity: sha512-XL0FJXuCLaDuX2sYqZUUSOJ2sG5/i1AAze+axqmLnSkNEVMVYLF+cbwlB2w8D1tinFuSikHmFta+P+HOofrLeA==} - engines: {node: ^18.18.0 || >=20.0.0} - peerDependencies: - eslint: ^8.56.0 - typescript: '*' - peerDependenciesMeta: - typescript: - optional: true - - '@typescript-eslint/types@7.18.0': - resolution: {integrity: sha512-iZqi+Ds1y4EDYUtlOOC+aUmxnE9xS/yCigkjA7XpTKV6nCBd3Hp/PRGGmdwnfkV2ThMyYldP1wRpm/id99spTQ==} - engines: {node: ^18.18.0 || >=20.0.0} - - '@typescript-eslint/typescript-estree@7.18.0': - resolution: {integrity: sha512-aP1v/BSPnnyhMHts8cf1qQ6Q1IFwwRvAQGRvBFkWlo3/lH29OXA3Pts+c10nxRxIBrDnoMqzhgdwVe5f2D6OzA==} - engines: {node: ^18.18.0 || >=20.0.0} - peerDependencies: - typescript: '*' - peerDependenciesMeta: - typescript: - optional: true - - '@typescript-eslint/utils@7.18.0': - resolution: {integrity: sha512-kK0/rNa2j74XuHVcoCZxdFBMF+aq/vH83CXAOHieC+2Gis4mF8jJXT5eAfyD3K0sAxtPuwxaIOIOvhwzVDt/kw==} - engines: {node: ^18.18.0 || >=20.0.0} - peerDependencies: - eslint: ^8.56.0 - - '@typescript-eslint/visitor-keys@7.18.0': - resolution: {integrity: sha512-cDF0/Gf81QpY3xYyJKDV14Zwdmid5+uuENhjH2EqFaF0ni+yAyq/LzMaIJdhNJXZI7uLzwIlA+V7oWoyn6Curg==} - engines: {node: ^18.18.0 || >=20.0.0} - - '@ungap/structured-clone@1.2.0': - resolution: {integrity: sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ==} - deprecated: Potential CWE-502 - Update to 1.3.1 or higher - '@vitest/coverage-v8@5.0.1': resolution: {integrity: sha512-FRC8ACiudC3dI6MTplzRSYWHDRnIv2IPfbzs4FdoJNsMal/35sWV8hwIfV8ZcqzSPy+uXHeMVONt9CEqtOU17w==} peerDependencies: @@ -1082,108 +1191,23 @@ packages: '@vitest/spy@5.0.1': resolution: {integrity: sha512-rbto/mF/SGERxEgYOek7Xm6B9b+y+mVoo+f4b2LymYO8zM1b7uB5nHuhVMTP2hxdzgxvGiZYGxGIaMvL5y180Q==} - acorn-jsx@5.3.2: - resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} - peerDependencies: - acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 - - acorn@8.12.1: - resolution: {integrity: sha512-tcpGyI9zbizT9JbV6oYE477V6mTlXvvi0T0G3SNIYE2apm/G5huBa1+K89VGeovbg+jycCrfhl3ADxErOuO6Jg==} - engines: {node: '>=0.4.0'} - hasBin: true - - ajv@6.12.6: - resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==} - - ansi-regex@5.0.1: - resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} - engines: {node: '>=8'} - ansi-regex@6.2.2: resolution: {integrity: sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==} engines: {node: '>=12'} - ansi-styles@4.3.0: - resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} - engines: {node: '>=8'} - antlr4@4.13.2: resolution: {integrity: sha512-QiVbZhyy4xAZ17UPEuG3YTOt8ZaoeOR1CvEAqrEsDBsOqINslaB147i9xqljZqoyf5S+EUlGStaj+t22LT9MOg==} engines: {node: '>=16'} - argparse@2.0.1: - resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} - - array-buffer-byte-length@1.0.2: - resolution: {integrity: sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==} - engines: {node: '>= 0.4'} - - array-includes@3.1.8: - resolution: {integrity: sha512-itaWrbYbqpGXkGhZPGUulwnhVf5Hpy1xiCFsGqyIGglbBxmG5vSjxQen3/WGOjPpNEv1RtBLKxbmVXm8HpJStQ==} - engines: {node: '>= 0.4'} - array-timsort@1.0.3: resolution: {integrity: sha512-/+3GRL7dDAGEfM6TseQk/U+mi18TU2Ms9I3UlLdUMhz2hbvGNTKdj9xniwXfUqgYhHxRx0+8UnKkvlNwVU+cWQ==} - array-union@2.1.0: - resolution: {integrity: sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==} - engines: {node: '>=8'} - - array.prototype.findlastindex@1.2.5: - resolution: {integrity: sha512-zfETvRFA8o7EiNn++N5f/kaCw221hrpGsDmcpndVupkPzEc1Wuf3VgC0qby1BbHs7f5DVYjgtEU2LLh5bqeGfQ==} - engines: {node: '>= 0.4'} - - array.prototype.flat@1.3.3: - resolution: {integrity: sha512-rwG/ja1neyLqCuGZ5YYrznA62D4mZXg0i1cIskIUKSiqF3Cje9/wXAls9B9s1Wa2fomMsIv8czB8jZcPmxCXFg==} - engines: {node: '>= 0.4'} - - array.prototype.flatmap@1.3.3: - resolution: {integrity: sha512-Y7Wt51eKJSyi80hFrJCePGGNo5ktJCslFuboqJsbf57CCPcm5zztluPlc4/aD8sWsKvlwatezpV4U1efk8kpjg==} - engines: {node: '>= 0.4'} - - arraybuffer.prototype.slice@1.0.4: - resolution: {integrity: sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==} - engines: {node: '>= 0.4'} - ast-v8-to-istanbul@1.0.7: resolution: {integrity: sha512-kFL68AG6ajd8fg248zwM9GQrUWEp79gsmjum34OEXjs4yHuUMZfYKwOLW9GMmB4oNvVrj+EAGxsP7ye2UR9UlA==} async-mutex@0.5.0: resolution: {integrity: sha512-1A94B18jkJ3DYq284ohPxoXbfTA5HsQ7/Mf4DEhcyLx3Bz27Rh59iScbB6EPiP+B+joue6YCxcMXSbFC1tZKwA==} - available-typed-arrays@1.0.7: - resolution: {integrity: sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==} - engines: {node: '>= 0.4'} - - balanced-match@1.0.2: - resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} - - brace-expansion@1.1.11: - resolution: {integrity: sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==} - - brace-expansion@2.0.1: - resolution: {integrity: sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==} - - braces@3.0.3: - resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} - engines: {node: '>=8'} - - call-bind-apply-helpers@1.0.1: - resolution: {integrity: sha512-BhYE+WDaywFg2TBWYNXAE+8B1ATnThNBqXHP5nQu0jWJdVvY2hvkpyB3qOmtmDePiS5/BDQ8wASEWGMWRG148g==} - engines: {node: '>= 0.4'} - - call-bind@1.0.8: - resolution: {integrity: sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww==} - engines: {node: '>= 0.4'} - - call-bound@1.0.3: - resolution: {integrity: sha512-YTd+6wGlNlPxSuri7Y6X8tY2dmm12UMH66RpKMhiX6rsk5wXXnYgbUcOt8kiS31/AjfoTOvCsE+w8nZQLQnzHA==} - engines: {node: '>= 0.4'} - - callsites@3.1.0: - resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} - engines: {node: '>=6'} - chai@6.2.2: resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==} engines: {node: '>=18'} @@ -1192,21 +1216,10 @@ packages: resolution: {integrity: sha512-2bxTP2yUH7AJj/VAXfcA+4IcWGdQ87HwBANLt5XxGTeomo8yG0y95N1um9i5StvhT/Bl0/2cARA5v1PpPXUxUA==} engines: {node: '>=14.16'} - chalk@4.1.2: - resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} - engines: {node: '>=10'} - chalk@5.6.2: resolution: {integrity: sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==} engines: {node: ^12.17.0 || ^14.13 || >=16.0.0} - color-convert@2.0.1: - resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} - engines: {node: '>=7.0.0'} - - color-name@1.1.4: - resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} - commander@14.0.3: resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==} engines: {node: '>=20'} @@ -1215,16 +1228,6 @@ packages: resolution: {integrity: sha512-uiqLcOiVDJtBP8WGkZHEP+FZIhTzP1dxvn59EfoYUi9gqupjrBWVQkO2atDrbnKPwLeotFYDsuNb26uBMqB+hw==} engines: {node: '>= 6'} - concat-map@0.0.1: - resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} - - confusing-browser-globals@1.0.10: - resolution: {integrity: sha512-gNld/3lySHwuhaVluJUKLePYirM3QNCKzVxqAdhJII9/WXKVX5PURzMVJspS1jTslSqjeuG4KMVTSouit5YPHA==} - - cross-spawn@7.0.3: - resolution: {integrity: sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==} - engines: {node: '>= 8'} - cspell-config-lib@10.0.1: resolution: {integrity: sha512-hMpo/0j6k7pbiqrLDOLJKD2IGP9XwhjKf2miiM6p84Xeo4nyuFZaxxDCQ68R851HSYFrrdltgpoipMbj1h2Tnw==} engines: {node: '>=22.18.0'} @@ -1266,26 +1269,6 @@ packages: engines: {node: '>=22.18.0'} hasBin: true - data-view-buffer@1.0.2: - resolution: {integrity: sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==} - engines: {node: '>= 0.4'} - - data-view-byte-length@1.0.2: - resolution: {integrity: sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==} - engines: {node: '>= 0.4'} - - data-view-byte-offset@1.0.1: - resolution: {integrity: sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==} - engines: {node: '>= 0.4'} - - debug@3.2.7: - resolution: {integrity: sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==} - peerDependencies: - supports-color: '*' - peerDependenciesMeta: - supports-color: - optional: true - debug@4.4.0: resolution: {integrity: sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==} engines: {node: '>=6.0'} @@ -1295,170 +1278,30 @@ packages: supports-color: optional: true - deep-is@0.1.4: - resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} - - define-data-property@1.1.4: - resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==} - engines: {node: '>= 0.4'} - - define-properties@1.2.1: - resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==} - engines: {node: '>= 0.4'} - detect-libc@2.1.2: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} - dir-glob@3.0.1: - resolution: {integrity: sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==} - engines: {node: '>=8'} - - doctrine@2.1.0: - resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==} - engines: {node: '>=0.10.0'} - - doctrine@3.0.0: - resolution: {integrity: sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==} - engines: {node: '>=6.0.0'} - - dunder-proto@1.0.1: - resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} - engines: {node: '>= 0.4'} - - env-paths@4.0.0: - resolution: {integrity: sha512-pxP8eL2SwwaTRi/KHYwLYXinDs7gL3jxFcBYmEdYfZmZXbaVDvdppd0XBU8qVz03rDfKZMXg1omHCbsJjZrMsw==} - engines: {node: '>=20'} - - es-abstract@1.23.9: - resolution: {integrity: sha512-py07lI0wjxAC/DcfK1S6G7iANonniZwTISvdPzk9hzeH0IZIshbuuFxLIU96OyF89Yb9hiqWn8M/bY83KY5vzA==} - engines: {node: '>= 0.4'} - - es-define-property@1.0.1: - resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} - engines: {node: '>= 0.4'} - - es-errors@1.3.0: - resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} - engines: {node: '>= 0.4'} + env-paths@4.0.0: + resolution: {integrity: sha512-pxP8eL2SwwaTRi/KHYwLYXinDs7gL3jxFcBYmEdYfZmZXbaVDvdppd0XBU8qVz03rDfKZMXg1omHCbsJjZrMsw==} + engines: {node: '>=20'} es-module-lexer@2.3.2: resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} - es-object-atoms@1.1.1: - resolution: {integrity: sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==} - engines: {node: '>= 0.4'} - - es-set-tostringtag@2.1.0: - resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==} - engines: {node: '>= 0.4'} - - es-shim-unscopables@1.0.2: - resolution: {integrity: sha512-J3yBRXCzDu4ULnQwxyToo/OjdMx6akgVC7K6few0a7F/0wLtmKKN7I73AH5T2836UuXRqN7Qg+IIUw/+YJksRw==} - - es-to-primitive@1.3.0: - resolution: {integrity: sha512-w+5mJ3GuFL+NjVtJlvydShqE1eN3h3PbI7/5LAsYJP/2qtuMXjfL2LpHSRqo4b4eSF5K/DH1JXKUAHSB2UW50g==} - engines: {node: '>= 0.4'} - esbuild@0.28.2: resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==} engines: {node: '>=18'} hasBin: true - escape-string-regexp@4.0.0: - resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} - engines: {node: '>=10'} - - eslint-config-airbnb-base@15.0.0: - resolution: {integrity: sha512-xaX3z4ZZIcFLvh2oUNvcX5oEofXda7giYmuplVxoOg5A7EXJMrUyqRgR+mhDhPK8LZ4PttFOBvCYDbX3sUoUig==} - engines: {node: ^10.12.0 || >=12.0.0} - peerDependencies: - eslint: ^7.32.0 || ^8.2.0 - eslint-plugin-import: ^2.25.2 - - eslint-config-airbnb-typescript@18.0.0: - resolution: {integrity: sha512-oc+Lxzgzsu8FQyFVa4QFaVKiitTYiiW3frB9KYW5OWdPrqFc7FzxgB20hP4cHMlr+MBzGcLl3jnCOVOydL9mIg==} - peerDependencies: - '@typescript-eslint/eslint-plugin': ^7.0.0 - '@typescript-eslint/parser': ^7.0.0 - eslint: ^8.56.0 - - eslint-import-resolver-node@0.3.9: - resolution: {integrity: sha512-WFj2isz22JahUv+B788TlO3N6zL3nNJGU8CcZbPZvVEkBPaJdCV4vy5wyghty5ROFbCRnm132v8BScu5/1BQ8g==} - - eslint-module-utils@2.12.0: - resolution: {integrity: sha512-wALZ0HFoytlyh/1+4wuZ9FJCD/leWHQzzrxJ8+rebyReSLk7LApMyd3WJaLVoN+D5+WIdJyDK1c6JnE65V4Zyg==} - engines: {node: '>=4'} - peerDependencies: - '@typescript-eslint/parser': '*' - eslint: '*' - eslint-import-resolver-node: '*' - eslint-import-resolver-typescript: '*' - eslint-import-resolver-webpack: '*' - peerDependenciesMeta: - '@typescript-eslint/parser': - optional: true - eslint: - optional: true - eslint-import-resolver-node: - optional: true - eslint-import-resolver-typescript: - optional: true - eslint-import-resolver-webpack: - optional: true - - eslint-plugin-import@2.31.0: - resolution: {integrity: sha512-ixmkI62Rbc2/w8Vfxyh1jQRTdRTF52VxwRVHl/ykPAmqG+Nb7/kNn+byLP0LxPgI7zWA16Jt82SybJInmMia3A==} - engines: {node: '>=4'} - peerDependencies: - '@typescript-eslint/parser': '*' - eslint: ^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8 || ^9 - peerDependenciesMeta: - '@typescript-eslint/parser': - optional: true - - eslint-scope@7.2.2: - resolution: {integrity: sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==} - engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} - - eslint-visitor-keys@3.4.3: - resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==} - engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} - - eslint@8.57.0: - resolution: {integrity: sha512-dZ6+mexnaTIbSBZWgou51U6OmzIhYM2VcNdtiTtI7qPNZm35Akpr0f6vtw3w1Kmn5PYo+tZVfh13WrhpS6oLqQ==} - engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} - deprecated: This version is no longer supported. Please see https://eslint.org/version-support for other options. - hasBin: true - - espree@9.6.1: - resolution: {integrity: sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==} - engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} - esprima@4.0.1: resolution: {integrity: sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==} engines: {node: '>=4'} hasBin: true - esquery@1.6.0: - resolution: {integrity: sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==} - engines: {node: '>=0.10'} - - esrecurse@4.3.0: - resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} - engines: {node: '>=4.0'} - - estraverse@5.3.0: - resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} - engines: {node: '>=4.0'} - estree-walker@3.0.3: resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} - esutils@2.0.3: - resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} - engines: {node: '>=0.10.0'} - eventemitter3@5.0.1: resolution: {integrity: sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==} @@ -1466,26 +1309,13 @@ packages: resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} engines: {node: '>=12.0.0'} - fast-deep-equal@3.1.3: - resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} - fast-equals@6.0.2: resolution: {integrity: sha512-sAjhj9ZhOxYCGiNMnZLaucOqf5ZeFnHNoKoAZiD9thhJ0N8RP85qJK759/97C/3L7NzzmGVB5uiX9AUpySZmUQ==} engines: {node: '>=6.0.0'} - fast-glob@3.3.2: - resolution: {integrity: sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==} - engines: {node: '>=8.6.0'} - fast-json-stable-stringify@2.1.0: resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} - fast-levenshtein@2.0.6: - resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} - - fastq@1.17.1: - resolution: {integrity: sha512-sRVD3lWVIXWg6By68ZN7vho9a1pQcN/WBFaAAsDDFzlJjvoGx0P8z7V1t72grFJfJhu3YPZBuu25f7Kaw2jN1w==} - fdir@6.5.0: resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} engines: {node: '>=12.0.0'} @@ -1498,132 +1328,22 @@ packages: fflate@0.8.3: resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==} - file-entry-cache@6.0.1: - resolution: {integrity: sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==} - engines: {node: ^10.12.0 || >=12.0.0} - - fill-range@7.1.1: - resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} - engines: {node: '>=8'} - - find-up@5.0.0: - resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} - engines: {node: '>=10'} - - flat-cache@3.2.0: - resolution: {integrity: sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==} - engines: {node: ^10.12.0 || >=12.0.0} - flatted@3.4.4: resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} - for-each@0.3.3: - resolution: {integrity: sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==} - - fs.realpath@1.0.0: - resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==} - fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} os: [darwin] - function-bind@1.1.2: - resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} - - function.prototype.name@1.1.8: - resolution: {integrity: sha512-e5iwyodOHhbMr/yNrc7fDYG4qlbIvI5gajyzPnb5TCwyhjApznQh1BMFou9b30SevY43gCJKXycoCBjMbsuW0Q==} - engines: {node: '>= 0.4'} - - functions-have-names@1.2.3: - resolution: {integrity: sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==} - gensequence@8.0.8: resolution: {integrity: sha512-omMVniXEXpdx/vKxGnPRoO2394Otlze28TyxECbFVyoSpZ9H3EO7lemjcB12OpQJzRW4e5tt/dL1rOxry6aMHg==} engines: {node: '>=20'} - get-intrinsic@1.2.7: - resolution: {integrity: sha512-VW6Pxhsrk0KAOqs3WEd0klDiF/+V7gQOpAvY1jVU/LHmaD/kQO4523aiJuikX/QAKYiW6x8Jh+RJej1almdtCA==} - engines: {node: '>= 0.4'} - - get-proto@1.0.1: - resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==} - engines: {node: '>= 0.4'} - - get-symbol-description@1.1.0: - resolution: {integrity: sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==} - engines: {node: '>= 0.4'} - - glob-parent@5.1.2: - resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} - engines: {node: '>= 6'} - - glob-parent@6.0.2: - resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} - engines: {node: '>=10.13.0'} - - glob@7.2.3: - resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} - deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me - global-directory@5.0.0: resolution: {integrity: sha512-1pgFdhK3J2LeM+dVf2Pd424yHx2ou338lC0ErNP2hPx4j8eW1Sp0XqSjNxtk6Tc4Kr5wlWtSvz8cn2yb7/SG/w==} engines: {node: '>=20'} - globals@13.24.0: - resolution: {integrity: sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==} - engines: {node: '>=8'} - - globalthis@1.0.4: - resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==} - engines: {node: '>= 0.4'} - - globby@11.1.0: - resolution: {integrity: sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==} - engines: {node: '>=10'} - - gopd@1.2.0: - resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} - engines: {node: '>= 0.4'} - - graphemer@1.4.0: - resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==} - - has-bigints@1.1.0: - resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==} - engines: {node: '>= 0.4'} - - has-flag@4.0.0: - resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} - engines: {node: '>=8'} - - has-property-descriptors@1.0.2: - resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==} - - has-proto@1.2.0: - resolution: {integrity: sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==} - engines: {node: '>= 0.4'} - - has-symbols@1.1.0: - resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} - engines: {node: '>= 0.4'} - - has-tostringtag@1.0.2: - resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==} - engines: {node: '>= 0.4'} - - hasown@2.0.2: - resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==} - engines: {node: '>= 0.4'} - - ignore@5.3.2: - resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} - engines: {node: '>= 4'} - - import-fresh@3.3.0: - resolution: {integrity: sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==} - engines: {node: '>=6'} - import-fresh@4.0.0: resolution: {integrity: sha512-Fpi660c7VPDM3fPKYovStd9IP1CPOikf6v/dGxJJMmHPcwYQIMJ4W7kO1avBYEpMqkCh+Dx3Ln6H7VYqgztLjw==} engines: {node: '>=22.15'} @@ -1631,166 +1351,21 @@ packages: import-meta-resolve@4.2.0: resolution: {integrity: sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg==} - imurmurhash@0.1.4: - resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} - engines: {node: '>=0.8.19'} - - inflight@1.0.6: - resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==} - deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful. - - inherits@2.0.4: - resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} - ini@6.0.0: resolution: {integrity: sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ==} engines: {node: ^20.17.0 || >=22.9.0} - internal-slot@1.1.0: - resolution: {integrity: sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==} - engines: {node: '>= 0.4'} - - is-array-buffer@3.0.5: - resolution: {integrity: sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==} - engines: {node: '>= 0.4'} - - is-async-function@2.1.0: - resolution: {integrity: sha512-GExz9MtyhlZyXYLxzlJRj5WUCE661zhDa1Yna52CN57AJsymh+DvXXjyveSioqSRdxvUrdKdvqB1b5cVKsNpWQ==} - engines: {node: '>= 0.4'} - - is-bigint@1.1.0: - resolution: {integrity: sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==} - engines: {node: '>= 0.4'} - - is-boolean-object@1.2.1: - resolution: {integrity: sha512-l9qO6eFlUETHtuihLcYOaLKByJ1f+N4kthcU9YjHy3N+B3hWv0y/2Nd0mu/7lTFnRQHTrSdXF50HQ3bl5fEnng==} - engines: {node: '>= 0.4'} - - is-callable@1.2.7: - resolution: {integrity: sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==} - engines: {node: '>= 0.4'} - - is-core-module@2.16.1: - resolution: {integrity: sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==} - engines: {node: '>= 0.4'} - - is-data-view@1.0.2: - resolution: {integrity: sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==} - engines: {node: '>= 0.4'} - - is-date-object@1.1.0: - resolution: {integrity: sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==} - engines: {node: '>= 0.4'} - - is-extglob@2.1.1: - resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} - engines: {node: '>=0.10.0'} - - is-finalizationregistry@1.1.1: - resolution: {integrity: sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==} - engines: {node: '>= 0.4'} - - is-generator-function@1.1.0: - resolution: {integrity: sha512-nPUB5km40q9e8UfN/Zc24eLlzdSf9OfKByBw9CIdw4H1giPMeA0OIJvbchsCu4npfI2QcMVBsGEBHKZ7wLTWmQ==} - engines: {node: '>= 0.4'} - - is-glob@4.0.3: - resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} - engines: {node: '>=0.10.0'} - - is-map@2.0.3: - resolution: {integrity: sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==} - engines: {node: '>= 0.4'} - is-network-error@1.3.1: resolution: {integrity: sha512-6QCxa49rQbmUWLfk0nuGqzql9U8uaV2H6279bRErPBHe/109hCzsLUBUHfbEtvLIHBd6hyXbgedBSHevm43Edw==} engines: {node: '>=16'} - is-number-object@1.1.1: - resolution: {integrity: sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==} - engines: {node: '>= 0.4'} - - is-number@7.0.0: - resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} - engines: {node: '>=0.12.0'} - - is-path-inside@3.0.3: - resolution: {integrity: sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==} - engines: {node: '>=8'} - - is-regex@1.2.1: - resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==} - engines: {node: '>= 0.4'} - is-safe-filename@0.1.1: resolution: {integrity: sha512-4SrR7AdnY11LHfDKTZY1u6Ga3RuxZdl3YKWWShO5iyuG5h8QS4GD2tOb04peBJ5I7pXbR+CGBNEhTcwK+FzN3g==} engines: {node: '>=20'} - is-set@2.0.3: - resolution: {integrity: sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==} - engines: {node: '>= 0.4'} - - is-shared-array-buffer@1.0.4: - resolution: {integrity: sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==} - engines: {node: '>= 0.4'} - - is-string@1.1.1: - resolution: {integrity: sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==} - engines: {node: '>= 0.4'} - - is-symbol@1.1.1: - resolution: {integrity: sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==} - engines: {node: '>= 0.4'} - - is-typed-array@1.1.15: - resolution: {integrity: sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==} - engines: {node: '>= 0.4'} - - is-weakmap@2.0.2: - resolution: {integrity: sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==} - engines: {node: '>= 0.4'} - - is-weakref@1.1.0: - resolution: {integrity: sha512-SXM8Nwyys6nT5WP6pltOwKytLV7FqQ4UiibxVmW+EIosHcmCqkkjViTb5SNssDlkCiEYRP1/pdWUKVvZBmsR2Q==} - engines: {node: '>= 0.4'} - - is-weakset@2.0.4: - resolution: {integrity: sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==} - engines: {node: '>= 0.4'} - - isarray@2.0.5: - resolution: {integrity: sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==} - - isexe@2.0.0: - resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} - js-tokens@10.0.0: resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==} - js-yaml@4.1.0: - resolution: {integrity: sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==} - hasBin: true - - json-buffer@3.0.1: - resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==} - - json-schema-traverse@0.4.1: - resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} - - json-stable-stringify-without-jsonify@1.0.1: - resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} - - json5@1.0.2: - resolution: {integrity: sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==} - hasBin: true - - keyv@4.5.4: - resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} - - levn@0.4.1: - resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} - engines: {node: '>= 0.8.0'} - lightningcss-android-arm64@1.33.0: resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} engines: {node: '>= 12.0.0'} @@ -1865,13 +1440,6 @@ packages: resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} engines: {node: '>= 12.0.0'} - locate-path@6.0.0: - resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} - engines: {node: '>=10'} - - lodash.merge@4.6.2: - resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==} - lossless-json@4.0.2: resolution: {integrity: sha512-+z0EaLi2UcWi8MZRxA5iTb6m4Ys4E80uftGY+yG5KNFJb5EceQXOhdW/pWJZ8m97s26u7yZZAYMcKWNztSZssA==} @@ -1881,28 +1449,6 @@ packages: magicast@0.5.5: resolution: {integrity: sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==} - math-intrinsics@1.1.0: - resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} - engines: {node: '>= 0.4'} - - merge2@1.4.1: - resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==} - engines: {node: '>= 8'} - - micromatch@4.0.8: - resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==} - engines: {node: '>=8.6'} - - minimatch@3.1.2: - resolution: {integrity: sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==} - - minimatch@9.0.5: - resolution: {integrity: sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==} - engines: {node: '>=16 || 14 >=14.17'} - - minimist@1.2.8: - resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} - ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} @@ -1911,59 +1457,38 @@ packages: engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true - natural-compare@1.4.0: - resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} - - object-inspect@1.13.3: - resolution: {integrity: sha512-kDCGIbxkDSXE3euJZZXzc6to7fCrKHNI/hSRQnRuQ+BWjFNzZwiFF8fj/6o2t2G9/jTj8PSIYTfCLelLZEeRpA==} - engines: {node: '>= 0.4'} - - object-keys@1.1.1: - resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==} - engines: {node: '>= 0.4'} - - object.assign@4.1.7: - resolution: {integrity: sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==} - engines: {node: '>= 0.4'} - - object.entries@1.1.7: - resolution: {integrity: sha512-jCBs/0plmPsOnrKAfFQXRG2NFjlhZgjjcBLSmTnEhU8U6vVTsVe8ANeQJCHTl3gSsI4J+0emOoCgoKlmQPMgmA==} - engines: {node: '>= 0.4'} - - object.fromentries@2.0.8: - resolution: {integrity: sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==} - engines: {node: '>= 0.4'} - - object.groupby@1.0.3: - resolution: {integrity: sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==} - engines: {node: '>= 0.4'} - - object.values@1.2.1: - resolution: {integrity: sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==} - engines: {node: '>= 0.4'} - obug@2.2.1: resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==} engines: {node: '>=12.20.0'} - once@1.4.0: - resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} - - optionator@0.9.4: - resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} - engines: {node: '>= 0.8.0'} - - own-keys@1.0.1: - resolution: {integrity: sha512-qFOyK5PjiWZd+QQIh+1jhdb9LpxTF0qs7Pm8o5QHYZ0M3vKqSqzsZaEB6oWlxZ+q2sJBMI/Ktgd2N5ZwQoRHfg==} - engines: {node: '>= 0.4'} - - p-limit@3.1.0: - resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} - engines: {node: '>=10'} + oxfmt@0.81.0: + resolution: {integrity: sha512-EIuSGUDB9hoHgppuQzTKI3DI1UJzPFTUrf3GGPqSef1tbdY1UNHsy240cOsPDxHFdvW6PJLr3WHS2RG1qvnd8Q==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@astrojs/compiler-rs': ^0.5.0 + svelte: ^5.0.0 + vite-plus: '*' + peerDependenciesMeta: + '@astrojs/compiler-rs': + optional: true + svelte: + optional: true + vite-plus: + optional: true - p-locate@5.0.0: - resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} - engines: {node: '>=10'} + oxlint@1.96.0: + resolution: {integrity: sha512-jyiSvUjzM6GPHNbNQSk9ov63KDusn7FJaIX4LqxJYN/VnRrEgwMplyZaoAfmVclfzxCmVhaIXLixnRJ2IAa0Hw==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + oxlint-tsgolint: '>=7.0.2008' + vite-plus: '*' + peerDependenciesMeta: + oxlint-tsgolint: + optional: true + vite-plus: + optional: true p-queue@9.1.2: resolution: {integrity: sha512-ktsDOALzTYTWWF1PbkNVg2rOt+HaOaMWJMUnt7T3qf5tvZ1L8dBW3tObzprBcXNMKkwj+yFSLqHso0x+UFcJXw==} @@ -1977,161 +1502,34 @@ packages: resolution: {integrity: sha512-AxTM2wDGORHGEkPCt8yqxOTMgpfbEHqF51f/5fJCmwFC3C/zNcGT63SymH2ttOAaiIws2zVg4+izQCjrakcwHg==} engines: {node: '>=20'} - parent-module@1.0.1: - resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} - engines: {node: '>=6'} - - path-exists@4.0.0: - resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} - engines: {node: '>=8'} - - path-is-absolute@1.0.1: - resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==} - engines: {node: '>=0.10.0'} - - path-key@3.1.1: - resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} - engines: {node: '>=8'} - - path-parse@1.0.7: - resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} - - path-type@4.0.0: - resolution: {integrity: sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==} - engines: {node: '>=8'} - picocolors@1.1.1: resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} - picomatch@2.3.1: - resolution: {integrity: sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==} - engines: {node: '>=8.6'} - picomatch@4.0.7: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} - possible-typed-array-names@1.0.0: - resolution: {integrity: sha512-d7Uw+eZoloe0EHDIYoe+bQ5WXnGMOpmiZFTuMWCwpjzzkL2nTjcKiAk4hh8TjnGye2TwWOk3UXucZ+3rbmBa8Q==} - engines: {node: '>= 0.4'} - postcss@8.5.28: resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==} engines: {node: ^10 || ^12 || >=14} - prelude-ls@1.2.1: - resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} - engines: {node: '>= 0.8.0'} - - punycode@2.3.1: - resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} - engines: {node: '>=6'} - - queue-microtask@1.2.3: - resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==} - - reflect.getprototypeof@1.0.10: - resolution: {integrity: sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==} - engines: {node: '>= 0.4'} - - regexp.prototype.flags@1.5.4: - resolution: {integrity: sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==} - engines: {node: '>= 0.4'} - - resolve-from@4.0.0: - resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} - engines: {node: '>=4'} - resolve-from@5.0.0: resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==} engines: {node: '>=8'} - resolve@1.22.10: - resolution: {integrity: sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w==} - engines: {node: '>= 0.4'} - hasBin: true - - reusify@1.0.4: - resolution: {integrity: sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==} - engines: {iojs: '>=1.0.0', node: '>=0.10.0'} - - rimraf@3.0.2: - resolution: {integrity: sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==} - deprecated: Rimraf versions prior to v4 are no longer supported - hasBin: true - rolldown@1.2.10: resolution: {integrity: sha512-OxkA08pSryMK7B3XiFA09B4OJ1xJMPgIYCBMY2xchzpqgBGsV1o0DetPAE+Sl3N3L4oCPiEzmHVSOj7iR04Zog==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true - run-parallel@1.2.0: - resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} - - safe-array-concat@1.1.3: - resolution: {integrity: sha512-AURm5f0jYEOydBj7VQlVvDrjeFgthDdEF5H1dP+6mNpoXOMo1quQqJ4wvJDyRZ9+pO3kGWoOdmV08cSv2aJV6Q==} - engines: {node: '>=0.4'} - - safe-push-apply@1.0.0: - resolution: {integrity: sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==} - engines: {node: '>= 0.4'} - - safe-regex-test@1.1.0: - resolution: {integrity: sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==} - engines: {node: '>= 0.4'} - - semver@6.3.1: - resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==} - hasBin: true - semver@7.8.5: resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} engines: {node: '>=10'} hasBin: true - set-function-length@1.2.2: - resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==} - engines: {node: '>= 0.4'} - - set-function-name@2.0.2: - resolution: {integrity: sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==} - engines: {node: '>= 0.4'} - - set-proto@1.0.0: - resolution: {integrity: sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==} - engines: {node: '>= 0.4'} - - shebang-command@2.0.0: - resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} - engines: {node: '>=8'} - - shebang-regex@3.0.0: - resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} - engines: {node: '>=8'} - - side-channel-list@1.0.0: - resolution: {integrity: sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==} - engines: {node: '>= 0.4'} - - side-channel-map@1.0.1: - resolution: {integrity: sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==} - engines: {node: '>= 0.4'} - - side-channel-weakmap@1.0.2: - resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==} - engines: {node: '>= 0.4'} - - side-channel@1.1.0: - resolution: {integrity: sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==} - engines: {node: '>= 0.4'} - siginfo@2.0.0: resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} - slash@3.0.0: - resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==} - engines: {node: '>=8'} - smol-toml@1.7.1: resolution: {integrity: sha512-PPlsspAZ4jbMBu5DMFhfUGDQLu/vrL4SyBROVS37x8ynnVmFIs1VPBz1Co8Xks3TvpIaZXmU85y4DrQ+UyVFoQ==} engines: {node: '>= 18'} @@ -2146,41 +1544,6 @@ packages: std-env@4.2.0: resolution: {integrity: sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==} - string.prototype.trim@1.2.10: - resolution: {integrity: sha512-Rs66F0P/1kedk5lyYyH9uBzuiI/kNRmwJAR9quK6VOtIpZ2G+hMZd+HQbbv25MgCA6gEffoMZYxlTod4WcdrKA==} - engines: {node: '>= 0.4'} - - string.prototype.trimend@1.0.9: - resolution: {integrity: sha512-G7Ok5C6E/j4SGfyLCloXTrngQIQU3PWtXGst3yM7Bea9FRURf1S42ZHlZZtsNque2FN2PoUhfZXYLNWwEr4dLQ==} - engines: {node: '>= 0.4'} - - string.prototype.trimstart@1.0.8: - resolution: {integrity: sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==} - engines: {node: '>= 0.4'} - - strip-ansi@6.0.1: - resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} - engines: {node: '>=8'} - - strip-bom@3.0.0: - resolution: {integrity: sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==} - engines: {node: '>=4'} - - strip-json-comments@3.1.1: - resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==} - engines: {node: '>=8'} - - supports-color@7.2.0: - resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} - engines: {node: '>=8'} - - supports-preserve-symlinks-flag@1.0.0: - resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} - engines: {node: '>= 0.4'} - - text-table@0.2.0: - resolution: {integrity: sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==} - tinybench@6.1.4: resolution: {integrity: sha512-9APumHG7r4yOk4X4WlkmE71aZcv1gvin1czO3OQ1U9iJcFA5Ja/ygyb0vPOVHTthFozUYs8CLoLUlM8grb2lTQ==} engines: {node: '>=20.0.0'} @@ -2193,23 +1556,14 @@ packages: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} + tinypool@2.2.0: + resolution: {integrity: sha512-jBrmx4lYmaC9k/mgPbylxs7kBUxHtD8256up+HjLaDFfXScKJQyil+SWXSvhAtT7XHo+yTVlpB81PGmHP8oLSQ==} + engines: {node: ^20.0.0 || >=22.0.0} + tinyrainbow@3.1.1: resolution: {integrity: sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==} engines: {node: '>=14.0.0'} - to-regex-range@5.0.1: - resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} - engines: {node: '>=8.0'} - - ts-api-utils@1.3.0: - resolution: {integrity: sha512-UQMIo7pb8WRomKR1/+MFVLTroIvDVtMX3K6OUir8ynLyzB8Jeriont2bTAtmNPa1ekAgN7YPDyf6V+ygrdU+eQ==} - engines: {node: '>=16'} - peerDependencies: - typescript: '>=4.2.0' - - tsconfig-paths@3.15.0: - resolution: {integrity: sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==} - tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} @@ -2218,45 +1572,14 @@ packages: engines: {node: '>=18.0.0'} hasBin: true - type-check@0.4.0: - resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} - engines: {node: '>= 0.8.0'} - - type-fest@0.20.2: - resolution: {integrity: sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==} - engines: {node: '>=10'} - - typed-array-buffer@1.0.3: - resolution: {integrity: sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==} - engines: {node: '>= 0.4'} - - typed-array-byte-length@1.0.3: - resolution: {integrity: sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==} - engines: {node: '>= 0.4'} - - typed-array-byte-offset@1.0.4: - resolution: {integrity: sha512-bTlAFB/FBYMcuX81gbL4OcpH5PmlFHqlCCpAl8AlEzMz5k53oNDvN8p1PNOWLEmI2x4orp3raOFB51tv9X+MFQ==} - engines: {node: '>= 0.4'} - - typed-array-length@1.0.7: - resolution: {integrity: sha512-3KS2b+kL7fsuk/eJZ7EQdnEmQoaho/r6KUef7hxvltNA5DR8NAUM+8wJMbJyZ4G9/7i3v5zPBIMN5aybAh2/Jg==} - engines: {node: '>= 0.4'} - typescript@5.9.2: resolution: {integrity: sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==} engines: {node: '>=14.17'} hasBin: true - unbox-primitive@1.1.0: - resolution: {integrity: sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==} - engines: {node: '>= 0.4'} - undici-types@7.18.2: resolution: {integrity: sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==} - uri-js@4.4.1: - resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} - vite@8.3.0: resolution: {integrity: sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ==} engines: {node: ^20.19.0 || >=22.12.0} @@ -2347,39 +1670,11 @@ packages: vscode-uri@3.1.0: resolution: {integrity: sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==} - which-boxed-primitive@1.1.1: - resolution: {integrity: sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==} - engines: {node: '>= 0.4'} - - which-builtin-type@1.2.1: - resolution: {integrity: sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==} - engines: {node: '>= 0.4'} - - which-collection@1.0.2: - resolution: {integrity: sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==} - engines: {node: '>= 0.4'} - - which-typed-array@1.1.18: - resolution: {integrity: sha512-qEcY+KJYlWyLH9vNbsr6/5j59AXk5ni5aakf8ldzBvGde6Iz4sxZGkJyWSAueTG7QhOvNRYb1lDdFmL5Td0QKA==} - engines: {node: '>= 0.4'} - - which@2.0.2: - resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} - engines: {node: '>= 8'} - hasBin: true - why-is-node-running@2.3.0: resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} engines: {node: '>=8'} hasBin: true - word-wrap@1.2.5: - resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} - engines: {node: '>=0.10.0'} - - wrappy@1.0.2: - resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} - ws@8.21.3: resolution: {integrity: sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==} engines: {node: '>=10.0.0'} @@ -2401,10 +1696,6 @@ packages: engines: {node: '>= 14.6'} hasBin: true - yocto-queue@0.1.0: - resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} - engines: {node: '>=10'} - snapshots: '@babel/helper-string-parser@7.29.7': {} @@ -2646,19 +1937,19 @@ snapshots: '@cspell/url@10.0.1': {} - '@electrum-cash/debug-logs@1.0.0(supports-color@7.2.0)': + '@electrum-cash/debug-logs@1.0.0': dependencies: - debug: 4.4.0(supports-color@7.2.0) + debug: 4.4.0 transitivePeerDependencies: - supports-color - '@electrum-cash/network@4.4.0(supports-color@7.2.0)': + '@electrum-cash/network@4.4.0': dependencies: - '@electrum-cash/debug-logs': 1.0.0(supports-color@7.2.0) + '@electrum-cash/debug-logs': 1.0.0 '@electrum-cash/socket': 4.1.0 - '@electrum-cash/web-socket': 4.1.0(supports-color@7.2.0) + '@electrum-cash/web-socket': 4.1.0 async-mutex: 0.5.0 - debug: 4.4.0(supports-color@7.2.0) + debug: 4.4.0 eventemitter3: 5.0.1 lossless-json: 4.0.2 transitivePeerDependencies: @@ -2668,9 +1959,9 @@ snapshots: '@electrum-cash/socket@4.1.0': {} - '@electrum-cash/web-socket@4.1.0(supports-color@7.2.0)': + '@electrum-cash/web-socket@4.1.0': dependencies: - '@electrum-cash/debug-logs': 1.0.0(supports-color@7.2.0) + '@electrum-cash/debug-logs': 1.0.0 '@electrum-cash/socket': 4.1.0 '@monsterbitar/isomorphic-ws': 5.3.1(ws@8.21.3) '@types/ws': 8.5.14 @@ -2761,67 +2052,134 @@ snapshots: '@esbuild/win32-x64@0.28.2': optional: true - '@eslint-community/eslint-utils@4.4.0(eslint@8.57.0(supports-color@7.2.0))': - dependencies: - eslint: 8.57.0(supports-color@7.2.0) - eslint-visitor-keys: 3.4.3 + '@jridgewell/resolve-uri@3.1.2': {} - '@eslint-community/regexpp@4.11.0': {} + '@jridgewell/sourcemap-codec@1.6.0': {} - '@eslint/eslintrc@2.1.4(supports-color@7.2.0)': + '@jridgewell/trace-mapping@0.3.31': dependencies: - ajv: 6.12.6 - debug: 4.4.0(supports-color@7.2.0) - espree: 9.6.1 - globals: 13.24.0 - ignore: 5.3.2 - import-fresh: 3.3.0 - js-yaml: 4.1.0 - minimatch: 3.1.2 - strip-json-comments: 3.1.1 - transitivePeerDependencies: - - supports-color - - '@eslint/js@8.57.0': {} + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.6.0 - '@humanwhocodes/config-array@0.11.14(supports-color@7.2.0)': + '@monsterbitar/isomorphic-ws@5.3.1(ws@8.21.3)': dependencies: - '@humanwhocodes/object-schema': 2.0.3 - debug: 4.4.0(supports-color@7.2.0) - minimatch: 3.1.2 - transitivePeerDependencies: - - supports-color + ws: 8.21.3 - '@humanwhocodes/module-importer@1.0.1': {} + '@oxc-project/types@0.151.0': {} - '@humanwhocodes/object-schema@2.0.3': {} + '@oxfmt/binding-android-arm-eabi@0.81.0': + optional: true - '@jridgewell/resolve-uri@3.1.2': {} + '@oxfmt/binding-android-arm64@0.81.0': + optional: true - '@jridgewell/sourcemap-codec@1.6.0': {} + '@oxfmt/binding-darwin-arm64@0.81.0': + optional: true - '@jridgewell/trace-mapping@0.3.31': - dependencies: - '@jridgewell/resolve-uri': 3.1.2 - '@jridgewell/sourcemap-codec': 1.6.0 + '@oxfmt/binding-darwin-x64@0.81.0': + optional: true - '@monsterbitar/isomorphic-ws@5.3.1(ws@8.21.3)': - dependencies: - ws: 8.21.3 + '@oxfmt/binding-freebsd-x64@0.81.0': + optional: true - '@nodelib/fs.scandir@2.1.5': - dependencies: - '@nodelib/fs.stat': 2.0.5 - run-parallel: 1.2.0 + '@oxfmt/binding-linux-arm-gnueabihf@0.81.0': + optional: true - '@nodelib/fs.stat@2.0.5': {} + '@oxfmt/binding-linux-arm-musleabihf@0.81.0': + optional: true - '@nodelib/fs.walk@1.2.8': - dependencies: - '@nodelib/fs.scandir': 2.1.5 - fastq: 1.17.1 + '@oxfmt/binding-linux-arm64-gnu@0.81.0': + optional: true - '@oxc-project/types@0.151.0': {} + '@oxfmt/binding-linux-arm64-musl@0.81.0': + optional: true + + '@oxfmt/binding-linux-ppc64-gnu@0.81.0': + optional: true + + '@oxfmt/binding-linux-riscv64-gnu@0.81.0': + optional: true + + '@oxfmt/binding-linux-riscv64-musl@0.81.0': + optional: true + + '@oxfmt/binding-linux-s390x-gnu@0.81.0': + optional: true + + '@oxfmt/binding-linux-x64-gnu@0.81.0': + optional: true + + '@oxfmt/binding-linux-x64-musl@0.81.0': + optional: true + + '@oxfmt/binding-openharmony-arm64@0.81.0': + optional: true + + '@oxfmt/binding-win32-arm64-msvc@0.81.0': + optional: true + + '@oxfmt/binding-win32-ia32-msvc@0.81.0': + optional: true + + '@oxfmt/binding-win32-x64-msvc@0.81.0': + optional: true + + '@oxlint/binding-android-arm-eabi@1.96.0': + optional: true + + '@oxlint/binding-android-arm64@1.96.0': + optional: true + + '@oxlint/binding-darwin-arm64@1.96.0': + optional: true + + '@oxlint/binding-darwin-x64@1.96.0': + optional: true + + '@oxlint/binding-freebsd-x64@1.96.0': + optional: true + + '@oxlint/binding-linux-arm-gnueabihf@1.96.0': + optional: true + + '@oxlint/binding-linux-arm-musleabihf@1.96.0': + optional: true + + '@oxlint/binding-linux-arm64-gnu@1.96.0': + optional: true + + '@oxlint/binding-linux-arm64-musl@1.96.0': + optional: true + + '@oxlint/binding-linux-ppc64-gnu@1.96.0': + optional: true + + '@oxlint/binding-linux-riscv64-gnu@1.96.0': + optional: true + + '@oxlint/binding-linux-riscv64-musl@1.96.0': + optional: true + + '@oxlint/binding-linux-s390x-gnu@1.96.0': + optional: true + + '@oxlint/binding-linux-x64-gnu@1.96.0': + optional: true + + '@oxlint/binding-linux-x64-musl@1.96.0': + optional: true + + '@oxlint/binding-openharmony-arm64@1.96.0': + optional: true + + '@oxlint/binding-win32-arm64-msvc@1.96.0': + optional: true + + '@oxlint/binding-win32-ia32-msvc@1.96.0': + optional: true + + '@oxlint/binding-win32-x64-msvc@1.96.0': + optional: true '@rolldown/binding-android-arm-eabi@1.2.10': optional: true @@ -2870,8 +2228,6 @@ snapshots: '@rolldown/pluginutils@1.0.1': {} - '@rtsao/scc@1.1.0': {} - '@types/chai@5.2.2': dependencies: '@types/deep-eql': 4.0.2 @@ -2880,8 +2236,6 @@ snapshots: '@types/estree@1.0.8': {} - '@types/json5@0.0.29': {} - '@types/node@24.13.3': dependencies: undici-types: 7.18.2 @@ -2892,89 +2246,6 @@ snapshots: dependencies: '@types/node': 24.13.3 - '@typescript-eslint/eslint-plugin@7.18.0(@typescript-eslint/parser@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2))(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2)': - dependencies: - '@eslint-community/regexpp': 4.11.0 - '@typescript-eslint/parser': 7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2) - '@typescript-eslint/scope-manager': 7.18.0 - '@typescript-eslint/type-utils': 7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2) - '@typescript-eslint/utils': 7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2) - '@typescript-eslint/visitor-keys': 7.18.0 - eslint: 8.57.0(supports-color@7.2.0) - graphemer: 1.4.0 - ignore: 5.3.2 - natural-compare: 1.4.0 - ts-api-utils: 1.3.0(typescript@5.9.2) - optionalDependencies: - typescript: 5.9.2 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/parser@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2)': - dependencies: - '@typescript-eslint/scope-manager': 7.18.0 - '@typescript-eslint/types': 7.18.0 - '@typescript-eslint/typescript-estree': 7.18.0(supports-color@7.2.0)(typescript@5.9.2) - '@typescript-eslint/visitor-keys': 7.18.0 - debug: 4.4.0(supports-color@7.2.0) - eslint: 8.57.0(supports-color@7.2.0) - optionalDependencies: - typescript: 5.9.2 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/scope-manager@7.18.0': - dependencies: - '@typescript-eslint/types': 7.18.0 - '@typescript-eslint/visitor-keys': 7.18.0 - - '@typescript-eslint/type-utils@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2)': - dependencies: - '@typescript-eslint/typescript-estree': 7.18.0(supports-color@7.2.0)(typescript@5.9.2) - '@typescript-eslint/utils': 7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2) - debug: 4.4.0(supports-color@7.2.0) - eslint: 8.57.0(supports-color@7.2.0) - ts-api-utils: 1.3.0(typescript@5.9.2) - optionalDependencies: - typescript: 5.9.2 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/types@7.18.0': {} - - '@typescript-eslint/typescript-estree@7.18.0(supports-color@7.2.0)(typescript@5.9.2)': - dependencies: - '@typescript-eslint/types': 7.18.0 - '@typescript-eslint/visitor-keys': 7.18.0 - debug: 4.4.0(supports-color@7.2.0) - globby: 11.1.0 - is-glob: 4.0.3 - minimatch: 9.0.5 - semver: 7.8.5 - ts-api-utils: 1.3.0(typescript@5.9.2) - optionalDependencies: - typescript: 5.9.2 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/utils@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2)': - dependencies: - '@eslint-community/eslint-utils': 4.4.0(eslint@8.57.0(supports-color@7.2.0)) - '@typescript-eslint/scope-manager': 7.18.0 - '@typescript-eslint/types': 7.18.0 - '@typescript-eslint/typescript-estree': 7.18.0(supports-color@7.2.0)(typescript@5.9.2) - eslint: 8.57.0(supports-color@7.2.0) - transitivePeerDependencies: - - supports-color - - typescript - - '@typescript-eslint/visitor-keys@7.18.0': - dependencies: - '@typescript-eslint/types': 7.18.0 - eslint-visitor-keys: 3.4.3 - - '@ungap/structured-clone@1.2.0': {} - '@vitest/coverage-v8@5.0.1(vitest@5.0.1)': dependencies: '@bcoe/v8-coverage': 1.0.2 @@ -3004,82 +2275,12 @@ snapshots: '@vitest/spy@5.0.1': {} - acorn-jsx@5.3.2(acorn@8.12.1): - dependencies: - acorn: 8.12.1 - - acorn@8.12.1: {} - - ajv@6.12.6: - dependencies: - fast-deep-equal: 3.1.3 - fast-json-stable-stringify: 2.1.0 - json-schema-traverse: 0.4.1 - uri-js: 4.4.1 - - ansi-regex@5.0.1: {} - ansi-regex@6.2.2: {} - ansi-styles@4.3.0: - dependencies: - color-convert: 2.0.1 - antlr4@4.13.2: {} - argparse@2.0.1: {} - - array-buffer-byte-length@1.0.2: - dependencies: - call-bound: 1.0.3 - is-array-buffer: 3.0.5 - - array-includes@3.1.8: - dependencies: - call-bind: 1.0.8 - define-properties: 1.2.1 - es-abstract: 1.23.9 - es-object-atoms: 1.1.1 - get-intrinsic: 1.2.7 - is-string: 1.1.1 - array-timsort@1.0.3: {} - array-union@2.1.0: {} - - array.prototype.findlastindex@1.2.5: - dependencies: - call-bind: 1.0.8 - define-properties: 1.2.1 - es-abstract: 1.23.9 - es-errors: 1.3.0 - es-object-atoms: 1.1.1 - es-shim-unscopables: 1.0.2 - - array.prototype.flat@1.3.3: - dependencies: - call-bind: 1.0.8 - define-properties: 1.2.1 - es-abstract: 1.23.9 - es-shim-unscopables: 1.0.2 - - array.prototype.flatmap@1.3.3: - dependencies: - call-bind: 1.0.8 - define-properties: 1.2.1 - es-abstract: 1.23.9 - es-shim-unscopables: 1.0.2 - - arraybuffer.prototype.slice@1.0.4: - dependencies: - array-buffer-byte-length: 1.0.2 - call-bind: 1.0.8 - define-properties: 1.2.1 - es-abstract: 1.23.9 - es-errors: 1.3.0 - get-intrinsic: 1.2.7 - is-array-buffer: 3.0.5 - ast-v8-to-istanbul@1.0.7: dependencies: '@jridgewell/trace-mapping': 0.3.31 @@ -3090,63 +2291,14 @@ snapshots: dependencies: tslib: 2.8.1 - available-typed-arrays@1.0.7: - dependencies: - possible-typed-array-names: 1.0.0 - - balanced-match@1.0.2: {} - - brace-expansion@1.1.11: - dependencies: - balanced-match: 1.0.2 - concat-map: 0.0.1 - - brace-expansion@2.0.1: - dependencies: - balanced-match: 1.0.2 - - braces@3.0.3: - dependencies: - fill-range: 7.1.1 - - call-bind-apply-helpers@1.0.1: - dependencies: - es-errors: 1.3.0 - function-bind: 1.1.2 - - call-bind@1.0.8: - dependencies: - call-bind-apply-helpers: 1.0.1 - es-define-property: 1.0.1 - get-intrinsic: 1.2.7 - set-function-length: 1.2.2 - - call-bound@1.0.3: - dependencies: - call-bind-apply-helpers: 1.0.1 - get-intrinsic: 1.2.7 - - callsites@3.1.0: {} - chai@6.2.2: {} chalk-template@1.1.2: dependencies: chalk: 5.6.2 - chalk@4.1.2: - dependencies: - ansi-styles: 4.3.0 - supports-color: 7.2.0 - chalk@5.6.2: {} - color-convert@2.0.1: - dependencies: - color-name: 1.1.4 - - color-name@1.1.4: {} - commander@14.0.3: {} comment-json@5.0.0: @@ -3154,16 +2306,6 @@ snapshots: array-timsort: 1.0.3 esprima: 4.0.1 - concat-map@0.0.1: {} - - confusing-browser-globals@1.0.10: {} - - cross-spawn@7.0.3: - dependencies: - path-key: 3.1.1 - shebang-command: 2.0.0 - which: 2.0.2 - cspell-config-lib@10.0.1: dependencies: '@cspell/cspell-types': 10.0.1 @@ -3254,155 +2396,18 @@ snapshots: semver: 7.8.5 tinyglobby: 0.2.17 - data-view-buffer@1.0.2: - dependencies: - call-bound: 1.0.3 - es-errors: 1.3.0 - is-data-view: 1.0.2 - - data-view-byte-length@1.0.2: - dependencies: - call-bound: 1.0.3 - es-errors: 1.3.0 - is-data-view: 1.0.2 - - data-view-byte-offset@1.0.1: - dependencies: - call-bound: 1.0.3 - es-errors: 1.3.0 - is-data-view: 1.0.2 - - debug@3.2.7(supports-color@7.2.0): - dependencies: - ms: 2.1.3 - optionalDependencies: - supports-color: 7.2.0 - - debug@4.4.0(supports-color@7.2.0): + debug@4.4.0: dependencies: ms: 2.1.3 - optionalDependencies: - supports-color: 7.2.0 - - deep-is@0.1.4: {} - - define-data-property@1.1.4: - dependencies: - es-define-property: 1.0.1 - es-errors: 1.3.0 - gopd: 1.2.0 - - define-properties@1.2.1: - dependencies: - define-data-property: 1.1.4 - has-property-descriptors: 1.0.2 - object-keys: 1.1.1 detect-libc@2.1.2: {} - dir-glob@3.0.1: - dependencies: - path-type: 4.0.0 - - doctrine@2.1.0: - dependencies: - esutils: 2.0.3 - - doctrine@3.0.0: - dependencies: - esutils: 2.0.3 - - dunder-proto@1.0.1: - dependencies: - call-bind-apply-helpers: 1.0.1 - es-errors: 1.3.0 - gopd: 1.2.0 - env-paths@4.0.0: dependencies: is-safe-filename: 0.1.1 - es-abstract@1.23.9: - dependencies: - array-buffer-byte-length: 1.0.2 - arraybuffer.prototype.slice: 1.0.4 - available-typed-arrays: 1.0.7 - call-bind: 1.0.8 - call-bound: 1.0.3 - data-view-buffer: 1.0.2 - data-view-byte-length: 1.0.2 - data-view-byte-offset: 1.0.1 - es-define-property: 1.0.1 - es-errors: 1.3.0 - es-object-atoms: 1.1.1 - es-set-tostringtag: 2.1.0 - es-to-primitive: 1.3.0 - function.prototype.name: 1.1.8 - get-intrinsic: 1.2.7 - get-proto: 1.0.1 - get-symbol-description: 1.1.0 - globalthis: 1.0.4 - gopd: 1.2.0 - has-property-descriptors: 1.0.2 - has-proto: 1.2.0 - has-symbols: 1.1.0 - hasown: 2.0.2 - internal-slot: 1.1.0 - is-array-buffer: 3.0.5 - is-callable: 1.2.7 - is-data-view: 1.0.2 - is-regex: 1.2.1 - is-shared-array-buffer: 1.0.4 - is-string: 1.1.1 - is-typed-array: 1.1.15 - is-weakref: 1.1.0 - math-intrinsics: 1.1.0 - object-inspect: 1.13.3 - object-keys: 1.1.1 - object.assign: 4.1.7 - own-keys: 1.0.1 - regexp.prototype.flags: 1.5.4 - safe-array-concat: 1.1.3 - safe-push-apply: 1.0.0 - safe-regex-test: 1.1.0 - set-proto: 1.0.0 - string.prototype.trim: 1.2.10 - string.prototype.trimend: 1.0.9 - string.prototype.trimstart: 1.0.8 - typed-array-buffer: 1.0.3 - typed-array-byte-length: 1.0.3 - typed-array-byte-offset: 1.0.4 - typed-array-length: 1.0.7 - unbox-primitive: 1.1.0 - which-typed-array: 1.1.18 - - es-define-property@1.0.1: {} - - es-errors@1.3.0: {} - es-module-lexer@2.3.2: {} - es-object-atoms@1.1.1: - dependencies: - es-errors: 1.3.0 - - es-set-tostringtag@2.1.0: - dependencies: - es-errors: 1.3.0 - get-intrinsic: 1.2.7 - has-tostringtag: 1.0.2 - hasown: 2.0.2 - - es-shim-unscopables@1.0.2: - dependencies: - hasown: 2.0.2 - - es-to-primitive@1.3.0: - dependencies: - is-callable: 1.2.7 - is-date-object: 1.1.0 - is-symbol: 1.1.1 - esbuild@0.28.2: optionalDependencies: '@esbuild/aix-ppc64': 0.28.2 @@ -3432,478 +2437,49 @@ snapshots: '@esbuild/win32-ia32': 0.28.2 '@esbuild/win32-x64': 0.28.2 - escape-string-regexp@4.0.0: {} - - eslint-config-airbnb-base@15.0.0(eslint-plugin-import@2.31.0(@typescript-eslint/parser@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2))(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0))(eslint@8.57.0(supports-color@7.2.0)): - dependencies: - confusing-browser-globals: 1.0.10 - eslint: 8.57.0(supports-color@7.2.0) - eslint-plugin-import: 2.31.0(@typescript-eslint/parser@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2))(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0) - object.assign: 4.1.7 - object.entries: 1.1.7 - semver: 6.3.1 - - eslint-config-airbnb-typescript@18.0.0(@typescript-eslint/eslint-plugin@7.18.0(@typescript-eslint/parser@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2))(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2))(@typescript-eslint/parser@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2))(eslint-plugin-import@2.31.0(@typescript-eslint/parser@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2))(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0))(eslint@8.57.0(supports-color@7.2.0)): - dependencies: - '@typescript-eslint/eslint-plugin': 7.18.0(@typescript-eslint/parser@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2))(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2) - '@typescript-eslint/parser': 7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2) - eslint: 8.57.0(supports-color@7.2.0) - eslint-config-airbnb-base: 15.0.0(eslint-plugin-import@2.31.0(@typescript-eslint/parser@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2))(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0))(eslint@8.57.0(supports-color@7.2.0)) - transitivePeerDependencies: - - eslint-plugin-import - - eslint-import-resolver-node@0.3.9(supports-color@7.2.0): - dependencies: - debug: 3.2.7(supports-color@7.2.0) - is-core-module: 2.16.1 - resolve: 1.22.10 - transitivePeerDependencies: - - supports-color - - eslint-module-utils@2.12.0(@typescript-eslint/parser@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2))(eslint-import-resolver-node@0.3.9(supports-color@7.2.0))(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0): - dependencies: - debug: 3.2.7(supports-color@7.2.0) - optionalDependencies: - '@typescript-eslint/parser': 7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2) - eslint: 8.57.0(supports-color@7.2.0) - eslint-import-resolver-node: 0.3.9(supports-color@7.2.0) - transitivePeerDependencies: - - supports-color - - eslint-plugin-import@2.31.0(@typescript-eslint/parser@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2))(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0): - dependencies: - '@rtsao/scc': 1.1.0 - array-includes: 3.1.8 - array.prototype.findlastindex: 1.2.5 - array.prototype.flat: 1.3.3 - array.prototype.flatmap: 1.3.3 - debug: 3.2.7(supports-color@7.2.0) - doctrine: 2.1.0 - eslint: 8.57.0(supports-color@7.2.0) - eslint-import-resolver-node: 0.3.9(supports-color@7.2.0) - eslint-module-utils: 2.12.0(@typescript-eslint/parser@7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2))(eslint-import-resolver-node@0.3.9(supports-color@7.2.0))(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0) - hasown: 2.0.2 - is-core-module: 2.16.1 - is-glob: 4.0.3 - minimatch: 3.1.2 - object.fromentries: 2.0.8 - object.groupby: 1.0.3 - object.values: 1.2.1 - semver: 6.3.1 - string.prototype.trimend: 1.0.9 - tsconfig-paths: 3.15.0 - optionalDependencies: - '@typescript-eslint/parser': 7.18.0(eslint@8.57.0(supports-color@7.2.0))(supports-color@7.2.0)(typescript@5.9.2) - transitivePeerDependencies: - - eslint-import-resolver-typescript - - eslint-import-resolver-webpack - - supports-color - - eslint-scope@7.2.2: - dependencies: - esrecurse: 4.3.0 - estraverse: 5.3.0 - - eslint-visitor-keys@3.4.3: {} - - eslint@8.57.0(supports-color@7.2.0): - dependencies: - '@eslint-community/eslint-utils': 4.4.0(eslint@8.57.0(supports-color@7.2.0)) - '@eslint-community/regexpp': 4.11.0 - '@eslint/eslintrc': 2.1.4(supports-color@7.2.0) - '@eslint/js': 8.57.0 - '@humanwhocodes/config-array': 0.11.14(supports-color@7.2.0) - '@humanwhocodes/module-importer': 1.0.1 - '@nodelib/fs.walk': 1.2.8 - '@ungap/structured-clone': 1.2.0 - ajv: 6.12.6 - chalk: 4.1.2 - cross-spawn: 7.0.3 - debug: 4.4.0(supports-color@7.2.0) - doctrine: 3.0.0 - escape-string-regexp: 4.0.0 - eslint-scope: 7.2.2 - eslint-visitor-keys: 3.4.3 - espree: 9.6.1 - esquery: 1.6.0 - esutils: 2.0.3 - fast-deep-equal: 3.1.3 - file-entry-cache: 6.0.1 - find-up: 5.0.0 - glob-parent: 6.0.2 - globals: 13.24.0 - graphemer: 1.4.0 - ignore: 5.3.2 - imurmurhash: 0.1.4 - is-glob: 4.0.3 - 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.1.2 - natural-compare: 1.4.0 - optionator: 0.9.4 - strip-ansi: 6.0.1 - text-table: 0.2.0 - transitivePeerDependencies: - - supports-color - - espree@9.6.1: - dependencies: - acorn: 8.12.1 - acorn-jsx: 5.3.2(acorn@8.12.1) - eslint-visitor-keys: 3.4.3 - esprima@4.0.1: {} - esquery@1.6.0: - dependencies: - estraverse: 5.3.0 - - esrecurse@4.3.0: - dependencies: - estraverse: 5.3.0 - - estraverse@5.3.0: {} - estree-walker@3.0.3: dependencies: '@types/estree': 1.0.8 - esutils@2.0.3: {} - eventemitter3@5.0.1: {} expect-type@1.4.0: {} - fast-deep-equal@3.1.3: {} - fast-equals@6.0.2: {} - fast-glob@3.3.2: - dependencies: - '@nodelib/fs.stat': 2.0.5 - '@nodelib/fs.walk': 1.2.8 - glob-parent: 5.1.2 - merge2: 1.4.1 - micromatch: 4.0.8 - fast-json-stable-stringify@2.1.0: {} - fast-levenshtein@2.0.6: {} - - fastq@1.17.1: - dependencies: - reusify: 1.0.4 - fdir@6.5.0(picomatch@4.0.7): optionalDependencies: picomatch: 4.0.7 fflate@0.8.3: {} - file-entry-cache@6.0.1: - dependencies: - flat-cache: 3.2.0 - - fill-range@7.1.1: - dependencies: - to-regex-range: 5.0.1 - - find-up@5.0.0: - dependencies: - locate-path: 6.0.0 - path-exists: 4.0.0 - - flat-cache@3.2.0: - dependencies: - flatted: 3.4.4 - keyv: 4.5.4 - rimraf: 3.0.2 - flatted@3.4.4: {} - for-each@0.3.3: - dependencies: - is-callable: 1.2.7 - - fs.realpath@1.0.0: {} - fsevents@2.3.3: optional: true - function-bind@1.1.2: {} - - function.prototype.name@1.1.8: - dependencies: - call-bind: 1.0.8 - call-bound: 1.0.3 - define-properties: 1.2.1 - functions-have-names: 1.2.3 - hasown: 2.0.2 - is-callable: 1.2.7 - - functions-have-names@1.2.3: {} - gensequence@8.0.8: {} - get-intrinsic@1.2.7: - dependencies: - call-bind-apply-helpers: 1.0.1 - es-define-property: 1.0.1 - es-errors: 1.3.0 - es-object-atoms: 1.1.1 - function-bind: 1.1.2 - get-proto: 1.0.1 - gopd: 1.2.0 - has-symbols: 1.1.0 - hasown: 2.0.2 - math-intrinsics: 1.1.0 - - get-proto@1.0.1: - dependencies: - dunder-proto: 1.0.1 - es-object-atoms: 1.1.1 - - get-symbol-description@1.1.0: - dependencies: - call-bound: 1.0.3 - es-errors: 1.3.0 - get-intrinsic: 1.2.7 - - glob-parent@5.1.2: - dependencies: - is-glob: 4.0.3 - - glob-parent@6.0.2: - dependencies: - is-glob: 4.0.3 - - glob@7.2.3: - dependencies: - fs.realpath: 1.0.0 - inflight: 1.0.6 - inherits: 2.0.4 - minimatch: 3.1.2 - once: 1.4.0 - path-is-absolute: 1.0.1 - global-directory@5.0.0: dependencies: ini: 6.0.0 - globals@13.24.0: - dependencies: - type-fest: 0.20.2 - - globalthis@1.0.4: - dependencies: - define-properties: 1.2.1 - gopd: 1.2.0 - - globby@11.1.0: - dependencies: - array-union: 2.1.0 - dir-glob: 3.0.1 - fast-glob: 3.3.2 - ignore: 5.3.2 - merge2: 1.4.1 - slash: 3.0.0 - - gopd@1.2.0: {} - - graphemer@1.4.0: {} - - has-bigints@1.1.0: {} - - has-flag@4.0.0: {} - - has-property-descriptors@1.0.2: - dependencies: - es-define-property: 1.0.1 - - has-proto@1.2.0: - dependencies: - dunder-proto: 1.0.1 - - has-symbols@1.1.0: {} - - has-tostringtag@1.0.2: - dependencies: - has-symbols: 1.1.0 - - hasown@2.0.2: - dependencies: - function-bind: 1.1.2 - - ignore@5.3.2: {} - - import-fresh@3.3.0: - dependencies: - parent-module: 1.0.1 - resolve-from: 4.0.0 - import-fresh@4.0.0: {} import-meta-resolve@4.2.0: {} - imurmurhash@0.1.4: {} - - inflight@1.0.6: - dependencies: - once: 1.4.0 - wrappy: 1.0.2 - - inherits@2.0.4: {} - ini@6.0.0: {} - internal-slot@1.1.0: - dependencies: - es-errors: 1.3.0 - hasown: 2.0.2 - side-channel: 1.1.0 - - is-array-buffer@3.0.5: - dependencies: - call-bind: 1.0.8 - call-bound: 1.0.3 - get-intrinsic: 1.2.7 - - is-async-function@2.1.0: - dependencies: - call-bound: 1.0.3 - get-proto: 1.0.1 - has-tostringtag: 1.0.2 - safe-regex-test: 1.1.0 - - is-bigint@1.1.0: - dependencies: - has-bigints: 1.1.0 - - is-boolean-object@1.2.1: - dependencies: - call-bound: 1.0.3 - has-tostringtag: 1.0.2 - - is-callable@1.2.7: {} - - is-core-module@2.16.1: - dependencies: - hasown: 2.0.2 - - is-data-view@1.0.2: - dependencies: - call-bound: 1.0.3 - get-intrinsic: 1.2.7 - is-typed-array: 1.1.15 - - is-date-object@1.1.0: - dependencies: - call-bound: 1.0.3 - has-tostringtag: 1.0.2 - - is-extglob@2.1.1: {} - - is-finalizationregistry@1.1.1: - dependencies: - call-bound: 1.0.3 - - is-generator-function@1.1.0: - dependencies: - call-bound: 1.0.3 - get-proto: 1.0.1 - has-tostringtag: 1.0.2 - safe-regex-test: 1.1.0 - - is-glob@4.0.3: - dependencies: - is-extglob: 2.1.1 - - is-map@2.0.3: {} - is-network-error@1.3.1: {} - is-number-object@1.1.1: - dependencies: - call-bound: 1.0.3 - has-tostringtag: 1.0.2 - - is-number@7.0.0: {} - - is-path-inside@3.0.3: {} - - is-regex@1.2.1: - dependencies: - call-bound: 1.0.3 - gopd: 1.2.0 - has-tostringtag: 1.0.2 - hasown: 2.0.2 - is-safe-filename@0.1.1: {} - is-set@2.0.3: {} - - is-shared-array-buffer@1.0.4: - dependencies: - call-bound: 1.0.3 - - is-string@1.1.1: - dependencies: - call-bound: 1.0.3 - has-tostringtag: 1.0.2 - - is-symbol@1.1.1: - dependencies: - call-bound: 1.0.3 - has-symbols: 1.1.0 - safe-regex-test: 1.1.0 - - is-typed-array@1.1.15: - dependencies: - which-typed-array: 1.1.18 - - is-weakmap@2.0.2: {} - - is-weakref@1.1.0: - dependencies: - call-bound: 1.0.3 - - is-weakset@2.0.4: - dependencies: - call-bound: 1.0.3 - get-intrinsic: 1.2.7 - - isarray@2.0.5: {} - - isexe@2.0.0: {} - js-tokens@10.0.0: {} - js-yaml@4.1.0: - dependencies: - argparse: 2.0.1 - - json-buffer@3.0.1: {} - - json-schema-traverse@0.4.1: {} - - json-stable-stringify-without-jsonify@1.0.1: {} - - json5@1.0.2: - dependencies: - minimist: 1.2.8 - - keyv@4.5.4: - dependencies: - json-buffer: 3.0.1 - - levn@0.4.1: - dependencies: - prelude-ls: 1.2.1 - type-check: 0.4.0 - lightningcss-android-arm64@1.33.0: optional: true @@ -3953,12 +2529,6 @@ snapshots: lightningcss-win32-arm64-msvc: 1.33.0 lightningcss-win32-x64-msvc: 1.33.0 - locate-path@6.0.0: - dependencies: - p-locate: 5.0.0 - - lodash.merge@4.6.2: {} - lossless-json@4.0.2: {} magic-string@1.4.2: @@ -3971,98 +2541,57 @@ snapshots: '@babel/types': 7.29.8 source-map-js: 1.2.1 - math-intrinsics@1.1.0: {} - - merge2@1.4.1: {} - - micromatch@4.0.8: - dependencies: - braces: 3.0.3 - picomatch: 2.3.1 - - minimatch@3.1.2: - dependencies: - brace-expansion: 1.1.11 - - minimatch@9.0.5: - dependencies: - brace-expansion: 2.0.1 - - minimist@1.2.8: {} - ms@2.1.3: {} nanoid@3.3.19: {} - natural-compare@1.4.0: {} - - object-inspect@1.13.3: {} - - object-keys@1.1.1: {} - - object.assign@4.1.7: - dependencies: - call-bind: 1.0.8 - call-bound: 1.0.3 - define-properties: 1.2.1 - es-object-atoms: 1.1.1 - has-symbols: 1.1.0 - object-keys: 1.1.1 - - object.entries@1.1.7: - dependencies: - call-bind: 1.0.8 - define-properties: 1.2.1 - es-abstract: 1.23.9 - - object.fromentries@2.0.8: - dependencies: - call-bind: 1.0.8 - define-properties: 1.2.1 - es-abstract: 1.23.9 - es-object-atoms: 1.1.1 - - object.groupby@1.0.3: - dependencies: - call-bind: 1.0.8 - define-properties: 1.2.1 - es-abstract: 1.23.9 - - object.values@1.2.1: - dependencies: - call-bind: 1.0.8 - call-bound: 1.0.3 - define-properties: 1.2.1 - es-object-atoms: 1.1.1 - obug@2.2.1: {} - once@1.4.0: - dependencies: - wrappy: 1.0.2 - - optionator@0.9.4: - dependencies: - deep-is: 0.1.4 - fast-levenshtein: 2.0.6 - levn: 0.4.1 - prelude-ls: 1.2.1 - type-check: 0.4.0 - word-wrap: 1.2.5 - - own-keys@1.0.1: - dependencies: - get-intrinsic: 1.2.7 - object-keys: 1.1.1 - safe-push-apply: 1.0.0 - - p-limit@3.1.0: + oxfmt@0.81.0: dependencies: - yocto-queue: 0.1.0 - - p-locate@5.0.0: - dependencies: - p-limit: 3.1.0 + tinypool: 2.2.0 + optionalDependencies: + '@oxfmt/binding-android-arm-eabi': 0.81.0 + '@oxfmt/binding-android-arm64': 0.81.0 + '@oxfmt/binding-darwin-arm64': 0.81.0 + '@oxfmt/binding-darwin-x64': 0.81.0 + '@oxfmt/binding-freebsd-x64': 0.81.0 + '@oxfmt/binding-linux-arm-gnueabihf': 0.81.0 + '@oxfmt/binding-linux-arm-musleabihf': 0.81.0 + '@oxfmt/binding-linux-arm64-gnu': 0.81.0 + '@oxfmt/binding-linux-arm64-musl': 0.81.0 + '@oxfmt/binding-linux-ppc64-gnu': 0.81.0 + '@oxfmt/binding-linux-riscv64-gnu': 0.81.0 + '@oxfmt/binding-linux-riscv64-musl': 0.81.0 + '@oxfmt/binding-linux-s390x-gnu': 0.81.0 + '@oxfmt/binding-linux-x64-gnu': 0.81.0 + '@oxfmt/binding-linux-x64-musl': 0.81.0 + '@oxfmt/binding-openharmony-arm64': 0.81.0 + '@oxfmt/binding-win32-arm64-msvc': 0.81.0 + '@oxfmt/binding-win32-ia32-msvc': 0.81.0 + '@oxfmt/binding-win32-x64-msvc': 0.81.0 + + oxlint@1.96.0: + optionalDependencies: + '@oxlint/binding-android-arm-eabi': 1.96.0 + '@oxlint/binding-android-arm64': 1.96.0 + '@oxlint/binding-darwin-arm64': 1.96.0 + '@oxlint/binding-darwin-x64': 1.96.0 + '@oxlint/binding-freebsd-x64': 1.96.0 + '@oxlint/binding-linux-arm-gnueabihf': 1.96.0 + '@oxlint/binding-linux-arm-musleabihf': 1.96.0 + '@oxlint/binding-linux-arm64-gnu': 1.96.0 + '@oxlint/binding-linux-arm64-musl': 1.96.0 + '@oxlint/binding-linux-ppc64-gnu': 1.96.0 + '@oxlint/binding-linux-riscv64-gnu': 1.96.0 + '@oxlint/binding-linux-riscv64-musl': 1.96.0 + '@oxlint/binding-linux-s390x-gnu': 1.96.0 + '@oxlint/binding-linux-x64-gnu': 1.96.0 + '@oxlint/binding-linux-x64-musl': 1.96.0 + '@oxlint/binding-openharmony-arm64': 1.96.0 + '@oxlint/binding-win32-arm64-msvc': 1.96.0 + '@oxlint/binding-win32-ia32-msvc': 1.96.0 + '@oxlint/binding-win32-x64-msvc': 1.96.0 p-queue@9.1.2: dependencies: @@ -4075,76 +2604,18 @@ snapshots: p-timeout@7.0.1: {} - parent-module@1.0.1: - dependencies: - callsites: 3.1.0 - - path-exists@4.0.0: {} - - path-is-absolute@1.0.1: {} - - path-key@3.1.1: {} - - path-parse@1.0.7: {} - - path-type@4.0.0: {} - picocolors@1.1.1: {} - picomatch@2.3.1: {} - picomatch@4.0.7: {} - possible-typed-array-names@1.0.0: {} - postcss@8.5.28: dependencies: nanoid: 3.3.19 picocolors: 1.1.1 source-map-js: 1.2.1 - prelude-ls@1.2.1: {} - - punycode@2.3.1: {} - - queue-microtask@1.2.3: {} - - reflect.getprototypeof@1.0.10: - dependencies: - call-bind: 1.0.8 - define-properties: 1.2.1 - es-abstract: 1.23.9 - es-errors: 1.3.0 - es-object-atoms: 1.1.1 - get-intrinsic: 1.2.7 - get-proto: 1.0.1 - which-builtin-type: 1.2.1 - - regexp.prototype.flags@1.5.4: - dependencies: - call-bind: 1.0.8 - define-properties: 1.2.1 - es-errors: 1.3.0 - get-proto: 1.0.1 - gopd: 1.2.0 - set-function-name: 2.0.2 - - resolve-from@4.0.0: {} - resolve-from@5.0.0: {} - resolve@1.22.10: - dependencies: - is-core-module: 2.16.1 - path-parse: 1.0.7 - supports-preserve-symlinks-flag: 1.0.0 - - reusify@1.0.4: {} - - rimraf@3.0.2: - dependencies: - glob: 7.2.3 - rolldown@1.2.10: dependencies: '@oxc-project/types': 0.151.0 @@ -4166,93 +2637,10 @@ snapshots: '@rolldown/binding-win32-arm64-msvc': 1.2.10 '@rolldown/binding-win32-x64-msvc': 1.2.10 - run-parallel@1.2.0: - dependencies: - queue-microtask: 1.2.3 - - safe-array-concat@1.1.3: - dependencies: - call-bind: 1.0.8 - call-bound: 1.0.3 - get-intrinsic: 1.2.7 - has-symbols: 1.1.0 - isarray: 2.0.5 - - safe-push-apply@1.0.0: - dependencies: - es-errors: 1.3.0 - isarray: 2.0.5 - - safe-regex-test@1.1.0: - dependencies: - call-bound: 1.0.3 - es-errors: 1.3.0 - is-regex: 1.2.1 - - semver@6.3.1: {} - semver@7.8.5: {} - set-function-length@1.2.2: - dependencies: - define-data-property: 1.1.4 - es-errors: 1.3.0 - function-bind: 1.1.2 - get-intrinsic: 1.2.7 - gopd: 1.2.0 - has-property-descriptors: 1.0.2 - - set-function-name@2.0.2: - dependencies: - define-data-property: 1.1.4 - es-errors: 1.3.0 - functions-have-names: 1.2.3 - has-property-descriptors: 1.0.2 - - set-proto@1.0.0: - dependencies: - dunder-proto: 1.0.1 - es-errors: 1.3.0 - es-object-atoms: 1.1.1 - - shebang-command@2.0.0: - dependencies: - shebang-regex: 3.0.0 - - shebang-regex@3.0.0: {} - - side-channel-list@1.0.0: - dependencies: - es-errors: 1.3.0 - object-inspect: 1.13.3 - - side-channel-map@1.0.1: - dependencies: - call-bound: 1.0.3 - es-errors: 1.3.0 - get-intrinsic: 1.2.7 - object-inspect: 1.13.3 - - side-channel-weakmap@1.0.2: - dependencies: - call-bound: 1.0.3 - es-errors: 1.3.0 - get-intrinsic: 1.2.7 - object-inspect: 1.13.3 - side-channel-map: 1.0.1 - - side-channel@1.1.0: - dependencies: - es-errors: 1.3.0 - object-inspect: 1.13.3 - side-channel-list: 1.0.0 - side-channel-map: 1.0.1 - side-channel-weakmap: 1.0.2 - siginfo@2.0.0: {} - slash@3.0.0: {} - smol-toml@1.7.1: {} source-map-js@1.2.1: {} @@ -4261,45 +2649,6 @@ snapshots: std-env@4.2.0: {} - string.prototype.trim@1.2.10: - dependencies: - call-bind: 1.0.8 - call-bound: 1.0.3 - define-data-property: 1.1.4 - define-properties: 1.2.1 - es-abstract: 1.23.9 - es-object-atoms: 1.1.1 - has-property-descriptors: 1.0.2 - - string.prototype.trimend@1.0.9: - dependencies: - call-bind: 1.0.8 - call-bound: 1.0.3 - define-properties: 1.2.1 - es-object-atoms: 1.1.1 - - string.prototype.trimstart@1.0.8: - dependencies: - call-bind: 1.0.8 - define-properties: 1.2.1 - es-object-atoms: 1.1.1 - - strip-ansi@6.0.1: - dependencies: - ansi-regex: 5.0.1 - - strip-bom@3.0.0: {} - - strip-json-comments@3.1.1: {} - - supports-color@7.2.0: - dependencies: - has-flag: 4.0.0 - - supports-preserve-symlinks-flag@1.0.0: {} - - text-table@0.2.0: {} - tinybench@6.1.4: {} tinyexec@1.3.0: {} @@ -4309,22 +2658,9 @@ snapshots: fdir: 6.5.0(picomatch@4.0.7) picomatch: 4.0.7 - tinyrainbow@3.1.1: {} - - to-regex-range@5.0.1: - dependencies: - is-number: 7.0.0 + tinypool@2.2.0: {} - ts-api-utils@1.3.0(typescript@5.9.2): - dependencies: - typescript: 5.9.2 - - tsconfig-paths@3.15.0: - dependencies: - '@types/json5': 0.0.29 - json5: 1.0.2 - minimist: 1.2.8 - strip-bom: 3.0.0 + tinyrainbow@3.1.1: {} tslib@2.8.1: {} @@ -4334,60 +2670,10 @@ snapshots: optionalDependencies: fsevents: 2.3.3 - type-check@0.4.0: - dependencies: - prelude-ls: 1.2.1 - - type-fest@0.20.2: {} - - typed-array-buffer@1.0.3: - dependencies: - call-bound: 1.0.3 - es-errors: 1.3.0 - is-typed-array: 1.1.15 - - typed-array-byte-length@1.0.3: - dependencies: - call-bind: 1.0.8 - for-each: 0.3.3 - gopd: 1.2.0 - has-proto: 1.2.0 - is-typed-array: 1.1.15 - - typed-array-byte-offset@1.0.4: - dependencies: - available-typed-arrays: 1.0.7 - call-bind: 1.0.8 - for-each: 0.3.3 - gopd: 1.2.0 - has-proto: 1.2.0 - is-typed-array: 1.1.15 - reflect.getprototypeof: 1.0.10 - - typed-array-length@1.0.7: - dependencies: - call-bind: 1.0.8 - for-each: 0.3.3 - gopd: 1.2.0 - is-typed-array: 1.1.15 - possible-typed-array-names: 1.0.0 - reflect.getprototypeof: 1.0.10 - typescript@5.9.2: {} - unbox-primitive@1.1.0: - dependencies: - call-bound: 1.0.3 - has-bigints: 1.1.0 - has-symbols: 1.1.0 - which-boxed-primitive: 1.1.1 - undici-types@7.18.2: {} - uri-js@4.4.1: - dependencies: - punycode: 2.3.1 - vite@8.3.0(@types/node@24.13.3)(esbuild@0.28.2)(tsx@4.23.12)(yaml@2.9.0): dependencies: lightningcss: 1.33.0 @@ -4428,63 +2714,13 @@ snapshots: vscode-uri@3.1.0: {} - which-boxed-primitive@1.1.1: - dependencies: - is-bigint: 1.1.0 - is-boolean-object: 1.2.1 - is-number-object: 1.1.1 - is-string: 1.1.1 - is-symbol: 1.1.1 - - which-builtin-type@1.2.1: - dependencies: - call-bound: 1.0.3 - function.prototype.name: 1.1.8 - has-tostringtag: 1.0.2 - is-async-function: 2.1.0 - is-date-object: 1.1.0 - is-finalizationregistry: 1.1.1 - is-generator-function: 1.1.0 - is-regex: 1.2.1 - is-weakref: 1.1.0 - isarray: 2.0.5 - which-boxed-primitive: 1.1.1 - which-collection: 1.0.2 - which-typed-array: 1.1.18 - - which-collection@1.0.2: - dependencies: - is-map: 2.0.3 - is-set: 2.0.3 - is-weakmap: 2.0.2 - is-weakset: 2.0.4 - - which-typed-array@1.1.18: - dependencies: - available-typed-arrays: 1.0.7 - call-bind: 1.0.8 - call-bound: 1.0.3 - for-each: 0.3.3 - gopd: 1.2.0 - has-tostringtag: 1.0.2 - - which@2.0.2: - dependencies: - isexe: 2.0.0 - why-is-node-running@2.3.0: dependencies: siginfo: 2.0.0 stackback: 0.0.2 - word-wrap@1.2.5: {} - - wrappy@1.0.2: {} - ws@8.21.3: {} xdg-basedir@5.1.0: {} yaml@2.9.0: {} - - yocto-queue@0.1.0: {} From 7e77c2a9f495589a194d24d50ba623879d2a48fa Mon Sep 17 00:00:00 2001 From: Mathieu Geukens Date: Wed, 2 Dec 2026 08:15:16 +0100 Subject: [PATCH 2/3] style: format packages with oxfmt Mechanical change: the output of `pnpm format`, no manual edits. Also normalises the CRLF line endings in TransactionBuilder.ts to LF. Refs #303 Co-Authored-By: Claude Fable 5.2 --- packages/cashc/src/Errors.ts | 129 +- packages/cashc/src/Warnings.ts | 8 +- packages/cashc/src/artifact/Artifact.ts | 10 +- packages/cashc/src/ast/AST.ts | 50 +- packages/cashc/src/ast/AstBuilder.ts | 56 +- packages/cashc/src/ast/Globals.ts | 39 +- packages/cashc/src/ast/Location.ts | 10 +- packages/cashc/src/ast/SymbolTable.ts | 14 +- packages/cashc/src/ast/error-listeners.ts | 12 +- packages/cashc/src/cashc-cli.ts | 8 +- packages/cashc/src/compiler.ts | 14 +- packages/cashc/src/dependency-resolution.ts | 12 +- .../src/generation/GenerateTargetTraversal.ts | 76 +- packages/cashc/src/generation/inlining.ts | 19 +- packages/cashc/src/generation/utils.ts | 9 +- packages/cashc/src/index.ts | 4 +- packages/cashc/src/internal.ts | 6 +- packages/cashc/src/parser.ts | 5 +- .../semantic/DeadCodeEliminationTraversal.ts | 7 +- .../semantic/EnsureFinalRequireTraversal.ts | 6 +- .../semantic/EnsureFunctionsSafeTraversal.ts | 8 +- .../semantic/FoldGlobalConstantsTraversal.ts | 19 +- .../semantic/InjectLocktimeGuardTraversal.ts | 4 +- .../src/semantic/SymbolTableTraversal.ts | 20 +- .../cashc/src/semantic/TypeCheckTraversal.ts | 24 +- .../cashc/src/semantic/UnusedCodeTraversal.ts | 4 +- packages/cashc/src/utils.ts | 6 +- packages/cashc/test/ast/AST.test.ts | 4 +- packages/cashc/test/ast/Location.test.ts | 10 +- .../bitauth-script/bitauth-script.test.ts | 7 +- packages/cashc/test/compiler/compiler.test.ts | 12 +- .../cashc/test/generation/fixture-utils.ts | 19 +- .../cashc/test/generation/generation.test.ts | 3 +- .../cashc/test/global-definitions.test.ts | 62 +- packages/cashc/test/imports.test.ts | 99 +- .../InjectLocktimeGuardTraversal.test.ts | 5 +- packages/cashc/test/test-utils.ts | 8 +- packages/cashscript/src/Argument.ts | 3 +- packages/cashscript/src/Contract.ts | 43 +- packages/cashscript/src/Errors.ts | 45 +- packages/cashscript/src/SignatureTemplate.ts | 14 +- packages/cashscript/src/TransactionBuilder.ts | 1318 +++++++++-------- packages/cashscript/src/debug-frame.ts | 50 +- packages/cashscript/src/debugging.ts | 122 +- packages/cashscript/src/index.ts | 6 +- packages/cashscript/src/interfaces.ts | 6 +- .../src/libauth-template/LibauthTemplate.ts | 115 +- .../cashscript/src/libauth-template/utils.ts | 51 +- .../src/network/ElectrumNetworkProvider.ts | 71 +- .../src/network/MockNetworkProvider.ts | 33 +- packages/cashscript/src/network/errors.ts | 5 +- .../cashscript/src/test/TestExtensions.ts | 20 +- packages/cashscript/src/transaction-utils.ts | 8 +- .../cashscript/src/types/type-inference.ts | 10 +- packages/cashscript/src/utils.ts | 89 +- .../cashscript/src/walletconnect-utils.ts | 6 +- packages/cashscript/test/Contract.test.ts | 36 +- .../cashscript/test/SignatureTemplate.test.ts | 45 +- .../test/TransactionBuilder.test.ts | 92 +- .../test/debugging-old-artifacts.test.ts | 7 +- packages/cashscript/test/debugging.test.ts | 384 +++-- .../cashscript/test/e2e/Announcement.test.ts | 24 +- packages/cashscript/test/e2e/BigInt.test.ts | 8 +- .../cashscript/test/e2e/HodlVault.test.ts | 96 +- .../cashscript/test/e2e/LocktimeGuard.test.ts | 16 +- packages/cashscript/test/e2e/Mecenas.test.ts | 39 +- .../cashscript/test/e2e/MultiContract.test.ts | 28 +- .../cashscript/test/e2e/P2PKH-tokens.test.ts | 110 +- packages/cashscript/test/e2e/P2PKH.test.ts | 75 +- .../test/e2e/TokenCategoryCheck.test.ts | 14 +- .../test/e2e/TransferWithTimeout.test.ts | 20 +- .../test/e2e/misc/timelocks.test.ts | 13 +- .../network/ElectrumNetworkProvider.test.ts | 8 +- .../e2e/network/MockNetworkProvider.test.ts | 21 +- .../test/multi-contract-debugging.test.ts | 126 +- packages/cashscript/test/test-util.ts | 36 +- .../test/types/Contract.types.test.ts | 26 +- packages/cashscript/test/util.test.ts | 13 +- packages/utils/src/artifact.ts | 26 +- packages/utils/src/bip68.ts | 4 +- packages/utils/src/bitauth-script.ts | 41 +- packages/utils/src/fingerprint.ts | 6 +- packages/utils/src/optimisations.ts | 2 +- packages/utils/src/script.ts | 40 +- packages/utils/src/source-map.ts | 99 +- packages/utils/src/types.ts | 29 +- packages/utils/test/data.test.ts | 10 +- packages/utils/test/fingerprint.test.ts | 20 +- packages/utils/test/hash.test.ts | 31 +- .../test/manual-optimisation-proofs.test.ts | 7 - packages/utils/test/script.test.ts | 10 +- packages/utils/test/types.test.ts | 38 +- 92 files changed, 2240 insertions(+), 2183 deletions(-) diff --git a/packages/cashc/src/Errors.ts b/packages/cashc/src/Errors.ts index a4141392d..599378b1a 100644 --- a/packages/cashc/src/Errors.ts +++ b/packages/cashc/src/Errors.ts @@ -30,10 +30,7 @@ import { BinaryOperator } from './ast/Operator.js'; export class CashScriptError extends Error { node: Node; - constructor( - node: Node, - message: string, - ) { + constructor(node: Node, message: string) { if (node.location) { message += ` at ${node.location.start}`; } @@ -58,9 +55,7 @@ export class ParseError extends Error { } export class UndefinedReferenceError extends CashScriptError { - constructor( - public node: IdentifierNode, - ) { + constructor(public node: IdentifierNode) { super(node, `Undefined reference to symbol ${node.name}`); } } @@ -100,62 +95,47 @@ export class ImportResolutionError extends CashScriptError { } export class EmptyContractError extends CashScriptError { - constructor( - public node: ContractNode, - ) { + constructor(public node: ContractNode) { super(node, `Contract ${node.name} contains no functions`); } } export class EmptyFunctionError extends CashScriptError { - constructor( - public node: FunctionDefinitionNode, - ) { + constructor(public node: FunctionDefinitionNode) { super(node, `Function ${node.name} contains no statements`); } } export class FinalRequireStatementError extends CashScriptError { - constructor( - public node: StatementNode, - ) { + constructor(public node: StatementNode) { super(node, 'Final statement is expected to be a require() statement'); } } export class UnusedFunctionReturnError extends CashScriptError { - constructor( - public node: FunctionCallNode, - ) { + constructor(public node: FunctionCallNode) { super(node, `Return value of ${node.identifier.name} must be used; only void functions may be called as a statement`); } } export class MissingReturnError extends CashScriptError { - constructor( - public node: Node, - ) { + constructor(public node: Node) { super(node, 'A value-returning function must end with a return statement'); } } export class MisplacedReturnError extends CashScriptError { - constructor( - public node: StatementNode, - ) { + constructor(public node: StatementNode) { super(node, 'A return statement is only allowed as the final statement of a function body'); } } export class UnsafeFunctionOperationError extends CashScriptError { - constructor( - node: Node, - operation: string, - ) { + constructor(node: Node, operation: string) { super( node, - `'${operation}' cannot be used inside a user-defined function. Use it directly in a ` - + 'contract function instead, or pass the resulting value into the function as a parameter', + `'${operation}' cannot be used inside a user-defined function. Use it directly in a ` + + 'contract function instead, or pass the resulting value into the function as a parameter', ); } } @@ -172,33 +152,25 @@ export class TypeError extends CashScriptError { } export class ReturnTypeError extends TypeError { - constructor( - node: Node, - actual?: Type, - expected?: Type, - ) { + constructor(node: Node, actual?: Type, expected?: Type) { super(node, actual, expected, `Cannot return type '${actual}' from a function with return type '${expected}'`); } } export class InvalidParameterTypeError extends TypeError { - constructor( - node: FunctionCallNode | RequireNode | InstantiationNode, - actual: Type[], - expected: Type[], - ) { + constructor(node: FunctionCallNode | RequireNode | InstantiationNode, actual: Type[], expected: Type[]) { const name = node instanceof RequireNode ? 'require' : node.identifier.name; super( - node, actual, expected, + node, + actual, + expected, `Found parameters (${actual}) in call to function '${name}' where parameters (${expected}) were expected`, ); } } export class UnequalTypeError extends TypeError { - constructor( - node: BinaryOpNode, - ) { + constructor(node: BinaryOpNode) { const left = node.left.type; const right = node.right.type; super(node, left, right, `Tried to apply operator '${node.operator}' to unequal types '${left}' and '${right}'`); @@ -206,11 +178,7 @@ export class UnequalTypeError extends TypeError { } export class UnsupportedTypeError extends TypeError { - constructor( - node: BinaryOpNode | UnaryOpNode | TimeOpNode | TupleIndexOpNode | SliceNode, - actual?: Type, - expected?: Type, - ) { + constructor(node: BinaryOpNode | UnaryOpNode | TimeOpNode | TupleIndexOpNode | SliceNode, actual?: Type, expected?: Type) { if (node instanceof BinaryOpNode && node.operator.startsWith('.')) { if (expected === PrimitiveType.INT) { super(node, actual, expected, `Tried to call member 'split' with unsupported parameter type '${actual}'`); @@ -239,49 +207,43 @@ export class UnsupportedTypeError extends TypeError { } export class CastTypeError extends TypeError { - constructor( - node: CastNode, - ) { + constructor(node: CastNode) { super(node, node.expression.type, node.type, `Type '${node.expression.type}' is not castable to type '${node.type}'`); } } export class AssignTypeError extends TypeError { - constructor( - node: AssignNode | VariableDefinitionNode | ConstantDefinitionNode, - ) { + constructor(node: AssignNode | VariableDefinitionNode | ConstantDefinitionNode) { const expected = node instanceof AssignNode ? node.identifier.type : node.type; const expression = node instanceof ConstantDefinitionNode ? node.value : node.expression; const target = node instanceof ConstantDefinitionNode ? `constant '${node.name}'` : 'variable'; - super(node, expression.type, expected, `Type '${expression.type}' can not be assigned to ${target} of type '${expected}'`); + super( + node, + expression.type, + expected, + `Type '${expression.type}' can not be assigned to ${target} of type '${expected}'`, + ); } } export class InvalidConstantExpressionError extends CashScriptError { - constructor( - public node: Node, - ) { + constructor(public node: Node) { super( node, - 'Global constant definitions only support literals, references to other constants, ' - + 'integer arithmetic and concatenation', + 'Global constant definitions only support literals, references to other constants, ' + + 'integer arithmetic and concatenation', ); } } export class DivisionByZeroError extends CashScriptError { - constructor( - public node: BinaryOpNode, - ) { + constructor(public node: BinaryOpNode) { super(node, 'Division by zero'); } } export class DuplicateTupleTargetError extends CashScriptError { - constructor( - node: TupleAssignmentNode, - name: string, - ) { + constructor(node: TupleAssignmentNode, name: string) { super(node, `Duplicate target '${name}' in tuple destructuring`); } } @@ -289,33 +251,28 @@ export class DuplicateTupleTargetError extends CashScriptError { export class ConstantModificationError extends CashScriptError { constructor(node: VariableDefinitionNode | ConstantDefinitionNode); constructor(node: Node, name: string); - constructor( - node: Node, - name?: string, - ) { + constructor(node: Node, name?: string) { const constantName = name ?? (node as VariableDefinitionNode | ConstantDefinitionNode).name; super(node, `Tried to modify immutable variable '${constantName}'`); } } -export class InvalidModifierError extends CashScriptError { } +export class InvalidModifierError extends CashScriptError {} export class ArrayElementError extends CashScriptError { - constructor( - node: ArrayNode, - ) { + constructor(node: ArrayNode) { super(node, 'Incorrect elements in array'); } } export class IndexOutOfBoundsError extends CashScriptError { - constructor( - node: TupleIndexOpNode | BinaryOpNode | SliceNode, - ) { + constructor(node: TupleIndexOpNode | BinaryOpNode | SliceNode) { if (node instanceof TupleIndexOpNode) { super(node, `Index ${node.index} out of bounds`); } else if ( - node instanceof BinaryOpNode && node.operator === BinaryOperator.SPLIT && node.right instanceof IntLiteralNode + node instanceof BinaryOpNode && + node.operator === BinaryOperator.SPLIT && + node.right instanceof IntLiteralNode ) { const splitIndex = Number(node.right.value); super(node, `Split index ${splitIndex} out of bounds for type ${node.left.type}`); @@ -330,19 +287,13 @@ export class IndexOutOfBoundsError extends CashScriptError { } export class NullDataChunkTooLargeError extends CashScriptError { - constructor( - node: ExpressionNode, - byteLength: number, - ) { + constructor(node: ExpressionNode, byteLength: number) { super(node, `LockingBytecodeNullData chunks can be at most 255 bytes, but found ${byteLength} bytes`); } } export class BitshiftBitcountNegativeError extends CashScriptError { - constructor( - node: BinaryOpNode, - bitcount: number, - ) { + constructor(node: BinaryOpNode, bitcount: number) { super(node, `Bitshift bitcount cannot be negative: ${bitcount}`); } } diff --git a/packages/cashc/src/Warnings.ts b/packages/cashc/src/Warnings.ts index 68eb7e147..e1040ae5b 100644 --- a/packages/cashc/src/Warnings.ts +++ b/packages/cashc/src/Warnings.ts @@ -19,17 +19,13 @@ export class CashScriptWarning { } export class UnusedVariableWarning extends CashScriptWarning { - constructor( - public symbol: Symbol, - ) { + constructor(public symbol: Symbol) { super(symbol.definition as Node, `Unused variable '${symbol.name}'`); } } export class UnusedAssignmentWarning extends CashScriptWarning { - constructor( - public identifier: IdentifierNode, - ) { + constructor(public identifier: IdentifierNode) { super(identifier, `Value assigned to '${identifier.name}' is never read`); } } diff --git a/packages/cashc/src/artifact/Artifact.ts b/packages/cashc/src/artifact/Artifact.ts index 159aa0ef3..823c36192 100644 --- a/packages/cashc/src/artifact/Artifact.ts +++ b/packages/cashc/src/artifact/Artifact.ts @@ -1,6 +1,4 @@ -import { - Artifact, CompilerOptions, DebugInformation, Script, scriptToAsm, -} from '@cashscript/utils'; +import { Artifact, CompilerOptions, DebugInformation, Script, scriptToAsm } from '@cashscript/utils'; import { version } from '../index.js'; import { Ast } from '../ast/AST.js'; @@ -15,8 +13,10 @@ export function generateArtifact( const { contract } = ast; if (!contract) throw new Error('Internal error: cannot generate an artifact for a source file with no contract'); - const constructorInputs = contract.parameters - .map((parameter) => ({ name: parameter.name, type: parameter.type.toString() })); + const constructorInputs = contract.parameters.map((parameter) => ({ + name: parameter.name, + type: parameter.type.toString(), + })); const abi = contract.functions.map((func) => ({ name: func.name, diff --git a/packages/cashc/src/ast/AST.ts b/packages/cashc/src/ast/AST.ts index b8858e23f..810b4bd1b 100644 --- a/packages/cashc/src/ast/AST.ts +++ b/packages/cashc/src/ast/AST.ts @@ -65,9 +65,7 @@ export class ConstantDefinitionNode extends Node implements Named, Typed { } export class ImportNode extends Node { - constructor( - public path: string, - ) { + constructor(public path: string) { super(); } @@ -135,9 +133,9 @@ export class ParameterNode extends Node implements Named, Typed { export type DefinitionNode = VariableDefinitionNode | ConstantDefinitionNode | FunctionDefinitionNode | ParameterNode; -export abstract class StatementNode extends Node { } -export abstract class ControlStatementNode extends StatementNode { } -export abstract class NonControlStatementNode extends StatementNode { } +export abstract class StatementNode extends Node {} +export abstract class ControlStatementNode extends StatementNode {} +export abstract class NonControlStatementNode extends StatementNode {} export class VariableDefinitionNode extends NonControlStatementNode implements Named, Typed { symbol?: Symbol; @@ -220,9 +218,7 @@ export class RequireNode extends NonControlStatementNode { } export class ConsoleStatementNode extends NonControlStatementNode { - constructor( - public parameters: ConsoleParameterNode[], - ) { + constructor(public parameters: ConsoleParameterNode[]) { super(); } @@ -232,9 +228,7 @@ export class ConsoleStatementNode extends NonControlStatementNode { } export class FunctionCallStatementNode extends NonControlStatementNode { - constructor( - public functionCall: FunctionCallNode, - ) { + constructor(public functionCall: FunctionCallNode) { super(); } @@ -244,9 +238,7 @@ export class FunctionCallStatementNode extends NonControlStatementNode { } export class ReturnNode extends NonControlStatementNode { - constructor( - public expressions: ExpressionNode[], - ) { + constructor(public expressions: ExpressionNode[]) { super(); } @@ -315,9 +307,7 @@ export class ForNode extends ControlStatementNode { export class BlockNode extends Node { symbolTable?: SymbolTable; - constructor( - public statements?: StatementNode[], - ) { + constructor(public statements?: StatementNode[]) { super(); } @@ -425,9 +415,7 @@ export class UnaryOpNode extends ExpressionNode { } export class NullaryOpNode extends ExpressionNode { - constructor( - public operator: NullaryOperator, - ) { + constructor(public operator: NullaryOperator) { super(); } @@ -437,9 +425,7 @@ export class NullaryOpNode extends ExpressionNode { } export class ArrayNode extends ExpressionNode { - constructor( - public elements: ExpressionNode[], - ) { + constructor(public elements: ExpressionNode[]) { super(); } @@ -451,9 +437,7 @@ export class ArrayNode extends ExpressionNode { export class IdentifierNode extends ExpressionNode implements Named { symbol?: Symbol; - constructor( - public name: string, - ) { + constructor(public name: string) { super(); } @@ -474,9 +458,7 @@ export abstract class LiteralNode extends ExpressionNode { } export class BoolLiteralNode extends LiteralNode { - constructor( - public value: boolean, - ) { + constructor(public value: boolean) { super(); this.type = PrimitiveType.BOOL; } @@ -487,9 +469,7 @@ export class BoolLiteralNode extends LiteralNode { } export class IntLiteralNode extends LiteralNode { - constructor( - public value: bigint, - ) { + constructor(public value: bigint) { super(); this.type = PrimitiveType.INT; } @@ -514,9 +494,7 @@ export class StringLiteralNode extends LiteralNode { } export class HexLiteralNode extends LiteralNode { - constructor( - public value: Uint8Array, - ) { + constructor(public value: Uint8Array) { super(); this.type = new BytesType(value.byteLength); } diff --git a/packages/cashc/src/ast/AstBuilder.ts b/packages/cashc/src/ast/AstBuilder.ts index 74a7a2566..701dce979 100644 --- a/packages/cashc/src/ast/AstBuilder.ts +++ b/packages/cashc/src/ast/AstBuilder.ts @@ -91,17 +91,11 @@ import type { } from '../grammar/CashScriptParser.js'; import CashScriptVisitor from '../grammar/CashScriptVisitor.js'; import { Location } from './Location.js'; -import { - Modifier, - NumberUnit, - TimeOp, -} from './Globals.js'; +import { Modifier, NumberUnit, TimeOp } from './Globals.js'; import { getPragmaName, PragmaName, getVersionOpFromCtx } from './Pragma.js'; import { ParseError } from '../Errors.js'; -export default class AstBuilder - extends ParseTreeVisitor - implements CashScriptVisitor { +export default class AstBuilder extends ParseTreeVisitor implements CashScriptVisitor { constructor(private tree: ParseTree) { super(); } @@ -161,17 +155,22 @@ export default class AstBuilder const pragmaName = getPragmaName(ctx.pragmaName().getText()); if (pragmaName !== PragmaName.CASHSCRIPT) throw new Error(); // Shouldn't happen - return ctx.pragmaValue().versionConstraint_list().map((constraint) => { - const op = getVersionOpFromCtx(constraint.versionOperator()); - return `${op}${constraint.VersionLiteral().getText()}`; - }); + return ctx + .pragmaValue() + .versionConstraint_list() + .map((constraint) => { + const op = getVersionOpFromCtx(constraint.versionOperator()); + return `${op}${constraint.VersionLiteral().getText()}`; + }); } visitContractDefinition(ctx: ContractDefinitionContext): ContractNode { const name = ctx.Identifier().getText(); - const parameters = ctx.parameterList().parameter_list().map((p) => this.visit(p) as ParameterNode); - const functions = ctx.contractFunctionDefinition_list() - .map((f) => this.visit(f) as FunctionDefinitionNode); + const parameters = ctx + .parameterList() + .parameter_list() + .map((p) => this.visit(p) as ParameterNode); + const functions = ctx.contractFunctionDefinition_list().map((f) => this.visit(f) as FunctionDefinitionNode); const contract = new ContractNode(name, parameters, functions); contract.location = Location.fromCtx(ctx); return contract; @@ -182,9 +181,8 @@ export default class AstBuilder } visitGlobalFunctionDefinition(ctx: GlobalFunctionDefinitionContext): FunctionDefinitionNode { - const returnTypes = ctx.typeName_list().length > 0 - ? ctx.typeName_list().map((typeName) => parseType(typeName.getText())) - : undefined; + const returnTypes = + ctx.typeName_list().length > 0 ? ctx.typeName_list().map((typeName) => parseType(typeName.getText())) : undefined; return this.buildFunctionDefinition(ctx, FunctionKind.GLOBAL, returnTypes); } @@ -194,7 +192,10 @@ export default class AstBuilder returnTypes?: Type[], ): FunctionDefinitionNode { const name = ctx.Identifier().getText(); - const parameters = ctx.parameterList().parameter_list().map((p) => this.visit(p) as ParameterNode); + const parameters = ctx + .parameterList() + .parameter_list() + .map((p) => this.visit(p) as ParameterNode); const body = this.visit(ctx.functionBody()) as BlockNode; const functionDefinition = new FunctionDefinitionNode(kind, name, parameters, body, returnTypes); functionDefinition.location = Location.fromCtx(ctx); @@ -285,7 +286,7 @@ export default class AstBuilder const leftIdentifier = new IdentifierNode(ctx.Identifier().getText()); leftIdentifier.location = Location.fromToken(ctx.Identifier().symbol); - const binaryOperator = (op === '+=' || op === '++') ? BinaryOperator.PLUS : BinaryOperator.MINUS; + const binaryOperator = op === '+=' || op === '++' ? BinaryOperator.PLUS : BinaryOperator.MINUS; let right: ExpressionNode; if (op === '++' || op === '--') { @@ -334,7 +335,7 @@ export default class AstBuilder visitIfStatement(ctx: IfStatementContext): BranchNode { const condition = this.visit(ctx.expression()); const ifBlock = this.visit(ctx._ifBlock) as StatementNode; - const elseBlock = ctx._elseBlock && this.visit(ctx._elseBlock) as StatementNode; + const elseBlock = ctx._elseBlock && (this.visit(ctx._elseBlock) as StatementNode); const branch = new BranchNode(condition, ifBlock, elseBlock); branch.location = Location.fromCtx(ctx); return branch; @@ -413,7 +414,10 @@ export default class AstBuilder visitFunctionCall(ctx: FunctionCallContext): FunctionCallNode { const identifier = new IdentifierNode(ctx.Identifier().getText()); identifier.location = Location.fromToken(ctx.Identifier().symbol); - const parameters = ctx.expressionList().expression_list().map((e) => this.visit(e)); + const parameters = ctx + .expressionList() + .expression_list() + .map((e) => this.visit(e)); const functionCall = new FunctionCallNode(identifier, parameters); functionCall.location = Location.fromCtx(ctx); return functionCall; @@ -422,7 +426,10 @@ export default class AstBuilder visitInstantiation(ctx: InstantiationContext): InstantiationNode { const identifier = new IdentifierNode(ctx.Identifier().getText()); identifier.location = Location.fromToken(ctx.Identifier().symbol); - const parameters = ctx.expressionList().expression_list().map((e) => this.visit(e)); + const parameters = ctx + .expressionList() + .expression_list() + .map((e) => this.visit(e)); const instantiation = new InstantiationNode(identifier, parameters); instantiation.location = Location.fromCtx(ctx); return instantiation; @@ -579,7 +586,8 @@ export default class AstBuilder } visitConsoleStatement(ctx: ConsoleStatementContext): ConsoleStatementNode { - const parameters = ctx.consoleParameterList() + const parameters = ctx + .consoleParameterList() .consoleParameter_list() .map((p) => this.visit(p) as ConsoleParameterNode); diff --git a/packages/cashc/src/ast/Globals.ts b/packages/cashc/src/ast/Globals.ts index 70c7b4290..88ff5b050 100644 --- a/packages/cashc/src/ast/Globals.ts +++ b/packages/cashc/src/ast/Globals.ts @@ -50,25 +50,15 @@ export enum Modifier { export const GLOBAL_SYMBOL_TABLE = new SymbolTable(); // Classes -GLOBAL_SYMBOL_TABLE.set( - Symbol.class(Class.LOCKING_BYTECODE_P2SH20, new BytesType(23), [new BytesType(20)]), -); -GLOBAL_SYMBOL_TABLE.set( - Symbol.class(Class.LOCKING_BYTECODE_P2SH32, new BytesType(35), [new BytesType(32)]), -); -GLOBAL_SYMBOL_TABLE.set( - Symbol.class(Class.LOCKING_BYTECODE_P2PKH, new BytesType(25), [new BytesType(20)]), -); -GLOBAL_SYMBOL_TABLE.set( - Symbol.class(Class.LOCKING_BYTECODE_NULLDATA, new BytesType(), [new ArrayType(new BytesType())]), -); +GLOBAL_SYMBOL_TABLE.set(Symbol.class(Class.LOCKING_BYTECODE_P2SH20, new BytesType(23), [new BytesType(20)])); +GLOBAL_SYMBOL_TABLE.set(Symbol.class(Class.LOCKING_BYTECODE_P2SH32, new BytesType(35), [new BytesType(32)])); +GLOBAL_SYMBOL_TABLE.set(Symbol.class(Class.LOCKING_BYTECODE_P2PKH, new BytesType(25), [new BytesType(20)])); +GLOBAL_SYMBOL_TABLE.set(Symbol.class(Class.LOCKING_BYTECODE_NULLDATA, new BytesType(), [new ArrayType(new BytesType())])); // Global functions // abs(int) -> int -GLOBAL_SYMBOL_TABLE.set( - Symbol.builtinFunction(GlobalFunction.ABS, PrimitiveType.INT, [PrimitiveType.INT], [Op.OP_ABS]), -); +GLOBAL_SYMBOL_TABLE.set(Symbol.builtinFunction(GlobalFunction.ABS, PrimitiveType.INT, [PrimitiveType.INT], [Op.OP_ABS])); // min(int, int) -> int GLOBAL_SYMBOL_TABLE.set( @@ -83,7 +73,8 @@ GLOBAL_SYMBOL_TABLE.set( // within(int, int, int) -> bool GLOBAL_SYMBOL_TABLE.set( Symbol.builtinFunction( - GlobalFunction.WITHIN, PrimitiveType.BOOL, + GlobalFunction.WITHIN, + PrimitiveType.BOOL, [PrimitiveType.INT, PrimitiveType.INT, PrimitiveType.INT], [Op.OP_WITHIN], ), @@ -95,9 +86,7 @@ GLOBAL_SYMBOL_TABLE.set( ); // sha1(any) -> bytes20 -GLOBAL_SYMBOL_TABLE.set( - Symbol.builtinFunction(GlobalFunction.SHA1, new BytesType(20), [PrimitiveType.ANY], [Op.OP_SHA1]), -); +GLOBAL_SYMBOL_TABLE.set(Symbol.builtinFunction(GlobalFunction.SHA1, new BytesType(20), [PrimitiveType.ANY], [Op.OP_SHA1])); // sha256(any) -> bytes32 GLOBAL_SYMBOL_TABLE.set( @@ -117,7 +106,8 @@ GLOBAL_SYMBOL_TABLE.set( // checkSig(sig, pubkey) -> bool GLOBAL_SYMBOL_TABLE.set( Symbol.builtinFunction( - GlobalFunction.CHECKSIG, PrimitiveType.BOOL, + GlobalFunction.CHECKSIG, + PrimitiveType.BOOL, [PrimitiveType.SIG, PrimitiveType.PUBKEY], [Op.OP_CHECKSIG], ), @@ -126,7 +116,8 @@ GLOBAL_SYMBOL_TABLE.set( // checkMultiSig(sig[], pubkey[]) -> bool GLOBAL_SYMBOL_TABLE.set( Symbol.builtinFunction( - GlobalFunction.CHECKMULTISIG, PrimitiveType.BOOL, + GlobalFunction.CHECKMULTISIG, + PrimitiveType.BOOL, [new ArrayType(PrimitiveType.SIG), new ArrayType(PrimitiveType.PUBKEY)], [Op.OP_CHECKMULTISIG], ), @@ -135,7 +126,8 @@ GLOBAL_SYMBOL_TABLE.set( // checkDataSig(datasig, bytes, pubkey) -> bool GLOBAL_SYMBOL_TABLE.set( Symbol.builtinFunction( - GlobalFunction.CHECKDATASIG, PrimitiveType.BOOL, + GlobalFunction.CHECKDATASIG, + PrimitiveType.BOOL, [PrimitiveType.DATASIG, new BytesType(), PrimitiveType.PUBKEY], [Op.OP_CHECKDATASIG], ), @@ -144,7 +136,8 @@ GLOBAL_SYMBOL_TABLE.set( // toPaddedBytes(int, int) -> bytes GLOBAL_SYMBOL_TABLE.set( Symbol.builtinFunction( - GlobalFunction.TO_PADDED_BYTES, new BytesType(), + GlobalFunction.TO_PADDED_BYTES, + new BytesType(), [PrimitiveType.INT, PrimitiveType.INT], [Op.OP_NUM2BIN], ), diff --git a/packages/cashc/src/ast/Location.ts b/packages/cashc/src/ast/Location.ts index a30546064..3de0f4a1d 100644 --- a/packages/cashc/src/ast/Location.ts +++ b/packages/cashc/src/ast/Location.ts @@ -2,7 +2,10 @@ import type { ParserRuleContext, Token } from 'antlr4'; import { LocationI } from '@cashscript/utils'; export class Location implements LocationI { - constructor(public start: Point, public end: Point) {} + constructor( + public start: Point, + public end: Point, + ) {} static fromCtx(ctx: ParserRuleContext): Location { const stop = ctx.stop?.text ? ctx.stop : ctx.start; @@ -36,7 +39,10 @@ export class Location implements LocationI { } export class Point { - constructor(public line: number, public column: number) {} + constructor( + public line: number, + public column: number, + ) {} offset(code: string): number { const lines = code.split('\n'); diff --git a/packages/cashc/src/ast/SymbolTable.ts b/packages/cashc/src/ast/SymbolTable.ts index 32bf1b163..fd25e361e 100644 --- a/packages/cashc/src/ast/SymbolTable.ts +++ b/packages/cashc/src/ast/SymbolTable.ts @@ -32,12 +32,14 @@ export class Symbol { public parameters?: Type[], public bytecode?: Script, public functionId?: number, - ) { } + ) {} hasModifier(modifier: Modifier): boolean { - return this.definition !== undefined - && !(this.definition instanceof FunctionDefinitionNode) - && this.definition.modifiers.includes(modifier); + return ( + this.definition !== undefined && + !(this.definition instanceof FunctionDefinitionNode) && + this.definition.modifiers.includes(modifier) + ); } getReferences(kind: ReferenceKind): Reference[] { @@ -101,9 +103,7 @@ export enum SymbolType { export class SymbolTable { symbols: Map = new Map(); - constructor( - public parent?: SymbolTable, - ) { } + constructor(public parent?: SymbolTable) {} set(symbol: Symbol): void { this.symbols.set(symbol.name, symbol); diff --git a/packages/cashc/src/ast/error-listeners.ts b/packages/cashc/src/ast/error-listeners.ts index f69ef0bdd..197069f1e 100644 --- a/packages/cashc/src/ast/error-listeners.ts +++ b/packages/cashc/src/ast/error-listeners.ts @@ -62,12 +62,7 @@ export class ThrowingErrorListener extends ErrorListener { } } -function createParseError( - line: number, - charPositionInLine: number, - message: string, - offendingSymbol?: unknown, -): ParseError { +function createParseError(line: number, charPositionInLine: number, message: string, offendingSymbol?: unknown): ParseError { const capitalisedMessage = message.charAt(0).toUpperCase() + message.slice(1); const token = getToken(offendingSymbol); const location = getTokenLocation(token) ?? createEmptyLocation(line, charPositionInLine); @@ -75,10 +70,7 @@ function createParseError( return new ParseError(capitalisedMessage, location); } -function normaliseSyntaxErrorMessage( - message: string, - offendingSymbol: unknown, -): string { +function normaliseSyntaxErrorMessage(message: string, offendingSymbol: unknown): string { const token = getToken(offendingSymbol); const tokenText = getTokenText(token); if (!tokenText) return message; diff --git a/packages/cashc/src/cashc-cli.ts b/packages/cashc/src/cashc-cli.ts index 997b0a3e4..c2ac96831 100644 --- a/packages/cashc/src/cashc-cli.ts +++ b/packages/cashc/src/cashc-cli.ts @@ -28,9 +28,7 @@ program .option('-S, --skip-enforce-function-parameter-types', 'Do not enforce function parameter types.') .option('-L, --skip-enforce-locktime-guard', 'Do not inject a tx.time guard when tx.locktime is used.') .addOption( - new Option('-f, --format ', 'Specify the format of the output.') - .choices(['json', 'ts']) - .default('json'), + new Option('-f, --format ', 'Specify the format of the output.').choices(['json', 'ts']).default('json'), ) .helpOption('-?, --help', 'Display help') .parse(); @@ -63,7 +61,9 @@ function run(): void { const bytesize = calculateBytesize(script); if (bytesize > MAX_INPUT_BYTESIZE) { - console.warn(`Warning: Your contract is ${bytesize} bytes, which is over the limit of ${MAX_INPUT_BYTESIZE} bytes and will not be accepted by the BCH network`); + console.warn( + `Warning: Your contract is ${bytesize} bytes, which is over the limit of ${MAX_INPUT_BYTESIZE} bytes and will not be accepted by the BCH network`, + ); } if (opts.asm) { diff --git a/packages/cashc/src/compiler.ts b/packages/cashc/src/compiler.ts index dcc21d97b..3b842eeb7 100644 --- a/packages/cashc/src/compiler.ts +++ b/packages/cashc/src/compiler.ts @@ -20,12 +20,7 @@ import { CashScriptErrorListener } from './ast/error-listeners.js'; import { MissingContractError } from './Errors.js'; import { CashScriptWarningListener, defaultWarningListener } from './Warnings.js'; import { parseCode } from './parser.js'; -import { - createDiskResolver, - createMemoryResolver, - ImportResolver, - resolveDependencies, -} from './dependency-resolution.js'; +import { createDiskResolver, createMemoryResolver, ImportResolver, resolveDependencies } from './dependency-resolution.js'; import GenerateTargetTraversal from './generation/GenerateTargetTraversal.js'; import { FoldGlobalConstantsTraversal } from './semantic/FoldGlobalConstantsTraversal.js'; import SymbolTableTraversal from './semantic/SymbolTableTraversal.js'; @@ -61,8 +56,7 @@ export interface CompileStringOptions extends CompileOptions { * @remarks Compilation warnings (e.g. unused variables) are passed to the `warningListener` compiler * option, or printed with `console.warn` when no listener is provided. */ -export const compileString: (code: string, compilerOptions?: CompileStringOptions) => Artifact = - compileStringInternal; +export const compileString: (code: string, compilerOptions?: CompileStringOptions) => Artifact = compileStringInternal; /** * Read a `.cash` source file from disk and compile it to an `Artifact`. @@ -76,9 +70,7 @@ export const compileString: (code: string, compilerOptions?: CompileStringOption * @returns The compiled CashScript artifact. * @throws If the file cannot be read, or if the source contains a compilation error. */ -export const compileFile: (codeFile: PathLike, compilerOptions?: CompileOptions) => Artifact = - compileFileInternal; - +export const compileFile: (codeFile: PathLike, compilerOptions?: CompileOptions) => Artifact = compileFileInternal; export interface InternalCompilerOptions extends CompilerOptions { disableInlining?: boolean; diff --git a/packages/cashc/src/dependency-resolution.ts b/packages/cashc/src/dependency-resolution.ts index 9be514ae2..a90c03d3d 100644 --- a/packages/cashc/src/dependency-resolution.ts +++ b/packages/cashc/src/dependency-resolution.ts @@ -1,11 +1,6 @@ import fs from 'fs'; import path from 'path'; -import { - SourceFileNode, - FunctionDefinitionNode, - ConstantDefinitionNode, - ImportNode, -} from './ast/AST.js'; +import { SourceFileNode, FunctionDefinitionNode, ConstantDefinitionNode, ImportNode } from './ast/AST.js'; import { checkVersionConstraints } from './ast/Pragma.js'; import type { CashScriptErrorListener } from './ast/error-listeners.js'; import { ImportResolutionError } from './Errors.js'; @@ -189,10 +184,7 @@ function collectImports( const transitiveDefinitions = collect(importedAst.imports, file); activePaths.delete(file.logicalPath); - return [ - ...transitiveDefinitions, - { functions: importedAst.functions, constants: importedAst.constants }, - ]; + return [...transitiveDefinitions, { functions: importedAst.functions, constants: importedAst.constants }]; }); const collected = collect(imports); diff --git a/packages/cashc/src/generation/GenerateTargetTraversal.ts b/packages/cashc/src/generation/GenerateTargetTraversal.ts index 1e6e825c0..fd78c697d 100644 --- a/packages/cashc/src/generation/GenerateTargetTraversal.ts +++ b/packages/cashc/src/generation/GenerateTargetTraversal.ts @@ -68,13 +68,7 @@ import { import AstTraversal from '../ast/AstTraversal.js'; import { GlobalFunction, Class } from '../ast/Globals.js'; import { BinaryOperator } from '../ast/Operator.js'; -import { - compileBinaryOp, - compileCast, - compileNullaryOp, - compileTimeOp, - compileUnaryOp, -} from './utils.js'; +import { compileBinaryOp, compileCast, compileNullaryOp, compileTimeOp, compileUnaryOp } from './utils.js'; import { getCompileTimeBytes, isNumericType } from '../utils.js'; import { collectFunctionCalls, isRecursive, shouldInline } from './inlining.js'; import type { InternalCompilerOptions } from '../compiler.js'; @@ -171,26 +165,32 @@ export default class GenerateTargetTraversal extends AstTraversal { private mergeInlinedDebugInfo(): void { this.inlineRanges.forEach(({ startIp, frame, line }) => { - this.requires.push(...frame.requires.map((entry) => ({ - ...entry, - ip: entry.ip + startIp, - line, - }))); - - this.consoleLogs.push(...frame.logs.map((entry) => ({ - ...entry, - ip: entry.ip + startIp, - data: entry.data.map((item) => (typeof item === 'string' ? item : { ...item, ip: item.ip + startIp })), - line, - }))); + this.requires.push( + ...frame.requires.map((entry) => ({ + ...entry, + ip: entry.ip + startIp, + line, + })), + ); + + this.consoleLogs.push( + ...frame.logs.map((entry) => ({ + ...entry, + ip: entry.ip + startIp, + data: entry.data.map((item) => (typeof item === 'string' ? item : { ...item, ip: item.ip + startIp })), + line, + })), + ); // Source tags use opcode indices rather than ips, which excludes the constructor arguments const startIndex = startIp - this.constructorParameterCount; - this.sourceTags.push(...parseSourceTags(frame.sourceTags ?? '').map((entry) => ({ - ...entry, - startIndex: entry.startIndex + startIndex, - endIndex: entry.endIndex + startIndex, - }))); + this.sourceTags.push( + ...parseSourceTags(frame.sourceTags ?? '').map((entry) => ({ + ...entry, + startIndex: entry.startIndex + startIndex, + endIndex: entry.endIndex + startIndex, + })), + ); }); // Restore overall program order, since the merged entries were appended after this program's own @@ -207,7 +207,7 @@ export default class GenerateTargetTraversal extends AstTraversal { }); const reachableCalls = [node.contract!, ...node.functions].flatMap((n) => collectFunctionCalls(n)); - const definedFunctions: Array<{ func: FunctionDefinitionNode, compiledResult: OptimiseBytecodeResult }> = []; + const definedFunctions: Array<{ func: FunctionDefinitionNode; compiledResult: OptimiseBytecodeResult }> = []; let nextFunctionId = recursiveFunctions.length; node.functions.forEach((func) => { @@ -274,11 +274,7 @@ export default class GenerateTargetTraversal extends AstTraversal { return optimisedResult; } - private buildDebugFrame( - node: FunctionDefinitionNode, - optimised: OptimiseBytecodeResult, - functionId?: number, - ): DebugFrame { + private buildDebugFrame(node: FunctionDefinitionNode, optimised: OptimiseBytecodeResult, functionId?: number): DebugFrame { return { id: functionId, name: node.name, @@ -836,10 +832,10 @@ export default class GenerateTargetTraversal extends AstTraversal { visitCast(node: CastNode): Node { node.expression = this.visit(node.expression); - this.emit( - compileCast(node.expression.type as PrimitiveType, node.type, node.isUnsafe), - { location: node.location, positionHint: PositionHint.END }, - ); + this.emit(compileCast(node.expression.type as PrimitiveType, node.type, node.isUnsafe), { + location: node.location, + positionHint: PositionHint.END, + }); this.popFromStack(); this.pushToStack('(value)'); return node; @@ -866,8 +862,8 @@ export default class GenerateTargetTraversal extends AstTraversal { // The call leaves one value per declared return type (none for a void function); a multi-return // function's values (a TupleType) are subsequently bound by visitTupleAssignment. - const returnValueCount = symbol.type === PrimitiveType.VOID ? 0 - : symbol.type instanceof TupleType ? symbol.type.elementTypes.length : 1; + const returnValueCount = + symbol.type === PrimitiveType.VOID ? 0 : symbol.type instanceof TupleType ? symbol.type.elementTypes.length : 1; for (let i = 0; i < returnValueCount; i += 1) this.pushToStack('(value)'); return node; @@ -1034,10 +1030,10 @@ export default class GenerateTargetTraversal extends AstTraversal { node.left = this.visit(node.left); node.right = this.visit(node.right); const bothOperandsAreNumeric = isNumericType(node.left.type) && isNumericType(node.right.type); - this.emit( - compileBinaryOp(node.operator, bothOperandsAreNumeric), - { location: node.location, positionHint: PositionHint.END }, - ); + this.emit(compileBinaryOp(node.operator, bothOperandsAreNumeric), { + location: node.location, + positionHint: PositionHint.END, + }); this.popFromStack(2); this.pushToStack('(value)'); if (node.operator === BinaryOperator.SPLIT) this.pushToStack('(value)'); diff --git a/packages/cashc/src/generation/inlining.ts b/packages/cashc/src/generation/inlining.ts index a25e40bcb..3504fda4f 100644 --- a/packages/cashc/src/generation/inlining.ts +++ b/packages/cashc/src/generation/inlining.ts @@ -1,10 +1,4 @@ -import { - encodeInt, - Op, - OptimiseBytecodeResult, - Script, - scriptToBytecode, -} from '@cashscript/utils'; +import { encodeInt, Op, OptimiseBytecodeResult, Script, scriptToBytecode } from '@cashscript/utils'; import { FunctionCallNode, FunctionDefinitionNode, Node } from '../ast/AST.js'; import AstTraversal from '../ast/AstTraversal.js'; import { Symbol } from '../ast/SymbolTable.js'; @@ -60,11 +54,12 @@ export function isRecursive(func: FunctionDefinitionNode): boolean { function transitiveCalledFunctions(func: FunctionDefinitionNode): FunctionDefinitionNode[] { const callees: FunctionDefinitionNode[] = []; - const visit = (current: FunctionDefinitionNode): void => calledFunctions(current).forEach((callee) => { - if (callees.includes(callee)) return; - callees.push(callee); - visit(callee); - }); + const visit = (current: FunctionDefinitionNode): void => + calledFunctions(current).forEach((callee) => { + if (callees.includes(callee)) return; + callees.push(callee); + visit(callee); + }); visit(func); return callees; diff --git a/packages/cashc/src/generation/utils.ts b/packages/cashc/src/generation/utils.ts index b6bac2195..c0fe26229 100644 --- a/packages/cashc/src/generation/utils.ts +++ b/packages/cashc/src/generation/utils.ts @@ -1,11 +1,4 @@ -import { - BytesType, - encodeInt, - Op, - PrimitiveType, - Script, - Type, -} from '@cashscript/utils'; +import { BytesType, encodeInt, Op, PrimitiveType, Script, Type } from '@cashscript/utils'; import { UnaryOperator, BinaryOperator, NullaryOperator } from '../ast/Operator.js'; import { TimeOp } from '../ast/Globals.js'; diff --git a/packages/cashc/src/index.ts b/packages/cashc/src/index.ts index 580d8cba4..b742202d7 100644 --- a/packages/cashc/src/index.ts +++ b/packages/cashc/src/index.ts @@ -1,9 +1,7 @@ export * from './Errors.js'; export * from './Warnings.js'; export * as utils from '@cashscript/utils'; -export { - compileFile, compileString, type CompileOptions, type CompileStringOptions, -} from './compiler.js'; +export { compileFile, compileString, type CompileOptions, type CompileStringOptions } from './compiler.js'; export * from './ast/Location.js'; export * from './ast/error-listeners.js'; diff --git a/packages/cashc/src/internal.ts b/packages/cashc/src/internal.ts index 583874697..921306fc0 100644 --- a/packages/cashc/src/internal.ts +++ b/packages/cashc/src/internal.ts @@ -4,5 +4,9 @@ * from the package's public API. This module is not re-exported from the package index and * carries no stability guarantees. */ -export { compileFileInternal as compileFile, compileStringInternal as compileString, DEFAULT_COMPILER_OPTIONS } from './compiler.js'; +export { + compileFileInternal as compileFile, + compileStringInternal as compileString, + DEFAULT_COMPILER_OPTIONS, +} from './compiler.js'; export type { InternalCompilerOptions } from './compiler.js'; diff --git a/packages/cashc/src/parser.ts b/packages/cashc/src/parser.ts index e7e0e799d..d08bb08eb 100644 --- a/packages/cashc/src/parser.ts +++ b/packages/cashc/src/parser.ts @@ -5,10 +5,7 @@ import { ThrowingErrorListener, CashScriptErrorListener, ForwardingErrorListener import CashScriptLexer from './grammar/CashScriptLexer.js'; import CashScriptParser from './grammar/CashScriptParser.js'; -export function parseCode( - code: string, - errorListener: CashScriptErrorListener = ThrowingErrorListener.INSTANCE, -): Ast { +export function parseCode(code: string, errorListener: CashScriptErrorListener = ThrowingErrorListener.INSTANCE): Ast { const syntaxErrorListener = new ForwardingErrorListener(errorListener); // Lexing (throwing on errors) diff --git a/packages/cashc/src/semantic/DeadCodeEliminationTraversal.ts b/packages/cashc/src/semantic/DeadCodeEliminationTraversal.ts index cacaff94d..ffa62e33a 100644 --- a/packages/cashc/src/semantic/DeadCodeEliminationTraversal.ts +++ b/packages/cashc/src/semantic/DeadCodeEliminationTraversal.ts @@ -1,9 +1,4 @@ -import { - FunctionCallNode, - FunctionDefinitionNode, - Node, - SourceFileNode, -} from '../ast/AST.js'; +import { FunctionCallNode, FunctionDefinitionNode, Node, SourceFileNode } from '../ast/AST.js'; import AstTraversal from '../ast/AstTraversal.js'; export default class DeadCodeEliminationTraversal extends AstTraversal { diff --git a/packages/cashc/src/semantic/EnsureFinalRequireTraversal.ts b/packages/cashc/src/semantic/EnsureFinalRequireTraversal.ts index 88d63f3ff..2bcd36fa1 100644 --- a/packages/cashc/src/semantic/EnsureFinalRequireTraversal.ts +++ b/packages/cashc/src/semantic/EnsureFinalRequireTraversal.ts @@ -102,11 +102,7 @@ function ensureFinalStatementIsRequire(block: BlockNode): void { return; } - if ( - finalStatement instanceof DoWhileNode - || finalStatement instanceof WhileNode - || finalStatement instanceof ForNode - ) { + if (finalStatement instanceof DoWhileNode || finalStatement instanceof WhileNode || finalStatement instanceof ForNode) { ensureFinalStatementIsRequire(finalStatement.block); return; } diff --git a/packages/cashc/src/semantic/EnsureFunctionsSafeTraversal.ts b/packages/cashc/src/semantic/EnsureFunctionsSafeTraversal.ts index dabd9ab4e..30fb6c025 100644 --- a/packages/cashc/src/semantic/EnsureFunctionsSafeTraversal.ts +++ b/packages/cashc/src/semantic/EnsureFunctionsSafeTraversal.ts @@ -1,10 +1,4 @@ -import { - FunctionCallNode, - FunctionDefinitionNode, - FunctionKind, - Node, - NullaryOpNode, -} from '../ast/AST.js'; +import { FunctionCallNode, FunctionDefinitionNode, FunctionKind, Node, NullaryOpNode } from '../ast/AST.js'; import AstTraversal from '../ast/AstTraversal.js'; import { GlobalFunction } from '../ast/Globals.js'; import { NullaryOperator } from '../ast/Operator.js'; diff --git a/packages/cashc/src/semantic/FoldGlobalConstantsTraversal.ts b/packages/cashc/src/semantic/FoldGlobalConstantsTraversal.ts index a75890077..3d3f7ff86 100644 --- a/packages/cashc/src/semantic/FoldGlobalConstantsTraversal.ts +++ b/packages/cashc/src/semantic/FoldGlobalConstantsTraversal.ts @@ -86,9 +86,7 @@ export class FoldGlobalConstantsTraversal extends AstTraversal { } } -const FOLDABLE_UNARY_OPERATORS = [ - UnaryOperator.NEGATE, -]; +const FOLDABLE_UNARY_OPERATORS = [UnaryOperator.NEGATE]; const FOLDABLE_BINARY_OPERATORS = [ BinaryOperator.PLUS, @@ -128,12 +126,17 @@ function foldIntArithmetic(node: BinaryOpNode): LiteralNode { } switch (operator) { - case BinaryOperator.MINUS: return withLocation(new IntLiteralNode(left.value - right.value), node); - case BinaryOperator.MUL: return withLocation(new IntLiteralNode(left.value * right.value), node); + case BinaryOperator.MINUS: + return withLocation(new IntLiteralNode(left.value - right.value), node); + case BinaryOperator.MUL: + return withLocation(new IntLiteralNode(left.value * right.value), node); // Note: BigInt division and modulo truncate towards zero, matching OP_DIV / OP_MOD semantics - case BinaryOperator.DIV: return withLocation(new IntLiteralNode(left.value / right.value), node); - case BinaryOperator.MOD: return withLocation(new IntLiteralNode(left.value % right.value), node); - default: throw new InvalidConstantExpressionError(node); + case BinaryOperator.DIV: + return withLocation(new IntLiteralNode(left.value / right.value), node); + case BinaryOperator.MOD: + return withLocation(new IntLiteralNode(left.value % right.value), node); + default: + throw new InvalidConstantExpressionError(node); } } diff --git a/packages/cashc/src/semantic/InjectLocktimeGuardTraversal.ts b/packages/cashc/src/semantic/InjectLocktimeGuardTraversal.ts index 6137d6e3c..555018919 100644 --- a/packages/cashc/src/semantic/InjectLocktimeGuardTraversal.ts +++ b/packages/cashc/src/semantic/InjectLocktimeGuardTraversal.ts @@ -58,9 +58,7 @@ class LocktimeGuardRequirementAnalyser extends AstTraversal { requiresLocktimeGuard = false; private isAlreadyCovered = false; - constructor( - private checkGlobalFunctionRequiresLocktimeGuard: (func: FunctionDefinitionNode) => boolean, - ) { + constructor(private checkGlobalFunctionRequiresLocktimeGuard: (func: FunctionDefinitionNode) => boolean) { super(); } diff --git a/packages/cashc/src/semantic/SymbolTableTraversal.ts b/packages/cashc/src/semantic/SymbolTableTraversal.ts index f52edb7ec..5f613af17 100644 --- a/packages/cashc/src/semantic/SymbolTableTraversal.ts +++ b/packages/cashc/src/semantic/SymbolTableTraversal.ts @@ -22,9 +22,7 @@ import { TupleAssignmentTarget, } from '../ast/AST.js'; import AstTraversal from '../ast/AstTraversal.js'; -import { - SymbolTable, Symbol, SymbolType, ReferenceKind, -} from '../ast/SymbolTable.js'; +import { SymbolTable, Symbol, SymbolType, ReferenceKind } from '../ast/SymbolTable.js'; import { createConstantLiteral } from './LowerGlobalConstantsTraversal.js'; import { RedefinitionError, @@ -273,7 +271,10 @@ export default class SymbolTableTraversal extends AstTraversal { } if (symbol.hasModifier(Modifier.UNUSED)) { - throw new InvalidModifierError(identifier, `Cannot assign to variable '${identifier.name}' because it is marked 'unused'`); + throw new InvalidModifierError( + identifier, + `Cannot assign to variable '${identifier.name}' because it is marked 'unused'`, + ); } // An assignment still needs the variable to be on the stack, so it does count as its final use for code generation @@ -283,11 +284,7 @@ export default class SymbolTableTraversal extends AstTraversal { } } -function validateModifiers( - node: ParameterNode | VariableDefinitionNode, - modifiers: Modifier[], - allowed: Modifier[], -): void { +function validateModifiers(node: ParameterNode | VariableDefinitionNode, modifiers: Modifier[], allowed: Modifier[]): void { const seen = new Set(); modifiers.forEach((modifier) => { @@ -304,10 +301,7 @@ function validateModifiers( }); } -function createTupleVariableDefinition( - node: TupleAssignmentNode, - target: TupleAssignmentTarget, -): VariableDefinitionNode { +function createTupleVariableDefinition(node: TupleAssignmentNode, target: TupleAssignmentTarget): VariableDefinitionNode { const definition = new VariableDefinitionNode(target.type!, target.modifiers, target.identifier.name, node.tuple); definition.location = node.location; return definition; diff --git a/packages/cashc/src/semantic/TypeCheckTraversal.ts b/packages/cashc/src/semantic/TypeCheckTraversal.ts index 8249cf111..6b6d88834 100644 --- a/packages/cashc/src/semantic/TypeCheckTraversal.ts +++ b/packages/cashc/src/semantic/TypeCheckTraversal.ts @@ -81,9 +81,9 @@ export default class TypeCheckTraversal extends AstTraversal { node.tuple = this.visit(node.tuple); // Reassigned variables use their current type, which may have been narrowed by a preceding x.length == N check - const targetsType = new TupleType(node.targets.map((target) => ( - target.isReassignment ? target.identifier.symbol!.type : target.type! - ))); + const targetsType = new TupleType( + node.targets.map((target) => (target.isReassignment ? target.identifier.symbol!.type : target.type!)), + ); if (!implicitlyCastable(node.tuple.type, targetsType)) { const targetNames = node.targets.map((target) => target.identifier.name).join(', '); const syntheticAssignment = new VariableDefinitionNode(targetsType, [], targetNames, node.tuple); @@ -140,7 +140,9 @@ export default class TypeCheckTraversal extends AstTraversal { node.condition = this.visit(node.condition); const narrowings = extractBytesNarrowings(node.condition); - executeWithNarrowedTypes(narrowings, () => { node.ifBlock = this.visit(node.ifBlock); }); + executeWithNarrowedTypes(narrowings, () => { + node.ifBlock = this.visit(node.ifBlock); + }); node.elseBlock = this.visitOptional(node.elseBlock); @@ -572,10 +574,7 @@ function inferTupleType(node: BinaryOpNode): Type { } // bytesX.split(NumberLiteral) -> bytes(NumberLiteral), bytes(X - NumberLiteral) - return new TupleType([ - new BytesType(splitIndex), - new BytesType(expressionType.bound! - splitIndex), - ]); + return new TupleType([new BytesType(splitIndex), new BytesType(expressionType.bound! - splitIndex)]); } function inferSliceType(node: SliceNode): Type { @@ -631,7 +630,7 @@ const inferPaddedBytesType = (node: FunctionCallNode): Type => { return new BytesType(); }; -type Narrowing = { symbol: Symbol, bound: number }; +type Narrowing = { symbol: Symbol; bound: number }; // Temporarily narrows each symbol's type to BytesType(bound), calls fn, then restores. // Recurses through the list so each narrowing is restored in reverse order as the stack unwinds. @@ -678,7 +677,7 @@ function extractSingleBytesNarrowing(expr: BinaryOpNode): Narrowing | undefined } // Matches expr.length N or N expr.length, returning the SIZE node and int literal. -function matchSizeLiteral(expr: BinaryOpNode): { sizeNode: UnaryOpNode, literalNode: IntLiteralNode } | undefined { +function matchSizeLiteral(expr: BinaryOpNode): { sizeNode: UnaryOpNode; literalNode: IntLiteralNode } | undefined { if (isSizeOp(expr.left) && expr.right instanceof IntLiteralNode) { return { sizeNode: expr.left, literalNode: expr.right }; } @@ -690,9 +689,8 @@ function matchSizeLiteral(expr: BinaryOpNode): { sizeNode: UnaryOpNode, literalN return undefined; } -const isSizeOp = (node: ExpressionNode): node is UnaryOpNode => ( - node instanceof UnaryOpNode && node.operator === UnaryOperator.SIZE -); +const isSizeOp = (node: ExpressionNode): node is UnaryOpNode => + node instanceof UnaryOpNode && node.operator === UnaryOperator.SIZE; function expectSingleValue(node: Node, type?: Type): void { if (type instanceof TupleType) { diff --git a/packages/cashc/src/semantic/UnusedCodeTraversal.ts b/packages/cashc/src/semantic/UnusedCodeTraversal.ts index 32276d932..3556fd1f9 100644 --- a/packages/cashc/src/semantic/UnusedCodeTraversal.ts +++ b/packages/cashc/src/semantic/UnusedCodeTraversal.ts @@ -86,9 +86,7 @@ export default class UnusedCodeWarningsTraversal extends AstTraversal { visitTupleAssignment(node: TupleAssignmentNode): Node { this.visit(node.tuple); - node.targets - .filter((target) => target.isReassignment) - .forEach((target) => this.recordWrite(target.identifier)); + node.targets.filter((target) => target.isReassignment).forEach((target) => this.recordWrite(target.identifier)); return node; } diff --git a/packages/cashc/src/utils.ts b/packages/cashc/src/utils.ts index e740bb46c..5dfa1c753 100644 --- a/packages/cashc/src/utils.ts +++ b/packages/cashc/src/utils.ts @@ -8,11 +8,7 @@ export function functionReturnType(returnTypes?: Type[]): Type { return new TupleType(returnTypes); } -export function resultingTypeForBinaryOp( - operator: BinaryOperator, - left: Type, - right: Type, -): Type | undefined { +export function resultingTypeForBinaryOp(operator: BinaryOperator, left: Type, right: Type): Type | undefined { if ([BinaryOperator.SHIFT_LEFT, BinaryOperator.SHIFT_RIGHT, BinaryOperator.SPLIT].includes(operator)) return left; if (implicitlyCastable(left, right)) return right; diff --git a/packages/cashc/test/ast/AST.test.ts b/packages/cashc/test/ast/AST.test.ts index a9d0deb11..616953397 100644 --- a/packages/cashc/test/ast/AST.test.ts +++ b/packages/cashc/test/ast/AST.test.ts @@ -33,8 +33,8 @@ describe('AST Builder', () => { describe('AST consistency', () => { interface TestSetup { - ast: Ast, - sourceOutput: string + ast: Ast; + sourceOutput: string; } function setup(input: string): TestSetup { diff --git a/packages/cashc/test/ast/Location.test.ts b/packages/cashc/test/ast/Location.test.ts index ebae658fa..93f40570c 100644 --- a/packages/cashc/test/ast/Location.test.ts +++ b/packages/cashc/test/ast/Location.test.ts @@ -4,17 +4,21 @@ import { parseCode } from '../../src/parser.js'; describe('Location', () => { it('should retrieve correct text from location', () => { - const code = fs.readFileSync(new URL('../valid-contract-files/simple_functions.cash', import.meta.url), { encoding: 'utf-8' }); + const code = fs.readFileSync(new URL('../valid-contract-files/simple_functions.cash', import.meta.url), { + encoding: 'utf-8', + }); const ast = parseCode(code); const f = ast.contract!.functions[0]; expect(f.location).toBeDefined(); - expect((f.location).text(code)).toEqual('function hello(sig s, pubkey pk) {\n require(checkSig(s, pk));\n }'); + expect(f.location.text(code)).toEqual('function hello(sig s, pubkey pk) {\n require(checkSig(s, pk));\n }'); }); it('should set the correct location points', () => { - const code = fs.readFileSync(new URL('../valid-contract-files/simple_functions.cash', import.meta.url), { encoding: 'utf-8' }); + const code = fs.readFileSync(new URL('../valid-contract-files/simple_functions.cash', import.meta.url), { + encoding: 'utf-8', + }); const ast = parseCode(code); const secondFunction = ast.contract!.functions[1]; diff --git a/packages/cashc/test/bitauth-script/bitauth-script.test.ts b/packages/cashc/test/bitauth-script/bitauth-script.test.ts index 64d5caf11..401026046 100644 --- a/packages/cashc/test/bitauth-script/bitauth-script.test.ts +++ b/packages/cashc/test/bitauth-script/bitauth-script.test.ts @@ -69,9 +69,10 @@ describe('Libauth Script formatting', () => { }); describe('User-defined function formatting', () => { - const compileFixture = (fixture: FunctionFixture): Artifact => (fixture.file - ? compileFile(new URL(`./fixtures/${fixture.file}`, import.meta.url), fixture.compilerOptions) - : compileString(fixture.sourceCode!, fixture.compilerOptions)); + const compileFixture = (fixture: FunctionFixture): Artifact => + fixture.file + ? compileFile(new URL(`./fixtures/${fixture.file}`, import.meta.url), fixture.compilerOptions) + : compileString(fixture.sourceCode!, fixture.compilerOptions); functionFixtures.forEach((fixture) => { describe(fixture.name, () => { diff --git a/packages/cashc/test/compiler/compiler.test.ts b/packages/cashc/test/compiler/compiler.test.ts index 7c5050007..cda41e245 100644 --- a/packages/cashc/test/compiler/compiler.test.ts +++ b/packages/cashc/test/compiler/compiler.test.ts @@ -54,7 +54,11 @@ describe('Compiler', () => { const warnings: Warnings.CashScriptWarning[] = []; try { - compileString(file.contents, { warningListener: (warning) => { warnings.push(warning); } }); + compileString(file.contents, { + warningListener: (warning) => { + warnings.push(warning); + }, + }); } catch { // ignore compilation errors from later phases } @@ -112,7 +116,11 @@ describe('Compiler', () => { describe('Custom warning listener', () => { it('uses the custom warning listener for compilation warnings', () => { const warnings: Warnings.CashScriptWarning[] = []; - compileString(UNUSED_VARIABLE_SOURCE, { warningListener: (warning) => { warnings.push(warning); } }); + compileString(UNUSED_VARIABLE_SOURCE, { + warningListener: (warning) => { + warnings.push(warning); + }, + }); expect(warnings).toHaveLength(1); expect(warnings[0]).toBeInstanceOf(Warnings.UnusedVariableWarning); diff --git a/packages/cashc/test/generation/fixture-utils.ts b/packages/cashc/test/generation/fixture-utils.ts index 5946ffd7c..f508c24df 100644 --- a/packages/cashc/test/generation/fixture-utils.ts +++ b/packages/cashc/test/generation/fixture-utils.ts @@ -14,17 +14,20 @@ export interface FixtureModule { } export async function loadFixtureModules(): Promise { - const modulePaths = fs.readdirSync(new URL('fixtures/', import.meta.url), { recursive: true, encoding: 'utf-8' }) + const modulePaths = fs + .readdirSync(new URL('fixtures/', import.meta.url), { recursive: true, encoding: 'utf-8' }) .map((entry) => entry.replaceAll('\\', '/')) .filter((entry) => entry.endsWith('.ts')); - return Promise.all(modulePaths.map(async (modulePath) => { - const imported = await import(`./fixtures/${modulePath.replace(/\.ts$/, '.js')}`); + return Promise.all( + modulePaths.map(async (modulePath) => { + const imported = await import(`./fixtures/${modulePath.replace(/\.ts$/, '.js')}`); - if (!Array.isArray(imported.fixtures)) { - throw new Error(`Fixture module fixtures/${modulePath} must export a 'fixtures' array`); - } + if (!Array.isArray(imported.fixtures)) { + throw new Error(`Fixture module fixtures/${modulePath} must export a 'fixtures' array`); + } - return { cashFile: modulePath.replace(/\.ts$/, '.cash'), fixtures: imported.fixtures }; - })); + return { cashFile: modulePath.replace(/\.ts$/, '.cash'), fixtures: imported.fixtures }; + }), + ); } diff --git a/packages/cashc/test/generation/generation.test.ts b/packages/cashc/test/generation/generation.test.ts index 2846c45ff..7faa8a7f8 100644 --- a/packages/cashc/test/generation/generation.test.ts +++ b/packages/cashc/test/generation/generation.test.ts @@ -9,7 +9,8 @@ const fixtureModules = await loadFixtureModules(); describe('Code generation & target code optimisation', () => { it('should have a fixture module for every valid contract file', () => { - const cashFiles = fs.readdirSync(new URL('../valid-contract-files', import.meta.url)) + const cashFiles = fs + .readdirSync(new URL('../valid-contract-files', import.meta.url)) .filter((fn) => fn.endsWith('.cash')) .map((fn) => `valid-contract-files/${fn}`); diff --git a/packages/cashc/test/global-definitions.test.ts b/packages/cashc/test/global-definitions.test.ts index ea09f474e..d38bc3ec7 100644 --- a/packages/cashc/test/global-definitions.test.ts +++ b/packages/cashc/test/global-definitions.test.ts @@ -259,14 +259,18 @@ describe('Inlining and shared definitions', () => { // own line is retained on its frame for future source attribution const artifact = compileString(code); expect(artifact.bytecode).not.toContain('OP_DEFINE'); - expect(artifact.debug?.requires).toContainEqual(expect.objectContaining({ - line: 7, - message: 'too big', - })); - expect(artifact.debug?.functions?.[0].requires).toContainEqual(expect.objectContaining({ - line: 3, - message: 'too big', - })); + expect(artifact.debug?.requires).toContainEqual( + expect.objectContaining({ + line: 7, + message: 'too big', + }), + ); + expect(artifact.debug?.functions?.[0].requires).toContainEqual( + expect.objectContaining({ + line: 3, + message: 'too big', + }), + ); }); it('attributes debug info of an inlined imported function to the call site', () => { @@ -284,15 +288,19 @@ describe('Inlining and shared definitions', () => { // is attributed to the call-site line; the function's frame retains its source provenance const artifact = compileString(source, { files: { './helpers.cash': importedSource } }); expect(artifact.bytecode).not.toContain('OP_DEFINE'); - expect(artifact.debug?.requires).toContainEqual(expect.objectContaining({ - line: 5, - message: 'must be positive', - })); - expect(artifact.debug?.functions).toContainEqual(expect.objectContaining({ - name: 'assertPositive', - sourceFile: 'helpers.cash', - requires: [expect.objectContaining({ line: 2, message: 'must be positive' })], - })); + expect(artifact.debug?.requires).toContainEqual( + expect.objectContaining({ + line: 5, + message: 'must be positive', + }), + ); + expect(artifact.debug?.functions).toContainEqual( + expect.objectContaining({ + name: 'assertPositive', + sourceFile: 'helpers.cash', + requires: [expect.objectContaining({ line: 2, message: 'must be positive' })], + }), + ); expect(artifact.debug?.sources).toEqual({ 'helpers.cash': importedSource }); expect(artifact.debug?.functions?.[0].id).toBeUndefined(); expect(artifact.debug?.inlineRanges).toMatch(/^\d+:\d+:assertPositive$/); @@ -318,10 +326,12 @@ describe('Inlining and shared definitions', () => { { name: 'big', id: 0 }, { name: 'assertSmall', id: undefined }, ]); - expect(artifact.debug?.functions?.[0].requires).toContainEqual(expect.objectContaining({ - line: 7, - message: 'value too large', - })); + expect(artifact.debug?.functions?.[0].requires).toContainEqual( + expect.objectContaining({ + line: 7, + message: 'value too large', + }), + ); expect(artifact.debug?.functions?.[0].inlineRanges).toMatch(/^\d+:\d+:assertSmall$/); }); @@ -448,8 +458,9 @@ describe('Stable function ID assignment', () => { // functionIds follow call order (b, then a) rather than declaration order, so swapping the two // declarations produces byte-identical output. - expect(compileString(reordered, { disableInlining: true }).bytecode) - .toEqual(compileString(ordered, { disableInlining: true }).bytecode); + expect(compileString(reordered, { disableInlining: true }).bytecode).toEqual( + compileString(ordered, { disableInlining: true }).bytecode, + ); }); it('renaming a function does not change the bytecode', () => { @@ -473,8 +484,9 @@ describe('Stable function ID assignment', () => { } }`; - expect(compileString(renamed, { disableInlining: true }).bytecode) - .toEqual(compileString(original, { disableInlining: true }).bytecode); + expect(compileString(renamed, { disableInlining: true }).bytecode).toEqual( + compileString(original, { disableInlining: true }).bytecode, + ); }); it('assigns IDs by first use across functions and constants', () => { diff --git a/packages/cashc/test/imports.test.ts b/packages/cashc/test/imports.test.ts index 3cf87258d..98388de2c 100644 --- a/packages/cashc/test/imports.test.ts +++ b/packages/cashc/test/imports.test.ts @@ -13,9 +13,8 @@ const readFixture = (name: string): string => fs.readFileSync(fixture(name), { e const countOpDefines = (bytecode: string): number => [...bytecode.matchAll(/OP_DEFINE/g)].length; // An artifact stores the source code of every imported file, so it can be recompiled from itself -const recompile = (artifact: Artifact): Artifact => ( - compileString(artifact.source, { ...artifact.compiler.options, files: artifact.debug?.sources }) -); +const recompile = (artifact: Artifact): Artifact => + compileString(artifact.source, { ...artifact.compiler.options, files: artifact.debug?.sources }); describe('Imports from the filesystem (compileFile)', () => { it('merges global functions from an imported file', () => { @@ -108,8 +107,9 @@ describe('Imports from in-memory files (compileString)', () => { }); it('supports files with the same basename in different directories', () => { - const code = 'import "./a/helper.cash";\nimport "./b/helper.cash";\n' - + 'contract C() { function spend(int x) { require(helperA(x) + helperB(x) == 10); } }'; + const code = + 'import "./a/helper.cash";\nimport "./b/helper.cash";\n' + + 'contract C() { function spend(int x) { require(helperA(x) + helperB(x) == 10); } }'; const files = { 'a/helper.cash': 'function helperA(int n) returns (int) { return n + 1; }', 'b/helper.cash': 'function helperB(int n) returns (int) { return n * 2; }', @@ -120,8 +120,9 @@ describe('Imports from in-memory files (compileString)', () => { }); it('de-duplicates a diamond import so a shared leaf is defined once', () => { - const code = 'import "./mid1.cash";\nimport "./mid2.cash";\n' - + 'contract Diamond() { function spend(int x) { require(m1(x) + m2(x) == 18); } }'; + const code = + 'import "./mid1.cash";\nimport "./mid2.cash";\n' + + 'contract Diamond() { function spend(int x) { require(m1(x) + m2(x) == 18); } }'; const files = { 'mid1.cash': 'import "./leaf.cash";\nfunction m1(int a) returns (int) { return leaf(a) * 2; }', 'mid2.cash': 'import "./leaf.cash";\nfunction m2(int a) returns (int) { return leaf(a) + 3; }', @@ -235,8 +236,10 @@ describe('Imports from node_modules (package imports)', () => { const artifact = compileFile(fixture('nm_package_deps_main.cash'), { disableInlining: true }); expect(artifact.contractName).toEqual('NodeModulesPackageDeps'); expect(countOpDefines(artifact.bytecode)).toEqual(2); - expect(artifact.debug?.functions?.map((func) => func.sourceFile).sort()) - .toEqual(['package:@cashlibs/utils/util.cash', 'package:mathlib/combined.cash']); + expect(artifact.debug?.functions?.map((func) => func.sourceFile).sort()).toEqual([ + 'package:@cashlibs/utils/util.cash', + 'package:mathlib/combined.cash', + ]); }); it('resolves scoped package imports', () => { @@ -247,14 +250,18 @@ describe('Imports from node_modules (package imports)', () => { it('records provenance as the logical package path rather than a filesystem path', () => { const artifact = compileFile(fixture('nm_transitive_main.cash'), { disableInlining: true }); - expect(artifact.debug?.functions?.map((func) => func.sourceFile).sort()) - .toEqual(['package:mathlib/helper.cash', 'package:mathlib/main.cash']); + expect(artifact.debug?.functions?.map((func) => func.sourceFile).sort()).toEqual([ + 'package:mathlib/helper.cash', + 'package:mathlib/main.cash', + ]); }); it('throws when different copies of a package are imported', () => { // copies/main.cash imports foo/x.cash, and bar/y.cash imports bar's own nested copy of foo/x.cash expect(() => compileFile(fixture('copies/main.cash'))).toThrow(ImportResolutionError); - expect(() => compileFile(fixture('copies/main.cash'))).toThrow(/Importing multiple copies of a package is not supported/); + expect(() => compileFile(fixture('copies/main.cash'))).toThrow( + /Importing multiple copies of a package is not supported/, + ); }); it('throws when a package import cannot be found in any node_modules directory', () => { @@ -265,8 +272,7 @@ describe('Imports from node_modules (package imports)', () => { }); it('resolves package imports from package: keys in the files option when compiling from a string', () => { - const code = 'import "mathlib/math.cash";\n' - + 'contract C() { function spend(int x) { require(nmAdd(x, 3) == 8); } }'; + const code = 'import "mathlib/math.cash";\n' + 'contract C() { function spend(int x) { require(nmAdd(x, 3) == 8); } }'; const files = { 'package:mathlib/math.cash': readFixture('node_modules/mathlib/math.cash') }; const artifact = compileString(code, { files, disableInlining: true }); @@ -276,8 +282,7 @@ describe('Imports from node_modules (package imports)', () => { it('does not resolve package imports from local files in the files option', () => { // A package import that is missing its './' must fail like it does in compileFile - const code = 'import "lib/math.cash";\n' - + 'contract C() { function spend(int x) { require(nmAdd(x, 3) == 8); } }'; + const code = 'import "lib/math.cash";\n' + 'contract C() { function spend(int x) { require(nmAdd(x, 3) == 8); } }'; const files = { 'lib/math.cash': readFixture('node_modules/mathlib/math.cash') }; expect(() => compileString(code, { files })).toThrow(ImportResolutionError); @@ -285,8 +290,9 @@ describe('Imports from node_modules (package imports)', () => { }); it('keeps in-memory package files separate from local files with the same path', () => { - const code = 'import "pkg/math.cash";\nimport "./pkg/math.cash";\n' - + 'contract C() { function spend(int x) { require(fromPackage(x) + fromLocal(x) == 3); } }'; + const code = + 'import "pkg/math.cash";\nimport "./pkg/math.cash";\n' + + 'contract C() { function spend(int x) { require(fromPackage(x) + fromLocal(x) == 3); } }'; const files = { 'package:pkg/math.cash': 'function fromPackage(int n) returns (int) { return n + 1; }', 'pkg/math.cash': 'function fromLocal(int n) returns (int) { return n + 2; }', @@ -297,8 +303,7 @@ describe('Imports from node_modules (package imports)', () => { }); it('resolves relative imports inside an in-memory package relative to the package file', () => { - const code = 'import "pkg/main.cash";\n' - + 'contract C() { function spend(int x) { require(pkgMain(x) == 12); } }'; + const code = 'import "pkg/main.cash";\n' + 'contract C() { function spend(int x) { require(pkgMain(x) == 12); } }'; const files = { 'package:pkg/main.cash': 'import "./helper.cash";\nfunction pkgMain(int n) returns (int) { return pkgHelper(n) * 2; }', 'package:pkg/helper.cash': 'function pkgHelper(int n) returns (int) { return n + 1; }', @@ -351,9 +356,7 @@ describe('Imports through symlinked packages (pnpm, npm link)', () => { fs.mkdirSync(path.dirname(path.join(tempDir, linkPath)), { recursive: true }); fs.symlinkSync(path.join(tempDir, target), path.join(tempDir, linkPath), 'junction'); }; - const compileTemp = (filePath: string): Artifact => ( - compileFile(path.join(tempDir, filePath), { disableInlining: true }) - ); + const compileTemp = (filePath: string): Artifact => compileFile(path.join(tempDir, filePath), { disableInlining: true }); const sourceFiles = (artifact: Artifact): string[] => artifact.debug!.functions!.map((func) => func.sourceFile!).sort(); beforeAll(() => { @@ -363,33 +366,49 @@ describe('Imports through symlinked packages (pnpm, npm link)', () => { // to the package in node_modules/.pnpm/@/node_modules write('pnpm/node_modules/.pnpm/inner-lib@1.0.0/node_modules/inner-lib/util.cash', PACKAGE_SOURCES['util.cash']); write('pnpm/node_modules/.pnpm/outer-lib@1.0.0/node_modules/outer-lib/lib.cash', PACKAGE_SOURCES['lib.cash']); - link('pnpm/node_modules/.pnpm/inner-lib@1.0.0/node_modules/inner-lib', 'pnpm/node_modules/.pnpm/outer-lib@1.0.0/node_modules/inner-lib'); + link( + 'pnpm/node_modules/.pnpm/inner-lib@1.0.0/node_modules/inner-lib', + 'pnpm/node_modules/.pnpm/outer-lib@1.0.0/node_modules/inner-lib', + ); link('pnpm/node_modules/.pnpm/outer-lib@1.0.0/node_modules/outer-lib', 'pnpm/node_modules/outer-lib'); - write('pnpm/transitive.cash', 'import "outer-lib/lib.cash";\n' - + 'contract Transitive() { function spend(int x) { require(outerFn(x) == 5); } }'); + write( + 'pnpm/transitive.cash', + 'import "outer-lib/lib.cash";\n' + 'contract Transitive() { function spend(int x) { require(outerFn(x) == 5); } }', + ); // A project that depends on both outer-lib and inner-lib (which outer-lib also depends on) link('pnpm/node_modules/.pnpm/outer-lib@1.0.0/node_modules/outer-lib', 'pnpm-shared/node_modules/outer-lib'); link('pnpm/node_modules/.pnpm/inner-lib@1.0.0/node_modules/inner-lib', 'pnpm-shared/node_modules/inner-lib'); - write('pnpm-shared/shared.cash', 'import "outer-lib/lib.cash";\nimport "inner-lib/util.cash";\n' - + 'contract Shared() { function spend(int x) { require(outerFn(x) + innerDouble(x) == 9); } }'); + write( + 'pnpm-shared/shared.cash', + 'import "outer-lib/lib.cash";\nimport "inner-lib/util.cash";\n' + + 'contract Shared() { function spend(int x) { require(outerFn(x) + innerDouble(x) == 9); } }', + ); // npm link / workspaces: the package is linked from outside of node_modules write('workspace/packages/linked/main.cash', PACKAGE_SOURCES['main.cash']); write('workspace/packages/linked/sub/helper.cash', PACKAGE_SOURCES['helper.cash']); link('workspace/packages/linked', 'workspace/app/node_modules/linked'); - write('workspace/app/main.cash', 'import "linked/main.cash";\n' - + 'contract Linked() { function spend(int x) { require(linkedFn(x) == 7); } }'); + write( + 'workspace/app/main.cash', + 'import "linked/main.cash";\n' + 'contract Linked() { function spend(int x) { require(linkedFn(x) == 7); } }', + ); // A project that imports a local file through a symlinked directory write('shared-code/helper.cash', PACKAGE_SOURCES['helper.cash']); link('shared-code', 'linked-dir/shared'); - write('linked-dir/main.cash', 'import "./shared/helper.cash";\n' - + 'contract LinkedDir() { function spend(int x) { require(linkedHelper(x) == 6); } }'); + write( + 'linked-dir/main.cash', + 'import "./shared/helper.cash";\n' + + 'contract LinkedDir() { function spend(int x) { require(linkedHelper(x) == 6); } }', + ); // A project that is itself reached through a symlink write('project/lib.cash', 'function localFn(int x) returns (int) { return x + 2; }'); - write('project/main.cash', 'import "./lib.cash";\ncontract Project() { function spend(int x) { require(localFn(x) == 4); } }'); + write( + 'project/main.cash', + 'import "./lib.cash";\ncontract Project() { function spend(int x) { require(localFn(x) == 4); } }', + ); link('project', 'project-link'); }); @@ -397,7 +416,7 @@ describe('Imports through symlinked packages (pnpm, npm link)', () => { fs.rmSync(tempDir, { recursive: true, force: true }); }); - it('resolves a package\'s own dependencies from where the package is installed', () => { + it("resolves a package's own dependencies from where the package is installed", () => { const artifact = compileTemp('pnpm/transitive.cash'); expect(sourceFiles(artifact)).toEqual(['package:inner-lib/util.cash', 'package:outer-lib/lib.cash']); }); @@ -448,8 +467,16 @@ describe('Imports through symlinked packages (pnpm, npm link)', () => { describe('compileFile / compileString equivalence', () => { const RECOMPILABLE_FIXTURES = [ - 'main.cash', 'diamond.cash', 'multi_return_main.cash', 'nested_main.cash', 'complex/main.cash', 'nm_main.cash', - 'nm_transitive_main.cash', 'nm_package_deps_main.cash', 'nm_scoped_main.cash', 'nested/nm_nested_main.cash', + 'main.cash', + 'diamond.cash', + 'multi_return_main.cash', + 'nested_main.cash', + 'complex/main.cash', + 'nm_main.cash', + 'nm_transitive_main.cash', + 'nm_package_deps_main.cash', + 'nm_scoped_main.cash', + 'nested/nm_nested_main.cash', 'shadow/nm_shadow_main.cash', ]; diff --git a/packages/cashc/test/semantic/InjectLocktimeGuardTraversal.test.ts b/packages/cashc/test/semantic/InjectLocktimeGuardTraversal.test.ts index c99f91139..1848dec93 100644 --- a/packages/cashc/test/semantic/InjectLocktimeGuardTraversal.test.ts +++ b/packages/cashc/test/semantic/InjectLocktimeGuardTraversal.test.ts @@ -140,7 +140,6 @@ describe('InjectLocktimeGuardTraversal', () => { expect(compileString(src).bytecode.startsWith(GUARD_PREFIX)).toBe(true); }); - it('does not inject when tx.locktime appears only inside a tx.time check expression', () => { const src = ` contract T() { @@ -221,8 +220,8 @@ describe('InjectLocktimeGuardTraversal', () => { // distinctive message, which is detectable even when the OP_DEFINE prologue precedes the contract body. describe('InjectLocktimeGuardTraversal — global functions', () => { const GUARD_MESSAGE = 'non-final sequence number'; - const guardInjected = (src: string): boolean => (compileString(src).debug?.requires ?? []) - .some((statement) => statement.message?.includes(GUARD_MESSAGE)); + const guardInjected = (src: string): boolean => + (compileString(src).debug?.requires ?? []).some((statement) => statement.message?.includes(GUARD_MESSAGE)); it('injects guard in the contract when an invoked global uses tx.locktime', () => { const src = ` diff --git a/packages/cashc/test/test-utils.ts b/packages/cashc/test/test-utils.ts index 42db93b81..90636951d 100644 --- a/packages/cashc/test/test-utils.ts +++ b/packages/cashc/test/test-utils.ts @@ -2,12 +2,12 @@ import fs from 'fs'; import { URL } from 'url'; export function getSubdirectories(directory: URL): string[] { - return fs.readdirSync(directory) - .filter((fn) => fs.statSync(new URL(fn, `${directory}/`)).isDirectory()); + return fs.readdirSync(directory).filter((fn) => fs.statSync(new URL(fn, `${directory}/`)).isDirectory()); } -export function readCashFiles(directory: URL): { fn: string, contents: string }[] { - return fs.readdirSync(directory) +export function readCashFiles(directory: URL): { fn: string; contents: string }[] { + return fs + .readdirSync(directory) .filter((fn) => fn.endsWith('.cash')) .map((fn) => ({ fn, contents: fs.readFileSync(new URL(fn, `${directory}/`), { encoding: 'utf-8' }) })); } diff --git a/packages/cashscript/src/Argument.ts b/packages/cashscript/src/Argument.ts index d0b860bb5..68e6842e0 100644 --- a/packages/cashscript/src/Argument.ts +++ b/packages/cashscript/src/Argument.ts @@ -119,8 +119,7 @@ export const encodeConstructorArguments = ( throw new Error('Cannot use signatures in constructor'); } - const encodedArgs = constructorArgs - .map((arg, i) => encodeFunction(arg, artifact.constructorInputs[i].type)); + const encodedArgs = constructorArgs.map((arg, i) => encodeFunction(arg, artifact.constructorInputs[i].type)); return encodedArgs as Uint8Array[]; }; diff --git a/packages/cashscript/src/Contract.ts b/packages/cashscript/src/Contract.ts index fc4170244..06a29330e 100644 --- a/packages/cashscript/src/Contract.ts +++ b/packages/cashscript/src/Contract.ts @@ -9,16 +9,17 @@ import { hash256, scriptToBytecode, } from '@cashscript/utils'; +import { ConstructorArgument, encodeFunctionArgument, encodeConstructorArguments, FunctionArgument } from './Argument.js'; import { - ConstructorArgument, encodeFunctionArgument, encodeConstructorArguments, FunctionArgument, -} from './Argument.js'; -import { - Unlocker, ContractOptions, GenerateUnlockingBytecodeOptions, SpendableUtxo, ContractType, ContractFunctionUnlocker, + Unlocker, + ContractOptions, + GenerateUnlockingBytecodeOptions, + SpendableUtxo, + ContractType, + ContractFunctionUnlocker, } from './interfaces.js'; import NetworkProvider from './network/NetworkProvider.js'; -import { - addressToLockScript, createUnlockingBytecode, createSighashPreimage, scriptToAddress, -} from './utils.js'; +import { addressToLockScript, createUnlockingBytecode, createSighashPreimage, scriptToAddress } from './utils.js'; import SignatureTemplate from './SignatureTemplate.js'; import { ParamsToTuple, AbiToFunctionMap } from './types/type-inference.js'; import semver from 'semver'; @@ -129,7 +130,7 @@ class ContractInternal< // Note: technically, it is possible to instantiate a Contract like this, which breaks the type safety, // but it seems unreasonable for anyone to do this // new Contract(artifact), [], { provider }) - this.contractType = this.options.contractType ?? 'p2sh32' as TContractType; + this.contractType = this.options.contractType ?? ('p2sh32' as TContractType); const expectedProperties = ['abi', 'bytecode', 'constructorInputs', 'contractName', 'compiler']; if (!expectedProperties.every((property) => property in artifact)) { @@ -141,7 +142,9 @@ class ContractInternal< } if (artifact.constructorInputs.length !== constructorArgs.length) { - throw new Error(`Incorrect number of arguments passed to ${artifact.contractName} constructor. Expected ${artifact.constructorInputs.length} arguments (${artifact.constructorInputs.map((input) => input.type)}) but got ${constructorArgs.length}`); + throw new Error( + `Incorrect number of arguments passed to ${artifact.contractName} constructor. Expected ${artifact.constructorInputs.length} arguments (${artifact.constructorInputs.map((input) => input.type)}) but got ${constructorArgs.length}`, + ); } // Encode arguments (this also performs type checking) @@ -162,7 +165,8 @@ class ContractInternal< } const contractBytecodeScript = generateContractBytecodeScript( - asmToScript(this.artifact.bytecode), this.encodedConstructorArgs, + asmToScript(this.artifact.bytecode), + this.encodedConstructorArgs, ); if (this.contractType !== 'p2s') { @@ -180,15 +184,18 @@ class ContractInternal< private createUnlocker(abiFunction: AbiFunction, selector?: number): ContractFunctionUnlocker { return (...args: FunctionArgument[]) => { if (abiFunction.inputs.length !== args.length) { - throw new Error(`Incorrect number of arguments passed to function ${abiFunction.name}. Expected ${abiFunction.inputs.length} arguments (${abiFunction.inputs.map((input) => input.type)}) but got ${args.length}`); + throw new Error( + `Incorrect number of arguments passed to function ${abiFunction.name}. Expected ${abiFunction.inputs.length} arguments (${abiFunction.inputs.map((input) => input.type)}) but got ${args.length}`, + ); } - const encodedArgs = args - .map((arg, i) => encodeFunctionArgument(arg, abiFunction.inputs[i].type)); + const encodedArgs = args.map((arg, i) => encodeFunctionArgument(arg, abiFunction.inputs[i].type)); - const generateUnlockingBytecode = ( - { transaction, sourceOutputs, inputIndex }: GenerateUnlockingBytecodeOptions, - ): Uint8Array => { + const generateUnlockingBytecode = ({ + transaction, + sourceOutputs, + inputIndex, + }: GenerateUnlockingBytecodeOptions): Uint8Array => { const bytecode = hexToBin(this.bytecode); const completeArgs = encodedArgs.map((arg) => { @@ -217,8 +224,8 @@ export type Contract< TResolved extends ResolvedConstraint = DefaultResolved, // The default of the Contract type is unspecified TContractType extends ContractType = ContractType, -// We opt out of the distributive conditional type behavior so users of generic 'Contract' types can access -// 'address' and 'tokenAddress' (even if they are not 'p2s') + // We opt out of the distributive conditional type behavior so users of generic 'Contract' types can access + // 'address' and 'tokenAddress' (even if they are not 'p2s') > = [TContractType] extends ['p2s'] ? Omit, 'address' | 'tokenAddress'> : ContractInternal; diff --git a/packages/cashscript/src/Errors.ts b/packages/cashscript/src/Errors.ts index ad4c40e10..712066c2c 100644 --- a/packages/cashscript/src/Errors.ts +++ b/packages/cashscript/src/Errors.ts @@ -22,13 +22,17 @@ export class UndefinedInputError extends Error { export class InputMissingLockingBytecodeError extends Error { constructor() { - super('Input UTXO is missing its lockingBytecode. UTXOs fetched from a network provider include it automatically; when constructing UTXOs manually, set lockingBytecode to the hex-encoded locking script of the output.'); + super( + 'Input UTXO is missing its lockingBytecode. UTXOs fetched from a network provider include it automatically; when constructing UTXOs manually, set lockingBytecode to the hex-encoded locking script of the output.', + ); } } export class OutputSatoshisTooSmallError extends Error { constructor(satoshis: bigint, minimumAmount: bigint) { - super(`Tried to add an output with ${satoshis} satoshis, which is less than the required minimum for this output-type (${minimumAmount})`); + super( + `Tried to add an output with ${satoshis} satoshis, which is less than the required minimum for this output-type (${minimumAmount})`, + ); } } @@ -70,7 +74,9 @@ export class OutputBchChangeLockedError extends Error { export class OutputTokenChangeLockedError extends Error { constructor(category: string) { - super(`Tried to add a token input or output with category ${category} after a change output with the same category was already added`); + super( + `Tried to add a token input or output with category ${category} after a change output with the same category was already added`, + ); } } @@ -82,7 +88,9 @@ export class TokensToNonTokenAddressError extends Error { export class OutputAddressNetworkMismatchError extends Error { constructor(address: string, expectedNetworkPrefix: string) { - super(`Tried to add an output to an address on the wrong network, ${address}. Expected network prefix: ${expectedNetworkPrefix}.`); + super( + `Tried to add an output to an address on the wrong network, ${address}. Expected network prefix: ${expectedNetworkPrefix}.`, + ); } } @@ -111,7 +119,9 @@ export class UnlockerLockingBytecodeMismatchError extends Error { unlockerLockScript: string, unlockerDescription: string, ) { - super(`Input #${inputIndex} is locked by ${utxoLockScript}, which does not match the provided unlocker (${unlockerDescription}, corresponding to ${unlockerLockScript}). This transaction would be rejected by the network. Make sure to use an unlocker that matches the address/contract holding the UTXO.`); + super( + `Input #${inputIndex} is locked by ${utxoLockScript}, which does not match the provided unlocker (${unlockerDescription}, corresponding to ${unlockerLockScript}). This transaction would be rejected by the network. Make sure to use an unlocker that matches the address/contract holding the UTXO.`, + ); } } @@ -135,7 +145,9 @@ export class TransactionFeePerByteTooHighError extends Error { export class TransactionFeePerByteTooLowError extends Error { constructor(feePerByte: number, minimumFeePerByte: number) { - super(`Transaction fee per byte of ${feePerByte} is lower than the standard minimum fee per byte of ${minimumFeePerByte}`); + super( + `Transaction fee per byte of ${feePerByte} is lower than the standard minimum fee per byte of ${minimumFeePerByte}`, + ); } } @@ -146,8 +158,12 @@ export class NoDebugInformationInArtifactError extends Error { } export class FailedTransactionError extends Error { - constructor(public reason: string, public bitauthUri: string) { - const warning = 'WARNING: it is unsafe to use this Bitauth URI when using real private keys as they are included in the transaction template'; + constructor( + public reason: string, + public bitauthUri: string, + ) { + const warning = + 'WARNING: it is unsafe to use this Bitauth URI when using real private keys as they are included in the transaction template'; super(`${reason}${bitauthUri ? `\n\n${warning}\n\nBitauth URI: ${bitauthUri}` : ''}`); } } @@ -218,9 +234,10 @@ const formatFrameContext = (frame: ResolvedFrame, contractName: string, lineNumb return `in contract ${contractName}.cash at line ${lineNumber}`; }; -const formatCallStack = (callStack: CallStackEntry[]): string => callStack - .map(({ functionName, sourceName, line, statement }) => { - const location = functionName ? `${functionName} (${sourceName}:${line})` : `${sourceName}:${line}`; - return ` at ${location} — ${statement}`; - }) - .join('\n'); +const formatCallStack = (callStack: CallStackEntry[]): string => + callStack + .map(({ functionName, sourceName, line, statement }) => { + const location = functionName ? `${functionName} (${sourceName}:${line})` : `${sourceName}:${line}`; + return ` at ${location} — ${statement}`; + }) + .join('\n'); diff --git a/packages/cashscript/src/SignatureTemplate.ts b/packages/cashscript/src/SignatureTemplate.ts index f80246efe..945416c12 100644 --- a/packages/cashscript/src/SignatureTemplate.ts +++ b/packages/cashscript/src/SignatureTemplate.ts @@ -1,11 +1,6 @@ import { decodePrivateKeyWif, hexToBin, isHex, secp256k1 } from '@bitauth/libauth'; import { hash256, scriptToBytecode } from '@cashscript/utils'; -import { - GenerateUnlockingBytecodeOptions, - SighashType, - SignatureAlgorithm, - P2PKHUnlocker, -} from './interfaces.js'; +import { GenerateUnlockingBytecodeOptions, SighashType, SignatureAlgorithm, P2PKHUnlocker } from './interfaces.js'; import { createSighashPreimage, publicKeyToP2PKHLockingBytecode, toSigningSerializationType } from './utils.js'; /** @@ -70,9 +65,10 @@ export default class SignatureTemplate { * @returns The raw signature bytes (without an appended sighash type byte). */ signMessageHash(payload: Uint8Array): Uint8Array { - const signature = this.signatureAlgorithm === SignatureAlgorithm.SCHNORR - ? secp256k1.signMessageHashSchnorr(this.privateKey, payload) as Uint8Array - : secp256k1.signMessageHashDER(this.privateKey, payload) as Uint8Array; + const signature = + this.signatureAlgorithm === SignatureAlgorithm.SCHNORR + ? (secp256k1.signMessageHashSchnorr(this.privateKey, payload) as Uint8Array) + : (secp256k1.signMessageHashDER(this.privateKey, payload) as Uint8Array); return signature; } diff --git a/packages/cashscript/src/TransactionBuilder.ts b/packages/cashscript/src/TransactionBuilder.ts index da93ace41..46b2bc627 100644 --- a/packages/cashscript/src/TransactionBuilder.ts +++ b/packages/cashscript/src/TransactionBuilder.ts @@ -1,655 +1,663 @@ -import { - binToHex, - decodeTransaction, - decodeTransactionUnsafe, - encodeTransaction, - hexToBin, - Transaction as LibauthTransaction, - WalletTemplate, -} from '@bitauth/libauth'; -import { - Unlocker, - Output, - TransactionDetails, - UnlockableUtxo, - SpendableUtxo, - InputOptions, - isUnlockableUtxo, - isStandardUnlockableUtxo, - StandardUnlockableUtxo, - VmResourceUsage, - isContractUnlocker, - isPlaceholderUnlocker, - BchChangeOutputOptions, - TokenChangeOutputOptions, -} from './interfaces.js'; -import { PLACEHOLDER_P2PKH_UNLOCKING_SIZE } from './constants.js'; -import { NetworkProvider } from './network/index.js'; -import { - calculateDust, - cashScriptOutputToLibauthOutput, - createOpReturnOutput, - delay, - generateLibauthSourceOutputs, - getOutputSize, - validateInput, - validateOutput, - validateUnlocker, -} from './utils.js'; -import { - FailedTransactionError, - TransactionFeeTooHighError, - TransactionFeePerByteTooHighError, - TransactionFeePerByteTooLowError, - TransactionInputsRequiredError, - TransactionOutputsRequiredError, - UnlockingBytecodeTooLargeError, - TransactionTooLargeError, -} from './Errors.js'; -import { DebugResults } from './debugging.js'; -import { debugLibauthTemplate, getLibauthTemplate, getBitauthUri } from './libauth-template/LibauthTemplate.js'; -import { getWcContractInfo, WcSourceOutput, WcTransactionOptions } from './walletconnect-utils.js'; -import semver from 'semver'; -import { WcTransactionObject } from './walletconnect-utils.js'; - -/** - * Options accepted by the `TransactionBuilder` constructor. - */ -export interface TransactionBuilderOptions { - /** Network provider used to broadcast the transaction and fetch details after sending. */ - provider: NetworkProvider; - /** Optional absolute cap on the transaction fee. Build/send throws if the fee exceeds this value. */ - maximumFeeSatoshis?: bigint; - /** Optional cap on the transaction fee rate in sats/byte. Build/send throws if exceeded. */ - maximumFeeSatsPerByte?: number; - /** Allow fungible token inputs to exceed token outputs (implicit burn). Defaults to `false`. */ - allowImplicitFungibleTokenBurn?: boolean; -} - -const DEFAULT_SEQUENCE = 0xfffffffe; - -/** - * Fluent builder for constructing, debugging, and broadcasting CashScript transactions. - * - * Inputs are added via `addInput` / `addInputs` with an `Unlocker` produced by a `Contract` or - * `SignatureTemplate`, outputs are added via `addOutput` / `addOutputs`, and the resulting - * transaction can be built (`build`), debugged (`debug`), or broadcast (`send`). - */ -export class TransactionBuilder { - public provider: NetworkProvider; - public inputs: UnlockableUtxo[] = []; - public outputs: Output[] = []; - - public locktime: number = 0; - public options: TransactionBuilderOptions; - - private changeLocks: Record = {}; - - /** - * Create a new TransactionBuilder. - * - * @param options - Builder options, including the network provider and optional fee/burn limits. - */ - constructor( - options: TransactionBuilderOptions, - ) { - this.provider = options.provider; - this.options = { - allowImplicitFungibleTokenBurn: options.allowImplicitFungibleTokenBurn ?? false, - ...options, - }; - } - - /** - * Add a single UTXO as an input to the transaction. - * - * @param utxo - The UTXO to spend. - * @param unlocker - The unlocker to generate the unlocking bytecode for this input. Typically - * obtained from `contract.unlock.(...args)` or `signatureTemplate.unlockP2PKH()`. - * @param options - Optional per-input options such as a custom sequence number. - * @returns This builder for chaining. - * @throws If the UTXO is invalid. - */ - addInput(utxo: SpendableUtxo, unlocker: Unlocker, options?: InputOptions): this { - return this.addInputs([utxo], unlocker, options); - } - - /** - * Add multiple UTXOs to the transaction that all share the same unlocker. - * - * @param utxos - The UTXOs to spend. - * @param unlocker - The shared unlocker used to unlock all provided UTXOs. - * @param options - Optional per-input options applied to every added input. - * @returns This builder for chaining. - * @throws If any UTXO is invalid. - */ - addInputs(utxos: SpendableUtxo[], unlocker: Unlocker, options?: InputOptions): this; - - /** - * Add multiple UTXOs that each carry their own unlocker. - * - * @param utxos - UTXOs that have already been paired with their individual unlockers. - * @returns This builder for chaining. - * @throws If any UTXO is missing its unlocker. - */ - addInputs(utxos: UnlockableUtxo[]): this; - - addInputs(utxos: SpendableUtxo[] | UnlockableUtxo[], unlocker?: Unlocker, options?: InputOptions): this { - utxos.forEach((utxo) => validateInput(utxo, this.changeLocks)); - if ( - (!unlocker && utxos.some((utxo) => !isUnlockableUtxo(utxo))) - || (unlocker && utxos.some((utxo) => isUnlockableUtxo(utxo))) - ) { - throw new Error('Either all UTXOs must have an individual unlocker specified, or no UTXOs must have an individual unlocker specified and a shared unlocker must be provided'); - } - - utxos.forEach((utxo, i) => ( - validateUnlocker(utxo, unlocker ?? (utxo as UnlockableUtxo).unlocker, this.inputs.length + i, this.provider.network) - )); - - if (!unlocker) { - this.inputs = this.inputs.concat(utxos as UnlockableUtxo[]); - return this; - } - - this.inputs = this.inputs.concat(utxos.map(((utxo) => ({ ...utxo, unlocker, options })))); - return this; - } - - /** - * Add a single output to the transaction. - * - * @param output - The output to add. Its address, amount and optional token are validated - * against the provider's network. - * @returns This builder for chaining. - * @throws If the output is invalid. - */ - addOutput(output: Output): this { - return this.addOutputs([output]); - } - - /** - * Add multiple outputs to the transaction. - * - * @param outputs - The outputs to add. Each output is validated against the provider's network. - * @returns This builder for chaining. - * @throws If any output is invalid. - */ - addOutputs(outputs: Output[]): this { - outputs.forEach((output) => validateOutput(output, this.provider.network, this.changeLocks)); - this.outputs = this.outputs.concat(outputs); - return this; - } - - // TODO: allow uint8array for chunks - /** - * Append an `OP_RETURN` output containing the provided data chunks. Hex strings prefixed with - * `0x` are decoded as bytes; other strings are encoded as UTF-8. - * - * @param chunks - The data chunks to include after the `OP_RETURN` opcode. - * @returns This builder for chaining. - */ - addOpReturnOutput(chunks: string[]): this { - this.addOutput(createOpReturnOutput(chunks)); - return this; - } - - /** - * Add a BCH change output for the remaining value after fees, if it exceeds the dust limit. The - * fee is computed from the transaction size at the configured fee rate; dust-sized change is - * simply absorbed into the fee. - * - * Should be called *after* all explicit inputs and outputs are added. - * - * @param changeOutputOptions - The destination address and the fee rate (in sats/byte) to use. - * @returns This builder for chaining. - * @throws If the available surplus is insufficient to cover the fee for the configured rate or - * if a BCH change output was already added. - */ - addBchChangeOutputIfNeeded(changeOutputOptions: BchChangeOutputOptions): this { - const totalBchInputAmount = this.inputs.reduce((total, input) => total + input.satoshis, 0n); - const totalBchOutputAmount = this.outputs.reduce((total, output) => total + output.amount, 0n); - - const tentativeSurplus = totalBchInputAmount - totalBchOutputAmount; - const tentativeTransactionSize = this.getTransactionSize(); - const tentativeFee = BigInt(Math.ceil(changeOutputOptions.feeRate * Number(tentativeTransactionSize))); - const tentativeChangeAmount = tentativeSurplus - tentativeFee; - - if (tentativeChangeAmount < 0n) { - throw new Error(`Transaction does not have enough funds to cover the transaction fee rate of ${changeOutputOptions.feeRate} even without adding a change output. Current surplus: ${tentativeSurplus}, current fee: ${tentativeFee}, current change amount: ${tentativeChangeAmount}`); - } - - const changeOutputSize = getOutputSize({ - to: changeOutputOptions.to, - amount: tentativeSurplus, - }); - - const transactionSize = tentativeTransactionSize + BigInt(changeOutputSize); - const calculatedFee = BigInt(Math.ceil(changeOutputOptions.feeRate * Number(transactionSize))); - - const changeAmount = tentativeSurplus - calculatedFee; - const changeOutput = { to: changeOutputOptions.to, amount: changeAmount }; - - const changeOutputDust = calculateDust(changeOutput); - if (changeAmount < changeOutputDust) { - this.changeLocks.BCH = true; - return this; - } - - this.addOutput(changeOutput); - this.changeLocks.BCH = true; - return this; - } - - /** - * Add a fungible token change output for the configured category if the transaction's inputs - * contain more tokens of that category than its outputs. The change output is sent to the - * provided token address and carries the dust-minimum BCH amount. - * - * Should be called *after* all explicit token outputs for the category are added and *before* - * `addBchChangeOutputIfNeeded`. - * - * @param changeOutputOptions - The token category to handle and the destination token address. - * @returns This builder for chaining. - * @throws If the destination is not a token-supporting address, or if a corresponding change output - * or BCH change output was already added. - */ - addTokenChangeOutputIfNeeded(changeOutputOptions: TokenChangeOutputOptions): this { - const { category, to } = changeOutputOptions; - - const inputAmount = this.inputs - .filter((input) => input.token?.category === category) - .reduce((total, input) => total + input.token!.amount, 0n); - - const outputAmount = this.outputs - .filter((output) => output.token?.category === category) - .reduce((total, output) => total + output.token!.amount, 0n); - - const changeAmount = inputAmount - outputAmount; - if (changeAmount <= 0n) { - this.changeLocks[category] = true; - return this; - } - - const changeOutput: Output = { - to, - amount: 0n, - token: { amount: changeAmount, category }, - }; - changeOutput.amount = BigInt(calculateDust(changeOutput)); - - this.addOutput(changeOutput); - this.changeLocks[category] = true; - return this; - } - - /** - * Build the transaction (skipping fee and burn checks) and return its encoded byte length. - * Inputs with a placeholder unlocker are counted at the size they take up once the wallet signs them. - * - * @returns The size of the transaction in bytes. - */ - getTransactionSize(): bigint { - const transaction = this.buildLibauthTransaction(true); - return BigInt(this.getEncodedTransactionSize(transaction)); - } - - // Placeholder unlockers serialise as an empty unlocking script, so their eventual signed size is added here - private getEncodedTransactionSize(transaction: LibauthTransaction): number { - const placeholderInputCount = this.inputs.filter((input) => isPlaceholderUnlocker(input.unlocker)).length; - return encodeTransaction(transaction).byteLength + placeholderInputCount * PLACEHOLDER_P2PKH_UNLOCKING_SIZE; - } - - /** - * Calculate the transaction fee in satoshis and the fee per byte. - * - * @returns The transaction fee in satoshis and the fee per byte. - */ - calculateTransactionFee(): { feeSats: bigint, feeSatsPerByte: number } { - const transactionSize = this.getTransactionSize(); - const totalInputAmount = this.inputs.reduce((total, input) => total + input.satoshis, 0n); - const totalOutputAmount = this.outputs.reduce((total, output) => total + output.amount, 0n); - const feeSats = totalInputAmount - totalOutputAmount; - const feeSatsPerByte = Number((Number(feeSats) / Number(transactionSize)).toFixed(2)); - return { feeSats, feeSatsPerByte }; - } - - /** - * Set the `nLockTime` of the transaction. - * - * @param locktime - The absolute locktime to use (block height or UNIX timestamp). - * @returns This builder for chaining. - * @throws If the locktime is not an unsigned 32-bit integer. - */ - setLocktime(locktime: number): this { - if (!Number.isInteger(locktime) || locktime < 0 || locktime > 0xffffffff) { - throw new Error(`Locktime ${locktime} should be an integer between 0 and 4294967295`); - } - - this.locktime = locktime; - return this; - } - - /** - * Build the transaction, applying fee and implicit-burn checks, and return the hex-encoded - * transaction bytes. - * - * @returns The signed transaction as a hex string. - * @throws If the transaction fee exceeds the configured maximum, or if fungible tokens are - * implicitly burned without `allowImplicitFungibleTokenBurn` enabled. - */ - build(): string { - const transaction = this.buildLibauthTransaction(); - return binToHex(encodeTransaction(transaction)); - } - - private buildLibauthTransaction(skipChecks: boolean = false): LibauthTransaction { - if (!skipChecks) { - this.checkFungibleTokenBurn(); - this.checkInputsAndOutputs(); - } - - const inputs: LibauthTransaction['inputs'] = this.inputs.map((utxo) => ({ - outpointIndex: utxo.vout, - outpointTransactionHash: hexToBin(utxo.txid), - sequenceNumber: utxo.options?.sequence ?? DEFAULT_SEQUENCE, - unlockingBytecode: new Uint8Array(), - })); - - const outputs = this.outputs.map(cashScriptOutputToLibauthOutput); - - const transaction = { - inputs, - locktime: this.locktime, - outputs, - version: 2, - }; - - // Generate source outputs from inputs (for signing with SIGHASH_UTXOS) - const sourceOutputs = generateLibauthSourceOutputs(this.inputs); - - const inputScripts = this.inputs.map((input, inputIndex) => ( - input.unlocker.generateUnlockingBytecode({ transaction, sourceOutputs, inputIndex }) - )); - - inputScripts.forEach((script, i) => { - if (!skipChecks) this.checkUnlockingBytecodeSize(script); - transaction.inputs[i].unlockingBytecode = script; - }); - - if (!skipChecks) { - this.checkFee(transaction); - this.checkTransactionSize(transaction); - } - - return transaction; - } - - /** - * Locally evaluate the transaction against the Bitcoin Cash VM using debug information from the - * contract artifacts. Throws a descriptive error if any input fails evaluation. - * - * @returns The full debug execution trace for every scenario in the generated libauth template. - * @throws If the transaction contains inputs with custom (non-standard) unlockers, or if the - * evaluation fails (e.g. a failing `require` statement). - */ - debug(): DebugResults { - if (this.inputs.some((input) => !isStandardUnlockableUtxo(input))) { - throw new Error('Cannot debug a transaction with custom unlocker'); - } - - // We can typecast this because we check that all inputs are standard unlockable in the check above - const contractVersions = (this.inputs as StandardUnlockableUtxo[]) - .map((input) => 'contract' in input.unlocker ? input.unlocker.contract.artifact.compiler.version : null) - .filter((version) => version !== null); - - if (!contractVersions.every((version) => semver.satisfies(version, '>=0.11.0', { includePrerelease: true }))) { - console.warn('For the best debugging experience, please recompile your contract with cashc version 0.11.0 or newer.'); - } - - return debugLibauthTemplate(this.getLibauthTemplate(), this); - } - - /** - * Compute VM resource usage (ops, op cost budget, sigchecks, hash iterations) for each input - * by running the transaction through `debug`. - * - * @param verbose - When `true`, also prints a formatted table of the results via `console.table`. - * @returns One entry per input with its VM resource usage metrics. - * @throws If the transaction contains inputs with custom (non-standard) unlockers, or if the - * evaluation fails. - */ - getVmResourceUsage(verbose: boolean = false): Array { - // Note that only StandardUnlockableUtxo inputs are supported for debugging, so any transaction with custom unlockers - // cannot be debugged (and therefore cannot return VM resource usage) - const results = this.debug(); - const vmResourceUsage: Array = []; - const tableData: Array> = []; - - const formatMetric = (value: number, total: number, withPercentage: boolean = false): string => - `${formatNumber(value)} / ${formatNumber(total)}${withPercentage ? ` (${(value / total * 100).toFixed(0)}%)` : ''}`; - const formatNumber = (value: number): string => value.toLocaleString('en'); - - const resultEntries = Object.entries(results); - for (const [index, input] of this.inputs.entries()) { - const [, result] = resultEntries.find(([entryKey]) => entryKey.includes(`input${index}`)) ?? []; - const metrics = result?.at(-1)?.metrics; - - // Should not happen - if (!metrics) throw new Error('VM resource could not be calculated'); - - vmResourceUsage.push(metrics); - tableData.push({ - 'Contract - Function': isContractUnlocker(input.unlocker) ? `${input.unlocker.contract.name} - ${input.unlocker.abiFunction.name}` : 'P2PKH Input', - Ops: metrics.evaluatedInstructionCount, - 'Op Cost Budget Usage': formatMetric(metrics.operationCost, metrics.maximumOperationCost, true), - SigChecks: formatMetric(metrics.signatureCheckCount, metrics.maximumSignatureCheckCount), - Hashes: formatMetric(metrics.hashDigestIterations, metrics.maximumHashDigestIterations), - }); - } - - if (verbose) { - console.log('VM Resource usage by inputs:'); - console.table(tableData); - } - - return vmResourceUsage; - } - - /** - * Build a Bitauth IDE URI that loads the transaction (and all private keys required to sign it) - * in the online Bitauth IDE debugger. - * - * WARNING: The URI embeds every private key used in the transaction. Do not share this URI if - * the transaction is signed with real private keys. - * - * @returns A Bitauth IDE URL for debugging this transaction. - * @throws If the transaction cannot be built (fee exceeds limit or fungible tokens burned). - */ - getBitauthUri(): string { - console.warn('WARNING: it is unsafe to use this Bitauth URI when using real private keys as they are included in the transaction template'); - return getBitauthUri(this.getLibauthTemplate()); - } - - /** - * Build the transaction and return the corresponding libauth `WalletTemplate`. Useful for - * exporting the transaction to external libauth-compatible tooling. - * - * @returns A libauth `WalletTemplate` describing this transaction. - * @throws If the transaction cannot be built (fee exceeds limit or fungible tokens burned). - */ - getLibauthTemplate(): WalletTemplate { - const libauthTransaction = this.buildLibauthTransaction(); - return getLibauthTemplate(this, libauthTransaction); - } - - /** - * Build and broadcast the transaction via the configured network provider. Before broadcasting, - * the transaction is evaluated locally (when all inputs use standard unlockers) so that failing - * require statements or VM errors surface with descriptive messages. - * - * @returns The decoded transaction details (including txid and raw hex). - * @throws A `FailedTransactionError` if the network rejects the transaction, or any of the - * build / local evaluation errors (e.g. fee cap, implicit burn, failing require statement). - */ - async send(): Promise; - - /** - * Build and broadcast the transaction, returning only the raw transaction hex string as retrieved - * from the network after broadcast. - * - * @param raw - Pass `true` to receive the raw transaction hex instead of decoded details. - * @returns The raw transaction hex as retrieved from the network after broadcast. - * @throws A `FailedTransactionError` if the network rejects the transaction, or any of the - * build / local evaluation errors (e.g. fee cap, implicit burn, failing require statement). - */ - async send(raw: true): Promise; - async send(raw?: true): Promise { - const tx = this.build(); - - // If all inputs are standard unlockable, we can debug the transaction locally - // before sending so any errors are caught early - if (this.inputs.every((input) => isStandardUnlockableUtxo(input))) { - this.debug(); - } - - let txid: string; - try { - txid = await this.provider.sendRawTransaction(tx); - } catch (e: any) { - const reason = e.error ?? e.message; - - const getBitauthUriWithFallback = (): string => { - try { - return getBitauthUri(this.getLibauthTemplate()); - } catch { - return 'Bitauth URI generation failed'; - } - }; - - throw new FailedTransactionError(reason, getBitauthUriWithFallback()); - } - - // The transaction was broadcast successfully, so failing to retrieve it afterwards is not a failed transaction - return raw ? this.getTxDetails(txid, raw) : this.getTxDetails(txid); - } - - private async getTxDetails(txid: string): Promise; - private async getTxDetails(txid: string, raw: true): Promise; - private async getTxDetails(txid: string, raw?: true): Promise { - for (let retries = 0; retries < 1200; retries += 1) { - await delay(500); - try { - const hex = await this.provider.getRawTransaction(txid); - - if (raw) return hex; - - const libauthTransaction = decodeTransaction(hexToBin(hex)) as LibauthTransaction; - return { ...libauthTransaction, txid, hex }; - } catch (ignored) { - // ignored - } - } - - throw new Error(`Transaction ${txid} was broadcast, but its details could not be retrieved for over 10 minutes`); - } - - /** - * Build the transaction and format it as a BCH WalletConnect transaction object suitable for - * signing and broadcasting via a BCH WalletConnect-compatible Bitcoin Cash wallet. - * - * See the [BCH WalletConnect spec](https://github.com/mainnet-pat/wc2-bch-bcr) for the object format. - * - * @param options - Optional WalletConnect options such as `broadcast` and `userPrompt`. - * @returns A WalletConnect transaction object ready to be sent to a WalletConnect wallet. - * @throws If the transaction cannot be built (fee exceeds limit or fungible tokens burned). - */ - generateWcTransactionObject(options?: WcTransactionOptions): WcTransactionObject { - const encodedTransaction = this.build(); - const transaction = decodeTransactionUnsafe(hexToBin(encodedTransaction)); - - const libauthSourceOutputs = generateLibauthSourceOutputs(this.inputs); - const sourceOutputs: WcSourceOutput[] = libauthSourceOutputs.map((sourceOutput, index) => { - return { - ...sourceOutput, - ...transaction.inputs[index], - ...getWcContractInfo(this.inputs[index]), - }; - }); - return { ...options, transaction, sourceOutputs }; - } - - private checkFee(transaction: LibauthTransaction): void { - const totalInputAmount = this.inputs.reduce((total, input) => total + input.satoshis, 0n); - const totalOutputAmount = this.outputs.reduce((total, output) => total + output.amount, 0n); - const transactionSize = this.getEncodedTransactionSize(transaction); - - const fee = totalInputAmount - totalOutputAmount; - const feePerByte = Number(fee) / transactionSize; - - if (this.options.maximumFeeSatoshis && fee > this.options.maximumFeeSatoshis) { - throw new TransactionFeeTooHighError(fee, this.options.maximumFeeSatoshis); - } - - // The limits are checked against the exact fee per byte, which is only rounded (away from the limit) for display - if (this.options.maximumFeeSatsPerByte && feePerByte > this.options.maximumFeeSatsPerByte) { - throw new TransactionFeePerByteTooHighError(Math.ceil(feePerByte * 100) / 100, this.options.maximumFeeSatsPerByte); - } - - const STANDARD_MIN_FEE_PER_BYTE = 1.0; - if (feePerByte < STANDARD_MIN_FEE_PER_BYTE) { - throw new TransactionFeePerByteTooLowError(Math.floor(feePerByte * 100) / 100, STANDARD_MIN_FEE_PER_BYTE); - } - } - - private checkFungibleTokenBurn(): void { - if (this.options.allowImplicitFungibleTokenBurn) return; - - const tokenInputAmounts: Record = {}; - const tokenOutputAmounts: Record = {}; - - for (const input of this.inputs) { - if (input.token?.amount) { - tokenInputAmounts[input.token.category] = (tokenInputAmounts[input.token.category] || 0n) + input.token.amount; - } - } - for (const output of this.outputs) { - if (output.token?.amount) { - tokenOutputAmounts[output.token.category] = (tokenOutputAmounts[output.token.category] || 0n) + output.token.amount; - } - } - - for (const [category, inputAmount] of Object.entries(tokenInputAmounts)) { - const outputAmount = tokenOutputAmounts[category] || 0n; - if (outputAmount < inputAmount) { - throw new Error(`Implicit burning of fungible tokens for category ${category} is not allowed (input amount: ${inputAmount}, output amount: ${outputAmount}). If this is intended, set allowImplicitFungibleTokenBurn to true.`); - } - } - } - - private checkInputsAndOutputs(): void { - if (this.inputs.length === 0) { - throw new TransactionInputsRequiredError(); - } - - if (this.outputs.length === 0) { - throw new TransactionOutputsRequiredError(); - } - } - - private checkUnlockingBytecodeSize(script: Uint8Array): void { - const MAX_UNLOCKING_BYTECODE_SIZE = 10_000; - if (script.byteLength > MAX_UNLOCKING_BYTECODE_SIZE) { - throw new UnlockingBytecodeTooLargeError(script.byteLength, MAX_UNLOCKING_BYTECODE_SIZE); - } - } - - private checkTransactionSize(transaction: LibauthTransaction): void { - const transactionSize = this.getEncodedTransactionSize(transaction); - - const TX_MAX_STANDARD_SIZE = 100_000; - if (transactionSize > TX_MAX_STANDARD_SIZE) { - throw new TransactionTooLargeError(transactionSize, TX_MAX_STANDARD_SIZE); - } - } -} +import { + binToHex, + decodeTransaction, + decodeTransactionUnsafe, + encodeTransaction, + hexToBin, + Transaction as LibauthTransaction, + WalletTemplate, +} from '@bitauth/libauth'; +import { + Unlocker, + Output, + TransactionDetails, + UnlockableUtxo, + SpendableUtxo, + InputOptions, + isUnlockableUtxo, + isStandardUnlockableUtxo, + StandardUnlockableUtxo, + VmResourceUsage, + isContractUnlocker, + isPlaceholderUnlocker, + BchChangeOutputOptions, + TokenChangeOutputOptions, +} from './interfaces.js'; +import { PLACEHOLDER_P2PKH_UNLOCKING_SIZE } from './constants.js'; +import { NetworkProvider } from './network/index.js'; +import { + calculateDust, + cashScriptOutputToLibauthOutput, + createOpReturnOutput, + delay, + generateLibauthSourceOutputs, + getOutputSize, + validateInput, + validateOutput, + validateUnlocker, +} from './utils.js'; +import { + FailedTransactionError, + TransactionFeeTooHighError, + TransactionFeePerByteTooHighError, + TransactionFeePerByteTooLowError, + TransactionInputsRequiredError, + TransactionOutputsRequiredError, + UnlockingBytecodeTooLargeError, + TransactionTooLargeError, +} from './Errors.js'; +import { DebugResults } from './debugging.js'; +import { debugLibauthTemplate, getLibauthTemplate, getBitauthUri } from './libauth-template/LibauthTemplate.js'; +import { getWcContractInfo, WcSourceOutput, WcTransactionOptions } from './walletconnect-utils.js'; +import semver from 'semver'; +import { WcTransactionObject } from './walletconnect-utils.js'; + +/** + * Options accepted by the `TransactionBuilder` constructor. + */ +export interface TransactionBuilderOptions { + /** Network provider used to broadcast the transaction and fetch details after sending. */ + provider: NetworkProvider; + /** Optional absolute cap on the transaction fee. Build/send throws if the fee exceeds this value. */ + maximumFeeSatoshis?: bigint; + /** Optional cap on the transaction fee rate in sats/byte. Build/send throws if exceeded. */ + maximumFeeSatsPerByte?: number; + /** Allow fungible token inputs to exceed token outputs (implicit burn). Defaults to `false`. */ + allowImplicitFungibleTokenBurn?: boolean; +} + +const DEFAULT_SEQUENCE = 0xfffffffe; + +/** + * Fluent builder for constructing, debugging, and broadcasting CashScript transactions. + * + * Inputs are added via `addInput` / `addInputs` with an `Unlocker` produced by a `Contract` or + * `SignatureTemplate`, outputs are added via `addOutput` / `addOutputs`, and the resulting + * transaction can be built (`build`), debugged (`debug`), or broadcast (`send`). + */ +export class TransactionBuilder { + public provider: NetworkProvider; + public inputs: UnlockableUtxo[] = []; + public outputs: Output[] = []; + + public locktime: number = 0; + public options: TransactionBuilderOptions; + + private changeLocks: Record = {}; + + /** + * Create a new TransactionBuilder. + * + * @param options - Builder options, including the network provider and optional fee/burn limits. + */ + constructor(options: TransactionBuilderOptions) { + this.provider = options.provider; + this.options = { + allowImplicitFungibleTokenBurn: options.allowImplicitFungibleTokenBurn ?? false, + ...options, + }; + } + + /** + * Add a single UTXO as an input to the transaction. + * + * @param utxo - The UTXO to spend. + * @param unlocker - The unlocker to generate the unlocking bytecode for this input. Typically + * obtained from `contract.unlock.(...args)` or `signatureTemplate.unlockP2PKH()`. + * @param options - Optional per-input options such as a custom sequence number. + * @returns This builder for chaining. + * @throws If the UTXO is invalid. + */ + addInput(utxo: SpendableUtxo, unlocker: Unlocker, options?: InputOptions): this { + return this.addInputs([utxo], unlocker, options); + } + + /** + * Add multiple UTXOs to the transaction that all share the same unlocker. + * + * @param utxos - The UTXOs to spend. + * @param unlocker - The shared unlocker used to unlock all provided UTXOs. + * @param options - Optional per-input options applied to every added input. + * @returns This builder for chaining. + * @throws If any UTXO is invalid. + */ + addInputs(utxos: SpendableUtxo[], unlocker: Unlocker, options?: InputOptions): this; + + /** + * Add multiple UTXOs that each carry their own unlocker. + * + * @param utxos - UTXOs that have already been paired with their individual unlockers. + * @returns This builder for chaining. + * @throws If any UTXO is missing its unlocker. + */ + addInputs(utxos: UnlockableUtxo[]): this; + + addInputs(utxos: SpendableUtxo[] | UnlockableUtxo[], unlocker?: Unlocker, options?: InputOptions): this { + utxos.forEach((utxo) => validateInput(utxo, this.changeLocks)); + if ( + (!unlocker && utxos.some((utxo) => !isUnlockableUtxo(utxo))) || + (unlocker && utxos.some((utxo) => isUnlockableUtxo(utxo))) + ) { + throw new Error( + 'Either all UTXOs must have an individual unlocker specified, or no UTXOs must have an individual unlocker specified and a shared unlocker must be provided', + ); + } + + utxos.forEach((utxo, i) => + validateUnlocker(utxo, unlocker ?? (utxo as UnlockableUtxo).unlocker, this.inputs.length + i, this.provider.network), + ); + + if (!unlocker) { + this.inputs = this.inputs.concat(utxos as UnlockableUtxo[]); + return this; + } + + this.inputs = this.inputs.concat(utxos.map((utxo) => ({ ...utxo, unlocker, options }))); + return this; + } + + /** + * Add a single output to the transaction. + * + * @param output - The output to add. Its address, amount and optional token are validated + * against the provider's network. + * @returns This builder for chaining. + * @throws If the output is invalid. + */ + addOutput(output: Output): this { + return this.addOutputs([output]); + } + + /** + * Add multiple outputs to the transaction. + * + * @param outputs - The outputs to add. Each output is validated against the provider's network. + * @returns This builder for chaining. + * @throws If any output is invalid. + */ + addOutputs(outputs: Output[]): this { + outputs.forEach((output) => validateOutput(output, this.provider.network, this.changeLocks)); + this.outputs = this.outputs.concat(outputs); + return this; + } + + // TODO: allow uint8array for chunks + /** + * Append an `OP_RETURN` output containing the provided data chunks. Hex strings prefixed with + * `0x` are decoded as bytes; other strings are encoded as UTF-8. + * + * @param chunks - The data chunks to include after the `OP_RETURN` opcode. + * @returns This builder for chaining. + */ + addOpReturnOutput(chunks: string[]): this { + this.addOutput(createOpReturnOutput(chunks)); + return this; + } + + /** + * Add a BCH change output for the remaining value after fees, if it exceeds the dust limit. The + * fee is computed from the transaction size at the configured fee rate; dust-sized change is + * simply absorbed into the fee. + * + * Should be called *after* all explicit inputs and outputs are added. + * + * @param changeOutputOptions - The destination address and the fee rate (in sats/byte) to use. + * @returns This builder for chaining. + * @throws If the available surplus is insufficient to cover the fee for the configured rate or + * if a BCH change output was already added. + */ + addBchChangeOutputIfNeeded(changeOutputOptions: BchChangeOutputOptions): this { + const totalBchInputAmount = this.inputs.reduce((total, input) => total + input.satoshis, 0n); + const totalBchOutputAmount = this.outputs.reduce((total, output) => total + output.amount, 0n); + + const tentativeSurplus = totalBchInputAmount - totalBchOutputAmount; + const tentativeTransactionSize = this.getTransactionSize(); + const tentativeFee = BigInt(Math.ceil(changeOutputOptions.feeRate * Number(tentativeTransactionSize))); + const tentativeChangeAmount = tentativeSurplus - tentativeFee; + + if (tentativeChangeAmount < 0n) { + throw new Error( + `Transaction does not have enough funds to cover the transaction fee rate of ${changeOutputOptions.feeRate} even without adding a change output. Current surplus: ${tentativeSurplus}, current fee: ${tentativeFee}, current change amount: ${tentativeChangeAmount}`, + ); + } + + const changeOutputSize = getOutputSize({ + to: changeOutputOptions.to, + amount: tentativeSurplus, + }); + + const transactionSize = tentativeTransactionSize + BigInt(changeOutputSize); + const calculatedFee = BigInt(Math.ceil(changeOutputOptions.feeRate * Number(transactionSize))); + + const changeAmount = tentativeSurplus - calculatedFee; + const changeOutput = { to: changeOutputOptions.to, amount: changeAmount }; + + const changeOutputDust = calculateDust(changeOutput); + if (changeAmount < changeOutputDust) { + this.changeLocks.BCH = true; + return this; + } + + this.addOutput(changeOutput); + this.changeLocks.BCH = true; + return this; + } + + /** + * Add a fungible token change output for the configured category if the transaction's inputs + * contain more tokens of that category than its outputs. The change output is sent to the + * provided token address and carries the dust-minimum BCH amount. + * + * Should be called *after* all explicit token outputs for the category are added and *before* + * `addBchChangeOutputIfNeeded`. + * + * @param changeOutputOptions - The token category to handle and the destination token address. + * @returns This builder for chaining. + * @throws If the destination is not a token-supporting address, or if a corresponding change output + * or BCH change output was already added. + */ + addTokenChangeOutputIfNeeded(changeOutputOptions: TokenChangeOutputOptions): this { + const { category, to } = changeOutputOptions; + + const inputAmount = this.inputs + .filter((input) => input.token?.category === category) + .reduce((total, input) => total + input.token!.amount, 0n); + + const outputAmount = this.outputs + .filter((output) => output.token?.category === category) + .reduce((total, output) => total + output.token!.amount, 0n); + + const changeAmount = inputAmount - outputAmount; + if (changeAmount <= 0n) { + this.changeLocks[category] = true; + return this; + } + + const changeOutput: Output = { + to, + amount: 0n, + token: { amount: changeAmount, category }, + }; + changeOutput.amount = BigInt(calculateDust(changeOutput)); + + this.addOutput(changeOutput); + this.changeLocks[category] = true; + return this; + } + + /** + * Build the transaction (skipping fee and burn checks) and return its encoded byte length. + * Inputs with a placeholder unlocker are counted at the size they take up once the wallet signs them. + * + * @returns The size of the transaction in bytes. + */ + getTransactionSize(): bigint { + const transaction = this.buildLibauthTransaction(true); + return BigInt(this.getEncodedTransactionSize(transaction)); + } + + // Placeholder unlockers serialise as an empty unlocking script, so their eventual signed size is added here + private getEncodedTransactionSize(transaction: LibauthTransaction): number { + const placeholderInputCount = this.inputs.filter((input) => isPlaceholderUnlocker(input.unlocker)).length; + return encodeTransaction(transaction).byteLength + placeholderInputCount * PLACEHOLDER_P2PKH_UNLOCKING_SIZE; + } + + /** + * Calculate the transaction fee in satoshis and the fee per byte. + * + * @returns The transaction fee in satoshis and the fee per byte. + */ + calculateTransactionFee(): { feeSats: bigint; feeSatsPerByte: number } { + const transactionSize = this.getTransactionSize(); + const totalInputAmount = this.inputs.reduce((total, input) => total + input.satoshis, 0n); + const totalOutputAmount = this.outputs.reduce((total, output) => total + output.amount, 0n); + const feeSats = totalInputAmount - totalOutputAmount; + const feeSatsPerByte = Number((Number(feeSats) / Number(transactionSize)).toFixed(2)); + return { feeSats, feeSatsPerByte }; + } + + /** + * Set the `nLockTime` of the transaction. + * + * @param locktime - The absolute locktime to use (block height or UNIX timestamp). + * @returns This builder for chaining. + * @throws If the locktime is not an unsigned 32-bit integer. + */ + setLocktime(locktime: number): this { + if (!Number.isInteger(locktime) || locktime < 0 || locktime > 0xffffffff) { + throw new Error(`Locktime ${locktime} should be an integer between 0 and 4294967295`); + } + + this.locktime = locktime; + return this; + } + + /** + * Build the transaction, applying fee and implicit-burn checks, and return the hex-encoded + * transaction bytes. + * + * @returns The signed transaction as a hex string. + * @throws If the transaction fee exceeds the configured maximum, or if fungible tokens are + * implicitly burned without `allowImplicitFungibleTokenBurn` enabled. + */ + build(): string { + const transaction = this.buildLibauthTransaction(); + return binToHex(encodeTransaction(transaction)); + } + + private buildLibauthTransaction(skipChecks: boolean = false): LibauthTransaction { + if (!skipChecks) { + this.checkFungibleTokenBurn(); + this.checkInputsAndOutputs(); + } + + const inputs: LibauthTransaction['inputs'] = this.inputs.map((utxo) => ({ + outpointIndex: utxo.vout, + outpointTransactionHash: hexToBin(utxo.txid), + sequenceNumber: utxo.options?.sequence ?? DEFAULT_SEQUENCE, + unlockingBytecode: new Uint8Array(), + })); + + const outputs = this.outputs.map(cashScriptOutputToLibauthOutput); + + const transaction = { + inputs, + locktime: this.locktime, + outputs, + version: 2, + }; + + // Generate source outputs from inputs (for signing with SIGHASH_UTXOS) + const sourceOutputs = generateLibauthSourceOutputs(this.inputs); + + const inputScripts = this.inputs.map((input, inputIndex) => + input.unlocker.generateUnlockingBytecode({ transaction, sourceOutputs, inputIndex }), + ); + + inputScripts.forEach((script, i) => { + if (!skipChecks) this.checkUnlockingBytecodeSize(script); + transaction.inputs[i].unlockingBytecode = script; + }); + + if (!skipChecks) { + this.checkFee(transaction); + this.checkTransactionSize(transaction); + } + + return transaction; + } + + /** + * Locally evaluate the transaction against the Bitcoin Cash VM using debug information from the + * contract artifacts. Throws a descriptive error if any input fails evaluation. + * + * @returns The full debug execution trace for every scenario in the generated libauth template. + * @throws If the transaction contains inputs with custom (non-standard) unlockers, or if the + * evaluation fails (e.g. a failing `require` statement). + */ + debug(): DebugResults { + if (this.inputs.some((input) => !isStandardUnlockableUtxo(input))) { + throw new Error('Cannot debug a transaction with custom unlocker'); + } + + // We can typecast this because we check that all inputs are standard unlockable in the check above + const contractVersions = (this.inputs as StandardUnlockableUtxo[]) + .map((input) => ('contract' in input.unlocker ? input.unlocker.contract.artifact.compiler.version : null)) + .filter((version) => version !== null); + + if (!contractVersions.every((version) => semver.satisfies(version, '>=0.11.0', { includePrerelease: true }))) { + console.warn('For the best debugging experience, please recompile your contract with cashc version 0.11.0 or newer.'); + } + + return debugLibauthTemplate(this.getLibauthTemplate(), this); + } + + /** + * Compute VM resource usage (ops, op cost budget, sigchecks, hash iterations) for each input + * by running the transaction through `debug`. + * + * @param verbose - When `true`, also prints a formatted table of the results via `console.table`. + * @returns One entry per input with its VM resource usage metrics. + * @throws If the transaction contains inputs with custom (non-standard) unlockers, or if the + * evaluation fails. + */ + getVmResourceUsage(verbose: boolean = false): Array { + // Note that only StandardUnlockableUtxo inputs are supported for debugging, so any transaction with custom unlockers + // cannot be debugged (and therefore cannot return VM resource usage) + const results = this.debug(); + const vmResourceUsage: Array = []; + const tableData: Array> = []; + + const formatMetric = (value: number, total: number, withPercentage: boolean = false): string => + `${formatNumber(value)} / ${formatNumber(total)}${withPercentage ? ` (${((value / total) * 100).toFixed(0)}%)` : ''}`; + const formatNumber = (value: number): string => value.toLocaleString('en'); + + const resultEntries = Object.entries(results); + for (const [index, input] of this.inputs.entries()) { + const [, result] = resultEntries.find(([entryKey]) => entryKey.includes(`input${index}`)) ?? []; + const metrics = result?.at(-1)?.metrics; + + // Should not happen + if (!metrics) throw new Error('VM resource could not be calculated'); + + vmResourceUsage.push(metrics); + tableData.push({ + 'Contract - Function': isContractUnlocker(input.unlocker) + ? `${input.unlocker.contract.name} - ${input.unlocker.abiFunction.name}` + : 'P2PKH Input', + Ops: metrics.evaluatedInstructionCount, + 'Op Cost Budget Usage': formatMetric(metrics.operationCost, metrics.maximumOperationCost, true), + SigChecks: formatMetric(metrics.signatureCheckCount, metrics.maximumSignatureCheckCount), + Hashes: formatMetric(metrics.hashDigestIterations, metrics.maximumHashDigestIterations), + }); + } + + if (verbose) { + console.log('VM Resource usage by inputs:'); + console.table(tableData); + } + + return vmResourceUsage; + } + + /** + * Build a Bitauth IDE URI that loads the transaction (and all private keys required to sign it) + * in the online Bitauth IDE debugger. + * + * WARNING: The URI embeds every private key used in the transaction. Do not share this URI if + * the transaction is signed with real private keys. + * + * @returns A Bitauth IDE URL for debugging this transaction. + * @throws If the transaction cannot be built (fee exceeds limit or fungible tokens burned). + */ + getBitauthUri(): string { + console.warn( + 'WARNING: it is unsafe to use this Bitauth URI when using real private keys as they are included in the transaction template', + ); + return getBitauthUri(this.getLibauthTemplate()); + } + + /** + * Build the transaction and return the corresponding libauth `WalletTemplate`. Useful for + * exporting the transaction to external libauth-compatible tooling. + * + * @returns A libauth `WalletTemplate` describing this transaction. + * @throws If the transaction cannot be built (fee exceeds limit or fungible tokens burned). + */ + getLibauthTemplate(): WalletTemplate { + const libauthTransaction = this.buildLibauthTransaction(); + return getLibauthTemplate(this, libauthTransaction); + } + + /** + * Build and broadcast the transaction via the configured network provider. Before broadcasting, + * the transaction is evaluated locally (when all inputs use standard unlockers) so that failing + * require statements or VM errors surface with descriptive messages. + * + * @returns The decoded transaction details (including txid and raw hex). + * @throws A `FailedTransactionError` if the network rejects the transaction, or any of the + * build / local evaluation errors (e.g. fee cap, implicit burn, failing require statement). + */ + async send(): Promise; + + /** + * Build and broadcast the transaction, returning only the raw transaction hex string as retrieved + * from the network after broadcast. + * + * @param raw - Pass `true` to receive the raw transaction hex instead of decoded details. + * @returns The raw transaction hex as retrieved from the network after broadcast. + * @throws A `FailedTransactionError` if the network rejects the transaction, or any of the + * build / local evaluation errors (e.g. fee cap, implicit burn, failing require statement). + */ + async send(raw: true): Promise; + async send(raw?: true): Promise { + const tx = this.build(); + + // If all inputs are standard unlockable, we can debug the transaction locally + // before sending so any errors are caught early + if (this.inputs.every((input) => isStandardUnlockableUtxo(input))) { + this.debug(); + } + + let txid: string; + try { + txid = await this.provider.sendRawTransaction(tx); + } catch (e: any) { + const reason = e.error ?? e.message; + + const getBitauthUriWithFallback = (): string => { + try { + return getBitauthUri(this.getLibauthTemplate()); + } catch { + return 'Bitauth URI generation failed'; + } + }; + + throw new FailedTransactionError(reason, getBitauthUriWithFallback()); + } + + // The transaction was broadcast successfully, so failing to retrieve it afterwards is not a failed transaction + return raw ? this.getTxDetails(txid, raw) : this.getTxDetails(txid); + } + + private async getTxDetails(txid: string): Promise; + private async getTxDetails(txid: string, raw: true): Promise; + private async getTxDetails(txid: string, raw?: true): Promise { + for (let retries = 0; retries < 1200; retries += 1) { + await delay(500); + try { + const hex = await this.provider.getRawTransaction(txid); + + if (raw) return hex; + + const libauthTransaction = decodeTransaction(hexToBin(hex)) as LibauthTransaction; + return { ...libauthTransaction, txid, hex }; + } catch (ignored) { + // ignored + } + } + + throw new Error(`Transaction ${txid} was broadcast, but its details could not be retrieved for over 10 minutes`); + } + + /** + * Build the transaction and format it as a BCH WalletConnect transaction object suitable for + * signing and broadcasting via a BCH WalletConnect-compatible Bitcoin Cash wallet. + * + * See the [BCH WalletConnect spec](https://github.com/mainnet-pat/wc2-bch-bcr) for the object format. + * + * @param options - Optional WalletConnect options such as `broadcast` and `userPrompt`. + * @returns A WalletConnect transaction object ready to be sent to a WalletConnect wallet. + * @throws If the transaction cannot be built (fee exceeds limit or fungible tokens burned). + */ + generateWcTransactionObject(options?: WcTransactionOptions): WcTransactionObject { + const encodedTransaction = this.build(); + const transaction = decodeTransactionUnsafe(hexToBin(encodedTransaction)); + + const libauthSourceOutputs = generateLibauthSourceOutputs(this.inputs); + const sourceOutputs: WcSourceOutput[] = libauthSourceOutputs.map((sourceOutput, index) => { + return { + ...sourceOutput, + ...transaction.inputs[index], + ...getWcContractInfo(this.inputs[index]), + }; + }); + return { ...options, transaction, sourceOutputs }; + } + + private checkFee(transaction: LibauthTransaction): void { + const totalInputAmount = this.inputs.reduce((total, input) => total + input.satoshis, 0n); + const totalOutputAmount = this.outputs.reduce((total, output) => total + output.amount, 0n); + const transactionSize = this.getEncodedTransactionSize(transaction); + + const fee = totalInputAmount - totalOutputAmount; + const feePerByte = Number(fee) / transactionSize; + + if (this.options.maximumFeeSatoshis && fee > this.options.maximumFeeSatoshis) { + throw new TransactionFeeTooHighError(fee, this.options.maximumFeeSatoshis); + } + + // The limits are checked against the exact fee per byte, which is only rounded (away from the limit) for display + if (this.options.maximumFeeSatsPerByte && feePerByte > this.options.maximumFeeSatsPerByte) { + throw new TransactionFeePerByteTooHighError(Math.ceil(feePerByte * 100) / 100, this.options.maximumFeeSatsPerByte); + } + + const STANDARD_MIN_FEE_PER_BYTE = 1.0; + if (feePerByte < STANDARD_MIN_FEE_PER_BYTE) { + throw new TransactionFeePerByteTooLowError(Math.floor(feePerByte * 100) / 100, STANDARD_MIN_FEE_PER_BYTE); + } + } + + private checkFungibleTokenBurn(): void { + if (this.options.allowImplicitFungibleTokenBurn) return; + + const tokenInputAmounts: Record = {}; + const tokenOutputAmounts: Record = {}; + + for (const input of this.inputs) { + if (input.token?.amount) { + tokenInputAmounts[input.token.category] = (tokenInputAmounts[input.token.category] || 0n) + input.token.amount; + } + } + for (const output of this.outputs) { + if (output.token?.amount) { + tokenOutputAmounts[output.token.category] = (tokenOutputAmounts[output.token.category] || 0n) + output.token.amount; + } + } + + for (const [category, inputAmount] of Object.entries(tokenInputAmounts)) { + const outputAmount = tokenOutputAmounts[category] || 0n; + if (outputAmount < inputAmount) { + throw new Error( + `Implicit burning of fungible tokens for category ${category} is not allowed (input amount: ${inputAmount}, output amount: ${outputAmount}). If this is intended, set allowImplicitFungibleTokenBurn to true.`, + ); + } + } + } + + private checkInputsAndOutputs(): void { + if (this.inputs.length === 0) { + throw new TransactionInputsRequiredError(); + } + + if (this.outputs.length === 0) { + throw new TransactionOutputsRequiredError(); + } + } + + private checkUnlockingBytecodeSize(script: Uint8Array): void { + const MAX_UNLOCKING_BYTECODE_SIZE = 10_000; + if (script.byteLength > MAX_UNLOCKING_BYTECODE_SIZE) { + throw new UnlockingBytecodeTooLargeError(script.byteLength, MAX_UNLOCKING_BYTECODE_SIZE); + } + } + + private checkTransactionSize(transaction: LibauthTransaction): void { + const transactionSize = this.getEncodedTransactionSize(transaction); + + const TX_MAX_STANDARD_SIZE = 100_000; + if (transactionSize > TX_MAX_STANDARD_SIZE) { + throw new TransactionTooLargeError(transactionSize, TX_MAX_STANDARD_SIZE); + } + } +} diff --git a/packages/cashscript/src/debug-frame.ts b/packages/cashscript/src/debug-frame.ts index f41edc2f3..55cfb6f30 100644 --- a/packages/cashscript/src/debug-frame.ts +++ b/packages/cashscript/src/debug-frame.ts @@ -51,10 +51,8 @@ export const rootFrame = (artifact: Artifact): ResolvedFrame => ({ export const getActiveBytecode = (instructions: AuthenticationInstruction[]): string => binToHex(encodeAuthenticationInstructions(instructions)); -export const resolveFrame = ( - artifact: Artifact, - step: AuthenticationProgramStateCommon, -): ResolvedFrame => resolveFrameByBytecode(artifact, getActiveBytecode(step.instructions)); +export const resolveFrame = (artifact: Artifact, step: AuthenticationProgramStateCommon): ResolvedFrame => + resolveFrameByBytecode(artifact, getActiveBytecode(step.instructions)); // Only defined frames (id present) execute as standalone VM programs; an inlined callable's // frame documents a body that only ever runs spliced into another program @@ -99,8 +97,9 @@ const resolveInlineAttributionStack = ( entry: DebugEntry, kind: 'requires' | 'logs', ): InlineAttribution[] => { - const range = parseAndResolveInlineRanges(containerFrame.inlineRanges, artifact.debug?.functions) - .find((candidate) => entry.ip >= candidate.startIp && entry.ip <= candidate.endIp); + const range = parseAndResolveInlineRanges(containerFrame.inlineRanges, artifact.debug?.functions).find( + (candidate) => entry.ip >= candidate.startIp && entry.ip <= candidate.endIp, + ); if (!range) return []; const frameEntry = findMatchingFrameEntry(containerFrame[kind], range.frame[kind], range, entry); @@ -109,10 +108,7 @@ const resolveInlineAttributionStack = ( const frame = resolveDebugFrame(artifact, range.frame); // The callable may itself contain deeper inlined callables - return [ - ...resolveInlineAttributionStack(artifact, frame, frameEntry, kind), - { frame, entry: frameEntry }, - ]; + return [...resolveInlineAttributionStack(artifact, frame, frameEntry, kind), { frame, entry: frameEntry }]; }; // A log merged from an inlined callable is attributed to the callable's own source @@ -120,7 +116,7 @@ export const attributeLogEntry = ( artifact: Artifact, frame: ResolvedFrame, logEntry: LogEntry, -): { logEntry: LogEntry, sourceName: string } => { +): { logEntry: LogEntry; sourceName: string } => { const inline = resolveInlineAttribution(artifact, frame, logEntry, 'logs'); if (!inline) return { logEntry, sourceName: frame.sourceName }; @@ -133,12 +129,12 @@ export const attributeLogEntry = ( const findMatchingFrameEntry = ( containerEntries: readonly DebugEntry[], frameEntries: readonly DebugEntry[], - range: { startIp: number, endIp: number }, + range: { startIp: number; endIp: number }, entry: DebugEntry, ): DebugEntry | undefined => { - const entriesInRange = containerEntries.filter((candidate) => ( - candidate.ip >= range.startIp && candidate.ip <= range.endIp - )); + const entriesInRange = containerEntries.filter( + (candidate) => candidate.ip >= range.startIp && candidate.ip <= range.endIp, + ); const position = entriesInRange.indexOf(entry); if (position === -1) return undefined; @@ -154,8 +150,9 @@ export const buildCallStack = ( ): CallStackEntry[] => { // These entries represent any called inlined functions at the top of the call stack. These are handled separately, // because the failing debug step refers to the frameEntry below, so we manually need to handle "deeper" calls - const inlineEntries = resolveInlineAttributionStack(artifact, failingFrame, requireStatement, 'requires') - .map(({ frame, entry }) => toCallStackEntry(frame, entry.ip)); + const inlineEntries = resolveInlineAttributionStack(artifact, failingFrame, requireStatement, 'requires').map( + ({ frame, entry }) => toCallStackEntry(frame, entry.ip), + ); // This entry is the actual VM-level failing function const frameEntry = toCallStackEntry(failingFrame, failingInstructionPointer); @@ -180,10 +177,7 @@ const expandRuntimeCaller = ( frame: ResolvedFrame, script: Script, invokeIp: number, -): CallStackEntry[] => [ - ...resolveInlinedCallerHops(artifact, frame, script, invokeIp), - toCallStackEntry(frame, invokeIp), -]; +): CallStackEntry[] => [...resolveInlinedCallerHops(artifact, frame, script, invokeIp), toCallStackEntry(frame, invokeIp)]; // Every defined function already gets expanded in buildCallStack, so this function exists to make sure any inlined // callers also get added to the call stack @@ -193,8 +187,9 @@ const resolveInlinedCallerHops = ( script: Script, invokeIp: number, ): CallStackEntry[] => { - const inlineRange = parseAndResolveInlineRanges(frame.inlineRanges, artifact.debug?.functions) - .find((candidate) => invokeIp >= candidate.startIp && invokeIp <= candidate.endIp); + const inlineRange = parseAndResolveInlineRanges(frame.inlineRanges, artifact.debug?.functions).find( + (candidate) => invokeIp >= candidate.startIp && invokeIp <= candidate.endIp, + ); if (!inlineRange) return []; const frameScript = bytecodeToScript(hexToBin(inlineRange.frame.bytecode)); @@ -224,7 +219,10 @@ const isAuthenticationProgramStackFrame = ( const toCallStackEntry = (frame: ResolvedFrame, instructionPointer: number): CallStackEntry => { const { lineNumber, statement } = getLocationDataForFrame(frame, instructionPointer); - const flattenedStatement = statement.split('\n').map((line) => line.trim()).join(' '); + const flattenedStatement = statement + .split('\n') + .map((line) => line.trim()) + .join(' '); return { functionName: frame.functionName, @@ -240,7 +238,7 @@ export const getRequireLocationDataForFrame = ( frame: ResolvedFrame, instructionPointer: number, requireLine: number, -): { lineNumber: number, statement: string } => { +): { lineNumber: number; statement: string } => { const locationData = getLocationDataForFrame(frame, instructionPointer); const statementEndLine = locationData.lineNumber + locationData.statement.split('\n').length - 1; if (statementEndLine >= requireLine) return locationData; @@ -252,7 +250,7 @@ export const getRequireLocationDataForFrame = ( export const getLocationDataForFrame = ( frame: ResolvedFrame, instructionPointer: number, -): { lineNumber: number, statement: string } => { +): { lineNumber: number; statement: string } => { const locationData = sourceMapToLocationData(frame.sourceMap); // We subtract the frame's ip offset (the constructor-arg prefix for the root frame, 0 for helper diff --git a/packages/cashscript/src/debugging.ts b/packages/cashscript/src/debugging.ts index 31a90b392..be85495ad 100644 --- a/packages/cashscript/src/debugging.ts +++ b/packages/cashscript/src/debugging.ts @@ -1,5 +1,30 @@ -import { AuthenticationErrorBch2025Additions, AuthenticationErrorCommon, AuthenticationInstruction, AuthenticationProgramCommon, AuthenticationProgramStateCommon, WalletTemplate, WalletTemplateScriptUnlocking, binToHex, createCompiler, decodeAuthenticationInstructions, encodeAuthenticationInstruction, walletTemplateToCompilerConfiguration } from '@bitauth/libauth'; -import { Artifact, LogData, LogEntry, Op, PrimitiveType, StackItem, asmToBytecode, bytecodeToAsm, decodeBool, decodeInt, decodeString } from '@cashscript/utils'; +import { + AuthenticationErrorBch2025Additions, + AuthenticationErrorCommon, + AuthenticationInstruction, + AuthenticationProgramCommon, + AuthenticationProgramStateCommon, + WalletTemplate, + WalletTemplateScriptUnlocking, + binToHex, + createCompiler, + decodeAuthenticationInstructions, + encodeAuthenticationInstruction, + walletTemplateToCompilerConfiguration, +} from '@bitauth/libauth'; +import { + Artifact, + LogData, + LogEntry, + Op, + PrimitiveType, + StackItem, + asmToBytecode, + bytecodeToAsm, + decodeBool, + decodeInt, + decodeString, +} from '@cashscript/utils'; import { findLastIndex, toRegExp } from './utils.js'; import { FailedRequireError, FailedTransactionError, FailedTransactionEvaluationError } from './Errors.js'; import { attributeLogEntry, buildCallStack, getActiveBytecode, resolveFrame } from './debug-frame.js'; @@ -13,14 +38,14 @@ export type DebugResults = Record; // debugs the template, optionally logging the execution data export const debugTemplate = (template: WalletTemplate, artifacts: Artifact[]): DebugResults => { // If a contract has the same name, but a different bytecode, then it is considered a name collision - const hasArtifactNameCollision = artifacts.some( - (artifact) => ( - artifacts.some((other) => other.contractName === artifact.contractName && other.bytecode !== artifact.bytecode) - ), + const hasArtifactNameCollision = artifacts.some((artifact) => + artifacts.some((other) => other.contractName === artifact.contractName && other.bytecode !== artifact.bytecode), ); if (hasArtifactNameCollision) { - throw new Error('There are multiple artifacts with the same contractName. Please make sure that all artifacts have unique names.'); + throw new Error( + 'There are multiple artifacts with the same contractName. Please make sure that all artifacts have unique names.', + ); } const results: DebugResults = {}; @@ -32,7 +57,12 @@ export const debugTemplate = (template: WalletTemplate, artifacts: Artifact[]): const matchingArtifact = artifacts.find((artifact) => unlockingScriptId.startsWith(artifact.contractName)); for (const scenarioId of scenarioIds) { - results[`${unlockingScriptId}.${scenarioId}`] = debugSingleScenario(template, matchingArtifact, unlockingScriptId, scenarioId); + results[`${unlockingScriptId}.${scenarioId}`] = debugSingleScenario( + template, + matchingArtifact, + unlockingScriptId, + scenarioId, + ); } } @@ -42,7 +72,10 @@ export const debugTemplate = (template: WalletTemplate, artifacts: Artifact[]): }; const debugSingleScenario = ( - template: WalletTemplate, artifact: Artifact | undefined, unlockingScriptId: string, scenarioId: string, + template: WalletTemplate, + artifact: Artifact | undefined, + unlockingScriptId: string, + scenarioId: string, ): DebugResult => { const { vm, program } = createProgram(template, unlockingScriptId, scenarioId); @@ -61,8 +94,9 @@ const debugSingleScenario = ( // we only need to check that there are no 'false' items in the control stack. // https://libauth.org/types/AuthenticationProgramStateControlStack.html // https://github.com/bitjson/bch-loops#control-stack - const executedDebugSteps = lockingScriptDebugResult - .filter((debugStep) => debugStep.controlStack.every(item => item !== false)); + const executedDebugSteps = lockingScriptDebugResult.filter((debugStep) => + debugStep.controlStack.every((item) => item !== false), + ); // P2PKH inputs do not have an artifact, so we skip the console.log handling if (artifact) { @@ -70,22 +104,22 @@ const debugSingleScenario = ( // - inside loops, the same log statement may be executed multiple times in different debug steps // - the same ip may be executed by multiple function frames, so they are matched against the active frame's logs. // - multiple log statements may exist for the same ip, so we need to handle all of them. - const executedLogs = executedDebugSteps - .flatMap((debugStep, index) => { - const frame = resolveFrame(artifact, debugStep); - const logEntries = frame.logs.filter((log) => log.ip === debugStep.ip); - if (logEntries.length === 0) return []; + const executedLogs = executedDebugSteps.flatMap((debugStep, index) => { + const frame = resolveFrame(artifact, debugStep); + const logEntries = frame.logs.filter((log) => log.ip === debugStep.ip); + if (logEntries.length === 0) return []; - const reversedPriorDebugSteps = executedDebugSteps.slice(0, index + 1).reverse(); - const frameBytecode = getActiveBytecode(debugStep.instructions); + const reversedPriorDebugSteps = executedDebugSteps.slice(0, index + 1).reverse(); + const frameBytecode = getActiveBytecode(debugStep.instructions); - return logEntries.map((logEntry) => { - const decodedLogData = logEntry.data - .map((dataEntry) => decodeLogDataEntry(dataEntry, reversedPriorDebugSteps, vm, frameBytecode)); + return logEntries.map((logEntry) => { + const decodedLogData = logEntry.data.map((dataEntry) => + decodeLogDataEntry(dataEntry, reversedPriorDebugSteps, vm, frameBytecode), + ); - return { ...attributeLogEntry(artifact, frame, logEntry), decodedLogData }; - }); + return { ...attributeLogEntry(artifact, frame, logEntry), decodedLogData }; }); + }); for (const { logEntry, decodedLogData, sourceName } of executedLogs) { const inputIndex = extractInputIndexFromScenario(scenarioId); @@ -115,7 +149,10 @@ const debugSingleScenario = ( const isNullFail = lastExecutedDebugStep.error.includes(AuthenticationErrorCommon.nonNullSignatureFailure); const requireStatementIp = failingIp + (isNullFail && isSignatureCheckWithoutVerify(failingInstruction) ? 1 : 0); - const { program: { inputIndex }, error } = lastExecutedDebugStep; + const { + program: { inputIndex }, + error, + } = lastExecutedDebugStep; // If there is no artifact, this is a P2PKH debug error, error can occur when final CHECKSIG fails with NULLFAIL or when // public key does not match pkh in EQUALVERIFY @@ -136,14 +173,19 @@ const debugSingleScenario = ( // Note that we use failingIp here rather than requireStatementIp, see comment above throw new FailedRequireError( - artifact, failingIp, requireStatement, inputIndex, getBitauthUri(template), error, frame, callStack, + artifact, + failingIp, + requireStatement, + inputIndex, + getBitauthUri(template), + error, + frame, + callStack, ); } // Note that we use failingIp here rather than requireStatementIp, see comment above - throw new FailedTransactionEvaluationError( - artifact, failingIp, inputIndex, getBitauthUri(template), error, frame, - ); + throw new FailedTransactionEvaluationError(artifact, failingIp, inputIndex, getBitauthUri(template), error, frame); } // Evaluate the final program state to see if it evaluated successfully @@ -162,7 +204,9 @@ const debugSingleScenario = ( // console.warn('message', finalExecutedVerifyIp); // console.warn(artifact.debug?.requires); - const { program: { inputIndex } } = lastExecutedDebugStep; + const { + program: { inputIndex }, + } = lastExecutedDebugStep; // If there is no artifact, this is a P2PKH debug error, final verify can only occur when final CHECKSIG failed // Note: due to P2PKHUnlocker implementation, this cannot happen in practice @@ -175,7 +219,11 @@ const debugSingleScenario = ( if (requireStatement) { const callStack = buildCallStack( - artifact, lastExecutedDebugStep, frame, requireStatement, sourcemapInstructionPointer, + artifact, + lastExecutedDebugStep, + frame, + requireStatement, + sourcemapInstructionPointer, ); throw new FailedRequireError( @@ -191,7 +239,12 @@ const debugSingleScenario = ( } throw new FailedTransactionEvaluationError( - artifact, sourcemapInstructionPointer, inputIndex, getBitauthUri(template), evaluationResult, frame, + artifact, + sourcemapInstructionPointer, + inputIndex, + getBitauthUri(template), + evaluationResult, + frame, ); } @@ -206,7 +259,7 @@ const extractInputIndexFromScenario = (scenarioId: string): number => { }; type Program = AuthenticationProgramCommon; -type CreateProgramResult = { vm: VM, program: Program }; +type CreateProgramResult = { vm: VM; program: Program }; // internal util. instantiates the virtual machine and compiles the template into a program const createProgram = (template: WalletTemplate, unlockingScriptId: string, scenarioId: string): CreateProgramResult => { @@ -352,10 +405,7 @@ const calculateCleanupSize = (instructions: Array { +const logDebugSteps = (debugSteps: AuthenticationProgramStateCommon[], instructions: AuthenticationInstruction[]): void => { debugSteps.map((step) => { const opcode = instructions[step.ip] ? bytecodeToAsm(encodeAuthenticationInstruction(instructions[step.ip])) : 'null'; console.warn(step.ip, opcode, step.stack, step.error); diff --git a/packages/cashscript/src/index.ts b/packages/cashscript/src/index.ts index 357e6c2b9..bda2254dd 100644 --- a/packages/cashscript/src/index.ts +++ b/packages/cashscript/src/index.ts @@ -13,11 +13,7 @@ export * as utils from '@cashscript/utils'; export * from './interfaces.js'; export * from './Errors.js'; export * from './network/errors.js'; -export { - type NetworkProvider, - ElectrumNetworkProvider, - MockNetworkProvider, -} from './network/index.js'; +export { type NetworkProvider, ElectrumNetworkProvider, MockNetworkProvider } from './network/index.js'; export { randomUtxo, randomToken, randomNFT } from './utils.js'; export * from './walletconnect-utils.js'; export { gatherBchUtxos, gatherFungibleTokenUtxos, type GatherUtxosResult } from './transaction-utils.js'; diff --git a/packages/cashscript/src/interfaces.ts b/packages/cashscript/src/interfaces.ts index 793b02e23..8ab31151c 100644 --- a/packages/cashscript/src/interfaces.ts +++ b/packages/cashscript/src/interfaces.ts @@ -60,7 +60,7 @@ export interface P2PKHUnlocker extends Unlocker { export type StandardUnlocker = ContractUnlocker | P2PKHUnlocker; -export type PlaceholderP2PKHUnlocker = Unlocker & { placeholder: true, lockingBytecode: string }; +export type PlaceholderP2PKHUnlocker = Unlocker & { placeholder: true; lockingBytecode: string }; export type ContractFunctionUnlocker = (...args: FunctionArgument[]) => ContractUnlocker; @@ -174,8 +174,8 @@ export interface TransactionDetails extends Transaction { } export interface ContractOptions { - provider: NetworkProvider, - contractType?: TContractType, + provider: NetworkProvider; + contractType?: TContractType; } export type ContractType = 'p2sh20' | 'p2sh32' | 'p2s'; diff --git a/packages/cashscript/src/libauth-template/LibauthTemplate.ts b/packages/cashscript/src/libauth-template/LibauthTemplate.ts index f10e2dff8..bfad9b6f0 100644 --- a/packages/cashscript/src/libauth-template/LibauthTemplate.ts +++ b/packages/cashscript/src/libauth-template/LibauthTemplate.ts @@ -12,11 +12,7 @@ import { WalletTemplateScriptUnlocking, WalletTemplateVariable, } from '@bitauth/libauth'; -import { - AbiFunction, - AbiInput, - Artifact, -} from '@cashscript/utils'; +import { AbiFunction, AbiInput, Artifact } from '@cashscript/utils'; import { EncodedConstructorArgument, EncodedFunctionArgument, encodeFunctionArguments } from '../Argument.js'; import { Contract } from '../Contract.js'; import { DebugResults, debugTemplate } from '../debugging.js'; @@ -35,7 +31,16 @@ import { addressToLockScript, extendedStringify, zip } from '../utils.js'; import { TransactionBuilder } from '../TransactionBuilder.js'; import { zlibSync } from 'fflate'; import MockNetworkProvider from '../network/MockNetworkProvider.js'; -import { addHexPrefixExceptEmpty, DEFAULT_VM_TARGET, formatBytecodeForDebugging, formatParametersForDebugging, getLockScriptName, getSignatureAndPubkeyFromP2PKHInput, getUnlockScriptName, serialiseTokenDetails } from './utils.js'; +import { + addHexPrefixExceptEmpty, + DEFAULT_VM_TARGET, + formatBytecodeForDebugging, + formatParametersForDebugging, + getLockScriptName, + getSignatureAndPubkeyFromP2PKHInput, + getUnlockScriptName, + serialiseTokenDetails, +} from './utils.js'; // TODO: Add / improve descriptions throughout the template generation @@ -47,9 +52,8 @@ export const getLibauthTemplate = ( throw new Error('Cannot use debugging functionality with a transaction that contains custom unlockers'); } - const vmTarget = transactionBuilder.provider instanceof MockNetworkProvider - ? transactionBuilder.provider.vmTarget - : DEFAULT_VM_TARGET; + const vmTarget = + transactionBuilder.provider instanceof MockNetworkProvider ? transactionBuilder.provider.vmTarget : DEFAULT_VM_TARGET; const template: WalletTemplate = { $schema: 'https://ide.bitauth.com/authentication-template-v0.schema.json', @@ -67,9 +71,9 @@ export const getLibauthTemplate = ( export const debugLibauthTemplate = (template: WalletTemplate, transaction: TransactionBuilder): DebugResults => { const allArtifacts = transaction.inputs - .map(input => isContractUnlocker(input.unlocker) ? input.unlocker.contract : undefined) + .map((input) => (isContractUnlocker(input.unlocker) ? input.unlocker.contract : undefined)) .filter((contract): contract is Contract => Boolean(contract)) - .map(contract => contract.artifact); + .map((contract) => contract.artifact); return debugTemplate(template, allArtifacts); }; @@ -80,9 +84,7 @@ export const getBitauthUri = (template: WalletTemplate): string => { return `https://ide.bitauth.com/import-template/${payload}`; }; -const generateAllTemplateEntities = ( - transactionBuilder: TransactionBuilder, -): WalletTemplate['entities'] => { +const generateAllTemplateEntities = (transactionBuilder: TransactionBuilder): WalletTemplate['entities'] => { const entities = transactionBuilder.inputs.map((input, inputIndex) => { if (isP2PKHUnlocker(input.unlocker)) { return generateTemplateEntitiesP2PKH(inputIndex); @@ -99,9 +101,7 @@ const generateAllTemplateEntities = ( return entities.reduce((acc, entity) => ({ ...acc, ...entity }), {}); }; -const generateAllTemplateScripts = ( - transactionBuilder: TransactionBuilder, -): WalletTemplate['scripts'] => { +const generateAllTemplateScripts = (transactionBuilder: TransactionBuilder): WalletTemplate['scripts'] => { const scripts = transactionBuilder.inputs.map((input, inputIndex) => { if (isP2PKHUnlocker(input.unlocker)) { return generateTemplateScriptsP2PKH(inputIndex); @@ -131,7 +131,7 @@ const generateLockingBytecodeParamsMapping = ( const mapping: Record = {}; // We can typecast this because we check that all inputs are standard unlockable at the top of this function - for (const input of (transactionBuilder.inputs as StandardUnlockableUtxo[])) { + for (const input of transactionBuilder.inputs as StandardUnlockableUtxo[]) { if (isContractUnlocker(input.unlocker)) { const lockScriptName = getLockScriptName(input.unlocker.contract); const lockingScriptParams = generateLockingScriptParams(input.unlocker.contract, input, lockScriptName); @@ -169,9 +169,7 @@ const generateAllTemplateScenarios = ( return scenarios.reduce((acc, scenario) => ({ ...acc, ...scenario }), {}); }; -const generateTemplateEntitiesP2PKH = ( - inputIndex: number, -): WalletTemplate['entities'] => { +const generateTemplateEntitiesP2PKH = (inputIndex: number): WalletTemplate['entities'] => { const lockScriptName = `p2pkh_placeholder_lock_${inputIndex}`; const unlockScriptName = `p2pkh_placeholder_unlock_${inputIndex}`; @@ -206,10 +204,7 @@ const generateTemplateEntitiesP2SH = ( [contract.artifact.contractName + '_input' + inputIndex + '_parameters']: { description: 'Contract creation and function parameters', name: `${contract.artifact.contractName} (input #${inputIndex})`, - scripts: [ - getLockScriptName(contract), - getUnlockScriptName(contract, abiFunction, inputIndex), - ], + scripts: [getLockScriptName(contract), getUnlockScriptName(contract, abiFunction, inputIndex)], variables: { ...createWalletTemplateVariables(contract.artifact, abiFunction, encodedFunctionArgs), ...generateFunctionIndexTemplateVariable(contract.artifact.abi), @@ -226,33 +221,31 @@ const createWalletTemplateVariables = ( encodedFunctionArgs: EncodedFunctionArgument[], ): Record => { const functionParameters = Object.fromEntries( - abiFunction.inputs.map((input, index) => ([ + abiFunction.inputs.map((input, index) => [ input.name, { description: `"${input.name}" parameter of function "${abiFunction.name}"`, name: input.name, type: encodedFunctionArgs[index] instanceof SignatureTemplate ? 'Key' : 'WalletData', }, - ])), + ]), ); const constructorParameters = Object.fromEntries( - artifact.constructorInputs.map((input) => ([ + artifact.constructorInputs.map((input) => [ input.name, { description: `"${input.name}" parameter of this contract`, name: input.name, type: 'WalletData', }, - ])), + ]), ); return { ...functionParameters, ...constructorParameters }; }; -const generateTemplateScriptsP2PKH = ( - inputIndex: number, -): WalletTemplate['scripts'] => { +const generateTemplateScriptsP2PKH = (inputIndex: number): WalletTemplate['scripts'] => { const lockScriptName = `p2pkh_placeholder_lock_${inputIndex}`; const unlockScriptName = `p2pkh_placeholder_unlock_${inputIndex}`; @@ -260,15 +253,13 @@ const generateTemplateScriptsP2PKH = ( [unlockScriptName]: { passes: [`P2PKH_spend_input${inputIndex}_evaluate`], name: `P2PKH Unlock (input #${inputIndex})`, - script: - `\n`, + script: `\n`, unlocks: lockScriptName, }, [lockScriptName]: { lockingType: 'standard', name: `P2PKH Lock (input #${inputIndex})`, - script: - `OP_DUP\nOP_HASH160 <$( OP_HASH160\n)> OP_EQUALVERIFY\nOP_CHECKSIG`, + script: `OP_DUP\nOP_HASH160 <$( OP_HASH160\n)> OP_EQUALVERIFY\nOP_CHECKSIG`, }, }; @@ -317,9 +308,10 @@ const generateTemplateUnlockScript = ( const scenarioIdentifier = `${contract.artifact.contractName}_${abiFunction.name}_input${inputIndex}_evaluate`; const functionIndex = contract.artifact.abi.findIndex((func) => func.name === abiFunction.name); - const functionIndexString = contract.artifact.abi.length > 1 - ? ['// function index in contract', ` // int = <${functionIndex}>`, ''] - : []; + const functionIndexString = + contract.artifact.abi.length > 1 + ? ['// function index in contract', ` // int = <${functionIndex}>`, ''] + : []; return { // this unlocking script must pass our only scenario @@ -413,7 +405,13 @@ const generateTemplateScenarioTransaction = ( outpointIndex: libauthInput.outpointIndex, outpointTransactionHash: binToHex(libauthInput.outpointTransactionHash), sequenceNumber: libauthInput.sequenceNumber, - unlockingBytecode: generateTemplateScenarioBytecode(csInput, libauthInput, inputIndex, 'p2pkh_placeholder_unlock', slotIndex === inputIndex), + unlockingBytecode: generateTemplateScenarioBytecode( + csInput, + libauthInput, + inputIndex, + 'p2pkh_placeholder_unlock', + slotIndex === inputIndex, + ), }; }); @@ -423,7 +421,10 @@ const generateTemplateScenarioTransaction = ( const outputs = zippedOutputs.map(([csOutput, libauthOutput]) => { return { lockingBytecode: generateTemplateScenarioTransactionOutputLockingBytecode( - csOutput, libauthOutput, contract, lockingBytecodeParamsMapping, + csOutput, + libauthOutput, + contract, + lockingBytecodeParamsMapping, ), token: serialiseTokenDetails(libauthOutput.token), valueSatoshis: Number(libauthOutput.valueSatoshis), @@ -443,7 +444,13 @@ const generateTemplateScenarioSourceOutputs = ( const zippedInputs = zip(transactionBuilder.inputs, libauthTransaction.inputs); return zippedInputs.map(([csInput, libauthInput], inputIndex) => { return { - lockingBytecode: generateTemplateScenarioBytecodeForSourceOutputs(csInput, libauthInput, inputIndex, 'p2pkh_placeholder_lock', inputIndex === slotIndex), + lockingBytecode: generateTemplateScenarioBytecodeForSourceOutputs( + csInput, + libauthInput, + inputIndex, + 'p2pkh_placeholder_lock', + inputIndex === slotIndex, + ), valueSatoshis: Number(csInput.satoshis), token: serialiseTokenDetails(csInput.token), }; @@ -461,13 +468,10 @@ const generateLockingScriptParams = ( }; } - const constructorParamsEntries = contract.artifact.constructorInputs - .map(({ name }, index) => [ - name, - addHexPrefixExceptEmpty( - binToHex(unlocker.contract.encodedConstructorArgs[index]), - ), - ]); + const constructorParamsEntries = contract.artifact.constructorInputs.map(({ name }, index) => [ + name, + addHexPrefixExceptEmpty(binToHex(unlocker.contract.encodedConstructorArgs[index])), + ]); const constructorParams = Object.fromEntries(constructorParamsEntries); @@ -545,7 +549,7 @@ const generateTemplateScenarioKeys = ( const entries = typesAndArguments .filter(([, arg]) => arg instanceof SignatureTemplate) - .map(([input, arg]) => ([input.name, binToHex((arg as SignatureTemplate).privateKey)] as const)); + .map(([input, arg]) => [input.name, binToHex((arg as SignatureTemplate).privateKey)] as const); return Object.fromEntries(entries); }; @@ -607,7 +611,8 @@ const generateTemplateScenarioTransactionOutputLockingBytecode = ( if (lockingBytecodeParams) return lockingBytecodeParams; if (csOutput.to instanceof Uint8Array) return binToHex(csOutput.to); - if (contract && contract.contractType !== 'p2s' && [contract.address, contract.tokenAddress].includes(csOutput.to)) return {}; + if (contract && contract.contractType !== 'p2s' && [contract.address, contract.tokenAddress].includes(csOutput.to)) + return {}; return binToHex(addressToLockScript(csOutput.to)); }; @@ -615,16 +620,12 @@ const generateTemplateScenarioParametersFunctionIndex = ( abiFunction: AbiFunction, abi: readonly AbiFunction[], ): Record => { - const functionIndex = abi.length > 1 - ? abi.findIndex((func) => func.name === abiFunction.name) - : undefined; + const functionIndex = abi.length > 1 ? abi.findIndex((func) => func.name === abiFunction.name) : undefined; return functionIndex !== undefined ? { function_index: functionIndex.toString() } : {}; }; -const generateFunctionIndexTemplateVariable = ( - abi: readonly AbiFunction[], -): Record => { +const generateFunctionIndexTemplateVariable = (abi: readonly AbiFunction[]): Record => { if (abi.length > 1) { return { function_index: { diff --git a/packages/cashscript/src/libauth-template/utils.ts b/packages/cashscript/src/libauth-template/utils.ts index bca72a597..b5f654f98 100644 --- a/packages/cashscript/src/libauth-template/utils.ts +++ b/packages/cashscript/src/libauth-template/utils.ts @@ -76,15 +76,18 @@ export const getSighashTypeName = (sighashType: SighashType): string => { [SighashType.SIGHASH_ALL]: 'all_outputs', [SighashType.SIGHASH_ALL | SighashType.SIGHASH_ANYONECANPAY]: 'all_outputs_single_input', [SighashType.SIGHASH_ALL | SighashType.SIGHASH_UTXOS]: 'all_outputs_all_utxos', - [SighashType.SIGHASH_ALL | SighashType.SIGHASH_ANYONECANPAY | SighashType.SIGHASH_UTXOS]: 'all_outputs_single_input_INVALID_all_utxos', + [SighashType.SIGHASH_ALL | SighashType.SIGHASH_ANYONECANPAY | SighashType.SIGHASH_UTXOS]: + 'all_outputs_single_input_INVALID_all_utxos', [SighashType.SIGHASH_SINGLE]: 'corresponding_output', [SighashType.SIGHASH_SINGLE | SighashType.SIGHASH_ANYONECANPAY]: 'corresponding_output_single_input', [SighashType.SIGHASH_SINGLE | SighashType.SIGHASH_UTXOS]: 'corresponding_output_all_utxos', - [SighashType.SIGHASH_SINGLE | SighashType.SIGHASH_ANYONECANPAY | SighashType.SIGHASH_UTXOS]: 'corresponding_output_single_input_INVALID_all_utxos', + [SighashType.SIGHASH_SINGLE | SighashType.SIGHASH_ANYONECANPAY | SighashType.SIGHASH_UTXOS]: + 'corresponding_output_single_input_INVALID_all_utxos', [SighashType.SIGHASH_NONE]: 'no_outputs', [SighashType.SIGHASH_NONE | SighashType.SIGHASH_ANYONECANPAY]: 'no_outputs_single_input', [SighashType.SIGHASH_NONE | SighashType.SIGHASH_UTXOS]: 'no_outputs_all_utxos', - [SighashType.SIGHASH_NONE | SighashType.SIGHASH_ANYONECANPAY | SighashType.SIGHASH_UTXOS]: 'no_outputs_single_input_INVALID_all_utxos', + [SighashType.SIGHASH_NONE | SighashType.SIGHASH_ANYONECANPAY | SighashType.SIGHASH_UTXOS]: + 'no_outputs_single_input_INVALID_all_utxos', }; return sighashTypeNames[sighashType]; @@ -100,19 +103,21 @@ export const formatParametersForDebugging = (types: readonly AbiInput[], args: E // We reverse the arguments because the order of the arguments in the bytecode is reversed const typesAndArguments = zip(types, args).reverse(); - return typesAndArguments.map(([input, arg]) => { - if (arg instanceof SignatureTemplate) { - const signatureAlgorithmName = getSignatureAlgorithmName(arg.signatureAlgorithm); - const sighashTypeName = getSighashTypeName(arg.sighashType); - return `<${input.name}.${signatureAlgorithmName}.${sighashTypeName}> // ${input.type}`; - } - - const typeStr = input.type === 'bytes' ? `bytes${arg.length}` : input.type; - - // we output these values as pushdata, comment will contain the type and the value of the variable - // e.g. // int = <0xa08601> - return `<${input.name}> // ${typeStr} = <${`0x${binToHex(arg)}`}>`; - }).join('\n'); + return typesAndArguments + .map(([input, arg]) => { + if (arg instanceof SignatureTemplate) { + const signatureAlgorithmName = getSignatureAlgorithmName(arg.signatureAlgorithm); + const sighashTypeName = getSighashTypeName(arg.sighashType); + return `<${input.name}.${signatureAlgorithmName}.${sighashTypeName}> // ${input.type}`; + } + + const typeStr = input.type === 'bytes' ? `bytes${arg.length}` : input.type; + + // we output these values as pushdata, comment will contain the type and the value of the variable + // e.g. // int = <0xa08601> + return `<${input.name}> // ${typeStr} = <${`0x${binToHex(arg)}`}>`; + }) + .join('\n'); }; export const formatBytecodeForDebugging = (artifact: Artifact): string => { @@ -135,10 +140,12 @@ export const serialiseTokenDetails = ( return { amount: token.amount.toString(), category: token.category instanceof Uint8Array ? binToHex(token.category) : token.category, - nft: token.nft ? { - capability: token.nft.capability, - commitment: token.nft.commitment instanceof Uint8Array ? binToHex(token.nft.commitment) : token.nft.commitment, - } : undefined, + nft: token.nft + ? { + capability: token.nft.capability, + commitment: token.nft.commitment instanceof Uint8Array ? binToHex(token.nft.commitment) : token.nft.commitment, + } + : undefined, }; }; @@ -154,8 +161,8 @@ interface LibauthTemplateTokenDetails { export const getSignatureAndPubkeyFromP2PKHInput = ( libauthInput: Input, ): { signature: Uint8Array; publicKey: Uint8Array } => { - const inputData = (assertSuccess( - decodeAuthenticationInstructions(libauthInput.unlockingBytecode)) + const inputData = assertSuccess( + decodeAuthenticationInstructions(libauthInput.unlockingBytecode), ) as AuthenticationInstructionPush[]; const signature = inputData[0].data; const publicKey = inputData[1].data; diff --git a/packages/cashscript/src/network/ElectrumNetworkProvider.ts b/packages/cashscript/src/network/ElectrumNetworkProvider.ts index eafe772c8..b8b1ca501 100644 --- a/packages/cashscript/src/network/ElectrumNetworkProvider.ts +++ b/packages/cashscript/src/network/ElectrumNetworkProvider.ts @@ -1,10 +1,6 @@ import { binToHex, hexToBin, isHex } from '@bitauth/libauth'; import { sha256 } from '@cashscript/utils'; -import { - ElectrumClient, - type RequestResponse, - type ElectrumClientEvents, -} from '@electrum-cash/network'; +import { ElectrumClient, type RequestResponse, type ElectrumClientEvents } from '@electrum-cash/network'; import { SpendableUtxo, Network } from '../interfaces.js'; import NetworkProvider from './NetworkProvider.js'; import { addressToLockScript } from '../utils.js'; @@ -16,7 +12,6 @@ import { NetworkProviderRelativeTimelockError, } from './errors.js'; - interface OptionsBase { manualConnectionManagement?: boolean; } @@ -52,7 +47,10 @@ export default class ElectrumNetworkProvider implements NetworkProvider { * @param options - Optional hostname, pre-configured `ElectrumClient`, and/or * `manualConnectionManagement` flag. */ - constructor(public network: Network = Network.MAINNET, options: Options = {}) { + constructor( + public network: Network = Network.MAINNET, + options: Options = {}, + ) { this.electrum = this.instantiateElectrumClient(network, options); this.manualConnectionManagement = options?.manualConnectionManagement ?? false; } @@ -92,34 +90,40 @@ export default class ElectrumNetworkProvider implements NetworkProvider { const lockingBytecodeBin = typeof lockingBytecode === 'string' ? hexToBin(lockingBytecode) : lockingBytecode; const scriptHash = lockingBytecodeToElectrumScriptHash(lockingBytecodeBin); const filteringOption = 'include_tokens'; - const result = await this.performRequest('blockchain.scripthash.listunspent', scriptHash, filteringOption) as ElectrumUtxo[]; + const result = (await this.performRequest( + 'blockchain.scripthash.listunspent', + scriptHash, + filteringOption, + )) as ElectrumUtxo[]; const utxos = result.map((utxo) => ({ txid: utxo.tx_hash, vout: utxo.tx_pos, satoshis: BigInt(utxo.value), lockingBytecode: binToHex(lockingBytecodeBin), - token: utxo.token_data ? { - ...utxo.token_data, - amount: BigInt(utxo.token_data.amount), - } : undefined, + token: utxo.token_data + ? { + ...utxo.token_data, + amount: BigInt(utxo.token_data.amount), + } + : undefined, })); return utxos; } async getBlockHeight(): Promise { - const { height } = await this.performRequest('blockchain.headers.get_tip') as BlockHeader; + const { height } = (await this.performRequest('blockchain.headers.get_tip')) as BlockHeader; return height; } async getRawTransaction(txid: string): Promise { - return await this.performRequest('blockchain.transaction.get', txid) as string; + return (await this.performRequest('blockchain.transaction.get', txid)) as string; } async sendRawTransaction(txHex: string): Promise { try { - return await this.performRequest('blockchain.transaction.broadcast', txHex) as string; + return (await this.performRequest('blockchain.transaction.broadcast', txHex)) as string; } catch (e: any) { const errorMessage = e.message ?? String(e); throw classifyNetworkProviderError(errorMessage); @@ -163,10 +167,7 @@ export default class ElectrumNetworkProvider implements NetworkProvider { * @param parameters - Parameters passed to the method. * @returns The raw Electrum server response. */ - async performRequest( - name: string, - ...parameters: (string | number | boolean)[] - ): Promise { + async performRequest(name: string, ...parameters: (string | number | boolean)[]): Promise { // Only connect the electrum client when no concurrent requests are running if (this.shouldConnect()) { await this.electrum.connect(); @@ -225,29 +226,15 @@ interface BlockHeader { hex: string; } -const MISSING_INPUTS_PATTERNS = [ - 'Missing inputs', - 'bad-txns-inputs-missingorspent', - 'bad-txns-inputs-spent', -]; - -const MEMPOOL_CONFLICT_PATTERNS = [ - 'txn-mempool-conflict', -]; - -const ALREADY_SUBMITTED_PATTERNS = [ - 'transaction already in block chain', - 'txn-already-known', - 'txn-already-in-mempool', -]; - -const ABSOLUTE_TIMELOCK_PATTERNS = [ - 'bad-txns-nonfinal', -]; - -const RELATIVE_TIMELOCK_PATTERNS = [ - 'non-BIP68-final', -]; +const MISSING_INPUTS_PATTERNS = ['Missing inputs', 'bad-txns-inputs-missingorspent', 'bad-txns-inputs-spent']; + +const MEMPOOL_CONFLICT_PATTERNS = ['txn-mempool-conflict']; + +const ALREADY_SUBMITTED_PATTERNS = ['transaction already in block chain', 'txn-already-known', 'txn-already-in-mempool']; + +const ABSOLUTE_TIMELOCK_PATTERNS = ['bad-txns-nonfinal']; + +const RELATIVE_TIMELOCK_PATTERNS = ['non-BIP68-final']; function classifyNetworkProviderError(errorMessage: string): Error { if (MISSING_INPUTS_PATTERNS.some((pattern) => errorMessage.includes(pattern))) { diff --git a/packages/cashscript/src/network/MockNetworkProvider.ts b/packages/cashscript/src/network/MockNetworkProvider.ts index c86dabb04..0253db258 100644 --- a/packages/cashscript/src/network/MockNetworkProvider.ts +++ b/packages/cashscript/src/network/MockNetworkProvider.ts @@ -2,7 +2,11 @@ import { binToHex, decodeTransactionUnsafe, hexToBin, isHex, Transaction as Liba import { sha256 } from '@cashscript/utils'; import { SpendableUtxo, Utxo, Network, VmTarget } from '../interfaces.js'; import NetworkProvider from './NetworkProvider.js'; -import { addressToLockScript, cashScriptOutputToLibauthOutput, libauthTokenDetailsToCashScriptTokenDetails } from '../utils.js'; +import { + addressToLockScript, + cashScriptOutputToLibauthOutput, + libauthTokenDetailsToCashScriptTokenDetails, +} from '../utils.js'; import { createVirtualMachine, DEFAULT_VM_TARGET } from '../libauth-template/utils.js'; import { NetworkProviderAbsoluteTimelockError } from './errors.js'; @@ -59,7 +63,8 @@ export default class MockNetworkProvider implements NetworkProvider { } async getUtxosForLockingBytecode(lockingBytecode: Uint8Array | string): Promise { - const lockingBytecodeHex = typeof lockingBytecode === 'string' ? lockingBytecode.toLowerCase() : binToHex(lockingBytecode); + const lockingBytecodeHex = + typeof lockingBytecode === 'string' ? lockingBytecode.toLowerCase() : binToHex(lockingBytecode); return this.utxoSet.filter(([key]) => key === lockingBytecodeHex).map(([, utxo]) => utxo); } @@ -126,9 +131,10 @@ export default class MockNetworkProvider implements NetworkProvider { const remainingUtxoEntries = [...this.utxoSet]; return transaction.inputs.map((input) => { - const utxoIndex = remainingUtxoEntries.findIndex(([, utxo]) => ( - utxo.txid.toLowerCase() === binToHex(input.outpointTransactionHash) && utxo.vout === input.outpointIndex - )); + const utxoIndex = remainingUtxoEntries.findIndex( + ([, utxo]) => + utxo.txid.toLowerCase() === binToHex(input.outpointTransactionHash) && utxo.vout === input.outpointIndex, + ); // TODO: we should check what error a BCHN node throws, so we can throw the same error here if (utxoIndex === -1) { @@ -143,11 +149,13 @@ export default class MockNetworkProvider implements NetworkProvider { private validateTransaction(transaction: LibauthTransaction, spentUtxoEntries: Array<[string, SpendableUtxo]>): void { this.validateLocktime(transaction); - const sourceOutputs = spentUtxoEntries.map(([lockingBytecode, utxo]) => cashScriptOutputToLibauthOutput({ - to: hexToBin(lockingBytecode), - amount: utxo.satoshis, - token: utxo.token, - })); + const sourceOutputs = spentUtxoEntries.map(([lockingBytecode, utxo]) => + cashScriptOutputToLibauthOutput({ + to: hexToBin(lockingBytecode), + amount: utxo.satoshis, + token: utxo.token, + }), + ); const vm = createVirtualMachine(this.vmTarget); const verificationResult = vm.verify({ transaction, sourceOutputs }); @@ -183,8 +191,9 @@ export default class MockNetworkProvider implements NetworkProvider { * @returns The added UTXO, annotated with the locking bytecode it was added under. */ addUtxo(addressOrLockingBytecode: string, utxo: Utxo): SpendableUtxo { - const lockingBytecode = isHex(addressOrLockingBytecode) ? - addressOrLockingBytecode.toLowerCase() : binToHex(addressToLockScript(addressOrLockingBytecode)); + const lockingBytecode = isHex(addressOrLockingBytecode) + ? addressOrLockingBytecode.toLowerCase() + : binToHex(addressToLockScript(addressOrLockingBytecode)); const annotatedUtxo = { ...utxo, lockingBytecode }; this.utxoSet.push([lockingBytecode, annotatedUtxo]); diff --git a/packages/cashscript/src/network/errors.ts b/packages/cashscript/src/network/errors.ts index 70fe97011..e055d8f21 100644 --- a/packages/cashscript/src/network/errors.ts +++ b/packages/cashscript/src/network/errors.ts @@ -1,6 +1,9 @@ // Base class for errors returned by a network provider when broadcasting a transaction. export class NetworkProviderError extends Error { - constructor(message: string, public originalError: string) { + constructor( + message: string, + public originalError: string, + ) { super(message); } } diff --git a/packages/cashscript/src/test/TestExtensions.ts b/packages/cashscript/src/test/TestExtensions.ts index c69aeb1ac..f210fd212 100644 --- a/packages/cashscript/src/test/TestExtensions.ts +++ b/packages/cashscript/src/test/TestExtensions.ts @@ -12,22 +12,19 @@ const testFramework: TestFramework = (globalThis as any).vi ?? (globalThis as an // Extend Vitest or Jest with the custom matchers expect.extend({ - toLog( - transaction: Debuggable, - match?: RegExp | string, - ) { + toLog(transaction: Debuggable, match?: RegExp | string) { const loggerSpy = testFramework.spyOn(console, 'log'); // Clear any previous calls (if spy reused accidentally) loggerSpy.mockClear(); // silence actual stdout output - loggerSpy.mockImplementation(() => { }); + loggerSpy.mockImplementation(() => {}); // Run debug, ignoring any errors because we only care about the logs, even if the transaction fails try { transaction.debug(); - } catch (error) { } + } catch (error) {} // We concatenate all the logs into a single string - if no logs are present, we set received to undefined const receivedBase = loggerSpy.mock.calls.reduce((acc, [log]) => `${acc}\n${log}`, '').trim(); @@ -56,9 +53,7 @@ expect.extend({ return { message, pass: true }; }, - toFailRequire( - transaction: Debuggable, - ) { + toFailRequire(transaction: Debuggable) { try { transaction.debug(); const message = (): string => 'Contract function did not fail a require statement.'; @@ -69,10 +64,7 @@ expect.extend({ return { message, pass: true }; } }, - toFailRequireWith( - transaction: Debuggable, - match: RegExp | string, - ) { + toFailRequireWith(transaction: Debuggable, match: RegExp | string) { try { transaction.debug(); const matcherHint = this.utils.matcherHint('.toFailRequireWith', undefined, match.toString(), { isNot: this.isNot }); @@ -94,4 +86,4 @@ expect.extend({ }, }); -export { }; +export {}; diff --git a/packages/cashscript/src/transaction-utils.ts b/packages/cashscript/src/transaction-utils.ts index 1373ef2c6..32d0e0088 100644 --- a/packages/cashscript/src/transaction-utils.ts +++ b/packages/cashscript/src/transaction-utils.ts @@ -20,9 +20,7 @@ export interface GatherUtxosResult { * @throws If the available non-token UTXOs do not cover the requested amount. */ export function gatherBchUtxos(utxos: U[], amount: bigint): GatherUtxosResult { - const sortedBchUtxos = utxos - .filter(isNonTokenUtxo) - .toSorted((a, b) => Number(b.satoshis - a.satoshis)); + const sortedBchUtxos = utxos.filter(isNonTokenUtxo).toSorted((a, b) => Number(b.satoshis - a.satoshis)); const targetUtxos: U[] = []; let total = 0n; @@ -51,7 +49,9 @@ export function gatherBchUtxos(utxos: U[], amount: bigint): Gath * @throws If the available fungible token UTXOs do not cover the requested amount. */ export function gatherFungibleTokenUtxos( - utxos: U[], tokenCategory: string, amount: bigint, + utxos: U[], + tokenCategory: string, + amount: bigint, ): GatherUtxosResult { const sortedTokenUtxos = utxos .filter((utxo) => isFungibleTokenUtxo(utxo) && utxo.token!.category === tokenCategory) diff --git a/packages/cashscript/src/types/type-inference.ts b/packages/cashscript/src/types/type-inference.ts index 0e8cbd44d..42ae077f2 100644 --- a/packages/cashscript/src/types/type-inference.ts +++ b/packages/cashscript/src/types/type-inference.ts @@ -22,11 +22,7 @@ type TypeMap = { // - If `Param` is a known type, it maps the `type` to `TypeMap[Type]`. // - If `Param` has an unknown `type`, it defaults to `any`. // - If `Param` is not an object with `type`, it defaults to `any`. -type ProcessParam = Param extends { type: infer Type } - ? Type extends keyof TypeMap - ? TypeMap[Type] - : any - : any; +type ProcessParam = Param extends { type: infer Type } ? (Type extends keyof TypeMap ? TypeMap[Type] : any) : any; // Main type to recursively convert an array of parameter definitions into a tuple. // Example: [{ type: "pubkey" }, { type: "int" }] -> [Uint8Array, bigint] @@ -47,8 +43,8 @@ export type ParamsToTuple = Params extends readonly [infer Head, ...infe // - Branch 2: If `Function` does not match the expected shape, it returns an empty object. type ProcessFunction = Function extends { name: string; inputs: readonly any[] } ? { - [functionName in Function['name']]: (...functionParameters: ParamsToTuple) => ReturnType; - } + [functionName in Function['name']]: (...functionParameters: ParamsToTuple) => ReturnType; + } : {}; // Recursively converts an ABI into a function map with parameter typings and return type. diff --git a/packages/cashscript/src/utils.ts b/packages/cashscript/src/utils.ts index f9ffc24ba..a9489f736 100644 --- a/packages/cashscript/src/utils.ts +++ b/packages/cashscript/src/utils.ts @@ -15,15 +15,7 @@ import { NonFungibleTokenCapability, SigningSerializationFlag, } from '@bitauth/libauth'; -import { - encodeInt, - hash160, - hash256, - Op, - Script, - scriptToBytecode, - encodeNullDataScript, -} from '@cashscript/utils'; +import { encodeInt, hash160, hash256, Op, Script, scriptToBytecode, encodeNullDataScript } from '@cashscript/utils'; import { Utxo, Output, @@ -244,7 +236,7 @@ export function generateLibauthSourceOutputs(inputs: UnlockableUtxo[]): LibauthO function isTokenAddress(address: string): boolean { const result = decodeCashAddress(address); if (typeof result === 'string') throw new Error(result); - const supportsTokens = (result.type === 'p2pkhWithTokens' || result.type === 'p2shWithTokens'); + const supportsTokens = result.type === 'p2pkhWithTokens' || result.type === 'p2shWithTokens'; return supportsTokens; } @@ -303,13 +295,8 @@ export function createUnlockingBytecode( return scriptToBytecode(inputScript); } -export function createOpReturnOutput( - opReturnData: string[], -): Output { - const script = [ - Op.OP_RETURN, - ...opReturnData.map((output: string) => toBin(output)), - ]; +export function createOpReturnOutput(opReturnData: string[]): Output { + const script = [Op.OP_RETURN, ...opReturnData.map((output: string) => toBin(output))]; return { to: encodeNullDataScript(script), amount: 0n }; } @@ -344,9 +331,7 @@ export function toRegExp(reasons: string[]): RegExp { return new RegExp(reasons.join('|').replace(/\(/g, '\\(').replace(/\)/g, '\\)')); } -export function scriptToAddress( - script: Script, network: string, addressType: AddressType, tokenSupport: boolean, -): string { +export function scriptToAddress(script: Script, network: string, addressType: AddressType, tokenSupport: boolean): string { const bytecode = scriptToP2SHLockingBytecode(script, addressType); const prefix = getNetworkPrefix(network); @@ -358,7 +343,7 @@ export function scriptToAddress( export function scriptToP2SHLockingBytecode(script: Script, addressType: AddressType): Uint8Array { const scriptBytecode = scriptToBytecode(script); - const scriptHash = (addressType === 'p2sh20') ? hash160(scriptBytecode) : hash256(scriptBytecode); + const scriptHash = addressType === 'p2sh20' ? hash160(scriptBytecode) : hash256(scriptBytecode); const addressContents = { payload: scriptHash, type: LockingBytecodeType[addressType] }; const lockingBytecode = addressContentsToLockingBytecode(addressContents); return lockingBytecode; @@ -386,12 +371,12 @@ export function utxoTokenComparator(a: Utxo, b: Utxo): number { } /** -* Helper function to convert an address to a locking script -* -* @param address Address to convert to locking script -* -* @returns a locking script corresponding to the passed address -*/ + * Helper function to convert an address to a locking script + * + * @param address Address to convert to locking script + * + * @returns a locking script corresponding to the passed address + */ export function addressToLockScript(address: string): Uint8Array { const result = cashAddressToLockingBytecode(address); if (typeof result === 'string') throw new Error(result); @@ -428,12 +413,13 @@ const randomBytesHex = (length: number): string => binToHex(crypto.getRandomValu * @param defaults - Values that override the randomly generated fields. * @returns A synthetic UTXO with random `txid`, `vout`, and `satoshis`. */ -export const randomUtxo = >(defaults?: T): Utxo & T => ({ - txid: randomBytesHex(32), - vout: Math.floor(Math.random() * 10), - satoshis: 100_000n + randomInt(), - ...defaults, -} as Utxo & T); +export const randomUtxo = >(defaults?: T): Utxo & T => + ({ + txid: randomBytesHex(32), + vout: Math.floor(Math.random() * 10), + satoshis: 100_000n + randomInt(), + ...defaults, + }) as Utxo & T; /** * Generate random fungible `TokenDetails` for use in tests and examples. Fields can be overridden @@ -479,27 +465,26 @@ export function findLastIndex(array: Array, predicate: (value: T, index: n } // JSON.stringify version that can serialize otherwise unsupported types (bigint and Uint8Array) -export const extendedStringify = (obj: any, spaces?: number): string => JSON.stringify( - obj, - (_, v) => { - if (typeof v === 'bigint') { - return `${v.toString()}`; - } - if (v instanceof Uint8Array) { - return `${binToHex(v)}`; - } - return v; - }, - spaces, -); +export const extendedStringify = (obj: any, spaces?: number): string => + JSON.stringify( + obj, + (_, v) => { + if (typeof v === 'bigint') { + return `${v.toString()}`; + } + if (v instanceof Uint8Array) { + return `${binToHex(v)}`; + } + return v; + }, + spaces, + ); -export const zip = (a: readonly T[], b: readonly U[]): [T, U][] => ( - Array.from(Array(Math.max(b.length, a.length)), (_, i) => [a[i], b[i]]) -); +export const zip = (a: readonly T[], b: readonly U[]): [T, U][] => + Array.from(Array(Math.max(b.length, a.length)), (_, i) => [a[i], b[i]]); -export const isFungibleTokenUtxo = (utxo: Utxo): boolean => ( - utxo.token !== undefined && utxo.token.amount > 0n && utxo.token.nft === undefined -); +export const isFungibleTokenUtxo = (utxo: Utxo): boolean => + utxo.token !== undefined && utxo.token.amount > 0n && utxo.token.nft === undefined; export const isNonTokenUtxo = (utxo: Utxo): boolean => utxo.token === undefined; diff --git a/packages/cashscript/src/walletconnect-utils.ts b/packages/cashscript/src/walletconnect-utils.ts index 140ab3427..152a6038e 100644 --- a/packages/cashscript/src/walletconnect-utils.ts +++ b/packages/cashscript/src/walletconnect-utils.ts @@ -24,15 +24,15 @@ export interface WcContractInfo { abiFunction: AbiFunction; redeemScript: Uint8Array; artifact: Partial; - } + }; } export function getWcContractInfo(input: UnlockableUtxo): WcContractInfo | {} { // If the input does not have a contract unlocker, return an empty object - if (!(isContractUnlocker(input.unlocker))) return {}; + if (!isContractUnlocker(input.unlocker)) return {}; const contract = input.unlocker.contract; const abiFunctionName = input.unlocker.abiFunction?.name; - const abiFunction = contract.artifact.abi.find(abi => abi.name === abiFunctionName); + const abiFunction = contract.artifact.abi.find((abi) => abi.name === abiFunctionName); if (!abiFunction) { throw new Error(`ABI function ${abiFunctionName} not found in contract artifact`); } diff --git a/packages/cashscript/test/Contract.test.ts b/packages/cashscript/test/Contract.test.ts index a24300d00..68224bb31 100644 --- a/packages/cashscript/test/Contract.test.ts +++ b/packages/cashscript/test/Contract.test.ts @@ -9,10 +9,7 @@ import { SignatureTemplate, TransactionBuilder, } from '../src/index.js'; -import { - aliceAddress, - alicePkh, alicePriv, alicePub, bobPriv, bobPub, -} from './fixture/vars.js'; +import { aliceAddress, alicePkh, alicePriv, alicePub, bobPriv, bobPub } from './fixture/vars.js'; import { addUtxo } from './test-util.js'; import { generateLibauthSourceOutputs } from '../src/utils.js'; import p2pkhArtifact from './fixture/p2pkh.artifact.js'; @@ -51,8 +48,9 @@ describe('Contract', () => { const provider = new ElectrumNetworkProvider(Network.CHIPNET); const constructorArgs = [placeholder(20), placeholder(20), 1000000n]; - expect(() => new Contract(deprecatedMecenasArtifact, constructorArgs, { provider })) - .toThrow(/unsupported compiler version/); + expect(() => new Contract(deprecatedMecenasArtifact, constructorArgs, { provider })).toThrow( + /unsupported compiler version/, + ); }); it('should fail with incomplete artifact', () => { @@ -60,9 +58,7 @@ describe('Contract', () => { expect(() => new Contract({ ...p2pkhArtifact, abi: undefined } as any, [], { provider })).toThrow(); expect(() => new Contract({ ...p2pkhArtifact, bytecode: undefined } as any, [], { provider })).toThrow(); - expect( - () => new Contract({ ...p2pkhArtifact, constructorInputs: undefined } as any, [], { provider }), - ).toThrow(); + expect(() => new Contract({ ...p2pkhArtifact, constructorInputs: undefined } as any, [], { provider })).toThrow(); expect(() => new Contract({ ...p2pkhArtifact, contractName: undefined } as any, [], { provider })).toThrow(); }); @@ -170,14 +166,15 @@ describe('Contract', () => { bbInstance = new Contract(boundedBytesArtifact, [], { provider }); }); - it('can\'t call spend with incorrect signature', () => { + it("can't call spend with incorrect signature", () => { expect(() => instance.unlock.spend()).toThrow(); expect(() => instance.unlock.spend(0n, 1n)).toThrow(); expect(() => instance.unlock.spend(alicePub, new SignatureTemplate(alicePriv), 0n)).toThrow(); expect(() => bbInstance.unlock.spend(hexToBin('e803'), 1000n)).toThrow(); expect(() => bbInstance.unlock.spend(hexToBin('e803000000'), 1000n)).toThrow(); - expect(() => instance.unlock.spend(alicePkh, placeholder(65))) - .toThrow("Found type 'bytes20' where type 'pubkey' was expected"); + expect(() => instance.unlock.spend(alicePkh, placeholder(65))).toThrow( + "Found type 'bytes20' where type 'pubkey' was expected", + ); }); it('can call spend with incorrect arguments', () => { @@ -192,16 +189,12 @@ describe('Contract', () => { }); it('generates correct locking bytecode', () => { - expect(instance.lockingBytecode) - .toEqual('aa2034d9ffce86b4d136ca74e9db6f6433d3548966a6be064052e728a4c1d16aa3a587'); + expect(instance.lockingBytecode).toEqual('aa2034d9ffce86b4d136ca74e9db6f6433d3548966a6be064052e728a4c1d16aa3a587'); }); it('can spend from a p2s contract', async () => { const p2sInstance = new Contract(p2pkhArtifact, [alicePkh], { provider, contractType: 'p2s' }); - const utxo = provider.addUtxo( - p2sInstance.lockingBytecode, - randomUtxo({ satoshis: 100_000n }), - ); + const utxo = provider.addUtxo(p2sInstance.lockingBytecode, randomUtxo({ satoshis: 100_000n })); const transaction = new TransactionBuilder({ provider }) .addInput(utxo, p2sInstance.unlock.spend(alicePub, new SignatureTemplate(alicePriv))) @@ -226,8 +219,11 @@ describe('Contract', () => { const transaction = decodeTransactionUnsafe(hexToBin(transactionBuilder.build())); const sourceOutputs = generateLibauthSourceOutputs(transactionBuilder.inputs); - expect(unlocker.generateUnlockingBytecode({ transaction, sourceOutputs, inputIndex: 0 })) - .toEqual(hexToBin('4135fac4118af15e0d66f30548dd0c31e1108f3389af96bb9db4f2305706e18fe52cc7163f6440fae98c48332d09c30380527a90604f14b4b3fc0c3aa0884c9c0a61210373cc07b54c22da627b572a387a20ea190c9382e5e6d48c1d5b89c5cea2c4c0881914512dbb2c8c02efbac8d92431aa0ac33f6b0bf97078a988ac')); + expect(unlocker.generateUnlockingBytecode({ transaction, sourceOutputs, inputIndex: 0 })).toEqual( + hexToBin( + '4135fac4118af15e0d66f30548dd0c31e1108f3389af96bb9db4f2305706e18fe52cc7163f6440fae98c48332d09c30380527a90604f14b4b3fc0c3aa0884c9c0a61210373cc07b54c22da627b572a387a20ea190c9382e5e6d48c1d5b89c5cea2c4c0881914512dbb2c8c02efbac8d92431aa0ac33f6b0bf97078a988ac', + ), + ); }); }); }); diff --git a/packages/cashscript/test/SignatureTemplate.test.ts b/packages/cashscript/test/SignatureTemplate.test.ts index 0b9904035..d94b0da4e 100644 --- a/packages/cashscript/test/SignatureTemplate.test.ts +++ b/packages/cashscript/test/SignatureTemplate.test.ts @@ -1,5 +1,11 @@ import { generateLibauthSourceOutputs } from '../src/utils.js'; -import { MockNetworkProvider, SighashType, SignatureAlgorithm, SignatureTemplate, TransactionBuilder } from '../src/index.js'; +import { + MockNetworkProvider, + SighashType, + SignatureAlgorithm, + SignatureTemplate, + TransactionBuilder, +} from '../src/index.js'; import { aliceAddress, alicePriv, alicePub, aliceWif } from './fixture/vars.js'; import { binToHex, decodeTransactionUnsafe, hexToBin } from '@bitauth/libauth'; @@ -24,19 +30,31 @@ describe('SignatureTemplate', () => { it('should generate a correct signature using Schnorr', () => { const signatureTemplate = new SignatureTemplate(alicePriv); const signature = signatureTemplate.generateSignature(hexToBin('0000000000000000000000')); - expect(signature).toEqual(hexToBin('bcac180e17de108003cce026708bd2af54b860dad2626cee157f4ed5abd993b9085d615015f905978adc51e8878226280ddd27d899f086519c0978e53332d79961')); + expect(signature).toEqual( + hexToBin( + 'bcac180e17de108003cce026708bd2af54b860dad2626cee157f4ed5abd993b9085d615015f905978adc51e8878226280ddd27d899f086519c0978e53332d79961', + ), + ); }); it('should generate a correct signature using ECDSA', () => { const signatureTemplate = new SignatureTemplate(alicePriv, undefined, SignatureAlgorithm.ECDSA); const signature = signatureTemplate.generateSignature(hexToBin('0000000000000000000000')); - expect(signature).toEqual(hexToBin('3045022100fa1d6a159a124e99479f78152422d55ff3c16f7fac5ae47fa291907f8f47613f02200d6c906f667b3712860b6f5a1f296ecb7dcd44da83c6a1eb45869b61c6b8dadb61')); + expect(signature).toEqual( + hexToBin( + '3045022100fa1d6a159a124e99479f78152422d55ff3c16f7fac5ae47fa291907f8f47613f02200d6c906f667b3712860b6f5a1f296ecb7dcd44da83c6a1eb45869b61c6b8dadb61', + ), + ); }); it('should append the configured sighash type, always including the BCH fork ID', () => { const signatureTemplate = new SignatureTemplate(alicePriv, SighashType.SIGHASH_SINGLE); const signature = signatureTemplate.generateSignature(hexToBin('0000000000000000000000')); - expect(signature).toEqual(hexToBin('bcac180e17de108003cce026708bd2af54b860dad2626cee157f4ed5abd993b9085d615015f905978adc51e8878226280ddd27d899f086519c0978e53332d79943')); + expect(signature).toEqual( + hexToBin( + 'bcac180e17de108003cce026708bd2af54b860dad2626cee157f4ed5abd993b9085d615015f905978adc51e8878226280ddd27d899f086519c0978e53332d79943', + ), + ); }); }); @@ -44,7 +62,11 @@ describe('SignatureTemplate', () => { it('should generate a correct signature using Schnorr', () => { const signatureTemplate = new SignatureTemplate(alicePriv); const signature = signatureTemplate.signMessageHash(hexToBin('0000000000000000000000')); - expect(signature).toEqual(hexToBin('bcac180e17de108003cce026708bd2af54b860dad2626cee157f4ed5abd993b9085d615015f905978adc51e8878226280ddd27d899f086519c0978e53332d799')); + expect(signature).toEqual( + hexToBin( + 'bcac180e17de108003cce026708bd2af54b860dad2626cee157f4ed5abd993b9085d615015f905978adc51e8878226280ddd27d899f086519c0978e53332d799', + ), + ); }); }); @@ -52,7 +74,11 @@ describe('SignatureTemplate', () => { it('should generate a correct signature using ECDSA', () => { const signatureTemplate = new SignatureTemplate(alicePriv, undefined, SignatureAlgorithm.ECDSA); const signature = signatureTemplate.signMessageHash(hexToBin('0000000000000000000000')); - expect(signature).toEqual(hexToBin('3045022100fa1d6a159a124e99479f78152422d55ff3c16f7fac5ae47fa291907f8f47613f02200d6c906f667b3712860b6f5a1f296ecb7dcd44da83c6a1eb45869b61c6b8dadb')); + expect(signature).toEqual( + hexToBin( + '3045022100fa1d6a159a124e99479f78152422d55ff3c16f7fac5ae47fa291907f8f47613f02200d6c906f667b3712860b6f5a1f296ecb7dcd44da83c6a1eb45869b61c6b8dadb', + ), + ); }); }); @@ -82,8 +108,11 @@ describe('SignatureTemplate', () => { const transaction = decodeTransactionUnsafe(hexToBin(transactionBuilder.build())); const sourceOutputs = generateLibauthSourceOutputs(transactionBuilder.inputs); - expect(unlocker.generateUnlockingBytecode({ transaction, sourceOutputs, inputIndex: 0 })) - .toEqual(hexToBin('415cbd7f111be33daa9578ed7ace1b6721a5d14206302c628b1bfc27cfef92a334943504089731b7ce10173be7f22dc175f6d10c8c5a3d1b41a64db09555ebb00d61210373cc07b54c22da627b572a387a20ea190c9382e5e6d48c1d5b89c5cea2c4c088')); + expect(unlocker.generateUnlockingBytecode({ transaction, sourceOutputs, inputIndex: 0 })).toEqual( + hexToBin( + '415cbd7f111be33daa9578ed7ace1b6721a5d14206302c628b1bfc27cfef92a334943504089731b7ce10173be7f22dc175f6d10c8c5a3d1b41a64db09555ebb00d61210373cc07b54c22da627b572a387a20ea190c9382e5e6d48c1d5b89c5cea2c4c088', + ), + ); }); }); }); diff --git a/packages/cashscript/test/TransactionBuilder.test.ts b/packages/cashscript/test/TransactionBuilder.test.ts index 3395bc4b7..283a54a2b 100644 --- a/packages/cashscript/test/TransactionBuilder.test.ts +++ b/packages/cashscript/test/TransactionBuilder.test.ts @@ -1,5 +1,13 @@ import { decodeTransactionUnsafe, hexToBin, stringify } from '@bitauth/libauth'; -import { Contract, SignatureTemplate, ElectrumNetworkProvider, MockNetworkProvider, placeholderP2PKHUnlocker, placeholderPublicKey, placeholderSignature } from '../src/index.js'; +import { + Contract, + SignatureTemplate, + ElectrumNetworkProvider, + MockNetworkProvider, + placeholderP2PKHUnlocker, + placeholderPublicKey, + placeholderSignature, +} from '../src/index.js'; import { bobAddress, bobPub, @@ -15,7 +23,14 @@ import { alicePriv, } from './fixture/vars.js'; import { Network, SpendableUtxo, Utxo } from '../src/interfaces.js'; -import { utxoComparator, calculateDust, randomUtxo, randomToken, isNonTokenUtxo, isFungibleTokenUtxo } from '../src/utils.js'; +import { + utxoComparator, + calculateDust, + randomUtxo, + randomToken, + isNonTokenUtxo, + isFungibleTokenUtxo, +} from '../src/utils.js'; import p2pkhArtifact from './fixture/p2pkh.artifact.js'; import twtArtifact from './fixture/transfer_with_timeout.artifact.js'; import { TransactionBuilder } from '../src/TransactionBuilder.js'; @@ -32,9 +47,7 @@ import { import { FailingMockNetworkProvider } from '../src/network/MockNetworkProvider.js'; describe('Transaction Builder', () => { - const provider = process.env.TESTS_USE_CHIPNET - ? new ElectrumNetworkProvider(Network.CHIPNET) - : new MockNetworkProvider(); + const provider = process.env.TESTS_USE_CHIPNET ? new ElectrumNetworkProvider(Network.CHIPNET) : new MockNetworkProvider(); let p2pkhInstance: Contract; let twtInstance: Contract; @@ -174,10 +187,11 @@ describe('Transaction Builder', () => { it('should fail when fee per byte is lower than 1, even when it rounds to 1', async () => { const mockProvider = new MockNetworkProvider(); const utxo = mockProvider.addUtxo(carolAddress, randomUtxo({ satoshis: 100_000n })); - const createTransaction = (fee: bigint): TransactionBuilder => new TransactionBuilder({ provider: mockProvider }) - .addInput(utxo, new SignatureTemplate(carolPriv).unlockP2PKH()) - .addOutput({ to: carolAddress, amount: 100_000n - fee }) - .addOpReturnOutput([`0x${'00'.repeat(100)}`]); + const createTransaction = (fee: bigint): TransactionBuilder => + new TransactionBuilder({ provider: mockProvider }) + .addInput(utxo, new SignatureTemplate(carolPriv).unlockP2PKH()) + .addOutput({ to: carolAddress, amount: 100_000n - fee }) + .addOpReturnOutput([`0x${'00'.repeat(100)}`]); const buildWithFee = (fee: bigint): string => createTransaction(fee).build(); // The OP_RETURN output makes the transaction large enough that a fee of (size - 1) satoshis is just below @@ -248,38 +262,43 @@ describe('Transaction Builder', () => { it('should fail when spending a contract UTXO with an unlocker of a different contract', async () => { const p2pkhUtxos = (await p2pkhInstance.getUtxos()).filter(isNonTokenUtxo); - expect(() => ( - new TransactionBuilder({ provider }) - .addInput(p2pkhUtxos[0], twtInstance.unlock.transfer(new SignatureTemplate(carolPriv))) - )).toThrow(UnlockerLockingBytecodeMismatchError); + expect(() => + new TransactionBuilder({ provider }).addInput( + p2pkhUtxos[0], + twtInstance.unlock.transfer(new SignatureTemplate(carolPriv)), + ), + ).toThrow(UnlockerLockingBytecodeMismatchError); }); it('should fail when spending a contract UTXO with an unlocker of the same contract with a different address type', async () => { const p2sh20Instance = new Contract(p2pkhArtifact, [carolPkh], { provider, contractType: 'p2sh20' }); const p2pkhUtxos = (await p2pkhInstance.getUtxos()).filter(isNonTokenUtxo); - expect(() => ( - new TransactionBuilder({ provider }) - .addInput(p2pkhUtxos[0], p2sh20Instance.unlock.spend(carolPub, new SignatureTemplate(carolPriv))) - )).toThrow(UnlockerLockingBytecodeMismatchError); + expect(() => + new TransactionBuilder({ provider }).addInput( + p2pkhUtxos[0], + p2sh20Instance.unlock.spend(carolPub, new SignatureTemplate(carolPriv)), + ), + ).toThrow(UnlockerLockingBytecodeMismatchError); }); it('should fail when spending a P2PKH UTXO with a SignatureTemplate for a different key', async () => { const aliceUtxos = (await provider.getUtxos(aliceAddress)).filter(isNonTokenUtxo); - expect(() => ( - new TransactionBuilder({ provider }) - .addInput(aliceUtxos[0], new SignatureTemplate(bobPriv).unlockP2PKH()) - )).toThrow(UnlockerLockingBytecodeMismatchError); + expect(() => + new TransactionBuilder({ provider }).addInput(aliceUtxos[0], new SignatureTemplate(bobPriv).unlockP2PKH()), + ).toThrow(UnlockerLockingBytecodeMismatchError); }); it('should fail when adding a UTXO without a lockingBytecode', async () => { const utxoWithoutLockingBytecode = randomUtxo() as SpendableUtxo; - expect(() => ( - new TransactionBuilder({ provider }) - .addInput(utxoWithoutLockingBytecode, new SignatureTemplate(bobPriv).unlockP2PKH()) - )).toThrow(InputMissingLockingBytecodeError); + expect(() => + new TransactionBuilder({ provider }).addInput( + utxoWithoutLockingBytecode, + new SignatureTemplate(bobPriv).unlockP2PKH(), + ), + ).toThrow(InputMissingLockingBytecodeError); }); }); @@ -446,13 +465,11 @@ describe('Transaction Builder', () => { }); describe('change output management', () => { - const carolUnlocker = (): ReturnType => ( - p2pkhInstance.unlock.spend(carolPub, new SignatureTemplate(carolPriv)) - ); + const carolUnlocker = (): ReturnType => + p2pkhInstance.unlock.spend(carolPub, new SignatureTemplate(carolPriv)); - const randomContractUtxo = (defaults?: Partial): SpendableUtxo => ( - randomUtxo({ ...defaults, lockingBytecode: p2pkhInstance.lockingBytecode }) - ); + const randomContractUtxo = (defaults?: Partial): SpendableUtxo => + randomUtxo({ ...defaults, lockingBytecode: p2pkhInstance.lockingBytecode }); describe('BCH change lock', () => { it('should prevent further inputs or outputs after a BCH change output was added', () => { @@ -487,9 +504,13 @@ describe('Transaction Builder', () => { .addTokenChangeOutputIfNeeded({ category: token.category, to: aliceTokenAddress }); expect(() => builder.addInput(randomContractUtxo({ token }), carolUnlocker())).toThrow(OutputTokenChangeLockedError); - expect(() => builder.addOutput({ - to: bobTokenAddress, amount: 1000n, token: { amount: 100n, category: token.category }, - })).toThrow(OutputTokenChangeLockedError); + expect(() => + builder.addOutput({ + to: bobTokenAddress, + amount: 1000n, + token: { amount: 100n, category: token.category }, + }), + ).toThrow(OutputTokenChangeLockedError); }); it('should leave other categories and non-token inputs/outputs unaffected', () => { @@ -561,8 +582,7 @@ describe('Transaction Builder', () => { it('should fail when the change address does not support tokens', () => { const token = randomToken(); - const builder = new TransactionBuilder({ provider }) - .addInput(randomContractUtxo({ token }), carolUnlocker()); + const builder = new TransactionBuilder({ provider }).addInput(randomContractUtxo({ token }), carolUnlocker()); expect(() => { builder.addTokenChangeOutputIfNeeded({ category: token.category, to: aliceAddress }); diff --git a/packages/cashscript/test/debugging-old-artifacts.test.ts b/packages/cashscript/test/debugging-old-artifacts.test.ts index 908d5fc5a..fcb1ef198 100644 --- a/packages/cashscript/test/debugging-old-artifacts.test.ts +++ b/packages/cashscript/test/debugging-old-artifacts.test.ts @@ -3,9 +3,7 @@ import { alicePkh, alicePriv, alicePub, bobPriv } from './fixture/vars.js'; const artifact = { contractName: 'P2PKH', - constructorInputs: [ - { name: 'pkh', type: 'bytes20' }, - ], + constructorInputs: [{ name: 'pkh', type: 'bytes20' }], abi: [ { name: 'spend', @@ -16,7 +14,8 @@ const artifact = { }, ], bytecode: 'OP_OVER OP_HASH160 OP_EQUALVERIFY OP_CHECKSIG', - source: 'pragma cashscript ^0.7.0;\n\ncontract P2PKH(bytes20 pkh) {\n // Require pk to match stored pkh and signature to match\n function spend(pubkey pk, sig s) {\n require(hash160(pk) == pkh);\n require(checkSig(s, pk));\n }\n}\n', + source: + 'pragma cashscript ^0.7.0;\n\ncontract P2PKH(bytes20 pkh) {\n // Require pk to match stored pkh and signature to match\n function spend(pubkey pk, sig s) {\n require(hash160(pk) == pkh);\n require(checkSig(s, pk));\n }\n}\n', compiler: { name: 'cashc', version: '0.7.0', diff --git a/packages/cashscript/test/debugging.test.ts b/packages/cashscript/test/debugging.test.ts index 5cbb1cfbb..293c3c712 100644 --- a/packages/cashscript/test/debugging.test.ts +++ b/packages/cashscript/test/debugging.test.ts @@ -1,4 +1,13 @@ -import { Contract, FailedTransactionEvaluationError, MockNetworkProvider, SignatureAlgorithm, SignatureTemplate, TransactionBuilder, UnlockerLockingBytecodeMismatchError, VmTarget } from '../src/index.js'; +import { + Contract, + FailedTransactionEvaluationError, + MockNetworkProvider, + SignatureAlgorithm, + SignatureTemplate, + TransactionBuilder, + UnlockerLockingBytecodeMismatchError, + VmTarget, +} from '../src/index.js'; import { DEFAULT_VM_TARGET, getLockScriptName } from '../src/libauth-template/utils.js'; import { aliceAddress, alicePriv, alicePub, bobPriv, bobPub } from './fixture/vars.js'; import { randomUtxo } from '../src/utils.js'; @@ -39,10 +48,7 @@ describe('Debugging tests', () => { const contractUtxo = provider.addUtxo(contractTestLogs.address, randomUtxo()); const contractTestLogInsideLoop = new Contract(artifactTestLogInsideLoop, [], { provider }); - const contractTestLogInsideLoopUtxo = provider.addUtxo( - contractTestLogInsideLoop.address, - randomUtxo(), - ); + const contractTestLogInsideLoopUtxo = provider.addUtxo(contractTestLogInsideLoop.address, randomUtxo()); it('should log correct values', async () => { const transaction = new TransactionBuilder({ provider }) @@ -50,7 +56,9 @@ describe('Debugging tests', () => { .addOutput({ to: contractTestLogs.address, amount: 10000n }); // console.log(ownerSig, owner, num, beef, 1, "test", true); - const expectedLog = new RegExp(`^\\[Input #0] Test.cash:10 0x[0-9a-f]{130} 0x${binToHex(alicePub)} 1000 0xbeef 1 test true$`); + const expectedLog = new RegExp( + `^\\[Input #0] Test.cash:10 0x[0-9a-f]{130} 0x${binToHex(alicePub)} 1000 0xbeef 1 test true$`, + ); expect(transaction).toLog(expectedLog); }); @@ -61,7 +69,9 @@ describe('Debugging tests', () => { .addOutput({ to: contractTestLogs.address, amount: 10000n }); // console.log(ownerSig, owner, num, beef, 1, "test", true); - const expectedLog = new RegExp(`^\\[Input #0] Test.cash:10 0x[0-9a-f]{130} 0x${binToHex(alicePub)} 100 0xbeef 1 test true$`); + const expectedLog = new RegExp( + `^\\[Input #0] Test.cash:10 0x[0-9a-f]{130} 0x${binToHex(alicePub)} 100 0xbeef 1 test true$`, + ); expect(transaction).toLog(expectedLog); }); @@ -71,7 +81,9 @@ describe('Debugging tests', () => { .addInput(contractUtxo, contractTestLogs.unlock.transfer(new SignatureTemplate(incorrectPriv), 1000n)) .addOutput({ to: contractTestLogs.address, amount: 10000n }); - const expectedLog = new RegExp(`^\\[Input #0] Test.cash:10 0x[0-9a-f]{130} 0x${binToHex(alicePub)} 1000 0xbeef 1 test true$`); + const expectedLog = new RegExp( + `^\\[Input #0] Test.cash:10 0x[0-9a-f]{130} 0x${binToHex(alicePub)} 1000 0xbeef 1 test true$`, + ); expect(transaction).not.toLog(expectedLog); }); @@ -99,10 +111,7 @@ describe('Debugging tests', () => { { provider }, ); - const utxo = provider.addUtxo( - contractTestMultipleConstructorParameters.address, - randomUtxo(), - ); + const utxo = provider.addUtxo(contractTestMultipleConstructorParameters.address, randomUtxo()); const transaction = new TransactionBuilder({ provider }) .addInput(utxo, contractTestMultipleConstructorParameters.unlock.secondFunction()) @@ -244,16 +253,10 @@ describe('Debugging tests', () => { const contractTestRequiresUtxo = provider.addUtxo(contractTestRequires.address, randomUtxo()); const contractTestMultiLineRequires = new Contract(artifactTestMultilineRequires, [], { provider }); - const contractTestMultiLineRequiresUtxo = provider.addUtxo( - contractTestMultiLineRequires.address, - randomUtxo(), - ); + const contractTestMultiLineRequiresUtxo = provider.addUtxo(contractTestMultiLineRequires.address, randomUtxo()); const contractTestRequireInsideLoop = new Contract(artifactTestRequireInsideLoop, [], { provider }); - const contractTestRequireInsideLoopUtxo = provider.addUtxo( - contractTestRequireInsideLoop.address, - randomUtxo(), - ); + const contractTestRequireInsideLoopUtxo = provider.addUtxo(contractTestRequireInsideLoop.address, randomUtxo()); // test_require it('should fail with error message when require statement fails in a multi-function contract', async () => { @@ -261,24 +264,25 @@ describe('Debugging tests', () => { .addInput(contractTestRequiresUtxo, contractTestRequires.unlock.test_require()) .addOutput({ to: contractTestRequires.address, amount: 1000n }); - expect(transaction).toFailRequireWith('Test.cash:13 Require statement failed at input 0 in contract Test.cash at line 13 with the following message: 1 should equal 2.'); + expect(transaction).toFailRequireWith( + 'Test.cash:13 Require statement failed at input 0 in contract Test.cash at line 13 with the following message: 1 should equal 2.', + ); expect(transaction).toFailRequireWith('Failing statement: require(1 == 2, "1 should equal 2")'); }); // test_require_single_function it('should fail with error message when require statement fails in single function', async () => { const contractSingleFunction = new Contract(artifactTestSingleFunction, [], { provider }); - const contractSingleFunctionUtxo = provider.addUtxo( - contractSingleFunction.address, - randomUtxo(), - ); + const contractSingleFunctionUtxo = provider.addUtxo(contractSingleFunction.address, randomUtxo()); const transaction = new TransactionBuilder({ provider }) .addInput(contractSingleFunctionUtxo, contractSingleFunction.unlock.test_require_single_function()) .addOutput({ to: contractSingleFunction.address, amount: 1000n }) .addOutput({ to: contractSingleFunction.address, amount: 1000n }); - expect(transaction).toFailRequireWith('Test.cash:4 Require statement failed at input 0 in contract Test.cash at line 4 with the following message: should have 1 output.'); + expect(transaction).toFailRequireWith( + 'Test.cash:4 Require statement failed at input 0 in contract Test.cash at line 4 with the following message: should have 1 output.', + ); expect(transaction).toFailRequireWith('Failing statement: require(tx.outputs.length == 1, "should have 1 output")'); }); @@ -292,7 +296,9 @@ describe('Debugging tests', () => { .addInput(contractFinalRequireVariableUtxo, contractFinalRequireVariable.unlock.test_final_require_variable(1n)) .addOutput({ to: contractFinalRequireVariable.address, amount: 1000n }); - expect(transaction).toFailRequireWith('Test.cash:5 Require statement failed at input 0 in contract Test.cash at line 5.'); + expect(transaction).toFailRequireWith( + 'Test.cash:5 Require statement failed at input 0 in contract Test.cash at line 5.', + ); expect(transaction).toFailRequireWith('Failing statement: require(isLarge)'); }); @@ -302,7 +308,9 @@ describe('Debugging tests', () => { .addInput(contractTestRequiresUtxo, contractTestRequires.unlock.test_multiple_require_statements()) .addOutput({ to: contractTestRequires.address, amount: 1000n }); - expect(transaction).toFailRequireWith('Test.cash:21 Require statement failed at input 0 in contract Test.cash at line 21 with the following message: 1 should equal 2.'); + expect(transaction).toFailRequireWith( + 'Test.cash:21 Require statement failed at input 0 in contract Test.cash at line 21 with the following message: 1 should equal 2.', + ); expect(transaction).toFailRequireWith('Failing statement: require(1 == 2, "1 should equal 2")'); expect(transaction).not.toFailRequireWith(/1 should equal 1/); }); @@ -313,7 +321,9 @@ describe('Debugging tests', () => { .addInput(contractTestRequiresUtxo, contractTestRequires.unlock.test_multiple_require_statements_final_fails()) .addOutput({ to: contractTestRequires.address, amount: 1000n }); - expect(transaction).toFailRequireWith('Test.cash:27 Require statement failed at input 0 in contract Test.cash at line 27 with the following message: 1 should equal 2.'); + expect(transaction).toFailRequireWith( + 'Test.cash:27 Require statement failed at input 0 in contract Test.cash at line 27 with the following message: 1 should equal 2.', + ); expect(transaction).toFailRequireWith('Failing statement: require(1 == 2, "1 should equal 2")'); expect(transaction).not.toFailRequireWith(/1 should equal 1/); }); @@ -332,7 +342,9 @@ describe('Debugging tests', () => { .addInput(contractTestRequiresUtxo, contractTestRequires.unlock.test_multiple_require_statements_no_message_final()) .addOutput({ to: contractTestRequires.address, amount: 1000n }); - expect(transaction).toFailRequireWith('Test.cash:32 Require statement failed at input 0 in contract Test.cash at line 32.'); + expect(transaction).toFailRequireWith( + 'Test.cash:32 Require statement failed at input 0 in contract Test.cash at line 32.', + ); expect(transaction).toFailRequireWith('Failing statement: require(1 == 2)'); expect(transaction).not.toFailRequireWith(/1 should equal 1/); }); @@ -343,7 +355,9 @@ describe('Debugging tests', () => { .addInput(contractTestRequiresUtxo, contractTestRequires.unlock.test_timeops_as_final_require()) .addOutput({ to: contractTestRequires.address, amount: 1000n }); - expect(transaction).toFailRequireWith('Test.cash:37 Require statement failed at input 0 in contract Test.cash at line 37 with the following message: time should be HUGE.'); + expect(transaction).toFailRequireWith( + 'Test.cash:37 Require statement failed at input 0 in contract Test.cash at line 37 with the following message: time should be HUGE.', + ); expect(transaction).toFailRequireWith('Failing statement: require(tx.time >= 100000000, "time should be HUGE")'); expect(transaction).not.toFailRequireWith(/1 should equal 1/); }); @@ -354,21 +368,27 @@ describe('Debugging tests', () => { .addInput(contractTestRequiresUtxo, contractTestRequires.unlock.test_final_require_in_if_statement(1n)) .addOutput({ to: contractTestRequires.address, amount: 1000n }); - expect(transactionIfBranch).toFailRequireWith('Test.cash:43 Require statement failed at input 0 in contract Test.cash at line 43 with the following message: 1 should equal 2.'); + expect(transactionIfBranch).toFailRequireWith( + 'Test.cash:43 Require statement failed at input 0 in contract Test.cash at line 43 with the following message: 1 should equal 2.', + ); expect(transactionIfBranch).toFailRequireWith('Failing statement: require(1 == a, "1 should equal 2")'); const transactionElseIfBranch = new TransactionBuilder({ provider }) .addInput(contractTestRequiresUtxo, contractTestRequires.unlock.test_final_require_in_if_statement(2n)) .addOutput({ to: contractTestRequires.address, amount: 1000n }); - expect(transactionElseIfBranch).toFailRequireWith('Test.cash:46 Require statement failed at input 0 in contract Test.cash at line 46 with the following message: 1 should equal 3.'); + expect(transactionElseIfBranch).toFailRequireWith( + 'Test.cash:46 Require statement failed at input 0 in contract Test.cash at line 46 with the following message: 1 should equal 3.', + ); expect(transactionElseIfBranch).toFailRequireWith('Failing statement: require(1 == b, "1 should equal 3")'); const transactionElseBranch = new TransactionBuilder({ provider }) .addInput(contractTestRequiresUtxo, contractTestRequires.unlock.test_final_require_in_if_statement(3n)) .addOutput({ to: contractTestRequires.address, amount: 1000n }); - expect(transactionElseBranch).toFailRequireWith('Test.cash:49 Require statement failed at input 0 in contract Test.cash at line 49 with the following message: switch should equal 4.'); + expect(transactionElseBranch).toFailRequireWith( + 'Test.cash:49 Require statement failed at input 0 in contract Test.cash at line 49 with the following message: switch should equal 4.', + ); expect(transactionElseBranch).toFailRequireWith('Failing statement: require(switch == c, "switch should equal 4")'); }); @@ -381,7 +401,9 @@ describe('Debugging tests', () => { ) .addOutput({ to: contractTestRequires.address, amount: 1000n }); - expect(transaction).toFailRequireWith('Test.cash:62 Require statement failed at input 0 in contract Test.cash at line 62 with the following message: sum should equal 10.'); + expect(transaction).toFailRequireWith( + 'Test.cash:62 Require statement failed at input 0 in contract Test.cash at line 62 with the following message: sum should equal 10.', + ); expect(transaction).toFailRequireWith('Failing statement: require(a + b + c + d + e == 10, "sum should equal 10")'); }); @@ -394,18 +416,23 @@ describe('Debugging tests', () => { ) .addOutput({ to: contractTestRequires.address, amount: 1000n }); - expect(checkSigTransaction).toFailRequireWith('Test.cash:77 Require statement failed at input 0 in contract Test.cash at line 77 with the following message: Signatures do not match.'); - expect(checkSigTransaction).toFailRequireWith('Failing statement: require(checkSig(s, pk), "Signatures do not match")'); + expect(checkSigTransaction).toFailRequireWith( + 'Test.cash:77 Require statement failed at input 0 in contract Test.cash at line 77 with the following message: Signatures do not match.', + ); + expect(checkSigTransaction).toFailRequireWith( + 'Failing statement: require(checkSig(s, pk), "Signatures do not match")', + ); const checkSigTransactionNullSignature = new TransactionBuilder({ provider }) - .addInput( - contractTestRequiresUtxo, - contractTestRequires.unlock.test_fail_checksig(hexToBin(''), bobPub), - ) + .addInput(contractTestRequiresUtxo, contractTestRequires.unlock.test_fail_checksig(hexToBin(''), bobPub)) .addOutput({ to: contractTestRequires.address, amount: 1000n }); - expect(checkSigTransactionNullSignature).toFailRequireWith('Test.cash:77 Require statement failed at input 0 in contract Test.cash at line 77 with the following message: Signatures do not match.'); - expect(checkSigTransactionNullSignature).toFailRequireWith('Failing statement: require(checkSig(s, pk), "Signatures do not match")'); + expect(checkSigTransactionNullSignature).toFailRequireWith( + 'Test.cash:77 Require statement failed at input 0 in contract Test.cash at line 77 with the following message: Signatures do not match.', + ); + expect(checkSigTransactionNullSignature).toFailRequireWith( + 'Failing statement: require(checkSig(s, pk), "Signatures do not match")', + ); }); // test_fail_checksig_final_verify @@ -417,8 +444,12 @@ describe('Debugging tests', () => { ) .addOutput({ to: contractTestRequires.address, amount: 1000n }); - expect(checkSigTransaction).toFailRequireWith('Test.cash:82 Require statement failed at input 0 in contract Test.cash at line 82 with the following message: Signatures do not match.'); - expect(checkSigTransaction).toFailRequireWith('Failing statement: require(checkSig(s, pk), "Signatures do not match")'); + expect(checkSigTransaction).toFailRequireWith( + 'Test.cash:82 Require statement failed at input 0 in contract Test.cash at line 82 with the following message: Signatures do not match.', + ); + expect(checkSigTransaction).toFailRequireWith( + 'Failing statement: require(checkSig(s, pk), "Signatures do not match")', + ); }); // test_fail_checkdatasig @@ -426,22 +457,38 @@ describe('Debugging tests', () => { const checkDataSigTransaction = new TransactionBuilder({ provider }) .addInput( contractTestRequiresUtxo, - contractTestRequires.unlock.test_fail_checkdatasig(new SignatureTemplate(alicePriv).generateSignature(hexToBin('0xbeef')).slice(0, -1), '0xbeef', bobPub), + contractTestRequires.unlock.test_fail_checkdatasig( + new SignatureTemplate(alicePriv).generateSignature(hexToBin('0xbeef')).slice(0, -1), + '0xbeef', + bobPub, + ), ) .addOutput({ to: contractTestRequires.address, amount: 1000n }); - expect(checkDataSigTransaction).toFailRequireWith('Test.cash:86 Require statement failed at input 0 in contract Test.cash at line 86 with the following message: Data Signatures do not match.'); - expect(checkDataSigTransaction).toFailRequireWith('Failing statement: require(checkDataSig(s, message, pk), "Data Signatures do not match")'); + expect(checkDataSigTransaction).toFailRequireWith( + 'Test.cash:86 Require statement failed at input 0 in contract Test.cash at line 86 with the following message: Data Signatures do not match.', + ); + expect(checkDataSigTransaction).toFailRequireWith( + 'Failing statement: require(checkDataSig(s, message, pk), "Data Signatures do not match")', + ); const checkDataSigTransactionWrongMessage = new TransactionBuilder({ provider }) .addInput( contractTestRequiresUtxo, - contractTestRequires.unlock.test_fail_checkdatasig(new SignatureTemplate(alicePriv).generateSignature(hexToBin('0xc0ffee')).slice(0, -1), '0xbeef', alicePub), + contractTestRequires.unlock.test_fail_checkdatasig( + new SignatureTemplate(alicePriv).generateSignature(hexToBin('0xc0ffee')).slice(0, -1), + '0xbeef', + alicePub, + ), ) .addOutput({ to: contractTestRequires.address, amount: 1000n }); - expect(checkDataSigTransactionWrongMessage).toFailRequireWith('Test.cash:86 Require statement failed at input 0 in contract Test.cash at line 86 with the following message: Data Signatures do not match.'); - expect(checkDataSigTransactionWrongMessage).toFailRequireWith('Failing statement: require(checkDataSig(s, message, pk), "Data Signatures do not match")'); + expect(checkDataSigTransactionWrongMessage).toFailRequireWith( + 'Test.cash:86 Require statement failed at input 0 in contract Test.cash at line 86 with the following message: Data Signatures do not match.', + ); + expect(checkDataSigTransactionWrongMessage).toFailRequireWith( + 'Failing statement: require(checkDataSig(s, message, pk), "Data Signatures do not match")', + ); }); // test_fail_checkmultisig @@ -458,33 +505,35 @@ describe('Debugging tests', () => { ) .addOutput({ to: contractTestRequires.address, amount: 1000n }); - expect(checkmultiSigTransaction).toFailRequireWith('Test.cash:90 Require statement failed at input 0 in contract Test.cash at line 90 with the following message: Multi Signatures do not match.'); - expect(checkmultiSigTransaction).toFailRequireWith('Failing statement: require(checkMultiSig([s1, s2], [pk1, pk2]), "Multi Signatures do not match")'); + expect(checkmultiSigTransaction).toFailRequireWith( + 'Test.cash:90 Require statement failed at input 0 in contract Test.cash at line 90 with the following message: Multi Signatures do not match.', + ); + expect(checkmultiSigTransaction).toFailRequireWith( + 'Failing statement: require(checkMultiSig([s1, s2], [pk1, pk2]), "Multi Signatures do not match")', + ); }); // test_fail_large_cleanup it('should fail with correct error message when a require statement fails in a function with a large cleanup', async () => { const transaction = new TransactionBuilder({ provider }) - .addInput( - contractTestMultiLineRequiresUtxo, - contractTestMultiLineRequires.unlock.test_fail_large_cleanup(), - ) + .addInput(contractTestMultiLineRequiresUtxo, contractTestMultiLineRequires.unlock.test_fail_large_cleanup()) .addOutput({ to: contractTestMultiLineRequires.address, amount: 1000n }); - expect(transaction).toFailRequireWith('Test.cash:22 Require statement failed at input 0 in contract Test.cash at line 22 with the following message: 1 should equal 2.'); + expect(transaction).toFailRequireWith( + 'Test.cash:22 Require statement failed at input 0 in contract Test.cash at line 22 with the following message: 1 should equal 2.', + ); expect(transaction).toFailRequireWith('Failing statement: require(1 == 2, "1 should equal 2")'); }); // test_fail_multiline_require it('should fail with correct error message and statement when a multiline require statement fails', async () => { const transaction = new TransactionBuilder({ provider }) - .addInput( - contractTestMultiLineRequiresUtxo, - contractTestMultiLineRequires.unlock.test_fail_multiline_require(), - ) + .addInput(contractTestMultiLineRequiresUtxo, contractTestMultiLineRequires.unlock.test_fail_multiline_require()) .addOutput({ to: contractTestMultiLineRequires.address, amount: 1000n }); - expect(transaction).toFailRequireWith('Test.cash:26 Require statement failed at input 0 in contract Test.cash at line 26 with the following message: 1 should equal 2.'); + expect(transaction).toFailRequireWith( + 'Test.cash:26 Require statement failed at input 0 in contract Test.cash at line 26 with the following message: 1 should equal 2.', + ); expect(transaction).toFailRequireWith(`Failing statement: require( 1 == 2, "1 should equal 2" @@ -500,7 +549,9 @@ describe('Debugging tests', () => { ) .addOutput({ to: contractTestMultiLineRequires.address, amount: 1000n }); - expect(transaction).toFailRequireWith('Test.cash:35 Require statement failed at input 0 in contract Test.cash at line 35 with the following message: 1 should equal 2.'); + expect(transaction).toFailRequireWith( + 'Test.cash:35 Require statement failed at input 0 in contract Test.cash at line 35 with the following message: 1 should equal 2.', + ); expect(transaction).toFailRequireWith(`Failing statement: require( 1 == 2, "1 should equal 2" @@ -517,7 +568,9 @@ describe('Debugging tests', () => { ) .addOutput({ to: contractTestMultiLineRequires.address, amount: 1000n }); - expect(transaction).toFailRequireWith('Test.cash:51 Require statement failed at input 0 in contract Test.cash at line 51.'); + expect(transaction).toFailRequireWith( + 'Test.cash:51 Require statement failed at input 0 in contract Test.cash at line 51.', + ); expect(transaction).toFailRequireWith(`Failing statement: require( !( 0x000000 @@ -542,7 +595,9 @@ describe('Debugging tests', () => { ) .addOutput({ to: contractTestMultiLineRequires.address, amount: 1000n }); - expect(transaction).toFailRequireWith('Test.cash:69 Require statement failed at input 0 in contract Test.cash at line 69.'); + expect(transaction).toFailRequireWith( + 'Test.cash:69 Require statement failed at input 0 in contract Test.cash at line 69.', + ); expect(transaction).toFailRequireWith(`Failing statement: require( new LockingBytecodeP2PKH( hash160(0x000000) @@ -560,8 +615,10 @@ describe('Debugging tests', () => { .addInput(contractTestRequireInsideLoopUtxo, contractTestRequireInsideLoop.unlock.test_require_inside_loop()) .addOutput({ to: contractTestRequireInsideLoop.address, amount: 10000n }); - expect(transaction).toFailRequireWith('Test.cash:7 Require statement failed at input 0 in contract Test.cash at line 7 with the following message: i should be less than 6.'); - expect(transaction).toFailRequireWith('Failing statement: require(i < 6, \'i should be less than 6\')'); + expect(transaction).toFailRequireWith( + 'Test.cash:7 Require statement failed at input 0 in contract Test.cash at line 7 with the following message: i should be less than 6.', + ); + expect(transaction).toFailRequireWith("Failing statement: require(i < 6, 'i should be less than 6')"); }); it('should fail a require statement inside a while loop', async () => { @@ -569,8 +626,10 @@ describe('Debugging tests', () => { .addInput(contractTestRequireInsideLoopUtxo, contractTestRequireInsideLoop.unlock.test_require_inside_while_loop()) .addOutput({ to: contractTestRequireInsideLoop.address, amount: 10000n }); - expect(transaction).toFailRequireWith('Test.cash:16 Require statement failed at input 0 in contract Test.cash at line 16 with the following message: while i should be less than 6.'); - expect(transaction).toFailRequireWith('Failing statement: require(i < 6, \'while i should be less than 6\')'); + expect(transaction).toFailRequireWith( + 'Test.cash:16 Require statement failed at input 0 in contract Test.cash at line 16 with the following message: while i should be less than 6.', + ); + expect(transaction).toFailRequireWith("Failing statement: require(i < 6, 'while i should be less than 6')"); }); it('should fail a require statement inside a for loop', async () => { @@ -578,8 +637,10 @@ describe('Debugging tests', () => { .addInput(contractTestRequireInsideLoopUtxo, contractTestRequireInsideLoop.unlock.test_require_inside_for_loop()) .addOutput({ to: contractTestRequireInsideLoop.address, amount: 10000n }); - expect(transaction).toFailRequireWith('Test.cash:26 Require statement failed at input 0 in contract Test.cash at line 26 with the following message: for i should be less than 2.'); - expect(transaction).toFailRequireWith('Failing statement: require(i < 2, \'for i should be less than 2\')'); + expect(transaction).toFailRequireWith( + 'Test.cash:26 Require statement failed at input 0 in contract Test.cash at line 26 with the following message: for i should be less than 2.', + ); + expect(transaction).toFailRequireWith("Failing statement: require(i < 2, 'for i should be less than 2')"); }); it('should fail the correct require statement inside complex nested loops', async () => { @@ -587,8 +648,10 @@ describe('Debugging tests', () => { .addInput(contractTestRequireInsideLoopUtxo, contractTestRequireInsideLoop.unlock.test_require_inside_loop_complex()) .addOutput({ to: contractTestRequireInsideLoop.address, amount: 10000n }); - expect(transaction).toFailRequireWith('Test.cash:41 Require statement failed at input 0 in contract Test.cash at line 41 with the following message: k should be less than 2.'); - expect(transaction).toFailRequireWith('Failing statement: require(k < 2, \'k should be less than 2\')'); + expect(transaction).toFailRequireWith( + 'Test.cash:41 Require statement failed at input 0 in contract Test.cash at line 41 with the following message: k should be less than 2.', + ); + expect(transaction).toFailRequireWith("Failing statement: require(k < 2, 'k should be less than 2')"); }); }); @@ -599,21 +662,17 @@ describe('Debugging tests', () => { const contractTestRequiresUtxo = provider.addUtxo(contractTestRequires.address, randomUtxo()); const contractTestMultiLineRequires = new Contract(artifactTestMultilineRequires, [], { provider }); - const contractTestMultiLineRequiresUtxo = provider.addUtxo( - contractTestMultiLineRequires.address, - randomUtxo(), - ); + const contractTestMultiLineRequiresUtxo = provider.addUtxo(contractTestMultiLineRequires.address, randomUtxo()); // test_invalid_split_range it('should fail with correct error message when an invalid OP_SPLIT range is used', async () => { const transaction = new TransactionBuilder({ provider }) - .addInput( - contractTestRequiresUtxo, - contractTestRequires.unlock.test_invalid_split_range(), - ) + .addInput(contractTestRequiresUtxo, contractTestRequires.unlock.test_invalid_split_range()) .addOutput({ to: contractTestRequires.address, amount: 1000n }); - expect(() => transaction.debug()).toThrow('Test.cash:68 Error in transaction at input 0 in contract Test.cash at line 68.'); + expect(() => transaction.debug()).toThrow( + 'Test.cash:68 Error in transaction at input 0 in contract Test.cash at line 68.', + ); expect(() => transaction.debug()).toThrow('Failing statement: test.split(4)'); expect(() => transaction.debug()).toThrow(`Reason: ${AuthenticationErrorCommon.invalidSplitIndex}`); }); @@ -621,13 +680,12 @@ describe('Debugging tests', () => { // test_invalid_input_index it('should fail with correct error message when an invalid input index is used', async () => { const transaction = new TransactionBuilder({ provider }) - .addInput( - contractTestRequiresUtxo, - contractTestRequires.unlock.test_invalid_input_index(), - ) + .addInput(contractTestRequiresUtxo, contractTestRequires.unlock.test_invalid_input_index()) .addOutput({ to: contractTestRequires.address, amount: 1000n }); - expect(() => transaction.debug()).toThrow('Test.cash:73 Error in transaction at input 0 in contract Test.cash at line 73.'); + expect(() => transaction.debug()).toThrow( + 'Test.cash:73 Error in transaction at input 0 in contract Test.cash at line 73.', + ); expect(() => transaction.debug()).toThrow('Failing statement: tx.inputs[5].value'); expect(() => transaction.debug()).toThrow(`Reason: ${AuthenticationErrorCommon.invalidTransactionUtxoIndex}`); }); @@ -635,13 +693,12 @@ describe('Debugging tests', () => { // test_multiline_non_require_error it('should fail with correct error message and statement when a multiline non-require statement fails', async () => { const transaction = new TransactionBuilder({ provider }) - .addInput( - contractTestMultiLineRequiresUtxo, - contractTestMultiLineRequires.unlock.test_multiline_non_require_error(), - ) + .addInput(contractTestMultiLineRequiresUtxo, contractTestMultiLineRequires.unlock.test_multiline_non_require_error()) .addOutput({ to: contractTestMultiLineRequires.address, amount: 1000n }); - expect(() => transaction.debug()).toThrow('Test.cash:43 Error in transaction at input 0 in contract Test.cash at line 43.'); + expect(() => transaction.debug()).toThrow( + 'Test.cash:43 Error in transaction at input 0 in contract Test.cash at line 43.', + ); expect(() => transaction.debug()).toThrow(`Failing statement: tx.outputs[ 5 ].value`); @@ -710,90 +767,70 @@ describe('Debugging tests', () => { it('should fail the TestExtensions test if an incorrect log is expected', async () => { const transaction = new TransactionBuilder({ provider }) - .addInput( - contractTestRequiresUtxo, - contractTestRequires.unlock.test_logs(), - ) + .addInput(contractTestRequiresUtxo, contractTestRequires.unlock.test_logs()) .addOutput({ to: contractTestRequires.address, amount: 10000n }); - expect( - () => expect(transaction).toLog('^This is definitely not the log$'), - ).toThrow(/Expected: .*This is definitely not the log.*\nReceived: (.|\n)*?\[Input #0] Test.cash:4 Hello World/); + expect(() => expect(transaction).toLog('^This is definitely not the log$')).toThrow( + /Expected: .*This is definitely not the log.*\nReceived: (.|\n)*?\[Input #0] Test.cash:4 Hello World/, + ); }); it('should fail the TestExtensions test if a log is logged that is NOT expected', async () => { const transaction = new TransactionBuilder({ provider }) - .addInput( - contractTestRequiresUtxo, - contractTestRequires.unlock.test_logs(), - ) + .addInput(contractTestRequiresUtxo, contractTestRequires.unlock.test_logs()) .addOutput({ to: contractTestRequires.address, amount: 10000n }); - expect( - () => expect(transaction).not.toLog('^\\[Input #0] Test.cash:4 Hello World$'), - ).toThrow( + expect(() => expect(transaction).not.toLog('^\\[Input #0] Test.cash:4 Hello World$')).toThrow( /Expected: not .*\[Input #0] Test.cash:4 Hello World.*\nReceived: (.|\n)*?\[Input #0] Test.cash:4 Hello World/, ); - expect( - () => expect(transaction).not.toLog(), - ).toThrow(/Expected: not .*undefined.*\nReceived: (.|\n)*?\[Input #0] Test.cash:4 Hello World/); + expect(() => expect(transaction).not.toLog()).toThrow( + /Expected: not .*undefined.*\nReceived: (.|\n)*?\[Input #0] Test.cash:4 Hello World/, + ); }); it('should fail the TestExtensions test if a log is expected where no log is logged', async () => { const transaction = new TransactionBuilder({ provider }) - .addInput( - contractTestRequiresUtxo, - contractTestRequires.unlock.test_no_logs(), - ) + .addInput(contractTestRequiresUtxo, contractTestRequires.unlock.test_no_logs()) .addOutput({ to: contractTestRequires.address, amount: 10000n }); - expect( - () => expect(transaction).toLog('Hello World'), - ).toThrow(/Expected: .*Hello World.*\nReceived: (.|\n)*?undefined/); + expect(() => expect(transaction).toLog('Hello World')).toThrow( + /Expected: .*Hello World.*\nReceived: (.|\n)*?undefined/, + ); }); it('should fail the TestExtensions test if an incorrect require error message is expected', async () => { const transaction = new TransactionBuilder({ provider }) - .addInput( - contractTestRequiresUtxo, - contractTestRequires.unlock.test_require(), - ) + .addInput(contractTestRequiresUtxo, contractTestRequires.unlock.test_require()) .addOutput({ to: contractTestRequires.address, amount: 10000n }); - expect( - () => expect(transaction).toFailRequireWith('1 should equal 3'), - ).toThrow(/Expected pattern: .*1 should equal 3.*\nReceived string: (.|\n)*?1 should equal 2/); + expect(() => expect(transaction).toFailRequireWith('1 should equal 3')).toThrow( + /Expected pattern: .*1 should equal 3.*\nReceived string: (.|\n)*?1 should equal 2/, + ); }); it('should fail the TestExtensions test if a require error message is expected where no error is thrown', async () => { const transaction = new TransactionBuilder({ provider }) - .addInput( - contractTestRequiresUtxo, - contractTestRequires.unlock.test_require_no_failure(), - ) + .addInput(contractTestRequiresUtxo, contractTestRequires.unlock.test_require_no_failure()) .addOutput({ to: contractTestRequires.address, amount: 10000n }); - expect( - () => expect(transaction).toFailRequireWith('1 should equal 3'), - ).toThrow(/Contract function did not fail a require statement/); + expect(() => expect(transaction).toFailRequireWith('1 should equal 3')).toThrow( + /Contract function did not fail a require statement/, + ); }); it('should fail the TestExtensions test if an error is thrown where it is NOT expected', async () => { const transaction = new TransactionBuilder({ provider }) - .addInput( - contractTestRequiresUtxo, - contractTestRequires.unlock.test_require(), - ) + .addInput(contractTestRequiresUtxo, contractTestRequires.unlock.test_require()) .addOutput({ to: contractTestRequires.address, amount: 10000n }); - expect( - () => expect(transaction).not.toFailRequireWith('1 should equal 2'), - ).toThrow(/Expected pattern: not .*1 should equal 2.*\nReceived string: (.|\n)*?1 should equal 2/); + expect(() => expect(transaction).not.toFailRequireWith('1 should equal 2')).toThrow( + /Expected pattern: not .*1 should equal 2.*\nReceived string: (.|\n)*?1 should equal 2/, + ); - expect( - () => expect(transaction).not.toFailRequire(), - ).toThrow(/Contract function failed a require statement\.*\nReceived string: (.|\n)*?1 should equal 2/); + expect(() => expect(transaction).not.toFailRequire()).toThrow( + /Contract function failed a require statement\.*\nReceived string: (.|\n)*?1 should equal 2/, + ); }); }); @@ -818,9 +855,9 @@ describe('Debugging tests', () => { const utxos = await provider.getUtxos(aliceAddress); - expect(() => ( - new TransactionBuilder({ provider }).addInputs(utxos, new SignatureTemplate(bobPriv).unlockP2PKH()) - )).toThrow(UnlockerLockingBytecodeMismatchError); + expect(() => + new TransactionBuilder({ provider }).addInputs(utxos, new SignatureTemplate(bobPriv).unlockP2PKH()), + ).toThrow(UnlockerLockingBytecodeMismatchError); }); }); @@ -844,7 +881,9 @@ describe('Debugging tests', () => { expect(transaction.getLibauthTemplate().supported[0]).toBe(vmTarget ?? DEFAULT_VM_TARGET); - const expectedLog = new RegExp(`^\\[Input #0] Test.cash:10 0x[0-9a-f]{130} 0x${binToHex(alicePub)} 1000 0xbeef 1 test true$`); + const expectedLog = new RegExp( + `^\\[Input #0] Test.cash:10 0x[0-9a-f]{130} 0x${binToHex(alicePub)} 1000 0xbeef 1 test true$`, + ); expect(transaction).toLog(expectedLog); }); }); @@ -854,8 +893,12 @@ describe('VM Resources', () => { it('Should output VM resource usage', async () => { const provider = new MockNetworkProvider(); - const contractSingleFunction = new Contract({ ...artifactTestSingleFunction, contractName: 'SingleFunction' }, [], { provider }); - const contractZeroHandling = new Contract({ ...artifactTestZeroHandling, contractName: 'ZeroHandling' }, [0n], { provider }); + const contractSingleFunction = new Contract({ ...artifactTestSingleFunction, contractName: 'SingleFunction' }, [], { + provider, + }); + const contractZeroHandling = new Contract({ ...artifactTestZeroHandling, contractName: 'ZeroHandling' }, [0n], { + provider, + }); provider.addUtxo(contractSingleFunction.address, randomUtxo()); provider.addUtxo(contractZeroHandling.address, randomUtxo()); @@ -915,7 +958,9 @@ describe('Debugging tests - user-defined function frames', () => { // The artifact's inline ranges tie the merged require back to the function's own frame, so // inlining is transparent: the failure reads like the defined variant below - expect(transaction).toFailRequireWith('Test.cash:4 Require statement failed at input 0 in contract Test, function checkValue (Test.cash, line 4) with the following message: value must be positive.'); + expect(transaction).toFailRequireWith( + 'Test.cash:4 Require statement failed at input 0 in contract Test, function checkValue (Test.cash, line 4) with the following message: value must be positive.', + ); expect(transaction).toFailRequireWith('Failing statement: require(value > 0, "value must be positive")'); }); @@ -924,7 +969,9 @@ describe('Debugging tests - user-defined function frames', () => { .addInput(contractUtxo, contract.unlock.spend(100n)) .addOutput({ to: contract.address, amount: 10000n }); - expect(transaction).toFailRequireWith('Test.cash:10 Require statement failed at input 0 in contract Test.cash at line 10 with the following message: x must be small.'); + expect(transaction).toFailRequireWith( + 'Test.cash:10 Require statement failed at input 0 in contract Test.cash at line 10 with the following message: x must be small.', + ); expect(transaction).toFailRequireWith('Failing statement: require(x < 100, "x must be small")'); }); @@ -936,7 +983,9 @@ describe('Debugging tests - user-defined function frames', () => { .addInput(nestedUtxo, nestedContract.unlock.spend(0n)) .addOutput({ to: nestedContract.address, amount: 10000n }); - expect(transaction).toFailRequireWith('Test.cash:3 Require statement failed at input 0 in contract Test, function assertPositive (Test.cash, line 3) with the following message: value must be positive.'); + expect(transaction).toFailRequireWith( + 'Test.cash:3 Require statement failed at input 0 in contract Test, function assertPositive (Test.cash, line 3) with the following message: value must be positive.', + ); expect(transaction).toFailRequireWith(` at assertPositive (Test.cash:3) — require(value > 0, "value must be positive"); at validate (Test.cash:7) — assertPositive(amount) at Test.cash:13 — validate(x)`); @@ -952,7 +1001,9 @@ describe('Debugging tests - user-defined function frames', () => { // The trace is identical to the inlined variant: runtime callers come from the VM's control // stack instead of inline ranges, but the displayed stack is the same - expect(transaction).toFailRequireWith('Test.cash:3 Require statement failed at input 0 in contract Test, function assertPositive (Test.cash, line 3) with the following message: value must be positive.'); + expect(transaction).toFailRequireWith( + 'Test.cash:3 Require statement failed at input 0 in contract Test, function assertPositive (Test.cash, line 3) with the following message: value must be positive.', + ); expect(transaction).toFailRequireWith(` at assertPositive (Test.cash:3) — require(value > 0, "value must be positive"); at validate (Test.cash:7) — assertPositive(amount) at Test.cash:13 — validate(x)`); @@ -966,8 +1017,11 @@ describe('Debugging tests - user-defined function frames', () => { .addInput(nestedUtxo, nestedContract.unlock.spend(0n)) .addOutput({ to: nestedContract.address, amount: 10000n }); - expect(transaction).toFailRequireWith('nested_helpers.cash:3 Require statement failed at input 0 in contract Test, function assertPositive (nested_helpers.cash, line 3) with the following message: value must be positive.'); - expect(transaction).toFailRequireWith(` at assertPositive (nested_helpers.cash:3) — require(value > 0, "value must be positive"); + expect(transaction).toFailRequireWith( + 'nested_helpers.cash:3 Require statement failed at input 0 in contract Test, function assertPositive (nested_helpers.cash, line 3) with the following message: value must be positive.', + ); + expect(transaction) + .toFailRequireWith(` at assertPositive (nested_helpers.cash:3) — require(value > 0, "value must be positive"); at validate (nested_helpers.cash:7) — assertPositive(amount) at Test.cash:6 — validate(x)`); }); @@ -982,7 +1036,9 @@ describe('Debugging tests - user-defined function frames', () => { // The invoke of bigCheck sits inside the inlined wrapper's body within the contract; the // inline range and the invoke's position within it give wrapper its own hop - expect(transaction).toFailRequireWith('Test.cash:3 Require statement failed at input 0 in contract Test, function bigCheck (Test.cash, line 3) with the following message: v must be positive.'); + expect(transaction).toFailRequireWith( + 'Test.cash:3 Require statement failed at input 0 in contract Test, function bigCheck (Test.cash, line 3) with the following message: v must be positive.', + ); expect(transaction).toFailRequireWith(` at bigCheck (Test.cash:3) — require(v > 0, "v must be positive"); at wrapper (Test.cash:8) — bigCheck(v) at Test.cash:13 — wrapper(x)`); @@ -999,7 +1055,9 @@ describe('Debugging tests - user-defined function frames', () => { // The inlined innerCheck attributes through deepHelper's inline ranges; the runtime hops come // from the VM's control stack, with the inlined middle recovered from the position of the // deepHelper invoke within middle's inline range in outerHelper - expect(transaction).toFailRequireWith('Test.cash:3 Require statement failed at input 0 in contract Test, function innerCheck (Test.cash, line 3) with the following message: v must be positive.'); + expect(transaction).toFailRequireWith( + 'Test.cash:3 Require statement failed at input 0 in contract Test, function innerCheck (Test.cash, line 3) with the following message: v must be positive.', + ); expect(transaction).toFailRequireWith(` at innerCheck (Test.cash:3) — require(v > 0, "v must be positive"); at deepHelper (Test.cash:7) — innerCheck(v) at middle (Test.cash:12) — deepHelper(v) @@ -1015,7 +1073,9 @@ describe('Debugging tests - user-defined function frames', () => { .addInput(multilineUtxo, multilineContract.unlock.spend(0n)) .addOutput({ to: multilineContract.address, amount: 10000n }); - expect(transaction).toFailRequireWith('Test.cash:3 Require statement failed at input 0 in contract Test, function checkRange (Test.cash, line 3) with the following message: value must be positive.'); + expect(transaction).toFailRequireWith( + 'Test.cash:3 Require statement failed at input 0 in contract Test, function checkRange (Test.cash, line 3) with the following message: value must be positive.', + ); expect(transaction).toFailRequireWith(`Failing statement: require( value > 0, "value must be positive" @@ -1031,7 +1091,9 @@ describe('Debugging tests - user-defined function frames', () => { // Inlining is transparent for debugging: the failure reads exactly like the defined // (OP_DEFINE'd) form of the same function — see the defined variants below - expect(transaction).toFailRequireWith('function_helpers.cash:3 Require statement failed at input 0 in contract Test, function assertPositive (function_helpers.cash, line 3) with the following message: value must be positive.'); + expect(transaction).toFailRequireWith( + 'function_helpers.cash:3 Require statement failed at input 0 in contract Test, function assertPositive (function_helpers.cash, line 3) with the following message: value must be positive.', + ); expect(transaction).toFailRequireWith('Failing statement: require(value > 0, "value must be positive")'); }); @@ -1056,7 +1118,9 @@ describe('Debugging tests - user-defined function frames', () => { .addInput(importedDefinedUtxo, importedDefinedContract.unlock.spend(0n)) .addOutput({ to: importedDefinedContract.address, amount: 10000n }); - expect(transaction).toFailRequireWith('function_helpers.cash:3 Require statement failed at input 0 in contract Test, function assertPositive (function_helpers.cash, line 3) with the following message: value must be positive.'); + expect(transaction).toFailRequireWith( + 'function_helpers.cash:3 Require statement failed at input 0 in contract Test, function assertPositive (function_helpers.cash, line 3) with the following message: value must be positive.', + ); expect(transaction).toFailRequireWith('Failing statement: require(value > 0, "value must be positive")'); }); @@ -1076,7 +1140,9 @@ describe('Debugging tests - user-defined function frames', () => { .addInput(multiReturnUtxo, multiReturnContract.unlock.spend(14n)) .addOutput({ to: multiReturnContract.address, amount: 10000n }); - expect(failingTransaction).toFailRequireWith('Test.cash:10 Require statement failed at input 0 in contract Test.cash at line 10 with the following message: remainder should be 1.'); + expect(failingTransaction).toFailRequireWith( + 'Test.cash:10 Require statement failed at input 0 in contract Test.cash at line 10 with the following message: remainder should be 1.', + ); }); it('logs intermediate results that get optimised out inside a function', () => { diff --git a/packages/cashscript/test/e2e/Announcement.test.ts b/packages/cashscript/test/e2e/Announcement.test.ts index 32bede6e5..9d0ff94c5 100644 --- a/packages/cashscript/test/e2e/Announcement.test.ts +++ b/packages/cashscript/test/e2e/Announcement.test.ts @@ -6,9 +6,7 @@ import { aliceAddress } from '../fixture/vars.js'; import artifact from '../fixture/announcement.artifact.js'; describe('Announcement', () => { - const provider = process.env.TESTS_USE_CHIPNET - ? new ElectrumNetworkProvider(Network.CHIPNET) - : new MockNetworkProvider(); + const provider = process.env.TESTS_USE_CHIPNET ? new ElectrumNetworkProvider(Network.CHIPNET) : new MockNetworkProvider(); const announcement = new Contract(artifact, [], { provider }); const minerFee = 1000n; @@ -33,7 +31,9 @@ describe('Announcement', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('Announcement.cash:16 Require statement failed at input 0 in contract Announcement.cash at line 16.'); + await expect(txPromise).rejects.toThrow( + 'Announcement.cash:16 Require statement failed at input 0 in contract Announcement.cash at line 16.', + ); await expect(txPromise).rejects.toThrow('Failing statement: require(tx.outputs[0].value == 0)'); }); @@ -50,7 +50,9 @@ describe('Announcement', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('Announcement.cash:17 Require statement failed at input 0 in contract Announcement.cash at line 17.'); + await expect(txPromise).rejects.toThrow( + 'Announcement.cash:17 Require statement failed at input 0 in contract Announcement.cash at line 17.', + ); await expect(txPromise).rejects.toThrow('Failing statement: require(tx.outputs[0].lockingBytecode == announcement)'); }); @@ -70,7 +72,9 @@ describe('Announcement', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('Announcement.cash:25 Require statement failed at input 0 in contract Announcement.cash at line 25.'); + await expect(txPromise).rejects.toThrow( + 'Announcement.cash:25 Require statement failed at input 0 in contract Announcement.cash at line 25.', + ); await expect(txPromise).rejects.toThrow('Failing statement: require(tx.outputs[1].value == changeAmount)'); }); @@ -89,8 +93,12 @@ describe('Announcement', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('Announcement.cash:24 Require statement failed at input 0 in contract Announcement.cash at line 24.'); - await expect(txPromise).rejects.toThrow('Failing statement: require(tx.outputs[1].lockingBytecode == tx.inputs[this.activeInputIndex].lockingBytecode)'); + await expect(txPromise).rejects.toThrow( + 'Announcement.cash:24 Require statement failed at input 0 in contract Announcement.cash at line 24.', + ); + await expect(txPromise).rejects.toThrow( + 'Failing statement: require(tx.outputs[1].lockingBytecode == tx.inputs[this.activeInputIndex].lockingBytecode)', + ); }); it('should succeed when announcing correct announcement', async () => { diff --git a/packages/cashscript/test/e2e/BigInt.test.ts b/packages/cashscript/test/e2e/BigInt.test.ts index e003f4596..793bbeb8b 100644 --- a/packages/cashscript/test/e2e/BigInt.test.ts +++ b/packages/cashscript/test/e2e/BigInt.test.ts @@ -11,9 +11,7 @@ import { randomUtxo } from '../../src/utils.js'; import { addUtxo, gatherUtxos } from '../test-util.js'; describe('BigInt', () => { - const provider = process.env.TESTS_USE_CHIPNET - ? new ElectrumNetworkProvider(Network.CHIPNET) - : new MockNetworkProvider(); + const provider = process.env.TESTS_USE_CHIPNET ? new ElectrumNetworkProvider(Network.CHIPNET) : new MockNetworkProvider(); const bigintContract = new Contract(artifact, [], { provider }); const MAX_INT64 = BigInt('9223372036854775807'); @@ -39,7 +37,9 @@ describe('BigInt', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('BigInt.cash:4 Require statement failed at input 0 in contract BigInt.cash at line 4'); + await expect(txPromise).rejects.toThrow( + 'BigInt.cash:4 Require statement failed at input 0 in contract BigInt.cash at line 4', + ); await expect(txPromise).rejects.toThrow('Failing statement: require(x >= maxInt64PlusOne)'); }); diff --git a/packages/cashscript/test/e2e/HodlVault.test.ts b/packages/cashscript/test/e2e/HodlVault.test.ts index 7c42c5888..759b8e5f4 100644 --- a/packages/cashscript/test/e2e/HodlVault.test.ts +++ b/packages/cashscript/test/e2e/HodlVault.test.ts @@ -8,12 +8,7 @@ import { SignatureAlgorithm, SighashType, } from '../../src/index.js'; -import { - alicePriv, - alicePub, - oracle, - oraclePub, -} from '../fixture/vars.js'; +import { alicePriv, alicePub, oracle, oraclePub } from '../fixture/vars.js'; import { addUtxo, gatherUtxos, getTxOutputs } from '../test-util.js'; import { FailedRequireError } from '../../src/Errors.js'; import artifact from '../fixture/hodl_vault.artifact.js'; @@ -22,9 +17,7 @@ import { randomUtxo } from '../../src/utils.js'; import { placeholder } from '@cashscript/utils'; describe('HodlVault', () => { - const provider = process.env.TESTS_USE_CHIPNET - ? new ElectrumNetworkProvider(Network.CHIPNET) - : new MockNetworkProvider(); + const provider = process.env.TESTS_USE_CHIPNET ? new ElectrumNetworkProvider(Network.CHIPNET) : new MockNetworkProvider(); const hodlVault = new Contract(artifact, [alicePub, oraclePub, 99000n, 30000n], { provider }); @@ -53,8 +46,12 @@ describe('HodlVault', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('HodlVault.cash:30 Require statement failed at input 0 in contract HodlVault.cash at line 30.'); - await expect(txPromise).rejects.toThrow('Failing statement: require(checkDataSig(oracleSig, oracleMessage, oraclePk))'); + await expect(txPromise).rejects.toThrow( + 'HodlVault.cash:30 Require statement failed at input 0 in contract HodlVault.cash at line 30.', + ); + await expect(txPromise).rejects.toThrow( + 'Failing statement: require(checkDataSig(oracleSig, oracleMessage, oraclePk))', + ); }); it('should fail when price is too low', async () => { @@ -75,7 +72,9 @@ describe('HodlVault', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('HodlVault.cash:27 Require statement failed at input 0 in contract HodlVault.cash at line 27.'); + await expect(txPromise).rejects.toThrow( + 'HodlVault.cash:27 Require statement failed at input 0 in contract HodlVault.cash at line 27.', + ); await expect(txPromise).rejects.toThrow('Failing statement: require(price >= priceTarget)'); }); @@ -126,9 +125,9 @@ describe('HodlVault', () => { it.skipIf(process.env.TESTS_USE_CHIPNET)('should succeed with precomputed ECDSA signature', async () => { // given const cleanProvider = new MockNetworkProvider(); - const contract = new Contract( - artifactUnenforcedTypes, [alicePub, oraclePub, 99000n, 30000n], { provider: cleanProvider }, - ); + const contract = new Contract(artifactUnenforcedTypes, [alicePub, oraclePub, 99000n, 30000n], { + provider: cleanProvider, + }); cleanProvider.addUtxo(contract.address, { satoshis: 100000n, txid: '11'.repeat(32), @@ -139,7 +138,8 @@ describe('HodlVault', () => { const to = contract.address; const amount = 10000n; const { utxos, changeAmount } = gatherUtxos(await contract.getUtxos(), { amount, fee: 2000n }); - const signature = '3045022100aa004a425c0c911594c0333164f990c760991b7f84272f35d98c9c6617d9c53602207dfe4729224d4e61496dff11963982cf79f05d623a6e4004b5f50b7cefa7175241'; + const signature = + '3045022100aa004a425c0c911594c0333164f990c760991b7f84272f35d98c9c6617d9c53602207dfe4729224d4e61496dff11963982cf79f05d623a6e4004b5f50b7cefa7175241'; // when const tx = await new TransactionBuilder({ provider: cleanProvider }) @@ -163,48 +163,60 @@ describe('HodlVault', () => { const { utxos, changeAmount } = gatherUtxos(await hodlVault.getUtxos(), { amount, fee: 2000n }); // sig: unlocker should throw when given an improper length - expect(() => hodlVault.unlock.spend(placeholder(100), oracleSig, message)).toThrow("Found type 'bytes100' where type 'sig' was expected"); + expect(() => hodlVault.unlock.spend(placeholder(100), oracleSig, message)).toThrow( + "Found type 'bytes100' where type 'sig' was expected", + ); // sig: unlocker should not throw when given a proper length, but transaction should fail on invalid sig // Note that this fails with "FailedTransactionEvaluationError" because an invalid signature encoding is NOT a failed // require statement - await expect(new TransactionBuilder({ provider }) - .addInputs(utxos, hodlVault.unlock.spend(placeholder(71), oracleSig, message)) - .addOutput({ to: to, amount: amount }) - .addOutput({ to: to, amount: changeAmount }) - .setLocktime(100_000) - .send()).rejects.toThrow('HodlVault.cash:31 Error in transaction at input 0 in contract HodlVault.cash at line 31'); + await expect( + new TransactionBuilder({ provider }) + .addInputs(utxos, hodlVault.unlock.spend(placeholder(71), oracleSig, message)) + .addOutput({ to: to, amount: amount }) + .addOutput({ to: to, amount: changeAmount }) + .setLocktime(100_000) + .send(), + ).rejects.toThrow('HodlVault.cash:31 Error in transaction at input 0 in contract HodlVault.cash at line 31'); // sig: unlocker should not throw when given an empty byte array, but transaction should fail on require statement // Note that this fails with "FailedRequireError" because a zero-length signature IS a failed require statement - await expect(new TransactionBuilder({ provider }) - .addInputs(utxos, hodlVault.unlock.spend(placeholder(0), oracleSig, message)) - .addOutput({ to: to, amount: amount }) - .addOutput({ to: to, amount: changeAmount }) - .setLocktime(100_000) - .send()).rejects.toThrow('HodlVault.cash:31 Require statement failed at input 0 in contract HodlVault.cash at line 31'); + await expect( + new TransactionBuilder({ provider }) + .addInputs(utxos, hodlVault.unlock.spend(placeholder(0), oracleSig, message)) + .addOutput({ to: to, amount: amount }) + .addOutput({ to: to, amount: changeAmount }) + .setLocktime(100_000) + .send(), + ).rejects.toThrow('HodlVault.cash:31 Require statement failed at input 0 in contract HodlVault.cash at line 31'); // datasig: unlocker should throw when given an improper length const signatureTemplate = new SignatureTemplate(alicePriv, SighashType.SIGHASH_ALL, SignatureAlgorithm.ECDSA); - expect(() => hodlVault.unlock.spend(signatureTemplate, placeholder(100), message)).toThrow("Found type 'bytes100' where type 'datasig' was expected"); + expect(() => hodlVault.unlock.spend(signatureTemplate, placeholder(100), message)).toThrow( + "Found type 'bytes100' where type 'datasig' was expected", + ); // datasig: unlocker should not throw when given a proper length, but transaction should fail on invalid sig // TODO: This somehow fails with "FailedRequireError" instead of "FailedTransactionEvaluationError", check why - await expect(new TransactionBuilder({ provider }) - .addInputs(utxos, hodlVault.unlock.spend(signatureTemplate, placeholder(64), message)) - .addOutput({ to: to, amount: amount }) - .addOutput({ to: to, amount: changeAmount }) - .setLocktime(100_000) - .send()).rejects.toThrow('HodlVault.cash:30 Require statement failed at input 0 in contract HodlVault.cash at line 30'); + await expect( + new TransactionBuilder({ provider }) + .addInputs(utxos, hodlVault.unlock.spend(signatureTemplate, placeholder(64), message)) + .addOutput({ to: to, amount: amount }) + .addOutput({ to: to, amount: changeAmount }) + .setLocktime(100_000) + .send(), + ).rejects.toThrow('HodlVault.cash:30 Require statement failed at input 0 in contract HodlVault.cash at line 30'); // datasig: unlocker should not throw when given an empty byte array, but transaction should fail on require statement // Note that this fails with "FailedRequireError" because a zero-length signature IS a failed require statement - await expect(new TransactionBuilder({ provider }) - .addInputs(utxos, hodlVault.unlock.spend(signatureTemplate, placeholder(0), message)) - .addOutput({ to: to, amount: amount }) - .addOutput({ to: to, amount: changeAmount }) - .setLocktime(100_000) - .send()).rejects.toThrow('HodlVault.cash:30 Require statement failed at input 0 in contract HodlVault.cash at line 30'); + await expect( + new TransactionBuilder({ provider }) + .addInputs(utxos, hodlVault.unlock.spend(signatureTemplate, placeholder(0), message)) + .addOutput({ to: to, amount: amount }) + .addOutput({ to: to, amount: changeAmount }) + .setLocktime(100_000) + .send(), + ).rejects.toThrow('HodlVault.cash:30 Require statement failed at input 0 in contract HodlVault.cash at line 30'); }); }); }); diff --git a/packages/cashscript/test/e2e/LocktimeGuard.test.ts b/packages/cashscript/test/e2e/LocktimeGuard.test.ts index 8503aef93..1e3278b59 100644 --- a/packages/cashscript/test/e2e/LocktimeGuard.test.ts +++ b/packages/cashscript/test/e2e/LocktimeGuard.test.ts @@ -1,6 +1,12 @@ import { hexToBin } from '@bitauth/libauth'; import { compileString } from 'cashc'; -import { Contract, MockNetworkProvider, ElectrumNetworkProvider, SignatureTemplate, TransactionBuilder } from '../../src/index.js'; +import { + Contract, + MockNetworkProvider, + ElectrumNetworkProvider, + SignatureTemplate, + TransactionBuilder, +} from '../../src/index.js'; import { bobAddress, bobPriv } from '../fixture/vars.js'; import { addUtxo } from '../test-util.js'; import { Network } from '../../src/interfaces.js'; @@ -8,9 +14,7 @@ import { randomUtxo } from '../../src/utils.js'; import artifact from '../fixture/tx_locktime_guard.artifact.js'; describe('Locktime Guard', () => { - const provider = process.env.TESTS_USE_CHIPNET - ? new ElectrumNetworkProvider(Network.CHIPNET) - : new MockNetworkProvider(); + const provider = process.env.TESTS_USE_CHIPNET ? new ElectrumNetworkProvider(Network.CHIPNET) : new MockNetworkProvider(); // define contract in the describe block so artifact typings aren't lost const locktimeGuardContract = new Contract(artifact, [], { provider }); @@ -44,8 +48,8 @@ describe('Locktime Guard', () => { .addBchChangeOutputIfNeeded({ to: locktimeGuardContract.address, feeRate: 1.0 }); expect(transaction).toFailRequireWith( - 'LocktimeGuard.cash:4 Require statement failed at input 0 in contract LocktimeGuard.cash at line 4' - + ' with the following message: Using tx.locktime requires a non-final sequence number on the spending input.', + 'LocktimeGuard.cash:4 Require statement failed at input 0 in contract LocktimeGuard.cash at line 4' + + ' with the following message: Using tx.locktime requires a non-final sequence number on the spending input.', ); // The guard is compiler-injected and has no user source, so there must be no (empty) failing statement line expect(transaction).not.toFailRequireWith('Failing statement:'); diff --git a/packages/cashscript/test/e2e/Mecenas.test.ts b/packages/cashscript/test/e2e/Mecenas.test.ts index c67c0bfef..1ecf6bff7 100644 --- a/packages/cashscript/test/e2e/Mecenas.test.ts +++ b/packages/cashscript/test/e2e/Mecenas.test.ts @@ -1,10 +1,5 @@ import { Contract, ElectrumNetworkProvider, MockNetworkProvider, Network, TransactionBuilder } from '../../src/index.js'; -import { - alicePkh, - bobPkh, - aliceAddress, - bobAddress, -} from '../fixture/vars.js'; +import { alicePkh, bobPkh, aliceAddress, bobAddress } from '../fixture/vars.js'; import { addUtxo, getLargestUtxo, getTxOutputs } from '../test-util.js'; import { FailedRequireError } from '../../src/Errors.js'; import artifact from '../fixture/mecenas.artifact.js'; @@ -12,9 +7,7 @@ import { randomUtxo } from '../../src/utils.js'; // Mecenas has this.age check omitted for testing describe('Mecenas', () => { - const provider = process.env.TESTS_USE_CHIPNET - ? new ElectrumNetworkProvider(Network.CHIPNET) - : new MockNetworkProvider(); + const provider = process.env.TESTS_USE_CHIPNET ? new ElectrumNetworkProvider(Network.CHIPNET) : new MockNetworkProvider(); const pledge = 10_000n; const mecenas = new Contract(artifact, [alicePkh, bobPkh, pledge], { provider }); @@ -47,7 +40,9 @@ describe('Mecenas', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('Mecenas.cash:14 Require statement failed at input 0 in contract Mecenas.cash at line 14.'); + await expect(txPromise).rejects.toThrow( + 'Mecenas.cash:14 Require statement failed at input 0 in contract Mecenas.cash at line 14.', + ); await expect(txPromise).rejects.toThrow('Failing statement: require(tx.inputs.length == 1)'); }); @@ -67,7 +62,9 @@ describe('Mecenas', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('Mecenas.cash:28 Require statement failed at input 0 in contract Mecenas.cash at line 28.'); + await expect(txPromise).rejects.toThrow( + 'Mecenas.cash:28 Require statement failed at input 0 in contract Mecenas.cash at line 28.', + ); await expect(txPromise).rejects.toThrow('Failing statement: require(tx.outputs[0].value == pledge)'); }); @@ -87,8 +84,12 @@ describe('Mecenas', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('Mecenas.cash:17 Require statement failed at input 0 in contract Mecenas.cash at line 17.'); - await expect(txPromise).rejects.toThrow('Failing statement: require(tx.outputs[0].lockingBytecode == new LockingBytecodeP2PKH(recipient))'); + await expect(txPromise).rejects.toThrow( + 'Mecenas.cash:17 Require statement failed at input 0 in contract Mecenas.cash at line 17.', + ); + await expect(txPromise).rejects.toThrow( + 'Failing statement: require(tx.outputs[0].lockingBytecode == new LockingBytecodeP2PKH(recipient))', + ); }); it('should fail when trying to send to multiple people', async () => { @@ -108,8 +109,12 @@ describe('Mecenas', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('Mecenas.cash:29 Require statement failed at input 0 in contract Mecenas.cash at line 29.'); - await expect(txPromise).rejects.toThrow('Failing statement: require(tx.outputs[1].lockingBytecode == tx.inputs[this.activeInputIndex].lockingBytecode)'); + await expect(txPromise).rejects.toThrow( + 'Mecenas.cash:29 Require statement failed at input 0 in contract Mecenas.cash at line 29.', + ); + await expect(txPromise).rejects.toThrow( + 'Failing statement: require(tx.outputs[1].lockingBytecode == tx.inputs[this.activeInputIndex].lockingBytecode)', + ); }); it('should fail when sending incorrect amount of change', async () => { @@ -129,7 +134,9 @@ describe('Mecenas', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('Mecenas.cash:30 Require statement failed at input 0 in contract Mecenas.cash at line 30.'); + await expect(txPromise).rejects.toThrow( + 'Mecenas.cash:30 Require statement failed at input 0 in contract Mecenas.cash at line 30.', + ); await expect(txPromise).rejects.toThrow('Failing statement: require(tx.outputs[1].value == changeValue)'); }); diff --git a/packages/cashscript/test/e2e/MultiContract.test.ts b/packages/cashscript/test/e2e/MultiContract.test.ts index 2004cbf26..4e1efead2 100644 --- a/packages/cashscript/test/e2e/MultiContract.test.ts +++ b/packages/cashscript/test/e2e/MultiContract.test.ts @@ -26,9 +26,7 @@ import { addUtxo, getTxOutputs } from '../test-util.js'; import SiblingIntrospectionArtifact from '../fixture/SiblingIntrospection.artifact.js'; describe('Multi Contract', () => { - const provider = process.env.TESTS_USE_CHIPNET - ? new ElectrumNetworkProvider(Network.CHIPNET) - : new MockNetworkProvider(); + const provider = process.env.TESTS_USE_CHIPNET ? new ElectrumNetworkProvider(Network.CHIPNET) : new MockNetworkProvider(); const aliceSignatureTemplate = new SignatureTemplate(alicePriv); const bobSignatureTemplate = new SignatureTemplate(bobPriv); @@ -68,7 +66,9 @@ describe('Multi Contract', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('P2PKH.cash:4 Require statement failed at input 0 in contract P2PKH.cash at line 4.'); + await expect(txPromise).rejects.toThrow( + 'P2PKH.cash:4 Require statement failed at input 0 in contract P2PKH.cash at line 4.', + ); await expect(txPromise).rejects.toThrow('Failing statement: require(hash160(pk) == pkh)'); }); @@ -93,7 +93,9 @@ describe('Multi Contract', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('P2PKH.cash:4 Require statement failed at input 1 in contract P2PKH.cash at line 4.'); + await expect(txPromise).rejects.toThrow( + 'P2PKH.cash:4 Require statement failed at input 1 in contract P2PKH.cash at line 4.', + ); await expect(txPromise).rejects.toThrow('Failing statement: require(hash160(pk) == pkh)'); }); @@ -154,7 +156,9 @@ describe('Multi Contract', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('P2PKH.cash:4 Require statement failed at input 0 in contract P2PKH.cash at line 4.'); + await expect(txPromise).rejects.toThrow( + 'P2PKH.cash:4 Require statement failed at input 0 in contract P2PKH.cash at line 4.', + ); await expect(txPromise).rejects.toThrow('Failing statement: require(hash160(pk) == pkh)'); }); @@ -179,7 +183,9 @@ describe('Multi Contract', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('TransferWithTimeout.cash:8 Require statement failed at input 1 in contract TransferWithTimeout.cash at line 8.'); + await expect(txPromise).rejects.toThrow( + 'TransferWithTimeout.cash:8 Require statement failed at input 1 in contract TransferWithTimeout.cash at line 8.', + ); await expect(txPromise).rejects.toThrow('Failing statement: require(checkSig(recipientSig, recipient))'); }); @@ -254,8 +260,12 @@ describe('Multi Contract', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('SiblingIntrospection.cash:7 Require statement failed at input 0 in contract SiblingIntrospection.cash at line 7 with the following message: output bytecode should match.'); - await expect(txPromise).rejects.toThrow('Failing statement: require(outputBytecode == expectedLockingBytecode, \'output bytecode should match\')'); + await expect(txPromise).rejects.toThrow( + 'SiblingIntrospection.cash:7 Require statement failed at input 0 in contract SiblingIntrospection.cash at line 7 with the following message: output bytecode should match.', + ); + await expect(txPromise).rejects.toThrow( + "Failing statement: require(outputBytecode == expectedLockingBytecode, 'output bytecode should match')", + ); }); }); }); diff --git a/packages/cashscript/test/e2e/P2PKH-tokens.test.ts b/packages/cashscript/test/e2e/P2PKH-tokens.test.ts index 2d1f8bb9c..dcc5cfd97 100644 --- a/packages/cashscript/test/e2e/P2PKH-tokens.test.ts +++ b/packages/cashscript/test/e2e/P2PKH-tokens.test.ts @@ -1,14 +1,13 @@ import { randomUtxo, randomToken, randomNFT } from '../../src/utils.js'; import { - Contract, SignatureTemplate, ElectrumNetworkProvider, MockNetworkProvider, + Contract, + SignatureTemplate, + ElectrumNetworkProvider, + MockNetworkProvider, TransactionBuilder, NetworkProvider, } from '../../src/index.js'; -import { - alicePkh, - alicePub, - alicePriv, -} from '../fixture/vars.js'; +import { alicePkh, alicePub, alicePriv } from '../fixture/vars.js'; import { addUtxo, getTxOutputs } from '../test-util.js'; import { Network, TokenDetails, Utxo } from '../../src/interfaces.js'; import artifact from '../fixture/p2pkh.artifact.js'; @@ -18,39 +17,61 @@ describe('P2PKH-tokens', () => { let provider: NetworkProvider; beforeAll(async () => { - provider = process.env.TESTS_USE_CHIPNET - ? new ElectrumNetworkProvider(Network.CHIPNET) - : new MockNetworkProvider(); + provider = process.env.TESTS_USE_CHIPNET ? new ElectrumNetworkProvider(Network.CHIPNET) : new MockNetworkProvider(); p2pkhInstance = new Contract(artifact, [alicePkh], { provider }); console.log(p2pkhInstance.tokenAddress); await addUtxo(provider, p2pkhInstance.address, randomUtxo()); await addUtxo(provider, p2pkhInstance.address, randomUtxo()); await addUtxo(provider, p2pkhInstance.address, randomUtxo({ vout: 0 })); - await addUtxo(provider, p2pkhInstance.address, randomUtxo({ - satoshis: 1000n, - token: randomToken(), - })); - await addUtxo(provider, p2pkhInstance.address, randomUtxo({ - satoshis: 1000n, - token: randomToken(), - })); - await addUtxo(provider, p2pkhInstance.address, randomUtxo({ - satoshis: 1000n, - token: randomNFT(), - })); - await addUtxo(provider, p2pkhInstance.address, randomUtxo({ - satoshis: 1000n, - token: randomNFT(), - })); - await addUtxo(provider, p2pkhInstance.address, randomUtxo({ - satoshis: 1000n, - token: { ...randomNFT(), ...randomToken() }, - })); - await addUtxo(provider, p2pkhInstance.address, randomUtxo({ - satoshis: 1000n, - token: { ...randomToken(), ...randomNFT() }, - })); + await addUtxo( + provider, + p2pkhInstance.address, + randomUtxo({ + satoshis: 1000n, + token: randomToken(), + }), + ); + await addUtxo( + provider, + p2pkhInstance.address, + randomUtxo({ + satoshis: 1000n, + token: randomToken(), + }), + ); + await addUtxo( + provider, + p2pkhInstance.address, + randomUtxo({ + satoshis: 1000n, + token: randomNFT(), + }), + ); + await addUtxo( + provider, + p2pkhInstance.address, + randomUtxo({ + satoshis: 1000n, + token: randomNFT(), + }), + ); + await addUtxo( + provider, + p2pkhInstance.address, + randomUtxo({ + satoshis: 1000n, + token: { ...randomNFT(), ...randomToken() }, + }), + ); + await addUtxo( + provider, + p2pkhInstance.address, + randomUtxo({ + satoshis: 1000n, + token: { ...randomToken(), ...randomNFT() }, + }), + ); }); describe('send (tokens)', () => { @@ -94,9 +115,7 @@ describe('P2PKH-tokens', () => { const to = p2pkhInstance.tokenAddress; const amount = 1000n; const fee = 1000n; - const fullBchBalance = nonTokenUtxos.reduce( - (total, utxo) => total + utxo.satoshis, 0n, - ); + const fullBchBalance = nonTokenUtxos.reduce((total, utxo) => total + utxo.satoshis, 0n); const changeAmount = fullBchBalance - fee - amount; const unlocker = p2pkhInstance.unlock.spend(alicePub, new SignatureTemplate(alicePriv)); @@ -112,7 +131,10 @@ describe('P2PKH-tokens', () => { const txOutputs = getTxOutputs(tx); expect(txOutputs).toEqual( - expect.arrayContaining([{ to, amount, token: nftUtxo1.token }, { to, amount, token: nftUtxo2.token }]), + expect.arrayContaining([ + { to, amount, token: nftUtxo1.token }, + { to, amount, token: nftUtxo2.token }, + ]), ); }); @@ -192,7 +214,7 @@ describe('P2PKH-tokens', () => { ); }); - it('should throw an error when trying to send a token the contract doesn\'t have', async () => { + it("should throw an error when trying to send a token the contract doesn't have", async () => { const contractUtxos = await p2pkhInstance.getUtxos(); const nonTokenUtxos = contractUtxos.filter(isNonTokenUtxo); @@ -215,7 +237,7 @@ describe('P2PKH-tokens', () => { ); }); - it('should throw an error when trying to send an NFT the contract doesn\'t have', async () => { + it("should throw an error when trying to send an NFT the contract doesn't have", async () => { const contractUtxos = await p2pkhInstance.getUtxos(); const nftUtxo = contractUtxos.find(isNftUtxo); const nonTokenUtxos = contractUtxos.filter(isNonTokenUtxo); @@ -301,13 +323,11 @@ describe('P2PKH-tokens', () => { }); // We don't include UTXOs that contain BOTH fungible and non-fungible tokens -const isFungibleTokenUtxo = (utxo: Utxo): boolean => ( - utxo.token !== undefined && utxo.token.amount > 0n && utxo.token.nft === undefined -); +const isFungibleTokenUtxo = (utxo: Utxo): boolean => + utxo.token !== undefined && utxo.token.amount > 0n && utxo.token.nft === undefined; // We don't include UTXOs that contain BOTH fungible and non-fungible tokens -const isNftUtxo = (utxo: Utxo): boolean => ( - utxo.token !== undefined && utxo.token.amount === 0n && utxo.token.nft !== undefined -); +const isNftUtxo = (utxo: Utxo): boolean => + utxo.token !== undefined && utxo.token.amount === 0n && utxo.token.nft !== undefined; const isNonTokenUtxo = (utxo: Utxo): boolean => utxo.token === undefined; diff --git a/packages/cashscript/test/e2e/P2PKH.test.ts b/packages/cashscript/test/e2e/P2PKH.test.ts index 3dc5bbe59..eb7c8bb0d 100644 --- a/packages/cashscript/test/e2e/P2PKH.test.ts +++ b/packages/cashscript/test/e2e/P2PKH.test.ts @@ -1,29 +1,20 @@ import { binToHex } from '@bitauth/libauth'; import { - Contract, SignatureTemplate, MockNetworkProvider, ElectrumNetworkProvider, + Contract, + SignatureTemplate, + MockNetworkProvider, + ElectrumNetworkProvider, FailedRequireError, TransactionBuilder, } from '../../src/index.js'; -import { - bobAddress, - bobPub, - bobPriv, - bobPkh, - alicePriv, - alicePub, - aliceAddress, -} from '../fixture/vars.js'; +import { bobAddress, bobPub, bobPriv, bobPkh, alicePriv, alicePub, aliceAddress } from '../fixture/vars.js'; import { addUtxo, gatherUtxos, getTxOutputs } from '../test-util.js'; import { Network } from '../../src/interfaces.js'; -import { - createOpReturnOutput, randomUtxo, -} from '../../src/utils.js'; +import { createOpReturnOutput, randomUtxo } from '../../src/utils.js'; import artifact from '../fixture/p2pkh.artifact.js'; describe('P2PKH-no-tokens', () => { - const provider = process.env.TESTS_USE_CHIPNET - ? new ElectrumNetworkProvider(Network.CHIPNET) - : new MockNetworkProvider(); + const provider = process.env.TESTS_USE_CHIPNET ? new ElectrumNetworkProvider(Network.CHIPNET) : new MockNetworkProvider(); // define contract in the describe block so artifact typings aren't lost const p2pkhContract = new Contract(artifact, [bobPkh], { provider }); @@ -53,7 +44,9 @@ describe('P2PKH-no-tokens', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('P2PKH.cash:4 Require statement failed at input 0 in contract P2PKH.cash at line 4.'); + await expect(txPromise).rejects.toThrow( + 'P2PKH.cash:4 Require statement failed at input 0 in contract P2PKH.cash at line 4.', + ); await expect(txPromise).rejects.toThrow('Failing statement: require(hash160(pk) == pkh)'); }); @@ -72,7 +65,9 @@ describe('P2PKH-no-tokens', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('P2PKH.cash:5 Require statement failed at input 0 in contract P2PKH.cash at line 5.'); + await expect(txPromise).rejects.toThrow( + 'P2PKH.cash:5 Require statement failed at input 0 in contract P2PKH.cash at line 5.', + ); await expect(txPromise).rejects.toThrow('Failing statement: require(checkSig(s, pk))'); }); @@ -97,23 +92,26 @@ describe('P2PKH-no-tokens', () => { // TODO: this fails on mocknet, because mocknet doesn't check inputs vs outputs, // we should add a sanity check in our own code - it.runIf(Boolean(process.env.TESTS_USE_CHIPNET))('should fail when not enough satoshis are provided in utxos', async () => { - // given - const to = p2pkhContract.address; - const amount = 1000n; - const { utxos, total, changeAmount } = gatherUtxos(await p2pkhContract.getUtxos(), { amount }); - const failureAmount = total + 1n; - - // when - const txPromise = new TransactionBuilder({ provider }) - .addInputs(utxos, p2pkhContract.unlock.spend(bobPub, new SignatureTemplate(bobPriv))) - .addOutput({ to, amount: failureAmount }) - .addOutput({ to, amount: changeAmount }) - .send(); - - // then - await expect(txPromise).rejects.toThrow(); - }); + it.runIf(Boolean(process.env.TESTS_USE_CHIPNET))( + 'should fail when not enough satoshis are provided in utxos', + async () => { + // given + const to = p2pkhContract.address; + const amount = 1000n; + const { utxos, total, changeAmount } = gatherUtxos(await p2pkhContract.getUtxos(), { amount }); + const failureAmount = total + 1n; + + // when + const txPromise = new TransactionBuilder({ provider }) + .addInputs(utxos, p2pkhContract.unlock.spend(bobPub, new SignatureTemplate(bobPriv))) + .addOutput({ to, amount: failureAmount }) + .addOutput({ to, amount: changeAmount }) + .send(); + + // then + await expect(txPromise).rejects.toThrow(); + }, + ); it('should succeed when providing UTXOs to .addInputs', async () => { // given @@ -131,10 +129,9 @@ describe('P2PKH-no-tokens', () => { // then expect.hasAssertions(); tx.inputs.forEach((input) => { - expect(utxos.find((utxo) => ( - utxo.txid === binToHex(input.outpointTransactionHash) - && utxo.vout === input.outpointIndex - ))).toBeTruthy(); + expect( + utxos.find((utxo) => utxo.txid === binToHex(input.outpointTransactionHash) && utxo.vout === input.outpointIndex), + ).toBeTruthy(); }); }); diff --git a/packages/cashscript/test/e2e/TokenCategoryCheck.test.ts b/packages/cashscript/test/e2e/TokenCategoryCheck.test.ts index 123a67872..7572e5d16 100644 --- a/packages/cashscript/test/e2e/TokenCategoryCheck.test.ts +++ b/packages/cashscript/test/e2e/TokenCategoryCheck.test.ts @@ -1,6 +1,9 @@ import { randomUtxo, randomToken, isFungibleTokenUtxo, isNonTokenUtxo, utxoComparator } from '../../src/utils.js'; import { - Contract, ElectrumNetworkProvider, FailedRequireError, MockNetworkProvider, + Contract, + ElectrumNetworkProvider, + FailedRequireError, + MockNetworkProvider, TransactionBuilder, } from '../../src/index.js'; import { Network } from '../../src/interfaces.js'; @@ -8,9 +11,7 @@ import { addUtxo } from '../test-util.js'; import artifact from '../fixture/token_category_comparison.artifact.js'; describe('TokenCategoryCheck', () => { - const provider = process.env.TESTS_USE_CHIPNET - ? new ElectrumNetworkProvider(Network.CHIPNET) - : new MockNetworkProvider(); + const provider = process.env.TESTS_USE_CHIPNET ? new ElectrumNetworkProvider(Network.CHIPNET) : new MockNetworkProvider(); const checkTokenCategoryContract = new Contract(artifact, [], { provider }); @@ -50,7 +51,9 @@ describe('TokenCategoryCheck', () => { .send(); await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('Test.cash:3 Require statement failed at input 0 in contract Test.cash at line 3.'); + await expect(txPromise).rejects.toThrow( + 'Test.cash:3 Require statement failed at input 0 in contract Test.cash at line 3.', + ); await expect(txPromise).rejects.toThrow('Failing statement: require(tx.inputs[1].tokenCategory == 0x)'); }); @@ -77,4 +80,3 @@ describe('TokenCategoryCheck', () => { }); }); }); - diff --git a/packages/cashscript/test/e2e/TransferWithTimeout.test.ts b/packages/cashscript/test/e2e/TransferWithTimeout.test.ts index 7fc68f6ac..e2c8e6bed 100644 --- a/packages/cashscript/test/e2e/TransferWithTimeout.test.ts +++ b/packages/cashscript/test/e2e/TransferWithTimeout.test.ts @@ -7,17 +7,13 @@ import { FailedRequireError, TransactionBuilder, } from '../../src/index.js'; -import { - alicePriv, alicePub, bobPriv, bobPub, -} from '../fixture/vars.js'; +import { alicePriv, alicePub, bobPriv, bobPub } from '../fixture/vars.js'; import { addUtxo, gatherUtxos, getTxOutputs } from '../test-util.js'; import twtArtifact from '../fixture/transfer_with_timeout.artifact.js'; import { randomUtxo } from '../../src/utils.js'; describe('TransferWithTimeout', () => { - const provider = process.env.TESTS_USE_CHIPNET - ? new ElectrumNetworkProvider(Network.CHIPNET) - : new MockNetworkProvider(); + const provider = process.env.TESTS_USE_CHIPNET ? new ElectrumNetworkProvider(Network.CHIPNET) : new MockNetworkProvider(); const twtInstancePast = new Contract(twtArtifact, [alicePub, bobPub, 100000n], { provider }); const twtInstanceFuture = new Contract(twtArtifact, [alicePub, bobPub, 2000000n], { provider }); @@ -46,7 +42,9 @@ describe('TransferWithTimeout', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('TransferWithTimeout.cash:8 Require statement failed at input 0 in contract TransferWithTimeout.cash at line 8.'); + await expect(txPromise).rejects.toThrow( + 'TransferWithTimeout.cash:8 Require statement failed at input 0 in contract TransferWithTimeout.cash at line 8.', + ); await expect(txPromise).rejects.toThrow('Failing statement: require(checkSig(recipientSig, recipient))'); }); @@ -65,7 +63,9 @@ describe('TransferWithTimeout', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('TransferWithTimeout.cash:13 Require statement failed at input 0 in contract TransferWithTimeout.cash at line 13.'); + await expect(txPromise).rejects.toThrow( + 'TransferWithTimeout.cash:13 Require statement failed at input 0 in contract TransferWithTimeout.cash at line 13.', + ); await expect(txPromise).rejects.toThrow('Failing statement: require(checkSig(senderSig, sender))'); }); @@ -84,7 +84,9 @@ describe('TransferWithTimeout', () => { // then await expect(txPromise).rejects.toThrow(FailedRequireError); - await expect(txPromise).rejects.toThrow('TransferWithTimeout.cash:14 Require statement failed at input 0 in contract TransferWithTimeout.cash at line 14.'); + await expect(txPromise).rejects.toThrow( + 'TransferWithTimeout.cash:14 Require statement failed at input 0 in contract TransferWithTimeout.cash at line 14.', + ); await expect(txPromise).rejects.toThrow('Failing statement: require(tx.time >= timeout)'); }); diff --git a/packages/cashscript/test/e2e/misc/timelocks.test.ts b/packages/cashscript/test/e2e/misc/timelocks.test.ts index afabd8a15..7c0646bd9 100644 --- a/packages/cashscript/test/e2e/misc/timelocks.test.ts +++ b/packages/cashscript/test/e2e/misc/timelocks.test.ts @@ -1,12 +1,5 @@ import { Contract, SignatureTemplate, ElectrumNetworkProvider, MockNetworkProvider } from '../../../src/index.js'; -import { - bobAddress, - bobPub, - carolPkh, - carolPub, - carolAddress, - carolPriv, -} from '../../fixture/vars.js'; +import { bobAddress, bobPub, carolPkh, carolPub, carolAddress, carolPriv } from '../../fixture/vars.js'; import { Network } from '../../../src/interfaces.js'; import { utxoComparator, calculateDust, randomUtxo, isNonTokenUtxo } from '../../../src/utils.js'; import p2pkhArtifact from '../../fixture/p2pkh.artifact.js'; @@ -15,9 +8,7 @@ import { TransactionBuilder } from '../../../src/TransactionBuilder.js'; import { addUtxo, getTxOutputs } from '../../test-util.js'; describe('Timelocks', () => { - const provider = process.env.TESTS_USE_CHIPNET - ? new ElectrumNetworkProvider(Network.CHIPNET) - : new MockNetworkProvider(); + const provider = process.env.TESTS_USE_CHIPNET ? new ElectrumNetworkProvider(Network.CHIPNET) : new MockNetworkProvider(); let p2pkhInstance: Contract; let twtInstance: Contract; diff --git a/packages/cashscript/test/e2e/network/ElectrumNetworkProvider.test.ts b/packages/cashscript/test/e2e/network/ElectrumNetworkProvider.test.ts index 7450dc755..93c48f8f1 100644 --- a/packages/cashscript/test/e2e/network/ElectrumNetworkProvider.test.ts +++ b/packages/cashscript/test/e2e/network/ElectrumNetworkProvider.test.ts @@ -12,7 +12,9 @@ describe.runIf(Boolean(process.env.TESTS_USE_CHIPNET))('ElectrumNetworkProvider' it('should be able to handle multiple concurrent requests', async () => { const provider = new ElectrumNetworkProvider(Network.CHIPNET); - const transactionPromise = provider.getRawTransaction('d72923b7cf345d2a90f951d66f437d4fbb941fcbd87bb54d8d88e51ecb3e3b9f'); + const transactionPromise = provider.getRawTransaction( + 'd72923b7cf345d2a90f951d66f437d4fbb941fcbd87bb54d8d88e51ecb3e3b9f', + ); const blockHeightPromise = provider.getBlockHeight(); const transaction = await transactionPromise; @@ -63,7 +65,9 @@ describe('ElectrumNetworkProvider automatic connection management', () => { const electrum = { connect: vi.fn(async () => {}), disconnect: vi.fn(async () => true), - request: vi.fn(async () => { throw new Error('request failed'); }), + request: vi.fn(async () => { + throw new Error('request failed'); + }), }; const provider = new ElectrumNetworkProvider(Network.CHIPNET, { electrum: electrum as unknown as ElectrumClient, diff --git a/packages/cashscript/test/e2e/network/MockNetworkProvider.test.ts b/packages/cashscript/test/e2e/network/MockNetworkProvider.test.ts index 1783ac591..f8c86f591 100644 --- a/packages/cashscript/test/e2e/network/MockNetworkProvider.test.ts +++ b/packages/cashscript/test/e2e/network/MockNetworkProvider.test.ts @@ -1,16 +1,14 @@ import { binToHex } from '@bitauth/libauth'; -import { Contract, MockNetworkProvider, NetworkProviderAbsoluteTimelockError, SignatureTemplate } from '../../../src/index.js'; +import { + Contract, + MockNetworkProvider, + NetworkProviderAbsoluteTimelockError, + SignatureTemplate, +} from '../../../src/index.js'; import { TransactionBuilder } from '../../../src/TransactionBuilder.js'; import { addressToLockScript, randomUtxo } from '../../../src/utils.js'; import p2pkhArtifact from '../../fixture/p2pkh.artifact.js'; -import { - aliceAddress, - alicePkh, - alicePriv, - alicePub, - bobAddress, - bobPriv, -} from '../../fixture/vars.js'; +import { aliceAddress, alicePkh, alicePriv, alicePub, bobAddress, bobPriv } from '../../fixture/vars.js'; describe.skipIf(Boolean(process.env.TESTS_USE_CHIPNET))('MockNetworkProvider', () => { describe('when updateUtxoSet is default (true)', () => { @@ -150,8 +148,9 @@ describe.skipIf(Boolean(process.env.TESTS_USE_CHIPNET))('MockNetworkProvider', ( .build(); }; - await expect(heightProvider.sendRawTransaction(buildWithLocktime(1001))) - .rejects.toThrow(NetworkProviderAbsoluteTimelockError); + await expect(heightProvider.sendRawTransaction(buildWithLocktime(1001))).rejects.toThrow( + NetworkProviderAbsoluteTimelockError, + ); await expect(heightProvider.sendRawTransaction(buildWithLocktime(1000))).resolves.toBeTruthy(); // Final sequence numbers disable the locktime, and time-based locktimes are not checked diff --git a/packages/cashscript/test/multi-contract-debugging.test.ts b/packages/cashscript/test/multi-contract-debugging.test.ts index 38a29de88..a6616c9b3 100644 --- a/packages/cashscript/test/multi-contract-debugging.test.ts +++ b/packages/cashscript/test/multi-contract-debugging.test.ts @@ -1,22 +1,13 @@ -import { - Contract, - MockNetworkProvider, - randomUtxo, - SignatureTemplate, - TransactionBuilder, -} from '../src/index.js'; -import { - alicePkh, - alicePriv, - alicePub, - bobAddress, - bobPkh, - bobPriv, - bobPub, -} from './fixture/vars.js'; +import { Contract, MockNetworkProvider, randomUtxo, SignatureTemplate, TransactionBuilder } from '../src/index.js'; +import { alicePkh, alicePriv, alicePub, bobAddress, bobPkh, bobPriv, bobPub } from './fixture/vars.js'; import p2pkhArtifact from './fixture/p2pkh.artifact.js'; import bigintArtifact from './fixture/bigint.artifact.js'; -import { ARTIFACT_FUNCTION_NAME_COLLISION, ARTIFACT_NAME_COLLISION, ARTIFACT_CONTRACT_NAME_COLLISION, ARTIFACT_SAME_NAME_DIFFERENT_PATH } from './fixture/debugging/multi_contract_debugging_contracts.js'; +import { + ARTIFACT_FUNCTION_NAME_COLLISION, + ARTIFACT_NAME_COLLISION, + ARTIFACT_CONTRACT_NAME_COLLISION, + ARTIFACT_SAME_NAME_DIFFERENT_PATH, +} from './fixture/debugging/multi_contract_debugging_contracts.js'; import { addressToLockScript } from '../src/utils.js'; import SiblingIntrospectionArtifact from './fixture/SiblingIntrospection.artifact.js'; @@ -30,20 +21,12 @@ describe('Multi-Contract-Debugging tests', () => { const sameNameDifferentPathContract = new Contract(ARTIFACT_SAME_NAME_DIFFERENT_PATH, [0n], { provider }); const expectedLockingBytecode = addressToLockScript(sameNameDifferentPathContract.address); - const siblingIntrospectionContract = new Contract( - SiblingIntrospectionArtifact, - [expectedLockingBytecode], - { provider }, - ); + const siblingIntrospectionContract = new Contract(SiblingIntrospectionArtifact, [expectedLockingBytecode], { + provider, + }); - const sameNameDifferentPathContractUtxo = provider.addUtxo( - sameNameDifferentPathContract.address, - randomUtxo(), - ); - const siblingIntrospectionUtxo = provider.addUtxo( - siblingIntrospectionContract.address, - randomUtxo(), - ); + const sameNameDifferentPathContractUtxo = provider.addUtxo(sameNameDifferentPathContract.address, randomUtxo()); + const siblingIntrospectionUtxo = provider.addUtxo(siblingIntrospectionContract.address, randomUtxo()); it('should log correct data in all executed console.log statements across all contracts in the correct order by input index', () => { const tx = new TransactionBuilder({ provider }) @@ -55,7 +38,9 @@ describe('Multi-Contract-Debugging tests', () => { amount: sameNameDifferentPathContractUtxo.satoshis - 2000n, }); - expect(tx).toLog('[Input #0] SiblingIntrospection.cash:6 outputBytecode: 0xaa2092e16594dd458916b3aa6cae4bf41352d1b3b39658698e8cddbeedd687efec7587\n[Input #0] SiblingIntrospection.cash:10 inputBytecode: 0xaa2092e16594dd458916b3aa6cae4bf41352d1b3b39658698e8cddbeedd687efec7587\n[Input #1] SameNameDifferentPath.cash:5 a is 0'); + expect(tx).toLog( + '[Input #0] SiblingIntrospection.cash:6 outputBytecode: 0xaa2092e16594dd458916b3aa6cae4bf41352d1b3b39658698e8cddbeedd687efec7587\n[Input #0] SiblingIntrospection.cash:10 inputBytecode: 0xaa2092e16594dd458916b3aa6cae4bf41352d1b3b39658698e8cddbeedd687efec7587\n[Input #1] SameNameDifferentPath.cash:5 a is 0', + ); }); it('should log correct data for the reached console.log statements if a require statement fails, and not log unreached console.log statements', () => { @@ -68,8 +53,12 @@ describe('Multi-Contract-Debugging tests', () => { amount: sameNameDifferentPathContractUtxo.satoshis - 2000n, }); - expect(tx).toLog('[Input #0] SiblingIntrospection.cash:6 outputBytecode: 0xaa20d510df1721debb0d678d8e424b5f64f04f820005f017cb4731f7be94cd63755787'); - expect(tx).not.toLog('[Input #0] SiblingIntrospection.cash:10 inputBytecode: 0xaa2092e16594dd458916b3aa6cae4bf41352d1b3b39658698e8cddbeedd687efec7587'); + expect(tx).toLog( + '[Input #0] SiblingIntrospection.cash:6 outputBytecode: 0xaa20d510df1721debb0d678d8e424b5f64f04f820005f017cb4731f7be94cd63755787', + ); + expect(tx).not.toLog( + '[Input #0] SiblingIntrospection.cash:10 inputBytecode: 0xaa2092e16594dd458916b3aa6cae4bf41352d1b3b39658698e8cddbeedd687efec7587', + ); expect(tx).not.toLog('[Input #1] SameNameDifferentPath.cash:5 a is 0'); }); }); @@ -78,14 +67,8 @@ describe('Multi-Contract-Debugging tests', () => { const sameNameDifferentPathContract1 = new Contract(ARTIFACT_SAME_NAME_DIFFERENT_PATH, [0n], { provider }); const sameNameDifferentPathContract2 = new Contract(ARTIFACT_SAME_NAME_DIFFERENT_PATH, [1n], { provider }); - const sameNameDifferentPathContract1Utxo = provider.addUtxo( - sameNameDifferentPathContract1.address, - randomUtxo(), - ); - const sameNameDifferentPathContract2Utxo = provider.addUtxo( - sameNameDifferentPathContract2.address, - randomUtxo(), - ); + const sameNameDifferentPathContract1Utxo = provider.addUtxo(sameNameDifferentPathContract1.address, randomUtxo()); + const sameNameDifferentPathContract2Utxo = provider.addUtxo(sameNameDifferentPathContract2.address, randomUtxo()); const tx = new TransactionBuilder({ provider }) .addInput(sameNameDifferentPathContract1Utxo, sameNameDifferentPathContract1.unlock.function_1(0n)) @@ -156,7 +139,9 @@ describe('Multi-Contract-Debugging tests', () => { console.warn(transaction.getBitauthUri()); - await expect(transaction).toFailRequireWith('P2PKH.cash:4 Require statement failed at input 0 in contract P2PKH.cash at line 4.'); + await expect(transaction).toFailRequireWith( + 'P2PKH.cash:4 Require statement failed at input 0 in contract P2PKH.cash at line 4.', + ); }); it('should fail with correct error message if a require statement in contract 2', async () => { @@ -182,7 +167,9 @@ describe('Multi-Contract-Debugging tests', () => { console.warn(transaction.getBitauthUri()); - await expect(transaction).toFailRequireWith('BigInt.cash:4 Require statement failed at input 1 in contract BigInt.cash at line 4.'); + await expect(transaction).toFailRequireWith( + 'BigInt.cash:4 Require statement failed at input 1 in contract BigInt.cash at line 4.', + ); }); it('should fail with correct error message when a final verify fails in contract 1', async () => { @@ -210,7 +197,9 @@ describe('Multi-Contract-Debugging tests', () => { console.warn(transaction.getBitauthUri()); - await expect(transaction).toFailRequireWith('P2PKH.cash:5 Require statement failed at input 0 in contract P2PKH.cash at line 5'); + await expect(transaction).toFailRequireWith( + 'P2PKH.cash:5 Require statement failed at input 0 in contract P2PKH.cash at line 5', + ); }); it('should fail with correct error message when a final verify fails in contract 2', async () => { @@ -246,18 +235,13 @@ describe('Multi-Contract-Debugging tests', () => { const incorrectContract = new Contract(p2pkhArtifact, [bobPkh], { provider }); const correctLockingBytecode = addressToLockScript(correctContract.address); - const siblingIntrospectionContract = new Contract( - SiblingIntrospectionArtifact, - [correctLockingBytecode], - { provider }, - ); + const siblingIntrospectionContract = new Contract(SiblingIntrospectionArtifact, [correctLockingBytecode], { + provider, + }); const correctContractUtxo = provider.addUtxo(correctContract.address, randomUtxo()); const incorrectContractUtxo = provider.addUtxo(incorrectContract.address, randomUtxo()); - const siblingIntrospectionUtxo = provider.addUtxo( - siblingIntrospectionContract.address, - randomUtxo(), - ); + const siblingIntrospectionUtxo = provider.addUtxo(siblingIntrospectionContract.address, randomUtxo()); it('should not throw fail any require statements when introspecting correct sibling UTXOs', () => { const tx = new TransactionBuilder({ provider }) @@ -276,8 +260,12 @@ describe('Multi-Contract-Debugging tests', () => { .addOutput({ to: siblingIntrospectionContract.address, amount: siblingIntrospectionUtxo.satoshis }) .addOutput({ to: correctContract.address, amount: incorrectContractUtxo.satoshis - 2000n }); - expect(tx).toFailRequireWith('SiblingIntrospection.cash:11 Require statement failed at input 0 in contract SiblingIntrospection.cash at line 11 with the following message: input bytecode should match.'); - expect(tx).toFailRequireWith('Failing statement: require(inputBytecode == expectedLockingBytecode, \'input bytecode should match\')'); + expect(tx).toFailRequireWith( + 'SiblingIntrospection.cash:11 Require statement failed at input 0 in contract SiblingIntrospection.cash at line 11 with the following message: input bytecode should match.', + ); + expect(tx).toFailRequireWith( + "Failing statement: require(inputBytecode == expectedLockingBytecode, 'input bytecode should match')", + ); }); it('should fail with correct error message when introspected output bytecode of a sibling UTXO does not match', () => { @@ -287,8 +275,12 @@ describe('Multi-Contract-Debugging tests', () => { .addOutput({ to: siblingIntrospectionContract.address, amount: siblingIntrospectionUtxo.satoshis }) .addOutput({ to: incorrectContract.address, amount: correctContractUtxo.satoshis - 2000n }); - expect(tx).toFailRequireWith('SiblingIntrospection.cash:7 Require statement failed at input 0 in contract SiblingIntrospection.cash at line 7 with the following message: output bytecode should match.'); - expect(tx).toFailRequireWith('Failing statement: require(outputBytecode == expectedLockingBytecode, \'output bytecode should match\')'); + expect(tx).toFailRequireWith( + 'SiblingIntrospection.cash:7 Require statement failed at input 0 in contract SiblingIntrospection.cash at line 7 with the following message: output bytecode should match.', + ); + expect(tx).toFailRequireWith( + "Failing statement: require(outputBytecode == expectedLockingBytecode, 'output bytecode should match')", + ); }); }); @@ -306,14 +298,18 @@ describe('Multi-Contract-Debugging tests', () => { .addInput(functionNameCollisionUtxo, functionNameCollision.unlock.name_collision(0n)) .addOutput({ to: nameCollision.address, amount: 10000n }); - expect(transaction1).toFailRequireWith('FunctionNameCollision.cash:4 Require statement failed at input 1 in contract FunctionNameCollision.cash at line 4 with the following message: b should be 1.'); + expect(transaction1).toFailRequireWith( + 'FunctionNameCollision.cash:4 Require statement failed at input 1 in contract FunctionNameCollision.cash at line 4 with the following message: b should be 1.', + ); const transaction2 = new TransactionBuilder({ provider }) .addInput(nameCollisionUtxo, nameCollision.unlock.name_collision(1n)) .addInput(functionNameCollisionUtxo, functionNameCollision.unlock.name_collision(1n)) .addOutput({ to: nameCollision.address, amount: 10000n }); - expect(transaction2).toFailRequireWith('NameCollision.cash:5 Require statement failed at input 0 in contract NameCollision.cash at line 5 with the following message: b should be 0.'); + expect(transaction2).toFailRequireWith( + 'NameCollision.cash:5 Require statement failed at input 0 in contract NameCollision.cash at line 5 with the following message: b should be 0.', + ); }); it('should still work with different instances of the same contract, with different paths due to different constructor parameter values', () => { @@ -328,14 +324,18 @@ describe('Multi-Contract-Debugging tests', () => { .addInput(contract2Utxo, p2pkhContract2.unlock.function_1(0n)) .addOutput({ to: p2pkhContract1.address, amount: 10000n }); - expect(transaction1).toFailRequireWith('SameNameDifferentPath.cash:9 Require statement failed at input 1 in contract SameNameDifferentPath.cash at line 9 with the following message: b should not be 0.'); + expect(transaction1).toFailRequireWith( + 'SameNameDifferentPath.cash:9 Require statement failed at input 1 in contract SameNameDifferentPath.cash at line 9 with the following message: b should not be 0.', + ); const transaction2 = new TransactionBuilder({ provider }) .addInput(contract1Utxo, p2pkhContract1.unlock.function_1(1n)) .addInput(contract2Utxo, p2pkhContract2.unlock.function_1(1n)) .addOutput({ to: p2pkhContract1.address, amount: 10000n }); - expect(transaction2).toFailRequireWith('SameNameDifferentPath.cash:6 Require statement failed at input 0 in contract SameNameDifferentPath.cash at line 6 with the following message: b should be 0.'); + expect(transaction2).toFailRequireWith( + 'SameNameDifferentPath.cash:6 Require statement failed at input 0 in contract SameNameDifferentPath.cash at line 6 with the following message: b should be 0.', + ); }); }); @@ -352,7 +352,9 @@ describe('Multi-Contract-Debugging tests', () => { .addInput(contractNameCollisionUtxo, contractNameCollision.unlock.name_collision(0n)) .addOutput({ to: nameCollision.address, amount: 10000n }); - expect(() => transaction.debug()).toThrow('There are multiple artifacts with the same contractName. Please make sure that all artifacts have unique names.'); + expect(() => transaction.debug()).toThrow( + 'There are multiple artifacts with the same contractName. Please make sure that all artifacts have unique names.', + ); }); it.todo('should fail with correct error message and statement when a multiline non-require statement fails'); diff --git a/packages/cashscript/test/test-util.ts b/packages/cashscript/test/test-util.ts index e29c158e2..621ca386d 100644 --- a/packages/cashscript/test/test-util.ts +++ b/packages/cashscript/test/test-util.ts @@ -1,9 +1,4 @@ -import { - lockingBytecodeToCashAddress, - hexToBin, - Transaction, - binToHex, -} from '@bitauth/libauth'; +import { lockingBytecodeToCashAddress, hexToBin, Transaction, binToHex } from '@bitauth/libauth'; import PQueue from 'p-queue'; import pRetry from 'p-retry'; import { Output, Network, SpendableUtxo, Utxo } from '../src/interfaces.js'; @@ -47,7 +42,6 @@ export function getLargestUtxo(utxos: U[]): U { // transaction before the next one tries to spend the funder's change UTXO. const liveAddUtxoQueue = new PQueue({ concurrency: 1, interval: 3000, intervalCap: 1, strict: true }); - // Adds a UTXO to the given address on any network provider: // - On MockNetworkProvider, the UTXO is inserted directly into the mock UTXO set. // - On live providers (e.g. ElectrumNetworkProvider for chipnet), a real transaction is @@ -55,11 +49,7 @@ const liveAddUtxoQueue = new PQueue({ concurrency: 1, interval: 3000, intervalCa // the UTXO on-chain. The returned UTXO contains the real txid/vout from the broadcast // transaction. // Token UTXOs are only supported on MockNetworkProvider. -export async function addUtxo( - provider: NetworkProvider, - address: string, - utxo: Utxo, -): Promise { +export async function addUtxo(provider: NetworkProvider, address: string, utxo: Utxo): Promise { if (provider instanceof MockNetworkProvider) { return provider.addUtxo(address, utxo); } @@ -72,10 +62,9 @@ export async function addUtxo( // otherwise race to fetch and spend the same funder UTXO, causing txn-mempool-conflict. // As a fallback, p-retry retries up to 10 times on mempool conflicts if one still slips // through (e.g. the electrum server hadn't yet indexed the previous change UTXO). - const result = await liveAddUtxoQueue.add(() => pRetry( - () => sendLiveAddUtxo(provider, address, utxo), - { shouldRetry: ({ error }) => isMempoolConflictError(error) }, - )); + const result = await liveAddUtxoQueue.add(() => + pRetry(() => sendLiveAddUtxo(provider, address, utxo), { shouldRetry: ({ error }) => isMempoolConflictError(error) }), + ); if (!result) throw new Error('addUtxo: live queue returned no result'); return result; } @@ -85,15 +74,8 @@ function isMempoolConflictError(error: unknown): boolean { return message.includes('txn-mempool-conflict') || message.includes('mempool conflict'); } -async function sendLiveAddUtxo( - provider: NetworkProvider, - address: string, - utxo: Utxo, -): Promise { - const funderUtxos = (await provider.getUtxos(funderAddress)) - .filter(isNonTokenUtxo) - .sort(utxoComparator) - .reverse(); +async function sendLiveAddUtxo(provider: NetworkProvider, address: string, utxo: Utxo): Promise { + const funderUtxos = (await provider.getUtxos(funderAddress)).filter(isNonTokenUtxo).sort(utxoComparator).reverse(); const { utxos: selected } = gatherUtxos(funderUtxos, { amount: utxo.satoshis, fee: 2000n }); @@ -113,8 +95,8 @@ async function sendLiveAddUtxo( export function gatherUtxos( utxos: U[], - options?: { amount?: bigint, fee?: bigint }, -): { utxos: U[], total: bigint, changeAmount: bigint } { + options?: { amount?: bigint; fee?: bigint }, +): { utxos: U[]; total: bigint; changeAmount: bigint } { const targetUtxos: U[] = []; let total = 0n; diff --git a/packages/cashscript/test/types/Contract.types.test.ts b/packages/cashscript/test/types/Contract.types.test.ts index d94bc1244..df2657343 100644 --- a/packages/cashscript/test/types/Contract.types.test.ts +++ b/packages/cashscript/test/types/Contract.types.test.ts @@ -11,25 +11,25 @@ import { binToHex } from '@bitauth/libauth'; interface ManualArtifactType extends Artifact { constructorInputs: [ { - name: 'pkh', - type: 'bytes20', + name: 'pkh'; + type: 'bytes20'; }, - ], + ]; abi: [ { - name: 'spend', + name: 'spend'; inputs: [ { - name: 'pk', - type: 'pubkey', + name: 'pk'; + type: 'pubkey'; }, { - name: 's', - type: 'sig', + name: 's'; + type: 'sig'; }, - ], + ]; }, - ] + ]; } // Create a MockNetworkProvider for the tests @@ -211,7 +211,6 @@ const provider = new MockNetworkProvider(); } } - // describe('TransferWithTimeout contract | 3 constructor inputs | two functions (1 arg each)') { // describe('Constructor arguments') @@ -250,7 +249,10 @@ const provider = new MockNetworkProvider(); { // describe('with inline contractType') { - const contract = new Contract(transferWithTimeoutArtifact, [alicePub, bobPub, 100_000n], { provider, contractType: 'p2s' }); + const contract = new Contract(transferWithTimeoutArtifact, [alicePub, bobPub, 100_000n], { + provider, + contractType: 'p2s', + }); // it('should give type errors when accessing address and tokenAddress') // @ts-expect-error diff --git a/packages/cashscript/test/util.test.ts b/packages/cashscript/test/util.test.ts index b09cb64c1..d9076d960 100644 --- a/packages/cashscript/test/util.test.ts +++ b/packages/cashscript/test/util.test.ts @@ -1,15 +1,6 @@ import { binToHex } from '@bitauth/libauth'; -import { - asmToBytecode, - asmToScript, - bytecodeToAsm, - placeholder, -} from '@cashscript/utils'; -import { - scriptToAddress, - createUnlockingBytecode, - getInputSize, -} from '../src/utils.js'; +import { asmToBytecode, asmToScript, bytecodeToAsm, placeholder } from '@cashscript/utils'; +import { scriptToAddress, createUnlockingBytecode, getInputSize } from '../src/utils.js'; import { Network } from '../src/interfaces.js'; import { alicePkh, alicePub } from './fixture/vars.js'; diff --git a/packages/utils/src/artifact.ts b/packages/utils/src/artifact.ts index 1e664a849..0ba59e3f8 100644 --- a/packages/utils/src/artifact.ts +++ b/packages/utils/src/artifact.ts @@ -85,7 +85,7 @@ export interface Artifact { name: string; version: string; options?: CompilerOptions; - } + }; updatedAt: string; fingerprint?: string; // SHA256 of the normalized bytecode pattern (BCH bytecode fingerprinting standard) } @@ -110,12 +110,7 @@ const MAX_INLINE_OBJECT_PROPERTIES = 3; // (e.g. `requires`, `constructorInputs`, `abi` inputs) are kept on a single line so list-like data // stays compact, while standalone objects assigned to a property (e.g. `compiler.options`) keep // their values expanded one per line. -function stringify( - obj: any, - format: 'json' | 'ts', - indentationLevel: number = 1, - isArrayElement: boolean = false, -): string { +function stringify(obj: any, format: 'json' | 'ts', indentationLevel: number = 1, isArrayElement: boolean = false): string { if (typeof obj === 'string') return formatString(obj, format); // Numbers, booleans and null are represented identically in JSON and TS @@ -155,12 +150,7 @@ function formatArray( return `[\n${lines}${trailingComma}\n${indent(indentationLevel - 1)}]`; } -function formatObject( - obj: any, - format: 'json' | 'ts', - indentationLevel: number, - isArrayElement: boolean, -): string { +function formatObject(obj: any, format: 'json' | 'ts', indentationLevel: number, isArrayElement: boolean): string { const entries = Object.entries(obj).filter(([, value]) => value !== undefined); if (entries.length === 0) return '{}'; @@ -170,9 +160,7 @@ function formatObject( if (format === 'json') return JSON.stringify(key); return /^[A-Za-z_$][\w$]*$/.test(key) ? key : formatString(key, format); }; - const formatted = entries.map( - ([key, value]) => `${formatKey(key)}: ${stringify(value, format, indentationLevel + 1)}`, - ); + const formatted = entries.map(([key, value]) => `${formatKey(key)}: ${stringify(value, format, indentationLevel + 1)}`); if (isArrayElement && entries.length <= MAX_INLINE_OBJECT_PROPERTIES && canInline(obj)) { return `{ ${formatted.join(', ')} }`; @@ -186,7 +174,7 @@ function formatObject( // A container can be inlined when none of its values are themselves a non-empty object or array function canInline(container: any): boolean { const values = Array.isArray(container) ? container : Object.values(container); - return values.every((value) => ( - value === undefined || value === null || typeof value !== 'object' || Object.keys(value).length === 0 - )); + return values.every( + (value) => value === undefined || value === null || typeof value !== 'object' || Object.keys(value).length === 0, + ); } diff --git a/packages/utils/src/bip68.ts b/packages/utils/src/bip68.ts index 1c31fc4b1..747598e2d 100644 --- a/packages/utils/src/bip68.ts +++ b/packages/utils/src/bip68.ts @@ -4,10 +4,10 @@ // see https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki#compatibility const SEQUENCE_FINAL = 0xffffffff; -const SEQUENCE_LOCKTIME_DISABLE_FLAG = (1 << 31); +const SEQUENCE_LOCKTIME_DISABLE_FLAG = 1 << 31; const SEQUENCE_LOCKTIME_GRANULARITY = 9; const SEQUENCE_LOCKTIME_MASK = 0x0000ffff; -const SEQUENCE_LOCKTIME_TYPE_FLAG = (1 << 22); +const SEQUENCE_LOCKTIME_TYPE_FLAG = 1 << 22; const BLOCKS_MAX = SEQUENCE_LOCKTIME_MASK; const SECONDS_MOD = 1 << SEQUENCE_LOCKTIME_GRANULARITY; diff --git a/packages/utils/src/bitauth-script.ts b/packages/utils/src/bitauth-script.ts index 03dd67d32..7bcc8c812 100644 --- a/packages/utils/src/bitauth-script.ts +++ b/packages/utils/src/bitauth-script.ts @@ -90,7 +90,11 @@ function segmentScript(params: WalkParams): Segment[] { } const endIndex = findLineGroupEnd(script, index, locationData, tags); - segments.push({ kind: 'lineGroup', asm: scriptToBitAuthAsm(script.slice(index, endIndex)), line: getDisplayLine(locationData[index]) }); + segments.push({ + kind: 'lineGroup', + asm: scriptToBitAuthAsm(script.slice(index, endIndex)), + line: getDisplayLine(locationData[index]), + }); index = endIndex; } @@ -117,9 +121,9 @@ function annotationSegment( // A line group runs until the next opcode that belongs to a tagged range or maps to a different source line function findLineGroupEnd(script: Script, start: number, locationData: FullLocationData, tags: SourceTagEntry[]): number { const line = getDisplayLine(locationData[start]); - const nextBoundary = range(start + 1, script.length - 1).find((index) => ( - getDisplayLine(locationData[index]) !== line || findTagAt(tags, index) !== undefined - )); + const nextBoundary = range(start + 1, script.length - 1).find( + (index) => getDisplayLine(locationData[index]) !== line || findTagAt(tags, index) !== undefined, + ); return nextBoundary ?? script.length; } @@ -159,14 +163,17 @@ function renderSegments(segments: Segment[], params: WalkParams): Row[] { function deriveFunctionSectionLines(segments: Segment[], sourceLines: string[]): Set { const localFunctionSegments = segments.filter( - (segment): segment is FunctionDefinitionSegment => segment.kind === 'functionDefinition' && segment.frame.sourceFile === undefined, + (segment): segment is FunctionDefinitionSegment => + segment.kind === 'functionDefinition' && segment.frame.sourceFile === undefined, ); - return new Set(localFunctionSegments.flatMap(({ location }) => { - let lastLine = location.end.line; - while (lastLine < sourceLines.length && sourceLines[lastLine].trim() === '') lastLine += 1; - return range(location.start.line, lastLine); - })); + return new Set( + localFunctionSegments.flatMap(({ location }) => { + let lastLine = location.end.line; + while (lastLine < sourceLines.length && sourceLines[lastLine].trim() === '') lastLine += 1; + return range(location.start.line, lastLine); + }), + ); } function renderSegment(state: RenderState, segment: Segment, context: RenderContext): RenderState { @@ -208,9 +215,7 @@ function renderFunctionDefinition( const isImported = frame.sourceFile !== undefined; const sourceLines = isImported ? context.sources![frame.sourceFile!].split('\n') : context.sourceLines; - const headerRows = isImported - ? [{ asm: '', comment: `>>> imported from ${frame.sourceFile}` }] - : []; + const headerRows = isImported ? [{ asm: '', comment: `>>> imported from ${frame.sourceFile}` }] : []; return { rows: [...state.rows, ...headerRows, ...buildFunctionSection(frame, location, sourceLines), BLANK_ROW], @@ -281,16 +286,10 @@ interface Anchor { } // Compiler-injected prologue checks: emitted before the function body but executing at its top. -const PROLOGUE_KINDS = [ - SourceTagKind.LOCKTIME_GUARD, - SourceTagKind.PARAMETER_VALIDATION, -]; +const PROLOGUE_KINDS = [SourceTagKind.LOCKTIME_GUARD, SourceTagKind.PARAMETER_VALIDATION]; // Compiler-injected epilogue checks: emitted after the function/loop body -const EPILOGUE_KINDS = [ - SourceTagKind.SCOPE_CLEANUP, - SourceTagKind.LOOP_CONDITION, -]; +const EPILOGUE_KINDS = [SourceTagKind.SCOPE_CLEANUP, SourceTagKind.LOOP_CONDITION]; function deriveAnchor( tag: SourceTagEntry, diff --git a/packages/utils/src/fingerprint.ts b/packages/utils/src/fingerprint.ts index b53624d44..2310f51e4 100644 --- a/packages/utils/src/fingerprint.ts +++ b/packages/utils/src/fingerprint.ts @@ -14,9 +14,9 @@ import { generateContractBytecodeScript, Op, Script, scriptToBytecode } from './ // See: https://gitlab.com/0353F40E/smart-contract-fingerprinting/ export function computeBytecodePattern(bytecode: Uint8Array): Uint8Array { const opcodes = decodeAuthenticationInstructions(bytecode).map((instruction) => instruction.opcode); - const chunks = groupByPushRun(opcodes).map((run) => ( - isPushOpcode(run[0]) ? encodePushCount(run.length) : Uint8Array.from(run) - )); + const chunks = groupByPushRun(opcodes).map((run) => + isPushOpcode(run[0]) ? encodePushCount(run.length) : Uint8Array.from(run), + ); return flattenBinArray(chunks); } diff --git a/packages/utils/src/optimisations.ts b/packages/utils/src/optimisations.ts index ceafd7f30..674a09286 100644 --- a/packages/utils/src/optimisations.ts +++ b/packages/utils/src/optimisations.ts @@ -189,7 +189,7 @@ export const optimisationReplacements = [ // NOTE: these optimisations (as well as some others above) are currently hardcoded, but should become dynamic. // This is something we want to properly implement in v0.15 - + // OP_TUCK leaves the two operands in the opposite order, so this only holds for order-independent comparisons ['OP_DUP OP_ROT OP_NUMEQUALVERIFY', 'OP_TUCK OP_NUMEQUALVERIFY'], diff --git a/packages/utils/src/script.ts b/packages/utils/src/script.ts index 115baeb8c..3e97dc729 100644 --- a/packages/utils/src/script.ts +++ b/packages/utils/src/script.ts @@ -54,9 +54,7 @@ export function bytecodeToScript(bytecode: Uint8Array): Script { const instructions = decodeAuthenticationInstructions(bytecode); // Convert the AuthenticationInstructions to script elements - const script = instructions.map((instruction) => ( - 'data' in instruction ? instruction.data : instruction.opcode - )); + const script = instructions.map((instruction) => ('data' in instruction ? instruction.data : instruction.opcode)); return script; } @@ -116,10 +114,7 @@ export function bytecodeToBitAuthAsm(bytecode: Uint8Array): string { } export function countOpcodes(script: Script): number { - return script - .filter((opOrData) => typeof opOrData === 'number') - .filter((op) => (op as number) > Op.OP_16) - .length; + return script.filter((opOrData) => typeof opOrData === 'number').filter((op) => (op as number) > Op.OP_16).length; } export function calculateBytesize(script: Script): number { @@ -172,7 +167,14 @@ export function optimiseBytecode( ): OptimiseBytecodeResult { for (let i = 0; i < runs; i += 1) { const result = replaceOps( - script, locationData, logs, requires, sourceTags, inlineRanges, constructorParamLength, optimisationReplacements, + script, + locationData, + logs, + requires, + sourceTags, + inlineRanges, + constructorParamLength, + optimisationReplacements, ); // Break on fixed point @@ -182,7 +184,12 @@ export function optimiseBytecode( } return { - script, locationData, logs, requires, sourceTags: reconcileScopeCleanupTags(script, sourceTags), inlineRanges, + script, + locationData, + logs, + requires, + sourceTags: reconcileScopeCleanupTags(script, sourceTags), + inlineRanges, }; } @@ -196,8 +203,9 @@ function reconcileScopeCleanupTags(script: Script, sourceTags: SourceTagEntry[]) const cleanupTags = sourceTags.filter((tag) => { if (tag.kind !== SourceTagKind.SCOPE_CLEANUP) return false; - const isOnlyCleanupOpcodes = range(tag.startIndex, tag.endIndex) - .every((index) => SCOPE_CLEANUP_OPCODES.includes(script[index] as Op)); + const isOnlyCleanupOpcodes = range(tag.startIndex, tag.endIndex).every((index) => + SCOPE_CLEANUP_OPCODES.includes(script[index] as Op), + ); if (!isOnlyCleanupOpcodes) return false; const overlapsOtherTag = otherTags.some((other) => tagsOverlap(tag, other)); @@ -309,9 +317,8 @@ function replaceOps( // Positions after the replaced pattern shift back by the length difference; positions inside // the replaced pattern clamp to the pattern's start. (Positions inside a pattern are impossible // for the current set of optimisations, but the clamp future-proofs the code.) - const adjustPosition = (position: number, patternStart: number): number => ( - position >= patternStart ? Math.max(patternStart, position - lengthDiff) : position - ); + const adjustPosition = (position: number, patternStart: number): number => + position >= patternStart ? Math.max(patternStart, position - lengthDiff) : position; newRequires = newRequires.map((require) => ({ ...require, @@ -336,7 +343,9 @@ function replaceOps( const addedTransformationsCount = data.ip - scriptIp; const addedTransformations = patternTokens.slice(0, addedTransformationsCount).join(' '); - const newTransformations = data.transformations ? `${addedTransformations} ${data.transformations}` : addedTransformations; + const newTransformations = data.transformations + ? `${addedTransformations} ${data.transformations}` + : addedTransformations; return { ...data, @@ -360,7 +369,6 @@ function replaceOps( startIp: adjustPosition(inlineRange.startIp, scriptIp), endIp: adjustPosition(inlineRange.endIp, scriptIp), })); - } asm = asm.replace(regex, replacement).replace(/\s+/g, ' ').trim(); diff --git a/packages/utils/src/source-map.ts b/packages/utils/src/source-map.ts index e1a4720c1..a0374968d 100644 --- a/packages/utils/src/source-map.ts +++ b/packages/utils/src/source-map.ts @@ -33,51 +33,53 @@ export function generateSourceMap(locationData: FullLocationData): string { let prevEndColumn = 0; let prevHint = PositionHint.START; - return locationData.map(({ location, positionHint }: SingleLocationData) => { - const prevStartLineString = prevStartLine === location.start.line ? '' : String(location.start.line); - prevStartLine = location.start.line; - - const prevStartColumnString = prevStartColumn === location.start.column ? '' : String(location.start.column); - prevStartColumn = location.start.column; - - const prevEndLineString = prevEndLine === location.end.line ? '' : String(location.end.line); - prevEndLine = location.end.line; - - const prevEndColumnString = prevEndColumn === location.end.column ? '' : String(location.end.column); - prevEndColumn = location.end.column; - - const hint = positionHint ?? PositionHint.START; - const prevHintString = prevHint === hint ? '' : String(hint); - prevHint = hint; - - let result = ''; - if (prevStartLineString) { - result += prevStartLineString; - } - - result += ':'; - if (prevStartColumnString) { - result += prevStartColumnString; - } - - result += ':'; - if (prevEndLineString) { - result += prevEndLineString; - } - - result += ':'; - if (prevEndColumnString) { - result += prevEndColumnString; - } - - result += ':'; - if (prevHintString) { - result += prevHintString; - } - - result = result.replace(/:*$/, ''); - return result; - }).join(';'); + return locationData + .map(({ location, positionHint }: SingleLocationData) => { + const prevStartLineString = prevStartLine === location.start.line ? '' : String(location.start.line); + prevStartLine = location.start.line; + + const prevStartColumnString = prevStartColumn === location.start.column ? '' : String(location.start.column); + prevStartColumn = location.start.column; + + const prevEndLineString = prevEndLine === location.end.line ? '' : String(location.end.line); + prevEndLine = location.end.line; + + const prevEndColumnString = prevEndColumn === location.end.column ? '' : String(location.end.column); + prevEndColumn = location.end.column; + + const hint = positionHint ?? PositionHint.START; + const prevHintString = prevHint === hint ? '' : String(hint); + prevHint = hint; + + let result = ''; + if (prevStartLineString) { + result += prevStartLineString; + } + + result += ':'; + if (prevStartColumnString) { + result += prevStartColumnString; + } + + result += ':'; + if (prevEndLineString) { + result += prevEndLineString; + } + + result += ':'; + if (prevEndColumnString) { + result += prevEndColumnString; + } + + result += ':'; + if (prevHintString) { + result += prevHintString; + } + + result = result.replace(/:*$/, ''); + return result; + }) + .join(';'); } export const sourceMapToLocationData = (sourceMap: string): FullLocationData => { @@ -154,10 +156,7 @@ export function generateInlineRanges(entries: InlineRange[]): string { .join(';'); } -export function parseAndResolveInlineRanges( - inlineRanges?: string, - frames?: readonly DebugFrame[], -): InlineRange[] { +export function parseAndResolveInlineRanges(inlineRanges?: string, frames?: readonly DebugFrame[]): InlineRange[] { if (!inlineRanges || !frames) return []; return parseInlineRanges(inlineRanges).flatMap(({ startIp, endIp, frameName }) => { @@ -166,7 +165,7 @@ export function parseAndResolveInlineRanges( }); } -function parseInlineRanges(inlineRanges: string): { startIp: number, endIp: number, frameName: string }[] { +function parseInlineRanges(inlineRanges: string): { startIp: number; endIp: number; frameName: string }[] { if (!inlineRanges) return []; return inlineRanges.split(';').map((segment) => { const [startStr, endStr, frameName] = segment.split(':'); diff --git a/packages/utils/src/types.ts b/packages/utils/src/types.ts index a36821c79..789e7463d 100644 --- a/packages/utils/src/types.ts +++ b/packages/utils/src/types.ts @@ -4,7 +4,7 @@ export class ArrayType { constructor( public elementType: Type, public bound?: number, - ) { } + ) {} toString(): string { return `${this.elementType}[${this.bound ?? ''}]`; @@ -12,9 +12,7 @@ export class ArrayType { } export class BytesType { - constructor( - public bound?: number, - ) { } + constructor(public bound?: number) {} static fromString(str: string): BytesType { const bound = str === 'byte' ? 1 : Number.parseInt(str.substring(5), 10) || undefined; @@ -27,9 +25,7 @@ export class BytesType { } export class TupleType { - constructor( - public elementTypes: Type[], - ) { } + constructor(public elementTypes: Type[]) {} toString(): string { return `(${this.elementTypes.join(', ')})`; @@ -119,8 +115,10 @@ export function implicitlyCastable(actual?: Type, expected?: Type): boolean { if (actual === PrimitiveType.VOID || expected === PrimitiveType.VOID) return false; if (actual instanceof TupleType && expected instanceof TupleType) { - return actual.elementTypes.length === expected.elementTypes.length - && actual.elementTypes.every((elementType, i) => implicitlyCastable(elementType, expected.elementTypes[i])); + return ( + actual.elementTypes.length === expected.elementTypes.length && + actual.elementTypes.every((elementType, i) => implicitlyCastable(elementType, expected.elementTypes[i])) + ); } // Can't cast between Tuple and non-Tuple @@ -181,10 +179,7 @@ export function arrayType(types: Type[]): Type | undefined { return resType; } -export function implicitlyCastableSignature( - actual: Type[], - expected: Type[], -): boolean { +export function implicitlyCastableSignature(actual: Type[], expected: Type[]): boolean { if (actual.length !== expected.length) return false; return expected.every((t, i) => implicitlyCastable(actual[i], t)); } @@ -200,12 +195,12 @@ export function isPrimitive(type: Type): type is PrimitiveType { export interface LocationI { start: { - line: number, - column: number + line: number; + column: number; }; end: { - line: number, - column: number + line: number; + column: number; }; } diff --git a/packages/utils/test/data.test.ts b/packages/utils/test/data.test.ts index 813c2fe07..8bbe3a670 100644 --- a/packages/utils/test/data.test.ts +++ b/packages/utils/test/data.test.ts @@ -1,13 +1,5 @@ import { hexToBin, VmNumberError } from '@bitauth/libauth'; -import { - decodeBool, - decodeInt, - decodeString, - encodeBool, - encodeInt, - encodeString, - placeholder, -} from '../src/index.js'; +import { decodeBool, decodeInt, decodeString, encodeBool, encodeInt, encodeString, placeholder } from '../src/index.js'; describe('data utils', () => { describe('encodeBool()', () => { diff --git a/packages/utils/test/fingerprint.test.ts b/packages/utils/test/fingerprint.test.ts index 4f6062200..99bbb9fe6 100644 --- a/packages/utils/test/fingerprint.test.ts +++ b/packages/utils/test/fingerprint.test.ts @@ -1,15 +1,8 @@ import { binToHex, flattenBinArray } from '@bitauth/libauth'; -import { - computeBytecodeFingerprint, - computeBytecodePattern, - isPushOpcode, - Op, - sha256, -} from '../src/index.js'; - -const concat = (...parts: Array): Uint8Array => ( - flattenBinArray(parts.map((part) => (typeof part === 'number' ? Uint8Array.of(part) : part))) -); +import { computeBytecodeFingerprint, computeBytecodePattern, isPushOpcode, Op, sha256 } from '../src/index.js'; + +const concat = (...parts: Array): Uint8Array => + flattenBinArray(parts.map((part) => (typeof part === 'number' ? Uint8Array.of(part) : part))); const zeroes = (length: number): Uint8Array => new Uint8Array(length); @@ -103,9 +96,8 @@ describe('fingerprint utils', () => { }); it('is invariant to the values of pushed data', () => { - const p2pkh = (pkh: Uint8Array): Uint8Array => ( - concat(Op.OP_DUP, Op.OP_HASH160, Op.OP_PUSHBYTES_20, pkh, Op.OP_EQUALVERIFY, Op.OP_CHECKSIG) - ); + const p2pkh = (pkh: Uint8Array): Uint8Array => + concat(Op.OP_DUP, Op.OP_HASH160, Op.OP_PUSHBYTES_20, pkh, Op.OP_EQUALVERIFY, Op.OP_CHECKSIG); const bytecodeA = p2pkh(new Uint8Array(20).fill(0xaa)); const bytecodeB = p2pkh(new Uint8Array(20).fill(0xbb)); expect(computeBytecodeFingerprint(bytecodeA)).toBe(computeBytecodeFingerprint(bytecodeB)); diff --git a/packages/utils/test/hash.test.ts b/packages/utils/test/hash.test.ts index b1314fe11..1fa125708 100644 --- a/packages/utils/test/hash.test.ts +++ b/packages/utils/test/hash.test.ts @@ -1,45 +1,42 @@ import { hexToBin } from '@bitauth/libauth'; -import { - hash160, - hash256, - ripemd160, - sha256, - sha512, -} from '../src/index.js'; +import { hash160, hash256, ripemd160, sha256, sha512 } from '../src/index.js'; describe('hashing functions', () => { describe('sha512()', () => { it('should perform a sha512 hash', () => { - expect(sha512(hexToBin('000000000000000000'))) - .toEqual(hexToBin('a85de39409374651002c84cba7c928eb96fb82f88acc2aeac392985def3e1389346122b82c9c47b743a5c2764bb0e3f5c309af7202dbe723e69a5193e84fcbc4')); + expect(sha512(hexToBin('000000000000000000'))).toEqual( + hexToBin( + 'a85de39409374651002c84cba7c928eb96fb82f88acc2aeac392985def3e1389346122b82c9c47b743a5c2764bb0e3f5c309af7202dbe723e69a5193e84fcbc4', + ), + ); }); }); describe('sha256()', () => { it('should perform a sha256 hash', () => { - expect(sha256(hexToBin('000000000000000000'))) - .toEqual(hexToBin('3e7077fd2f66d689e0cee6a7cf5b37bf2dca7c979af356d0a31cbc5c85605c7d')); + expect(sha256(hexToBin('000000000000000000'))).toEqual( + hexToBin('3e7077fd2f66d689e0cee6a7cf5b37bf2dca7c979af356d0a31cbc5c85605c7d'), + ); }); }); describe('ripemd160()', () => { it('should perform a ripemd160 hash', () => { - expect(ripemd160(hexToBin('000000000000000000'))) - .toEqual(hexToBin('f4b7fe5e9c0898fb14bf52365feece17d5047199')); + expect(ripemd160(hexToBin('000000000000000000'))).toEqual(hexToBin('f4b7fe5e9c0898fb14bf52365feece17d5047199')); }); }); describe('hash160()', () => { it('should perform a sha256 hash, then a ripemd160 hash on the result', () => { - expect(hash160(hexToBin('000000000000000000'))) - .toEqual(hexToBin('85179ad383f90555e7b98bfa4e9a560ab6eba1e6')); + expect(hash160(hexToBin('000000000000000000'))).toEqual(hexToBin('85179ad383f90555e7b98bfa4e9a560ab6eba1e6')); }); }); describe('hash256()', () => { it('should perform a sha256 hash, then a sha256 hash on the result', () => { - expect(hash256(hexToBin('000000000000000000'))) - .toEqual(hexToBin('edb908054ac1409be5f77d5369c6e03490b2f6676d68d0b3370f8159e0fdadf9')); + expect(hash256(hexToBin('000000000000000000'))).toEqual( + hexToBin('edb908054ac1409be5f77d5369c6e03490b2f6676d68d0b3370f8159e0fdadf9'), + ); }); }); }); diff --git a/packages/utils/test/manual-optimisation-proofs.test.ts b/packages/utils/test/manual-optimisation-proofs.test.ts index d2a50d131..cbbb98bd1 100644 --- a/packages/utils/test/manual-optimisation-proofs.test.ts +++ b/packages/utils/test/manual-optimisation-proofs.test.ts @@ -12,9 +12,6 @@ describe('Manual Optimisation Proofs', () => { // <1> <1> OP_LESSTHANOREQUAL // OP_EQUALVERIFY - - - // <1> <2> OP_LESSTHAN OP_NOT // <1> <2> OP_GREATERTHANOREQUAL // OP_EQUALVERIFY @@ -27,8 +24,6 @@ describe('Manual Optimisation Proofs', () => { // <1> <1> OP_GREATERTHANOREQUAL // OP_EQUALVERIFY - - // <1> <2> OP_LESSTHANOREQUAL OP_NOT // <1> <2> OP_GREATERTHAN // OP_EQUALVERIFY @@ -41,8 +36,6 @@ describe('Manual Optimisation Proofs', () => { // <1> <1> OP_GREATERTHAN // OP_EQUALVERIFY - - // <1> <2> OP_GREATERTHANOREQUAL OP_NOT // <1> <2> OP_LESSTHAN // OP_EQUALVERIFY diff --git a/packages/utils/test/script.test.ts b/packages/utils/test/script.test.ts index fa7ae8f4a..a85f48716 100644 --- a/packages/utils/test/script.test.ts +++ b/packages/utils/test/script.test.ts @@ -92,15 +92,15 @@ describe('script utils', () => { hexToBin('0000000000000001'), ]; - const output = hexToBin('04534c500001010747454e45534953034353530d43617368536372697074534c501768747470733a2f2f636173687363726970742e6f72672f4c0001080102080000000000000001'); + const output = hexToBin( + '04534c500001010747454e45534953034353530d43617368536372697074534c501768747470733a2f2f636173687363726970742e6f72672f4c0001080102080000000000000001', + ); expect(encodeNullDataScript(input)).toEqual(output); }); }); - describe.skip('TODO: generateContractBytecodeScript()', () => { - }); + describe.skip('TODO: generateContractBytecodeScript()', () => {}); - describe.skip('TODO: optimiseBytecode()', () => { - }); + describe.skip('TODO: optimiseBytecode()', () => {}); }); diff --git a/packages/utils/test/types.test.ts b/packages/utils/test/types.test.ts index 9489ae947..3e1680b8e 100644 --- a/packages/utils/test/types.test.ts +++ b/packages/utils/test/types.test.ts @@ -1,11 +1,4 @@ -import { - ArrayType, - BytesType, - explicitlyCastable, - parseType, - PrimitiveType, - TupleType, -} from '../src/index.js'; +import { ArrayType, BytesType, explicitlyCastable, parseType, PrimitiveType, TupleType } from '../src/index.js'; describe('type utilities', () => { describe('explicitlyCastable()', () => { @@ -15,43 +8,32 @@ describe('type utilities', () => { }); it('cannot cast tuples', () => { - expect(explicitlyCastable(PrimitiveType.INT, new TupleType(PrimitiveType.INT, PrimitiveType.INT))) - .toEqual(false); - expect(explicitlyCastable(new TupleType(PrimitiveType.INT, PrimitiveType.INT), PrimitiveType.STRING)) - .toEqual(false); + expect(explicitlyCastable(PrimitiveType.INT, new TupleType(PrimitiveType.INT, PrimitiveType.INT))).toEqual(false); + expect(explicitlyCastable(new TupleType(PrimitiveType.INT, PrimitiveType.INT), PrimitiveType.STRING)).toEqual(false); }); it('cannot cast between array an non-array', () => { - expect(explicitlyCastable(PrimitiveType.INT, new ArrayType(PrimitiveType.INT))) - .toEqual(false); + expect(explicitlyCastable(PrimitiveType.INT, new ArrayType(PrimitiveType.INT))).toEqual(false); }); it('cannot cast arrays if their elements cannot be cast', () => { - expect( - explicitlyCastable(new ArrayType(PrimitiveType.BOOL), new ArrayType(PrimitiveType.STRING)), - ).toEqual(false); + expect(explicitlyCastable(new ArrayType(PrimitiveType.BOOL), new ArrayType(PrimitiveType.STRING))).toEqual(false); }); it('can cast arrays if their elements can be cast', () => { - expect( - explicitlyCastable(new ArrayType(PrimitiveType.BOOL), new ArrayType(PrimitiveType.INT)), - ).toEqual(true); + expect(explicitlyCastable(new ArrayType(PrimitiveType.BOOL), new ArrayType(PrimitiveType.INT))).toEqual(true); }); // TODO: fully test cast combinations }); - describe.skip('TODO: implicitlyCastable()', () => { - }); + describe.skip('TODO: implicitlyCastable()', () => {}); - describe.skip('TODO: resultingType()', () => { - }); + describe.skip('TODO: resultingType()', () => {}); - describe.skip('TODO: arrayType()', () => { - }); + describe.skip('TODO: arrayType()', () => {}); - describe.skip('TODO: implicitlyCastableSignature()', () => { - }); + describe.skip('TODO: implicitlyCastableSignature()', () => {}); describe('parseType()', () => { it('should parse primitive type strings', () => { From 3322c11ad5f63a23525434c2083727b1a7a6d4a0 Mon Sep 17 00:00:00 2001 From: Mathieu Geukens Date: Sun, 29 Nov 2026 08:49:10 +0100 Subject: [PATCH 3/3] chore: check formatting in CI and ignore the reformat in git blame Refs #303 Co-Authored-By: Claude Fable 5.2 --- .git-blame-ignore-revs | 2 ++ .github/workflows/github-actions.yml | 3 +++ 2 files changed, 5 insertions(+) create mode 100644 .git-blame-ignore-revs diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 000000000..add1688de --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,2 @@ +# Mechanical reformat with oxfmt +7e77c2a9f495589a194d24d50ba623879d2a48fa diff --git a/.github/workflows/github-actions.yml b/.github/workflows/github-actions.yml index 8beccf5e4..e2e598cd6 100644 --- a/.github/workflows/github-actions.yml +++ b/.github/workflows/github-actions.yml @@ -40,6 +40,9 @@ jobs: - name: Run linter run: pnpm lint + - name: Check formatting + run: pnpm format:check + - name: Run spellchecker run: pnpm spellcheck