diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index c8aebcf651..23ba5e0904 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -116,6 +116,7 @@ /packages/eth-json-rpc-middleware/src/wallet.* @MetaMask/confirmations @MetaMask/wallet-api-platform-engineers /packages/eth-json-rpc-provider @MetaMask/wallet-integrations @MetaMask/core-platform /packages/foundryup @MetaMask/mobile-platform @MetaMask/extension-platform +/packages/solana-test-validator-up @MetaMask/mobile-platform @MetaMask/extension-platform @MetaMask/networks /packages/json-rpc-engine @MetaMask/wallet-integrations @MetaMask/core-platform /packages/json-rpc-middleware-stream @MetaMask/wallet-integrations @MetaMask/core-platform /packages/keyring-controller @MetaMask/accounts-engineers @MetaMask/core-platform @@ -223,6 +224,8 @@ /packages/app-metadata-controller/CHANGELOG.md @MetaMask/mobile-platform @MetaMask/core-platform /packages/foundryup/package.json @MetaMask/mobile-platform @MetaMask/extension-platform @MetaMask/core-platform /packages/foundryup/CHANGELOG.md @MetaMask/mobile-platform @MetaMask/extension-platform @MetaMask/core-platform +/packages/solana-test-validator-up/package.json @MetaMask/mobile-platform @MetaMask/extension-platform @MetaMask/networks @MetaMask/core-platform +/packages/solana-test-validator-up/CHANGELOG.md @MetaMask/mobile-platform @MetaMask/extension-platform @MetaMask/networks @MetaMask/core-platform /packages/seedless-onboarding-controller/package.json @MetaMask/web3auth @MetaMask/core-platform /packages/seedless-onboarding-controller/CHANGELOG.md @MetaMask/web3auth @MetaMask/core-platform /packages/shield-controller/package.json @MetaMask/web3auth @MetaMask/core-platform diff --git a/README.md b/README.md index 64a2300566..3121f8d7ee 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,7 @@ Each package in this repository has its own README where you can find installati - [`@metamask/signature-controller`](packages/signature-controller) - [`@metamask/snap-account-service`](packages/snap-account-service) - [`@metamask/social-controllers`](packages/social-controllers) +- [`@metamask/solana-test-validator-up`](packages/solana-test-validator-up) - [`@metamask/storage-service`](packages/storage-service) - [`@metamask/subscription-controller`](packages/subscription-controller) - [`@metamask/transaction-controller`](packages/transaction-controller) @@ -191,6 +192,7 @@ linkStyle default opacity:0.5 signature_controller(["@metamask/signature-controller"]); snap_account_service(["@metamask/snap-account-service"]); social_controllers(["@metamask/social-controllers"]); + solana_test_validator_up(["@metamask/solana-test-validator-up"]); storage_service(["@metamask/storage-service"]); subscription_controller(["@metamask/subscription-controller"]); transaction_controller(["@metamask/transaction-controller"]); diff --git a/packages/solana-test-validator-up/CHANGELOG.md b/packages/solana-test-validator-up/CHANGELOG.md new file mode 100644 index 0000000000..654712d58b --- /dev/null +++ b/packages/solana-test-validator-up/CHANGELOG.md @@ -0,0 +1,14 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added + +- Add the `@metamask/solana-test-validator-up` package ([#8826](https://github.com/MetaMask/core/pull/8826)). + +[Unreleased]: https://github.com/MetaMask/core/ diff --git a/packages/solana-test-validator-up/LICENSE b/packages/solana-test-validator-up/LICENSE new file mode 100644 index 0000000000..9ec4f4514e --- /dev/null +++ b/packages/solana-test-validator-up/LICENSE @@ -0,0 +1,6 @@ +This project is licensed under either of + + * MIT license ([LICENSE.MIT](LICENSE.MIT)) + * Apache License, Version 2.0 ([LICENSE.APACHE2](LICENSE.APACHE2)) + +at your option. diff --git a/packages/solana-test-validator-up/LICENSE.APACHE2 b/packages/solana-test-validator-up/LICENSE.APACHE2 new file mode 100644 index 0000000000..e6e77b0890 --- /dev/null +++ b/packages/solana-test-validator-up/LICENSE.APACHE2 @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/solana-test-validator-up/LICENSE.MIT b/packages/solana-test-validator-up/LICENSE.MIT new file mode 100644 index 0000000000..fe29e78e0f --- /dev/null +++ b/packages/solana-test-validator-up/LICENSE.MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 MetaMask + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/solana-test-validator-up/README.md b/packages/solana-test-validator-up/README.md new file mode 100644 index 0000000000..3af5881c10 --- /dev/null +++ b/packages/solana-test-validator-up/README.md @@ -0,0 +1,116 @@ +# `@metamask/solana-test-validator-up` + +`solana-test-validator-up` installs a pinned Solana/Agave runtime for local +development and CI. It follows the same runtime-only shape as +`@metamask/foundryup`: this package installs external runtime artifacts into the +MetaMask cache and exposes binaries in `node_modules/.bin`; the consuming test +harness owns process startup, local-validator config, readiness checks, and +seeding. + +This package does not use Docker and does not start or seed a Solana node. + +## Usage + +Install the package in the consuming repo: + +```bash +yarn add @metamask/solana-test-validator-up +npm install @metamask/solana-test-validator-up +``` + +For Yarn v4 projects, it is usually simplest to add package scripts in the +consuming repo: + +```json +{ + "scripts": { + "solana-test-validator-up": "node_modules/.bin/solana-test-validator-up", + "solana-test-validator": "node_modules/.bin/solana-test-validator", + "solana": "node_modules/.bin/solana" + } +} +``` + +Install solana-test-validator and the Solana CLI: + +```bash +yarn solana-test-validator-up install +``` + +Run the installed validator wrapper: + +```bash +node_modules/.bin/solana-test-validator --reset +``` + +For MetaMask Extension E2E tests, the Solana seeder should spawn +`node_modules/.bin/solana-test-validator`, pass its generated local-validator +ports and ledger directory, poll JSON-RPC directly, and perform all account +seeding itself. + +## Installed Artifacts + +`solana-test-validator-up` installs: + +- a platform-specific Solana/Agave release archive +- a `node_modules/.bin/solana-test-validator` wrapper +- a `node_modules/.bin/solana` wrapper + +## CLI + +```bash +solana-test-validator-up [install] [options] +solana-test-validator-up cache clean [options] +``` + +Options: + +- `--bin-directory `: directory for generated wrappers. Defaults to + `node_modules/.bin`. +- `--cache-directory `: artifact cache directory. Defaults to + `.metamask/cache`. +- `--release-url ` and `--release-checksum `: override the Solana + release archive for the current platform. +- `--platform `: override platform selection, for example + `linux-x64`. + +## Default Release + +The package currently pins Agave `v3.1.14` for `darwin-arm64`, `darwin-x64`, +and `linux-x64`. + +## Cache + +The cache defaults to `.metamask/cache` in the current repo. If `.yarnrc.yml` +contains `enableGlobalCache: true`, the cache moves to `~/.cache/metamask`, +matching the `@metamask/foundryup` behavior. + +Clean only this package's cache namespace: + +```bash +yarn solana-test-validator-up cache clean +``` + +## Package Config + +The consuming repo can override the pinned artifact URLs and checksums in its +root `package.json`: + +```json +{ + "solanaTestValidatorUp": { + "release": { + "version": "v3.1.14", + "platforms": { + "linux-x64": { + "url": "https://github.com/anza-xyz/agave/releases/download/v3.1.14/solana-release-x86_64-unknown-linux-gnu.tar.bz2", + "checksum": "06f97c065cc977cbec2f13ffc9bc9d3b92fef485431fcb370a269de69532ef51" + } + } + } + } +} +``` + +Supported package config keys are `solanaTestValidatorUp`, +`solanatestvalidatorup`, and `solana-test-validator-up`. diff --git a/packages/solana-test-validator-up/jest.config.js b/packages/solana-test-validator-up/jest.config.js new file mode 100644 index 0000000000..8a2791c96d --- /dev/null +++ b/packages/solana-test-validator-up/jest.config.js @@ -0,0 +1,32 @@ +/* + * For a detailed explanation regarding each configuration property and type check, visit: + * https://jestjs.io/docs/configuration + */ + +const merge = require('deepmerge'); +const path = require('path'); + +const baseConfig = require('../../jest.config.packages'); + +const displayName = path.basename(__dirname); + +module.exports = merge(baseConfig, { + // The display name when running multiple projects + displayName, + + // The CLI entrypoint is exercised through package builds and installed-bin smoke tests. + coveragePathIgnorePatterns: [ + ...baseConfig.coveragePathIgnorePatterns, + './src/bin/solana-test-validator-up.ts', + ], + + // An object that configures minimum threshold enforcement for coverage results + coverageThreshold: { + global: { + branches: 35, + functions: 60, + lines: 65, + statements: 65, + }, + }, +}); diff --git a/packages/solana-test-validator-up/package.json b/packages/solana-test-validator-up/package.json new file mode 100644 index 0000000000..d09693597e --- /dev/null +++ b/packages/solana-test-validator-up/package.json @@ -0,0 +1,71 @@ +{ + "name": "@metamask/solana-test-validator-up", + "version": "0.0.0", + "description": "solana-test-validator runtime installer for MetaMask E2E tests", + "keywords": [ + "Ethereum", + "MetaMask" + ], + "homepage": "https://github.com/MetaMask/core/tree/main/packages/solana-test-validator-up#readme", + "bugs": { + "url": "https://github.com/MetaMask/core/issues" + }, + "license": "(MIT OR Apache-2.0)", + "repository": { + "type": "git", + "url": "https://github.com/MetaMask/core.git" + }, + "bin": "./dist/bin/solana-test-validator-up.mjs", + "files": [ + "dist/" + ], + "sideEffects": false, + "main": "./dist/index.cjs", + "types": "./dist/index.d.cts", + "exports": { + ".": { + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } + }, + "./package.json": "./package.json" + }, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, + "scripts": { + "build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references", + "build:all": "ts-bridge --project tsconfig.build.json --verbose --clean", + "build:docs": "typedoc", + "changelog:update": "../../scripts/update-changelog.sh @metamask/solana-test-validator-up", + "changelog:validate": "../../scripts/validate-changelog.sh @metamask/solana-test-validator-up", + "messenger-action-types:check": "tsx ../../packages/messenger-cli/src/cli.ts --formatter oxfmt --check", + "messenger-action-types:generate": "tsx ../../packages/messenger-cli/src/cli.ts --formatter oxfmt --generate", + "since-latest-release": "../../scripts/since-latest-release.sh", + "test": "NODE_OPTIONS=--experimental-vm-modules jest --reporters=jest-silent-reporter", + "test:clean": "NODE_OPTIONS=--experimental-vm-modules jest --clearCache", + "test:verbose": "NODE_OPTIONS=--experimental-vm-modules jest --verbose", + "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch" + }, + "devDependencies": { + "@metamask/auto-changelog": "^6.1.0", + "@ts-bridge/cli": "^0.6.4", + "@types/jest": "^29.5.14", + "deepmerge": "^4.2.2", + "jest": "^29.7.0", + "ts-jest": "^29.2.5", + "tsx": "^4.20.5", + "typedoc": "^0.25.13", + "typedoc-plugin-missing-exports": "^2.0.0", + "typescript": "~5.3.3" + }, + "engines": { + "node": "^18.18 || >=20" + } +} diff --git a/packages/solana-test-validator-up/src/bin/solana-test-validator-up.ts b/packages/solana-test-validator-up/src/bin/solana-test-validator-up.ts new file mode 100644 index 0000000000..77c33bc3d7 --- /dev/null +++ b/packages/solana-test-validator-up/src/bin/solana-test-validator-up.ts @@ -0,0 +1,64 @@ +#!/usr/bin/env node +/* eslint-disable no-restricted-globals */ +import { + cleanSolanaTestValidatorCache, + installSolanaTestValidator, + parseSolanaTestValidatorInstallCliOptions, + readSolanaTestValidatorInstallOptionsFromPackageJson, +} from '../install'; + +async function main(): Promise { + const [command, ...args] = process.argv.slice(2); + + if (command === '--help' || command === 'help') { + printHelp(); + return; + } + + if (command === 'cache' && args[0] === 'clean') { + await cleanSolanaTestValidatorCache({ + ...readSolanaTestValidatorInstallOptionsFromPackageJson(), + ...parseSolanaTestValidatorInstallCliOptions(args.slice(1)), + }); + console.log('[solana-test-validator-up] cache cleaned'); + return; + } + + const installArgs = command === 'install' ? args : process.argv.slice(2); + const result = await installSolanaTestValidator({ + ...readSolanaTestValidatorInstallOptionsFromPackageJson(), + ...parseSolanaTestValidatorInstallCliOptions(installArgs), + }); + + console.log( + `[solana-test-validator-up] Solana release ${ + result.cacheHit ? 'found in cache' : 'installed' + }`, + ); + console.log( + `[solana-test-validator-up] solana-test-validator installed at ${result.binaryPath}`, + ); +} + +main().catch((error) => { + console.error(error); + process.exit(1); +}); + +function printHelp(): void { + console.log(`Usage: solana-test-validator-up [install] [options] + solana-test-validator-up cache clean [options] + +Commands: + install Install solana-test-validator and solana CLI. Default command. + cache clean Remove cached solana-test-validator-up artifacts. + +Options: + --bin-directory Directory for executable wrappers. + Defaults to node_modules/.bin. + --cache-directory Cache directory. Defaults to .metamask/cache. + --release-url Solana release archive URL for the current platform. + --release-checksum Expected Solana release SHA-256 checksum. + --platform Override platform key, e.g. linux-x64. + --help Show this help text.`); +} diff --git a/packages/solana-test-validator-up/src/index.ts b/packages/solana-test-validator-up/src/index.ts new file mode 100644 index 0000000000..b1acf97cfc --- /dev/null +++ b/packages/solana-test-validator-up/src/index.ts @@ -0,0 +1,15 @@ +export { + SOLANA_TEST_VALIDATOR_DEFAULT_RELEASE, + cleanSolanaTestValidatorCache, + getSolanaTestValidatorCacheDirectory, + installSolanaTestValidator, + parseSolanaTestValidatorInstallCliOptions, + readSolanaTestValidatorInstallOptionsFromPackageJson, +} from './install'; +export type { + SolanaTestValidatorArtifactConfig, + SolanaTestValidatorArtifactPlatformConfig, + SolanaTestValidatorInstallDependencies, + SolanaTestValidatorInstallOptions, + SolanaTestValidatorInstallResult, +} from './install'; diff --git a/packages/solana-test-validator-up/src/install.test.ts b/packages/solana-test-validator-up/src/install.test.ts new file mode 100644 index 0000000000..f5a1f6cf53 --- /dev/null +++ b/packages/solana-test-validator-up/src/install.test.ts @@ -0,0 +1,317 @@ +/* eslint-disable jest/expect-expect, n/no-sync */ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + existsSync, + lstatSync, + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import { mkdir, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { + SOLANA_TEST_VALIDATOR_DEFAULT_RELEASE, + cleanSolanaTestValidatorCache, + getSolanaTestValidatorCacheDirectory, + installSolanaTestValidator, + parseSolanaTestValidatorInstallCliOptions, + readSolanaTestValidatorInstallOptionsFromPackageJson, +} from './install'; +import type { SolanaTestValidatorInstallDependencies } from './install'; + +describe('solana-test-validator-up installer', () => { + let tempDirs: string[] = []; + + afterEach(() => { + for (const tempDir of tempDirs) { + rmSync(tempDir, { force: true, recursive: true }); + } + tempDirs = []; + }); + + it('pins an Agave release with Solana validator archives', () => { + assert.equal(SOLANA_TEST_VALIDATOR_DEFAULT_RELEASE.version, 'v3.1.14'); + assert.equal( + SOLANA_TEST_VALIDATOR_DEFAULT_RELEASE.platforms['darwin-arm64']?.checksum, + '54cfc2680bd6426fda04619ee01933f40a649c8056f3a61ba20dc54dd427ebed', + ); + assert.equal( + SOLANA_TEST_VALIDATOR_DEFAULT_RELEASE.platforms['linux-x64']?.checksum, + '06f97c065cc977cbec2f13ffc9bc9d3b92fef485431fcb370a269de69532ef51', + ); + }); + + it('uses the local MetaMask cache when Yarn global cache is disabled', () => { + const cwd = createTempDir(); + writeFileSync(join(cwd, '.yarnrc.yml'), 'enableGlobalCache: false\n'); + + assert.equal( + getSolanaTestValidatorCacheDirectory({ cwd }), + join(cwd, '.metamask', 'cache'), + ); + }); + + it('reads pinned installer options from package.json', () => { + const cwd = createTempDir(); + writeFileSync( + join(cwd, 'package.json'), + JSON.stringify({ + solanaTestValidatorUp: { + release: { + platforms: { + 'linux-x64': { + checksum: + '06f97c065cc977cbec2f13ffc9bc9d3b92fef485431fcb370a269de69532ef51', + url: 'https://example.test/solana-release.tar.bz2', + }, + }, + version: 'test-version', + }, + }, + }), + ); + + assert.deepEqual( + readSolanaTestValidatorInstallOptionsFromPackageJson({ cwd }), + { + release: { + platforms: { + 'linux-x64': { + checksum: + '06f97c065cc977cbec2f13ffc9bc9d3b92fef485431fcb370a269de69532ef51', + url: 'https://example.test/solana-release.tar.bz2', + }, + }, + version: 'test-version', + }, + }, + ); + }); + + it('parses installer CLI options', () => { + assert.deepEqual( + parseSolanaTestValidatorInstallCliOptions([ + '--cache-directory', + '/tmp/cache', + '--bin-directory', + '/tmp/bin', + '--release-url', + 'https://example.test/solana-release.tar.bz2', + '--release-checksum', + 'abc123', + ]), + { + binDirectory: '/tmp/bin', + cacheDirectory: '/tmp/cache', + release: { + platforms: { + current: { + checksum: 'abc123', + url: 'https://example.test/solana-release.tar.bz2', + }, + }, + }, + }, + ); + }); + + it('downloads, verifies, caches, and installs Solana CLI wrappers', async () => { + const cwd = createTempDir(); + const cacheDirectory = join(cwd, '.metamask', 'cache'); + const binDirectory = join(cwd, 'node_modules', '.bin'); + const downloads: { destination: string; url: string }[] = []; + const releaseContent = 'fake solana release archive'; + const dependencies = createDependencies({ downloads, releaseContent }); + + const result = await installSolanaTestValidator( + { + binDirectory, + cacheDirectory, + cwd, + platform: 'darwin-arm64', + release: { + platforms: { + 'darwin-arm64': { + checksum: sha256(releaseContent), + url: 'https://example.test/solana-release-aarch64.tar.bz2', + }, + }, + version: 'test-solana', + }, + }, + dependencies, + ); + + assert.equal(result.cacheHit, false); + assert.equal(result.version, 'test-solana'); + assert.equal( + result.binaryPath, + join(binDirectory, 'solana-test-validator'), + ); + assert.ok(result.solanaBinary.endsWith('/bin/solana')); + assert.ok(result.validatorBinary.endsWith('/bin/solana-test-validator')); + assert.ok(existsSync(result.binaryPath)); + assert.deepEqual( + downloads.map(({ url }) => url), + ['https://example.test/solana-release-aarch64.tar.bz2'], + ); + + const wrapperOutput = execFileSync( + process.execPath, + [result.binaryPath, '--version'], + { encoding: 'utf8' }, + ); + assert.equal(wrapperOutput.trim(), 'solana-test-validator --version'); + }); + + it('replaces stale bin symlinks without modifying their targets', async () => { + const cwd = createTempDir(); + const cacheDirectory = join(cwd, '.metamask', 'cache'); + const binDirectory = join(cwd, 'node_modules', '.bin'); + const releaseContent = 'fake solana release archive'; + const staleValidatorTarget = join(cwd, 'stale-validator-target'); + const staleSolanaTarget = join(cwd, 'stale-solana-target'); + + await mkdir(binDirectory, { recursive: true }); + writeFileSync(staleValidatorTarget, 'do not overwrite validator'); + writeFileSync(staleSolanaTarget, 'do not overwrite solana'); + symlinkSync( + staleValidatorTarget, + join(binDirectory, 'solana-test-validator'), + ); + symlinkSync(staleSolanaTarget, join(binDirectory, 'solana')); + + const result = await installSolanaTestValidator( + { + binDirectory, + cacheDirectory, + cwd, + platform: 'darwin-arm64', + release: { + platforms: { + 'darwin-arm64': { + checksum: sha256(releaseContent), + url: 'https://example.test/solana-release-aarch64.tar.bz2', + }, + }, + }, + }, + createDependencies({ releaseContent }), + ); + + assert.equal( + readFileSync(staleValidatorTarget, 'utf8'), + 'do not overwrite validator', + ); + assert.equal( + readFileSync(staleSolanaTarget, 'utf8'), + 'do not overwrite solana', + ); + assert.equal(lstatSync(result.binaryPath).isSymbolicLink(), false); + assert.equal( + lstatSync(join(binDirectory, 'solana')).isSymbolicLink(), + false, + ); + }); + + it('reuses cached release artifacts without downloading again', async () => { + const cwd = createTempDir(); + const cacheDirectory = join(cwd, '.metamask', 'cache'); + const binDirectory = join(cwd, 'node_modules', '.bin'); + const releaseContent = 'cached solana release archive'; + const release = { + platforms: { + 'linux-x64': { + checksum: sha256(releaseContent), + url: 'https://example.test/solana-release.tar.bz2', + }, + }, + version: 'cached-version', + }; + + await installSolanaTestValidator( + { binDirectory, cacheDirectory, cwd, platform: 'linux-x64', release }, + createDependencies({ releaseContent }), + ); + + const result = await installSolanaTestValidator( + { binDirectory, cacheDirectory, cwd, platform: 'linux-x64', release }, + { + downloadFile: async (): Promise => { + throw new Error('cache miss'); + }, + }, + ); + + assert.equal(result.cacheHit, true); + }); + + it('cleans only the solana-test-validator-up cache namespace', async () => { + const cwd = createTempDir(); + const cacheDirectory = join(cwd, '.metamask', 'cache'); + await mkdir(join(cacheDirectory, 'solana-test-validator-up', 'old'), { + recursive: true, + }); + await mkdir(join(cacheDirectory, 'foundryup', 'kept'), { + recursive: true, + }); + + await cleanSolanaTestValidatorCache({ cacheDirectory, cwd }); + + assert.equal( + existsSync(join(cacheDirectory, 'solana-test-validator-up')), + false, + ); + assert.equal(existsSync(join(cacheDirectory, 'foundryup', 'kept')), true); + }); + + function createTempDir(): string { + const tempDir = mkdtempSync( + join(tmpdir(), 'solana-test-validator-up-test-'), + ); + tempDirs.push(tempDir); + return tempDir; + } +}); + +function createDependencies({ + downloads = [], + releaseContent, +}: { + downloads?: { destination: string; url: string }[]; + releaseContent: string; +}): SolanaTestValidatorInstallDependencies { + return { + downloadFile: async (url, destination): Promise => { + downloads.push({ destination, url }); + await writeFile(destination, releaseContent); + }, + extractArchive: async (_archivePath, destination): Promise => { + const binDirectory = join(destination, 'solana-release', 'bin'); + await mkdir(binDirectory, { recursive: true }); + await writeExecutable( + join(binDirectory, 'solana-test-validator'), + 'solana-test-validator', + ); + await writeExecutable(join(binDirectory, 'solana'), 'solana'); + }, + }; +} + +async function writeExecutable(path: string, name: string): Promise { + await writeFile( + path, + `#!/usr/bin/env node\nconsole.log(${JSON.stringify(name)} + ' ' + process.argv.slice(2).join(' '));\n`, + { mode: 0o755 }, + ); +} + +function sha256(content: string): string { + return createHash('sha256').update(content).digest('hex'); +} diff --git a/packages/solana-test-validator-up/src/install.ts b/packages/solana-test-validator-up/src/install.ts new file mode 100644 index 0000000000..a0b0d7cf8c --- /dev/null +++ b/packages/solana-test-validator-up/src/install.ts @@ -0,0 +1,597 @@ +/* eslint-disable import-x/no-nodejs-modules, no-restricted-globals */ +import { spawn } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + createWriteStream, + existsSync, + readdirSync, + readFileSync, + statSync, +} from 'node:fs'; +import { + chmod, + mkdir, + readFile, + rename, + rm, + unlink, + writeFile, +} from 'node:fs/promises'; +import { request as requestHttp } from 'node:http'; +import { request as requestHttps } from 'node:https'; +import { arch as osArch, homedir, platform as osPlatform } from 'node:os'; +import { dirname, join, relative } from 'node:path'; +import { pipeline } from 'node:stream/promises'; + +const SOLANA_TEST_VALIDATOR_CACHE_NAMESPACE = 'solana-test-validator-up'; +const RELEASE_CACHE_NAMESPACE = 'release'; + +export type SolanaTestValidatorArtifactConfig = { + platforms: Record< + string, + SolanaTestValidatorArtifactPlatformConfig | undefined + >; + version?: string; +}; + +export type SolanaTestValidatorArtifactPlatformConfig = { + checksum: string; + size?: number; + url: string; +}; + +export type SolanaTestValidatorInstallOptions = { + binDirectory?: string; + cacheDirectory?: string; + cwd?: string; + platform?: string; + release?: SolanaTestValidatorArtifactConfig; +}; + +export type SolanaTestValidatorInstallResult = { + binaryPath: string; + cacheHit: boolean; + checksum: string; + solanaBinary: string; + validatorBinary: string; + version?: string; +}; + +export type SolanaTestValidatorInstallDependencies = { + downloadFile?: (url: string, destination: string) => Promise; + extractArchive?: (archivePath: string, destination: string) => Promise; +}; + +type SolanaTestValidatorPackageJson = { + 'solana-test-validator-up'?: SolanaTestValidatorPackageJsonConfig; + solanaTestValidatorUp?: SolanaTestValidatorPackageJsonConfig; + solanatestvalidatorup?: SolanaTestValidatorPackageJsonConfig; +}; + +type SolanaTestValidatorPackageJsonConfig = Pick< + SolanaTestValidatorInstallOptions, + 'binDirectory' | 'cacheDirectory' | 'release' +>; + +export const SOLANA_TEST_VALIDATOR_DEFAULT_RELEASE: SolanaTestValidatorArtifactConfig = + { + version: 'v3.1.14', + platforms: { + 'darwin-arm64': { + checksum: + '54cfc2680bd6426fda04619ee01933f40a649c8056f3a61ba20dc54dd427ebed', + size: 77_158_067, + url: 'https://github.com/anza-xyz/agave/releases/download/v3.1.14/solana-release-aarch64-apple-darwin.tar.bz2', + }, + 'darwin-x64': { + checksum: + 'e3768ed01daa1e3cfc02af3e3eb396cec2d48a99ecf80cd5d7bdff510f808d1f', + size: 81_239_759, + url: 'https://github.com/anza-xyz/agave/releases/download/v3.1.14/solana-release-x86_64-apple-darwin.tar.bz2', + }, + 'linux-x64': { + checksum: + '06f97c065cc977cbec2f13ffc9bc9d3b92fef485431fcb370a269de69532ef51', + size: 215_235_690, + url: 'https://github.com/anza-xyz/agave/releases/download/v3.1.14/solana-release-x86_64-unknown-linux-gnu.tar.bz2', + }, + }, + }; + +export function getSolanaTestValidatorCacheDirectory({ + cwd = process.cwd(), + homeDirectory = homedir(), +}: { + cwd?: string; + homeDirectory?: string; +} = {}): string { + const yarnRcPath = join(cwd, '.yarnrc.yml'); + + try { + const yarnRc = readFileSync(yarnRcPath, 'utf8'); + if (/^\s*enableGlobalCache:\s*true\s*$/mu.test(yarnRc)) { + return join(homeDirectory, '.cache', 'metamask'); + } + } catch (error) { + if (!isFileMissingError(error)) { + console.warn( + `Warning: Error reading ${yarnRcPath}, using local solana-test-validator-up cache:`, + error, + ); + } + } + + return join(cwd, '.metamask', 'cache'); +} + +export function readSolanaTestValidatorInstallOptionsFromPackageJson({ + cwd = process.cwd(), + packageJsonPath = join(cwd, 'package.json'), +}: { + cwd?: string; + packageJsonPath?: string; +} = {}): SolanaTestValidatorInstallOptions { + const packageJson = JSON.parse( + readFileSync(packageJsonPath, 'utf8'), + ) as SolanaTestValidatorPackageJson; + const config = + packageJson.solanaTestValidatorUp ?? + packageJson.solanatestvalidatorup ?? + packageJson['solana-test-validator-up']; + const options: SolanaTestValidatorInstallOptions = {}; + + if (config?.binDirectory) { + options.binDirectory = config.binDirectory; + } + if (config?.cacheDirectory) { + options.cacheDirectory = config.cacheDirectory; + } + if (config?.release) { + options.release = config.release; + } + + return options; +} + +export function parseSolanaTestValidatorInstallCliOptions( + args: string[], +): SolanaTestValidatorInstallOptions { + const options: SolanaTestValidatorInstallOptions = {}; + const release: Partial = {}; + + for (let index = 0; index < args.length; index += 1) { + const arg = args[index]; + const value = args[index + 1]; + + switch (arg) { + case '--bin-directory': + options.binDirectory = readCliValue(arg, value); + index += 1; + break; + case '--cache-directory': + options.cacheDirectory = readCliValue(arg, value); + index += 1; + break; + case '--platform': + options.platform = readCliValue(arg, value); + index += 1; + break; + case '--release-checksum': + release.checksum = readCliValue(arg, value); + index += 1; + break; + case '--release-url': + release.url = readCliValue(arg, value); + index += 1; + break; + default: + throw new Error( + `Unknown solana-test-validator-up install option: ${arg}`, + ); + } + } + + if (release.url || release.checksum) { + options.release = { + platforms: { + current: requireCompletePlatformConfig( + release, + 'Solana release CLI options', + ), + }, + }; + } + + return options; +} + +export async function installSolanaTestValidator( + options: SolanaTestValidatorInstallOptions = {}, + dependencies: SolanaTestValidatorInstallDependencies = {}, +): Promise { + const cwd = options.cwd ?? process.cwd(); + const cacheDirectory = + options.cacheDirectory ?? getSolanaTestValidatorCacheDirectory({ cwd }); + const binDirectory = + options.binDirectory ?? join(cwd, 'node_modules', '.bin'); + const platformKey = options.platform ?? getPlatformKey(); + const release = options.release ?? SOLANA_TEST_VALIDATOR_DEFAULT_RELEASE; + const releaseConfig = resolvePlatformConfig( + release, + platformKey, + 'Solana release', + ); + const releaseResult = await installSolanaRelease( + { cacheDirectory, config: releaseConfig }, + dependencies, + ); + const binaryPath = await installExecutableWrapper({ + binDirectory, + commandName: 'solana-test-validator', + executablePath: releaseResult.validatorBinary, + }); + await installExecutableWrapper({ + binDirectory, + commandName: 'solana', + executablePath: releaseResult.solanaBinary, + }); + + return { + binaryPath, + cacheHit: releaseResult.cacheHit, + checksum: releaseConfig.checksum, + solanaBinary: releaseResult.solanaBinary, + validatorBinary: releaseResult.validatorBinary, + version: release.version, + }; +} + +export async function cleanSolanaTestValidatorCache( + options: Pick< + SolanaTestValidatorInstallOptions, + 'cacheDirectory' | 'cwd' + > = {}, +): Promise { + const cwd = options.cwd ?? process.cwd(); + const cacheDirectory = + options.cacheDirectory ?? getSolanaTestValidatorCacheDirectory({ cwd }); + + await rm(join(cacheDirectory, SOLANA_TEST_VALIDATOR_CACHE_NAMESPACE), { + force: true, + recursive: true, + }); +} + +async function installSolanaRelease( + { + cacheDirectory, + config, + }: { + cacheDirectory: string; + config: SolanaTestValidatorArtifactPlatformConfig; + }, + dependencies: SolanaTestValidatorInstallDependencies, +): Promise<{ + cacheHit: boolean; + solanaBinary: string; + validatorBinary: string; +}> { + const cacheKey = getCacheKey(config); + const cacheRoot = join( + cacheDirectory, + SOLANA_TEST_VALIDATOR_CACHE_NAMESPACE, + RELEASE_CACHE_NAMESPACE, + cacheKey, + ); + const checksumPath = join(cacheRoot, '.source-checksum'); + const cached = findSolanaBinaries(cacheRoot); + + if ( + cached && + existsSync(checksumPath) && + readFileSync(checksumPath, 'utf8') === config.checksum + ) { + return { cacheHit: true, ...cached }; + } + + const tempRoot = `${cacheRoot}.downloading`; + const archivePath = join(tempRoot, 'solana-release.tar.bz2'); + const downloadFile = dependencies.downloadFile ?? downloadFileFromUrl; + const extractArchive = dependencies.extractArchive ?? extractTarBz2Archive; + + await rm(tempRoot, { force: true, recursive: true }); + await rm(cacheRoot, { force: true, recursive: true }); + await mkdir(tempRoot, { recursive: true }); + + try { + await downloadFile(config.url, archivePath); + await verifyFileChecksum( + archivePath, + config.checksum, + 'Downloaded Solana release', + ); + await extractArchive(archivePath, tempRoot); + + const binaries = findSolanaBinaries(tempRoot); + if (!binaries) { + throw new Error( + 'Solana release archive did not contain bin/solana-test-validator and bin/solana.', + ); + } + + await writeFile(checksumPath.replace(cacheRoot, tempRoot), config.checksum); + await mkdir(dirname(cacheRoot), { recursive: true }); + await rename(tempRoot, cacheRoot); + + return { + cacheHit: false, + solanaBinary: binaries.solanaBinary.replace(tempRoot, cacheRoot), + validatorBinary: binaries.validatorBinary.replace(tempRoot, cacheRoot), + }; + } catch (error) { + await rm(tempRoot, { force: true, recursive: true }); + await rm(cacheRoot, { force: true, recursive: true }); + throw error; + } +} + +async function installExecutableWrapper({ + binDirectory, + commandName, + executablePath, +}: { + binDirectory: string; + commandName: string; + executablePath: string; +}): Promise { + const binaryPath = join(binDirectory, commandName); + const relativeExecutablePath = relative(binDirectory, executablePath); + + await mkdir(binDirectory, { recursive: true }); + await unlink(binaryPath).catch((error) => { + if (!isFileMissingError(error)) { + throw error; + } + }); + await writeFile( + binaryPath, + `#!/usr/bin/env node +const { spawnSync } = require('node:child_process'); +const path = require('node:path'); + +const executablePath = path.resolve(__dirname, ${JSON.stringify(relativeExecutablePath)}); +const result = spawnSync(executablePath, process.argv.slice(2), { + stdio: 'inherit', +}); + +if (result.error) { + console.error(result.error.message); + process.exit(1); +} + +if (result.signal) { + process.kill(process.pid, result.signal); +} + +process.exit(result.status ?? 0); +`, + ); + await chmod(binaryPath, 0o755); + + return binaryPath; +} + +function findSolanaBinaries( + root: string, +): { solanaBinary: string; validatorBinary: string } | undefined { + const validatorBinary = findExecutable(root, 'solana-test-validator'); + const solanaBinary = findExecutable(root, 'solana'); + + if (!validatorBinary || !solanaBinary) { + return undefined; + } + + return { solanaBinary, validatorBinary }; +} + +function findExecutable(root: string, name: string): string | undefined { + if (!existsSync(root)) { + return undefined; + } + + for (const entry of readdirSync(root)) { + const entryPath = join(root, entry); + const stat = statSync(entryPath); + if (stat.isDirectory()) { + const found = findExecutable(entryPath, name); + if (found) { + return found; + } + } else if (entry === name) { + return entryPath; + } + } + + return undefined; +} + +function resolvePlatformConfig( + config: SolanaTestValidatorArtifactConfig, + platform: string, + label: string, +): SolanaTestValidatorArtifactPlatformConfig { + const platformConfig = config.platforms[platform] ?? config.platforms.current; + + if (!platformConfig) { + throw new Error(`No ${label} is configured for ${platform}.`); + } + + return platformConfig; +} + +function requireCompletePlatformConfig( + config: Partial, + label: string, +): SolanaTestValidatorArtifactPlatformConfig { + if (!config.url || !config.checksum) { + throw new Error(`${label} require both a URL and a checksum.`); + } + + return { + checksum: config.checksum, + url: config.url, + }; +} + +function getCacheKey( + config: SolanaTestValidatorArtifactPlatformConfig, +): string { + return createHash('sha256') + .update(`${config.url}:${config.checksum}`) + .digest('hex'); +} + +async function verifyFileChecksum( + filePath: string, + expectedChecksum: string, + label: string, +): Promise { + const checksum = createHash('sha256') + .update(await readFile(filePath)) + .digest('hex'); + + if (checksum !== expectedChecksum) { + throw new Error( + `${label} checksum mismatch. Expected ${expectedChecksum}, got ${checksum}.`, + ); + } +} + +async function downloadFileFromUrl( + url: string, + destination: string, +): Promise { + await mkdir(dirname(destination), { recursive: true }); + await pipeline( + await openDownloadStream(new URL(url)), + createWriteStream(destination), + ); +} + +async function openDownloadStream( + url: URL, + redirectsRemaining = 5, +): Promise { + const request = url.protocol === 'http:' ? requestHttp : requestHttps; + + return await new Promise((resolvePromise, rejectPromise) => { + const req = request(url, (response) => { + const { headers, statusCode, statusMessage } = response; + + if ( + statusCode && + statusCode >= 300 && + statusCode < 400 && + headers.location + ) { + response.resume(); + if (redirectsRemaining <= 0) { + rejectPromise(new Error(`Too many redirects downloading ${url}`)); + return; + } + + openDownloadStream( + new URL(headers.location, url), + redirectsRemaining - 1, + ) + .then(resolvePromise) + .catch(rejectPromise); + return; + } + + if (!statusCode || statusCode < 200 || statusCode >= 300) { + response.resume(); + rejectPromise( + new Error( + `Request to ${url} failed with ${statusCode ?? 'unknown'} ${ + statusMessage ?? '' + }`.trim(), + ), + ); + return; + } + + resolvePromise(response); + }); + + req.on('error', rejectPromise); + req.end(); + }); +} + +async function extractTarBz2Archive( + archivePath: string, + destination: string, +): Promise { + await runCommand('tar', ['-xjf', archivePath, '-C', destination]); +} + +async function runCommand(command: string, args: string[]): Promise { + await new Promise((resolvePromise, rejectPromise) => { + const child = spawn(command, args, { + shell: false, + stdio: ['ignore', 'ignore', 'pipe'], + }); + let stderr = ''; + + child.stderr.on('data', (chunk) => { + stderr += chunk.toString(); + }); + child.on('error', rejectPromise); + child.on('close', (code) => { + if (code === 0) { + resolvePromise(); + return; + } + rejectPromise( + new Error( + `${command} ${args.join(' ')} failed with code ${code}: ${stderr}`, + ), + ); + }); + }); +} + +function getPlatformKey(): string { + const platform = osPlatform(); + const arch = osArch(); + + if (platform === 'darwin' && arch === 'arm64') { + return 'darwin-arm64'; + } + if (platform === 'darwin' && arch === 'x64') { + return 'darwin-x64'; + } + if (platform === 'linux' && arch === 'x64') { + return 'linux-x64'; + } + + return `${platform}-${arch}`; +} + +function readCliValue(arg: string, value: string | undefined): string { + if (!value || value.startsWith('--')) { + throw new Error(`${arg} requires a value.`); + } + + return value; +} + +function isFileMissingError(error: unknown): boolean { + return ( + typeof error === 'object' && + error !== null && + Object.prototype.hasOwnProperty.call(error, 'code') && + (error as NodeJS.ErrnoException).code === 'ENOENT' + ); +} diff --git a/packages/solana-test-validator-up/tsconfig.build.json b/packages/solana-test-validator-up/tsconfig.build.json new file mode 100644 index 0000000000..02a0eea03f --- /dev/null +++ b/packages/solana-test-validator-up/tsconfig.build.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.packages.build.json", + "compilerOptions": { + "baseUrl": "./", + "outDir": "./dist", + "rootDir": "./src" + }, + "references": [], + "include": ["../../types", "./src"] +} diff --git a/packages/solana-test-validator-up/tsconfig.json b/packages/solana-test-validator-up/tsconfig.json new file mode 100644 index 0000000000..025ba2ef7f --- /dev/null +++ b/packages/solana-test-validator-up/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.packages.json", + "compilerOptions": { + "baseUrl": "./" + }, + "references": [], + "include": ["../../types", "./src"] +} diff --git a/packages/solana-test-validator-up/typedoc.json b/packages/solana-test-validator-up/typedoc.json new file mode 100644 index 0000000000..c9da015dbf --- /dev/null +++ b/packages/solana-test-validator-up/typedoc.json @@ -0,0 +1,7 @@ +{ + "entryPoints": ["./src/index.ts"], + "excludePrivate": true, + "hideGenerator": true, + "out": "docs", + "tsconfig": "./tsconfig.build.json" +} diff --git a/teams.json b/teams.json index 2c19709511..ee5d8d1d43 100644 --- a/teams.json +++ b/teams.json @@ -68,6 +68,7 @@ "metamask/eth-json-rpc-middleware": "team-core-platform,team-confirmations,team-wallet-integrations", "metamask/eth-json-rpc-provider": "team-wallet-integrations,team-core-platform", "metamask/foundryup": "team-mobile-platform,team-extension-platform", + "metamask/solana-test-validator-up": "team-mobile-platform,team-extension-platform,team-networks", "metamask/json-rpc-engine": "team-wallet-integrations,team-core-platform", "metamask/json-rpc-middleware-stream": "team-wallet-integrations,team-core-platform", "metamask/keyring-controller": "team-accounts-framework,team-core-platform", diff --git a/tsconfig.build.json b/tsconfig.build.json index 1604f654f5..94487f45a3 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -241,6 +241,9 @@ { "path": "./packages/social-controllers/tsconfig.build.json" }, + { + "path": "./packages/solana-test-validator-up/tsconfig.build.json" + }, { "path": "./packages/storage-service/tsconfig.build.json" }, diff --git a/tsconfig.json b/tsconfig.json index 9ca28b560c..60a45b2126 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -233,6 +233,9 @@ { "path": "./packages/social-controllers" }, + { + "path": "./packages/solana-test-validator-up" + }, { "path": "./packages/subscription-controller" }, diff --git a/yarn.lock b/yarn.lock index d177fa888e..918dfa131a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5624,6 +5624,25 @@ __metadata: languageName: unknown linkType: soft +"@metamask/solana-test-validator-up@workspace:packages/solana-test-validator-up": + version: 0.0.0-use.local + resolution: "@metamask/solana-test-validator-up@workspace:packages/solana-test-validator-up" + dependencies: + "@metamask/auto-changelog": "npm:^6.1.0" + "@ts-bridge/cli": "npm:^0.6.4" + "@types/jest": "npm:^29.5.14" + deepmerge: "npm:^4.2.2" + jest: "npm:^29.7.0" + ts-jest: "npm:^29.2.5" + tsx: "npm:^4.20.5" + typedoc: "npm:^0.25.13" + typedoc-plugin-missing-exports: "npm:^2.0.0" + typescript: "npm:~5.3.3" + bin: + solana-test-validator-up: ./dist/bin/solana-test-validator-up.mjs + languageName: unknown + linkType: soft + "@metamask/stake-sdk@npm:^3.2.1": version: 3.2.1 resolution: "@metamask/stake-sdk@npm:3.2.1"