diff --git a/.changeset/brave-otters-recover.md b/.changeset/brave-otters-recover.md new file mode 100644 index 00000000..83110eae --- /dev/null +++ b/.changeset/brave-otters-recover.md @@ -0,0 +1,5 @@ +--- +"@cartesi/cli": minor +--- + +expose the fund recovery commands as library functions: `foreclose`, `refund` and `withdraw` diff --git a/.changeset/tidy-moons-shake.md b/.changeset/tidy-moons-shake.md new file mode 100644 index 00000000..f626bc2a --- /dev/null +++ b/.changeset/tidy-moons-shake.md @@ -0,0 +1,5 @@ +--- +"@cartesi/cli": minor +--- + +expose the deposit commands as library functions: `depositEther`, `depositErc20`, `depositErc721`, `depositErc1155` and `depositErc1155Batch` diff --git a/.changeset/wild-crabs-invent.md b/.changeset/wild-crabs-invent.md new file mode 100644 index 00000000..947a4282 --- /dev/null +++ b/.changeset/wild-crabs-invent.md @@ -0,0 +1,5 @@ +--- +"@cartesi/cli": minor +--- + +expose the CLI as a library, so `build`, `run`, `hash` and the other commands can be called programmatically from a script: `import { build } from "@cartesi/cli"` diff --git a/apps/cli/README.md b/apps/cli/README.md index 8c52e002..7bd9d2c5 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -17,3 +17,65 @@ cartesi --help ``` More documentation at [https://docs.cartesi.io](https://docs.cartesi.io). + +## Library + +Every command of the CLI is also available as a function, so applications can be +built, run and inspected from a script, without going through the command line: + +```shell +npm install @cartesi/cli +``` + +```ts +import { build, depositErc20, hash, run, send } from "@cartesi/cli"; + +// build the application, same as `cartesi build` +await build(); + +// read the template hash of the machine snapshot, same as `cartesi hash` +console.log(await hash()); + +// start a local node and deploy the application to it, same as `cartesi run` +const node = await run({ epochLength: 10 }); +console.log(`running at ${node.url}, deployed at ${node.deployment?.address}`); + +// send an input to the application, same as `cartesi send` +await send({ input: "hello" }); + +// deposit tokens to the application, same as `cartesi deposit erc20` +await depositErc20({ amount: "1.5" }); + +await node.stop(); +``` + +The following functions are available: `addressBook`, `build`, `clean`, +`create`, `depositErc20`, `depositErc721`, `depositErc1155`, +`depositErc1155Batch`, `depositEther`, `doctor`, `foreclose`, `hash`, `logs`, +`refund`, `run`, `send`, `shell`, `status` and `withdraw`. + +A few things to keep in mind: + +- functions operate on the current working directory, just like the CLI, and + read `cartesi.toml` from it by default. Functions that take a configuration + accept a path, a list of paths (merged in order), or an already parsed + `Config` object; +- functions are silent, and never write to the terminal. Pass + `progress: "default"` (or `"verbose"`) to get the same output as the CLI; +- functions throw on error, and never terminate the process; +- `run` returns a handle of the environment, which keeps running in the + background until `stop()` is called. Use `deploy()` to redeploy the + application after a rebuild; +- `send` and the `deposit*` functions resolve the application address, the + sender and the RPC URL from the running project, and never prompt for them. + Amounts are given in the base unit of the asset as a `bigint`, or in its + display unit as a string (`"1.5"`). A deposit that cannot be made throws a + `DepositError` (`InsufficientBalanceError`, `InvalidAmountError` or + `TokenNotFoundError`); +- `foreclose`, `refund` and `withdraw` send their transaction with + cartesi-rollups-cli in the rollups node container, without asking for + confirmation, and return its JSON output. With `stream: true` they attach + it to the terminal instead, as the CLI does. + +The package is typed, and the types of the configuration file (`Config`, +`DriveConfig`, `MachineConfig`, ...) are exported as well. diff --git a/apps/cli/build.ts b/apps/cli/build.ts index bb7cbe08..f0a5c990 100644 --- a/apps/cli/build.ts +++ b/apps/cli/build.ts @@ -7,7 +7,7 @@ const define = { ), }; -// build for npm package +// build for npm package: the CLI entrypoint (executable) and the library entrypoint await Bun.build({ banner: "#!/usr/bin/env node", define, @@ -18,6 +18,26 @@ await Bun.build({ target: "node", }); +// the library loads its dependencies from node_modules instead of bundling its +// own copies, so a consumer shares them: an error thrown from viem is an +// instance of the consumer's viem classes, and viem isn't shipped twice. Keep +// in sync with the dependencies of package.json. The CLI and the binaries stay +// self-contained +const external = ["execa", "semver", "smol-toml", "viem"].flatMap((name) => [ + name, + `${name}/*`, +]); + +await Bun.build({ + define, + entrypoints: ["./src/lib.ts"], + external, + minify: true, + outdir: "dist", + sourcemap: true, + target: "node", +}); + // build bun binaries for all supported platforms const targets: Bun.Build.CompileTarget[] = [ "bun-darwin-arm64", diff --git a/apps/cli/package.json b/apps/cli/package.json index 6491bb67..60b38e25 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -9,10 +9,24 @@ "type": "module", "homepage": "https://github.com/cartesi/cli", "license": "Apache-2.0", + "main": "./dist/lib.js", + "exports": { + ".": { + "types": "./dist/types/lib.d.ts", + "default": "./dist/lib.js" + }, + "./package.json": "./package.json" + }, "repository": "cartesi/cli", "files": [ "/dist" ], + "dependencies": { + "execa": "^10.0.1", + "semver": "^7.8.5", + "smol-toml": "^1.9.0", + "viem": "^2.57.3" + }, "devDependencies": { "@cartesi/wagmi-plugin": "1.0.0-alpha.9", "@commander-js/extra-typings": "^15.0.0", @@ -29,7 +43,6 @@ "cli-table3": "^0.6.5", "commander": "^15.0.0", "dotenv": "^18.0.5", - "execa": "^10.0.1", "fs-extra": "^11.4.1", "get-port": "^7.2.0", "listr2": "^11.1.1", @@ -38,18 +51,16 @@ "ora": "^9.4.1", "p-retry": "^8.0.1", "rimraf": "^6.1.3", - "semver": "^7.8.5", - "smol-toml": "^1.9.0", "typescript": "^7.0.2", - "viem": "^2.57.3", "yaml": "^2.9.1" }, "scripts": { - "build": "run-s clean codegen compile", + "build": "run-s clean codegen compile types", "clean": "rimraf dist", "codegen": "run-p codegen:wagmi", "codegen:wagmi": "wagmi generate", "compile": "bun build.ts", + "types": "tsc -p tsconfig.build.json", "lint": "biome lint", "posttest": "bun lint", "test": "bun test", @@ -59,5 +70,6 @@ "engines": { "node": ">=24.0.0" }, - "bugs": "https://github.com/cartesi/cli/issues" + "bugs": "https://github.com/cartesi/cli/issues", + "types": "./dist/types/lib.d.ts" } diff --git a/apps/cli/src/api/address-book.ts b/apps/cli/src/api/address-book.ts new file mode 100644 index 00000000..0a1cef5f --- /dev/null +++ b/apps/cli/src/api/address-book.ts @@ -0,0 +1,24 @@ +import { type AddressBook, getAddressBook, getProjectName } from "../base.js"; + +export type AddressBookOptions = { + /** + * Name of the project (used by docker compose and cartesi-rollups-node). + * @default basename of the current working directory + */ + projectName?: string; +}; + +/** + * Get the addresses of all smart contracts deployed to the runtime environment + * of the application, indexed by contract name. + * @param options address book options + * @returns map of contract name to contract address + */ +export const addressBook = async ( + options: AddressBookOptions = {}, +): Promise => { + const projectName = getProjectName(options); + return getAddressBook({ projectName }); +}; + +export type { AddressBook }; diff --git a/apps/cli/src/api/build.ts b/apps/cli/src/api/build.ts new file mode 100644 index 00000000..c7d71185 --- /dev/null +++ b/apps/cli/src/api/build.ts @@ -0,0 +1,246 @@ +import chalk from "chalk"; +import fs from "fs-extra"; +import { Listr, type ListrTask } from "listr2"; +import path from "node:path"; +import { getContextPath } from "../base.js"; +import { + buildDirectory, + buildDocker, + buildEmpty, + buildNone, + buildNvram, + buildTar, +} from "../builder/index.js"; +import type { + Config, + DriveConfig, + ImageInfo, + NvramConfig, + WithdrawalConfig, +} from "../config.js"; +import { bootMachine } from "../machine.js"; +import { type AccountsDriveLayout, resolveWithdrawal } from "../withdrawal.js"; +import { + type ConfigOptions, + listrRenderer, + type ProgressOptions, + resolveConfig, +} from "./types.js"; + +export type BuildOptions = ConfigOptions & + ProgressOptions & { + /** + * Keep intermediate files, used for debugging. + * @default false + */ + debug?: boolean; + + /** + * Only build the drives, do not boot the machine. + * @default false + */ + drivesOnly?: boolean; + }; + +export type BuildResult = { + /** Application configuration used by the build. */ + config: Config; + + /** Directory where the drives and the machine snapshot were written to. */ + destination: string; + + /** Information of the docker image used to build the root drive, if any. */ + imageInfo?: ImageInfo; + + /** + * Placement of the accounts drive in the built machine, and the emergency + * withdrawal configuration derived from it. Undefined when the application + * has no accounts drive, or when only the drives were built. + */ + withdrawal?: { + layout: AccountsDriveLayout; + withdrawal: WithdrawalConfig; + }; +}; + +// context for Listr build tasks +type BuildContext = { + config: Config; + debug: boolean; + destination: string; + imageInfo?: ImageInfo; +}; + +const buildDriveTask = ( + name: string, + drive: DriveConfig, +): ListrTask => ({ + title: `Building drive ${chalk.cyan(name)}`, + task: async (ctx, task) => { + const { config, debug, destination } = ctx; + const sdk = config.sdk; + const reporter = (line: string) => { + task.output = line; + }; + + switch (drive.builder) { + case "directory": { + await buildDirectory( + name, + drive, + sdk, + destination, + debug, + reporter, + ); + break; + } + case "docker": { + const imageInfo = await buildDocker( + name, + drive, + sdk, + destination, + debug, + reporter, + ); + if (imageInfo && name === "root") { + // only set image info for root drive + ctx.imageInfo = imageInfo; + } + break; + } + case "empty": { + await buildEmpty(name, drive, sdk, destination); + break; + } + case "tar": { + await buildTar(name, drive, sdk, destination, reporter); + break; + } + case "none": { + await buildNone(name, drive, destination); + break; + } + } + task.title = `Build drive ${chalk.cyan(name)}`; + }, +}); + +const buildNvramTask = ( + label: string, + nvram: NvramConfig, +): ListrTask => ({ + title: `Building nvram ${chalk.cyan(label)}`, + task: async (ctx, task) => { + await buildNvram(label, nvram, ctx.destination); + task.title = `Build nvram ${chalk.cyan(label)}`; + }, +}); + +/** + * Build the application, by building the Cartesi machine drives, configuring a + * machine and booting it, so a machine snapshot is created at `.cartesi/image`. + * + * Drives are built relative to the current working directory, so are the + * configuration files, if provided as paths. + * + * @param options build options + * @returns configuration used and location of the build artifacts + */ +export const build = async ( + options: BuildOptions = {}, +): Promise => { + const { debug = false, drivesOnly = false, progress = "silent" } = options; + + // get application configuration, from a Config object or 'cartesi.toml' + const config = resolveConfig(options.config); + + // destination directory for image and intermediate files + const destination = path.resolve(getContextPath()); + + // prepare context directory + await fs.emptyDir(destination); // XXX: make it less error prone + + // build context + const ctx: BuildContext = { + config, + debug, + destination, + imageInfo: undefined, + }; + + // tasks to build drives + const driveTasks = Object.entries(config.drives).map(([name, drive]) => + buildDriveTask(name, drive), + ); + + // tasks to build the images backing nvrams, pristine ones need none + const nvramTasks = Object.entries(config.nvrams).map(([label, nvram]) => + buildNvramTask(label, nvram), + ); + + const groups: ListrTask[] = [ + { + title: "Build drives", + task: async (_ctx, task) => { + return task.newListr(driveTasks, { + concurrent: true, + rendererOptions: { + collapseSubtasks: false, + }, + ctx, + }); + }, + }, + ]; + + if (nvramTasks.length > 0) { + groups.push({ + title: "Build nvrams", + task: async (_ctx, task) => { + return task.newListr(nvramTasks, { + concurrent: true, + rendererOptions: { + collapseSubtasks: false, + }, + ctx, + }); + }, + }); + } + + const builds = new Listr(groups, { + ctx, + renderer: listrRenderer(progress), + }); + const result = await builds.run(); + + // if only build drives, quit here + if (drivesOnly) { + return { config, destination, imageInfo: result.imageInfo }; + } + + // create machine snapshot + await bootMachine( + config, + result.imageInfo, + { + finalHash: true, + store: "image", + }, + { + cwd: destination, + stdio: progress === "silent" ? "pipe" : "inherit", + }, + ); + + // make snapshot readable by all users, because cartesi-machine sets to 600 + const imagePath = path.join(destination, "image"); + await fs.chmod(imagePath, 0o755); + + // check the accounts drive where the machine placed it + const withdrawal = resolveWithdrawal(config, imagePath); + + return { config, destination, imageInfo: result.imageInfo, withdrawal }; +}; diff --git a/apps/cli/src/api/clean.ts b/apps/cli/src/api/clean.ts new file mode 100644 index 00000000..11964a7d --- /dev/null +++ b/apps/cli/src/api/clean.ts @@ -0,0 +1,10 @@ +import fs from "fs-extra"; +import { getContextPath } from "../base.js"; + +/** + * Delete all cached build artifacts of the application, by emptying the + * `.cartesi` directory of the current working directory. + */ +export const clean = async (): Promise => { + await fs.emptyDir(getContextPath()); +}; diff --git a/apps/cli/src/api/connection.ts b/apps/cli/src/api/connection.ts new file mode 100644 index 00000000..1c136fcf --- /dev/null +++ b/apps/cli/src/api/connection.ts @@ -0,0 +1,91 @@ +import { type Address, getAddress } from "viem"; +import { getProjectName } from "../base.js"; +import { getApplicationAddress } from "../exec/rollups.js"; +import { connect, type DevnetClient, getDefaultSender } from "../wallet.js"; + +export type ConnectionOptions = { + /** + * Address of the application to interact with. + * @default the application deployed to the local node + */ + application?: Address; + + /** + * Address of the transaction sender, which is impersonated. + * @default the first account of the devnet + */ + from?: Address; + + /** + * Name of the project (used by docker compose and cartesi-rollups-node). + * @default basename of the current working directory + */ + projectName?: string; + + /** + * RPC URL of the Cartesi Devnet. + * @default the anvil of the running project + */ + rpcUrl?: string; + + /** + * Client to send the transactions with. + * @default a client connected to the devnet of the running project + */ + client?: DevnetClient; +}; + +export type Connection = { + /** Address of the application to interact with. */ + application: Address; + + /** Client connected to the devnet. */ + client: DevnetClient; + + /** Address of the transaction sender. */ + from: Address; + + /** Name of the project. */ + projectName: string; +}; + +/** + * Resolve everything needed to send a transaction to a local environment: the + * client, the sender and the application address, querying the running project + * for whatever was not explicitly provided. + * @param options connection options + * @returns the resolved connection + */ +export const resolveConnection = async ( + options: ConnectionOptions, +): Promise => { + const projectName = getProjectName(options); + + // resolve the application address from the local node, if not provided. + // A given address is checksummed, which also rejects a malformed one + const application = options.application + ? getAddress(options.application) + : await getApplicationAddress({ projectName }); + if (!application) { + throw new Error( + `Unable to resolve the address of the application of project '${projectName}', make sure it is deployed, or define 'application'`, + ); + } + + // connect to anvil, without prompting for the RPC URL + const client = + options.client ?? + (await connect({ + interactive: false, + projectName, + rpcUrl: options.rpcUrl, + })); + + // the transaction sender, impersonated. Checksummed, as the addresses read + // from the chain are, for the deposits to compare them + const from = options.from + ? getAddress(options.from) + : await getDefaultSender(client); + + return { application, client, from, projectName }; +}; diff --git a/apps/cli/src/api/create.ts b/apps/cli/src/api/create.ts new file mode 100644 index 00000000..b3e8618f --- /dev/null +++ b/apps/cli/src/api/create.ts @@ -0,0 +1,49 @@ +import { download, type DownloadTemplateResult } from "../template.js"; + +/** Templates available at the `cartesi/application-templates` repository. */ +export const TEMPLATES = [ + "cpp", + "cpp-low-level", + "go", + "java", + "javascript", + "lua", + "python", + "ruby", + "rust", + "typescript", +] as const; + +export type Template = (typeof TEMPLATES)[number]; + +/** Default branch of the `cartesi/application-templates` repository. */ +export const DEFAULT_TEMPLATES_BRANCH = "prerelease/sdk-12"; + +export type CreateOptions = { + /** Application name, also used as the directory the application is created at. */ + name: string; + + /** Name of the template to use, one of {@link TEMPLATES}. */ + template: string; + + /** + * Branch of the `cartesi/application-templates` repository to use. + * @default DEFAULT_TEMPLATES_BRANCH + */ + branch?: string; +}; + +/** + * Create an application from a template of the `cartesi/application-templates` + * repository. + * @param options create options + * @returns directory the application was created at, and its source repository + */ +export const create = async ( + options: CreateOptions, +): Promise => { + const { branch = DEFAULT_TEMPLATES_BRANCH, name, template } = options; + return download(template, branch, name); +}; + +export type { DownloadTemplateResult }; diff --git a/apps/cli/src/api/deposit/common.ts b/apps/cli/src/api/deposit/common.ts new file mode 100644 index 00000000..fcb328c4 --- /dev/null +++ b/apps/cli/src/api/deposit/common.ts @@ -0,0 +1,82 @@ +import { type Address, type Hash, type Hex, parseUnits } from "viem"; +import type { ConnectionOptions } from "../connection.js"; +import type { ProgressOptions } from "../types.js"; + +/** Base class of the errors of a deposit that could not be made. */ +export class DepositError extends Error { + constructor(message: string) { + super(message); + this.name = "DepositError"; + } +} + +/** The sender does not own enough of the asset being deposited. */ +export class InsufficientBalanceError extends DepositError { + constructor(message = "Insufficient balance") { + super(message); + this.name = "InsufficientBalanceError"; + } +} + +/** The amount being deposited is not valid. */ +export class InvalidAmountError extends DepositError { + constructor(message: string) { + super(message); + this.name = "InvalidAmountError"; + } +} + +/** The token being deposited does not exist. */ +export class TokenNotFoundError extends DepositError { + constructor(message: string) { + super(message); + this.name = "TokenNotFoundError"; + } +} + +/** + * An amount of an asset, either in its base unit (as a `bigint`), or in its + * display unit (as a string, like `"1.5"`), converted using the number of + * decimals of the asset. + */ +export type Amount = bigint | string; + +export type DepositOptions = ConnectionOptions & + ProgressOptions & { + /** + * Additional data forwarded to the application. + * @default "0x" + */ + execLayerData?: Hex; + }; + +export type PortalDepositOptions = DepositOptions & { + /** + * Additional data forwarded to the base layer. + * @default "0x" + */ + baseLayerData?: Hex; +}; + +export type DepositResult = { + /** Address of the application the asset was deposited to. */ + application: Address; + + /** Address of the sender of the deposit. */ + from: Address; + + /** Hash of the deposit transaction. */ + transactionHash: Hash; + + /** Hash of the approval transaction, when an approval was necessary. */ + approvalTransactionHash?: Hash; +}; + +/** + * Convert an {@link Amount} to the base unit of the asset. + * @param amount amount in base units, or in display units as a string + * @param decimals number of decimals of the asset + * @returns the amount in the base unit of the asset + */ +export const parseAmount = (amount: Amount, decimals: number): bigint => + typeof amount === "bigint" ? amount : parseUnits(amount, decimals); diff --git a/apps/cli/src/api/deposit/erc1155.ts b/apps/cli/src/api/deposit/erc1155.ts new file mode 100644 index 00000000..a4cfda97 --- /dev/null +++ b/apps/cli/src/api/deposit/erc1155.ts @@ -0,0 +1,304 @@ +import chalk from "chalk"; +import { type Address, getAddress, type Hash } from "viem"; +import { + erc1155BatchPortalAbi, + erc1155BatchPortalAddress, + erc1155SinglePortalAbi, + erc1155SinglePortalAddress, + testMultiTokenAbi, + testMultiTokenAddress, +} from "../../contracts.js"; +import type { DevnetClient } from "../../wallet.js"; +import { resolveConnection } from "../connection.js"; +import { + type Amount, + type DepositResult, + InsufficientBalanceError, + InvalidAmountError, + parseAmount, + type PortalDepositOptions, +} from "./common.js"; +import { applicationLabel, depositSpinner } from "./progress.js"; + +export type DepositErc1155Options = PortalDepositOptions & { + /** ID of the token to deposit. */ + tokenId: Amount; + + /** Number of units of the token to deposit. */ + amount: Amount; + + /** + * Address of the ERC-1155 token contract. + * @default the test multi token deployed to the devnet + */ + token?: Address; +}; + +export type DepositErc1155Result = DepositResult & { + /** ID of the token deposited. */ + tokenId: bigint; + + /** Number of units deposited. */ + amount: bigint; + + /** Address of the token contract. */ + token: Address; +}; + +export type DepositErc1155BatchOptions = PortalDepositOptions & { + /** IDs of the tokens to deposit. */ + tokenIds: Amount[]; + + /** Number of units of each token to deposit, in the same order. */ + amounts: Amount[]; + + /** + * Address of the ERC-1155 token contract. + * @default the test multi token deployed to the devnet + */ + token?: Address; +}; + +export type DepositErc1155BatchResult = DepositResult & { + /** IDs of the tokens deposited. */ + tokenIds: bigint[]; + + /** Number of units deposited of each token, in the same order. */ + amounts: bigint[]; + + /** Address of the token contract. */ + token: Address; +}; + +/** + * Deposit units of a single ERC-1155 token to an application running on a local + * environment. The portal is approved to transfer the tokens, if it is not + * already. + * @param options deposit options + * @returns the deposit made, and the transaction that made it + */ +export const depositErc1155 = async ( + options: DepositErc1155Options, +): Promise => { + const { + baseLayerData = "0x", + execLayerData = "0x", + token: tokenAddress = testMultiTokenAddress, + } = options; + const token = getAddress(tokenAddress); + const { application, client, from } = await resolveConnection(options); + + const tokenId = parseAmount(options.tokenId, 0); + const amount = parseAmount(options.amount, 0); + + // ensure amount is positive + if (amount <= 0n) { + throw new InvalidAmountError( + "Amount of tokens to be deposited, must be greater than zero.", + ); + } + + // check balance + const balance = await client.readContract({ + abi: testMultiTokenAbi, + address: token, + functionName: "balanceOf", + args: [from, tokenId], + }); + if (balance < amount) { + throw new InsufficientBalanceError(); + } + + const progress = depositSpinner(options); + + // approve the portal, if needed + const approvalTransactionHash = await approvePortal({ + client, + from, + portal: erc1155SinglePortalAddress, + progress, + token, + }); + + // simulate deposit call + const { request } = await client.simulateContract({ + abi: erc1155SinglePortalAbi, + account: from, + address: erc1155SinglePortalAddress, + functionName: "depositSingleErc1155Token", + args: [ + token, + application, + tokenId, + amount, + baseLayerData, + execLayerData, + ], + }); + + // for messages + const amountLabel = `${chalk.cyan(amount)} units of token id ${tokenId}`; + + // send deposit + progress.start( + `Depositing ${amountLabel} to ${applicationLabel(application)}...`, + ); + const transactionHash = await client.writeContract(request); + await client.waitForTransactionReceipt({ hash: transactionHash }); + progress.succeed( + `Deposited ${amountLabel} to ${applicationLabel(application)}`, + ); + + return { + amount, + application, + approvalTransactionHash, + from, + token, + tokenId, + transactionHash, + }; +}; + +/** + * Deposit units of several ERC-1155 tokens to an application running on a local + * environment, in a single transaction. The portal is approved to transfer the + * tokens, if it is not already. + * @param options deposit options + * @returns the deposit made, and the transaction that made it + */ +export const depositErc1155Batch = async ( + options: DepositErc1155BatchOptions, +): Promise => { + const { + baseLayerData = "0x", + execLayerData = "0x", + token: tokenAddress = testMultiTokenAddress, + } = options; + const token = getAddress(tokenAddress); + const { application, client, from } = await resolveConnection(options); + + const tokenIds = options.tokenIds.map((tokenId) => parseAmount(tokenId, 0)); + const amounts = options.amounts.map((amount) => parseAmount(amount, 0)); + + if (tokenIds.length !== amounts.length) { + throw new InvalidAmountError( + "Token IDs and amounts must have the same length.", + ); + } + + for (const [index, amount] of amounts.entries()) { + if (amount <= 0n) { + throw new InvalidAmountError( + `Amount of token Id: ${tokenIds[index]} to be deposited, must be greater than zero.`, + ); + } + } + + // check balances + for (const [index, tokenId] of tokenIds.entries()) { + const balance = await client.readContract({ + abi: testMultiTokenAbi, + address: token, + functionName: "balanceOf", + args: [from, tokenId], + }); + if (balance < amounts[index]) { + throw new InsufficientBalanceError( + `Insufficient balance for token ID ${tokenId}`, + ); + } + } + + const progress = depositSpinner(options); + + // approve the portal, if needed + const approvalTransactionHash = await approvePortal({ + client, + from, + portal: erc1155BatchPortalAddress, + progress, + token, + }); + + // simulate batch deposit call + const { request } = await client.simulateContract({ + abi: erc1155BatchPortalAbi, + account: from, + address: erc1155BatchPortalAddress, + functionName: "depositBatchErc1155Token", + args: [ + token, + application, + tokenIds, + amounts, + baseLayerData, + execLayerData, + ], + }); + + // for messages + const amountLabel = tokenIds + .map( + (tokenId, index) => + `${chalk.cyan(amounts[index])} units of token id ${tokenId}`, + ) + .join(", "); + + // send deposit + progress.start(`Depositing tokens to ${applicationLabel(application)}...`); + const transactionHash = await client.writeContract(request); + await client.waitForTransactionReceipt({ hash: transactionHash }); + progress.succeed( + `Deposited ${amountLabel} to ${applicationLabel(application)}`, + ); + + return { + amounts, + application, + approvalTransactionHash, + from, + token, + tokenIds, + transactionHash, + }; +}; + +/** + * Approve a portal to transfer the tokens of the sender, if it is not approved + * already. + * @returns the hash of the approval transaction, if one was necessary + */ +const approvePortal = async (options: { + client: DevnetClient; + from: Address; + portal: Address; + progress: ReturnType; + token: Address; +}): Promise => { + const { client, from, portal, progress, token } = options; + + const isApproved = await client.readContract({ + abi: testMultiTokenAbi, + address: token, + functionName: "isApprovedForAll", + args: [from, portal], + }); + + if (isApproved) { + return undefined; + } + + progress.start(`Approving ERC1155Portal...`); + const { request } = await client.simulateContract({ + abi: testMultiTokenAbi, + account: from, + address: token, + functionName: "setApprovalForAll", + args: [portal, true], + }); + const hash = await client.writeContract(request); + await client.waitForTransactionReceipt({ hash }); + progress.succeed(`Approved ERC1155Portal`); + return hash; +}; diff --git a/apps/cli/src/api/deposit/erc20.ts b/apps/cli/src/api/deposit/erc20.ts new file mode 100644 index 00000000..2569801b --- /dev/null +++ b/apps/cli/src/api/deposit/erc20.ts @@ -0,0 +1,156 @@ +import chalk from "chalk"; +import { type Address, erc20Abi, formatUnits, getAddress } from "viem"; +import { + erc20PortalAbi, + erc20PortalAddress, + testFungibleTokenAddress, +} from "../../contracts.js"; +import type { DevnetClient } from "../../wallet.js"; +import { resolveConnection } from "../connection.js"; +import { + type Amount, + type DepositOptions, + type DepositResult, + InsufficientBalanceError, + parseAmount, +} from "./common.js"; +import { applicationLabel, depositSpinner } from "./progress.js"; + +export type Erc20Token = { + address: Address; + name: string; + symbol: string; + decimals: number; +}; + +/** + * Read the metadata of an ERC-20 token. + * @param client client connected to the devnet + * @param address address of the token contract + * @returns name, symbol and decimals of the token + */ +export const readErc20Token = async ( + client: DevnetClient, + address: Address, +): Promise => { + const args = { abi: erc20Abi, address } as const; + const symbol = await client.readContract({ + ...args, + functionName: "symbol", + }); + const name = await client.readContract({ ...args, functionName: "name" }); + const decimals = await client.readContract({ + ...args, + functionName: "decimals", + }); + return { address, name, symbol, decimals }; +}; + +export type DepositErc20Options = DepositOptions & { + /** + * Amount to deposit, in the base unit of the token, or in its display unit + * when given as a string. + */ + amount: Amount; + + /** + * Address of the ERC-20 token contract. + * @default the test token deployed to the devnet + */ + token?: Address; +}; + +export type DepositErc20Result = DepositResult & { + /** Amount deposited, in the base unit of the token. */ + amount: bigint; + + /** Token deposited. */ + token: Erc20Token; +}; + +/** + * Deposit ERC-20 tokens to an application running on a local environment. The + * portal is approved to transfer the tokens, if it is not already. + * @param options deposit options + * @returns the deposit made, and the transaction that made it + */ +export const depositErc20 = async ( + options: DepositErc20Options, +): Promise => { + const { execLayerData = "0x", token: address = testFungibleTokenAddress } = + options; + const { application, client, from } = await resolveConnection(options); + + const token = await readErc20Token(client, getAddress(address)); + const { decimals, symbol } = token; + const amount = parseAmount(options.amount, decimals); + + // check balance + const balance = await client.readContract({ + abi: erc20Abi, + address: token.address, + functionName: "balanceOf", + args: [from], + }); + if (balance < amount) { + throw new InsufficientBalanceError(); + } + + // check allowance + const allowance = await client.readContract({ + abi: erc20Abi, + address: token.address, + functionName: "allowance", + args: [from, erc20PortalAddress], + }); + + // for messages + const amountLabel = `${chalk.cyan(formatUnits(amount, decimals))} ${symbol}`; + const progress = depositSpinner(options); + + // approve if needed + let approvalTransactionHash: `0x${string}` | undefined; + if (allowance < amount) { + progress.start(`Approving ${amountLabel}...`); + const { request } = await client.simulateContract({ + abi: erc20Abi, + account: from, + address: token.address, + functionName: "approve", + args: [erc20PortalAddress, amount], + }); + approvalTransactionHash = await client.writeContract(request); + await client.waitForTransactionReceipt({ + hash: approvalTransactionHash, + }); + progress.succeed(`Approved ${amountLabel}`); + } + + // simulate deposit call + const { request } = await client.simulateContract({ + abi: erc20PortalAbi, + account: from, + address: erc20PortalAddress, + functionName: "depositErc20Tokens", + args: [token.address, application, amount, execLayerData], + }); + + // send deposit + progress.start( + `Depositing ${amountLabel} to ${applicationLabel(application)}...`, + ); + const transactionHash = await client.writeContract(request); + await client.waitForTransactionReceipt({ hash: transactionHash }); + progress.succeed( + `Deposited ${amountLabel} to ${applicationLabel(application)}`, + ); + + return { + amount, + application, + approvalTransactionHash, + from, + token, + transactionHash, + }; +}; diff --git a/apps/cli/src/api/deposit/erc721.ts b/apps/cli/src/api/deposit/erc721.ts new file mode 100644 index 00000000..aaea3d91 --- /dev/null +++ b/apps/cli/src/api/deposit/erc721.ts @@ -0,0 +1,189 @@ +import chalk from "chalk"; +import { + type Address, + BaseError, + ContractFunctionRevertedError, + erc721Abi, + getAddress, + type Hash, + isAddressEqual, +} from "viem"; +import { + erc721PortalAbi, + erc721PortalAddress, + testNonFungibleTokenAbi, + testNonFungibleTokenAddress, +} from "../../contracts.js"; +import type { DevnetClient } from "../../wallet.js"; +import { resolveConnection } from "../connection.js"; +import { + type Amount, + type DepositResult, + InsufficientBalanceError, + parseAmount, + type PortalDepositOptions, + TokenNotFoundError, +} from "./common.js"; +import { applicationLabel, depositSpinner } from "./progress.js"; + +export type Erc721Token = { + address: Address; + name: string; + symbol: string; +}; + +/** + * Read the metadata of an ERC-721 token. + * @param client client connected to the devnet + * @param address address of the token contract + * @returns name and symbol of the token + */ +export const readErc721Token = async ( + client: DevnetClient, + address: Address, +): Promise => { + const args = { abi: erc721Abi, address } as const; + const symbol = await client.readContract({ + ...args, + functionName: "symbol", + }); + const name = await client.readContract({ ...args, functionName: "name" }); + return { address, name, symbol }; +}; + +export type DepositErc721Options = PortalDepositOptions & { + /** ID of the token to deposit. */ + tokenId: Amount; + + /** + * Address of the ERC-721 token contract. + * @default the test NFT deployed to the devnet + */ + token?: Address; +}; + +export type DepositErc721Result = DepositResult & { + /** ID of the token deposited. */ + tokenId: bigint; + + /** Token deposited. */ + token: Erc721Token; +}; + +/** + * Deposit an ERC-721 token to an application running on a local environment. + * The portal is approved to transfer the token, if it is not already. + * @param options deposit options + * @returns the deposit made, and the transaction that made it + */ +export const depositErc721 = async ( + options: DepositErc721Options, +): Promise => { + const { + baseLayerData = "0x", + execLayerData = "0x", + token: address = testNonFungibleTokenAddress, + } = options; + const { application, client, from } = await resolveConnection(options); + + const tokenId = parseAmount(options.tokenId, 0); + const token = await readErc721Token(client, getAddress(address)); + + // the test NFT has a different abi, which allows minting + const tokenAbi = isAddressEqual(token.address, testNonFungibleTokenAddress) + ? testNonFungibleTokenAbi + : erc721Abi; + + // check ownership + let currentOwner: Address; + try { + currentOwner = await client.readContract({ + abi: tokenAbi, + address: token.address, + args: [tokenId], + functionName: "ownerOf", + }); + } catch (e: unknown) { + if (e instanceof BaseError) { + const revertError = e.walk( + (err) => err instanceof ContractFunctionRevertedError, + ); + if ( + revertError instanceof ContractFunctionRevertedError && + revertError.data?.errorName === "ERC721NonexistentToken" + ) { + throw new TokenNotFoundError(`Token ${tokenId} does not exist`); + } + throw new Error("Failed to check ownership", { cause: e }); + } + throw e; + } + + if (!isAddressEqual(currentOwner, from)) { + throw new InsufficientBalanceError(); + } + + // check allowance + const operator = await client.readContract({ + abi: tokenAbi, + address: token.address, + args: [tokenId], + functionName: "getApproved", + }); + + // for messages + const tokenLabel = `${chalk.cyan(tokenId)} ${token.symbol}`; + const progress = depositSpinner(options); + + // approve if needed + let approvalTransactionHash: Hash | undefined; + if (operator !== erc721PortalAddress) { + progress.start(`Approving ${tokenLabel}...`); + const { request } = await client.simulateContract({ + abi: tokenAbi, + account: from, + address: token.address, + functionName: "approve", + args: [erc721PortalAddress, tokenId], + }); + approvalTransactionHash = await client.writeContract(request); + await client.waitForTransactionReceipt({ + hash: approvalTransactionHash, + }); + progress.succeed(`Approved ${tokenLabel}`); + } + + // simulate deposit call + const { request } = await client.simulateContract({ + abi: erc721PortalAbi, + account: from, + address: erc721PortalAddress, + functionName: "depositErc721Token", + args: [ + token.address, + application, + tokenId, + baseLayerData, + execLayerData, + ], + }); + + // send deposit + progress.start( + `Depositing ${tokenLabel} to ${applicationLabel(application)}...`, + ); + const transactionHash = await client.writeContract(request); + await client.waitForTransactionReceipt({ hash: transactionHash }); + progress.succeed( + `Deposited ${tokenLabel} to ${applicationLabel(application)}`, + ); + + return { + application, + approvalTransactionHash, + from, + token, + tokenId, + transactionHash, + }; +}; diff --git a/apps/cli/src/api/deposit/ether.ts b/apps/cli/src/api/deposit/ether.ts new file mode 100644 index 00000000..168be87a --- /dev/null +++ b/apps/cli/src/api/deposit/ether.ts @@ -0,0 +1,68 @@ +import chalk from "chalk"; +import { formatUnits } from "viem"; +import { etherPortalAbi, etherPortalAddress } from "../../contracts.js"; +import { resolveConnection } from "../connection.js"; +import { + type Amount, + type DepositOptions, + type DepositResult, + InsufficientBalanceError, + parseAmount, +} from "./common.js"; +import { applicationLabel, depositSpinner } from "./progress.js"; + +export type DepositEtherOptions = DepositOptions & { + /** Amount to deposit, in wei, or in ETH when given as a string. */ + amount: Amount; +}; + +export type DepositEtherResult = DepositResult & { + /** Amount deposited, in wei. */ + amount: bigint; +}; + +/** + * Deposit ether to an application running on a local environment. + * @param options deposit options + * @returns the deposit made, and the transaction that made it + */ +export const depositEther = async ( + options: DepositEtherOptions, +): Promise => { + const { execLayerData = "0x" } = options; + const { application, client, from } = await resolveConnection(options); + + const { decimals, symbol } = client.chain.nativeCurrency; + const amount = parseAmount(options.amount, decimals); + + // check balance + const balance = await client.getBalance({ address: from }); + if (balance < amount) { + throw new InsufficientBalanceError(); + } + + const { request } = await client.simulateContract({ + abi: etherPortalAbi, + account: from, + address: etherPortalAddress, + args: [application, execLayerData], + functionName: "depositEther", + value: amount, + }); + + // for messages + const amountLabel = `${chalk.cyan(formatUnits(amount, decimals))} ${symbol}`; + + // send deposit + const progress = depositSpinner(options); + progress.start( + `Depositing ${amountLabel} to ${applicationLabel(application)}...`, + ); + const transactionHash = await client.writeContract(request); + await client.waitForTransactionReceipt({ hash: transactionHash }); + progress.succeed( + `Deposited ${amountLabel} to ${applicationLabel(application)}`, + ); + + return { amount, application, from, transactionHash }; +}; diff --git a/apps/cli/src/api/deposit/index.ts b/apps/cli/src/api/deposit/index.ts new file mode 100644 index 00000000..f6fad201 --- /dev/null +++ b/apps/cli/src/api/deposit/index.ts @@ -0,0 +1,15 @@ +export { + type Amount, + DepositError, + type DepositOptions, + type DepositResult, + InsufficientBalanceError, + InvalidAmountError, + parseAmount, + type PortalDepositOptions, + TokenNotFoundError, +} from "./common.js"; +export * from "./erc20.js"; +export * from "./erc721.js"; +export * from "./erc1155.js"; +export * from "./ether.js"; diff --git a/apps/cli/src/api/deposit/progress.ts b/apps/cli/src/api/deposit/progress.ts new file mode 100644 index 00000000..fca69fde --- /dev/null +++ b/apps/cli/src/api/deposit/progress.ts @@ -0,0 +1,19 @@ +import chalk from "chalk"; +import ora from "ora"; +import type { Address } from "viem"; +import type { ProgressOptions } from "../types.js"; + +// Kept apart from common.ts, whose declarations are public: the spinner's type +// comes from ora, a devDependency, which a consumer of the library types +// doesn't have. + +/** + * Create the spinner used to report the progress of a deposit, silent unless + * the caller asked for progress. + */ +export const depositSpinner = (options: ProgressOptions) => + ora({ isSilent: (options.progress ?? "silent") === "silent" }); + +/** Label of an application address, used in progress messages. */ +export const applicationLabel = (application: Address) => + chalk.cyan(application); diff --git a/apps/cli/src/api/doctor.ts b/apps/cli/src/api/doctor.ts new file mode 100644 index 00000000..621143fd --- /dev/null +++ b/apps/cli/src/api/doctor.ts @@ -0,0 +1,242 @@ +import { execa } from "execa"; +import semver from "semver"; +import { DEFAULT_SDK_IMAGE, DEFAULT_SDK_VERSION } from "../config.js"; +import { cartesiMachine } from "../exec/index.js"; + +const MINIMUM_DOCKER_VERSION = "25.0.0"; // Replace with our minimum required Docker version +const MINIMUM_DOCKER_COMPOSE_VERSION = "2.24.0"; // Replace with our minimum required Docker Compose version +const MINIMUM_BUILDX_VERSION = "0.13.0"; // Replace with our minimum required Buildx version + +const COMPOSE_NOT_INSTALLED = + "Docker Compose is required but not installed or the command execution failed. Please refer to the Docker Compose documentation for installation instructions: https://docs.docker.com/compose/install/"; +const BUILDX_NOT_INSTALLED = + "Docker Buildx is required but not installed. Please refer to the Docker Desktop documentation for installation instructions: https://docs.docker.com/desktop/"; + +export type DoctorCheck = { + /** Name of the requirement being checked. */ + name: string; + + /** + * Whether the requirement is satisfied (`ok`), is not (`failed`), or could + * not be checked because a requirement it depends on is not satisfied + * (`skipped`). + */ + status: "ok" | "failed" | "skipped"; + + /** Detail of a satisfied requirement, usually the installed version. */ + detail?: string; + + /** Reason why the requirement is not satisfied, or was skipped. */ + message?: string; +}; + +export type DoctorResult = { + /** Whether all requirements are satisfied. */ + ok: boolean; + + /** Every requirement checked, satisfied or not. */ + checks: DoctorCheck[]; +}; + +type Check = { + name: string; + + /** Names of the checks this one depends on, listed before it. */ + requires?: string[]; + + run: () => Promise; +}; + +/** + * Run a docker command, turning the failures of a missing docker, or of a + * missing docker plugin, into messages that say what to install. + * @param args arguments of the docker command + * @param notInstalled message for the docker exit code of an unknown command + * @returns the standard output of the command + */ +const docker = async (args: string[], notInstalled?: string) => { + try { + const { stdout } = await execa("docker", args); + return stdout; + } catch (e: unknown) { + if ( + e instanceof Error && + (e as NodeJS.ErrnoException).code === "ENOENT" + ) { + throw new Error("Docker not found"); + } + if ( + notInstalled && + e instanceof Error && + (e as Error & { exitCode?: number }).exitCode === 125 + ) { + throw new Error(notInstalled); + } + throw e; + } +}; + +const checkDocker = async (): Promise => { + const dockerVersion = await docker([ + "version", + "--format", + "{{json .Client.Version}}", + ]); + + const v = semver.coerce(dockerVersion); + if (v !== null && !semver.gte(v, MINIMUM_DOCKER_VERSION)) { + throw new Error( + `Unsupported Docker version. Minimum required version is ${MINIMUM_DOCKER_VERSION}. Installed version is ${v}.`, + ); + } + return v?.version; +}; + +const checkCompose = async (): Promise => { + const dockerComposeVersion = await docker( + ["compose", "version", "--short"], + COMPOSE_NOT_INSTALLED, + ); + + const v = semver.coerce(dockerComposeVersion); + if (v !== null && !semver.gte(v, MINIMUM_DOCKER_COMPOSE_VERSION)) { + throw new Error( + `Unsupported Docker Compose version. Minimum required version is ${MINIMUM_DOCKER_COMPOSE_VERSION}. Installed version is ${v}.`, + ); + } + return dockerComposeVersion; +}; + +const checkBuildx = async (): Promise => { + const buildxOutput = await docker( + ["buildx", "version"], + BUILDX_NOT_INSTALLED, + ); + + const v = semver.coerce(buildxOutput); + if (v !== null && !semver.gte(v, MINIMUM_BUILDX_VERSION)) { + throw new Error( + `Unsupported Docker Buildx version. Minimum required version is ${MINIMUM_BUILDX_VERSION}. Installed version is ${v}.`, + ); + } + return v?.version; +}; + +const checkRiscv = async (): Promise => { + const platformsOutput = await docker( + ["buildx", "ls", "--format", "{{.Platforms}}"], + BUILDX_NOT_INSTALLED, + ); + + const buildxPlatforms: string[] = platformsOutput + .split(",") + .map((platform) => platform.trim()); + + if (!buildxPlatforms.includes("linux/riscv64")) { + throw new Error( + "Your system does not support riscv64 architecture. Run `docker run --privileged --rm tonistiigi/binfmt:riscv` to enable riscv64 support.", + ); + } + return "linux/riscv64"; +}; + +const checkCartesiMachine = async (): Promise => { + // doctor does not read cartesi.toml, so check against the default sdk image. the host binary + // still takes precedence, which is the install most likely to be out of date + const v = await cartesiMachine.version({ + image: `${DEFAULT_SDK_IMAGE}:${DEFAULT_SDK_VERSION}`, + }); + + if (v === null) { + throw new Error( + "Could not determine the Cartesi Machine version. Check that Docker is running.", + ); + } + if (!semver.satisfies(v.format(), cartesiMachine.requiredVersion)) { + throw new Error( + `Unsupported Cartesi Machine version. Required version is ${cartesiMachine.requiredVersion.raw}. Installed version is ${v.format()}.`, + ); + } + return v.format(); +}; + +// the Cartesi Machine check requires nothing, as a host cartesi-machine +// satisfies it without docker +const checks: Check[] = [ + { name: "Docker Engine", run: checkDocker }, + { + name: "Docker Compose", + requires: ["Docker Engine"], + run: checkCompose, + }, + { + name: "Docker Buildx", + requires: ["Docker Engine"], + run: checkBuildx, + }, + { + name: "Docker RISC-V support", + requires: ["Docker Engine", "Docker Buildx"], + run: checkRiscv, + }, + { name: "Cartesi Machine", run: checkCartesiMachine }, +]; + +/** + * Mark the checks whose requirements are not satisfied as skipped, as their + * own failure would only repeat the failure of the requirement. A check lists + * its requirements before it, so a skipped requirement skips its dependents. + * @param checks the checks, with their requirements + * @param results the result of each check, in the same order + * @returns the results, with the checks whose requirements failed skipped + */ +export const skipUnmetRequirements = ( + checks: { name: string; requires?: string[] }[], + results: DoctorCheck[], +): DoctorCheck[] => { + const status = new Map(); + return results.map((result, index) => { + const unmet = checks[index]?.requires?.find( + (name) => status.get(name) !== "ok", + ); + const check: DoctorCheck = + unmet === undefined + ? result + : { + name: result.name, + status: "skipped", + message: `requires ${unmet}`, + }; + status.set(check.name, check.status); + return check; + }); +}; + +/** + * Check whether the system has everything needed to build and run Cartesi + * applications. All requirements are checked concurrently, and the result of + * every check is reported, satisfied or not. A check whose requirement is not + * satisfied is reported as skipped, instead of failing on its own. + * @returns the result of every check + */ +export const doctor = async (): Promise => { + const results = await Promise.all( + checks.map(async ({ name, run }): Promise => { + try { + return { name, status: "ok", detail: await run() }; + } catch (e: unknown) { + return { + name, + status: "failed", + message: e instanceof Error ? e.message : String(e), + }; + } + }), + ); + + const resolved = skipUnmetRequirements(checks, results); + return { + ok: resolved.every((check) => check.status === "ok"), + checks: resolved, + }; +}; diff --git a/apps/cli/src/api/foreclose.ts b/apps/cli/src/api/foreclose.ts new file mode 100644 index 00000000..9f6a1945 --- /dev/null +++ b/apps/cli/src/api/foreclose.ts @@ -0,0 +1,71 @@ +import { getCartesiEnvironmentVariables, getProjectName } from "../base.js"; +import { getHostSigner, getNodeSigner } from "../exec/node-container.js"; +import { getNodeWithdrawalConfig } from "../exec/rollups.js"; +import { resolveForecloseSigner } from "../foreclose.js"; +import { resolveNodeApplication } from "../node.js"; +import { + type RecoveryOptions, + type RecoveryResult, + runRecoveryCommand, +} from "./recovery.js"; +import type { Notice } from "./types.js"; + +export type ForecloseOptions = RecoveryOptions & { + /** + * Index of the guardian in the mnemonic. + * @default looked up from the application guardian; ignored for private-key signers + */ + accountIndex?: number; + + /** + * Called with what is worth telling about the signer, such as an account + * index that is ignored. Nothing is written to the terminal without it. + */ + onNotice?: (notice: Notice) => void; +}; + +/** + * Foreclose an application, so its users can withdraw their funds. Signs as + * the application guardian, with the rollups node signer by default, looking + * up the guardian in its mnemonic. To sign as a guardian outside it, set + * `CARTESI_AUTH_MNEMONIC` or `CARTESI_AUTH_PRIVATE_KEY`, and + * `CARTESI_AUTH_KIND` when both are set. + * @param options foreclose options + * @returns the application foreclosed, and the output of cartesi-rollups-cli + */ +export const foreclose = async ( + options: ForecloseOptions = {}, +): Promise => { + const { onNotice, stream = false } = options; + const projectName = getProjectName(options); + const application = await resolveNodeApplication({ + application: options.application, + projectName, + }); + + const { guardian } = await getNodeWithdrawalConfig({ + application, + projectName, + }); + // the node signer is only needed without a signer for the command + const host = getHostSigner(getCartesiEnvironmentVariables()); + const { accountIndex, env, warning } = resolveForecloseSigner({ + accountIndex: options.accountIndex, + guardian, + host, + node: host ? undefined : await getNodeSigner({ projectName }), + }); + if (warning) { + onNotice?.({ level: "warning", message: warning }); + } + + const output = await runRecoveryCommand({ + accountIndex, + command: ["cartesi-rollups-cli", "foreclose", application], + env, + projectName, + stream, + tx: options, + }); + return { application, output }; +}; diff --git a/apps/cli/src/api/hash.ts b/apps/cli/src/api/hash.ts new file mode 100644 index 00000000..1be3a630 --- /dev/null +++ b/apps/cli/src/api/hash.ts @@ -0,0 +1,22 @@ +import type { Hash } from "viem"; +import { getMachineHash } from "../base.js"; + +export type HashOptions = { + /** + * SDK image that built the machine snapshot, used when there is no local + * `cartesi-machine-stored-hash`, as an emulator of another version may not + * load the snapshot. + * @default the sdk of `cartesi.toml` + */ + sdk?: string; +}; + +/** + * Read the template hash of the Cartesi machine snapshot created by + * {@link build}, at `.cartesi/image` of the current working directory. + * @param options hash options + * @returns the machine template hash, or `undefined` if there is no snapshot + */ +export const hash = async ( + options: HashOptions = {}, +): Promise => getMachineHash({ sdk: options.sdk }); diff --git a/apps/cli/src/api/index.ts b/apps/cli/src/api/index.ts new file mode 100644 index 00000000..1d7a82a7 --- /dev/null +++ b/apps/cli/src/api/index.ts @@ -0,0 +1,22 @@ +export * from "./address-book.js"; +export * from "./build.js"; +export * from "./clean.js"; +export * from "./connection.js"; +export * from "./create.js"; +export * from "./deposit/index.js"; +export * from "./doctor.js"; +export * from "./foreclose.js"; +export * from "./hash.js"; +export * from "./logs.js"; +export { + NodeCommandError, + type RecoveryOptions, + type RecoveryResult, +} from "./recovery.js"; +export * from "./refund.js"; +export * from "./run.js"; +export * from "./send.js"; +export * from "./shell.js"; +export * from "./status.js"; +export * from "./types.js"; +export * from "./withdraw.js"; diff --git a/apps/cli/src/api/logs.ts b/apps/cli/src/api/logs.ts new file mode 100644 index 00000000..7f9eee52 --- /dev/null +++ b/apps/cli/src/api/logs.ts @@ -0,0 +1,177 @@ +import { execa } from "execa"; +import { getProjectName } from "../base.js"; +import { isPrtNodeService } from "../compose/prt-node.js"; + +/** The node's compose service, shown by default and first. */ +export const NODE_SERVICE = "rollups_node"; + +/** + * The services of a running environment, as compose lists them; an exited + * container is still listed, so its last logs can be read. + */ +export const listServices = async (projectName: string): Promise => { + const { stdout } = await execa("docker", [ + "compose", + "--project-name", + projectName, + "ps", + "--services", + "--all", + ]); + return stdout + .split("\n") + .map((line) => line.trim()) + .filter((line) => line.length > 0); +}; + +/** + * The services to show: the ones named, checked against the environment, or + * the node followed by every PRT node. + * @param services the environment's services, from `listServices` + * @param requested the services named by the caller + * @throws when the node isn't there, or a named service isn't + */ +export const selectLogServices = ( + services: string[], + requested: string[], +): string[] => { + if (requested.length === 0) { + if (!services.includes(NODE_SERVICE)) { + throw new Error(`service ${NODE_SERVICE} not found`); + } + return [NODE_SERVICE, ...services.filter(isPrtNodeService)]; + } + // compose shows nothing for an unknown service, without an error + const unknown = requested.filter((service) => !services.includes(service)); + if (unknown.length > 0) { + throw new Error( + `service ${unknown.join(", ")} not found; the environment has ${services.join(", ")}`, + ); + } + return requested; +}; + +/** + * The `docker compose logs` arguments. One service is shown as it is, like + * `docker container logs`; more than one get compose's per-service prefix, + * which tells the node's lines from the PRT nodes'. + */ +export const buildLogsArgs = (options: { + follow?: boolean; + projectName: string; + services: string[]; + since?: string; + tail?: string; + until?: string; +}): string[] => { + const { follow, projectName, services, since, tail, until } = options; + const args = ["compose", "--project-name", projectName, "logs"]; + if (follow) args.push("--follow"); + if (since) args.push("--since", since); + if (tail) args.push("--tail", tail); + if (until) args.push("--until", until); + if (services.length === 1) args.push("--no-log-prefix"); + return [...args, ...services]; +}; + +export type LogsOptions = { + /** + * Name of the project (used by docker compose and cartesi-rollups-node). + * @default basename of the current working directory + */ + projectName?: string; + + /** + * Services to show, as `run` names them. + * @default the node followed by every PRT node + */ + services?: string[]; + + /** Follow log output. */ + follow?: boolean; + + /** + * Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative + * (e.g. 42m for 42 minutes). + */ + since?: string; + + /** + * Number of lines to show from the end of the logs. + * @default "all" + */ + tail?: string; + + /** + * Show logs before a timestamp (e.g. 2013-01-02T13:23:37Z) or relative + * (e.g. 42m for 42 minutes). + */ + until?: string; + + /** + * Write the logs directly to the terminal instead of returning them. + * @default false + */ + stream?: boolean; + + /** + * Called for every log line, as they are produced. Useful together with + * `follow`, where collecting the whole output is not an option. The + * returned logs are empty when it consumes them. + */ + onLine?: (line: string) => void; +}; + +/** + * Read the logs of a local environment: the rollups node and its PRT nodes, or + * the services given. + * + * By default the logs are collected and returned. When `stream` is enabled the + * logs are written directly to the terminal and nothing is returned. Individual + * lines can also be consumed as they are produced by using `onLine`. + * + * @param options logs options + * @returns the collected logs, or `undefined` when `stream` is enabled + */ +export const logs = async ( + options: LogsOptions = {}, +): Promise => { + const { + follow, + onLine, + since, + stream = false, + tail = "all", + until, + } = options; + const projectName = getProjectName(options); + + const services = selectLogServices( + await listServices(projectName), + options.services ?? [], + ); + + const args = buildLogsArgs({ + follow, + projectName, + services, + since, + tail, + until, + }); + + if (stream) { + await execa("docker", args, { stdio: "inherit" }); + return undefined; + } + + // interleave stdout and stderr, as docker logs writes to both + const subprocess = execa("docker", args, { all: true }); + if (onLine) { + for await (const line of subprocess.iterable({ from: "all" })) { + onLine(line); + } + } + const { all, stdout } = await subprocess; + return all ?? stdout; +}; diff --git a/apps/cli/src/api/recovery.ts b/apps/cli/src/api/recovery.ts new file mode 100644 index 00000000..fc6b4dd0 --- /dev/null +++ b/apps/cli/src/api/recovery.ts @@ -0,0 +1,110 @@ +import type { Address } from "viem"; +import { + execNodeCommand, + runAttachedNodeCommand, + type TransactionOptions, + transactionArgs, +} from "../exec/node-container.js"; +import type { ProgressOptions } from "./types.js"; + +export { NodeCommandError } from "../exec/node-container.js"; + +/** + * Options shared by the fund recovery functions, `foreclose`, `refund` and + * `withdraw`, which send their transaction with cartesi-rollups-cli inside + * the rollups node container. + */ +export type RecoveryOptions = ProgressOptions & { + /** + * Address of the application. + * @default the application deployed for the current machine + */ + application?: string; + + /** + * Name of the project (used by docker compose and cartesi-rollups-node). + * @default basename of the current working directory + */ + projectName?: string; + + /** Index of the signer account in the node mnemonic. */ + accountIndex?: number; + + /** + * Wait for the transaction receipt. + * @default true + */ + wait?: boolean; + + /** Maximum time to wait for the receipt (e.g. 30s, 5m). */ + waitTimeout?: string; + + /** + * Attach cartesi-rollups-cli to the terminal, so it asks for confirmation + * and prints its own output, which is not returned. A failure it printed + * is thrown as a NodeCommandError, with its exit code. Without it nothing + * is asked, and the output is returned. + * @default false + */ + stream?: boolean; + + /** + * Skip the confirmation of cartesi-rollups-cli. Only with `stream`, as + * nothing is asked without it. + */ + yes?: boolean; + + /** + * Have cartesi-rollups-cli print its output as JSON. Only with `stream`, + * as the output is always read as JSON without it. + */ + json?: boolean; +}; + +export type RecoveryResult = { + /** Address of the application. */ + application: Address; + + /** + * Output of cartesi-rollups-cli, as it prints it with `--json`. Undefined + * with `stream`, as it is printed instead. + */ + output?: Record; +}; + +/** + * Run a cartesi-rollups-cli command that sends a transaction. With `stream`, + * it is attached to the terminal with the transaction options as given. + * Otherwise it runs with `--yes` and `--json`, and its output is returned. + * @returns the output of the command, undefined with `stream` + */ +export const runRecoveryCommand = async (options: { + accountIndex?: number; + command: string[]; + env?: Record; + projectName: string; + stream: boolean; + tx: TransactionOptions; +}): Promise | undefined> => { + const { accountIndex, command, env, projectName, stream, tx } = options; + if (stream) { + await runAttachedNodeCommand({ + accountIndex, + command: [...command, ...transactionArgs(tx)], + env, + projectName, + }); + return undefined; + } + + const stdout = await execNodeCommand({ + accountIndex, + command: [ + ...command, + ...transactionArgs({ ...tx, json: true, yes: true }), + ], + env, + projectName, + }); + return JSON.parse(stdout); +}; diff --git a/apps/cli/src/api/refund.ts b/apps/cli/src/api/refund.ts new file mode 100644 index 00000000..fed0f43b --- /dev/null +++ b/apps/cli/src/api/refund.ts @@ -0,0 +1,70 @@ +import { getProjectName } from "../base.js"; +import { removeNodePath, writeNodeTempFile } from "../exec/node-container.js"; +import { resolveNodeApplication } from "../node.js"; +import { getInputData } from "../refund.js"; +import { + type RecoveryOptions, + type RecoveryResult, + runRecoveryCommand, +} from "./recovery.js"; + +export type RefundOptions = RecoveryOptions & { + /** Index of the deposit input to refund. */ + inputIndex: bigint; + + /** + * File with the 0x-prefixed InputAdded.input bytes of the deposit. + * @default read from the node + */ + inputFile?: string; +}; + +/** + * Refund a deposit that was not finalized before the application was + * foreclosed. The gas is paid by the account `accountIndex` of the node + * mnemonic. + * @param options refund options + * @returns the application, and the output of cartesi-rollups-cli + */ +export const refund = async ( + options: RefundOptions, +): Promise => { + const { inputFile, inputIndex, stream = false } = options; + const projectName = getProjectName(options); + const application = await resolveNodeApplication({ + application: options.application, + projectName, + }); + + const data = await getInputData({ + application, + inputFile, + inputIndex, + projectName, + }); + + // the node tool reads the input bytes from a file in its container + const path = await writeNodeTempFile({ + content: `${data}\n`, + projectName, + }); + try { + const output = await runRecoveryCommand({ + accountIndex: options.accountIndex, + command: [ + "cartesi-rollups-cli", + "refund", + application, + inputIndex.toString(), + "--input-file", + path, + ], + projectName, + stream, + tx: options, + }); + return { application, output }; + } finally { + await removeNodePath({ path, projectName }); + } +}; diff --git a/apps/cli/src/api/run.ts b/apps/cli/src/api/run.ts new file mode 100644 index 00000000..1df2ad52 --- /dev/null +++ b/apps/cli/src/api/run.ts @@ -0,0 +1,684 @@ +import chalk from "chalk"; +import getPort, { portNumbers } from "get-port"; +import ora from "ora"; +import { + type Address, + createPublicClient, + type Hex, + http, + numberToHex, +} from "viem"; +import fs from "node:fs"; +import { + getCartesiEnvironmentVariables, + getContextPath, + getMachineHash, + getProjectName, +} from "../base.js"; +import { nodePrtAuthVariables } from "../compose/node.js"; +import { + DEFAULT_SDK_VERSION, + PREFERRED_PORT, + type WithdrawalConfig, +} from "../config.js"; +import { + deployApplication, + type EnvironmentOptions, + host, + removeApplication, + type RollupsDeployment, + startEnvironment, + startPrtNodes, + stopEnvironment, + stopPrtNodes as stopPrtNodeServices, + waitHealthyEnvironment, +} from "../exec/rollups.js"; +import { + checkPrtNodes, + describePrtNode, + describeReference, + readerModeChanged, + type ResolvedPrt, + resolvePrtNodes, + runnableNodes, + sentriesOf, +} from "../prt.js"; +import type { ForkConfig } from "../types/chain.js"; +import { assertForkConfig } from "../validations.js"; +import { connect } from "../wallet.js"; +import { DEVNET_GUARDIAN, getWithdrawalConfig } from "../withdrawal.js"; +import { + type ConfigOptions, + listrRenderer, + type Notice, + type Progress, + type ProgressOptions, + resolveConfig, +} from "./types.js"; + +export type RunOptions = ConfigOptions & + ProgressOptions & { + /** + * Interval between blocks, in seconds. + * @default 2 + */ + blockTime?: number; + + /** + * Number of blocks between a claim being submitted and accepted + * (Authority/Quorum only). + * @default 0 + */ + claimStagingPeriod?: number; + + /** Number of cpu limits for the rollups-node. */ + cpus?: number; + + /** + * Default block used when fetching new blocks. + * @default "latest" + */ + defaultBlock?: "latest" | "safe" | "finalized"; + + /** + * Deploy the application built at `.cartesi/image` after the + * environment is healthy. When there is no machine snapshot the + * environment is started anyway, and no application is deployed. + * @default true + */ + deploy?: boolean; + + /** + * Run the environment in the background. When disabled, the returned + * {@link RunResult.cmd} resolves when the environment terminates. + * @default true + */ + detach?: boolean; + + /** + * Do not start the environment, only resolve the docker compose + * configuration, returned as {@link RunResult.config}. + * @default false + */ + dryRun?: boolean; + + /** + * Length of an epoch, in blocks. + * @default 720 + */ + epochLength?: number; + + /** Block number to fork from. */ + forkBlockNumber?: number; + + /** RPC URL to fork from. */ + forkUrl?: string; + + /** Memory limit for the rollups-node, in MB. */ + memory?: number; + + /** + * Port to listen on. + * @default first free port from 6751 + */ + port?: number; + + /** + * Name of the project (used by docker compose and cartesi-rollups-node). + * @default basename of the current working directory + */ + projectName?: string; + + /** + * Deploy the application with PRT consensus. + * @default false + */ + prt?: boolean; + + /** Version of the Cartesi Rollups Runtime to use. */ + runtimeVersion?: string; + + /** + * Optional services to start, from {@link AVAILABLE_SERVICES}. The + * single value `all` starts every optional service. + * @default [] + */ + services?: string[]; + + /** + * Increase the log level of the environment services. + * @default true when `progress` is "verbose" + */ + verbose?: boolean; + + /** + * Called for configuration that is valid but worth saying out loud, + * such as a `[prt]` section that has no effect. Nothing is written to + * the terminal when it is not given. + */ + onNotice?: (notice: RunNotice) => void; + }; + +/** Something worth telling the caller about the configuration of a run. */ +export type RunNotice = Notice; + +export type RunResult = { + /** Name of the project the environment was started as. */ + projectName: string; + + /** Port the environment is listening on. */ + port: number; + + /** URL of the environment. */ + url: string; + + /** Current deployment of the application, if any. */ + readonly deployment: RollupsDeployment | undefined; + + /** The `[prt]` setup the application was deployed with, if any. */ + readonly prtConfig: ResolvedPrt | undefined; + + /** The PRT node services running for the deployment. */ + readonly prtServices: string[]; + + /** + * Docker compose configuration of the environment. Only defined when the + * `dryRun` option is enabled, in which case nothing is started. + */ + config?: string; + + /** + * Resolves when the environment terminates. Only defined when the `detach` + * option is disabled. + */ + cmd?: Promise; + + /** + * Deploy the application currently built at `.cartesi/image`, replacing the + * previous deployment, if any. Useful to redeploy after a rebuild. + * @returns the new deployment, or `undefined` if there is no machine snapshot + */ + deploy(): Promise; + + /** Remove the current deployment of the application from the environment. */ + undeploy(): Promise; + + /** + * Stop the PRT nodes of the deployment. They read the machine a rebuild + * replaces, so they are stopped before building and started again by + * {@link RunResult.deploy}. + */ + stopPrtNodes(): Promise; + + /** Stop the environment, removing its containers and volumes. */ + stop(): Promise; +}; + +/** + * Resolve the configuration of an optional anvil fork. + * @param options fork url and optional block number + * @returns fork configuration, or `undefined` if no fork url was provided + */ +export const configureFork = async (options: { + forkUrl?: string; + forkBlockNumber?: number; +}): Promise => { + if (!options.forkUrl) { + return undefined; + } + + const url = options.forkUrl; + + // create a client to upstream so we can query it + const client = createPublicClient({ + transport: http(url), + }); + + // use explicit fork-block-number or query from upstream + const blockNumber = options.forkBlockNumber + ? BigInt(options.forkBlockNumber) + : await client.getBlockNumber(); + + // need to query fork chainId if forkUrl is specified + const chainId = await client.getChainId(); + + return { blockNumber, chainId, url }; +}; + +const undeployApplication = async (options: { + progress: Progress; + projectName: string; +}) => { + const { progress, projectName } = options; + const spinner = ora({ + isSilent: progress === "silent", + text: `${chalk.cyan(projectName)} undeploying...`, + }).start(); + await removeApplication({ + application: projectName, + force: true, + projectName, + }); + spinner.succeed(`${chalk.cyan(projectName)} undeployed`); +}; + +/** + * Report [prt] settings that are valid but have no effect. + */ +const reportPrtWarnings = (options: { + claimStagingPeriod: number; + notify: (notice: RunNotice) => void; + prtConfig?: ResolvedPrt; +}) => { + const { claimStagingPeriod, notify, prtConfig } = options; + for (const warning of prtConfig?.warnings ?? []) { + notify({ level: "warning", message: warning }); + } + if ( + prtConfig && + sentriesOf(prtConfig).length > 0 && + claimStagingPeriod === 0 + ) { + notify({ + level: "warning", + message: + "with --claim-staging-period 0 a staged claim is accepted at once, so the sentries have no effect", + }); + } +}; + +/** + * Funds the pool accounts and checks the other PRT nodes have ETH, once anvil + * is up and before the deploy they claim for. + */ +const fundPrtNodes = async (options: { + environment: EnvironmentOptions; + prtConfig?: ResolvedPrt; +}) => { + const { environment, prtConfig } = options; + if (!prtConfig || runnableNodes(prtConfig).length === 0) { + return; + } + const client = await connect({ + rpcUrl: `${host}:${environment.port}/anvil`, + }); + await checkPrtNodes(client, prtConfig); +}; + +/** + * Starts the PRT nodes the CLI runs, for the deployed application, then reports + * the manager and every [prt.nodes] entry in file order: a check for each one + * running, a note for each one appointed only. + * @returns the services started + */ +const runPrtNodes = async (options: { + application: Address; + environment: EnvironmentOptions; + progress: Progress; + prtConfig?: ResolvedPrt; +}): Promise => { + const { application, environment, progress, prtConfig } = options; + if ( + !prtConfig || + (prtConfig.nodes.length === 0 && + prtConfig.reference.label === undefined) + ) { + return []; + } + + const nodes = runnableNodes(prtConfig); + const spinner = ora({ isSilent: progress === "silent" }); + let services: string[] = []; + if (nodes.length > 0) { + spinner.start( + `starting ${nodes.length === 1 ? "the PRT node" : `${nodes.length} PRT nodes`}...`, + ); + try { + services = await startPrtNodes({ + ...environment, + application, + imageTag: environment.runtimeVersion, + nodes: prtConfig.nodes, + }); + spinner.stop(); + } catch (error: unknown) { + spinner.fail("the PRT nodes failed to start"); + throw error; + } + } + + // log-symbols' blue info mark is hard to read on a dark terminal + const note = (text: string) => + spinner.stopAndPersist({ symbol: chalk.cyan("\u2139"), text }); + if (prtConfig.reference.claim) { + note(describeReference(prtConfig)); + } else { + spinner.warn(describeReference(prtConfig)); + } + if (prtConfig.sentryManager === undefined) { + spinner.warn("sentry manager none (the sentries can't be rotated)"); + } else { + note(`sentry manager ${prtConfig.sentryManager}`); + } + for (const node of prtConfig.nodes) { + if (node.type === undefined) { + note(describePrtNode(node)); + } else { + spinner.succeed(describePrtNode(node)); + } + } + return services; +}; + +const deployMachine = async (options: { + claimStagingPeriod: number; + consensus?: Address; + epochLength: number; + hash: Hex; + progress: Progress; + projectName: string; + prt?: boolean; + prtConfig?: ResolvedPrt; + salt: Hex; + withdrawalConfig?: WithdrawalConfig; +}) => { + const { + claimStagingPeriod, + consensus, + epochLength, + hash, + progress, + projectName, + prt, + prtConfig, + salt, + withdrawalConfig, + } = options; + + // deploy application to node (onchain and offchain) + const spinner = ora({ + isSilent: progress === "silent", + text: `deploying ${chalk.cyan(hash)} as ${chalk.cyan(projectName)}`, + }); + + const application = await deployApplication({ + claimStagingPeriod, + consensus, + epochLength, + name: projectName, + projectName, + prt, + salt, + sentries: + prtConfig && sentriesOf(prtConfig).map(({ address }) => address), + sentryManager: prtConfig?.sentryManager, + snapshotPath: "/var/lib/cartesi-rollups-node/snapshots/image", + withdrawalConfig, + }); + spinner.succeed( + `${chalk.cyan(projectName)} machine hash is ${chalk.cyan(hash)}`, + ); + spinner.succeed( + `${chalk.cyan(projectName)} contract deployed at ${chalk.cyan(application.address)}`, + ); + return application; +}; + +/** + * Run a local Cartesi node for the application, and deploy to it the machine + * snapshot built at `.cartesi/image`, if there is one. + * + * The environment keeps running in the background until + * {@link RunResult.stop} is called. + * + * @param options run options + * @returns a handle of the running environment + */ +export const run = async (options: RunOptions = {}): Promise => { + const { + blockTime = 2, + claimStagingPeriod = 0, + cpus, + defaultBlock = "latest", + deploy: deployOnStart = true, + detach = true, + dryRun = false, + epochLength = 720, + memory, + progress = "silent", + prt = false, + runtimeVersion = DEFAULT_SDK_VERSION, + services = [], + } = options; + + const notify = options.onNotice ?? (() => {}); + + const verbose = options.verbose ?? progress === "verbose"; + + // project name explicitly defined or the current directory name + const projectName = getProjectName(options); + + // get application configuration (e.g. use withdrawal config if present) + const applicationConfig = resolveConfig(options.config); + + // resolve port number, using the first free port in a range, unless explicitly set + const port = + options.port || + (await getPort({ + port: portNumbers(PREFERRED_PORT, PREFERRED_PORT + 10), + })); + + // host address + const url = `${host}:${port}`; + + // configure optional anvil fork + const forkConfig = await configureFork(options); + + if (forkConfig) { + await assertForkConfig(forkConfig, { includePRT: prt }); + } + + // emergency withdrawal configuration, derived from the accounts drive of the built + // machine. The configuration is resolved again, as a rebuild may have changed it. + const imagePath = getContextPath("image"); + const resolveWithdrawalConfig = () => + getWithdrawalConfig(resolveConfig(options.config), imagePath, { + fork: forkConfig !== undefined, + }); + + // fail before starting the environment if it can't be derived + if (fs.existsSync(imagePath)) { + resolveWithdrawalConfig(); + } + + // [prt] is parsed either way, so a mistake in it fails early, but the node + // takes sentries only on a PRT deploy. Resolved again on a rebuild, like + // the withdrawal configuration. + const resolvePrt = () => { + const config = resolveConfig(options.config); + return prt && config.prt + ? resolvePrtNodes(config.prt, { + guardian: config.withdrawal?.guardian ?? DEVNET_GUARDIAN, + }) + : undefined; + }; + if (applicationConfig.prt && !prt) { + notify({ + level: "info", + message: "[prt] in cartesi.toml is ignored without --prt", + }); + } + + // fail before starting the environment if [prt] can't be resolved + let prtConfig = resolvePrt(); + reportPrtWarnings({ claimStagingPeriod, notify, prtConfig }); + + // in reader mode the node has no PRT signer + const claimSubmission = prtConfig?.reference.claim ?? true; + if (!claimSubmission) { + const hostVars = getCartesiEnvironmentVariables(); + const prtAuth = nodePrtAuthVariables.filter( + (name) => hostVars[name] !== undefined, + ); + if (prtAuth.length > 0) { + notify({ + level: "warning", + message: `${prtAuth.join(", ")} ${prtAuth.length === 1 ? "is" : "are"} set, but [prt.nodes.${prtConfig?.reference.label}] has claim = false, so the rollups-node runs in reader mode with no PRT signer and the value is dropped`, + }); + } + } + + const environment: EnvironmentOptions = { + blockTime, + claimSubmission, + cpus, + defaultBlock, + forkConfig, + memory, + port, + projectName, + prt, + runtimeVersion, + services, + verbose, + }; + + // run compose environment + const { cmd, config } = await startEnvironment({ + ...environment, + detach, + dryRun, + }); + + let deployment: RollupsDeployment | undefined; + let prtServices: string[] = []; + let salt = 0; + + const stopPrtNodes = async () => { + await stopPrtNodeServices({ projectName, services: prtServices }); + prtServices = []; + }; + + const stop = async () => { + await stopEnvironment({ projectName }); + prtServices = []; + }; + + const undeploy = async () => { + if (deployment) { + await undeployApplication({ progress, projectName }); + deployment = undefined; + } + }; + + /** + * Deploy the machine snapshot, replacing the previous deployment. + * @param options.initial whether this is the deploy at startup, which uses + * the [prt] setup resolved and reported before the environment started, + * instead of resolving and reporting it again + */ + const deployMachineSnapshot = async (options: { initial: boolean }) => { + const machineHash = await getMachineHash({ + sdk: applicationConfig.sdk, + }); + if (!machineHash) { + return undefined; + } + + // the PRT nodes read the machine a rebuild replaces, and claim for the + // application this redeploy removes + await stopPrtNodes(); + + // the accounts drive may have moved with a rebuild, resolved before + // undeploying in case it is now invalid + const withdrawalConfig = resolveWithdrawalConfig(); + + // a PRT redeploy creates a new consensus, with the sentries as they are + // in the config now. The node's mode can't change: it is fixed in its + // database + if (!options.initial) { + const resolved = resolvePrt(); + const moved = readerModeChanged(prtConfig, resolved); + if (moved !== undefined) { + notify({ level: "warning", message: moved }); + } else { + prtConfig = resolved; + } + reportPrtWarnings({ claimStagingPeriod, notify, prtConfig }); + } + await fundPrtNodes({ environment, prtConfig }); + + // keep the consensus of the previous deployment, if there is one; a + // PRT deploy ignores it and creates a new one + const consensus = deployment?.consensus; + await undeploy(); + + deployment = await deployMachine({ + claimStagingPeriod, + consensus, + epochLength, + hash: machineHash, + progress, + projectName, + prt, + prtConfig, + salt: numberToHex(salt++, { size: 32 }), + withdrawalConfig, + }); + prtServices = await runPrtNodes({ + application: deployment.address, + environment, + progress, + prtConfig, + }); + return deployment; + }; + + const deploy = () => deployMachineSnapshot({ initial: false }); + + const result: RunResult = { + get deployment() { + return deployment; + }, + get prtConfig() { + return prtConfig; + }, + get prtServices() { + return prtServices; + }, + cmd, + config, + deploy, + port, + projectName, + stop, + stopPrtNodes, + undeploy, + url, + }; + + if (dryRun) { + // environment was not started, just return the compose configuration + return result; + } + + ora({ isSilent: progress === "silent" }).succeed( + `${chalk.cyan(projectName)} starting at ${chalk.cyan(url)}`, + ); + + // wait for the environment to be healthy + await waitHealthyEnvironment({ + name: projectName, + port, + projectName, + renderer: listrRenderer(progress), + services, + }); + + // deploy the application built at .cartesi/image, if there is one + if (deployOnStart) { + await deployMachineSnapshot({ initial: true }); + } + + return result; +}; diff --git a/apps/cli/src/api/send.ts b/apps/cli/src/api/send.ts new file mode 100644 index 00000000..af36712b --- /dev/null +++ b/apps/cli/src/api/send.ts @@ -0,0 +1,178 @@ +import { + type Address, + encodeAbiParameters, + encodePacked, + getAddress, + type Hash, + type Hex, + isAddress, + isHex, + parseAbiParameters, + stringToHex, +} from "viem"; +import { inputBoxAbi, inputBoxAddress } from "../contracts.js"; +import { type ConnectionOptions, resolveConnection } from "./connection.js"; + +/** Encoding of an application input. */ +export type InputEncoding = "abi" | "abi-packed" | "hex" | "string"; + +export type EncodeInputOptions = { + /** + * Encoding of the input. When not defined, an input starting with `0x` is + * assumed to be hex, and anything else is encoded as an UTF-8 string. + */ + encoding?: InputEncoding; + + /** ABI parameters, required by the `abi` and `abi-packed` encodings. */ + abiParams?: string; +}; + +/** + * Encode an application input as hex, according to the given encoding. + * @param input input payload + * @param options encoding options + * @returns the encoded input, or `undefined` if there is no input + */ +export const encodeInput = async ( + input: string | undefined, + options: EncodeInputOptions, +): Promise => { + const { encoding } = options; + if (input) { + if (encoding === "hex") { + // validate if is a hex value + if (!isHex(input)) { + throw new Error("input encoded as hex must start with 0x"); + } + return input; + } + if (encoding === "string") { + // encode UTF-8 string as hex + return stringToHex(input); + } + if (encoding === "abi" || encoding === "abi-packed") { + const abiParams = options.abiParams; + if (!abiParams) { + throw new Error("Undefined input-abi-params"); + } + const abiParameters = parseAbiParameters(abiParams); + // TODO: decode values + const values = input.split(",").map((v, index) => { + if (index >= abiParameters.length) { + throw new Error( + `Too many values, expected ${abiParameters.length} values based on --input-abi-params '${abiParams}', parsing value at index ${index} from input '${input}'`, + ); + } + const param = abiParameters[index]; + switch (param.type) { + case "string": + return v; + case "bool": + if (v === "true") return true; + if (v === "false") return false; + throw new Error(`Invalid boolean value: ${v}`); + case "uint": + case "uint8": + case "uint16": + case "uint32": + case "uint64": + case "uint128": + case "uint256": + case "int": + case "int8": + case "int16": + case "int32": + case "int64": + case "int128": + case "int256": + try { + return BigInt(v); + } catch { + throw new Error(`Invalid uint value: ${v}`); + } + case "bytes": + if (isHex(v)) { + return v as Hex; + } + throw new Error(`Invalid bytes value: ${v}`); + case "address": + if (isAddress(v)) { + return getAddress(v); + } + throw new Error(`Invalid address value: ${v}`); + default: + throw new Error(`Unsupported type ${param.type}`); + } + }); + if (values.length !== abiParameters.length) { + throw new Error( + `Not enough values, expected ${abiParameters.length} values based on --input-abi-params '${abiParams}', parsed ${values.length} values from input '${input}'`, + ); + } + if (encoding === "abi") { + return encodeAbiParameters(abiParameters, values); + } + const types = abiParameters.map((p) => p.type); + return encodePacked(types, values); + } + if (isHex(input)) { + // encoding not specified, if starts with 0x, assume hex + return input; + } + // encode UTF-8 string as hex + return stringToHex(input); + } + return undefined; +}; + +export type SendOptions = ConnectionOptions & + EncodeInputOptions & { + /** Input payload, encoded according to `encoding`. */ + input?: string; + + /** Input payload already encoded as hex. Takes precedence over `input`. */ + payload?: Hex; + }; + +export type SendResult = { + /** Address of the application the input was sent to. */ + application: Address; + + /** Address of the input sender. */ + from: Address; + + /** Input payload, encoded as hex. */ + payload: Hex; + + /** Hash of the transaction that added the input. */ + transactionHash: Hash; +}; + +/** + * Send an input to an application running on a local environment. + * @param options send options + * @returns the input sent, and the transaction that added it to the input box + */ +export const send = async (options: SendOptions): Promise => { + // encode the payload, unless it is already encoded + const payload = + options.payload ?? (await encodeInput(options.input, options)); + if (!payload) { + throw new Error("Undefined input payload"); + } + + const { application, client, from } = await resolveConnection(options); + + const { request } = await client.simulateContract({ + address: inputBoxAddress, + abi: inputBoxAbi, + account: from, + args: [application, payload], + functionName: "addInput", + }); + + const transactionHash = await client.writeContract(request); + await client.waitForTransactionReceipt({ hash: transactionHash }); + + return { application, from, payload, transactionHash }; +}; diff --git a/apps/cli/src/api/shell.ts b/apps/cli/src/api/shell.ts new file mode 100644 index 00000000..65dd9aa2 --- /dev/null +++ b/apps/cli/src/api/shell.ts @@ -0,0 +1,92 @@ +import { ExecaError } from "execa"; +import fs from "fs-extra"; +import path from "node:path"; +import { getContextPath } from "../base.js"; +import { nvramHasImage, nvramImageFilename } from "../builder/nvram.js"; +import { bootMachine } from "../machine.js"; +import { type ConfigOptions, resolveConfig } from "./types.js"; + +export type ShellOptions = ConfigOptions & { + /** + * Shell command to run inside the machine. + * @default "/bin/sh" + */ + command?: string; + + /** + * Run as the root user. + * @default false + */ + runAsRoot?: boolean; +}; + +/** + * Boot the machine of the application in interactive mode, running a shell (or + * any other command) inside it. Requires the drives to be built already, by + * {@link build}. + * + * The machine is attached to the terminal of the calling process. + * + * @param options shell options + */ +export const shell = async (options: ShellOptions = {}): Promise => { + const { command = "/bin/sh", runAsRoot = false } = options; + + // get application configuration, from a Config object or 'cartesi.toml' + const config = resolveConfig(options.config); + + // destination directory for image and intermediate files + const destination = path.resolve(getContextPath()); + + // check if all drives are built + for (const [name, drive] of Object.entries(config.drives)) { + const filename = `${name}.${drive.format}`; + const pathname = getContextPath(filename); + if (!fs.existsSync(pathname)) { + throw new Error(`drive '${name}' not built, run 'build'`); + } + } + + // check if all nvrams backed by an image are built, pristine ones have none + for (const [label, nvram] of Object.entries(config.nvrams)) { + if (!nvramHasImage(nvram)) { + continue; + } + const pathname = getContextPath(nvramImageFilename(label)); + if (!fs.existsSync(pathname)) { + throw new Error(`nvram '${label}' not built, run 'build'`); + } + } + + const machine = { + ...config.machine, + + // create shell entrypoint + entrypoint: command, + + // run as root if flag is set + user: runAsRoot ? "root" : undefined, + }; + + // boot machine + try { + await bootMachine( + { ...config, machine }, + undefined, + { interactive: true }, // start with interactive mode on + { + cwd: destination, + stdio: "inherit", + tty: true, + }, + ); + } catch (error: unknown) { + if (error instanceof ExecaError) { + // exit code of a shell terminated by SIGINT, just return gracefully + if (error.exitCode === 130) { + return; + } + } + throw error; + } +}; diff --git a/apps/cli/src/api/status.ts b/apps/cli/src/api/status.ts new file mode 100644 index 00000000..955e78f0 --- /dev/null +++ b/apps/cli/src/api/status.ts @@ -0,0 +1,48 @@ +import { getProjectName, getServiceState } from "../base.js"; +import { getDeployments, type RollupsDeployment } from "../exec/rollups.js"; + +export type StatusOptions = { + /** + * Name of the project (used by docker compose and cartesi-rollups-node). + * @default basename of the current working directory + */ + projectName?: string; +}; + +export type StatusResult = { + /** Name of the project the status refers to. */ + projectName: string; + + /** Whether the rollups node of the environment is running. */ + running: boolean; + + /** State of the rollups node container, as reported by docker compose. */ + state?: string; + + /** Applications deployed to the rollups node. */ + deployments: RollupsDeployment[]; +}; + +/** + * Query the status of a local environment, and the applications deployed to it. + * @param options status options + * @returns state of the environment and its deployments + */ +export const status = async ( + options: StatusOptions = {}, +): Promise => { + const projectName = getProjectName(options); + + const state = await getServiceState({ + projectName, + service: "rollups_node", + }); + const deployments = await getDeployments({ projectName }); + + return { + projectName, + running: state === "running", + state, + deployments, + }; +}; diff --git a/apps/cli/src/api/types.ts b/apps/cli/src/api/types.ts new file mode 100644 index 00000000..d3c34858 --- /dev/null +++ b/apps/cli/src/api/types.ts @@ -0,0 +1,84 @@ +import { getApplicationConfig } from "../base.js"; +import type { Config } from "../config.js"; + +/** + * Verbosity of the progress information written to the terminal while an API + * function is running. + * + * - `silent`: nothing is written to the terminal (default of the library API); + * - `default`: spinners and task lists, same as the CLI; + * - `verbose`: no spinners, one line per event, same as the CLI `--verbose`. + */ +export type Progress = "silent" | "default" | "verbose"; + +/** + * Options shared by all API functions that report progress. + */ +export type ProgressOptions = { + /** + * How much progress information is written to the terminal. + * @default "silent" + */ + progress?: Progress; +}; + +/** + * Something worth telling the caller, such as configuration that is valid but + * has no effect. API functions that take an `onNotice` callback report these + * through it, instead of writing them to the terminal. + */ +export type Notice = { + level: "info" | "warning"; + message: string; +}; + +/** + * Application configuration, either already parsed, or a path (or list of + * paths) of TOML configuration files to be read and merged, in order. + */ +export type ConfigInput = Config | string | string[]; + +export type ConfigOptions = { + /** + * Application configuration, or path of the configuration file(s). + * @default "cartesi.toml" + */ + config?: ConfigInput; +}; + +/** + * Resolve the application configuration from the several ways it can be + * provided to the API: an already parsed {@link Config}, one configuration file + * path, a list of configuration file paths, or nothing (which falls back to + * `cartesi.toml` of the current directory). + * @param config configuration or path of configuration file(s) + * @returns parsed application configuration + */ +export const resolveConfig = (config?: ConfigInput): Config => { + if (config === undefined) { + return getApplicationConfig(["cartesi.toml"]); + } + if (typeof config === "string") { + return getApplicationConfig([config]); + } + if (Array.isArray(config)) { + return getApplicationConfig(config); + } + return config; +}; + +/** + * Map a {@link Progress} value to a listr2 renderer name. + * @param progress progress verbosity + * @returns name of the listr2 renderer + */ +export const listrRenderer = (progress: Progress = "silent") => { + switch (progress) { + case "silent": + return "silent" as const; + case "verbose": + return "verbose" as const; + case "default": + return "default" as const; + } +}; diff --git a/apps/cli/src/api/withdraw.ts b/apps/cli/src/api/withdraw.ts new file mode 100644 index 00000000..c74ab67a --- /dev/null +++ b/apps/cli/src/api/withdraw.ts @@ -0,0 +1,216 @@ +import chalk from "chalk"; +import fs from "fs-extra"; +import { type Address, getAddress, type Hash } from "viem"; +import { getProjectName } from "../base.js"; +import { + execNodeCommand, + removeNodePath, + runAttachedNodeCommand, + type TransactionOptions, + transactionArgs, + writeNodeTempFile, +} from "../exec/node-container.js"; +import { getNodeWithdrawalConfig } from "../exec/rollups.js"; +import { resolveNodeApplication } from "../node.js"; +import { + assertForeclosed, + generateAccountProofs, + replayLastFinalizedEpoch, +} from "../withdraw.js"; +import { + type RecoveryOptions, + type RecoveryResult, + runRecoveryCommand, +} from "./recovery.js"; +import type { Progress } from "./types.js"; + +export type WithdrawOptions = RecoveryOptions & { + /** + * Account to withdraw the funds of, whose proofs are generated from the + * application replayed up to its last finalized epoch. Either this or + * `proofFile` is required. + */ + account?: Address; + + /** + * Withdraw proof generated elsewhere, instead of generating it. Either this + * or `account` is required. + */ + proofFile?: string; +}; + +/** + * Generate the proofs of an account and prove the accounts drive root, if + * nobody did it yet + * @returns path of the withdraw proof inside the rollups node container + */ +const proveAccount = async (options: { + account: Address; + accountIndex?: number; + application: Address; + driveRootProven: boolean; + finalizedMachineRoot: Hash; + progress: Progress; + projectName: string; + stream: boolean; + tx: TransactionOptions; +}): Promise => { + const { + account, + accountIndex, + application, + driveRootProven, + finalizedMachineRoot, + progress, + projectName, + stream, + tx, + } = options; + const driveConfig = await getNodeWithdrawalConfig({ + application, + projectName, + }); + + const { store } = await replayLastFinalizedEpoch({ + application, + finalizedMachineRoot, + progress, + projectName, + }); + + const proof = await generateAccountProofs({ + account, + application, + driveConfig, + finalizedMachineRoot, + progress, + projectName, + store, + }); + + if (!driveRootProven) { + // the withdrawal depends on it, so always wait for the receipt + const command = [ + "cartesi-rollups-cli", + "prove-drive-root", + application, + "--proof-file", + proof.driveRootProofFile, + ]; + if (stream) { + // keep stdout for the output of the withdrawal + await runAttachedNodeCommand({ + accountIndex, + command: [ + ...command, + ...transactionArgs({ ...tx, json: false, wait: true }), + ], + projectName, + stdout: "stderr", + }); + } else { + await execNodeCommand({ + accountIndex, + command: [ + ...command, + ...transactionArgs({ + ...tx, + json: false, + wait: true, + yes: true, + }), + ], + projectName, + }); + } + } + + return proof.withdrawProofFile; +}; + +/** + * Withdraw the funds of an account from a foreclosed application. The gas is + * paid by the account `accountIndex` of the node mnemonic. The application is + * replayed and the proofs are generated in the rollups node container, unless + * a `proofFile` is given; replays and proofs are kept there, for the next + * withdrawals to reuse. + * @param options withdraw options + * @returns the application, and the output of cartesi-rollups-cli + */ +export const withdraw = async ( + options: WithdrawOptions, +): Promise => { + const { + accountIndex, + proofFile, + progress = "silent", + stream = false, + } = options; + if (options.account && proofFile) { + throw new Error("Define either account or proofFile, not both"); + } + if (!options.account && !proofFile) { + throw new Error( + "Define the account to withdraw the funds of, or a proofFile", + ); + } + + const projectName = getProjectName(options); + const application = await resolveNodeApplication({ + application: options.application, + projectName, + }); + const { driveRootProven, finalizedMachineRoot } = await assertForeclosed({ + application, + projectName, + }); + + let withdrawProofFile: string; + let tmpProofFile: string | undefined; + try { + if (proofFile) { + if (!driveRootProven) { + throw new Error( + `The accounts drive root of ${application} isn't proven yet. ${chalk.cyan("--proof-file")} only carries the account proof; run ${chalk.cyan("cartesi withdraw --account
")} once so the CLI proves the drive root, then ${chalk.cyan("--proof-file")} will work`, + ); + } + tmpProofFile = await writeNodeTempFile({ + content: await fs.readFile(proofFile, "utf-8"), + projectName, + }); + withdrawProofFile = tmpProofFile; + } else { + withdrawProofFile = await proveAccount({ + // checksummed, as it names the directory of its cached proofs + account: getAddress(options.account as Address), + accountIndex, + application, + driveRootProven, + finalizedMachineRoot, + progress, + projectName, + stream, + tx: options, + }); + } + + const output = await runRecoveryCommand({ + accountIndex, + command: [ + "cartesi-rollups-cli", + "withdraw", + application, + "--proof-file", + withdrawProofFile, + ], + projectName, + stream, + tx: options, + }); + return { application, output }; + } finally { + if (tmpProofFile) { + await removeNodePath({ path: tmpProofFile, projectName }); + } + } +}; diff --git a/apps/cli/src/base.ts b/apps/cli/src/base.ts index d121cb79..25640811 100644 --- a/apps/cli/src/base.ts +++ b/apps/cli/src/base.ts @@ -31,7 +31,7 @@ import { testUsdWithdrawalOutputBuilderAddress, usdWithdrawalOutputBuilderFactoryAddress, } from "./contracts.js"; -import { cartesiMachineStoredHash } from "./exec"; +import { cartesiMachineStoredHash } from "./exec/index.js"; import { getApplicationAddress, getForkConfig } from "./exec/rollups.js"; import type { PsResponse } from "./types/docker.js"; import { assertForkConfig } from "./validations.js"; diff --git a/apps/cli/src/commands/address-book.ts b/apps/cli/src/commands/address-book.ts index c979f665..a9b9b9ae 100755 --- a/apps/cli/src/commands/address-book.ts +++ b/apps/cli/src/commands/address-book.ts @@ -1,6 +1,6 @@ import { Command } from "@commander-js/extra-typings"; import Table from "cli-table3"; -import { getAddressBook, getProjectName } from "../base.js"; +import { addressBook as getAddressBook } from "../api/address-book.js"; export const createAddressBookCommand = () => { return new Command("address-book") @@ -18,8 +18,7 @@ export const createAddressBookCommand = () => { ) .action(async (contract, options, command) => { const { json } = options; - const projectName = getProjectName(options); - const addressBook = await getAddressBook({ projectName }); + const addressBook = await getAddressBook(options); if (contract !== undefined) { // look up a single contract by name (case-insensitive) diff --git a/apps/cli/src/commands/build.ts b/apps/cli/src/commands/build.ts index 9aa69ef5..2f4d638c 100755 --- a/apps/cli/src/commands/build.ts +++ b/apps/cli/src/commands/build.ts @@ -1,95 +1,21 @@ import { Command, Option } from "@commander-js/extra-typings"; -import chalk from "chalk"; -import fs from "fs-extra"; -import { Listr, type ListrTask } from "listr2"; -import path from "node:path"; -import { getApplicationConfig, getContextPath } from "../base.js"; -import { - buildDirectory, - buildDocker, - buildEmpty, - buildNone, - buildNvram, - buildTar, -} from "../builder/index.js"; -import type { Config, DriveConfig, ImageInfo, NvramConfig } from "../config.js"; -import { bootMachine } from "../machine.js"; -import { describeWithdrawalConfig, resolveWithdrawal } from "../withdrawal.js"; - -// context for Listr build tasks -interface BuildContext { - config: Config; - debug: boolean; - destination: string; - imageInfo?: ImageInfo; -} - -const buildDriveTask = ( - name: string, - drive: DriveConfig, -): ListrTask => ({ - title: `Building drive ${chalk.cyan(name)}`, - task: async (ctx, task) => { - const { config, debug, destination } = ctx; - const sdk = config.sdk; - const reporter = (line: string) => { - task.output = line; - }; - - switch (drive.builder) { - case "directory": { - await buildDirectory( - name, - drive, - sdk, - destination, - debug, - reporter, - ); - break; - } - case "docker": { - const imageInfo = await buildDocker( - name, - drive, - sdk, - destination, - debug, - reporter, - ); - if (imageInfo && name === "root") { - // only set image info for root drive - ctx.imageInfo = imageInfo; - } - break; - } - case "empty": { - await buildEmpty(name, drive, sdk, destination); - break; - } - case "tar": { - await buildTar(name, drive, sdk, destination, reporter); - break; - } - case "none": { - await buildNone(name, drive, destination); - break; - } - } - task.title = `Build drive ${chalk.cyan(name)}`; - }, -}); - -const buildNvramTask = ( - label: string, - nvram: NvramConfig, -): ListrTask => ({ - title: `Building nvram ${chalk.cyan(label)}`, - task: async (ctx, task) => { - await buildNvram(label, nvram, ctx.destination); - task.title = `Build nvram ${chalk.cyan(label)}`; - }, -}); +import { type BuildResult, build } from "../api/build.js"; +import { describeWithdrawalConfig } from "../withdrawal.js"; + +/** + * Print what a build has to show after its progress: the accounts drive + * layout, and what will be deployed from it. Shared by `cartesi build` and the + * "Build and redeploy" of `cartesi run`. + */ +export const printBuildResult = (result: BuildResult) => { + if (result.withdrawal) { + const { layout, withdrawal } = result.withdrawal; + console.log(); + console.log( + describeWithdrawalConfig(result.config, layout, withdrawal), + ); + } +}; export const createBuildCommand = () => { return new Command("build") @@ -113,103 +39,14 @@ export const createBuildCommand = () => { .option("-d, --drives-only", "only build drives, do not boot machine") .option("-v, --verbose", "verbose output", false) .action(async (options) => { - const { debug, drivesOnly, verbose } = options; + const { config, debug, drivesOnly, verbose } = options; - // get application configuration from 'cartesi.toml' - const config = getApplicationConfig(options.config); - - // destination directory for image and intermediate files - const destination = path.resolve(getContextPath()); - - // prepare context directory - await fs.emptyDir(destination); // XXX: make it less error prone - - // build context - const ctx = { + const result = await build({ config, debug, - destination, - verbose, - imageInfo: undefined, - }; - - // tasks to build drives - const driveTasks = Object.entries(config.drives).map( - ([name, drive]) => buildDriveTask(name, drive), - ); - - // tasks to build the images backing nvrams, pristine ones need none - const nvramTasks = Object.entries(config.nvrams).map( - ([label, nvram]) => buildNvramTask(label, nvram), - ); - - const groups: ListrTask[] = [ - { - title: "Build drives", - task: async (_ctx, task) => { - return task.newListr(driveTasks, { - concurrent: true, - rendererOptions: { - collapseSubtasks: false, - }, - ctx, - }); - }, - }, - ]; - - if (nvramTasks.length > 0) { - groups.push({ - title: "Build nvrams", - task: async (_ctx, task) => { - return task.newListr(nvramTasks, { - concurrent: true, - rendererOptions: { - collapseSubtasks: false, - }, - ctx, - }); - }, - }); - } - - const builds = new Listr(groups, { - ctx, - renderer: verbose ? "verbose" : "default", + drivesOnly, + progress: verbose ? "verbose" : "default", }); - const result = await builds.run(); - - // if only build drives, quit here - if (drivesOnly) { - return; - } - - // create machine snapshot - await bootMachine( - config, - result.imageInfo, - { - finalHash: true, - store: "image", - }, - { - cwd: destination, - stdio: "inherit", - }, - ); - - // make snapshot readable by all users, because cartesi-machine sets to 600 - const imagePath = path.join(destination, "image"); - await fs.chmod(imagePath, 0o755); - - // check the accounts drive where the machine placed it, and show the result - const resolved = resolveWithdrawal(config, imagePath); - if (resolved) { - const { layout, withdrawal } = resolved; - console.log(); - console.log( - describeWithdrawalConfig(config, layout, withdrawal), - ); - } + printBuildResult(result); }); }; diff --git a/apps/cli/src/commands/clean.ts b/apps/cli/src/commands/clean.ts index 71bd0824..69790592 100755 --- a/apps/cli/src/commands/clean.ts +++ b/apps/cli/src/commands/clean.ts @@ -1,11 +1,10 @@ import { Command } from "@commander-js/extra-typings"; -import fs from "fs-extra"; -import { getContextPath } from "../base.js"; +import { clean } from "../api/clean.js"; export const createCleanCommand = () => { return new Command("clean") .description("Deletes all cached build artifacts of application.") .action(async () => { - await fs.emptyDir(getContextPath()); + await clean(); }); }; diff --git a/apps/cli/src/commands/create.ts b/apps/cli/src/commands/create.ts index 606230b7..87bd5ebe 100755 --- a/apps/cli/src/commands/create.ts +++ b/apps/cli/src/commands/create.ts @@ -1,22 +1,7 @@ import { Command, Option } from "@commander-js/extra-typings"; import chalk from "chalk"; import ora from "ora"; -import { download } from "../template.js"; - -export const DEFAULT_TEMPLATES_BRANCH = "prerelease/sdk-12"; - -const TEMPLATES = [ - "cpp", - "cpp-low-level", - "go", - "java", - "javascript", - "lua", - "python", - "ruby", - "rust", - "typescript", -] as const; +import { create, DEFAULT_TEMPLATES_BRANCH, TEMPLATES } from "../api/create.js"; export const createCreateCommand = () => { return new Command("create") @@ -34,7 +19,7 @@ export const createCreateCommand = () => { .action(async (name, { branch, template }) => { const spinner = ora("Creating application...").start(); try { - const { dir } = await download(template, branch, name); + const { dir } = await create({ branch, name, template }); spinner.succeed(`Application created at ${chalk.cyan(dir)}`); } catch (e: unknown) { spinner.fail( diff --git a/apps/cli/src/commands/deposit/erc1155.ts b/apps/cli/src/commands/deposit/erc1155.ts index b40ba366..f7508249 100644 --- a/apps/cli/src/commands/deposit/erc1155.ts +++ b/apps/cli/src/commands/deposit/erc1155.ts @@ -1,17 +1,12 @@ import { Command } from "@commander-js/extra-typings"; import input from "@inquirer/input"; -import chalk from "chalk"; -import ora from "ora"; import { type Address, getAddress, isAddress, isHex } from "viem"; -import { getProjectName } from "../../base.js"; import { - erc1155BatchPortalAbi, - erc1155BatchPortalAddress, - erc1155SinglePortalAbi, - erc1155SinglePortalAddress, - testMultiTokenAbi, - testMultiTokenAddress, -} from "../../contracts.js"; + depositErc1155, + depositErc1155Batch, +} from "../../api/deposit/erc1155.js"; +import { getProjectName } from "../../base.js"; +import { testMultiTokenAddress } from "../../contracts.js"; import { addressInput, bigintInput, @@ -19,25 +14,18 @@ import { } from "../../prompts.js"; import { connect, getDefaultSender } from "../../wallet.js"; import type { DepositCommandOpts } from "../deposit.js"; +import { reportDepositError } from "./error.js"; -type ERC1155Token = { - address: Address; - name: string; -}; - -const parseToken = async (options: { - token?: string; -}): Promise => { - const address = - options.token && isAddress(options.token) - ? getAddress(options.token) - : await addressInput({ - message: "Token address", - default: testMultiTokenAddress, - }); +const parseTokenAddress = async (token?: string): Promise
=> + token && isAddress(token) + ? getAddress(token) + : addressInput({ + message: "Token address", + default: testMultiTokenAddress, + }); - return { address, name: "TestMultiToken" }; -}; +const parseBigints = (value: string): bigint[] => + value.split(",").map((v) => BigInt(v.trim())); export const createErc1155SingleCommand = () => { return new Command<[], Record, DepositCommandOpts>( @@ -54,11 +42,9 @@ export const createErc1155SingleCommand = () => { const { from } = command.optsWithGlobals(); // connect to anvil - const testClient = await connect(command.optsWithGlobals()); + const client = await connect(command.optsWithGlobals()); - const token = await parseToken({ - token: options.token, - }); + const token = await parseTokenAddress(options.token); const tokenId = tokenIdString ? BigInt(tokenIdString) @@ -75,7 +61,7 @@ export const createErc1155SingleCommand = () => { const account = from && isAddress(from) ? getAddress(from) - : await getDefaultSender(testClient); + : await getDefaultSender(client); const amount = amountString ? BigInt(amountString) @@ -84,18 +70,6 @@ export const createErc1155SingleCommand = () => { decimals: 0, }); - // ensure amount is positive - if (amount <= BigInt(0)) { - console.error( - chalk.red( - "Amount of tokens to be deposited, must be greater than zero.", - ), - ); - return; - } - - const tokenAbi = testMultiTokenAbi; - const baseLayerData = isHex(options.baseLayerData) ? options.baseLayerData : "0x"; @@ -103,72 +77,22 @@ export const createErc1155SingleCommand = () => { ? options.execLayerData : "0x"; - // progress spinner - const progress = ora(); - - // check balance - const balance = await testClient.readContract({ - abi: tokenAbi, - address: token.address, - functionName: "balanceOf", - args: [account, tokenId], - }); - if (balance < amount) { - progress.fail("Insufficient balance"); - return; - } - - // check if sufficiently approved - const isApproved = await testClient.readContract({ - abi: tokenAbi, - address: token.address, - functionName: "isApprovedForAll", - args: [account, erc1155SinglePortalAddress], - }); - - // approve if needed - if (isApproved === false) { - progress.start(`Approving ERC1155Portal...`); - const { request } = await testClient.simulateContract({ - abi: tokenAbi, - account, - address: token.address, - functionName: "setApprovalForAll", - args: [erc1155SinglePortalAddress, true], - }); - const hash = await testClient.writeContract(request); - await testClient.waitForTransactionReceipt({ hash }); - progress.succeed(`Approved ERC1155Portal`); - } - - // simulate deposit call - const { request } = await testClient.simulateContract({ - abi: erc1155SinglePortalAbi, - account, - address: erc1155SinglePortalAddress, - functionName: "depositSingleErc1155Token", - args: [ - token.address, - application, - tokenId, + try { + await depositErc1155({ amount, + application, baseLayerData, + client, execLayerData, - ], - }); - - // for messages - const amountLabel = `${chalk.cyan(amount)} units of token id ${tokenId}`; - - // send deposit - progress.start( - `Depositing ${amountLabel} to ${chalk.cyan(application)}...`, - ); - const hash = await testClient.writeContract(request); - await testClient.waitForTransactionReceipt({ hash }); - progress.succeed( - `Deposited ${amountLabel} to ${chalk.cyan(application)}`, - ); + from: account, + progress: "default", + projectName, + token, + tokenId, + }); + } catch (e: unknown) { + reportDepositError(e); + } }); }; @@ -187,59 +111,19 @@ export const createErc1155BatchCommand = () => { const { from } = command.optsWithGlobals(); // connect to anvil - const testClient = await connect(command.optsWithGlobals()); - - const token = await parseToken({ - token: options.token, - }); + const client = await connect(command.optsWithGlobals()); - // Parse token IDs - let tokenIds: bigint[]; + const token = await parseTokenAddress(options.token); - if (tokenIdsString) { - tokenIds = tokenIdsString - .split(",") - .map((id) => BigInt(id.trim())); - } else { - // Prompt for token IDs if not provided - const user_input = await input({ - message: "Token IDs (comma separated)", - }); - tokenIds = user_input.split(",").map((id) => BigInt(id.trim())); - } - - // Parse amounts - let amounts: bigint[]; - - if (amountsString) { - amounts = amountsString.split(",").map((a) => BigInt(a.trim())); - } else { - // Prompt for amounts if not provided - const user_input = await input({ - message: "Amounts (comma separated)", - }); - amounts = user_input.split(",").map((a) => BigInt(a.trim())); - } - - if (tokenIds.length !== amounts.length) { - console.error( - chalk.red( - "Token IDs and amounts must have the same length.", - ), - ); - return; - } + const tokenIds = parseBigints( + tokenIdsString ?? + (await input({ message: "Token IDs (comma separated)" })), + ); - for (let i = 0; i < amounts.length; i++) { - if (amounts[i] <= BigInt(0)) { - console.error( - chalk.red( - `Amount of token Id: ${tokenIds[i]} to be deposited, must be greater than zero.`, - ), - ); - return; - } - } + const amounts = parseBigints( + amountsString ?? + (await input({ message: "Amounts (comma separated)" })), + ); const projectName = getProjectName(command.optsWithGlobals()); @@ -253,9 +137,7 @@ export const createErc1155BatchCommand = () => { const account = from && isAddress(from) ? getAddress(from) - : await getDefaultSender(testClient); - - const tokenAbi = testMultiTokenAbi; + : await getDefaultSender(client); const baseLayerData = isHex(options.baseLayerData) ? options.baseLayerData @@ -264,80 +146,21 @@ export const createErc1155BatchCommand = () => { ? options.execLayerData : "0x"; - // progress spinner - const progress = ora(); - - // check balances - for (let i = 0; i < tokenIds.length; i++) { - const balance = await testClient.readContract({ - abi: tokenAbi, - address: token.address, - functionName: "balanceOf", - args: [account, tokenIds[i]], - }); - if (balance < amounts[i]) { - progress.fail( - `Insufficient balance for token ID ${tokenIds[i]}`, - ); - return; - } - } - - // check if sufficiently approved - const isApproved = await testClient.readContract({ - abi: tokenAbi, - address: token.address, - functionName: "isApprovedForAll", - args: [account, erc1155BatchPortalAddress], - }); - - // approve if needed - if (isApproved === false) { - progress.start(`Approving ERC1155Portal...`); - const { request } = await testClient.simulateContract({ - abi: tokenAbi, - account, - address: token.address, - functionName: "setApprovalForAll", - args: [erc1155BatchPortalAddress, true], - }); - const hash = await testClient.writeContract(request); - await testClient.waitForTransactionReceipt({ hash }); - progress.succeed(`Approved ERC1155Portal`); - } - - // simulate batch deposit call - const { request } = await testClient.simulateContract({ - abi: erc1155BatchPortalAbi, - account, - address: erc1155BatchPortalAddress, - functionName: "depositBatchErc1155Token", - args: [ - token.address, - application, - tokenIds, + try { + await depositErc1155Batch({ amounts, + application, baseLayerData, + client, execLayerData, - ], - }); - - // for messages - const amountLabel = tokenIds - .map( - (id, i) => - `${chalk.cyan(amounts[i])} units of token id ${id}`, - ) - .join(", "); - - // send deposit - progress.start( - `Depositing tokens to ${chalk.cyan(application)}...`, - ); - const hash = await testClient.writeContract(request); - await testClient.waitForTransactionReceipt({ hash }); - progress.succeed( - `Deposited ${amountLabel} to ${chalk.cyan(application)}`, - ); + from: account, + progress: "default", + projectName, + token, + tokenIds, + }); + } catch (e: unknown) { + reportDepositError(e); + } }); }; diff --git a/apps/cli/src/commands/deposit/erc20.ts b/apps/cli/src/commands/deposit/erc20.ts index 8ba8f3e1..5d0c64e6 100755 --- a/apps/cli/src/commands/deposit/erc20.ts +++ b/apps/cli/src/commands/deposit/erc20.ts @@ -1,22 +1,8 @@ import { Command } from "@commander-js/extra-typings"; -import chalk from "chalk"; -import ora from "ora"; -import { - type Address, - type PublicClient, - erc20Abi, - formatUnits, - getAddress, - isAddress, - isHex, - parseUnits, -} from "viem"; +import { type Address, getAddress, isAddress, isHex } from "viem"; +import { depositErc20, readErc20Token } from "../../api/deposit/erc20.js"; import { getProjectName } from "../../base.js"; -import { - erc20PortalAbi, - erc20PortalAddress, - testFungibleTokenAddress, -} from "../../contracts.js"; +import { testFungibleTokenAddress } from "../../contracts.js"; import { addressInput, bigintInput, @@ -24,55 +10,15 @@ import { } from "../../prompts.js"; import { connect, getDefaultSender } from "../../wallet.js"; import type { DepositCommandOpts } from "../deposit.js"; +import { reportDepositError } from "./error.js"; -type ERC20Token = { - address: Address; - name: string; - symbol: string; - decimals: number; -}; - -const readToken = async ( - publicClient: PublicClient, - address: Address, -): Promise => { - const args = { abi: erc20Abi, address }; - const symbol = await publicClient.readContract({ - ...args, - functionName: "symbol", - }); - const name = await publicClient.readContract({ - ...args, - functionName: "name", - }); - const decimals = await publicClient.readContract({ - ...args, - functionName: "decimals", - }); - return { - address, - name, - symbol, - decimals, - }; -}; - -const parseToken = async (options: { - testClient: PublicClient; - token?: string; -}): Promise => { - const { testClient } = options; - - const address = - options.token && isAddress(options.token) - ? getAddress(options.token) - : await addressInput({ - message: "Token address", - default: testFungibleTokenAddress, - }); - - return readToken(testClient, address); -}; +const parseTokenAddress = async (token?: string): Promise
=> + token && isAddress(token) + ? getAddress(token) + : addressInput({ + message: "Token address", + default: testFungibleTokenAddress, + }); export const createErc20Command = () => { return new Command<[], Record, DepositCommandOpts>("erc20") @@ -87,18 +33,16 @@ export const createErc20Command = () => { const projectName = getProjectName(command.optsWithGlobals()); // connect to anvil - const testClient = await connect(command.optsWithGlobals()); + const client = await connect(command.optsWithGlobals()); // the input sender, impersonated const account = from && isAddress(from) ? getAddress(from) - : await getDefaultSender(testClient); + : await getDefaultSender(client); - const token = await parseToken({ - testClient, - token: options.token, - }); + const tokenAddress = await parseTokenAddress(options.token); + const token = await readErc20Token(client, tokenAddress); // get dapp address from local node, or ask const application = await getInputApplicationAddress({ @@ -108,7 +52,7 @@ export const createErc20Command = () => { const { decimals, symbol } = token; const amount = amountStr - ? parseUnits(amountStr, decimals) + ? amountStr : await bigintInput({ message: `Amount (${symbol})`, decimals, @@ -118,64 +62,19 @@ export const createErc20Command = () => { ? options.execLayerData : "0x"; - // progress spinner - const progress = ora(); - - // check balance - const balance = await testClient.readContract({ - abi: erc20Abi, - address: token.address, - functionName: "balanceOf", - args: [account], - }); - if (balance < amount) { - progress.fail("Insufficient balance"); - return; - } - - // check allowance - const allowance = await testClient.readContract({ - abi: erc20Abi, - address: token.address, - functionName: "allowance", - args: [account, erc20PortalAddress], - }); - - // for messages - const amountLabel = `${chalk.cyan(formatUnits(amount, decimals))} ${symbol}`; - - // approve if needed - if (allowance < amount) { - progress.start(`Approving ${amountLabel}...`); - const { request } = await testClient.simulateContract({ - abi: erc20Abi, - account, - address: token.address, - functionName: "approve", - args: [erc20PortalAddress, amount], + try { + await depositErc20({ + amount, + application, + client, + execLayerData, + from: account, + progress: "default", + projectName, + token: token.address, }); - const hash = await testClient.writeContract(request); - await testClient.waitForTransactionReceipt({ hash }); - progress.succeed(`Approved ${amountLabel}`); + } catch (e: unknown) { + reportDepositError(e); } - - // simulate deposit call - const { request } = await testClient.simulateContract({ - abi: erc20PortalAbi, - account, - address: erc20PortalAddress, - functionName: "depositErc20Tokens", - args: [token.address, application, amount, execLayerData], - }); - - // send deposit - progress.start( - `Depositing ${amountLabel} to ${chalk.cyan(application)}...`, - ); - const hash = await testClient.writeContract(request); - await testClient.waitForTransactionReceipt({ hash }); - progress.succeed( - `Deposited ${amountLabel} to ${chalk.cyan(application)}`, - ); }); }; diff --git a/apps/cli/src/commands/deposit/erc721.ts b/apps/cli/src/commands/deposit/erc721.ts index 4aaaf7e0..362d8e98 100755 --- a/apps/cli/src/commands/deposit/erc721.ts +++ b/apps/cli/src/commands/deposit/erc721.ts @@ -1,23 +1,8 @@ import { Command } from "@commander-js/extra-typings"; -import chalk from "chalk"; -import ora from "ora"; -import { - type Address, - BaseError, - ContractFunctionRevertedError, - type PublicClient, - erc721Abi, - getAddress, - isAddress, - isHex, -} from "viem"; +import { type Address, getAddress, isAddress, isHex } from "viem"; +import { depositErc721, readErc721Token } from "../../api/deposit/erc721.js"; import { getProjectName } from "../../base.js"; -import { - erc721PortalAbi, - erc721PortalAddress, - testNonFungibleTokenAbi, - testNonFungibleTokenAddress, -} from "../../contracts.js"; +import { testNonFungibleTokenAddress } from "../../contracts.js"; import { addressInput, bigintInput, @@ -25,49 +10,15 @@ import { } from "../../prompts.js"; import { connect, getDefaultSender } from "../../wallet.js"; import type { DepositCommandOpts } from "../deposit.js"; +import { reportDepositError } from "./error.js"; -type ERC721Token = { - address: Address; - name: string; - symbol: string; -}; - -const readToken = async ( - publicClient: PublicClient, - address: Address, -): Promise => { - const args = { abi: erc721Abi, address }; - const symbol = await publicClient.readContract({ - ...args, - functionName: "symbol", - }); - const name = await publicClient.readContract({ - ...args, - functionName: "name", - }); - return { - address, - name, - symbol, - }; -}; - -const parseToken = async (options: { - testClient: PublicClient; - token?: string; -}): Promise => { - const { testClient } = options; - - const address = - options.token && isAddress(options.token) - ? getAddress(options.token) - : await addressInput({ - message: "Token address", - default: testNonFungibleTokenAddress, - }); - - return readToken(testClient, address); -}; +const parseTokenAddress = async (token?: string): Promise
=> + token && isAddress(token) + ? getAddress(token) + : addressInput({ + message: "Token address", + default: testNonFungibleTokenAddress, + }); export const createErc721Command = () => { return new Command<[], Record, DepositCommandOpts>("erc721") @@ -87,22 +38,20 @@ export const createErc721Command = () => { const projectName = getProjectName(command.optsWithGlobals()); // connect to anvil - const testClient = await connect(command.optsWithGlobals()); + const client = await connect(command.optsWithGlobals()); // the input sender, impersonated const account = from && isAddress(from) ? getAddress(from) - : await getDefaultSender(testClient); + : await getDefaultSender(client); - const token = await parseToken({ - testClient, - token: options.token, - }); - const tokenAbi = - token.address === testNonFungibleTokenAddress - ? testNonFungibleTokenAbi - : erc721Abi; + // read the token before asking for the application, so a wrong + // token address fails before the prompt + const token = await readErc721Token( + client, + await parseTokenAddress(options.token), + ); // get dapp address from local node, or ask const application = await getInputApplicationAddress({ @@ -110,8 +59,6 @@ export const createErc721Command = () => { projectName, }); - const { symbol } = token; - const baseLayerData = isHex(options.baseLayerData) ? options.baseLayerData : "0x"; @@ -119,87 +66,20 @@ export const createErc721Command = () => { ? options.execLayerData : "0x"; - // progress spinner - const progress = ora(); - - // check balance try { - const currentOwner = await testClient.readContract({ - abi: tokenAbi, - address: token.address, - args: [tokenId], - functionName: "ownerOf", - }); - - if (currentOwner !== account) { - progress.fail("Insufficient balance"); - return; - } - } catch (e: unknown) { - if (e instanceof BaseError) { - const revertError = e.walk( - (err) => err instanceof ContractFunctionRevertedError, - ); - if (revertError instanceof ContractFunctionRevertedError) { - const errorName = revertError.data?.errorName ?? ""; - if (errorName === "ERC721NonexistentToken") { - progress.fail(`Token ${tokenIdStr} does not exist`); - return; - } - } - progress.fail("Failed to check ownership"); - } - } - - // check allowance - const operator = await testClient.readContract({ - abi: tokenAbi, - address: token.address, - args: [tokenId], - functionName: "getApproved", - }); - - // for messages - const amountStr = `${chalk.cyan(tokenIdStr)} ${symbol}`; - - // approve if needed - if (operator !== erc721PortalAddress) { - progress.start(`Approving ${amountStr}...`); - const { request } = await testClient.simulateContract({ - abi: tokenAbi, - account, - address: token.address, - functionName: "approve", - args: [erc721PortalAddress, tokenId], - }); - const hash = await testClient.writeContract(request); - await testClient.waitForTransactionReceipt({ hash }); - progress.succeed(`Approved ${amountStr}`); - } - - // simulate deposit call - const { request } = await testClient.simulateContract({ - abi: erc721PortalAbi, - account, - address: erc721PortalAddress, - functionName: "depositErc721Token", - args: [ - token.address, + await depositErc721({ application, - tokenId, baseLayerData, + client, execLayerData, - ], - }); - - // send deposit - progress.start( - `Depositing ${amountStr} to ${chalk.cyan(application)}...`, - ); - const hash = await testClient.writeContract(request); - await testClient.waitForTransactionReceipt({ hash }); - progress.succeed( - `Deposited ${amountStr} to ${chalk.cyan(application)}`, - ); + from: account, + progress: "default", + projectName, + token: token.address, + tokenId, + }); + } catch (e: unknown) { + reportDepositError(e); + } }); }; diff --git a/apps/cli/src/commands/deposit/error.ts b/apps/cli/src/commands/deposit/error.ts new file mode 100644 index 00000000..0975a854 --- /dev/null +++ b/apps/cli/src/commands/deposit/error.ts @@ -0,0 +1,15 @@ +import ora from "ora"; +import { DepositError } from "../../api/deposit/common.js"; + +/** + * Report a deposit that could not be made because of the asset, the amount or + * the balance of the sender. Any other error is rethrown. + * @param e error thrown by a deposit + */ +export const reportDepositError = (e: unknown): void => { + if (e instanceof DepositError) { + ora().fail(e.message); + return; + } + throw e; +}; diff --git a/apps/cli/src/commands/deposit/ether.ts b/apps/cli/src/commands/deposit/ether.ts index ad23054d..6b3768c2 100755 --- a/apps/cli/src/commands/deposit/ether.ts +++ b/apps/cli/src/commands/deposit/ether.ts @@ -1,12 +1,11 @@ import { Command } from "@commander-js/extra-typings"; -import chalk from "chalk"; -import ora from "ora"; -import { formatUnits, getAddress, isAddress, isHex, parseUnits } from "viem"; +import { getAddress, isAddress, isHex } from "viem"; +import { depositEther } from "../../api/deposit/ether.js"; import { getProjectName } from "../../base.js"; -import { etherPortalAbi, etherPortalAddress } from "../../contracts.js"; import { bigintInput, getInputApplicationAddress } from "../../prompts.js"; import { connect, getDefaultSender } from "../../wallet.js"; import type { DepositCommandOpts } from "../deposit.js"; +import { reportDepositError } from "./error.js"; export const createEtherCommand = () => { return new Command<[], Record, DepositCommandOpts>("ether") @@ -20,13 +19,13 @@ export const createEtherCommand = () => { const projectName = getProjectName(command.optsWithGlobals()); // connect to anvil - const testClient = await connect(command.optsWithGlobals()); + const client = await connect(command.optsWithGlobals()); // the input sender, impersonated const account = from && isAddress(from) ? getAddress(from) - : await getDefaultSender(testClient); + : await getDefaultSender(client); // get dapp address from local node, or ask const application = await getInputApplicationAddress({ @@ -34,9 +33,9 @@ export const createEtherCommand = () => { projectName, }); - const { decimals, symbol } = testClient.chain.nativeCurrency; + const { decimals, symbol } = client.chain.nativeCurrency; const amount = amountStr - ? parseUnits(amountStr, decimals) + ? amountStr : await bigintInput({ message: `Amount (${symbol})`, decimals, @@ -46,38 +45,18 @@ export const createEtherCommand = () => { ? options.execLayerData : "0x"; - // progress spinner - const progress = ora(); - - // for messages - const amountLabel = `${chalk.cyan(formatUnits(amount, decimals))} ${symbol}`; - - // check balance - const balance = await testClient.getBalance({ - address: account, - }); - if (balance < amount) { - progress.fail("Insufficient balance"); - return; + try { + await depositEther({ + amount, + application, + client, + execLayerData, + from: account, + progress: "default", + projectName, + }); + } catch (e: unknown) { + reportDepositError(e); } - - const { request } = await testClient.simulateContract({ - abi: etherPortalAbi, - account, - address: etherPortalAddress, - args: [application, execLayerData], - functionName: "depositEther", - value: amount, - }); - - // send deposit - progress.start( - `Depositing ${amountLabel} to ${chalk.cyan(application)}...`, - ); - const hash = await testClient.writeContract(request); - await testClient.waitForTransactionReceipt({ hash }); - progress.succeed( - `Deposited ${amountLabel} to ${chalk.cyan(application)}`, - ); }); }; diff --git a/apps/cli/src/commands/doctor.ts b/apps/cli/src/commands/doctor.ts index c54c1d72..8bbc74b7 100755 --- a/apps/cli/src/commands/doctor.ts +++ b/apps/cli/src/commands/doctor.ts @@ -1,162 +1,30 @@ import { Command } from "@commander-js/extra-typings"; import chalk from "chalk"; -import { execa } from "execa"; -import ora, { type Ora } from "ora"; -import semver from "semver"; -import { DEFAULT_SDK_IMAGE, DEFAULT_SDK_VERSION } from "../config.js"; -import { cartesiMachine } from "../exec/index.js"; - -const MINIMUM_DOCKER_VERSION = "25.0.0"; // Replace with our minimum required Docker version -const MINIMUM_DOCKER_COMPOSE_VERSION = "2.24.0"; // Replace with our minimum required Docker Compose version -const MINIMUM_BUILDX_VERSION = "0.13.0"; // Replace with our minimum required Buildx version - -const checkDocker = async (progress: Ora): Promise => { - try { - progress.start("Checking Docker Engine version..."); - const { stdout: dockerVersion } = await execa("docker", [ - "version", - "--format", - "{{json .Client.Version}}", - ]); - - const v = semver.coerce(dockerVersion); - if (v !== null && !semver.gte(v, MINIMUM_DOCKER_VERSION)) { - throw new Error( - `Unsupported Docker version. Minimum required version is ${MINIMUM_DOCKER_VERSION}. Installed version is ${v}.`, - ); - } - progress.succeed(`Docker Engine ${chalk.cyan(v)}`); - } catch (e: unknown) { - if ( - e instanceof Error && - (e as NodeJS.ErrnoException).code === "ENOENT" - ) { - throw new Error("Docker not found"); - } - throw e; - } - - return true; -}; - -const checkCompose = async (progress: Ora): Promise => { - try { - progress.start("Checking Docker Compose version..."); - const { stdout: dockerComposeVersion } = await execa("docker", [ - "compose", - "version", - "--short", - ]); - - const v = semver.coerce(dockerComposeVersion); - if (v !== null && !semver.gte(v, MINIMUM_DOCKER_COMPOSE_VERSION)) { - throw new Error( - `Unsupported Docker Compose version. Minimum required version is ${MINIMUM_DOCKER_COMPOSE_VERSION}. Installed version is ${v}.`, - ); - } - progress.succeed(`Docker Compose ${chalk.cyan(dockerComposeVersion)}`); - } catch (e: unknown) { - if ( - e instanceof Error && - (e as Error & { exitCode?: number }).exitCode === 125 - ) { - throw new Error( - "Docker Compose is required but not installed or the command execution failed. Please refer to the Docker Compose documentation for installation instructions: https://docs.docker.com/compose/install/", - ); - } - throw e; - } - - return true; -}; - -const checkBuildx = async (progress: Ora): Promise => { - try { - progress.start("Checking Docker Buildx version..."); - const { stdout: buildxOutput } = await execa("docker", [ - "buildx", - "version", - ]); - - const v = semver.coerce(buildxOutput); - if (v !== null && !semver.gte(v, MINIMUM_BUILDX_VERSION)) { - throw new Error( - `Unsupported Docker Buildx version. Minimum required version is ${MINIMUM_BUILDX_VERSION}. Installed version is ${v}.`, - ); - } - progress.succeed(`Docker Buildx ${chalk.cyan(v)}`); - - progress.start("Checking Docker RISC-V support..."); - const { stdout: platformsOutput } = await execa("docker", [ - "buildx", - "ls", - "--format", - "{{.Platforms}}", - ]); - - const buildxPlatforms: string[] = platformsOutput - .split(",") - .map((platform) => platform.trim()); - - if (!buildxPlatforms.includes("linux/riscv64")) { - throw new Error( - "Your system does not support riscv64 architecture. Run `docker run --privileged --rm tonistiigi/binfmt:riscv` to enable riscv64 support.", - ); - } - progress.succeed( - `Docker RISC-V support ${chalk.cyan("linux/riscv64")}`, - ); - } catch (e: unknown) { - if ( - e instanceof Error && - (e as Error & { exitCode?: number }).exitCode === 125 - ) { - throw new Error( - "Docker Buildx is required but not installed. Please refer to the Docker Desktop documentation for installation instructions: https://docs.docker.com/desktop/", - ); - } - throw e; - } - - return true; -}; - -const checkCartesiMachine = async (progress: Ora): Promise => { - progress.start("Checking Cartesi Machine version..."); - - // doctor does not read cartesi.toml, so check against the default sdk image. the host binary - // still takes precedence, which is the install most likely to be out of date - const v = await cartesiMachine.version({ - image: `${DEFAULT_SDK_IMAGE}:${DEFAULT_SDK_VERSION}`, - }); - - if (v === null) { - throw new Error( - "Could not determine the Cartesi Machine version. Check that Docker is running.", - ); - } - if (!semver.satisfies(v.format(), cartesiMachine.requiredVersion)) { - throw new Error( - `Unsupported Cartesi Machine version. Required version is ${cartesiMachine.requiredVersion.raw}. Installed version is ${v.format()}.`, - ); - } - progress.succeed(`Cartesi Machine ${chalk.cyan(v.format())}`); - - return true; -}; +import ora from "ora"; +import { doctor } from "../api/doctor.js"; export const createDoctorCommand = () => { return new Command("doctor").action(async () => { - const progress = ora(); - try { - await checkDocker(progress); - await checkCompose(progress); - await checkBuildx(progress); - await checkCartesiMachine(progress); - progress.succeed("Your system is ready."); - } catch (e: unknown) { - progress.fail((e as Error).message); + const progress = ora("Checking system requirements...").start(); + const { checks, ok } = await doctor(); + progress.stop(); + + // a skipped check isn't shown, the failure of its requirement says it all + for (const check of checks) { + if (check.status === "ok") { + progress.succeed( + check.detail + ? `${check.name} ${chalk.cyan(check.detail)}` + : check.name, + ); + } else if (check.status === "failed") { + progress.fail(check.message ?? `${check.name} not found`); + } + } + + if (!ok) { process.exit(1); } + progress.succeed("Your system is ready."); }); }; diff --git a/apps/cli/src/commands/foreclose.ts b/apps/cli/src/commands/foreclose.ts index 8725fabc..737b4c02 100644 --- a/apps/cli/src/commands/foreclose.ts +++ b/apps/cli/src/commands/foreclose.ts @@ -1,92 +1,8 @@ import { Command } from "@commander-js/extra-typings"; import chalk from "chalk"; -import { type Address, isAddressEqual, zeroAddress } from "viem"; -import { privateKeyToAccount } from "viem/accounts"; -import { getCartesiEnvironmentVariables, getProjectName } from "../base.js"; -import { - getHostSigner, - getNodeSigner, - handleNodeCommandError, - type HostSigner, - hostSignerEnv, - type NodeSigner, - runNodeCommand, - transactionArgs, -} from "../exec/node-container.js"; -import { getNodeWithdrawalConfig } from "../exec/rollups.js"; -import { addRecoveryOptions, resolveNodeApplication } from "../node.js"; -import { findMnemonicAccountIndex } from "../wallet.js"; - -/** - * Work out how to sign as the guardian, the only account allowed to - * foreclose. A signer given for the command takes precedence over the node's. - * cartesi-rollups-cli signs with whatever its environment configures, so for - * a mnemonic the guardian's account index is looked up, unless one is given. - * A private key has no index to choose. - * @returns the account index and environment to sign with, and a warning to show, if any - */ -export const resolveForecloseSigner = (options: { - accountIndex?: number; - guardian: Address; - host?: HostSigner; - node?: NodeSigner; -}): { - accountIndex?: number; - env?: Record; - warning?: string; -} => { - const { accountIndex, guardian, host, node } = options; - - if (isAddressEqual(guardian, zeroAddress)) { - throw new Error( - "The application was deployed without a withdrawal config and cannot be foreclosed", - ); - } - - // the signer given for the command is passed down to cartesi-rollups-cli - const env = host ? hostSignerEnv(host) : undefined; - const ignoredIndex = - accountIndex === undefined - ? {} - : { - warning: - "--account-index is ignored when signing with a private key", - }; - - if (host?.kind === "private_key") { - const { address } = privateKeyToAccount(host.privateKey); - if (!isAddressEqual(address, guardian)) { - throw new Error( - `The private key's address ${address} isn't the guardian ${guardian}`, - ); - } - return { ...ignoredIndex, env }; - } - - // the node's private key is never read, so it can't be checked here - const signer = host ?? node; - if (!signer) { - throw new Error("No signer to foreclose with"); - } - if (signer.kind === "private_key") { - return ignoredIndex; - } - - if (accountIndex !== undefined) { - return { accountIndex, env }; - } - - const index = findMnemonicAccountIndex({ - address: guardian, - mnemonic: signer.mnemonic, - }); - if (index === undefined) { - throw new Error( - `Guardian ${guardian} isn't one of the first 20 accounts of the mnemonic in use. If it belongs to another mnemonic, set CARTESI_AUTH_MNEMONIC; if its index is higher, pass --account-index; if it's a raw private key, set CARTESI_AUTH_PRIVATE_KEY`, - ); - } - return { accountIndex: index, env }; -}; +import { foreclose } from "../api/foreclose.js"; +import { handleNodeCommandError } from "../exec/node-container.js"; +import { addRecoveryOptions } from "./recovery.js"; export const createForecloseCommand = () => { return addRecoveryOptions( @@ -106,39 +22,11 @@ Set CARTESI_AUTH_KIND to mnemonic or private_key when both are set.`, .configureHelp({ showGlobalOptions: true }), "index of the guardian in the mnemonic (default: looked up from the application guardian; ignored for private-key signers)", ).action(async (options) => { - const projectName = getProjectName(options); - const application = await resolveNodeApplication({ - application: options.application, - projectName, - }); - - const { guardian } = await getNodeWithdrawalConfig({ - application, - projectName, - }); - // the node signer is only needed without a signer for the command - const host = getHostSigner(getCartesiEnvironmentVariables()); - const { accountIndex, env, warning } = resolveForecloseSigner({ - accountIndex: options.accountIndex, - guardian, - host, - node: host ? undefined : await getNodeSigner({ projectName }), - }); - if (warning) { - console.warn(chalk.yellow(warning)); - } - try { - await runNodeCommand({ - accountIndex, - command: [ - "cartesi-rollups-cli", - "foreclose", - application, - ...transactionArgs(options), - ], - env, - projectName, + await foreclose({ + ...options, + onNotice: ({ message }) => console.warn(chalk.yellow(message)), + stream: true, }); } catch (error: unknown) { handleNodeCommandError(error); diff --git a/apps/cli/src/commands/hash.ts b/apps/cli/src/commands/hash.ts index 54ccb239..2752dc68 100755 --- a/apps/cli/src/commands/hash.ts +++ b/apps/cli/src/commands/hash.ts @@ -1,6 +1,6 @@ import { Command } from "@commander-js/extra-typings"; import chalk from "chalk"; -import { getMachineHash } from "../base.js"; +import { hash } from "../api/hash.js"; export const createHashCommand = () => { return new Command("hash") @@ -9,14 +9,14 @@ export const createHashCommand = () => { ) .option("--json", "Format output as json.") .action(async ({ json }, command) => { - const hash = await getMachineHash(); - if (hash) { + const machineHash = await hash(); + if (machineHash) { if (!json) { console.log( - `${chalk.green("?")} Cartesi machine templateHash ${chalk.cyan(hash)}\n`, + `${chalk.green("?")} Cartesi machine templateHash ${chalk.cyan(machineHash)}\n`, ); } else { - process.stdout.write(JSON.stringify({ hash })); + process.stdout.write(JSON.stringify({ hash: machineHash })); } } else { command.error( diff --git a/apps/cli/src/commands/logs.ts b/apps/cli/src/commands/logs.ts index 0bb98c39..8f3b498b 100644 --- a/apps/cli/src/commands/logs.ts +++ b/apps/cli/src/commands/logs.ts @@ -1,79 +1,5 @@ import { Command } from "@commander-js/extra-typings"; -import { execa } from "execa"; -import { getProjectName } from "../base.js"; -import { isPrtNodeService } from "../compose/prt-node.js"; - -/** The node's compose service, shown by default and first. */ -export const NODE_SERVICE = "rollups_node"; - -/** - * The services of a running environment, as compose lists them; an exited - * container is still listed, so its last logs can be read. - */ -export const listServices = async (projectName: string): Promise => { - const { stdout } = await execa("docker", [ - "compose", - "--project-name", - projectName, - "ps", - "--services", - "--all", - ]); - return stdout - .split("\n") - .map((line) => line.trim()) - .filter((line) => line.length > 0); -}; - -/** - * The services to show: the ones named, checked against the environment, or - * the node followed by every PRT node. - * @param services the environment's services, from `listServices` - * @param requested the services named on the command line - * @throws when the node isn't there, or a named service isn't - */ -export const selectLogServices = ( - services: string[], - requested: string[], -): string[] => { - if (requested.length === 0) { - if (!services.includes(NODE_SERVICE)) { - throw new Error(`service ${NODE_SERVICE} not found`); - } - return [NODE_SERVICE, ...services.filter(isPrtNodeService)]; - } - // compose shows nothing for an unknown service, without an error - const unknown = requested.filter((service) => !services.includes(service)); - if (unknown.length > 0) { - throw new Error( - `service ${unknown.join(", ")} not found; the environment has ${services.join(", ")}`, - ); - } - return requested; -}; - -/** - * The `docker compose logs` arguments. One service is shown as it is, like - * `docker container logs`; more than one get compose's per-service prefix, - * which tells the node's lines from the PRT nodes'. - */ -export const buildLogsArgs = (options: { - follow?: boolean; - projectName: string; - services: string[]; - since?: string; - tail?: string; - until?: string; -}): string[] => { - const { follow, projectName, services, since, tail, until } = options; - const args = ["compose", "--project-name", projectName, "logs"]; - if (follow) args.push("--follow"); - if (since) args.push("--since", since); - if (tail) args.push("--tail", tail); - if (until) args.push("--until", until); - if (services.length === 1) args.push("--no-log-prefix"); - return [...args, ...services]; -}; +import { logs } from "../api/logs.js"; export const createLogsCommand = () => { return new Command("logs") @@ -104,24 +30,16 @@ export const createLogsCommand = () => { ) .configureHelp({ showGlobalOptions: true }) .action(async (requested, options) => { - const { follow, since, tail, until } = options; - const projectName = getProjectName(options); - const services = selectLogServices( - await listServices(projectName), - requested, - ); + const { follow, projectName, since, tail, until } = options; - await execa( - "docker", - buildLogsArgs({ - follow, - projectName, - services, - since, - tail, - until, - }), - { stdio: "inherit" }, - ); + await logs({ + follow, + projectName, + services: requested, + since, + stream: true, + tail, + until, + }); }); }; diff --git a/apps/cli/src/commands/recovery.ts b/apps/cli/src/commands/recovery.ts new file mode 100644 index 00000000..60ba5474 --- /dev/null +++ b/apps/cli/src/commands/recovery.ts @@ -0,0 +1,43 @@ +import { + type Command, + Option, + type OptionValues, +} from "@commander-js/extra-typings"; +import { parseAccountIndex } from "../base.js"; + +/** + * Add the options shared by the fund recovery commands: the application and + * project, the signer account index, and the transaction flags forwarded to + * cartesi-rollups-cli + * @param accountIndexDescription what the account index selects for this command + */ +export const addRecoveryOptions = < + Args extends unknown[], + Opts extends OptionValues, + GlobalOpts extends OptionValues, +>( + command: Command, + accountIndexDescription: string, +) => + command + .option("--application
", "application address") + .option( + "--project-name ", + "name of project (used by docker compose and cartesi-rollups-node)", + ) + .addOption( + new Option( + "--account-index ", + accountIndexDescription, + ).argParser(parseAccountIndex), + ) + .option("-y, --yes", "skip the confirmation prompt") + .option("--json", "print the result as JSON") + .option( + "--no-wait", + "return after broadcast without waiting for the receipt", + ) + .option( + "--wait-timeout ", + "maximum time to wait for the receipt (e.g. 30s, 5m)", + ); diff --git a/apps/cli/src/commands/refund.ts b/apps/cli/src/commands/refund.ts index 8af854e0..2cfbd76c 100644 --- a/apps/cli/src/commands/refund.ts +++ b/apps/cli/src/commands/refund.ts @@ -1,56 +1,8 @@ import { Command } from "@commander-js/extra-typings"; -import chalk from "chalk"; -import fs from "fs-extra"; -import { type Address, type Hex, isHex } from "viem"; -import { getProjectName, parseInputIndex } from "../base.js"; -import { - handleNodeCommandError, - removeNodePath, - runNodeCommand, - transactionArgs, - writeNodeTempFile, -} from "../exec/node-container.js"; -import { getNodeInput } from "../exec/rollups.js"; -import { addRecoveryOptions, resolveNodeApplication } from "../node.js"; - -/** - * Get the complete InputAdded.input bytes of the deposit to refund, from a - * file or from the node - */ -export const getInputData = async (options: { - application: Address; - inputFile?: string; - inputIndex: bigint; - io?: { getNodeInput: typeof getNodeInput }; - projectName: string; -}): Promise => { - const { - application, - inputFile, - inputIndex, - io = { getNodeInput }, - projectName, - } = options; - - if (inputFile) { - const data = (await fs.readFile(inputFile, "utf-8")).trim(); - if (!isHex(data) || data.length <= 2) { - throw new Error( - `${inputFile} must contain the 0x-prefixed hexadecimal input bytes`, - ); - } - return data; - } - - try { - return await io.getNodeInput({ application, inputIndex, projectName }); - } catch (error: unknown) { - throw new Error( - `Input ${inputIndex} not found in the node, use ${chalk.cyan("--input-file")} with the InputAdded.input bytes`, - { cause: error }, - ); - } -}; +import { refund } from "../api/refund.js"; +import { parseInputIndex } from "../base.js"; +import { handleNodeCommandError } from "../exec/node-container.js"; +import { addRecoveryOptions } from "./recovery.js"; export const createRefundCommand = () => { return addRecoveryOptions( @@ -70,42 +22,10 @@ export const createRefundCommand = () => { ), "index of the account in the node mnemonic paying for gas", ).action(async (inputIndex, options) => { - const projectName = getProjectName(options); - const application = await resolveNodeApplication({ - application: options.application, - projectName, - }); - - const data = await getInputData({ - application, - inputFile: options.inputFile, - inputIndex, - projectName, - }); - - // the node tool reads the input bytes from a file in its container - const path = await writeNodeTempFile({ - content: `${data}\n`, - projectName, - }); try { - await runNodeCommand({ - accountIndex: options.accountIndex, - command: [ - "cartesi-rollups-cli", - "refund", - application, - inputIndex.toString(), - "--input-file", - path, - ...transactionArgs(options), - ], - projectName, - }); + await refund({ ...options, inputIndex, stream: true }); } catch (error: unknown) { handleNodeCommandError(error); - } finally { - await removeNodePath({ path, projectName }); } }); }; diff --git a/apps/cli/src/commands/run.ts b/apps/cli/src/commands/run.ts index c98ff183..30a1a68e 100755 --- a/apps/cli/src/commands/run.ts +++ b/apps/cli/src/commands/run.ts @@ -1,73 +1,36 @@ -import { - Command, - type CommandUnknownOpts, - Option, -} from "@commander-js/extra-typings"; +import { Command, Option } from "@commander-js/extra-typings"; import { AbortPromptError, ExitPromptError } from "@inquirer/core"; import chalk from "chalk"; import { ExecaError } from "execa"; -import getPort, { portNumbers } from "get-port"; -import fs from "node:fs"; import ora from "ora"; -import { - type Address, - createPublicClient, - type Hex, - http, - numberToHex, -} from "viem"; -import { - getApplicationConfig, - getCartesiEnvironmentVariables, - getContextPath, - getMachineHash, - getProjectName, -} from "../base.js"; -import { - nodeAllowedEnvironmentVariables, - nodePrtAuthVariables, -} from "../compose/node.js"; -import { - DEFAULT_SDK_VERSION, - PREFERRED_PORT, - type WithdrawalConfig, -} from "../config.js"; +import { build } from "../api/build.js"; +import { logs } from "../api/logs.js"; +import { run, type RunNotice, type RunResult } from "../api/run.js"; +import { nodeAllowedEnvironmentVariables } from "../compose/node.js"; +import { DEFAULT_SDK_VERSION } from "../config.js"; import { AVAILABLE_SERVICES, - deployApplication, - type EnvironmentOptions, - host, - removeApplication, getDeployments, type RollupsDeployment, - startEnvironment, - startPrtNodes, - stopEnvironment, - stopPrtNodes, TERMINAL_APPLICATION_STATUSES, - waitHealthyEnvironment, } from "../exec/rollups.js"; import { keySelect } from "../prompts.js"; -import { - checkPrtNodes, - describePrtNode, - describeReference, - readerModeChanged, - type ResolvedPrt, - resolvePrtNodes, - runnableNodes, - sentriesOf, -} from "../prt.js"; -import type { ForkConfig } from "../types/chain.js"; -import { assertForkConfig } from "../validations.js"; -import { connect } from "../wallet.js"; -import { DEVNET_GUARDIAN, getWithdrawalConfig } from "../withdrawal.js"; +import { printBuildResult } from "./build.js"; const commaSeparatedList = (value: string) => value.split(","); /** How often the interactive shell re-reads the application status. */ const STATUS_POLL_INTERVAL = 5_000; +/** Print configuration the run reported, as a warning or a dim note. */ +const reportNotice = ({ level, message }: RunNotice) => { + if (level === "warning") { + console.warn(chalk.yellow(`WARNING: ${message}`)); + } else { + console.log(chalk.dim(message)); + } +}; + /** * Report an application that is no longer in the `OK` state. The node stops * processing inputs on a terminal status while still accepting them on-chain, @@ -97,40 +60,14 @@ const reportApplicationStatus = (deployment: RollupsDeployment) => { }; const shell = async (options: { - build?: CommandUnknownOpts; - deployment?: RollupsDeployment; - environment: EnvironmentOptions; - epochLength: number; - log?: CommandUnknownOpts; - projectName: string; - prt?: boolean; - salt: number; - sdk: string; - /** the PRT node services running for the deployment */ - prtServices: string[]; - /** the [prt] setup the environment started with */ - prtConfig?: ResolvedPrt; - resolveWithdrawalConfig: () => WithdrawalConfig | undefined; - resolvePrt: () => ResolvedPrt | undefined; - claimStagingPeriod: number; + config: string[]; + node: RunResult; + verbose: boolean; }) => { - const { - build, - environment, - epochLength, - log, - projectName, - prt, - sdk, - resolveWithdrawalConfig, - resolvePrt, - claimStagingPeriod, - } = options; + const { config, node, verbose } = options; + const { projectName } = node; - let lastDeployment = options.deployment; - let salt = options.salt; - let prtServices = options.prtServices; - let lastStatus = lastDeployment?.status; + let lastStatus = node.deployment?.status; let pendingReport: RollupsDeployment | undefined; /** @@ -139,7 +76,7 @@ const shell = async (options: { * here -- the caller aborts the prompt and reports once it has closed. */ const pollStatus = async (abort: () => void) => { - const address = lastDeployment?.address; + const address = node.deployment?.address; if (!address) { return; } @@ -184,12 +121,11 @@ const shell = async (options: { switch (option) { case "l": { try { - await log?.parseAsync( - ["--project-name", projectName, "--follow"], - { - from: "user", - }, - ); + await logs({ + follow: true, + projectName, + stream: true, + }); } catch (error: unknown) { if (error instanceof ExecaError) { // just continue gracefully @@ -202,59 +138,22 @@ const shell = async (options: { break; } case "b": { - // the PRT nodes read the machine the build replaces, and - // claim for the application the redeploy removes - await stopPrtNodes({ - projectName, - services: prtServices, - }); - prtServices = []; - - // build - await build?.parseAsync([], { from: "user" }); + // the PRT nodes read the machine the build replaces + await node.stopPrtNodes(); + + // build, showing what `cartesi build` shows + printBuildResult( + await build({ + config, + progress: verbose ? "verbose" : "default", + }), + ); - // redeploy - const hash = await getMachineHash({ sdk }); - if (hash) { - // the accounts drive may have moved with the rebuild, - // resolved before undeploying in case it is now invalid - const withdrawalConfig = resolveWithdrawalConfig(); - // a PRT redeploy creates a new consensus, with the - // sentries as they are in the config now. The node's - // mode can't change: it is fixed in its database - const resolved = resolvePrt(); - const moved = readerModeChanged( - options.prtConfig, - resolved, - ); - if (moved !== undefined) { - console.warn(chalk.yellow(`WARNING: ${moved}`)); - } - const prtConfig = - moved === undefined ? resolved : options.prtConfig; - reportPrtWarnings(prtConfig, claimStagingPeriod); - await fundPrtNodes({ environment, prtConfig }); - if (lastDeployment) { - await undeploy({ projectName }); - } - lastDeployment = await deploy({ - consensus: lastDeployment?.consensus, - epochLength, - hash, - projectName, - prt, - prtConfig, - salt: numberToHex(salt++, { size: 32 }), - withdrawalConfig, - claimStagingPeriod, - }); - lastStatus = lastDeployment?.status; + // redeploy, with the PRT nodes of the configuration now + const deployment = await node.deploy(); + if (deployment) { + lastStatus = deployment.status; pendingReport = undefined; - prtServices = await runPrtNodes({ - application: lastDeployment.address, - environment, - prtConfig, - }); } break; @@ -279,199 +178,6 @@ const shell = async (options: { } }; -const undeploy = async (options: { projectName: string }) => { - const { projectName } = options; - const progress = ora(`${chalk.cyan(projectName)} undeploying...`).start(); - await removeApplication({ - application: projectName, - force: true, - projectName, - }); - progress.succeed(`${chalk.cyan(projectName)} undeployed`); -}; - -/** - * Warn about [prt] settings that are valid but have no effect. - */ -const reportPrtWarnings = ( - prtConfig: ResolvedPrt | undefined, - claimStagingPeriod: number, -) => { - for (const warning of prtConfig?.warnings ?? []) { - console.warn(chalk.yellow(`WARNING: ${warning}`)); - } - if ( - prtConfig && - sentriesOf(prtConfig).length > 0 && - claimStagingPeriod === 0 - ) { - console.warn( - chalk.yellow( - "WARNING: with --claim-staging-period 0 a staged claim is accepted at once, so the sentries have no effect", - ), - ); - } -}; - -/** - * Funds the pool accounts and checks the other PRT nodes have ETH, once anvil - * is up and before the deploy they claim for. - */ -const fundPrtNodes = async (options: { - environment: EnvironmentOptions; - prtConfig?: ResolvedPrt; -}) => { - const { environment, prtConfig } = options; - if (!prtConfig || runnableNodes(prtConfig).length === 0) { - return; - } - const client = await connect({ - rpcUrl: `${host}:${environment.port}/anvil`, - }); - await checkPrtNodes(client, prtConfig); -}; - -/** - * Starts the PRT nodes the CLI runs, for the deployed application, then prints - * the rollups-node's line, the manager and every [prt.nodes] entry in file - * order: a check for each one running, a note for each one appointed only. - * @returns the services started - */ -const runPrtNodes = async (options: { - application: Address; - environment: EnvironmentOptions; - prtConfig?: ResolvedPrt; -}): Promise => { - const { application, environment, prtConfig } = options; - if ( - !prtConfig || - (prtConfig.nodes.length === 0 && - prtConfig.reference.label === undefined) - ) { - return []; - } - - const nodes = runnableNodes(prtConfig); - const progress = ora(); - let services: string[] = []; - if (nodes.length > 0) { - progress.start( - `starting ${nodes.length === 1 ? "the PRT node" : `${nodes.length} PRT nodes`}...`, - ); - try { - services = await startPrtNodes({ - ...environment, - application, - imageTag: environment.runtimeVersion, - nodes: prtConfig.nodes, - }); - progress.stop(); - } catch (error: unknown) { - progress.fail("the PRT nodes failed to start"); - throw error; - } - } - - // log-symbols' blue info mark is hard to read on a dark terminal - const note = (text: string) => - progress.stopAndPersist({ symbol: chalk.cyan("ℹ"), text }); - if (prtConfig.reference.claim) { - note(describeReference(prtConfig)); - } else { - progress.warn(describeReference(prtConfig)); - } - if (prtConfig.sentryManager === undefined) { - progress.warn("sentry manager none (the sentries can't be rotated)"); - } else { - note(`sentry manager ${prtConfig.sentryManager}`); - } - for (const node of prtConfig.nodes) { - if (node.type === undefined) { - note(describePrtNode(node)); - } else { - progress.succeed(describePrtNode(node)); - } - } - return services; -}; - -const deploy = async (options: { - consensus?: Address; - epochLength: number; - hash: Hex; - projectName: string; - prt?: boolean; - prtConfig?: ResolvedPrt; - salt: Hex; - withdrawalConfig?: WithdrawalConfig; - claimStagingPeriod: number; -}) => { - const { - consensus, - epochLength, - hash, - projectName, - prt, - prtConfig, - salt, - withdrawalConfig, - claimStagingPeriod, - } = options; - - // deploy application to node (onchain and offchain) - const progress = ora( - `deploying ${chalk.cyan(hash)} as ${chalk.cyan(projectName)}`, - ); - - const application = await deployApplication({ - consensus, - epochLength, - name: projectName, - projectName, - prt, - salt, - sentries: - prtConfig && sentriesOf(prtConfig).map(({ address }) => address), - sentryManager: prtConfig?.sentryManager, - snapshotPath: "/var/lib/cartesi-rollups-node/snapshots/image", - withdrawalConfig, - claimStagingPeriod, - }); - progress.succeed( - `${chalk.cyan(projectName)} machine hash is ${chalk.cyan(hash)}`, - ); - progress.succeed( - `${chalk.cyan(projectName)} contract deployed at ${chalk.cyan(application.address)}`, - ); - return application; -}; - -const configureFork = async (options: { - forkUrl?: string; - forkBlockNumber?: number; -}): Promise => { - if (!options.forkUrl) { - return undefined; - } - - const url = options.forkUrl; - - // create a client to upstream so we can query it - const client = createPublicClient({ - transport: http(url), - }); - - // use explicit fork-block-number or query from upstream - const blockNumber = options.forkBlockNumber - ? BigInt(options.forkBlockNumber) - : await client.getBlockNumber(); - - // need to query fork chainId if forkUrl is specified - const chainId = await client.getChainId(); - - return { blockNumber, chainId, url }; -}; - export const createRunCommand = () => { return new Command("run") .description("Run a local cartesi node for the application.") @@ -564,25 +270,27 @@ export const createRunCommand = () => { [], ) .option("-v, --verbose", "verbose output", false) - .action(async (options, program) => { + .action(async (options) => { const { prt, blockTime, + config, cpus, defaultBlock, dryRun, epochLength, + forkBlockNumber, + forkUrl, memory, + port, + projectName, runtimeVersion, services, verbose, listSupportedVariables, claimStagingPeriod, - config: configFiles, } = options; - const progress = ora(); - if (listSupportedVariables) { const allowedVarsByService = { rollupsNode: nodeAllowedEnvironmentVariables, @@ -603,152 +311,40 @@ export const createRunCommand = () => { ); } - // project name explicitly defined or the current directory name - const projectName = getProjectName(options); - - // get application configuration (e.g. use withdrawal config if present) - const applicationConfig = getApplicationConfig(configFiles); - - // [prt] is parsed either way, so a mistake in it fails early, but - // the node takes sentries only on a PRT deploy. Read again on a - // rebuild, like the withdrawal config. - const resolvePrt = () => { - const config = getApplicationConfig(configFiles); - return prt && config.prt - ? resolvePrtNodes(config.prt, { - guardian: - config.withdrawal?.guardian ?? DEVNET_GUARDIAN, - }) - : undefined; - }; - if (applicationConfig.prt && !prt) { - console.log( - chalk.dim("[prt] in cartesi.toml is ignored without --prt"), - ); - } - - // fail before starting the environment if [prt] can't be resolved - const prtConfig = resolvePrt(); - reportPrtWarnings(prtConfig, claimStagingPeriod); - - // in reader mode the node has no PRT signer - const claimSubmission = prtConfig?.reference.claim ?? true; - if (!claimSubmission) { - const hostVars = getCartesiEnvironmentVariables(); - const prtAuth = nodePrtAuthVariables.filter( - (name) => hostVars[name] !== undefined, - ); - if (prtAuth.length > 0) { - console.warn( - chalk.yellow( - `WARNING: ${prtAuth.join(", ")} ${prtAuth.length === 1 ? "is" : "are"} set, but [prt.nodes.${prtConfig?.reference.label}] has claim = false, so the rollups-node runs in reader mode with no PRT signer and the value is dropped`, - ), - ); - } - } - - // resolve port number, using the first free port in a range, unless explicitly set - const port = - options.port || - (await getPort({ - port: portNumbers(PREFERRED_PORT, PREFERRED_PORT + 10), - })); - - // configure optional anvil fork - const forkConfig = await configureFork(options); - - if (forkConfig) { - await assertForkConfig(forkConfig, { includePRT: prt }); - } - - // emergency withdrawal configuration, derived from the accounts drive of the built - // machine. The configuration is read again, as a rebuild may have changed it. - const imagePath = getContextPath("image"); - const resolveWithdrawalConfig = () => - getWithdrawalConfig( - getApplicationConfig(configFiles), - imagePath, - { - fork: forkConfig !== undefined, - }, - ); - - // fail before starting the environment if it can't be derived - const withdrawalConfig = fs.existsSync(imagePath) - ? resolveWithdrawalConfig() - : undefined; - // if TTY is not attached, run on foreground (not detached) - const detach = process.stdin.isTTY; + const detach = !!process.stdin.isTTY; - const environment: EnvironmentOptions = { + const node = await run({ blockTime, + claimStagingPeriod, + config, cpus, defaultBlock, - forkConfig, + detach, + dryRun, + epochLength, + forkBlockNumber, + forkUrl, memory, + onNotice: reportNotice, port, + progress: verbose ? "verbose" : "default", projectName, prt, - claimSubmission, runtimeVersion, services, verbose, - }; - - // run compose environment (detached) - const { cmd, config } = await startEnvironment({ - ...environment, - detach, - dryRun, }); - // host address - const address = `${host}:${port}`; - - if (dryRun && config) { + if (dryRun) { // just show the docker compose configuration and quit - process.stdout.write(config); + if (node.config) { + process.stdout.write(node.config); + } return; } - progress.succeed( - `${chalk.cyan(projectName)} starting at ${chalk.cyan(`${address}`)}`, - ); - - // wait for the environment to be healthy - await waitHealthyEnvironment({ - name: projectName, - port, - projectName, - services, - }); - - // deploy the application - let deployment: RollupsDeployment | undefined; - let prtServices: string[] = []; - let salt = 0; - const hash = await getMachineHash({ - sdk: applicationConfig.sdk, - }); - if (hash) { - await fundPrtNodes({ environment, prtConfig }); - deployment = await deploy({ - epochLength, - hash, - projectName, - prt, - prtConfig, - salt: numberToHex(salt++, { size: 32 }), - claimStagingPeriod, - withdrawalConfig, - }); - prtServices = await runPrtNodes({ - application: deployment.address, - environment, - prtConfig, - }); - } else { + if (!node.deployment) { console.warn( chalk.yellow( "machine snapshot not found, waiting for build", @@ -757,10 +353,12 @@ export const createRunCommand = () => { } const shutdown = async () => { - progress.start(`${chalk.cyan(projectName)} stopping...`); + const progress = ora().start( + `${chalk.cyan(node.projectName)} stopping...`, + ); try { - await stopEnvironment({ projectName }); - progress.succeed(`${chalk.cyan(projectName)} stopped`); + await node.stop(); + progress.succeed(`${chalk.cyan(node.projectName)} stopped`); } catch (e: unknown) { progress.fail( e instanceof Error ? e.message : "Unknown error", @@ -774,34 +372,13 @@ export const createRunCommand = () => { process.on("SIGINT", () => {}); process.on("SIGTERM", () => {}); - const log = program.parent?.commands.find( - (c) => c.name() === "logs", - ); - const build = program.parent?.commands.find( - (c) => c.name() === "build", - ); - await shell({ - build, - deployment, - environment, - epochLength, - log, - projectName, - prt, - salt, - sdk: applicationConfig.sdk, - prtServices, - prtConfig, - claimStagingPeriod, - resolveWithdrawalConfig, - resolvePrt, - }); + await shell({ config, node, verbose }); await shutdown(); } else { process.on("SIGINT", shutdown); process.on("SIGTERM", shutdown); try { - await cmd; + await node.cmd; } catch (error: unknown) { if (error instanceof ExecaError) { // just continue gracefully diff --git a/apps/cli/src/commands/send.ts b/apps/cli/src/commands/send.ts index debb653e..05a6970e 100755 --- a/apps/cli/src/commands/send.ts +++ b/apps/cli/src/commands/send.ts @@ -1,115 +1,11 @@ import { Command, Option } from "@commander-js/extra-typings"; import ora from "ora"; -import { - encodeAbiParameters, - encodePacked, - getAddress, - isAddress, - isHex, - parseAbiParameters, - stringToHex, -} from "viem"; +import { getAddress, isAddress } from "viem"; +import { encodeInput, send } from "../api/send.js"; import { getProjectName } from "../base.js"; -import { inputBoxAbi, inputBoxAddress } from "../contracts.js"; import { bytesInput, getInputApplicationAddress } from "../prompts.js"; import { connect, getDefaultSender } from "../wallet.js"; -const getInput = async ( - input: string | undefined, - options: { - encoding?: "abi" | "abi-packed" | "hex" | "string"; - abiParams?: string; - }, -): Promise<`0x${string}` | undefined> => { - const { encoding } = options; - if (input) { - if (encoding === "hex") { - // validate if is a hex value - if (!isHex(input)) { - throw new Error("input encoded as hex must start with 0x"); - } - return input; - } - if (encoding === "string") { - // encode UTF-8 string as hex - return stringToHex(input); - } - if (encoding === "abi" || encoding === "abi-packed") { - const abiParams = options.abiParams; - if (!abiParams) { - throw new Error("Undefined input-abi-params"); - } - const abiParameters = parseAbiParameters(abiParams); - // TODO: decode values - const values = input.split(",").map((v, index) => { - if (index >= abiParameters.length) { - throw new Error( - `Too many values, expected ${abiParameters.length} values based on --input-abi-params '${abiParams}', parsing value at index ${index} from input '${input}'`, - ); - } - const param = abiParameters[index]; - switch (param.type) { - case "string": - return v; - case "bool": - if (v === "true") return true; - if (v === "false") return false; - throw new Error(`Invalid boolean value: ${v}`); - case "uint": - case "uint8": - case "uint16": - case "uint32": - case "uint64": - case "uint128": - case "uint256": - case "int": - case "int8": - case "int16": - case "int32": - case "int64": - case "int128": - case "int256": - try { - return BigInt(v); - } catch { - throw new Error(`Invalid uint value: ${v}`); - } - case "bytes": - if (isHex(v)) { - return v as `0x${string}`; - } - throw new Error(`Invalid bytes value: ${v}`); - case "address": - if (isAddress(v)) { - return getAddress(v); - } - throw new Error(`Invalid address value: ${v}`); - default: - throw new Error(`Unsupported type ${param.type}`); - } - }); - if (values.length !== abiParameters.length) { - throw new Error( - `Not enough values, expected ${abiParameters.length} values based on --input-abi-params '${abiParams}', parsed ${values.length} values from input '${input}'`, - ); - } - if (encoding === "abi") { - return encodeAbiParameters(abiParameters, values); - } else if (encoding === "abi-packed") { - const types = abiParameters.map((p) => p.type); - return encodePacked(types, values); - } - } - if (isHex(input)) { - // encoding not specified, if starts with 0x, assume hex - return input; - } - // encode UTF-8 string as hex - return stringToHex(input); - } - return undefined; -}; - export const createSendCommand = () => { const command = new Command("send") .description("Send input to the application") @@ -138,7 +34,7 @@ export const createSendCommand = () => { const projectName = getProjectName(options); - // connect to anvil + // connect to anvil, so we can ask which account to impersonate const testClient = await connect(options); // the input sender, impersonated @@ -154,25 +50,22 @@ export const createSendCommand = () => { }); const payload = - (await getInput(input, options)) || + (await encodeInput(input, options)) || (await bytesInput({ abiParams: options.abiParams, encoding: options.encoding, message: "Input", })); - const { request } = await testClient.simulateContract({ - address: inputBoxAddress, - abi: inputBoxAbi, - account, - args: [applicationAddress, payload], - functionName: "addInput", - }); - - const hash = await testClient.writeContract(request); const progress = ora("Sending input...").start(); - await testClient.waitForTransactionReceipt({ hash }); - progress.succeed(`Input sent: ${hash}`); + const { transactionHash } = await send({ + application: applicationAddress, + client: testClient, + from: account, + payload, + projectName, + }); + progress.succeed(`Input sent: ${transactionHash}`); }); return command; }; diff --git a/apps/cli/src/commands/shell.ts b/apps/cli/src/commands/shell.ts index 2a022938..7131971b 100755 --- a/apps/cli/src/commands/shell.ts +++ b/apps/cli/src/commands/shell.ts @@ -1,10 +1,5 @@ import { Command } from "@commander-js/extra-typings"; -import { ExecaError } from "execa"; -import fs from "fs-extra"; -import path from "node:path"; -import { getApplicationConfig, getContextPath } from "../base.js"; -import { nvramHasImage, nvramImageFilename } from "../builder/nvram.js"; -import { bootMachine } from "../machine.js"; +import { shell } from "../api/shell.js"; export const createShellCommand = () => { return new Command("shell") @@ -17,60 +12,8 @@ export const createShellCommand = () => { ) .option("--run-as-root", "run as root user", false) .action(async (options) => { - const { command, runAsRoot } = options; + const { command, config, runAsRoot } = options; - // get application configuration from 'cartesi.toml' - const config = getApplicationConfig(options.config); - - // destination directory for image and intermediate files - const destination = path.resolve(getContextPath()); - - // check if all drives are built - for (const [name, drive] of Object.entries(config.drives)) { - const filename = `${name}.${drive.format}`; - const pathname = getContextPath(filename); - if (!fs.existsSync(pathname)) { - throw new Error(`drive '${name}' not built, run 'build'`); - } - } - - // check if all nvrams backed by an image are built, pristine ones have none - for (const [label, nvram] of Object.entries(config.nvrams)) { - if (!nvramHasImage(nvram)) { - continue; - } - const pathname = getContextPath(nvramImageFilename(label)); - if (!fs.existsSync(pathname)) { - throw new Error(`nvram '${label}' not built, run 'build'`); - } - } - - // create shell entrypoint - config.machine.entrypoint = command; - - // run as root if flag is set - config.machine.user = runAsRoot ? "root" : undefined; - - // boot machine - try { - await bootMachine( - config, - undefined, - { interactive: true }, // start with interactive mode on - { - cwd: destination, - stdio: "inherit", - tty: true, - }, - ); - } catch (error: unknown) { - if (error instanceof ExecaError) { - // just continue gracefully - if (error.exitCode === 130) { - return; - } - throw error; - } - } + await shell({ command, config, runAsRoot }); }); }; diff --git a/apps/cli/src/commands/status.ts b/apps/cli/src/commands/status.ts index 1deb6dbb..80721330 100644 --- a/apps/cli/src/commands/status.ts +++ b/apps/cli/src/commands/status.ts @@ -1,10 +1,9 @@ import { Command } from "@commander-js/extra-typings"; import chalk from "chalk"; import Table from "cli-table3"; -import { getProjectName, getServiceState } from "../base.js"; +import { status } from "../api/status.js"; import { type ApplicationStatus, - getDeployments, type RollupsDeployment, TERMINAL_APPLICATION_STATUSES, } from "../exec/rollups.js"; @@ -34,29 +33,22 @@ export const createStatusCommand = () => { .action(async (options) => { const { json } = options; - const projectName = getProjectName(options); - - const status = await getServiceState({ - projectName, - service: "rollups_node", - }); - const deployments = await getDeployments({ - projectName, - }); + const { deployments, projectName, running, state } = + await status(options); if (json) { process.stdout.write( JSON.stringify({ - status, + status: state, deployments, }), ); } else { console.log( - `${chalk.cyan(projectName)} is ${status === "running" ? chalk.green("running") : chalk.red("not running")}`, + `${chalk.cyan(projectName)} is ${running ? chalk.green("running") : chalk.red("not running")}`, ); - if (status === "running") { + if (running) { if (deployments.length === 0) { console.log(chalk.red("no applications deployed")); } else { diff --git a/apps/cli/src/commands/withdraw.ts b/apps/cli/src/commands/withdraw.ts index 4055afe1..5adff215 100644 --- a/apps/cli/src/commands/withdraw.ts +++ b/apps/cli/src/commands/withdraw.ts @@ -1,361 +1,11 @@ import { Command, Option } from "@commander-js/extra-typings"; -import chalk from "chalk"; -import fs from "fs-extra"; -import ora from "ora"; -import pRetry, { type Options as RetryOptions } from "p-retry"; -import { type Address, type Hash, zeroHash } from "viem"; +import { withdraw } from "../api/withdraw.js"; import { getProjectName, parseAddress } from "../base.js"; -import { - iApplicationAbi, - iOutputsMerkleRootValidatorAbi, -} from "../contracts.js"; -import { - execNodeCommand, - handleNodeCommandError, - nodePathExists, - removeNodePath, - runNodeCommand, - type TransactionOptions, - transactionArgs, - writeNodeTempFile, -} from "../exec/node-container.js"; -import { - type AccountsDriveConfig, - proveAccountsDrive, - replayMachine, -} from "../exec/cartesi-rollups-machine-tool.js"; -import { - getLastAcceptedEpoch, - getNodeWithdrawalConfig, -} from "../exec/rollups.js"; -import { - addRecoveryOptions, - getAnvilClient, - resolveNodeApplication, -} from "../node.js"; +import { handleNodeCommandError } from "../exec/node-container.js"; +import { resolveNodeApplication } from "../node.js"; +import { addRecoveryOptions } from "./recovery.js"; import { addressInput } from "../prompts.js"; - -/** - * Directory inside the rollups node container where replayed machines and - * proofs are kept, so further withdrawals of the same application reuse them - */ -const WORK_DIR = "/tmp/cartesi-withdraw"; - -/** - * Path of the machine replayed up to an epoch. Keyed by application and epoch, - * so a redeploy or another epoch never reuses a snapshot. - */ -export const replayStorePath = (application: Address, epochIndex: bigint) => - `${WORK_DIR}/${application}/epoch-${epochIndex}`; - -/** - * Directory of the proofs generated for an account of an application - */ -export const proofStorePath = (application: Address, account: Address) => - `${WORK_DIR}/${application}/${account}`; - -/** - * Operations on the rollups node container used to replay and prove, so tests - * can run the steps without one - */ -export type WithdrawIo = { - execNodeCommand: typeof execNodeCommand; - getLastAcceptedEpoch: typeof getLastAcceptedEpoch; - nodePathExists: typeof nodePathExists; - proveAccountsDrive: typeof proveAccountsDrive; - removeNodePath: typeof removeNodePath; - replayMachine: typeof replayMachine; -}; - -const defaultIo: WithdrawIo = { - execNodeCommand, - getLastAcceptedEpoch, - nodePathExists, - proveAccountsDrive, - removeNodePath, - replayMachine, -}; - -/** - * How long to wait for the node to process the last finalized epoch - */ -const FINALIZED_EPOCH_RETRY: RetryOptions = { - retries: 15, - minTimeout: 1_000, - maxTimeout: 2_000, - factor: 1.2, -}; - -/** - * Read the foreclosure state of the application from the chain. The node - * observes it some blocks later, which is too late for a withdrawal that - * follows another one. The last finalized machine root is the one the proofs - * are checked against on chain. - */ -const readForeclosureState = async (options: { - application: Address; - projectName: string; -}) => { - const { application, projectName } = options; - const client = await getAnvilClient({ projectName }); - const [foreclosed, [driveRootProven], validator] = await Promise.all([ - client.readContract({ - abi: iApplicationAbi, - address: application, - functionName: "isForeclosed", - }), - client.readContract({ - abi: iApplicationAbi, - address: application, - functionName: "getAccountsDriveMerkleRoot", - }), - client.readContract({ - abi: iApplicationAbi, - address: application, - functionName: "getOutputsMerkleRootValidator", - }), - ]); - const finalizedMachineRoot = await client.readContract({ - abi: iOutputsMerkleRootValidatorAbi, - address: validator, - args: [application], - functionName: "getLastFinalizedMachineMerkleRoot", - }); - return { driveRootProven, finalizedMachineRoot, foreclosed }; -}; - -const isSameHash = (a: Hash, b: Hash) => a.toLowerCase() === b.toLowerCase(); - -/** - * Find the epoch the node has with the machine root finalized on chain. The - * node records accepted epochs some blocks after the chain, so it may still - * report an older one; nothing is finalized after the foreclosure, so it - * catches up. - * @returns the index of the epoch - */ -const waitForFinalizedEpoch = async (options: { - application: Address; - finalizedMachineRoot: Hash; - io: WithdrawIo; - projectName: string; - retry: RetryOptions; -}): Promise => { - const { application, finalizedMachineRoot, io, projectName, retry } = - options; - let last: { index?: bigint; machineHash?: Hash } = {}; - try { - return await pRetry(async () => { - const epoch = await io.getLastAcceptedEpoch({ - application, - projectName, - }); - last = epoch ?? {}; - if ( - !epoch?.machineHash || - !isSameHash(epoch.machineHash, finalizedMachineRoot) - ) { - throw new Error("node is behind the chain"); - } - return epoch.index; - }, retry); - } catch { - throw new Error( - `The node hasn't processed the last finalized epoch yet (node epoch ${last.index ?? "none"} root ${last.machineHash ?? "none"}, chain root ${finalizedMachineRoot}); try again shortly`, - ); - } -}; - -/** - * Replay the application up to its last finalized epoch, unless a previous - * withdrawal already did it. Nothing is finalized after the foreclosure, so - * the replayed machine never changes. - * @returns path of the replayed machine inside the rollups node container - */ -export const replayLastFinalizedEpoch = async (options: { - application: Address; - finalizedMachineRoot: Hash; - io?: WithdrawIo; - projectName: string; - retry?: RetryOptions; -}): Promise<{ store: string }> => { - const { - application, - finalizedMachineRoot, - io = defaultIo, - projectName, - retry = FINALIZED_EPOCH_RETRY, - } = options; - if (isSameHash(finalizedMachineRoot, zeroHash)) { - throw new Error("No finalized epoch, there are no funds to withdraw"); - } - - const progress = ora("Looking up the last finalized epoch...").start(); - let epochIndex: bigint; - try { - epochIndex = await waitForFinalizedEpoch({ - application, - finalizedMachineRoot, - io, - projectName, - retry, - }); - } catch (error: unknown) { - progress.fail(); - throw error; - } - - const store = replayStorePath(application, epochIndex); - if (await io.nodePathExists({ path: store, projectName })) { - progress.succeed( - `Using the machine replayed up to epoch ${chalk.cyan(epochIndex)}`, - ); - return { store }; - } - - // replay into a temporary path, so an interrupted replay is never reused - const tmp = `${store}.tmp`; - progress.text = `Replaying the inputs up to epoch ${chalk.cyan(epochIndex)}, this may take a while...`; - try { - await io.removeNodePath({ path: tmp, projectName }); - const replay = await io.replayMachine({ - application, - epochIndex, - projectName, - store: tmp, - }); - if (!isSameHash(replay.machineRoot, finalizedMachineRoot)) { - throw new Error( - `Replayed machine root ${replay.machineRoot} does not match the finalized machine root ${finalizedMachineRoot} of epoch ${epochIndex}`, - ); - } - await io.execNodeCommand({ command: ["mv", tmp, store], projectName }); - progress.succeed( - `Replayed ${chalk.cyan(replay.processedInputs)} inputs up to epoch ${chalk.cyan(epochIndex)}`, - ); - } catch (error: unknown) { - progress.fail("Failed to replay the application"); - await io.removeNodePath({ path: tmp, projectName }); - throw error; - } - return { store }; -}; - -/** - * Generate the accounts drive proofs of an account from the replayed machine, - * checking they prove the finalized machine root - * @returns the paths of the proofs inside the rollups node container - */ -export const generateAccountProofs = async (options: { - account: Address; - application: Address; - driveConfig: AccountsDriveConfig; - io?: WithdrawIo; - finalizedMachineRoot: Hash; - projectName: string; - store: string; -}) => { - const { - account, - application, - driveConfig, - finalizedMachineRoot, - io = defaultIo, - projectName, - store, - } = options; - const progress = ora( - `Generating the proofs of ${chalk.cyan(account)}...`, - ).start(); - const proof = await io - .proveAccountsDrive({ - account, - driveConfig, - outDir: proofStorePath(application, account), - projectName, - snapshot: store, - }) - .catch((error: unknown) => { - progress.fail(`Failed to generate the proofs of ${account}`); - throw error; - }); - if (!isSameHash(proof.machineRoot, finalizedMachineRoot)) { - progress.fail(); - // a cached snapshot that doesn't prove the finalized root would fail - // every retry, so drop it and let the next run replay - await io.removeNodePath({ path: store, projectName }); - throw new Error( - `Proof machine root ${proof.machineRoot} does not match the finalized machine root ${finalizedMachineRoot}. Removed the cached snapshot; run the command again to replay it`, - ); - } - progress.succeed( - `Generated the proofs of ${chalk.cyan(account)} (account index ${chalk.cyan(proof.accountIndex)})`, - ); - return proof; -}; - -/** - * Generate the proofs of an account and prove the accounts drive root, if - * nobody did it yet - * @returns path of the withdraw proof inside the rollups node container - */ -const proveAccount = async (options: { - account: Address; - accountIndex?: number; - application: Address; - driveRootProven: boolean; - finalizedMachineRoot: Hash; - projectName: string; - tx: TransactionOptions; -}): Promise => { - const { - account, - accountIndex, - application, - driveRootProven, - finalizedMachineRoot, - projectName, - tx, - } = options; - const driveConfig = await getNodeWithdrawalConfig({ - application, - projectName, - }); - - const { store } = await replayLastFinalizedEpoch({ - application, - finalizedMachineRoot, - projectName, - }); - - const proof = await generateAccountProofs({ - account, - application, - driveConfig, - finalizedMachineRoot, - projectName, - store, - }); - - if (!driveRootProven) { - // the withdrawal depends on it, so always wait for the receipt, and - // keep stdout for the output of the withdrawal - await runNodeCommand({ - accountIndex, - command: [ - "cartesi-rollups-cli", - "prove-drive-root", - application, - "--proof-file", - proof.driveRootProofFile, - ...transactionArgs({ ...tx, json: false, wait: true }), - ], - projectName, - stdout: "stderr", - }); - } - - return proof.withdrawProofFile; -}; +import { assertForeclosed } from "../withdraw.js"; export const createWithdrawCommand = () => { return addRecoveryOptions( @@ -378,69 +28,32 @@ export const createWithdrawCommand = () => { ), "index of the account in the node mnemonic paying for gas", ).action(async (options) => { - const { accountIndex, proofFile } = options; + const { proofFile } = options; const projectName = getProjectName(options); - const application = await resolveNodeApplication({ - application: options.application, - projectName, - }); - const { driveRootProven, finalizedMachineRoot, foreclosed } = - await readForeclosureState({ application, projectName }); - if (!foreclosed) { - throw new Error( - `Application ${chalk.cyan(application)} is not foreclosed, use ${chalk.cyan("cartesi foreclose")} first`, - ); + + // ask for the account only once the application is known to be + // foreclosed, so a mistake fails before the prompt + let account = options.account; + if (!proofFile && !account) { + const application = await resolveNodeApplication({ + application: options.application, + projectName, + }); + await assertForeclosed({ application, projectName }); + account = await addressInput({ + message: "Account to withdraw the funds of", + }); } - let withdrawProofFile: string; - let tmpProofFile: string | undefined; try { - if (proofFile) { - if (!driveRootProven) { - throw new Error( - `The accounts drive root of ${application} isn't proven yet. ${chalk.cyan("--proof-file")} only carries the account proof; run ${chalk.cyan("cartesi withdraw --account
")} once so the CLI proves the drive root, then ${chalk.cyan("--proof-file")} will work`, - ); - } - tmpProofFile = await writeNodeTempFile({ - content: await fs.readFile(proofFile, "utf-8"), - projectName, - }); - withdrawProofFile = tmpProofFile; - } else { - const account = - options.account ?? - (await addressInput({ - message: "Account to withdraw the funds of", - })); - withdrawProofFile = await proveAccount({ - account, - accountIndex, - application, - driveRootProven, - finalizedMachineRoot, - projectName, - tx: options, - }); - } - - await runNodeCommand({ - accountIndex, - command: [ - "cartesi-rollups-cli", - "withdraw", - application, - "--proof-file", - withdrawProofFile, - ...transactionArgs(options), - ], - projectName, + await withdraw({ + ...options, + account, + progress: "default", + stream: true, }); } catch (error: unknown) { handleNodeCommandError(error); - } finally { - if (tmpProofFile) { - await removeNodePath({ path: tmpProofFile, projectName }); - } } }); }; diff --git a/apps/cli/src/exec/node-container.ts b/apps/cli/src/exec/node-container.ts index 15a07e8e..3a0502ec 100644 --- a/apps/cli/src/exec/node-container.ts +++ b/apps/cli/src/exec/node-container.ts @@ -100,18 +100,20 @@ export const runNodeCommand = (options: { * @returns stdout of the command */ export const execNodeCommand = async (options: { + accountIndex?: number; command: string[]; + env?: Record; input?: string; projectName: string; service?: string; workdir?: string; }): Promise => { - const { input, ...rest } = options; + const { env, input, ...rest } = options; try { const { stdout } = await execa( "docker", - nodeExecArgs({ ...rest, interactive: false }), - { input }, + nodeExecArgs({ ...rest, env, interactive: false }), + { env, input }, ); return stdout; } catch (error: unknown) { @@ -173,13 +175,46 @@ export const nodePathExists = async (options: { return exitCode === 0; }; +/** + * A command run with the terminal attached failed. It already printed its + * error to the terminal, so only its exit code is kept. + */ +export class NodeCommandError extends Error { + readonly exitCode: number; + + constructor(exitCode: number, options?: ErrorOptions) { + super(`The node command failed with exit code ${exitCode}`, options); + this.name = "NodeCommandError"; + this.exitCode = exitCode; + } +} + +/** + * Run a command inside the rollups node container with the terminal attached, + * like `runNodeCommand`, failing with a NodeCommandError when it exits with an + * error it already printed + */ +export const runAttachedNodeCommand = async ( + options: Parameters[0], +) => { + try { + await runNodeCommand(options); + } catch (error: unknown) { + if (error instanceof ExecaError) { + throw new NodeCommandError(error.exitCode ?? 1, { cause: error }); + } + throw error; + } +}; + /** * Report the failure of a command run with the terminal attached. The command - * already printed its error, so only its exit code is propagated. + * already printed its error, so only its exit code is propagated. Any other + * error is thrown, to be printed. */ export const handleNodeCommandError = (error: unknown) => { - if (error instanceof ExecaError) { - process.exitCode = error.exitCode ?? 1; + if (error instanceof NodeCommandError) { + process.exitCode = error.exitCode; return; } throw error; diff --git a/apps/cli/src/exec/rollups.ts b/apps/cli/src/exec/rollups.ts index f0b9b626..f1b5dcd6 100644 --- a/apps/cli/src/exec/rollups.ts +++ b/apps/cli/src/exec/rollups.ts @@ -730,9 +730,10 @@ export const waitHealthyEnvironment = async (options: { name?: string; port: number; projectName: string; + renderer?: "default" | "silent" | "verbose"; services: string[]; }) => { - const { name, port, projectName, services } = options; + const { name, port, projectName, renderer = "default", services } = options; // select subset of optional services const optionalServices = @@ -757,7 +758,7 @@ export const waitHealthyEnvironment = async (options: { }); }); - const tasks = new Listr(monitorTasks, { concurrent: true }); + const tasks = new Listr(monitorTasks, { concurrent: true, renderer }); await tasks.run(); }; diff --git a/apps/cli/src/exec/util.ts b/apps/cli/src/exec/util.ts index 0869348f..e933a366 100644 --- a/apps/cli/src/exec/util.ts +++ b/apps/cli/src/exec/util.ts @@ -1,4 +1,4 @@ -import { ExecaError, execa, type Options } from "execa"; +import { ExecaError, execa, type Options, type Result } from "execa"; import os from "node:os"; export type Reporter = (line: string) => void; @@ -29,11 +29,13 @@ const pipeReporter = (proc: ReturnType, reporter: Reporter) => { }); }; +// the return type is explicit because the type execa infers for it cannot be +// named from outside its own package, which breaks declaration emit export const execaDockerFallback = async ( command: string, args: readonly string[], options: ExecaOptionsDockerFallback, -) => { +): Promise => { const { reporter } = options; try { if (options.forceDocker) { diff --git a/apps/cli/src/foreclose.ts b/apps/cli/src/foreclose.ts new file mode 100644 index 00000000..72bb1166 --- /dev/null +++ b/apps/cli/src/foreclose.ts @@ -0,0 +1,79 @@ +import { type Address, isAddressEqual, zeroAddress } from "viem"; +import { privateKeyToAccount } from "viem/accounts"; +import { + type HostSigner, + hostSignerEnv, + type NodeSigner, +} from "./exec/node-container.js"; +import { findMnemonicAccountIndex } from "./wallet.js"; + +/** + * Work out how to sign as the guardian, the only account allowed to + * foreclose. A signer given for the command takes precedence over the node's. + * cartesi-rollups-cli signs with whatever its environment configures, so for + * a mnemonic the guardian's account index is looked up, unless one is given. + * A private key has no index to choose. + * @returns the account index and environment to sign with, and a warning to show, if any + */ +export const resolveForecloseSigner = (options: { + accountIndex?: number; + guardian: Address; + host?: HostSigner; + node?: NodeSigner; +}): { + accountIndex?: number; + env?: Record; + warning?: string; +} => { + const { accountIndex, guardian, host, node } = options; + + if (isAddressEqual(guardian, zeroAddress)) { + throw new Error( + "The application was deployed without a withdrawal config and cannot be foreclosed", + ); + } + + // the signer given for the command is passed down to cartesi-rollups-cli + const env = host ? hostSignerEnv(host) : undefined; + const ignoredIndex = + accountIndex === undefined + ? {} + : { + warning: + "--account-index is ignored when signing with a private key", + }; + + if (host?.kind === "private_key") { + const { address } = privateKeyToAccount(host.privateKey); + if (!isAddressEqual(address, guardian)) { + throw new Error( + `The private key's address ${address} isn't the guardian ${guardian}`, + ); + } + return { ...ignoredIndex, env }; + } + + // the node's private key is never read, so it can't be checked here + const signer = host ?? node; + if (!signer) { + throw new Error("No signer to foreclose with"); + } + if (signer.kind === "private_key") { + return ignoredIndex; + } + + if (accountIndex !== undefined) { + return { accountIndex, env }; + } + + const index = findMnemonicAccountIndex({ + address: guardian, + mnemonic: signer.mnemonic, + }); + if (index === undefined) { + throw new Error( + `Guardian ${guardian} isn't one of the first 20 accounts of the mnemonic in use. If it belongs to another mnemonic, set CARTESI_AUTH_MNEMONIC; if its index is higher, pass --account-index; if it's a raw private key, set CARTESI_AUTH_PRIVATE_KEY`, + ); + } + return { accountIndex: index, env }; +}; diff --git a/apps/cli/src/lib.ts b/apps/cli/src/lib.ts new file mode 100644 index 00000000..21f9e359 --- /dev/null +++ b/apps/cli/src/lib.ts @@ -0,0 +1,63 @@ +/** + * Programmatic API of the Cartesi CLI. + * + * Every command of the CLI is also available as a function, so applications can + * be built, run and inspected from a script: + * + * ```ts + * import { build, hash, run } from "@cartesi/cli"; + * + * await build(); + * console.log(await hash()); + * + * const node = await run(); + * // ... + * await node.stop(); + * ``` + * + * Unless stated otherwise, functions operate on the current working directory, + * just like the CLI, and are silent: nothing is written to the terminal. Pass + * `progress: "default"` to get the same output as the CLI. + */ +export * from "./api/index.js"; + +// configuration of an application ('cartesi.toml') +export { + type Config, + DEFAULT_SDK_IMAGE, + DEFAULT_SDK_VERSION, + defaultConfig, + defaultMachineConfig, + defaultRootDriveConfig, + type DirectoryDriveConfig, + type DockerDriveConfig, + type DriveConfig, + type DriveFormat, + type EmptyDriveConfig, + type ExistingDriveConfig, + type ImageInfo, + type MachineConfig, + type NvramConfig, + parse as parseConfig, + PREFERRED_PORT, + type TarDriveConfig, + type WithdrawalConfig, + type WithdrawalOptions, +} from "./config.js"; + +// runtime environment +export { + AVAILABLE_SERVICES, + type RollupsDeployment, +} from "./exec/rollups.js"; + +export type { ForkConfig } from "./types/chain.js"; +export { cartesi, type DevnetClient } from "./wallet.js"; + +// emergency withdrawal, derived from the accounts drive of the built machine +export { + type AccountsDriveLayout, + describeWithdrawalConfig, + getWithdrawalConfig, + resolveWithdrawal, +} from "./withdrawal.js"; diff --git a/apps/cli/src/node.ts b/apps/cli/src/node.ts index 9d45d203..d7d08ab6 100644 --- a/apps/cli/src/node.ts +++ b/apps/cli/src/node.ts @@ -1,24 +1,25 @@ -import { - type Command, - Option, - type OptionValues, -} from "@commander-js/extra-typings"; import chalk from "chalk"; import { type Address, createPublicClient, getAddress, http, + type HttpTransport, isAddress, + type PublicClient, } from "viem"; -import { getServiceState, parseAccountIndex } from "./base.js"; +import { getServiceState } from "./base.js"; import { getApplicationAddress, getProjectPort } from "./exec/rollups.js"; /** * Create a read-only client for the anvil of the local environment * @param options projectName */ -export const getAnvilClient = async (options: { projectName: string }) => { +// the return type is explicit because the one inferred by createPublicClient +// cannot be named from outside viem, which breaks declaration emit +export const getAnvilClient = async (options: { + projectName: string; +}): Promise> => { const host = await getProjectPort(options); return createPublicClient({ transport: http(`http://${host}/anvil`) }); }; @@ -67,40 +68,3 @@ export const resolveNodeApplication = async (options: { } return address; }; - -/** - * Add the options shared by the fund recovery commands: the application and - * project, the signer account index, and the transaction flags forwarded to - * cartesi-rollups-cli - * @param accountIndexDescription what the account index selects for this command - */ -export const addRecoveryOptions = < - Args extends unknown[], - Opts extends OptionValues, - GlobalOpts extends OptionValues, ->( - command: Command, - accountIndexDescription: string, -) => - command - .option("--application
", "application address") - .option( - "--project-name ", - "name of project (used by docker compose and cartesi-rollups-node)", - ) - .addOption( - new Option( - "--account-index ", - accountIndexDescription, - ).argParser(parseAccountIndex), - ) - .option("-y, --yes", "skip the confirmation prompt") - .option("--json", "print the result as JSON") - .option( - "--no-wait", - "return after broadcast without waiting for the receipt", - ) - .option( - "--wait-timeout ", - "maximum time to wait for the receipt (e.g. 30s, 5m)", - ); diff --git a/apps/cli/src/refund.ts b/apps/cli/src/refund.ts new file mode 100644 index 00000000..ffd48867 --- /dev/null +++ b/apps/cli/src/refund.ts @@ -0,0 +1,43 @@ +import chalk from "chalk"; +import fs from "fs-extra"; +import { type Address, type Hex, isHex } from "viem"; +import { getNodeInput } from "./exec/rollups.js"; + +/** + * Get the complete InputAdded.input bytes of the deposit to refund, from a + * file or from the node + */ +export const getInputData = async (options: { + application: Address; + inputFile?: string; + inputIndex: bigint; + io?: { getNodeInput: typeof getNodeInput }; + projectName: string; +}): Promise => { + const { + application, + inputFile, + inputIndex, + io = { getNodeInput }, + projectName, + } = options; + + if (inputFile) { + const data = (await fs.readFile(inputFile, "utf-8")).trim(); + if (!isHex(data) || data.length <= 2) { + throw new Error( + `${inputFile} must contain the 0x-prefixed hexadecimal input bytes`, + ); + } + return data; + } + + try { + return await io.getNodeInput({ application, inputIndex, projectName }); + } catch (error: unknown) { + throw new Error( + `Input ${inputIndex} not found in the node, use ${chalk.cyan("--input-file")} with the InputAdded.input bytes`, + { cause: error }, + ); + } +}; diff --git a/apps/cli/src/validations.ts b/apps/cli/src/validations.ts index 1fab8cca..0f71fd38 100644 --- a/apps/cli/src/validations.ts +++ b/apps/cli/src/validations.ts @@ -18,12 +18,12 @@ import { erc721PortalConfig, etherPortalConfig, inputBoxConfig, -} from "./contracts"; -import type { CartesiEnvironmentVariables } from "./base"; -import { nodeSecretFileVariables } from "./compose/node"; -import ForkChainValidationError from "./errors/ForkChainValidationError"; -import UnsupportedForkChainError from "./errors/UnsupportedForkChainError"; -import type { ForkConfig } from "./types/chain"; +} from "./contracts.js"; +import type { CartesiEnvironmentVariables } from "./base.js"; +import { nodeSecretFileVariables } from "./compose/node.js"; +import ForkChainValidationError from "./errors/ForkChainValidationError.js"; +import UnsupportedForkChainError from "./errors/UnsupportedForkChainError.js"; +import type { ForkConfig } from "./types/chain.js"; interface AssertForkConfigOptions { includePRT?: boolean; diff --git a/apps/cli/src/wallet.ts b/apps/cli/src/wallet.ts index 6f4977b8..0792c43d 100644 --- a/apps/cli/src/wallet.ts +++ b/apps/cli/src/wallet.ts @@ -1,13 +1,18 @@ import input from "@inquirer/input"; import { type Address, + type Chain, createTestClient, defineChain, type Hex, http, + type HttpTransport, isAddressEqual, + type PublicActions, publicActions, + type TestClient, toHex, + type WalletActions, walletActions, } from "viem"; import { mnemonicToAccount } from "viem/accounts"; @@ -17,7 +22,9 @@ import { DEVNET_MNEMONIC } from "./compose/node.js"; import { PREFERRED_PORT } from "./config.js"; import { getProjectPort } from "./exec/rollups.js"; -export const cartesi = defineChain({ +// the type is explicit because the one inferred by defineChain cannot be named +// from outside viem, which breaks declaration emit +export const cartesi: Chain = defineChain({ ...anvil, name: "Cartesi Devnet", testnet: true, @@ -26,6 +33,7 @@ export const cartesi = defineChain({ const getRpcUrl = async (options: { rpcUrl?: string; projectName?: string; + interactive?: boolean; }) => { // if rpcUrl is provided, use it if (options.rpcUrl) return options.rpcUrl; @@ -35,7 +43,14 @@ const getRpcUrl = async (options: { const projectName = getProjectName(options); const host = await getProjectPort({ projectName }); return `http://${host}/anvil`; - } catch { + } catch (error: unknown) { + if (options.interactive === false) { + // no terminal to ask the user for the RPC URL + throw new Error( + `Unable to resolve the RPC URL of project '${getProjectName(options)}', make sure it is running, or define 'rpcUrl'`, + { cause: error }, + ); + } return await input({ message: "RPC URL", default: `http://127.0.0.1:${PREFERRED_PORT}/anvil`, @@ -43,10 +58,27 @@ const getRpcUrl = async (options: { } }; +/** + * Client connected to the devnet of a local environment. + * + * The type is spelled out, instead of inferred from {@link connect}, because the + * inferred one inlines viem internals that cannot be named from outside their + * package, which breaks declaration emit. + */ +export type DevnetClient = TestClient<"anvil", HttpTransport, typeof cartesi> & + PublicActions & + WalletActions; + export const connect = async (options: { rpcUrl?: string; projectName?: string; -}) => { + + /** + * Ask for the RPC URL when it can't be resolved from the running project. + * @default true + */ + interactive?: boolean; +}): Promise => { // resolve rpc url const rpcUrl = await getRpcUrl(options); diff --git a/apps/cli/src/withdraw.ts b/apps/cli/src/withdraw.ts new file mode 100644 index 00000000..c5b2f58c --- /dev/null +++ b/apps/cli/src/withdraw.ts @@ -0,0 +1,305 @@ +import chalk from "chalk"; +import ora from "ora"; +import pRetry, { type Options as RetryOptions } from "p-retry"; +import { type Address, type Hash, zeroHash } from "viem"; +import type { Progress } from "./api/types.js"; +import { + iApplicationAbi, + iOutputsMerkleRootValidatorAbi, +} from "./contracts.js"; +import { + type AccountsDriveConfig, + proveAccountsDrive, + replayMachine, +} from "./exec/cartesi-rollups-machine-tool.js"; +import { + execNodeCommand, + nodePathExists, + removeNodePath, +} from "./exec/node-container.js"; +import { getLastAcceptedEpoch } from "./exec/rollups.js"; +import { getAnvilClient } from "./node.js"; + +/** + * Directory inside the rollups node container where replayed machines and + * proofs are kept, so further withdrawals of the same application reuse them + */ +const WORK_DIR = "/tmp/cartesi-withdraw"; + +/** + * Path of the machine replayed up to an epoch. Keyed by application and epoch, + * so a redeploy or another epoch never reuses a snapshot. + */ +export const replayStorePath = (application: Address, epochIndex: bigint) => + `${WORK_DIR}/${application}/epoch-${epochIndex}`; + +/** + * Directory of the proofs generated for an account of an application + */ +export const proofStorePath = (application: Address, account: Address) => + `${WORK_DIR}/${application}/${account}`; + +/** + * Operations on the rollups node container used to replay and prove, so tests + * can run the steps without one + */ +export type WithdrawIo = { + execNodeCommand: typeof execNodeCommand; + getLastAcceptedEpoch: typeof getLastAcceptedEpoch; + nodePathExists: typeof nodePathExists; + proveAccountsDrive: typeof proveAccountsDrive; + removeNodePath: typeof removeNodePath; + replayMachine: typeof replayMachine; +}; + +const defaultIo: WithdrawIo = { + execNodeCommand, + getLastAcceptedEpoch, + nodePathExists, + proveAccountsDrive, + removeNodePath, + replayMachine, +}; + +/** + * How long to wait for the node to process the last finalized epoch + */ +const FINALIZED_EPOCH_RETRY: RetryOptions = { + retries: 15, + minTimeout: 1_000, + maxTimeout: 2_000, + factor: 1.2, +}; + +/** + * Read the foreclosure state of the application from the chain. The node + * observes it some blocks later, which is too late for a withdrawal that + * follows another one. The last finalized machine root is the one the proofs + * are checked against on chain. + */ +export const readForeclosureState = async (options: { + application: Address; + projectName: string; +}) => { + const { application, projectName } = options; + const client = await getAnvilClient({ projectName }); + const [foreclosed, [driveRootProven], validator] = await Promise.all([ + client.readContract({ + abi: iApplicationAbi, + address: application, + functionName: "isForeclosed", + }), + client.readContract({ + abi: iApplicationAbi, + address: application, + functionName: "getAccountsDriveMerkleRoot", + }), + client.readContract({ + abi: iApplicationAbi, + address: application, + functionName: "getOutputsMerkleRootValidator", + }), + ]); + const finalizedMachineRoot = await client.readContract({ + abi: iOutputsMerkleRootValidatorAbi, + address: validator, + args: [application], + functionName: "getLastFinalizedMachineMerkleRoot", + }); + return { driveRootProven, finalizedMachineRoot, foreclosed }; +}; + +/** + * Read the foreclosure state of the application, which must be foreclosed for + * its funds to be withdrawn + * @throws when the application is not foreclosed + */ +export const assertForeclosed = async (options: { + application: Address; + projectName: string; +}) => { + const state = await readForeclosureState(options); + if (!state.foreclosed) { + throw new Error( + `Application ${chalk.cyan(options.application)} is not foreclosed, use ${chalk.cyan("cartesi foreclose")} first`, + ); + } + return state; +}; + +const isSameHash = (a: Hash, b: Hash) => a.toLowerCase() === b.toLowerCase(); + +/** + * Find the epoch the node has with the machine root finalized on chain. The + * node records accepted epochs some blocks after the chain, so it may still + * report an older one; nothing is finalized after the foreclosure, so it + * catches up. + * @returns the index of the epoch + */ +const waitForFinalizedEpoch = async (options: { + application: Address; + finalizedMachineRoot: Hash; + io: WithdrawIo; + projectName: string; + retry: RetryOptions; +}): Promise => { + const { application, finalizedMachineRoot, io, projectName, retry } = + options; + let last: { index?: bigint; machineHash?: Hash } = {}; + try { + return await pRetry(async () => { + const epoch = await io.getLastAcceptedEpoch({ + application, + projectName, + }); + last = epoch ?? {}; + if ( + !epoch?.machineHash || + !isSameHash(epoch.machineHash, finalizedMachineRoot) + ) { + throw new Error("node is behind the chain"); + } + return epoch.index; + }, retry); + } catch { + throw new Error( + `The node hasn't processed the last finalized epoch yet (node epoch ${last.index ?? "none"} root ${last.machineHash ?? "none"}, chain root ${finalizedMachineRoot}); try again shortly`, + ); + } +}; + +/** + * Replay the application up to its last finalized epoch, unless a previous + * withdrawal already did it. Nothing is finalized after the foreclosure, so + * the replayed machine never changes. + * @returns path of the replayed machine inside the rollups node container + */ +export const replayLastFinalizedEpoch = async (options: { + application: Address; + finalizedMachineRoot: Hash; + io?: WithdrawIo; + progress?: Progress; + projectName: string; + retry?: RetryOptions; +}): Promise<{ store: string }> => { + const { + application, + finalizedMachineRoot, + io = defaultIo, + progress: verbosity = "silent", + projectName, + retry = FINALIZED_EPOCH_RETRY, + } = options; + if (isSameHash(finalizedMachineRoot, zeroHash)) { + throw new Error("No finalized epoch, there are no funds to withdraw"); + } + + const progress = ora({ + isSilent: verbosity === "silent", + text: "Looking up the last finalized epoch...", + }).start(); + let epochIndex: bigint; + try { + epochIndex = await waitForFinalizedEpoch({ + application, + finalizedMachineRoot, + io, + projectName, + retry, + }); + } catch (error: unknown) { + progress.fail(); + throw error; + } + + const store = replayStorePath(application, epochIndex); + if (await io.nodePathExists({ path: store, projectName })) { + progress.succeed( + `Using the machine replayed up to epoch ${chalk.cyan(epochIndex)}`, + ); + return { store }; + } + + // replay into a temporary path, so an interrupted replay is never reused + const tmp = `${store}.tmp`; + progress.text = `Replaying the inputs up to epoch ${chalk.cyan(epochIndex)}, this may take a while...`; + try { + await io.removeNodePath({ path: tmp, projectName }); + const replay = await io.replayMachine({ + application, + epochIndex, + projectName, + store: tmp, + }); + if (!isSameHash(replay.machineRoot, finalizedMachineRoot)) { + throw new Error( + `Replayed machine root ${replay.machineRoot} does not match the finalized machine root ${finalizedMachineRoot} of epoch ${epochIndex}`, + ); + } + await io.execNodeCommand({ command: ["mv", tmp, store], projectName }); + progress.succeed( + `Replayed ${chalk.cyan(replay.processedInputs)} inputs up to epoch ${chalk.cyan(epochIndex)}`, + ); + } catch (error: unknown) { + progress.fail("Failed to replay the application"); + await io.removeNodePath({ path: tmp, projectName }); + throw error; + } + return { store }; +}; + +/** + * Generate the accounts drive proofs of an account from the replayed machine, + * checking they prove the finalized machine root + * @returns the paths of the proofs inside the rollups node container + */ +export const generateAccountProofs = async (options: { + account: Address; + application: Address; + driveConfig: AccountsDriveConfig; + io?: WithdrawIo; + finalizedMachineRoot: Hash; + progress?: Progress; + projectName: string; + store: string; +}) => { + const { + account, + application, + driveConfig, + finalizedMachineRoot, + io = defaultIo, + progress: verbosity = "silent", + projectName, + store, + } = options; + const progress = ora({ + isSilent: verbosity === "silent", + text: `Generating the proofs of ${chalk.cyan(account)}...`, + }).start(); + const proof = await io + .proveAccountsDrive({ + account, + driveConfig, + outDir: proofStorePath(application, account), + projectName, + snapshot: store, + }) + .catch((error: unknown) => { + progress.fail(`Failed to generate the proofs of ${account}`); + throw error; + }); + if (!isSameHash(proof.machineRoot, finalizedMachineRoot)) { + progress.fail(); + // a cached snapshot that doesn't prove the finalized root would fail + // every retry, so drop it and let the next run replay + await io.removeNodePath({ path: store, projectName }); + throw new Error( + `Proof machine root ${proof.machineRoot} does not match the finalized machine root ${finalizedMachineRoot}. Removed the cached snapshot; run the command again to replay it`, + ); + } + progress.succeed( + `Generated the proofs of ${chalk.cyan(account)} (account index ${chalk.cyan(proof.accountIndex)})`, + ); + return proof; +}; diff --git a/apps/cli/tests/integration/commands/recovery.test.ts b/apps/cli/tests/integration/commands/recovery.test.ts index 9c1b634f..2a180688 100644 --- a/apps/cli/tests/integration/commands/recovery.test.ts +++ b/apps/cli/tests/integration/commands/recovery.test.ts @@ -10,7 +10,7 @@ import { testUsdcAddress, testUsdWithdrawalOutputBuilderAddress, } from "../../../src/contracts"; -import { replayStorePath } from "../../../src/commands/withdraw"; +import { replayStorePath } from "../../../src/withdraw"; import { getNodeInput, getNodeWithdrawalConfig, diff --git a/apps/cli/tests/unit/api/connection.test.ts b/apps/cli/tests/unit/api/connection.test.ts new file mode 100644 index 00000000..2e5c4c3b --- /dev/null +++ b/apps/cli/tests/unit/api/connection.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "bun:test"; +import { resolveConnection } from "../../../src/api/connection.js"; +import type { DevnetClient } from "../../../src/wallet.js"; + +// never called, as every address is given +const client = {} as DevnetClient; + +const application = "0x1111111111111111111111111111111111111111"; +const sender = "0x23618e81E3f5cdF7f54C3d65f7FBc0aBf5B21E8f"; + +describe("api/connection", () => { + describe("resolveConnection", () => { + it("should checksum the sender, as addresses read from the chain are", async () => { + const connection = await resolveConnection({ + application, + client, + from: sender.toLowerCase() as `0x${string}`, + projectName: "test", + }); + expect(connection.from).toBe(sender); + }); + + it("should checksum the application", async () => { + const connection = await resolveConnection({ + application: application.toLowerCase() as `0x${string}`, + client, + from: sender, + projectName: "test", + }); + expect(connection.application).toBe(application); + }); + + it("should reject a malformed sender", async () => { + expect( + resolveConnection({ + application, + client, + from: "0x1234", + projectName: "test", + }), + ).rejects.toThrow("is invalid"); + }); + }); +}); diff --git a/apps/cli/tests/unit/api/deposit.test.ts b/apps/cli/tests/unit/api/deposit.test.ts new file mode 100644 index 00000000..8926c0ad --- /dev/null +++ b/apps/cli/tests/unit/api/deposit.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from "bun:test"; +import { parseEther } from "viem"; +import { + DepositError, + InsufficientBalanceError, + InvalidAmountError, + parseAmount, + TokenNotFoundError, +} from "../../../src/api/deposit/index.js"; + +describe("api/deposit", () => { + describe("parseAmount", () => { + it("should take a bigint as base units", () => { + expect(parseAmount(42n, 18)).toBe(42n); + expect(parseAmount(0n, 6)).toBe(0n); + }); + + it("should take a string as display units", () => { + expect(parseAmount("1.5", 18)).toBe(parseEther("1.5")); + expect(parseAmount("2", 6)).toBe(2_000_000n); + }); + + it("should take a string as an integer when there are no decimals", () => { + expect(parseAmount("42", 0)).toBe(42n); + }); + }); + + describe("errors", () => { + it("should all be deposit errors", () => { + expect(new InsufficientBalanceError()).toBeInstanceOf(DepositError); + expect(new InvalidAmountError("too small")).toBeInstanceOf( + DepositError, + ); + expect(new TokenNotFoundError("no token")).toBeInstanceOf( + DepositError, + ); + }); + + it("should have a default message for an insufficient balance", () => { + expect(new InsufficientBalanceError().message).toBe( + "Insufficient balance", + ); + expect( + new InsufficientBalanceError( + "Insufficient balance for token ID 1", + ).message, + ).toBe("Insufficient balance for token ID 1"); + }); + }); +}); diff --git a/apps/cli/tests/unit/api/doctor.test.ts b/apps/cli/tests/unit/api/doctor.test.ts new file mode 100644 index 00000000..67d04b12 --- /dev/null +++ b/apps/cli/tests/unit/api/doctor.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from "bun:test"; +import { + type DoctorCheck, + skipUnmetRequirements, +} from "../../../src/api/doctor.js"; + +const checks = [ + { name: "Docker Engine" }, + { name: "Docker Compose", requires: ["Docker Engine"] }, + { name: "Docker Buildx", requires: ["Docker Engine"] }, + { + name: "Docker RISC-V support", + requires: ["Docker Engine", "Docker Buildx"], + }, + { name: "Cartesi Machine" }, +]; + +const ok = (name: string): DoctorCheck => ({ name, status: "ok" }); +const failed = (name: string): DoctorCheck => ({ + name, + status: "failed", + message: `${name} failed`, +}); + +describe("api/doctor", () => { + describe("skipUnmetRequirements", () => { + it("should keep the results when every requirement is met", () => { + const results = checks.map(({ name }) => ok(name)); + expect(skipUnmetRequirements(checks, results)).toEqual(results); + }); + + it("should skip every check that requires a missing docker", () => { + const results = [ + failed("Docker Engine"), + failed("Docker Compose"), + failed("Docker Buildx"), + failed("Docker RISC-V support"), + ok("Cartesi Machine"), + ]; + expect(skipUnmetRequirements(checks, results)).toEqual([ + failed("Docker Engine"), + { + name: "Docker Compose", + status: "skipped", + message: "requires Docker Engine", + }, + { + name: "Docker Buildx", + status: "skipped", + message: "requires Docker Engine", + }, + { + name: "Docker RISC-V support", + status: "skipped", + message: "requires Docker Engine", + }, + ok("Cartesi Machine"), + ]); + }); + + it("should skip the RISC-V check when buildx is missing", () => { + const results = [ + ok("Docker Engine"), + ok("Docker Compose"), + failed("Docker Buildx"), + failed("Docker RISC-V support"), + ok("Cartesi Machine"), + ]; + expect(skipUnmetRequirements(checks, results)).toEqual([ + ok("Docker Engine"), + ok("Docker Compose"), + failed("Docker Buildx"), + { + name: "Docker RISC-V support", + status: "skipped", + message: "requires Docker Buildx", + }, + ok("Cartesi Machine"), + ]); + }); + + it("should keep a failure whose requirements are met", () => { + const results = [ + ok("Docker Engine"), + ok("Docker Compose"), + ok("Docker Buildx"), + failed("Docker RISC-V support"), + failed("Cartesi Machine"), + ]; + expect(skipUnmetRequirements(checks, results)).toEqual(results); + }); + }); +}); diff --git a/apps/cli/tests/unit/api/send.test.ts b/apps/cli/tests/unit/api/send.test.ts new file mode 100644 index 00000000..f6690b1e --- /dev/null +++ b/apps/cli/tests/unit/api/send.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from "bun:test"; +import { encodeAbiParameters, parseAbiParameters, stringToHex } from "viem"; +import { encodeInput } from "../../../src/api/send.js"; + +describe("api/send", () => { + describe("encodeInput", () => { + it("should return undefined for an empty input", async () => { + expect(await encodeInput(undefined, {})).toBeUndefined(); + expect(await encodeInput("", {})).toBeUndefined(); + }); + + it("should assume hex when the input starts with 0x", async () => { + expect(await encodeInput("0xdeadbeef", {})).toBe("0xdeadbeef"); + }); + + it("should encode as an UTF-8 string by default", async () => { + expect(await encodeInput("hello", {})).toBe(stringToHex("hello")); + }); + + it("should encode as an UTF-8 string when requested", async () => { + expect( + await encodeInput("0xdeadbeef", { encoding: "string" }), + ).toBe(stringToHex("0xdeadbeef")); + }); + + it("should validate a hex encoded input", async () => { + expect( + encodeInput("deadbeef", { encoding: "hex" }), + ).rejects.toThrow("input encoded as hex must start with 0x"); + }); + + it("should encode abi parameters", async () => { + const abiParams = "address,uint256,bool,string"; + const encoded = await encodeInput( + "0x1111111111111111111111111111111111111111,42,true,hello", + { abiParams, encoding: "abi" }, + ); + expect(encoded).toBe( + encodeAbiParameters(parseAbiParameters(abiParams), [ + "0x1111111111111111111111111111111111111111", + 42n, + true, + "hello", + ]), + ); + }); + + it("should encode packed abi parameters", async () => { + const encoded = await encodeInput("42,hello", { + abiParams: "uint256,string", + encoding: "abi-packed", + }); + expect(encoded).toBe( + `0x${42n.toString(16).padStart(64, "0")}${stringToHex("hello").slice(2)}`, + ); + }); + + it("should require abi params for abi encodings", async () => { + expect(encodeInput("42", { encoding: "abi" })).rejects.toThrow( + "Undefined input-abi-params", + ); + }); + + it("should validate the number of abi values", async () => { + expect( + encodeInput("42", { + abiParams: "uint256,string", + encoding: "abi", + }), + ).rejects.toThrow("Not enough values"); + + expect( + encodeInput("42,hello", { + abiParams: "uint256", + encoding: "abi", + }), + ).rejects.toThrow("Too many values"); + }); + + it("should validate abi values", async () => { + expect( + encodeInput("nan", { abiParams: "uint256", encoding: "abi" }), + ).rejects.toThrow("Invalid uint value: nan"); + + expect( + encodeInput("yes", { abiParams: "bool", encoding: "abi" }), + ).rejects.toThrow("Invalid boolean value: yes"); + + expect( + encodeInput("0x00", { abiParams: "address", encoding: "abi" }), + ).rejects.toThrow("Invalid address value: 0x00"); + + expect( + encodeInput("nothex", { abiParams: "bytes", encoding: "abi" }), + ).rejects.toThrow("Invalid bytes value: nothex"); + }); + }); +}); diff --git a/apps/cli/tests/unit/api/types.test.ts b/apps/cli/tests/unit/api/types.test.ts new file mode 100644 index 00000000..3c055456 --- /dev/null +++ b/apps/cli/tests/unit/api/types.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from "bun:test"; +import * as path from "node:path"; +import { listrRenderer, resolveConfig } from "../../../src/api/types.js"; +import { defaultConfig } from "../../../src/config.js"; + +const fixture = (...paths: string[]) => + path.join(__dirname, "..", "config", "fixtures", ...paths); + +describe("api/types", () => { + describe("resolveConfig", () => { + it("should default to the default configuration", () => { + // there is no cartesi.toml at the root of the repository + expect(resolveConfig()).toEqual(defaultConfig()); + }); + + it("should return a configuration object as is", () => { + const config = defaultConfig(); + config.sdk = "my/sdk:1.0.0"; + expect(resolveConfig(config)).toBe(config); + }); + + it("should read a configuration file", () => { + const config = resolveConfig(fixture("drives", "rives.toml")); + expect(Object.keys(config.drives)).toEqual([ + "root", + "doom", + "tetrix", + ]); + expect(config.nvrams).toEqual({}); + }); + + it("should merge a list of configuration files", () => { + const config = resolveConfig([ + fixture("drives", "rives.toml"), + fixture("withdrawal", "config.toml"), + ]); + expect(Object.keys(config.drives)).toEqual([ + "root", + "doom", + "tetrix", + ]); + expect(config.nvrams.accounts?.accountsDrive).toBe(true); + }); + + it("should fail for a configuration file that does not exist", () => { + expect(() => resolveConfig("undefined.toml")).toThrow( + "Config file undefined.toml does not exist", + ); + }); + }); + + describe("listrRenderer", () => { + it("should be silent by default", () => { + expect(listrRenderer()).toBe("silent"); + expect(listrRenderer("silent")).toBe("silent"); + expect(listrRenderer("default")).toBe("default"); + expect(listrRenderer("verbose")).toBe("verbose"); + }); + }); +}); diff --git a/apps/cli/tests/unit/commands/foreclose.test.ts b/apps/cli/tests/unit/commands/foreclose.test.ts index adb34669..667f5ce0 100644 --- a/apps/cli/tests/unit/commands/foreclose.test.ts +++ b/apps/cli/tests/unit/commands/foreclose.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "bun:test"; import { zeroAddress } from "viem"; import { mnemonicToAccount } from "viem/accounts"; -import { resolveForecloseSigner } from "../../../src/commands/foreclose"; +import { resolveForecloseSigner } from "../../../src/foreclose"; import { DEVNET_MNEMONIC } from "../../../src/compose/node"; // account 1 of the devnet mnemonic diff --git a/apps/cli/tests/unit/commands/logs.test.ts b/apps/cli/tests/unit/commands/logs.test.ts index 23e00ead..db22f056 100644 --- a/apps/cli/tests/unit/commands/logs.test.ts +++ b/apps/cli/tests/unit/commands/logs.test.ts @@ -1,9 +1,6 @@ import { describe, expect, it } from "bun:test"; -import { - buildLogsArgs, - createLogsCommand, - selectLogServices, -} from "../../../src/commands/logs"; +import { buildLogsArgs, selectLogServices } from "../../../src/api/logs"; +import { createLogsCommand } from "../../../src/commands/logs"; describe("logs command", () => { // as `docker compose ps --services --all` lists an environment with a diff --git a/apps/cli/tests/unit/commands/refund.test.ts b/apps/cli/tests/unit/commands/refund.test.ts index e10b3a00..fc82930c 100644 --- a/apps/cli/tests/unit/commands/refund.test.ts +++ b/apps/cli/tests/unit/commands/refund.test.ts @@ -3,7 +3,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { parseInputIndex } from "../../../src/base"; -import { getInputData } from "../../../src/commands/refund"; +import { getInputData } from "../../../src/refund"; import { application } from "../fixtures"; describe("parseInputIndex", () => { diff --git a/apps/cli/tests/unit/commands/withdraw.test.ts b/apps/cli/tests/unit/commands/withdraw.test.ts index fc200f6c..d261e5da 100644 --- a/apps/cli/tests/unit/commands/withdraw.test.ts +++ b/apps/cli/tests/unit/commands/withdraw.test.ts @@ -6,7 +6,7 @@ import { replayLastFinalizedEpoch, replayStorePath, type WithdrawIo, -} from "../../../src/commands/withdraw"; +} from "../../../src/withdraw"; import { account, application } from "../fixtures"; const root = toHex(1, { size: 32 }); diff --git a/apps/cli/tsconfig.build.json b/apps/cli/tsconfig.build.json new file mode 100644 index 00000000..3486907a --- /dev/null +++ b/apps/cli/tsconfig.build.json @@ -0,0 +1,15 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "emitDeclarationOnly": true, + "allowImportingTsExtensions": false, + "outDir": "dist/types", + "rootDir": "src" + }, + // only the library entrypoint and what it imports, the commands are not part + // of the public API and are typed by the CLI build + "files": ["src/lib.ts"], + "include": [] +} diff --git a/bun.lock b/bun.lock index a3cbcea1..473ab1ea 100644 --- a/bun.lock +++ b/bun.lock @@ -13,10 +13,16 @@ }, "apps/cli": { "name": "@cartesi/cli", - "version": "2.0.0-alpha.41", + "version": "2.0.0-alpha.42", "bin": { "cartesi": "./dist/index.js", }, + "dependencies": { + "execa": "^10.0.1", + "semver": "^7.8.5", + "smol-toml": "^1.9.0", + "viem": "^2.57.3", + }, "devDependencies": { "@cartesi/wagmi-plugin": "1.0.0-alpha.9", "@commander-js/extra-typings": "^15.0.0", @@ -33,7 +39,6 @@ "cli-table3": "^0.6.5", "commander": "^15.0.0", "dotenv": "^18.0.5", - "execa": "^10.0.1", "fs-extra": "^11.4.1", "get-port": "^7.2.0", "listr2": "^11.1.1", @@ -42,10 +47,7 @@ "ora": "^9.4.1", "p-retry": "^8.0.1", "rimraf": "^6.1.3", - "semver": "^7.8.5", - "smol-toml": "^1.9.0", "typescript": "^7.0.2", - "viem": "^2.57.3", "yaml": "^2.9.1", }, }, @@ -787,7 +789,7 @@ "parse-ms": ["parse-ms@4.0.0", "", {}, "sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw=="], - "path-key": ["path-key@4.0.0", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="], + "path-key": ["path-key@2.0.1", "", {}, "sha512-fEHGKCSmUSDPv4uoj8AlD+joPlq3peND+HRYyxFz4KPw4z926S/b8rIuFs2FYJg3BwsxJf6A9/3eIdLaYC+9Dw=="], "path-parse": ["path-parse@1.0.7", "", {}, "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw=="], @@ -1051,8 +1053,6 @@ "cli-truncate/string-width": ["string-width@8.3.0", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ=="], - "cross-spawn/path-key": ["path-key@2.0.1", "", {}, "sha512-fEHGKCSmUSDPv4uoj8AlD+joPlq3peND+HRYyxFz4KPw4z926S/b8rIuFs2FYJg3BwsxJf6A9/3eIdLaYC+9Dw=="], - "cross-spawn/semver": ["semver@5.7.2", "", { "bin": { "semver": "bin/semver" } }, "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g=="], "fast-json-stringify/ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="], @@ -1069,6 +1069,8 @@ "npm-run-all/chalk": ["chalk@2.4.2", "", { "dependencies": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ=="], + "npm-run-path/path-key": ["path-key@4.0.0", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="], + "ora/chalk": ["chalk@5.6.2", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="], "ora/string-width": ["string-width@8.3.0", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ=="],