diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bff5f21..2d19198 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -185,6 +185,7 @@ jobs: bash -x start_ocean.sh --with-typesense 2>&1 > start_ocean.log & - name: Install dependencies run: npm ci + - run: npm run build - run: docker image ls - name: Wait for node to be ready run: | diff --git a/CLAUDE.md b/CLAUDE.md index 92b3eb2..1229045 100755 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -7,7 +7,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co `ocean-cli` (npm package `@oceanprotocol/cli`, version 2.0.0; installs a `bin` named `ocean-cli`) is a TypeScript CLI that wraps the Ocean Protocol JavaScript library (`@oceanprotocol/lib`, a.k.a. ocean.js) to publish, edit, consume/download, and run compute-to-data (C2D) on assets, plus manage escrow payments, access lists, persistent-storage buckets, auth tokens, and admin node logs. It talks to an **Ocean Node** (the single service that replaced the old standalone Provider and Aquarius apps — it does metadata caching, indexing, encryption, ordering, and compute) and to an EVM chain via an RPC endpoint. -The package is pure ESM (`"type": "module"` in `package.json`). All relative imports MUST carry an explicit `.js` extension even though the source is `.ts` (e.g. `import { Commands } from "./commands.js"`). Node 22 is expected (`.nvmrc` = `22.23.1`; CI pins the same). The dev toolchain sets the floor: `eslint@10` needs `>=22.13.0` and `release-it@21` needs `>=22.21.0`, so an older 22.x will fail `npm run lint` / `npm run release` even though `engines.node` is only `>=22` (that bound is for consumers of the published package, who get `dependencies` only). +The package is pure ESM (`"type": "module"` in `package.json`). All relative imports MUST carry an explicit `.js` extension even though the source is `.ts` (e.g. `import { Commands } from "./commands.js"`). Node 24 is expected for local dev (`.nvmrc` = `24`). CI runs the build, lint, and system-test jobs on a matrix of Node `22`, `24`, and `26` (with several steps pinned to `24`), while `publish.yml` pins `22.23.1`. The dev toolchain sets the floor: `eslint@10` needs `>=22.13.0` and `release-it@21` needs `>=22.21.0`, so a Node older than those will fail `npm run lint` / `npm run release` even though `engines.node` is only `>=22` (that bound is for consumers of the published package, who get `dependencies` only). ## Commands @@ -78,8 +78,9 @@ All registered in `src/cli.ts` via Commander (`commander` v13). Every command su - Assets: `getDDO`, `publish`, `publishAlgo`, `editAsset` (alias `edit`), `download`, `allowAlgo`. - Compute: `startCompute`, `startFreeCompute`, `getComputeEnvironments` (alias `getC2DEnvs`), `computeStreamableLogs`, `stopCompute`, `getJobStatus`, `downloadJobResults`. - Tokens/auth: `mintOcean`, `generateAuthToken`, `invalidateAuthToken`. -- Escrow: `depositEscrow`, `getUserFundsEscrow`, `withdrawFromEscrow`, `authorizeEscrow`, `getAuthorizationsEscrow`. +- Escrow: `depositEscrow`, `getUserFundsEscrow`, `withdrawFromEscrow`, `authorizeEscrow`, `getAuthorizationsEscrow`, `getEscrowInfo` (alias `escrowInfo`). - Access lists: `createAccessList`, `addToAccessList`, `checkAccessList`, `removeFromAccessList`. +- Subsidy providers: `getSubsidyProviders` (alias `subsidyProviders`), `getSubsidyStatus` (alias `subsidyStatus`). Provider addresses come **only** from the node's status (`nodeSubsidyInfo` in `nodeConnection.ts`), never from bundled config — a node may not support subsidies. `getSubsidyStatus` uses the ocean.js `SubsidyView`/`OPFSubsidyProvider`/`OneTimeSubsidyProvider` wrappers. Compute/service commands (`startCompute`, `startService`, `extendService`) also take `--subsidyProviders ` (tri-state: omit → node default, `none`/empty → `[]`, CSV → those; parsed by `parseSubsidyProviders` in `helpers.ts`). `startFreeCompute` ignores it. - Persistent storage buckets: `createBucket`, `addFileToBucket`, `listBuckets`, `listFilesInBucket`, `getFileObject`, `deleteFile`. - Admin: `downloadNodeLogs`. - Node selection: `setNode` (alias `useNode`), `getNode` (alias `currentNode`). @@ -158,7 +159,7 @@ uses directly. `destroyProviders()` tears providers down on exit (next to `stopP - `createAssetUtil(...)` wraps ocean.js `createAsset` (used by publish/publishAlgo and the interactive publisher). It resolves the active ERC20 template (`calculateActiveTemplateIndex` reads and `JSON.parse`s the `@oceanprotocol/contracts` `ERC20Template.json` ABI, resolved via `createRequire`/`require.resolve` so it works from any cwd — e.g. a global install — not a cwd-relative `node_modules` path), and for **Oasis Sapphire** (`config.sdk === 'oasis'`) wraps the signer with `wrapEthersSigner` from `@oasisprotocol/sapphire-ethers-v6` (`getSignerAccordingSdk`; sapphire-paratime v2 moved its ethers integration into that package, and it throws `SignerHasNoProviderError` for a provider-less signer) and deploys an allow access list before creating the asset. - `updateAssetMetadata(...)` — used by `editAsset`, `allowAlgo`, `disallowAlgo` and the interactive publisher. It validates the DDO via `aquarius.validate`, then either `ProviderInstance.encrypt`s the DDO (flags = 2) or hexlifies raw JSON (flags = 0) depending on the `encryptDDO` flag, then calls `nft.setMetadata`. - `handleComputeOrder(...)` — the ordering state machine used in compute: validOrder + no fees → reuse as-is; validOrder + fees → `datatoken.reuseOrder` paying only provider fees; no order → `orderAsset` (pay 1 datatoken + fees). Approves provider-fee tokens first when the fee amount > 0. -- `resolveComputeInputs(...)` + `parseComputeInput(...)` — parse the datasets/algo CLI strings (DID | JSON object | array | mixed | legacy `[did:a,did:b]`), resolve DID entries through `aquarius.waitForIndexer`, pass raw `fileObject` entries through (aligned with a `null` DDO slot), and pick `providerURI` from the first DID-based DDO's `serviceEndpoint` (else fall back to `NODE_URL`). +- `resolveComputeInputs(...)` + `parseComputeInput(...)` — parse the datasets/algo CLI strings (DID | JSON object | array | mixed | legacy `[did:a,did:b]`), resolve DID entries through `aquarius.waitForIndexer`, pass raw entries through (a `fileObject`, or for an algorithm inline `meta.rawcode`; aligned with a `null` DDO slot), and pick `providerURI` from the first DID-based DDO's `serviceEndpoint` (else fall back to `NODE_URL`). - `fixAndParseProviderFees(...)` — regex-based repair of the stringified provider-initialize response that is round-tripped from `initializeCompute` into `computeStart` (adds quotes to keys, DIDs, hex addresses). Fragile by design; touch carefully. - `getIndexingWaitSettings()` — reads the `INDEXING_*` env vars. - Signing/encryption is always done via the `Signer` and `ProviderInstance` from ocean.js; the CLI never handles raw keys beyond constructing the `ethers.Wallet`. @@ -175,8 +176,8 @@ uses directly. `destroyProviders()` tears providers down on exit (next to `stopP The `startCompute` **action in `cli.ts`** orchestrates a two-phase flow (not a single `Commands` method). It first resolves the **payment/escrow chain** with `resolveChainId(options.chainId)` (`--chainId` flag → default chain → error) and passes it as an explicit trailing param to both compute methods: 1. `commands.initializeCompute([...], paymentChainId)` — resolves inputs, fetches compute envs (`ProviderInstance.getComputeEnvironments`), matches the env by id, validates that the **payment chain** is in both `computeEnv.fees` and the RPC registry, plus paymentToken/resources/maxJobDuration (capping to `env.maxJobDuration`), and returns the provider `initializeCompute` response (payment + provider fees). Signs against the payment chain (`signerFor(paymentChainId)`). -2. Prints payment details, converts amount with `unitsToAmount`, and asks for confirmation unless `--accept true` (hard error on non-TTY). -3. `commands.computeStart([...], paymentChainId)` — **per-asset ordering**: each DID-based dataset/algorithm DDO is ordered on **its own** chain via a per-chain `{ signer, config, Datatoken }` context (`orderCtxFor(ddo.chainId)`, memoized within the call), replacing the old single `Datatoken` on the signer's one chain. Escrow funds (`EscrowContract.verifyFundsForEscrowPayment`), deposit/authorize, and `ProviderInstance.computeStart` all run on the **payment chain** (`paymentSigner` = `signerFor(paymentChainId)`), independent of where the assets live (C2D V2: all datasets passed together in `assets`; the old `additionalDatasets` param is unused). Prints `JobID` and the agreement id (`payment.lockTx`). +2. Prints payment details, converts amount with `unitsToAmount`, quotes the prepaid subsidy with `commands.computePrefundedUnits(subsidyProviders, lockUnits)` (it reuses the env/node/resources that `initializeCompute` stored in `computeQuoteCtx`), prints `total job cost` / `prepaid subsidy covers` / `you pay`, and asks for confirmation unless `--accept true` (hard error on non-TTY). The quoted figure is passed to `computeStart` as its 4th param so the confirmed share is the funded share. +3. `commands.computeStart([...], paymentChainId)` — **per-asset ordering**: each DID-based dataset/algorithm DDO is ordered on **its own** chain via a per-chain `{ signer, config, Datatoken }` context (`orderCtxFor(ddo.chainId)`, memoized within the call), replacing the old single `Datatoken` on the signer's one chain. Escrow funds (`EscrowContract.verifyFundsForEscrowPayment`), deposit/authorize, and `ProviderInstance.computeStart` all run on the **payment chain** (`paymentSigner` = `signerFor(paymentChainId)`), independent of where the assets live (C2D V2: all datasets passed together in `assets`; the old `additionalDatasets` param is unused). Prints `JobID` and the agreement id (`payment.lockTx`). **Prepaid subsidy:** before funding, `prefundedUnitsForJob` calls ocean.js `estimateJobSubsidy` (lib ≥ 10.1.0; node status + image gate + per-provider quotes) and the pure `prefundedLockUnits()` helper (`helpers.ts`) turns the result into the pre-funded base units for the `--subsidyProviders` tri-state (omitted → the node-set projection; a list → only the named providers, since the node *replaces* its set; `[]` → 0). Only the **payer share** (`lock − prefunded`) is passed to `verifyFundsForEscrowPayment` and to the balance/authorize follow-up, so a fully sponsored job deposits nothing; the lib call is still made with `"0"` because it also creates/repairs the authorization the node needs. Any estimate failure falls back to full payer funding. `startService`/`extendService` use the same method with `jobType` 2 (image gate predicate: a non-empty entrypoint or cmd), passed as a `quotePrefunded` callback into `quoteServicePayerShare` (`serviceHelpers.ts`, read-only). The order is quote → `confirmServicePayment` → `fundServiceEscrow`, so no deposit/authorize is sent before the user confirms; `fundServiceEscrow` passes **human** units for both lib amounts. **Multi-chain compute (category d).** A single job may mix datasets/algorithm on different chains and pay/escrow on yet another. `--chainId` is **only** the payment chain; asset chains are always taken from each DDO, never passed by the user. `Commands.ensureComputeChainsRegistered(paymentChainId, ddos, algoDdo)` validates up front — via the pure `computeJobChainIds()` helper (`helpers.ts`) — that every chain the job touches (payment + each DID asset/algo chain) has a registered RPC, and errors listing the missing chain(s) before any paid order. In the common **single-chain** case every asset shares the payment chain, so ordering/escrow/`computeStart` are equivalent to before. @@ -184,7 +185,7 @@ The `startCompute` **action in `cli.ts`** orchestrates a two-phase flow (not a s ### Escrow, access lists, persistent storage, auth, node logs -- **Escrow** (`EscrowContract` from ocean.js, address from `address.json`): `depositEscrow` approves then deposits; `withdrawFromEscrow` checks balance first; `authorizeEscrow` sets per-payee lock limits; `getUserFundsEscrow` / `getAuthorizationsEscrow` read state. +- **Escrow** (`EscrowContract` from ocean.js, address from `ConfigHelper` via `requireAddress(chainId, "escrow", …)`): `depositEscrow` approves then deposits; `withdrawFromEscrow` checks balance first; `authorizeEscrow` sets per-payee lock limits; `getUserFundsEscrow` / `getAuthorizationsEscrow` read state. **Escrow v2** (ocean.js escrow-v2 release / contracts `^3.2.0-rc.0`): `authorize` now **always overwrites** the on-chain record (it no longer no-ops when one exists — that is what makes renew/shorten/revoke reachable) and takes a trailing `expiryTimestamp` (unix seconds; `0` = indefinite, a past value revokes), surfaced as `authorizeEscrow --expiry`; `authorizeEscrowPayee` therefore dropped its old "already authorized → null tx" branch. `getAuthorizationsEscrow` prints the new 7th tuple field `expiryTimestamp`, and reads `Current Locked Amount` as **payer-funded only** (`P`); provider-sponsored tokens (`S`) live in a separate bucket. `getEscrowInfo [token]` is a read-only diagnostic: it reads `version`/`escrowKind`/`maxSponsorsPerLock` directly and feature-detects `isEscrowLockSubsidy`/`isEscrowEnterprise` via ERC-165 (`supportsInterface`), plus `getSponsoredTotal`/`getReclaimable` and the enterprise `feeCollector`/`isTokenAllowed` when a token is given; it degrades gracefully against a legacy escrow. The CLI never creates locks itself (the node does at compute/service start), so `createLock`/`reLock`'s new `jobType`/`subsidyProviders` params are only relevant through the node; `--subsidyProviders` on `startCompute`/`startService`/`extendService` is what feeds pre-funded sponsorship. - **Access lists** (`AccesslistFactory` / `AccessListContract` from ocean.js): `createAccessList` deploys via the factory (address from `address.json`); membership is an ERC721 balance — `addToAccessList` mints/`batchMint`s NFTs, `checkAccessList` tests `balance > 0`, `removeFromAccessList` burns each token via `tokenOfOwnerByIndex`. - **Persistent storage** (`ProviderInstance.*PersistentStorage*`): bucket CRUD + file upload/list/get/delete. `addFileToBucket` streams the file with a progress logger and a 30-minute (`UPLOAD_TIMEOUT_MS`) abort timeout; buckets can be gated by an access-list address. - **Auth tokens**: `generateAuthToken` / `invalidateAuthToken` via `ProviderInstance`. diff --git a/README.md b/README.md index 255d4ea..d7f5a75 100644 --- a/README.md +++ b/README.md @@ -178,6 +178,7 @@ ocean-cli computeStreamableLogs # or --job - `--accept true` auto-confirms payment (mandatory when stdin is not a TTY); `false` prompts. - `--services` (comma-separated dataset service ids, mapped by position to the datasets) and `--algo-service` (the algorithm's service id) are optional; the first available service is used when omitted. - `--output` is an optional stringified JSON remote-storage backend for results (S3, FTP, URL, Arweave, IPFS); omitted means results stay on the node's disk. Example: `'{"remoteStorage":{"type":"s3","s3Access":{"endpoint":"https://s3.amazonaws.com","region":"us-east-1","bucket":"my-results","objectKey":"jobs/result.tar","accessKeyId":"AKIA...","secretAccessKey":"..."}}}'`. +- `--subsidyProviders` optionally picks which subsidy providers back the escrow claim (see [Subsidy providers](#subsidy-providers)). `startFreeCompute` takes the same dataset/algo/`--services`/`--algo-service`/`--output` arguments, targets a free environment and does no ordering or payment. @@ -237,10 +238,32 @@ ocean-cli getUserFundsEscrow 0xToken ocean-cli withdrawFromEscrow 0xToken 50 ocean-cli authorizeEscrow 0xToken 0xPayee 1000 3600 10 # token payee maxLockedAmount maxLockSeconds maxLockCounts ocean-cli getAuthorizationsEscrow 0xToken 0xPayee +ocean-cli getEscrowInfo [0xToken] # alias escrowInfo; read-only capability report ``` All accept `--chainId`. `authorizeEscrow` flags: `--token --payee --maxLockedAmount --maxLockSeconds --maxLockCounts`. +**Escrow v2.** The escrow contracts support **lock-time pre-funded sponsorship** (a subsidy provider can back part or all of a lock at creation, so a fully-sponsored user can transact with no deposit) and **authorization expiry** (a payee key can be time-boxed or revoked). The CLI reflects this: + +- `authorizeEscrow` takes `-e, --expiry ` (`0` = indefinite, default). Re-running it **overwrites** the record (renew/shorten), and an `--expiry` in the past **revokes** it; claim and cancel are never gated by expiry, so existing locks stay claimable. Example — revoke then re-grant for 1h: `ocean-cli authorizeEscrow 0xToken 0xPayee 1000 3600 10 --expiry 1` then `... --expiry $(( $(date +%s) + 3600 ))`. +- `getAuthorizationsEscrow` prints the authorization's `expiryTimestamp`, and `getEscrowInfo [token]` reports the escrow's capabilities (version, `escrowKind`, `IEscrowLockSubsidy`/`IEscrowEnterprise` support, `maxSponsorsPerLock`) via ERC-165, plus the sponsored-bucket total and your reclaimable amount when a token is given. +- Reading state: `getUserFunds().locked` and `Current Locked Amount` now count only the payer's **own** locked funds; provider-sponsored tokens live in a separate sponsored bucket (`getEscrowInfo `). + +These commands require the Escrow v2 deployment; they degrade gracefully against a legacy escrow. + +### Subsidy providers + +Subsidy providers are on-chain contracts that sponsor part or all of a job's cost (a subsidy released back to the payer, plus an optional bonus paid to the node), subject to allow-lists, job-type restrictions and per-period caps. **The Ocean Node is the source of truth for which subsidy providers are usable** (a node may not support them at all), so the CLI reads provider addresses from the node's status, never from bundled contract addresses. + +```bash +ocean-cli getSubsidyProviders # alias subsidyProviders; per-chain providers the node advertises +ocean-cli getSubsidyStatus 0xToken # alias subsidyStatus; your limits / remaining credit +``` + +- `getSubsidyStatus` discovers the provider contract(s) from the node, then prints each one's kind, per-window buckets (limit / used / remaining / reset), claimable amount, contract balance and your eligibility. Flags: `--token --chainId --node --jobType --amount --subsidy 0xA[,0xB]`. `--node ` queries a specific Ocean Node (default: the active node) and uses that node's on-chain address for the `isNodeAllowed` check; adding `--jobType` and `--amount` also prints a subsidy quote (`{subsidy, bonus}`). `--subsidy` depends on the node's provider filter: with the filter **off** the node accepts any provider named per request, so the listed addresses are queried as-is (even when the node advertises none; the ones it does not advertise are flagged as not node defaults); with the filter **on** the list is narrowed to what the node advertises. +- `startCompute`, `startService` and `extendService` take `--subsidyProviders `: omit for the node's defaults, `none` (or empty) to claim with **no** subsidy, or `0xA,0xB` to claim against exactly those contracts. `startFreeCompute` ignores it (a free job does no escrow claim). +- **Zero-deposit paid compute.** Before a paid `startCompute` the CLI asks the subsidy providers how much of the job they would **pre-fund** at lock time and deposits only your share; the payment prompt shows the total cost and what you pay. A fully sponsored job needs no payment tokens **for the compute lock** — only gas for a single `authorize` transaction, which lets the node create the lock (with a ceiling of `0`, i.e. the lock can never take your own funds). Refund-only providers pre-fund nothing, so you still front the full cost and are reimbursed at claim. Sponsorship and that ceiling cover the compute lock only: each DID-based dataset or algorithm is still ordered on its own chain before the job starts, which can cost a datatoken and/or provider fees (plus gas) that no subsidy covers. The quote is advisory: if a provider's budget runs out before the node creates the lock, the node rejects the job and nothing is locked or deposited for it, but orders already placed for its assets are not reversed. `startService` and `extendService` apply the same rule to the service lock. + ### Access lists ```bash @@ -286,60 +309,63 @@ ocean-cli mintOcean [--token 0xOcean] [--chainId 8996] # mint test Ocean tok ## Command reference -50 commands, as registered in `src/cli.ts`. `` is required, `[x]` optional. A named option **overrides** its positional when both are passed, but a required `` must still be given positionally (passing only its option fails with *missing required argument* — this affects e.g. `publish`, `startCompute`, `startFreeCompute`); optional `[x]` positionals may instead be supplied as named options. Commands with no Options entry (e.g. `downloadJobResults`) are positional-only. ` --help` is authoritative. +53 commands, as registered in `src/cli.ts`. `` is required, `[x]` optional. A named option **overrides** its positional when both are passed. Every positional that has a matching named option is declared `[x]`, so it can be supplied **either** positionally **or** by its option alone (the command itself errors if a needed value is missing from both). The remaining `` positionals have no named-option equivalent and must be given positionally — these are `setNodeEnv`, `startService`, `downloadJobResults`, `restartService`, and the bucket commands (`addFileToBucket`, `listFilesInBucket`, `getFileObject`, `deleteFile`). Commands with no Options entry are positional-only. ` --help` is authoritative. | Command | Aliases | Arguments | Options | | --- | --- | --- | --- | | `help` | `h` | | | -| `setNode` | `useNode` | `` | `-n, --node` | +| `setNode` | `useNode` | `[nodeUrl]` | `-n, --node` | | `setNodeEnv` | `useNodeEnv` | `` | | | `getNode` | `currentNode` | | | -| `addChain` | `addRpc` | ` [rpcUrl...]` | `-c, --chainId`, `-u, --url` | -| `removeChain` | `removeRpc` | `` | `-c, --chainId` | +| `addChain` | `addRpc` | `[chainId] [rpcUrl...]` | `-c, --chainId`, `-u, --url` | +| `removeChain` | `removeRpc` | `[chainId]` | `-c, --chainId` | | `listChains` | `getRpcs`, `chains` | | | -| `setChain` | `useChain` | `` | `-c, --chainId` | +| `setChain` | `useChain` | `[chainId]` | `-c, --chainId` | | `getChain` | `currentChain` | | | -| `getDDO` | | `` | `-d, --did` | -| `publish` | | `` | `-f, --file`, `-e, --encrypt [bool]` (default true) | -| `publishAlgo` | | `` | `-f, --file`, `-e, --encrypt [bool]` | -| `editAsset` | `edit` | ` ` | `-d, --did`, `-f, --file`, `-e, --encrypt [bool]` | -| `download` | | ` [folder] [serviceId]` | `-d, --did`, `-f, --folder` (default `.`), `-s, --service` | -| `allowAlgo` | | ` ` | `-d, --dataset`, `-a, --algo`, `-e, --encrypt [bool]` | -| `startCompute` | | `[datasets] [algo] [env] [maxJobDuration] [paymentToken] [resources] [output] [serviceIds] [algoServiceId]` | `-d, --datasets`, `-a, --algo`, `-e, --env`, `--maxJobDuration`, `-t, --token`, `--resources`, `--chainId`, `--accept`, `-o, --output`, `-s, --services`, `-x, --algo-service` | +| `getDDO` | | `[did]` | `-d, --did` | +| `publish` | | `[file]` | `-f, --file`, `-e, --encrypt [bool]` (default true) | +| `publishAlgo` | | `[file]` | `-f, --file`, `-e, --encrypt [bool]` | +| `editAsset` | `edit` | `[did] [file]` | `-d, --did`, `-f, --file`, `-e, --encrypt [bool]` | +| `download` | | `[did] [folder] [serviceId]` | `-d, --did`, `-f, --folder` (default `.`), `-s, --service` | +| `allowAlgo` | | `[datasetDid] [algoDid]` | `-d, --dataset`, `-a, --algo`, `-e, --encrypt [bool]` | +| `startCompute` | | `[datasets] [algo] [env] [maxJobDuration] [paymentToken] [resources] [output] [serviceIds] [algoServiceId]` | `-d, --datasets`, `-a, --algo`, `-e, --env`, `--maxJobDuration`, `-t, --token`, `--resources`, `--chainId`, `--accept`, `-o, --output`, `-s, --services`, `-x, --algo-service`, `--subsidyProviders` | | `startFreeCompute` | | `[datasets] [algo] [env] [output] [serviceIds] [algoServiceId]` | `-d, --datasets`, `-a, --algo`, `-e, --env`, `-o, --output`, `-s, --services`, `-x, --algo-service`, `--chainId` | | `getComputeEnvironments` | `getC2DEnvs` | `[node]` | `-n, --node` | | `searchComputeResources` | `findComputeNodes` | | `--cpu --ram --disk --gpu --gpu-model --resource --free --paid --both --chain --token --max-price --duration --order-by` | -| `computeStreamableLogs` | | `` | `-j, --job` | -| `stopCompute` | | ` ` | `-d, --dataset`, `-j, --job`, `-a, --agreement` | -| `getJobStatus` | | ` [agreementId]` | `-d, --dataset`, `-j, --job`, `-a, --agreement` | +| `computeStreamableLogs` | | `[jobId]` | `-j, --job` | +| `stopCompute` | | `[datasetDid] [jobId] [agreementId]` | `-d, --dataset`, `-j, --job`, `-a, --agreement` | +| `getJobStatus` | | `[datasetDid] [jobId] [agreementId]` | `-d, --dataset`, `-j, --job`, `-a, --agreement` | | `downloadJobResults` | | ` [folder]` | | | `getServiceTemplates` | `serviceTemplates` | `[node]` | `-n, --node` | -| `startService` | | ` ` | `--template`, `-i, --image`, `--tag`, `--checksum`, `--dockerfile`, `--additional-docker-files`, `--cmd`, `--entrypoint`, `-p, --ports`, `-r, --resources`, `-u, --user-data`, `--user-data-file`, `--accept`, `--wait`, `--timeout`, `--chainId` | +| `startService` | | ` ` | `--template`, `-i, --image`, `--tag`, `--checksum`, `--dockerfile`, `--additional-docker-files`, `--cmd`, `--entrypoint`, `-p, --ports`, `-r, --resources`, `-u, --user-data`, `--user-data-file`, `--accept`, `--wait`, `--timeout`, `--chainId`, `--subsidyProviders` | | `getServiceStatus` | `myServices` | `[serviceId]` | `-s, --service`, `-v, --verbose` | | `getServices` | `listServices` | `[node]` | `-n, --node`, `--status`, `--include-all`, `--from`, `-v, --verbose` | -| `serviceLogs` | `computeServiceLogs` | `` | `-s, --service`, `--since` | -| `extendService` | | ` [paymentToken]` | `-s, --service`, `--duration`, `-t, --token`, `--accept`, `--chainId` | +| `serviceLogs` | `computeServiceLogs` | `[serviceId]` | `-s, --service`, `--since` | +| `extendService` | | `[serviceId] [additionalDuration] [paymentToken]` | `-s, --service`, `--duration`, `-t, --token`, `--accept`, `--chainId`, `--subsidyProviders` | | `restartService` | | `` | `-u, --user-data`, `--user-data-file`, `--cmd`, `--entrypoint`, `--image`, `--tag`, `--checksum`, `--dockerfile`, `--additional-docker-files`, `--wait`, `--timeout` | -| `stopService` | | `` | `-s, --service` | +| `stopService` | | `[serviceId]` | `-s, --service` | | `mintOcean` | | | `-t, --token`, `--chainId` | | `generateAuthToken` | | | | -| `invalidateAuthToken` | | `` | `-t, --token` | -| `depositEscrow` | | ` ` | `-t, --token`, `-a, --amount`, `--chainId` | -| `getUserFundsEscrow` | | `` | `-t, --token`, `--chainId` | -| `withdrawFromEscrow` | | ` ` | `-t, --token`, `-a, --amount`, `--chainId` | -| `authorizeEscrow` | | ` ` | `-t, --token`, `-p, --payee`, `-m, --maxLockedAmount`, `-s, --maxLockSeconds`, `-c, --maxLockCounts`, `--chainId` | -| `getAuthorizationsEscrow` | | ` ` | `-t, --token`, `-p, --payee`, `--chainId` | -| `createAccessList` | | ` [initialUsers] [transferable]` | `-n, --name`, `-s, --symbol`, `-u, --initial-users`, `-t, --transferable`, `--chainId` | -| `addToAccessList` | | `
` | `-a, --address`, `-u, --users`, `--chainId` | -| `checkAccessList` | | `
` | `-a, --address`, `-u, --users`, `--chainId` | -| `removeFromAccessList` | | `
` | `-a, --address`, `-u, --users`, `--chainId` | +| `invalidateAuthToken` | | `[token]` | `-t, --token` | +| `depositEscrow` | | `[token] [amount]` | `-t, --token`, `-a, --amount`, `--chainId` | +| `getUserFundsEscrow` | | `[token]` | `-t, --token`, `--chainId` | +| `withdrawFromEscrow` | | `[token] [amount]` | `-t, --token`, `-a, --amount`, `--chainId` | +| `authorizeEscrow` | | `[token] [payee] [maxLockedAmount] [maxLockSeconds] [maxLockCounts]` | `-t, --token`, `-p, --payee`, `-m, --maxLockedAmount`, `-s, --maxLockSeconds`, `-c, --maxLockCounts`, `-e, --expiry`, `--chainId` | +| `getAuthorizationsEscrow` | | `[token] [payee]` | `-t, --token`, `-p, --payee`, `--chainId` | +| `getEscrowInfo` | `escrowInfo` | `[token]` | `-t, --token`, `--chainId` | +| `getSubsidyProviders` | `subsidyProviders` | | `--chainId` | +| `getSubsidyStatus` | `subsidyStatus` | `[token]` | `-t, --token`, `--chainId`, `--node`, `--jobType`, `--amount`, `--subsidy` | +| `createAccessList` | | `[name] [symbol] [initialUsers] [transferable]` | `-n, --name`, `-s, --symbol`, `-u, --initial-users`, `-t, --transferable`, `--chainId` | +| `addToAccessList` | | `[address] [users]` | `-a, --address`, `-u, --users`, `--chainId` | +| `checkAccessList` | | `[address] [users]` | `-a, --address`, `-u, --users`, `--chainId` | +| `removeFromAccessList` | | `[address] [users]` | `-a, --address`, `-u, --users`, `--chainId` | | `createBucket` | | `[accessListAddress]` | | | `addFileToBucket` | | ` [fileName]` | | | `listBuckets` | | | `-o, --owner` | | `listFilesInBucket` | | `` | | | `getFileObject` | | ` ` | | | `deleteFile` | | ` ` | | -| `downloadNodeLogs` | | ` [last] [from] [to]` | `-o, --output`, `-l, --last`, `-f, --from`, `-t, --to`, `-m, --maxLogs` | +| `downloadNodeLogs` | | `[output] [last] [from] [to]` | `-o, --output`, `-l, --last`, `-f, --from`, `-t, --to`, `-m, --maxLogs` | ## Sample metadata files diff --git a/package-lock.json b/package-lock.json index 96c72e3..31e629d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,9 +10,9 @@ "license": "Apache-2.0", "dependencies": { "@oasisprotocol/sapphire-ethers-v6": "^6.0.1", - "@oceanprotocol/contracts": "^2.9.0", + "@oceanprotocol/contracts": "^3.2.0-rc.1", "@oceanprotocol/ddo-js": "^1.0.0", - "@oceanprotocol/lib": "^9.0.0", + "@oceanprotocol/lib": "^10.1.0", "chalk": "^6.0.1", "commander": "^15.0.0", "enquirer": "^2.4.1", @@ -1211,32 +1211,32 @@ "license": "MIT" }, "node_modules/@libp2p/bootstrap": { - "version": "12.0.29", - "resolved": "https://registry.npmjs.org/@libp2p/bootstrap/-/bootstrap-12.0.29.tgz", - "integrity": "sha512-HJqRyr75io10F/zaJCMGhrdOi7an4bJmgw12DLrBR/hPteeFAIZ4bXeiV+GNxw5vmRJoEpfUTVzIwPTsRJMViw==", + "version": "12.0.32", + "resolved": "https://registry.npmjs.org/@libp2p/bootstrap/-/bootstrap-12.0.32.tgz", + "integrity": "sha512-MpGPeijiYP7a//EsbcrWAuWjHNoGhIqv4ONcGXkuTgSCJbJVWpZrR2uA+I/UW7wW0UB4a3PmHJWAd4klMgZqlA==", "license": "Apache-2.0 OR MIT", "dependencies": { - "@libp2p/interface": "^3.2.5", - "@libp2p/interface-internal": "^3.1.11", - "@libp2p/peer-id": "^6.0.14", + "@libp2p/interface": "^3.3.0", + "@libp2p/interface-internal": "^3.1.13", + "@libp2p/peer-id": "^6.0.15", "@multiformats/multiaddr": "^13.0.3", "@multiformats/multiaddr-matcher": "^3.0.2", "main-event": "^1.0.1" } }, "node_modules/@libp2p/circuit-relay-v2": { - "version": "4.2.11", - "resolved": "https://registry.npmjs.org/@libp2p/circuit-relay-v2/-/circuit-relay-v2-4.2.11.tgz", - "integrity": "sha512-q47qWuJxmNocAX4oRAUWpp2d56aiymsih9ORCkBdQGUkBzynPyBsucvCX5bnF8tb80Ji5wBHl4jCa1DmrW1T1A==", + "version": "4.2.13", + "resolved": "https://registry.npmjs.org/@libp2p/circuit-relay-v2/-/circuit-relay-v2-4.2.13.tgz", + "integrity": "sha512-AGEzj72W7Ae5eizaM+HeDzJBR28zK4yYp4BYvUOHQViT62W97FIITo/9Gc5rlkKti+gJJAurBm3cHV4A8Wcoxw==", "license": "Apache-2.0 OR MIT", "dependencies": { - "@libp2p/crypto": "^5.1.22", - "@libp2p/interface": "^3.2.5", - "@libp2p/interface-internal": "^3.1.11", - "@libp2p/peer-collections": "^7.0.26", - "@libp2p/peer-id": "^6.0.14", - "@libp2p/peer-record": "^9.0.15", - "@libp2p/utils": "^7.3.2", + "@libp2p/crypto": "^5.1.23", + "@libp2p/interface": "^3.3.0", + "@libp2p/interface-internal": "^3.1.13", + "@libp2p/peer-collections": "^7.0.28", + "@libp2p/peer-id": "^6.0.15", + "@libp2p/peer-record": "^9.0.16", + "@libp2p/utils": "^7.4.1", "@multiformats/multiaddr": "^13.0.3", "@multiformats/multiaddr-matcher": "^3.0.2", "any-signal": "^4.1.1", @@ -1250,28 +1250,10 @@ "uint8arrays": "^6.1.1" } }, - "node_modules/@libp2p/circuit-relay-v2/node_modules/nanoid": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-6.0.1.tgz", - "integrity": "sha512-3wVS3i51pE2pi1k5FFL/95BGfVS0kSsvDVuGXHOtxox/TywUmtgq+3qiTOTbs9J7KfHaXPiN171k/A6dBnaXFw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.js" - }, - "engines": { - "node": "^22 || ^24 || >=26" - } - }, "node_modules/@libp2p/circuit-relay-v2/node_modules/protons-runtime": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/protons-runtime/-/protons-runtime-7.0.0.tgz", - "integrity": "sha512-r/e72006xoVND4Uvf1aIs4OQOkJaASBU3ip4DzOWAktoKAkTiOYqKoS3TYMBm8HnnYU8+h0uEzr5gIRwk/pmTg==", + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/protons-runtime/-/protons-runtime-7.1.2.tgz", + "integrity": "sha512-j7Y7MfCwPCxYwopyqDt8+CoJULzdajSBrFAzzfBHEhOTfdvOJ2z1QLK9aK34bSBz6V/9JAAlrsc/rFkIbqppuw==", "license": "Apache-2.0 OR MIT", "dependencies": { "uint8-varint": "^3.0.0", @@ -1289,12 +1271,12 @@ } }, "node_modules/@libp2p/crypto": { - "version": "5.1.22", - "resolved": "https://registry.npmjs.org/@libp2p/crypto/-/crypto-5.1.22.tgz", - "integrity": "sha512-yVk4BefSiEz044kjsiLSEoJTbhRoyamqx4kFI9LnX8/asr4wnqDWKTXcn6mSx/RVNEzmDO70l3vOvcMCl4aLCQ==", + "version": "5.1.23", + "resolved": "https://registry.npmjs.org/@libp2p/crypto/-/crypto-5.1.23.tgz", + "integrity": "sha512-u6XVMD1YpUJgjS5MAayrxlzi+hQcj3FHY0wS6/M/T93ntyCW13BmmRzFb2ESamk65PEuSCAChmQeSzRV2sh2rQ==", "license": "Apache-2.0 OR MIT", "dependencies": { - "@libp2p/interface": "^3.2.5", + "@libp2p/interface": "^3.3.0", "@noble/curves": "^2.0.1", "@noble/hashes": "^2.0.1", "multiformats": "^14.0.0", @@ -1351,17 +1333,17 @@ } }, "node_modules/@libp2p/identify": { - "version": "4.1.12", - "resolved": "https://registry.npmjs.org/@libp2p/identify/-/identify-4.1.12.tgz", - "integrity": "sha512-nNBnxSclPVsvRsaLlwX9cz7gO020KjWEsaSzqDryWz6VStbLLdcwJYkVUP3do7VoFHkkF8PMQkScW7XCA27ZOA==", + "version": "4.1.14", + "resolved": "https://registry.npmjs.org/@libp2p/identify/-/identify-4.1.14.tgz", + "integrity": "sha512-c7oU0DSKzkMNsanruOQc4Zy6mSf3fq8/W+4E/I936HiHZc/LIbUuCWaxbgmQexdfKqECH1qH4q9IwaCUWmjPMQ==", "license": "Apache-2.0 OR MIT", "dependencies": { - "@libp2p/crypto": "^5.1.22", - "@libp2p/interface": "^3.2.5", - "@libp2p/interface-internal": "^3.1.11", - "@libp2p/peer-id": "^6.0.14", - "@libp2p/peer-record": "^9.0.15", - "@libp2p/utils": "^7.3.2", + "@libp2p/crypto": "^5.1.23", + "@libp2p/interface": "^3.3.0", + "@libp2p/interface-internal": "^3.1.13", + "@libp2p/peer-id": "^6.0.15", + "@libp2p/peer-record": "^9.0.16", + "@libp2p/utils": "^7.4.1", "@multiformats/multiaddr": "^13.0.3", "@multiformats/multiaddr-matcher": "^3.0.2", "it-drain": "^3.0.10", @@ -1373,9 +1355,9 @@ } }, "node_modules/@libp2p/identify/node_modules/protons-runtime": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/protons-runtime/-/protons-runtime-7.0.0.tgz", - "integrity": "sha512-r/e72006xoVND4Uvf1aIs4OQOkJaASBU3ip4DzOWAktoKAkTiOYqKoS3TYMBm8HnnYU8+h0uEzr5gIRwk/pmTg==", + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/protons-runtime/-/protons-runtime-7.1.2.tgz", + "integrity": "sha512-j7Y7MfCwPCxYwopyqDt8+CoJULzdajSBrFAzzfBHEhOTfdvOJ2z1QLK9aK34bSBz6V/9JAAlrsc/rFkIbqppuw==", "license": "Apache-2.0 OR MIT", "dependencies": { "uint8-varint": "^3.0.0", @@ -1393,9 +1375,9 @@ } }, "node_modules/@libp2p/interface": { - "version": "3.2.5", - "resolved": "https://registry.npmjs.org/@libp2p/interface/-/interface-3.2.5.tgz", - "integrity": "sha512-RdTchTdakBBc4ShKKsvoME/bJYsrCoVDpdYQVdd4TQ30TCb8QwWKGClqAtw7gfLNuaUKm41xz06kASW6AZpbDA==", + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/@libp2p/interface/-/interface-3.3.0.tgz", + "integrity": "sha512-SXahM/4IgpiFKTtocbXYSTA1wEUVjktmT1yBCzBbc2Vgsu1VBCg6SvsFmXo2Hbeyev3D8EU+y3uaCKDB43C/Vg==", "license": "Apache-2.0 OR MIT", "dependencies": { "@multiformats/dns": "^1.0.6", @@ -1407,13 +1389,13 @@ } }, "node_modules/@libp2p/interface-internal": { - "version": "3.1.11", - "resolved": "https://registry.npmjs.org/@libp2p/interface-internal/-/interface-internal-3.1.11.tgz", - "integrity": "sha512-lHJueWKdfkf/nrbVkGNUWrqDvF3T9Brn4hyONQmhTqG2mWyWKntRR/CkPjVgMRDSF2fuyzDJGg+n9tC0Gphk8g==", + "version": "3.1.13", + "resolved": "https://registry.npmjs.org/@libp2p/interface-internal/-/interface-internal-3.1.13.tgz", + "integrity": "sha512-+vjQzpQl+0uoWCyNwV5NDnv1RAK9LDeWGeMbx/Fl2ZWrndtuFUPa9LxwqHXrTly6YOhgUatSzVqZBWnrQ1PxGg==", "license": "Apache-2.0 OR MIT", "dependencies": { - "@libp2p/interface": "^3.2.5", - "@libp2p/peer-collections": "^7.0.26", + "@libp2p/interface": "^3.3.0", + "@libp2p/peer-collections": "^7.0.28", "@multiformats/multiaddr": "^13.0.3", "progress-events": "^1.0.1" } @@ -1428,19 +1410,19 @@ } }, "node_modules/@libp2p/kad-dht": { - "version": "16.4.3", - "resolved": "https://registry.npmjs.org/@libp2p/kad-dht/-/kad-dht-16.4.3.tgz", - "integrity": "sha512-i3FDNr9XLHcl8X27MRWrra3UyZw4o1esIen+66CNwFzZOTe85ndv6zNDOpgd2di1JT+E/xhKrghd+0wO3zfC6w==", + "version": "16.4.5", + "resolved": "https://registry.npmjs.org/@libp2p/kad-dht/-/kad-dht-16.4.5.tgz", + "integrity": "sha512-Pxmk3pIfe5Ih1xr+CY1uzw8AXRY+2VI6p3iebM4ljueu+dovEPIahW8tq4F2iNHIQftuc9Svncw4JikwrU7I1w==", "license": "Apache-2.0 OR MIT", "dependencies": { - "@libp2p/crypto": "^5.1.22", - "@libp2p/interface": "^3.2.5", - "@libp2p/interface-internal": "^3.1.11", - "@libp2p/peer-collections": "^7.0.26", - "@libp2p/peer-id": "^6.0.14", - "@libp2p/ping": "^3.1.11", + "@libp2p/crypto": "^5.1.23", + "@libp2p/interface": "^3.3.0", + "@libp2p/interface-internal": "^3.1.13", + "@libp2p/peer-collections": "^7.0.28", + "@libp2p/peer-id": "^6.0.15", + "@libp2p/ping": "^3.1.13", "@libp2p/record": "^4.0.15", - "@libp2p/utils": "^7.3.2", + "@libp2p/utils": "^7.4.1", "@multiformats/multiaddr": "^13.0.3", "@multiformats/multiaddr-matcher": "^3.0.2", "any-signal": "^4.1.1", @@ -1467,9 +1449,9 @@ } }, "node_modules/@libp2p/kad-dht/node_modules/protons-runtime": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/protons-runtime/-/protons-runtime-7.0.0.tgz", - "integrity": "sha512-r/e72006xoVND4Uvf1aIs4OQOkJaASBU3ip4DzOWAktoKAkTiOYqKoS3TYMBm8HnnYU8+h0uEzr5gIRwk/pmTg==", + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/protons-runtime/-/protons-runtime-7.1.2.tgz", + "integrity": "sha512-j7Y7MfCwPCxYwopyqDt8+CoJULzdajSBrFAzzfBHEhOTfdvOJ2z1QLK9aK34bSBz6V/9JAAlrsc/rFkIbqppuw==", "license": "Apache-2.0 OR MIT", "dependencies": { "uint8-varint": "^3.0.0", @@ -1487,12 +1469,12 @@ } }, "node_modules/@libp2p/logger": { - "version": "6.2.12", - "resolved": "https://registry.npmjs.org/@libp2p/logger/-/logger-6.2.12.tgz", - "integrity": "sha512-FwCdJ5hGFDvWI/SULZ4Iez+k+JtdMAj4/EK6bWmkh08ORIztwKpt0IXCOe8nIfKhBKwLYJu00BnZDRsedX7+7Q==", + "version": "6.2.13", + "resolved": "https://registry.npmjs.org/@libp2p/logger/-/logger-6.2.13.tgz", + "integrity": "sha512-+tkZuRPoiFdh+frG//3hQ3goV1uMzRblpZ+mwtezgLXkRNqB5YKBLl+c/rtrurwAUqjCuI/yoEPJBiCizg2z6w==", "license": "Apache-2.0 OR MIT", "dependencies": { - "@libp2p/interface": "^3.2.5", + "@libp2p/interface": "^3.3.0", "@multiformats/multiaddr": "^13.0.3", "interface-datastore": "^10.0.1", "multiformats": "^14.0.0", @@ -1500,13 +1482,13 @@ } }, "node_modules/@libp2p/multistream-select": { - "version": "7.0.26", - "resolved": "https://registry.npmjs.org/@libp2p/multistream-select/-/multistream-select-7.0.26.tgz", - "integrity": "sha512-bbKMgu7W/J6eknQODGpySshZq9QWEYbIM/fMYrihbdIT/eS1h+8U6ko2qylfwbDyYlnUoYP45Cqi+oxoNwGH3Q==", + "version": "7.0.28", + "resolved": "https://registry.npmjs.org/@libp2p/multistream-select/-/multistream-select-7.0.28.tgz", + "integrity": "sha512-X6rmxeAlFeTDHDc4IPujz+y9TdA8cSMFfWyGJfxdIbQpDc1PwZI/Ttt3YWp0LAT9sbSYVFaWA6cGTN9EnMWtGQ==", "license": "Apache-2.0 OR MIT", "dependencies": { - "@libp2p/interface": "^3.2.5", - "@libp2p/utils": "^7.3.2", + "@libp2p/interface": "^3.3.0", + "@libp2p/utils": "^7.4.1", "it-length-prefixed": "^11.0.1", "uint8arraylist": "^3.0.2", "uint8arrays": "^6.1.1" @@ -1522,38 +1504,38 @@ } }, "node_modules/@libp2p/peer-collections": { - "version": "7.0.26", - "resolved": "https://registry.npmjs.org/@libp2p/peer-collections/-/peer-collections-7.0.26.tgz", - "integrity": "sha512-hjJbC/Jo1TjxqaKph2W6ARRnrNoBCEbSQMUsGT17JXQktJc7ImVGLoFy2VsZoJGMX4RLN+gKp6f8McFGb5Vi1w==", + "version": "7.0.28", + "resolved": "https://registry.npmjs.org/@libp2p/peer-collections/-/peer-collections-7.0.28.tgz", + "integrity": "sha512-+evafZ5oSnGRfB7z+ycf09ehzNhCKoOZaiHgi6TpnDitpRQM5KQeN0H9Ep2uNJtzyW944HOG41BqcSaHbEHv7Q==", "license": "Apache-2.0 OR MIT", "dependencies": { - "@libp2p/interface": "^3.2.5", - "@libp2p/peer-id": "^6.0.14", - "@libp2p/utils": "^7.3.2", + "@libp2p/interface": "^3.3.0", + "@libp2p/peer-id": "^6.0.15", + "@libp2p/utils": "^7.4.1", "multiformats": "^14.0.0" } }, "node_modules/@libp2p/peer-id": { - "version": "6.0.14", - "resolved": "https://registry.npmjs.org/@libp2p/peer-id/-/peer-id-6.0.14.tgz", - "integrity": "sha512-tquBouwbUXgntPtT5q4vfaXbNWmSzh2zo4p2u8IzclVvggXOpmyBlAUNPXDiFqZvQpsxVBrTTemmn0+AwDwecg==", + "version": "6.0.15", + "resolved": "https://registry.npmjs.org/@libp2p/peer-id/-/peer-id-6.0.15.tgz", + "integrity": "sha512-aIbYJcldMNOIzmm9J57aESjZInYFdrQ9AY0ij+qn0Oam2vBxDfEIJZxJu+JzVkB2rVvT+FHDQXKWT2nAqNgB8w==", "license": "Apache-2.0 OR MIT", "dependencies": { - "@libp2p/crypto": "^5.1.22", - "@libp2p/interface": "^3.2.5", + "@libp2p/crypto": "^5.1.23", + "@libp2p/interface": "^3.3.0", "multiformats": "^14.0.0", "uint8arrays": "^6.1.1" } }, "node_modules/@libp2p/peer-record": { - "version": "9.0.15", - "resolved": "https://registry.npmjs.org/@libp2p/peer-record/-/peer-record-9.0.15.tgz", - "integrity": "sha512-WZH9Xkdvpr6TlM6eDdE/KZJmk558jrAC/ufNHnbWXdEUxF/GTzx7RsrBgaC6cPGBTNTjzICfO6vZKR2US0Fl9Q==", + "version": "9.0.16", + "resolved": "https://registry.npmjs.org/@libp2p/peer-record/-/peer-record-9.0.16.tgz", + "integrity": "sha512-J4QoPr0F1v6xqjHjAJ9KPbg4jdDlGutDk2K3Km6+o0nWzZCgCGeSEIDOO2UvPa2bFoZTL62cD73fn8tm5K06cg==", "license": "Apache-2.0 OR MIT", "dependencies": { - "@libp2p/crypto": "^5.1.22", - "@libp2p/interface": "^3.2.5", - "@libp2p/peer-id": "^6.0.14", + "@libp2p/crypto": "^5.1.23", + "@libp2p/interface": "^3.3.0", + "@libp2p/peer-id": "^6.0.15", "@multiformats/multiaddr": "^13.0.3", "multiformats": "^14.0.0", "protons-runtime": "^7.0.0", @@ -1563,9 +1545,9 @@ } }, "node_modules/@libp2p/peer-record/node_modules/protons-runtime": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/protons-runtime/-/protons-runtime-7.0.0.tgz", - "integrity": "sha512-r/e72006xoVND4Uvf1aIs4OQOkJaASBU3ip4DzOWAktoKAkTiOYqKoS3TYMBm8HnnYU8+h0uEzr5gIRwk/pmTg==", + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/protons-runtime/-/protons-runtime-7.1.2.tgz", + "integrity": "sha512-j7Y7MfCwPCxYwopyqDt8+CoJULzdajSBrFAzzfBHEhOTfdvOJ2z1QLK9aK34bSBz6V/9JAAlrsc/rFkIbqppuw==", "license": "Apache-2.0 OR MIT", "dependencies": { "uint8-varint": "^3.0.0", @@ -1583,16 +1565,16 @@ } }, "node_modules/@libp2p/peer-store": { - "version": "12.0.26", - "resolved": "https://registry.npmjs.org/@libp2p/peer-store/-/peer-store-12.0.26.tgz", - "integrity": "sha512-VoLjd7SQrYN45w3pnGl8YQQn+9tzMsoZxdmSG7VWoMiQhMLyxCtkctsVi9OCdT1IkdelPRq84KHklkK0D4FG9w==", + "version": "12.0.28", + "resolved": "https://registry.npmjs.org/@libp2p/peer-store/-/peer-store-12.0.28.tgz", + "integrity": "sha512-dj4qRhN01kml/It5/4P4DVcjfEZXJ2uZVVItCrs2YBGG2HLEYfWQZYROVbTCXDOCWwZK46aJ8eSLt4orsefq7Q==", "license": "Apache-2.0 OR MIT", "dependencies": { - "@libp2p/crypto": "^5.1.22", - "@libp2p/interface": "^3.2.5", - "@libp2p/peer-collections": "^7.0.26", - "@libp2p/peer-id": "^6.0.14", - "@libp2p/peer-record": "^9.0.15", + "@libp2p/crypto": "^5.1.23", + "@libp2p/interface": "^3.3.0", + "@libp2p/peer-collections": "^7.0.28", + "@libp2p/peer-id": "^6.0.15", + "@libp2p/peer-record": "^9.0.16", "@multiformats/multiaddr": "^13.0.3", "interface-datastore": "^10.0.1", "it-all": "^3.0.9", @@ -1605,9 +1587,9 @@ } }, "node_modules/@libp2p/peer-store/node_modules/protons-runtime": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/protons-runtime/-/protons-runtime-7.0.0.tgz", - "integrity": "sha512-r/e72006xoVND4Uvf1aIs4OQOkJaASBU3ip4DzOWAktoKAkTiOYqKoS3TYMBm8HnnYU8+h0uEzr5gIRwk/pmTg==", + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/protons-runtime/-/protons-runtime-7.1.2.tgz", + "integrity": "sha512-j7Y7MfCwPCxYwopyqDt8+CoJULzdajSBrFAzzfBHEhOTfdvOJ2z1QLK9aK34bSBz6V/9JAAlrsc/rFkIbqppuw==", "license": "Apache-2.0 OR MIT", "dependencies": { "uint8-varint": "^3.0.0", @@ -1625,13 +1607,13 @@ } }, "node_modules/@libp2p/ping": { - "version": "3.1.11", - "resolved": "https://registry.npmjs.org/@libp2p/ping/-/ping-3.1.11.tgz", - "integrity": "sha512-3ByJjpzxMAEJv8ZjWeLYv9k0Ba3eVxPRcWc8H79/RQhTQwY2zZvHYX4gQUmyqA9Sv0Q6peL4TwUW7E3wgN27Mw==", + "version": "3.1.13", + "resolved": "https://registry.npmjs.org/@libp2p/ping/-/ping-3.1.13.tgz", + "integrity": "sha512-zB0TYbxWD73z3kqHrC2PDk7CAX0wQ0smz6mZ9okE4MoFgJv+XtMaIB2pB/4eT7xjWwdc2w3mYRmq+lMyXl3nXQ==", "license": "Apache-2.0 OR MIT", "dependencies": { - "@libp2p/interface": "^3.2.5", - "@libp2p/interface-internal": "^3.1.11", + "@libp2p/interface": "^3.3.0", + "@libp2p/interface-internal": "^3.1.13", "p-event": "^7.0.0", "race-signal": "^2.0.0", "uint8arraylist": "^3.0.2", @@ -1659,9 +1641,9 @@ } }, "node_modules/@libp2p/record/node_modules/protons-runtime": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/protons-runtime/-/protons-runtime-7.0.0.tgz", - "integrity": "sha512-r/e72006xoVND4Uvf1aIs4OQOkJaASBU3ip4DzOWAktoKAkTiOYqKoS3TYMBm8HnnYU8+h0uEzr5gIRwk/pmTg==", + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/protons-runtime/-/protons-runtime-7.1.2.tgz", + "integrity": "sha512-j7Y7MfCwPCxYwopyqDt8+CoJULzdajSBrFAzzfBHEhOTfdvOJ2z1QLK9aK34bSBz6V/9JAAlrsc/rFkIbqppuw==", "license": "Apache-2.0 OR MIT", "dependencies": { "uint8-varint": "^3.0.0", @@ -1679,13 +1661,13 @@ } }, "node_modules/@libp2p/tcp": { - "version": "11.0.26", - "resolved": "https://registry.npmjs.org/@libp2p/tcp/-/tcp-11.0.26.tgz", - "integrity": "sha512-OOLb1Ov6zQRo983fEPRUvfcWmFrm2oJlwPgf7M6pzLyQOsTxpgb2MV37Az8ANy5GEAG4JJ+KPZn3g7JfEp33xA==", + "version": "11.0.28", + "resolved": "https://registry.npmjs.org/@libp2p/tcp/-/tcp-11.0.28.tgz", + "integrity": "sha512-+YD59zz1V8YT47ZiInqoHAeSx45BC2bb5FVu3Bplo5zOxMMNXcH5WATIgn+IYIbusNPpMcs5wKd0QimQwzBl6Q==", "license": "Apache-2.0 OR MIT", "dependencies": { - "@libp2p/interface": "^3.2.5", - "@libp2p/utils": "^7.3.2", + "@libp2p/interface": "^3.3.0", + "@libp2p/utils": "^7.4.1", "@multiformats/multiaddr": "^13.0.3", "@multiformats/multiaddr-matcher": "^3.0.2", "main-event": "^1.0.1", @@ -1704,15 +1686,15 @@ } }, "node_modules/@libp2p/utils": { - "version": "7.3.2", - "resolved": "https://registry.npmjs.org/@libp2p/utils/-/utils-7.3.2.tgz", - "integrity": "sha512-nVfJkTE3QMa/LVKVD5sKDB8birKua0BR0oKoqnLSXsX1ez89PvhR1zZjBfARSGVZdv5qUmblcdcvjJ76HD0CWA==", + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/@libp2p/utils/-/utils-7.4.1.tgz", + "integrity": "sha512-e9cZeop+awI0rFczG4DvAwVeHqBhuCZfTyskvgONfKQrsT7L0BSlTlTTzZoFF8Dnb+QrzHsoIpnl0PrCr0h+Hg==", "license": "Apache-2.0 OR MIT", "dependencies": { "@chainsafe/is-ip": "^2.1.0", "@chainsafe/netmask": "^2.0.0", - "@libp2p/interface": "^3.2.5", - "@libp2p/logger": "^6.2.12", + "@libp2p/interface": "^3.3.0", + "@libp2p/logger": "^6.2.13", "@multiformats/multiaddr": "^13.0.3", "@multiformats/multiaddr-matcher": "^3.0.2", "@sindresorhus/fnv1a": "^3.1.0", @@ -1766,13 +1748,13 @@ } }, "node_modules/@libp2p/websockets": { - "version": "10.1.19", - "resolved": "https://registry.npmjs.org/@libp2p/websockets/-/websockets-10.1.19.tgz", - "integrity": "sha512-inY5dWhm+mCrnS/wcHIWtDZ908c1W7UkpXE9i6uvnJVapWbvonvX9GEsTLvh4NbL7SOfnOHGkwDVgx1M2RxcRA==", + "version": "10.1.21", + "resolved": "https://registry.npmjs.org/@libp2p/websockets/-/websockets-10.1.21.tgz", + "integrity": "sha512-2iItZGEfTlGFUEcFCghtlsIiQ+fBowopysBB/8ya0MvZkRic/6o9oSklWT5pWDmXtmqmbp1Dko/iLcBOhDOgFw==", "license": "Apache-2.0 OR MIT", "dependencies": { - "@libp2p/interface": "^3.2.5", - "@libp2p/utils": "^7.3.2", + "@libp2p/interface": "^3.3.0", + "@libp2p/utils": "^7.4.1", "@multiformats/multiaddr": "^13.0.3", "@multiformats/multiaddr-matcher": "^3.0.2", "@multiformats/multiaddr-to-uri": "^12.0.0", @@ -1945,9 +1927,9 @@ } }, "node_modules/@oceanprotocol/contracts": { - "version": "2.9.0", - "resolved": "https://registry.npmjs.org/@oceanprotocol/contracts/-/contracts-2.9.0.tgz", - "integrity": "sha512-B3dQNxIYD7bASNE066vfZu6Ik5uHZ/1c+QEcUvAsfoNvUUJ5+uQfIvhwrpdMCza1GtE11EW2glDPZvbr2LwFsg==", + "version": "3.2.0-rc.1", + "resolved": "https://registry.npmjs.org/@oceanprotocol/contracts/-/contracts-3.2.0-rc.1.tgz", + "integrity": "sha512-chZ9YTKNLj6nWxUrfIYRDdA3oBOd3iHaF7MolUvTI7LqNS25dG+r9WWnZqblwwq+YPXGY63D7pvmuohGSAxTFQ==", "license": "Apache-2.0" }, "node_modules/@oceanprotocol/ddo-js": { @@ -1964,26 +1946,26 @@ } }, "node_modules/@oceanprotocol/lib": { - "version": "9.0.0", - "resolved": "https://registry.npmjs.org/@oceanprotocol/lib/-/lib-9.0.0.tgz", - "integrity": "sha512-nm0rSNIqbfvBzi4MSvMvll3YvwRuavgJ+iL/wHf/IPtZ/w++GOwx6c8U3Y3vv6/WuKVxz+Oe+uRjCMglJh+BpQ==", + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/@oceanprotocol/lib/-/lib-10.1.0.tgz", + "integrity": "sha512-cZue8rqPFgPeC1yuht1A1j5nL9M9C/GQVtHYMk4GhoYpkOzAfPMBqHw2gscmf9r8sdtBZEpSXq2TviZdXwamag==", "license": "Apache-2.0", "dependencies": { "@chainsafe/libp2p-noise": "^17.0.0", "@chainsafe/libp2p-yamux": "^8.0.1", - "@libp2p/bootstrap": "^12.0.29", - "@libp2p/circuit-relay-v2": "^4.2.11", - "@libp2p/identify": "^4.1.12", - "@libp2p/interface": "^3.2.5", - "@libp2p/kad-dht": "^16.4.2", - "@libp2p/peer-id": "^6.0.14", - "@libp2p/ping": "^3.1.11", - "@libp2p/tcp": "^11.0.26", - "@libp2p/utils": "^7.3.2", - "@libp2p/websockets": "^10.1.19", + "@libp2p/bootstrap": "^12.0.31", + "@libp2p/circuit-relay-v2": "^4.2.13", + "@libp2p/identify": "^4.1.14", + "@libp2p/interface": "^3.3.0", + "@libp2p/kad-dht": "^16.4.5", + "@libp2p/peer-id": "^6.0.15", + "@libp2p/ping": "^3.1.13", + "@libp2p/tcp": "^11.0.28", + "@libp2p/utils": "^7.4.1", + "@libp2p/websockets": "^10.1.21", "@multiformats/multiaddr": "^13.0.3", "@oasisprotocol/sapphire-ethers-v6": "^6.0.1", - "@oceanprotocol/ddo-js": "^0.4.1", + "@oceanprotocol/ddo-js": "^1.0.0", "bignumber.js": "^11.1.5", "cross-fetch": "^4.1.0", "crypto-js": "^4.2.0", @@ -1991,7 +1973,7 @@ "eciesjs": "^0.5.0", "ethers": "^6.17.0", "jsonwebtoken": "^9.0.3", - "libp2p": "^3.3.8", + "libp2p": "^3.3.10", "multiformats": "^14.0.5", "uint8arrays": "^6.1.1" }, @@ -1999,19 +1981,6 @@ "node": ">=22" } }, - "node_modules/@oceanprotocol/lib/node_modules/@oceanprotocol/ddo-js": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/@oceanprotocol/ddo-js/-/ddo-js-0.4.1.tgz", - "integrity": "sha512-QCEhBtBq6qMt545cQQne0C5leGRLgA+jOsbuRWQeY9VVj5HKdjc+1/oqm5BdNYBGa8HuZ+4GccJw0rREQf0CMA==", - "license": "Apache-2.0", - "dependencies": { - "ethers": "^6.17.0", - "jsonld": "^9.0.0", - "n3": "^2.2.0", - "rdf-literal": "^2.0.0", - "rdf-validate-shacl": "^0.6.5" - } - }, "node_modules/@oceanprotocol/lib/node_modules/cross-fetch": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-4.1.0.tgz", @@ -4688,22 +4657,22 @@ } }, "node_modules/libp2p": { - "version": "3.3.8", - "resolved": "https://registry.npmjs.org/libp2p/-/libp2p-3.3.8.tgz", - "integrity": "sha512-CMDYzEflxjtDkRV4vx8u4H93VxnPJOnntqd1pumrb5meorpe3hppxvwvgUc/eQ/5+ZwRQCgFi1rUfaaQt0zy0g==", + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/libp2p/-/libp2p-3.3.11.tgz", + "integrity": "sha512-+J3Dw1RnGdcpQaPN1HD+Z6xVS3qY0vnsqE2Tu//pfoiJxabaZVkc2FBNnNQ1Sj+Th2qoloeJ11jvxuNXSa1gtA==", "license": "Apache-2.0 OR MIT", "dependencies": { "@chainsafe/is-ip": "^2.1.0", "@chainsafe/netmask": "^2.0.0", - "@libp2p/crypto": "^5.1.22", - "@libp2p/interface": "^3.2.5", - "@libp2p/interface-internal": "^3.1.11", - "@libp2p/logger": "^6.2.12", - "@libp2p/multistream-select": "^7.0.26", - "@libp2p/peer-collections": "^7.0.26", - "@libp2p/peer-id": "^6.0.14", - "@libp2p/peer-store": "^12.0.26", - "@libp2p/utils": "^7.3.2", + "@libp2p/crypto": "^5.1.23", + "@libp2p/interface": "^3.3.0", + "@libp2p/interface-internal": "^3.1.13", + "@libp2p/logger": "^6.2.13", + "@libp2p/multistream-select": "^7.0.28", + "@libp2p/peer-collections": "^7.0.28", + "@libp2p/peer-id": "^6.0.15", + "@libp2p/peer-store": "^12.0.28", + "@libp2p/utils": "^7.4.1", "@multiformats/dns": "^1.0.6", "@multiformats/multiaddr": "^13.0.3", "@multiformats/multiaddr-matcher": "^3.0.2", @@ -4981,6 +4950,24 @@ "node": ">=12.0" } }, + "node_modules/nanoid": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-6.0.2.tgz", + "integrity": "sha512-hIvVOb9Qr1p/9CNNLOe0OlWvgx/ziTsVwKN/GDSsuArN2K0wDiafP3s0SWmsm7o2BdnyS8Z9Z64NFBUbn6ziBg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.js" + }, + "engines": { + "node": "^22 || ^24 || >=26" + } + }, "node_modules/natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", @@ -5303,9 +5290,9 @@ } }, "node_modules/p-retry": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-8.0.0.tgz", - "integrity": "sha512-kFVqH1HxOHp8LupNsOys7bSV09VYTRLxarH/mokO4Rqhk6wGi70E0jh4VzvVGXfEVNggHoHLAMWsQqHyU1Ey9A==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-8.0.1.tgz", + "integrity": "sha512-NAigyu8hfvJe7MsS18mnc4is0MZtau3QMdBklaJKK23oBQb6occO3UPM3vHmTckW8KhfyjMZaUOqdTFEYliHgg==", "license": "MIT", "dependencies": { "is-network-error": "^1.3.0" diff --git a/package.json b/package.json index 96c38a0..13f2b8a 100644 --- a/package.json +++ b/package.json @@ -75,9 +75,9 @@ }, "dependencies": { "@oasisprotocol/sapphire-ethers-v6": "^6.0.1", - "@oceanprotocol/contracts": "^2.9.0", + "@oceanprotocol/contracts": "^3.2.0-rc.1", "@oceanprotocol/ddo-js": "^1.0.0", - "@oceanprotocol/lib": "^9.0.0", + "@oceanprotocol/lib": "^10.1.0", "chalk": "^6.0.1", "commander": "^15.0.0", "enquirer": "^2.4.1", diff --git a/src/cli.ts b/src/cli.ts index 33fe40e..65184b6 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -11,12 +11,17 @@ import { ServiceStatusNumber, ServiceRestartParams, } from "@oceanprotocol/lib"; -import { parseComputeInput, toBoolean } from "./helpers.js"; +import { + parseComputeInput, + toBoolean, + parseSubsidyProviders, +} from "./helpers.js"; import { getCurrentNodeUrl, getCurrentEnvId, hasNode, nodeChainIds, + nodeSubsidyInfo, setCurrentNodeUrl, setCurrentEnvId, clearCurrentEnvId, @@ -87,17 +92,18 @@ const HELP_GROUPS: HelpGroup[] = [ }, { heading: "Chains & RPC", - commands: [ - "addChain", - "removeChain", - "listChains", - "setChain", - "getChain", - ], + commands: ["addChain", "removeChain", "listChains", "setChain", "getChain"], }, { heading: "Assets — publish, edit, consume", - commands: ["publish", "publishAlgo", "editAsset", "allowAlgo", "getDDO", "download"], + commands: [ + "publish", + "publishAlgo", + "editAsset", + "allowAlgo", + "getDDO", + "download", + ], }, { heading: "Compute", @@ -140,6 +146,7 @@ const HELP_GROUPS: HelpGroup[] = [ "withdrawFromEscrow", "authorizeEscrow", "getAuthorizationsEscrow", + "getEscrowInfo", ], }, { @@ -151,6 +158,10 @@ const HELP_GROUPS: HelpGroup[] = [ "removeFromAccessList", ], }, + { + heading: "Subsidy providers", + commands: ["getSubsidyProviders", "getSubsidyStatus"], + }, { heading: "Persistent storage (buckets)", commands: [ @@ -179,14 +190,19 @@ function groupedCommandNames(): string[] { // vanish from help), one grouped twice, or a group naming a command that no longer exists. function assertHelpGroupsCoverAll(program: Command): void { const grouped = groupedCommandNames(); - const dupes = [...new Set(grouped.filter((n, i) => grouped.indexOf(n) !== i))]; + const dupes = [ + ...new Set(grouped.filter((n, i) => grouped.indexOf(n) !== i)), + ]; const registered = program.commands.map((c) => c.name()); const missing = registered.filter((n) => !grouped.includes(n)); const unknown = grouped.filter((n) => !registered.includes(n)); const problems: string[] = []; - if (dupes.length) problems.push(`listed in more than one group: ${dupes.join(", ")}`); - if (missing.length) problems.push(`not in any help group: ${missing.join(", ")}`); - if (unknown.length) problems.push(`grouped but not registered: ${unknown.join(", ")}`); + if (dupes.length) + problems.push(`listed in more than one group: ${dupes.join(", ")}`); + if (missing.length) + problems.push(`not in any help group: ${missing.join(", ")}`); + if (unknown.length) + problems.push(`grouped but not registered: ${unknown.join(", ")}`); if (problems.length) { throw new Error(`Help groups out of sync — ${problems.join("; ")}`); } @@ -204,7 +220,10 @@ export function formatGroupedHelp(program: Command): string { return ` ${label}${gap}${desc}`; }; - const out: string[] = [chalk.bold(`Ocean CLI v${pkg.version} — commands`), ""]; + const out: string[] = [ + chalk.bold(`Ocean CLI v${pkg.version} — commands`), + "", + ]; for (const group of HELP_GROUPS) { out.push(chalk.cyan.bold(group.heading)); for (const n of group.commands ?? []) out.push(line(n)); @@ -227,6 +246,32 @@ export function formatGroupedHelp(program: Command): string { // (dev via tsx) and dist/ (published), since both sit one level below the root. const pkg = createRequire(import.meta.url)("../package.json"); +// Print the subsidy-provider info a node advertises in its status (shared by getNode and +// getSubsidyProviders). `indent` lets getNode nest it under the node summary. +function printSubsidyInfo( + info: { providers: Record; filter: boolean }, + indent = " ", +): void { + const chains = Object.keys(info.providers).filter( + (c) => (info.providers[c]?.length ?? 0) > 0, + ); + if (chains.length === 0) { + console.log( + chalk.yellow(`${indent}Subsidy providers: none advertised by this node.`), + ); + } else { + console.log(`${indent}Subsidy providers:`); + for (const c of chains.sort()) { + console.log(`${indent} chain ${c}: ${info.providers[c].join(", ")}`); + } + } + console.log( + `${indent}Subsidy provider filter (whitelist enforced): ${ + info.filter ? "on" : "off" + }`, + ); +} + // Parse a CLI JSON array-of-strings option (e.g. --cmd '["python","app.py"]'). // Returns the array, or throws with a clear message for the action to surface. function parseJsonStringArray(name: string, value: string): string[] { @@ -293,7 +338,9 @@ function resolveChainId(flag?: string | number): number { if (flag !== undefined && flag !== null && `${flag}`.trim() !== "") { const id = Number(flag); if (!Number.isInteger(id) || id <= 0) { - throw new Error(`Invalid --chainId "${flag}": must be a positive integer.`); + throw new Error( + `Invalid --chainId "${flag}": must be a positive integer.`, + ); } if (!hasChain(id)) { throw new Error( @@ -463,10 +510,15 @@ export async function createCLI() { .description( "Sets / switches the Ocean Node used by subsequent commands, without restarting", ) - .argument("", "HTTP(S) URL, peer id or full multiaddr of the node") + .argument("[nodeUrl]", "HTTP(S) URL, peer id or full multiaddr of the node") .option("-n, --node ", "Ocean Node to use") .action(async (nodeUrl, options) => { const target = options.node || nodeUrl; + if (!target) { + throw new Error( + "A node is required. Pass it positionally or with --node (URL / peer id / multiaddr).", + ); + } const previous = getCurrentNodeUrl(); if (target === previous) { console.log(chalk.green(`Node ${target} is already the active one.`)); @@ -612,7 +664,9 @@ export async function createCLI() { const configured = nodeChains.filter((c) => hasChain(Number(c))); if (configured.length) { console.log( - chalk.green(` RPC configured for chain(s): ${configured.join(", ")}`), + chalk.green( + ` RPC configured for chain(s): ${configured.join(", ")}`, + ), ); } if (missing.length) { @@ -627,11 +681,85 @@ export async function createCLI() { } catch { // RPC not configured / unavailable — the node info above is still useful. } + printSubsidyInfo(nodeSubsidyInfo(status)); } else { console.log(chalk.yellow("Node is not reachable right now.")); } }); + // getSubsidyProviders command — show the subsidy-provider contracts the current node + // advertises per chain (and whether it enforces a whitelist on user-supplied ones). + // Node-dependent (deliberately NOT in NODE_FREE_COMMANDS): the preAction gate refuses it + // until a node is set. Implemented inline like getNode — no signer/Commands needed. + program + .command("getSubsidyProviders") + .alias("subsidyProviders") + .description( + "Show the subsidy-provider contracts the current Ocean Node supports (per chain)", + ) + .action(async () => { + const current = getCurrentNodeUrl(); + if (!current) { + console.log( + chalk.yellow( + "No Ocean Node set. Run `setNode ` to pick one.", + ), + ); + return; + } + const status = await validateNode(current); + if (!status) { + console.log(chalk.yellow("Node is not reachable right now.")); + return; + } + console.log(`Ocean Node: ${current}`); + printSubsidyInfo(nodeSubsidyInfo(status)); + }); + + // getSubsidyStatus command — read-only, provider-agnostic subsidy report for a token on a + // chain: kind, per-window buckets (limit/used/remaining), claimable-now amount, contract + // balance, eligibility, and (with --node/--jobType/--amount) a quote. Provider addresses are + // discovered from the node; --subsidy only narrows to a subset the node advertises. + program + .command("getSubsidyStatus") + .alias("subsidyStatus") + .description( + "Show subsidy limits / remaining credit for a token from the node's subsidy providers", + ) + .argument("[token]", "Token address to report limits/credit for (or use --token)") + .option("-t, --token ", "Token address to report limits/credit for") + .option( + "--chainId ", + "Subsidy/escrow chain (default: active chain)", + ) + .option( + "--subsidy ", + "Narrow to specific node-advertised provider contract(s) (comma-separated); else all the node lists", + ) + .option( + "--node ", + "Ocean Node to query for providers (URL / peer id / multiaddr); default: active node. Its on-chain address is used for isNodeAllowed / quoteSubsidy", + ) + .option( + "--jobType ", + "Job type for isJobTypeSubsidized / quoteSubsidy (compute | service | none)", + ) + .option( + "--amount ", + "Job amount to quote a subsidy for, in natural token units (e.g. 1.5). Needs --jobType (uses the queried node's address).", + ) + .action(async (token, options) => { + const { signer, chainId } = await initializeSigner(); + const commands = new Commands(signer, chainId); + if ((await routeExplicit(commands, options.chainId)) === null) return; + await commands.getSubsidyStatus(token || options.token, { + subsidy: options.subsidy, + node: options.node, + jobType: options.jobType, + amount: options.amount, + }); + }); + // --------------------------------------------------------------------------- // Chain / RPC management (node-free — see NODE_FREE_COMMANDS). Implemented directly // here, mirroring setNode/getNode: the registry is the single source of truth and no @@ -649,7 +777,7 @@ export async function createCLI() { .description( "Register an RPC chain at runtime (verifies each URL serves the chain; persists)", ) - .argument("", "Chain id the URL(s) serve") + .argument("[chainId]", "Chain id the URL(s) serve") .argument("[rpcUrl...]", "One or more RPC URLs for that chain") .option("-c, --chainId ", "Chain id the URL(s) serve") .option("-u, --url ", "One or more RPC URLs for that chain") @@ -659,12 +787,14 @@ export async function createCLI() { const urls: string[] = options.url && options.url.length ? options.url : rpcUrlArgs; if (!Number.isInteger(id) || id <= 0) { - console.error(chalk.red(`Invalid chainId "${chainIdArg}".`)); - return; + throw new Error( + `A valid chain id is required. Pass it positionally or with --chainId (got "${chainIdArg ?? ""}").`, + ); } if (!urls || urls.length === 0) { - console.error(chalk.red("At least one RPC URL is required.")); - return; + throw new Error( + "At least one RPC URL is required. Pass it positionally or with --url.", + ); } try { await addChain(id, urls); @@ -682,14 +812,15 @@ export async function createCLI() { .command("removeChain") .alias("removeRpc") .description("Unregister an RPC chain (persists)") - .argument("", "Chain id to remove") + .argument("[chainId]", "Chain id to remove") .option("-c, --chainId ", "Chain id to remove") .action(async (chainIdArg, options) => { loadRegistry(); const id = Number(options.chainId || chainIdArg); if (!Number.isInteger(id) || id <= 0) { - console.error(chalk.red(`Invalid chainId "${chainIdArg}".`)); - return; + throw new Error( + `A valid chain id is required. Pass it positionally or with --chainId (got "${chainIdArg ?? ""}").`, + ); } try { removeChain(id); @@ -755,15 +886,18 @@ export async function createCLI() { program .command("setChain") .alias("useChain") - .description("Set the default (active) chain (must be registered; persists)") - .argument("", "Chain id to make default") + .description( + "Set the default (active) chain (must be registered; persists)", + ) + .argument("[chainId]", "Chain id to make default") .option("-c, --chainId ", "Chain id to make default") .action(async (chainIdArg, options) => { loadRegistry(); const id = Number(options.chainId || chainIdArg); if (!Number.isInteger(id) || id <= 0) { - console.error(chalk.red(`Invalid chainId "${chainIdArg}".`)); - return; + throw new Error( + `A valid chain id is required. Pass it positionally or with --chainId (got "${chainIdArg ?? ""}").`, + ); } try { setDefaultChainId(id); @@ -796,14 +930,12 @@ export async function createCLI() { program .command("getDDO") .description("Gets DDO for an asset using the asset did") - .argument("", "The asset DID") + .argument("[did]", "The asset DID") .option("-d, --did ", "The asset DID") .action(async (did, options) => { const assetDid = options.did || did; if (!assetDid) { - console.error(chalk.red("DID is required")); - // process.exit(1); - return; + throw new Error("A DID is required. Pass it positionally or with --did."); } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); @@ -814,15 +946,15 @@ export async function createCLI() { program .command("publish") .description("Publishes a new asset with access service or compute service") - .argument("", "Path to metadata file") + .argument("[metadataFile]", "Path to metadata file") .option("-f, --file ", "Path to metadata file") .option("-e, --encrypt [boolean]", "Encrypt DDO", true) .action(async (metadataFile, options) => { const file = options.file || metadataFile; if (!file) { - console.error(chalk.red("Metadata file is required")); - // process.exit(1); - return; + throw new Error( + "A metadata file is required. Pass it positionally or with --file.", + ); } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); @@ -833,15 +965,15 @@ export async function createCLI() { program .command("publishAlgo") .description("Publishes a new algorithm") - .argument("", "Path to metadata file") + .argument("[metadataFile]", "Path to metadata file") .option("-f, --file ", "Path to metadata file") .option("-e, --encrypt [boolean]", "Encrypt DDO", true) .action(async (metadataFile, options) => { const file = options.file || metadataFile; if (!file) { - console.error(chalk.red("Metadata file is required")); - // process.exit(1); - return; + throw new Error( + "A metadata file is required. Pass it positionally or with --file.", + ); } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); @@ -853,8 +985,8 @@ export async function createCLI() { .command("editAsset") .alias("edit") .description("Updates DDO using the metadata items in the file") - .argument("", "Dataset DID") - .argument("", "Updated metadata file") + .argument("[datasetDid]", "Dataset DID") + .argument("[metadataFile]", "Updated metadata file") .option("-d, --did ", "Dataset DID") .option("-f, --file ", "Updated metadata file") .option("-e, --encrypt [boolean]", "Encrypt DDO", true) @@ -862,9 +994,9 @@ export async function createCLI() { const dsDid = options.did || datasetDid; const file = options.file || metadataFile; if (!dsDid || !file) { - console.error(chalk.red("Dataset DID and metadata file are required")); - // process.exit(1); - return; + throw new Error( + "A dataset DID and metadata file are required. Pass them positionally or with --did / --file.", + ); } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); @@ -875,7 +1007,7 @@ export async function createCLI() { program .command("download") .description("Downloads an asset into specified folder") - .argument("", "The asset DID") + .argument("[did]", "The asset DID") .argument("[folder]", "Destination folder", ".") .argument("[serviceId]", "Service ID (optional)") .option("-d, --did ", "The asset DID") @@ -886,9 +1018,7 @@ export async function createCLI() { const destFolder = options.folder || folder || "."; const svcId = options.service || serviceId; if (!assetDid) { - console.error(chalk.red("DID is required")); - // process.exit(1); - return; + throw new Error("A DID is required. Pass it positionally or with --did."); } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); @@ -899,8 +1029,8 @@ export async function createCLI() { program .command("allowAlgo") .description("Approves an algorithm to run on a dataset") - .argument("", "Dataset DID") - .argument("", "Algorithm DID") + .argument("[datasetDid]", "Dataset DID") + .argument("[algoDid]", "Algorithm DID") .option("-d, --dataset ", "Dataset DID") .option("-a, --algo ", "Algorithm DID") .option("-e, --encrypt [boolean]", "Encrypt DDO", true) @@ -908,9 +1038,9 @@ export async function createCLI() { const dsDid = options.dataset || datasetDid; const aDid = options.algo || algoDid; if (!dsDid || !aDid) { - console.error(chalk.red("Dataset DID and Algorithm DID are required")); - // process.exit(1); - return; + throw new Error( + "A dataset DID and algorithm DID are required. Pass them positionally or with --dataset / --algo.", + ); } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); @@ -922,11 +1052,11 @@ export async function createCLI() { .command("startCompute") .description("Starts a compute job") .argument( - "", + "[datasetDids]", 'Dataset DIDs (comma-separated), an empty array for none, OR a JSON ComputeAsset object/array with a fileObject (raw datasets, no DID). Mixed input must be valid JSON, e.g. \'["did:op:abc",{"fileObject":{...}}]\'', ) .argument( - "", + "[algoDid]", "Algorithm DID, OR a JSON ComputeAlgorithm object with a fileObject and meta (raw algorithm, no DID)", ) .argument( @@ -978,6 +1108,10 @@ export async function createCLI() { "-o, --output [output]", "Output backend to save job results to. Supported types include S3, FTP, URL, Arweave, etc. Defaults to node local disk if omitted.", ) + .option( + "--subsidyProviders ", + "Subsidy provider contract addresses (comma-separated) to claim against. Omit to use the node's defaults; pass 'none' (or empty) to explicitly claim with no subsidy.", + ) .action( async ( datasetDids, @@ -1044,6 +1178,20 @@ export async function createCLI() { ); return; } + + // Tri-state: undefined (node default) | [] (no subsidy) | [addr,...]. + // Validate up front so a malformed address is rejected before compute + // initialization and the payment prompt. + let subsidyProviders: string[] | undefined; + try { + subsidyProviders = parseSubsidyProviders(options.subsidyProviders); + } catch (e) { + console.error( + chalk.red(`Invalid --subsidyProviders: ${(e as Error).message}`), + ); + return; + } + const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); @@ -1092,6 +1240,27 @@ export async function createCLI() { initResp.payment.amount.toString(), ); + // Subsidy providers may pre-fund part or all of the lock, so show the whole + // price and what the payer actually funds. The same figure is handed to + // computeStart below, so what is confirmed here is what gets deposited. + const lockUnits = BigInt(initResp.payment.amount.toString()); + const prefundedUnits = await commands.computePrefundedUnits( + subsidyProviders, + lockUnits, + ); + const toAmount = (units: bigint) => + unitsToAmount(paymentSigner, initResp.payment.token, units.toString()); + const youPay = await toAmount(lockUnits - prefundedUnits); + console.log(chalk.yellow(` total job cost: ${amount}`)); + if (prefundedUnits > 0n) { + console.log( + chalk.green( + ` prepaid subsidy covers: ${await toAmount(prefundedUnits)}`, + ), + ); + } + console.log(chalk.yellow(` you pay: ${youPay}`)); + const proceed = options.accept; if (!proceed) { if (!process.stdin.isTTY) { @@ -1104,7 +1273,7 @@ export async function createCLI() { } const rl = createInterface({ input, output: stdout }); const confirmation = await rl.question( - `\nProceed with payment for starting compute job at price ${amount} in tokens from address ${initResp.payment.token}? (y/n): `, + `\nProceed with starting the compute job? Total cost ${amount}, you pay ${youPay}, in tokens from address ${initResp.payment.token} (y/n): `, ); rl.close(); if ( @@ -1132,7 +1301,12 @@ export async function createCLI() { algoSvcId, ]; - const started = await commands.computeStart(computeArgs, paymentChainId); + const started = await commands.computeStart( + computeArgs, + paymentChainId, + subsidyProviders, + prefundedUnits, + ); if (started) { console.log(chalk.green("Compute job started successfully.")); } @@ -1144,11 +1318,11 @@ export async function createCLI() { .command("startFreeCompute") .description("Starts a FREE compute job") .argument( - "", + "[datasetDids]", 'Dataset DIDs (comma-separated), an empty array for none, OR a JSON ComputeAsset object/array with a fileObject (raw datasets, no DID). Mixed input must be valid JSON, e.g. \'["did:op:abc",{"fileObject":{...}}]\'', ) .argument( - "", + "[algoDid]", "Algorithm DID, OR a JSON ComputeAlgorithm object with a fileObject and meta (raw algorithm, no DID)", ) .argument( @@ -1272,12 +1446,17 @@ export async function createCLI() { program .command("computeStreamableLogs") .description("Gets the existing compute streamable logs") - .argument("", "Job ID") + .argument("[jobId]", "Job ID") .option("-j, --job ", "Job ID") .action(async (jobId, options) => { + const args = jobId || options.job; + if (!args) { + throw new Error( + "A job ID is required. Pass it positionally or with --job.", + ); + } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); - const args = jobId || options.job; await commands.computeStreamableLogs([args]); }); @@ -1285,9 +1464,9 @@ export async function createCLI() { program .command("stopCompute") .description("Stops a compute job") - .argument("", "Dataset DID") - .argument("", "Job ID") - .argument("", "Agreement ID") + .argument("[datasetDid]", "Dataset DID") + .argument("[jobId]", "Job ID") + .argument("[agreementId]", "Agreement ID") .option("-d, --dataset ", "Dataset DID") .option("-j, --job ", "Job ID") .option("-a, --agreement [agreementId]", "Agreement ID") @@ -1296,9 +1475,9 @@ export async function createCLI() { const jId = options.job || jobId; const agrId = options.agreement || agreementId; if (!dsDid || !jId) { - console.error(chalk.red("Dataset DID and Job ID are required")); - // process.exit(1); - return; + throw new Error( + "A dataset DID and job ID are required. Pass them positionally or with --dataset / --job.", + ); } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); @@ -1311,8 +1490,8 @@ export async function createCLI() { program .command("getJobStatus") .description("Displays the compute job status") - .argument("", "Dataset DID") - .argument("", "Job ID") + .argument("[datasetDid]", "Dataset DID") + .argument("[jobId]", "Job ID") .argument("[agreementId]", "Agreement ID") .option("-d, --dataset ", "Dataset DID") .option("-j, --job ", "Job ID") @@ -1322,9 +1501,9 @@ export async function createCLI() { const jId = options.job || jobId; const agrId = options.agreement || agreementId; if (!dsDid || !jId) { - console.error(chalk.red("Dataset DID and Job ID are required")); - // process.exit(1); - return; + throw new Error( + "A dataset DID and job ID are required. Pass them positionally or with --dataset / --job.", + ); } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); @@ -1447,6 +1626,10 @@ export async function createCLI() { "--chainId ", "Payment/escrow chain (default: active chain); must be one the env prices on", ) + .option( + "--subsidyProviders ", + "Subsidy provider contract addresses (comma-separated) to claim against. Omit for node defaults; 'none' (or empty) for no subsidy.", + ) .action(async (computeEnvId, duration, paymentToken, options) => { const envId = options.env || computeEnvId; const token = paymentToken; @@ -1474,11 +1657,13 @@ export async function createCLI() { let ports: number[] | undefined; let cmd: string[] | undefined; let entrypoint: string[] | undefined; + let subsidyProviders: string[] | undefined; try { if (options.ports) ports = parsePorts(options.ports); if (options.cmd) cmd = parseJsonStringArray("--cmd", options.cmd); if (options.entrypoint) entrypoint = parseJsonStringArray("--entrypoint", options.entrypoint); + subsidyProviders = parseSubsidyProviders(options.subsidyProviders); } catch (e) { console.error(chalk.red((e as Error).message)); return; @@ -1508,6 +1693,7 @@ export async function createCLI() { accept: options.accept, wait: options.wait, timeout: options.timeout, + subsidyProviders, }); }); @@ -1591,7 +1777,7 @@ export async function createCLI() { .command("serviceLogs") .alias("computeServiceLogs") .description("Streams live logs from an on-demand service's container") - .argument("", "Service ID") + .argument("[serviceId]", "Service ID") .option("-s, --service ", "Service ID") .option( "--since ", @@ -1600,8 +1786,9 @@ export async function createCLI() { .action(async (serviceId, options) => { const id = options.service || serviceId; if (!id) { - console.error(chalk.red("Missing required argument: ")); - return; + throw new Error( + "A service ID is required. Pass it positionally or with --service.", + ); } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); @@ -1614,9 +1801,9 @@ export async function createCLI() { .description( "Extends a running on-demand service's expiry (paid via escrow)", ) - .argument("", "Service ID") + .argument("[serviceId]", "Service ID") .argument( - "", + "[additionalDuration]", "Additional duration in seconds", parseInt, ) @@ -1636,31 +1823,47 @@ export async function createCLI() { "Auto-confirm payment (true/false)", toBoolean, ) - .option("--chainId ", "Payment/escrow chain (default: active chain)") + .option( + "--chainId ", + "Payment/escrow chain (default: active chain)", + ) + .option( + "--subsidyProviders ", + "Subsidy provider contract addresses (comma-separated) to claim against. Omit for node defaults; 'none' (or empty) for no subsidy.", + ) .action(async (serviceId, additionalDuration, paymentToken, options) => { const id = options.service || serviceId; const addl = options.duration || additionalDuration; const token = options.token || paymentToken; if (!id || !addl) { - console.error( - chalk.red( - "Missing required arguments: ", - ), + throw new Error( + "A service ID and additional duration are required. Pass them positionally or with --service / --duration.", ); - return; } if (!Number.isInteger(addl) || addl <= 0) { + throw new Error( + "additionalDuration must be a positive integer number of seconds.", + ); + } + let subsidyProviders: string[] | undefined; + try { + subsidyProviders = parseSubsidyProviders(options.subsidyProviders); + } catch (e) { console.error( - chalk.red( - "additionalDuration must be a positive integer number of seconds.", - ), + chalk.red(`Invalid --subsidyProviders: ${(e as Error).message}`), ); return; } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); if ((await routeExplicit(commands, options.chainId)) === null) return; - await commands.extendService(id, addl, token, options.accept); + await commands.extendService( + id, + addl, + token, + options.accept, + subsidyProviders, + ); }); // restartService command @@ -1785,13 +1988,14 @@ export async function createCLI() { program .command("stopService") .description("Stops an on-demand service and releases its resources") - .argument("", "Service ID") + .argument("[serviceId]", "Service ID") .option("-s, --service ", "Service ID") .action(async (serviceId, options) => { const id = options.service || serviceId; if (!id) { - console.error(chalk.red("Missing required argument: ")); - return; + throw new Error( + "A service ID is required. Pass it positionally or with --service.", + ); } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); @@ -1828,30 +2032,41 @@ export async function createCLI() { program .command("invalidateAuthToken") .description("Invalidate auth token") - .argument("", "Auth token") + .argument("[token]", "Auth token") .option("-t, --token ", "Auth token") .action(async (token, options) => { + const authToken = token || options.token; + if (!authToken) { + throw new Error( + "An auth token is required. Pass it positionally or with --token.", + ); + } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); - await commands.invalidateAuthToken([token || options.token]); + await commands.invalidateAuthToken([authToken]); }); // Escrow deposit command program .command("depositEscrow") .description("Deposit tokens into the escrow contract") - .argument("", "Address of the token to deposit") - .argument("", "Amount of tokens to deposit") + .argument("[token]", "Address of the token to deposit") + .argument("[amount]", "Amount of tokens to deposit") .option("-t, --token ", "Address of the token to deposit") .option("-a, --amount ", "Amount of tokens to deposit") .option("--chainId ", "Escrow chain (default: active chain)") .action(async (token, amount, options) => { + const tokenAddress = options.token || token; + const amountToDeposit = options.amount || amount; + if (!tokenAddress || !amountToDeposit) { + throw new Error( + "A token address and amount are required. Pass them positionally or with --token / --amount.", + ); + } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); const target = await routeExplicit(commands, options.chainId); if (target === null) return; - const tokenAddress = options.token || token; - const amountToDeposit = options.amount || amount; const success = await commands.depositToEscrow( commands.signer, tokenAddress, @@ -1870,41 +2085,56 @@ export async function createCLI() { program .command("getUserFundsEscrow") .description("Get deposited token amount in escrow for user") - .argument("", "Address of the token to check") + .argument("[token]", "Address of the token to check") .option("-t, --token ", "Address of the token to check") .option("--chainId ", "Escrow chain (default: active chain)") .action(async (token, options) => { + const tokenAddress = token || options.token; + if (!tokenAddress) { + throw new Error( + "A token address is required. Pass it positionally or with --token.", + ); + } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); if ((await routeExplicit(commands, options.chainId)) === null) return; - await commands.getEscrowBalance(token || options.token); + await commands.getEscrowBalance(tokenAddress); }); // Withdraw from escrow program .command("withdrawFromEscrow") .description("Withdraw tokens from escrow") - .argument("", "Address of the token to check") - .argument("", "Amount of tokens to withdraw") + .argument("[token]", "Address of the token to check") + .argument("[amount]", "Amount of tokens to withdraw") .option("-t, --token ", "Address of the token to check") .option("-a, --amount ", "Amount of tokens to withdraw") .option("--chainId ", "Escrow chain (default: active chain)") .action(async (token, amount, options) => { + const tokenAddress = token || options.token; + const amountToWithdraw = amount || options.amount; + if (!tokenAddress || !amountToWithdraw) { + throw new Error( + "A token address and amount are required. Pass them positionally or with --token / --amount.", + ); + } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); if ((await routeExplicit(commands, options.chainId)) === null) return; - await commands.withdrawFromEscrow(token || options.token, amount); + await commands.withdrawFromEscrow(tokenAddress, amountToWithdraw); }); // Escrow authorization command program .command("authorizeEscrow") - .description("Authorize a payee to lock and claim funds from escrow") - .argument("", "Address of the token to authorize") - .argument("", "Address of the payee to authorize") - .argument("", "Maximum amount that can be locked by payee") - .argument("", "Maximum lock duration in seconds") - .argument("", "Maximum number of locks allowed") + .description( + "Authorize (or re-authorize) a payee to lock and claim funds from escrow. Re-running overwrites the existing limits (renew/shorten); pass a past --expiry to revoke", + ) + .argument("[token]", "Address of the token to authorize") + .argument("[payee]", "Address of the payee to authorize") + .argument("[maxLockedAmount]", "Maximum amount that can be locked by payee") + .argument("[maxLockSeconds]", "Maximum lock duration in seconds") + .argument("[maxLockCounts]", "Maximum number of locks allowed") .option("-t, --token ", "Address of the token to authorize") .option("-p, --payee ", "Address of the payee to authorize") .option( @@ -1919,6 +2149,10 @@ export async function createCLI() { "-c, --maxLockCounts ", "Maximum number of locks allowed", ) + .option( + "-e, --expiry ", + "Escrow v2: unix timestamp (seconds) after which the payee can no longer create/extend locks. 0 = indefinite (default). A past timestamp revokes; claim/cancel are never gated by it", + ) .option("--chainId ", "Escrow chain (default: active chain)") .action( async ( @@ -1938,12 +2172,25 @@ export async function createCLI() { const maxLockSecondsValue = options.maxLockSeconds || maxLockSeconds; const maxLockCountsValue = options.maxLockCounts || maxLockCounts; + if ( + !tokenAddress || + !payeeAddress || + !maxLockedAmountValue || + !maxLockSecondsValue || + !maxLockCountsValue + ) { + throw new Error( + "token, payee, maxLockedAmount, maxLockSeconds and maxLockCounts are all required. Pass them positionally or with --token / --payee / --maxLockedAmount / --maxLockSeconds / --maxLockCounts.", + ); + } + const success = await commands.authorizeEscrowPayee( tokenAddress, payeeAddress, maxLockedAmountValue, maxLockSecondsValue, maxLockCountsValue, + options.expiry, ); if (!success) { @@ -1955,29 +2202,54 @@ export async function createCLI() { }, ); + // Escrow v2 diagnostics: escrow kind/version, ERC-165 capabilities, and (with a token) the + // sponsored bucket / enterprise fee gate. + program + .command("getEscrowInfo") + .alias("escrowInfo") + .description( + "Show escrow capabilities for the active chain (version, kind, lock-time sponsorship, enterprise fee gate). Pass a token to also read the sponsored bucket and fee gate", + ) + .argument( + "[token]", + "Optional token address to read the sponsored bucket / fee gate for", + ) + .option("-t, --token ", "Optional token address") + .option("--chainId ", "Escrow chain (default: active chain)") + .action(async (token, options) => { + const { signer, chainId } = await initializeSigner(); + const commands = new Commands(signer, chainId); + if ((await routeExplicit(commands, options.chainId)) === null) return; + await commands.getEscrowInfo(options.token || token); + }); + program .command("getAuthorizationsEscrow") .description("Get authorizations for escrow") - .argument("", "Address of the token to check") - .argument("", "Address of the payee to check") + .argument("[token]", "Address of the token to check") + .argument("[payee]", "Address of the payee to check") .option("-t, --token ", "Address of the token to check") .option("-p, --payee ", "Address of the payee to check") .option("--chainId ", "Escrow chain (default: active chain)") .action(async (token, payee, options) => { + const tokenAddress = token || options.token; + const payeeAddress = payee || options.payee; + if (!tokenAddress || !payeeAddress) { + throw new Error( + "A token address and payee are required. Pass them positionally or with --token / --payee.", + ); + } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); if ((await routeExplicit(commands, options.chainId)) === null) return; - await commands.getAuthorizationsEscrow( - token || options.token, - payee || options.payee, - ); + await commands.getAuthorizationsEscrow(tokenAddress, payeeAddress); }); program .command("createAccessList") .description("Create a new access list contract") - .argument("", "Name for the access list") - .argument("", "Symbol for the access list") + .argument("[name]", "Name for the access list") + .argument("[symbol]", "Symbol for the access list") .argument( "[initialUsers]", "Comma-separated list of initial user addresses", @@ -2002,12 +2274,19 @@ export async function createCLI() { ) .option("--chainId ", "Chain to deploy on (default: active chain)") .action(async (name, symbol, initialUsers, transferable, options) => { + const listName = options.name || name; + const listSymbol = options.symbol || symbol; + if (!listName || !listSymbol) { + throw new Error( + "A name and symbol are required. Pass them positionally or with --name / --symbol.", + ); + } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); if ((await routeExplicit(commands, options.chainId)) === null) return; await commands.createAccessList([ - options.name || name, - options.symbol || symbol, + listName, + listSymbol, options.transferable || transferable, options.initialUsers || initialUsers, ]); @@ -2016,8 +2295,8 @@ export async function createCLI() { program .command("addToAccessList") .description("Add user(s) to an access list") - .argument("", "Address of the access list contract") - .argument("", "Comma-separated list of user addresses to add") + .argument("[accessListAddress]", "Address of the access list contract") + .argument("[users]", "Comma-separated list of user addresses to add") .option( "-a, --address ", "Address of the access list contract", @@ -2028,20 +2307,24 @@ export async function createCLI() { ) .option("--chainId ", "Access-list chain (default: active chain)") .action(async (accessListAddress, users, options) => { + const listAddress = options.address || accessListAddress; + const listUsers = options.users || users; + if (!listAddress || !listUsers) { + throw new Error( + "An access-list address and user(s) are required. Pass them positionally or with --address / --users.", + ); + } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); if ((await routeExplicit(commands, options.chainId)) === null) return; - await commands.addToAccessList([ - options.address || accessListAddress, - options.users || users, - ]); + await commands.addToAccessList([listAddress, listUsers]); }); program .command("checkAccessList") .description("Check if user(s) are on an access list") - .argument("", "Address of the access list contract") - .argument("", "Comma-separated list of user addresses to check") + .argument("[accessListAddress]", "Address of the access list contract") + .argument("[users]", "Comma-separated list of user addresses to check") .option( "-a, --address ", "Address of the access list contract", @@ -2052,20 +2335,24 @@ export async function createCLI() { ) .option("--chainId ", "Access-list chain (default: active chain)") .action(async (accessListAddress, users, options) => { + const listAddress = options.address || accessListAddress; + const listUsers = options.users || users; + if (!listAddress || !listUsers) { + throw new Error( + "An access-list address and user(s) are required. Pass them positionally or with --address / --users.", + ); + } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); if ((await routeExplicit(commands, options.chainId)) === null) return; - await commands.checkAccessList([ - options.address || accessListAddress, - options.users || users, - ]); + await commands.checkAccessList([listAddress, listUsers]); }); program .command("removeFromAccessList") .description("Remove user(s) from an access list") - .argument("", "Address of the access list contract") - .argument("", "Comma-separated list of user addresses to remove") + .argument("[accessListAddress]", "Address of the access list contract") + .argument("[users]", "Comma-separated list of user addresses to remove") .option( "-a, --address ", "Address of the access list contract", @@ -2076,19 +2363,23 @@ export async function createCLI() { ) .option("--chainId ", "Access-list chain (default: active chain)") .action(async (accessListAddress, users, options) => { + const listAddress = options.address || accessListAddress; + const listUsers = options.users || users; + if (!listAddress || !listUsers) { + throw new Error( + "An access-list address and user(s) are required. Pass them positionally or with --address / --users.", + ); + } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); if ((await routeExplicit(commands, options.chainId)) === null) return; - await commands.removeFromAccessList([ - options.address || accessListAddress, - options.users || users, - ]); + await commands.removeFromAccessList([listAddress, listUsers]); }); program .command("downloadNodeLogs") .description("Download logs from a node as an admin") - .argument("", "Output directory to save the logs") + .argument("[output]", "Output directory to save the logs") .argument( "[last]", "Period of time to get logs from now (in hours). Use either last or from-to", @@ -2110,15 +2401,21 @@ export async function createCLI() { "-m, --maxLogs [maxLogs]", "Maximum number of logs to retrieve (default: 100, max: 1000)", ) - .action(async (output, last, from, to, options) => { + .action(async (output, last, from, to, maxLogs, options) => { + const outputDir = options.output || output; + if (!outputDir) { + throw new Error( + "An output directory is required. Pass it positionally or with --output.", + ); + } const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); await commands.downloadNodeLogs([ - options.output || output, + outputDir, options.last || last, options.from || from, options.to || to, - options.maxLogs, + options.maxLogs || maxLogs, ]); }); @@ -2223,8 +2520,14 @@ export async function createCLI() { "--token ", "Restrict to payment-token address(es), comma-separated; applied to every --chain", ) - .option("--max-price ", "Drop paid results costing more than this (human units)") - .option("--duration ", "Assumed job duration for the cost estimate") + .option( + "--max-price ", + "Drop paid results costing more than this (human units)", + ) + .option( + "--duration ", + "Assumed job duration for the cost estimate", + ) .option( "--order-by ", "Order results: price | freeCapacity | resources | leastBusy", diff --git a/src/commands.ts b/src/commands.ts index 83bee58..c042385 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -13,7 +13,9 @@ import { isOrderable, computeJobChainIds, summarizeComputeEnvFees, + prefundedLockUnits, getDdoChainId, + resolveSubsidyProviderAddresses, } from "./helpers.js"; import { getConfigFor, @@ -38,8 +40,15 @@ import { unitsToAmount, EscrowContract, getTokenDecimals, + estimateJobSubsidy, + isNonEmpty, AccesslistFactory, AccessListContract, + SubsidyView, + SubsidyKind, + SubsidyPeriod, + OPFSubsidyProvider, + OneTimeSubsidyProvider, ComputeResourceRequest, ComputeSearchDimensionResult, ServiceJob, @@ -69,14 +78,22 @@ import { estimateServiceCost, parseUserData, describeUserDataKeys, - verifyServiceEscrow, + quoteServicePayerShare, + fundServiceEscrow, pollServiceStatus, printServiceJob, formatExpiry, statusLabel, isTerminal, } from "./serviceHelpers.js"; -import { ensureP2PReady, getSearchSeedNode } from "./nodeConnection.js"; +import { + ensureP2PReady, + getSearchSeedNode, + getCurrentNodeUrl, + validateNode, + nodeSubsidyInfo, +} from "./nodeConnection.js"; +import { escrowContractFor } from "./escrowHelpers.js"; import { ResourceSearchParams, ProviderEnvRow, @@ -120,6 +137,11 @@ async function drainLogStream(stream: any): Promise { return Buffer.concat(chunks).toString("utf-8"); } +// `total - share` for display, without float noise (0.41 - 0.1 = 0.31, not 0.3099…). +function formatAmountDiff(total: number, share: string): string { + return Number((total - Number(share)).toFixed(18)).toString(); +} + export class Commands { public signer: Signer; public config: Config; @@ -544,7 +566,10 @@ export class Commands { ); } catch (error: unknown) { const message = error instanceof Error ? error.message : String(error); - console.error(chalk.red("Error getting Policy Server Object:"), message); + console.error( + chalk.red("Error getting Policy Server Object:"), + message, + ); return; } } @@ -901,10 +926,126 @@ export class Commands { } console.log(chalk.yellow("\n--- Payment Details ---")); console.log(JSON.stringify(providerInitializeComputeJob, null, 2)); + // Kept for computePrefundedUnits(), which the startCompute action calls before the + // payment prompt (one fresh Commands instance per invocation, methods run in turn). + this.computeQuoteCtx = { + signer: paymentSigner, + chainId: payChain, + node: providerURI, + token: paymentToken, + environmentId: computeEnv.id, + resources: parsedResources, + durationSeconds: supportedMaxJobDuration, + }; return providerInitializeComputeJob; } - public async computeStart(args: string[], paymentChainId?: number) { + private computeQuoteCtx?: { + signer: Signer; + chainId: number; + node: string; + token: string; + environmentId: string; + resources: ComputeResourceRequest[]; + durationSeconds: number; + }; + + // How much of a paid compute job's lock (base units) subsidy providers would + // pre-fund, for the job last passed to initializeCompute(). Lets the caller show the + // payer's real share before asking for confirmation, then hand the same figure to + // computeStart() so what was confirmed is what gets funded. + public async computePrefundedUnits( + subsidyProviders: string[] | undefined, + lockUnits: bigint, + ): Promise { + if (!this.computeQuoteCtx) return 0n; + return this.prefundedUnitsForJob({ + ...this.computeQuoteCtx, + jobType: 1, + // The node treats every algorithm a consumer supplies (raw code, a file or a + // DID) as untrusted for a provider's image allowlist, so a provider that + // restricts images never sponsors a compute job (the container is then + // irrelevant). Mirror that, or the estimate would count a subsidy the node + // will not apply. + hasCustomEntrypoint: true, + subsidyProviders, + lockUnits, + }); + } + + // Base units of the lock that subsidy providers would pre-fund for a paid compute + // job or on-demand service (0 when none do). Advisory and read-only: any failure to quote — an older + // node, an unreachable provider contract, an escrow the node advertises that is not + // the configured one — falls back to 0, i.e. the payer funds the whole job as before. + private async prefundedUnitsForJob(p: { + jobType: 1 | 2; // ocean-node numbering: compute | service + // The node's own predicate for "not the trusted operator image" (see call sites). + hasCustomEntrypoint: boolean; + signer: Signer; + chainId: number; + node: string; + token: string; + environmentId: string; + resources: ComputeResourceRequest[]; + durationSeconds: number; + container?: { + image?: string; + tag?: string; + checksum?: string; + dockerfile?: string; + }; + subsidyProviders?: string[]; + lockUnits: bigint; + }): Promise { + // `[]` is an explicit "no subsidy". + if (p.subsidyProviders && p.subsidyProviders.length === 0) return 0n; + try { + const decimals = Number(await getTokenDecimals(p.signer, p.token)); + const estimate = await estimateJobSubsidy({ + signer: p.signer, + chainId: p.chainId, + payer: await p.signer.getAddress(), + node: p.node, + token: p.token, + environmentId: p.environmentId, + resources: p.resources, + durationSeconds: p.durationSeconds, + jobType: p.jobType, + container: p.container ?? {}, + hasCustomEntrypoint: p.hasCustomEntrypoint, + // Quote against the amount actually being locked: the helper derives its own + // cost (with the env's minimum duration), which can exceed it. + subsidyNeeded: ethers.formatUnits(p.lockUnits, decimals), + customSubsidyProviders: p.subsidyProviders, + tokenDecimals: decimals, + config: this.configFor(p.chainId), + }); + return prefundedLockUnits( + estimate, + p.subsidyProviders, + decimals, + p.lockUnits, + ); + } catch (error) { + console.log( + chalk.yellow( + `Could not estimate the prepaid subsidy (${ + (error as Error)?.message ?? error + }); assuming you fund the whole job.`, + ), + ); + return 0n; + } + } + + public async computeStart( + args: string[], + paymentChainId?: number, + subsidyProviders?: string[], + // Pre-funded base units the caller already quoted (and showed the user) with + // computePrefundedUnits(); quoted here when omitted. + quotedPrefundedUnits?: bigint, + ) { const resolved = await resolveComputeInputs( args[1], args[2], @@ -1282,22 +1423,69 @@ export class Commands { return; } - const escrow = new EscrowContract( - getAddress(parsedProviderInitializeComputeJob.payment.escrowAddress), + // Version-matched ABI: a legacy escrow returns six-field authorizations, which the + // funds check below and the authorization reads after it must be able to decode. + const escrow = await escrowContractFor( + parsedProviderInitializeComputeJob.payment.escrowAddress, paymentSigner, + payChain, ); console.log("Verifying payment..."); await new Promise((resolve) => setTimeout(resolve, 3000)); + // amountToDeposit and maxLockedAmount must be in the SAME unit: the lib compares + // them directly and treats the larger as a human-readable amount. Pass the human + // amount for both (passing base units for maxLockedAmount makes the lib demand + // amount * 10^decimals tokens and the funds check always fails). + // The node's lock amount is authoritative. Subsidy providers may pre-fund part or + // all of it at lock time (Escrow v2), so only the remainder is the payer's to hold + // in escrow: a fully sponsored job needs no deposit at all. + const lockUnits = BigInt( + parsedProviderInitializeComputeJob.payment.amount.toString(), + ); + let prefundedUnits = quotedPrefundedUnits; + if (prefundedUnits === undefined) { + this.computeQuoteCtx = { + signer: paymentSigner, + chainId: payChain, + node: providerURI, + token: paymentToken, + environmentId: computeEnv.id, + resources: JSON.parse(resources), + durationSeconds: supportedMaxJobDuration, + }; + prefundedUnits = await this.computePrefundedUnits( + subsidyProviders, + lockUnits, + ); + } + if (prefundedUnits > lockUnits) prefundedUnits = lockUnits; + const payerUnits = lockUnits - prefundedUnits; + const paymentAmountHuman = await unitsToAmount( + paymentSigner, + paymentToken, + payerUnits.toString(), + ); + if (prefundedUnits > 0n && quotedPrefundedUnits === undefined) { + const [covered, total] = await Promise.all( + [prefundedUnits, lockUnits].map((units) => + unitsToAmount(paymentSigner, paymentToken, units.toString()), + ), + ); + console.log( + chalk.green( + `Prepaid subsidy covers ${covered} of ${total}; you fund ${paymentAmountHuman}.`, + ), + ); + } + // Called with the payer share even when it is 0: it deposits nothing then, but + // still creates or repairs the authorization the node needs to create the lock + // (a fresh wallet gets a zero-ceiling, sponsored-only one). const validationEscrow = await escrow.verifyFundsForEscrowPayment( paymentToken, computeEnv.consumerAddress, - await unitsToAmount( - paymentSigner, - paymentToken, - parsedProviderInitializeComputeJob.payment.amount, - ), - parsedProviderInitializeComputeJob.payment.amount.toString(), + paymentAmountHuman, + paymentAmountHuman, parsedProviderInitializeComputeJob.payment.minLockSeconds.toString(), "10", ); @@ -1326,9 +1514,8 @@ export class Commands { const minLockSeconds = parsedProviderInitializeComputeJob.payment.minLockSeconds.toString(); - const requiredUnits = BigInt( - parsedProviderInitializeComputeJob.payment.amount.toString(), - ); + // Only the payer's own share has to be available in escrow. + const requiredUnits = payerUnits; const availableUnits = async (): Promise => { // ethers returns the userFunds struct; `available` excludes what is locked. const funds = await escrow.getUserFunds(payerAddress, tokenAddress); @@ -1344,7 +1531,7 @@ export class Commands { ); console.log( chalk.yellow( - `Escrow balance is short of this job's cost — depositing ${shortfall}...`, + `Escrow balance is short of your share of this job's cost — depositing ${shortfall}...`, ), ); const tokenContract = new ethers.Contract( @@ -1369,7 +1556,7 @@ export class Commands { ); console.error( chalk.red( - `Escrow balance for token ${paymentToken} is below this job's cost (${needed}) and the deposit did not go through. ` + + `Escrow balance for token ${paymentToken} is below your share of this job's cost (${needed}) and the deposit did not go through. ` + `Deposit manually and retry:\n` + ` npm run cli depositEscrow ${paymentToken} ${needed}`, ), @@ -1387,18 +1574,14 @@ export class Commands { "Escrow authorization for the compute node is missing after the funds check — authorizing explicitly...", ), ); - // Ten times the job cost as the ceiling: locks accumulate against + // Ten times the payer's share as the ceiling: locks accumulate against // maxLockedAmount until they are claimed, so a ceiling of exactly one job's - // cost would reject the next job started before this one settles. - const jobCost = await unitsToAmount( - paymentSigner, - paymentToken, - parsedProviderInitializeComputeJob.payment.amount, - ); + // share would reject the next job started before this one settles. A fully + // sponsored job gives 0: the node may then lock only sponsored funds. const authorizeTx = await escrow.authorize( tokenAddress, payeeAddress, - (Number(jobCost) * 10).toString(), + (Number(paymentAmountHuman) * 10).toString(), minLockSeconds, "10", ); @@ -1467,6 +1650,13 @@ export class Commands { // additionalDatasets, only c2d v1 output, policiesServer, + undefined, // signal + undefined, // queueMaxWaitTime + undefined, // dockerRegistryAuth + undefined, // outputBucketId + // Consumer-selected subsidy providers (ocean.js #2160): tri-state — undefined lets + // the node use its configured defaults, [] claims with none, a list uses exactly those. + subsidyProviders, ); console.log("computeJobs: ", computeJobs); @@ -1939,11 +2129,20 @@ export class Commands { token: string, durationSeconds: number, accept?: boolean, + // The payer's own share from quoteServicePayerShare; below the cost when subsidy + // providers pre-fund part of the lock. + payerShareHuman?: string, ): Promise { + const youPay = payerShareHuman ?? String(costHuman); + const sponsored = Number(youPay) < costHuman; console.log( chalk.yellow( `\n--- Payment Details ---\n` + - ` estimated cost: ${costHuman} (token ${token})\n` + + ` estimated total cost: ${costHuman} (token ${token})\n` + + (sponsored + ? ` prepaid subsidy covers: ${formatAmountDiff(costHuman, youPay)}\n` + : "") + + ` you pay: ${youPay}\n` + ` duration: ${durationSeconds}s\n` + ` Note: the final cost is computed by the node and shown after start.`, ), @@ -1962,7 +2161,7 @@ export class Commands { } const rl = createInterface({ input, output }); const confirmation = await rl.question( - `\nProceed with payment of estimated ${costHuman} ${token} for ${durationSeconds}s? (y/n): `, + `\nProceed? Estimated total cost ${costHuman}, you pay ${youPay} (token ${token}) for ${durationSeconds}s (y/n): `, ); rl.close(); const answer = confirmation.trim().toLowerCase(); @@ -2013,11 +2212,6 @@ export class Commands { ); } } - if (t.requiredResources?.length) { - console.log( - ` requiredResources: ${JSON.stringify(t.requiredResources)}`, - ); - } if (t.recommendedResources?.length) { console.log( ` recommendedResources: ${JSON.stringify(t.recommendedResources)}`, @@ -2061,6 +2255,7 @@ export class Commands { accept?: boolean; wait?: boolean; timeout?: number; + subsidyProviders?: string[]; }): Promise { try { const { chainId } = await this.signer.provider.getNetwork(); @@ -2254,7 +2449,7 @@ export class Commands { const userDataKeys = describeUserDataKeys(userData); if (userDataKeys) console.log(`userData keys: ${userDataKeys}`); - // 6. Cost + escrow gate + // 6. Cost + the payer's share of it (read-only; funding happens after the prompt) const cost = estimateServiceCost( env, chainIdNum, @@ -2270,15 +2465,29 @@ export class Commands { ); return; } - const escrowOk = await verifyServiceEscrow( + const payerShare = await quoteServicePayerShare( this.signer, - chainIdNum, opts.paymentToken, - env.consumerAddress, cost, - opts.duration, + (lockUnits) => + this.prefundedUnitsForJob({ + jobType: 2, + // Same predicate the node applies to a service for the image allowlist. + hasCustomEntrypoint: + isNonEmpty(dockerEntrypoint) || isNonEmpty(dockerCmd), + signer: this.signer, + chainId: chainIdNum, + node: this.oceanNodeUrl, + token: opts.paymentToken, + environmentId: env.id, + resources, + durationSeconds: opts.duration, + container: { image, tag, checksum, dockerfile }, + subsidyProviders: opts.subsidyProviders, + lockUnits, + }), ); - if (!escrowOk) return; + if (payerShare === null) return; // 7. Confirmation prompt const proceed = await this.confirmServicePayment( @@ -2286,9 +2495,22 @@ export class Commands { opts.paymentToken, opts.duration, opts.accept, + payerShare, ); if (!proceed) return; + // Only now, after the user agreed, deposit the payer's share (if any is + // missing) and authorize the node. + const funded = await fundServiceEscrow( + this.signer, + chainIdNum, + opts.paymentToken, + env.consumerAddress, + payerShare, + opts.duration, + ); + if (!funded) return; + // 8. Start (async on the node — returns immediately in status Starting) const params: ServiceStartParams = { environment: env.id, @@ -2304,6 +2526,8 @@ export class Commands { duration: opts.duration, userData, // plain object; ocean.js encrypts it to the node payment: { chainId: chainIdNum, token: opts.paymentToken }, + // Tri-state consumer-selected subsidy providers (ocean.js #2160 / #2163). + subsidyProviders: opts.subsidyProviders, }; const jobs = await ProviderInstance.serviceStart( @@ -2470,6 +2694,7 @@ export class Commands { additionalDuration: number, paymentToken?: string, accept?: boolean, + subsidyProviders?: string[], ): Promise { try { if (!Number.isInteger(additionalDuration) || additionalDuration <= 0) { @@ -2578,15 +2803,36 @@ export class Commands { return; } - const escrowOk = await verifyServiceEscrow( + const payerShare = await quoteServicePayerShare( this.signer, - chainIdNum, token, - env.consumerAddress, cost, - additionalDuration, + (lockUnits) => + this.prefundedUnitsForJob({ + jobType: 2, + hasCustomEntrypoint: + isNonEmpty(job.dockerEntrypoint) || isNonEmpty(job.dockerCmd), + signer: this.signer, + chainId: chainIdNum, + node: this.oceanNodeUrl, + token, + environmentId: env.id, + resources: (job.resources ?? []).map((r: any) => ({ + id: r.id, + amount: r.amount, + })), + durationSeconds: additionalDuration, + container: { + image: job.image, + tag: job.tag, + checksum: job.checksum, + dockerfile: job.dockerfile, + }, + subsidyProviders, + lockUnits, + }), ); - if (!escrowOk) return; + if (payerShare === null) return; // 4. Confirmation prompt const proceed = await this.confirmServicePayment( @@ -2594,9 +2840,22 @@ export class Commands { token, additionalDuration, accept, + payerShare, ); if (!proceed) return; + // Only now, after the user agreed, deposit the payer's share (if any is + // missing) and authorize the node. + const funded = await fundServiceEscrow( + this.signer, + chainIdNum, + token, + env.consumerAddress, + payerShare, + additionalDuration, + ); + if (!funded) return; + // 5. Extend const oldExpiry = job.expiresAt; const extended = await ProviderInstance.serviceExtend( @@ -2606,6 +2865,8 @@ export class Commands { additionalDuration, { chainId: chainIdNum, token }, AbortSignal.timeout(120_000), + // Tri-state consumer-selected subsidy providers (ocean.js #2160). + subsidyProviders, ); const newJob = extended?.[0]; if (!newJob) { @@ -3112,6 +3373,10 @@ export class Commands { maxLockedAmount: string, maxLockSeconds: string, maxLockCounts: string, + // Escrow v2: unix timestamp (seconds) after which the payee can no longer create/extend + // locks. Omitted/undefined → "0" (indefinite, the pre-v2 behaviour). A past timestamp + // revokes; claim and cancel are never gated by it, so funds are never stuck. + expiryTimestamp?: string, ) { try { // Neither the Escrow contract nor ocean.js rejects a zero/negative limit — @@ -3131,6 +3396,22 @@ export class Commands { } } + // expiryTimestamp is optional; when given it must be a non-negative integer (unix + // seconds). "0" is the indefinite default. A value in the past is allowed on purpose — + // that is how a revoke is expressed. + let expiry = "0"; + if (expiryTimestamp !== undefined && expiryTimestamp !== "") { + if (!/^\d+$/.test(expiryTimestamp.trim())) { + console.error( + chalk.red( + `expiryTimestamp must be a non-negative unix timestamp in seconds (got "${expiryTimestamp}"). Use 0 for indefinite.`, + ), + ); + return false; + } + expiry = expiryTimestamp.trim(); + } + const escrowAddress = requireAddress( Number(this.config.chainId), "escrow", @@ -3139,40 +3420,32 @@ export class Commands { const escrow = new EscrowContract(getAddress(escrowAddress), this.signer); - console.log("Authorizing payee..."); + // Escrow v2: authorize() always sends a transaction now — it creates OR overwrites the + // on-chain record (it no longer silently no-ops when one already exists). That is what + // makes renew / shorten / revoke reachable: re-authorizing updates the limits, and a past + // expiry revokes. So authorizeTx is always a TransactionResponse here (never null). + // Format the ISO date defensively: a valid unix-seconds string can still be large + // enough that expiry * 1000 falls outside JavaScript Date's ±8.64e15 ms range, where + // toISOString() throws. The on-chain expiry is unaffected, so keep it and drop only the + // human-readable ISO suffix when conversion is invalid. + let expiryNote: string; + if (expiry === "0") { + expiryNote = "indefinite"; + } else { + const expiryDate = new Date(Number(expiry) * 1000); + expiryNote = Number.isNaN(expiryDate.getTime()) + ? `expiry ${expiry}` + : `expiry ${expiry} (${expiryDate.toISOString()})`; + } + console.log(`Authorizing payee... (${expiryNote})`); const authorizeTx = await escrow.authorize( getAddress(token), getAddress(payee), maxLockedAmount, maxLockSeconds, maxLockCounts, + expiry, ); - // ocean.js sends NO transaction when an authorization already exists for - // (payer, token, payee) — authorizeTx is null and the existing limits stay - // as they are. Say so explicitly: dereferencing null here used to surface - // as a TypeError under "Authorization failed", which reads like a chain - // error and hides the fact that the old, possibly lower, maxLockSeconds / - // maxLockedAmount / maxLockCounts are still in force. - if (!authorizeTx) { - const existing = await escrow.getAuthorizations( - getAddress(token), - await this.signer.getAddress(), - getAddress(payee), - ); - console.log( - chalk.yellow( - `Payee ${payee} is already authorized for token ${token} — the existing ` + - `authorization was left untouched (it cannot be raised or lowered here).`, - ), - ); - if (existing?.length) { - const a = existing[0]; - console.log( - ` maxLockedAmount (wei): ${a.maxLockedAmount} maxLockSeconds: ${a.maxLockSeconds} maxLockCounts: ${a.maxLockCounts}`, - ); - } - return true; - } await authorizeTx.wait(); console.log(`Successfully authorized payee ${payee} for token ${token}`); @@ -3190,8 +3463,10 @@ export class Commands { const payerAddress = getAddress(payer); const payeeAddress = getAddress(payee); const decimals = await getTokenDecimals(this.signer, token); - const escrow = new EscrowContract( - getAddress(requireAddress(chainId, "escrow", "Escrow")), + // Version-matched ABI: a legacy (v1) escrow returns six-field authorizations, which the + // lib's default seven-field ABI cannot decode. + const escrow = await escrowContractFor( + requireAddress(chainId, "escrow", "Escrow"), this.signer, chainId, ); @@ -3220,16 +3495,391 @@ export class Commands { decimals, ); + // Escrow v2: the auth tuple gained a 7th field, expiryTimestamp (unix seconds; 0 = + // indefinite). A legacy (v1) escrow returns a 6-field tuple (decoded with the six-field + // ABI above), so read defensively and treat a missing value as indefinite. + const expiryRaw = authorization.expiryTimestamp ?? authorization[6] ?? "0"; + const expirySeconds = Number(expiryRaw); + const expiryLabel = + !expirySeconds || expirySeconds === 0 + ? "indefinite (0)" + : `${expirySeconds} (${new Date(expirySeconds * 1000).toISOString()})${ + expirySeconds * 1000 < Date.now() ? " — EXPIRED/revoked" : "" + }`; + console.log("Authorizations found:"); - console.log(`- Current Locked Amount: ${Number(currentLockedAmount)}`); + // Escrow v2: currentLockedAmount reflects only the payer's OWN locked funds (P), not any + // provider-sponsored portion (S). The sponsored bucket is read via getEscrowInfo. + console.log( + `- Current Locked Amount (payer-funded): ${Number(currentLockedAmount)}`, + ); console.log(`- Current Locks: ${authorization.currentLocks}`); console.log(`- Max locked amount: ${Number(maxLockedAmount)}`); console.log(`- Max lock seconds: ${authorization.maxLockSeconds}`); console.log(`- Max lock counts: ${authorization.maxLockCounts}`); + console.log(`- Expiry: ${expiryLabel}`); return authorizations; } + /** + * Read-only Escrow v2 diagnostics for the active (or --chainId) chain. Uses ERC-165 capability + * discovery so it also prints something sensible against a legacy (pre-v2) escrow. When a token + * is supplied it additionally prints, for a lock-subsidy escrow, the sponsored bucket total and + * the signer's reclaimable amount, and for an enterprise escrow, the token's fee gate. + */ + public async getEscrowInfo(token?: string) { + const chainId = Number(this.config.chainId); + const escrowAddress = requireAddress(chainId, "escrow", "Escrow"); + const escrow = new EscrowContract( + getAddress(escrowAddress), + this.signer, + chainId, + ); + + console.log(`Escrow ${escrowAddress} (chain ${chainId}):`); + + // version() / escrowKind() only exist on a v2 escrow — a legacy escrow reverts or lacks the + // method, which surfaces as a thrown error; catch and report "legacy (pre-v2)". + let isV2 = true; + try { + const version = await escrow.version(); + console.log(`- Version: ${version}`); + } catch { + isV2 = false; + console.log("- Version: legacy (pre-v2, no on-chain version())"); + } + + if (isV2) { + try { + const kind = await escrow.escrowKind(); + console.log( + `- Kind: ${kind === 1 ? "ENTERPRISE (fee-gated)" : "COMMUNITY (permissionless)"}`, + ); + } catch { + /* escrowKind not available — ignore */ + } + } + + // supportsInterface() is safe against a legacy escrow (returns false on revert). + const lockSubsidy = await escrow.isEscrowLockSubsidy(); + const enterprise = await escrow.isEscrowEnterprise(); + console.log(`- Lock-time sponsorship (IEscrowLockSubsidy): ${lockSubsidy}`); + console.log(`- Enterprise (IEscrowEnterprise): ${enterprise}`); + + if (lockSubsidy) { + try { + const max = await escrow.maxSponsorsPerLock(); + console.log(`- Max sponsors per lock: ${max}`); + } catch { + /* ignore */ + } + } + + if (!token) { + if (lockSubsidy || enterprise) { + console.log( + chalk.gray( + "Pass a token address to also see the sponsored bucket / fee gate for that token.", + ), + ); + } + return; + } + + const tokenAddress = getAddress(token); + + if (lockSubsidy) { + try { + const sponsoredTotal = await escrow.getSponsoredTotal(tokenAddress); + const reclaimable = await escrow.getReclaimable( + await this.signer.getAddress(), + tokenAddress, + ); + console.log(`- Sponsored bucket total (${token}): ${sponsoredTotal}`); + console.log(`- Your reclaimable (${token}): ${reclaimable}`); + } catch (error) { + console.error(chalk.yellow("Could not read sponsorship state:"), error); + } + } + + if (enterprise) { + try { + const collector = await escrow.feeCollector(); + const allowed = await escrow.isTokenAllowed(tokenAddress); + console.log(`- Fee collector: ${collector}`); + console.log(`- Token allowed (${token}): ${allowed}`); + } catch (error) { + console.error( + chalk.yellow("Could not read enterprise fee gate:"), + error, + ); + } + } + } + + // Map the user's --jobType to the on-chain JobType enum (NONE=0, COMPUTE=1, SERVICE=2, + // fixed by the escrow claim ABI). Accepts a name or a raw number; throws on anything else. + private mapJobType(jt?: string): number | undefined { + if (jt === undefined) return undefined; + const s = jt.trim().toLowerCase(); + if (s === "compute") return 1; + if (s === "service") return 2; + if (s === "none") return 0; + if (/^\d+$/.test(s)) return Number(s); + throw new Error( + `Unknown --jobType '${jt}' (use compute | service | none, or a number).`, + ); + } + + /** + * Read-only, provider-agnostic subsidy report (ocean.js #2163 / contracts #1052). Discovers + * the provider contracts from the current node, then for each one uses the `SubsidyView` base + * wrapper (ERC-165) to print a unified report — kind, per-window buckets (limit/used/remaining), + * the claimable amount now, contract balance and eligibility — plus kind-specific detail for + * rolling-window (OPF) and one-time providers. Answers "do I have credit available?". + */ + public async getSubsidyStatus( + token: string, + opts: { + subsidy?: string; + node?: string; + jobType?: string; + amount?: string; + } = {}, + ): Promise { + if (!token) { + console.error( + chalk.red( + "A token address is required. Pass it positionally (getSubsidyStatus 0x...) or with --token 0x...", + ), + ); + return; + } + const chainId = Number(this.config.chainId); + const payer = await this.signer.getAddress(); + const tokenAddress = getAddress(token); + + // Provider addresses come from the node (or, when its provider filter is off, from the + // caller's own --subsidy list), never from bundled config. `--node` + // (opts.node) targets a specific Ocean Node to query (URL / peer id / multiaddr, + // like setNode); without it we use the active node. The on-chain node operator + // address for isNodeAllowed / quoteSubsidy is taken from that node's own status + // (status.address), so the caller never has to supply it separately. + const nodeUrl = opts.node || getCurrentNodeUrl(); + if (!nodeUrl) { + console.error( + chalk.red( + "No Ocean Node to query. Set one with setNode, or pass --node .", + ), + ); + return; + } + const status = await validateNode(nodeUrl); + if (!status) { + console.error( + chalk.red( + `Could not read status of ${nodeUrl}. The node advertises which subsidy providers it supports.`, + ), + ); + return; + } + const { providers, filter } = nodeSubsidyInfo(status); + const nodeAddress = status.address ? getAddress(status.address) : undefined; + + let addresses: string[]; + let jobType: number | undefined; + try { + const resolved = resolveSubsidyProviderAddresses( + chainId, + providers, + filter, + opts.subsidy, + ); + addresses = resolved.addresses; + if (resolved.ignored.length) { + console.warn( + chalk.yellow( + `Ignoring --subsidy address(es) the node does not advertise (its provider filter is on): ${resolved.ignored.join( + ", ", + )}`, + ), + ); + } + if (resolved.notAdvertised.length) { + console.log( + chalk.yellow( + `Not a node default — the node accepts these only when named with --subsidyProviders: ${resolved.notAdvertised.join( + ", ", + )}`, + ), + ); + } + jobType = this.mapJobType(opts.jobType); + } catch (e) { + console.error(chalk.red((e as Error).message)); + return; + } + + for (const address of addresses) { + console.log( + chalk.cyan(`\n=== Subsidy provider ${address} (chain ${chainId}) ===`), + ); + try { + const view = new SubsidyView(this.signer, address, chainId); + // We don't gate on `isSubsidyView()` (ERC-165) — it can under-report. `subsidyKind()` + // is the liveness probe: if it reverts, the address isn't a readable subsidy view + // (which also covers a user-named `--subsidy` address the node does not vouch for). + let kind: SubsidyKind; + try { + kind = await view.subsidyKind(); + } catch { + console.warn( + chalk.yellow( + ` ${address} is not a readable subsidy provider (subsidyKind() reverted) — skipping.`, + ), + ); + continue; + } + console.log(` Kind: ${SubsidyKind[kind] ?? kind}`); + + const report = await view.subsidyBuckets(payer, tokenAddress); + console.log( + report.paused + ? chalk.red( + " Paused: true (this subsidy provider is paused — no claims are possible)", + ) + : chalk.green(" Paused: false"), + ); + console.log( + report.userAllowed + ? chalk.green(" User allowed: true") + : chalk.red( + " User allowed: false (you are not on this provider's user access list — you cannot use this subsidy provider)", + ), + ); + console.log( + report.tokenEnabled + ? chalk.green(" Token enabled: true") + : chalk.red( + " Token enabled: false (this token is not subsidised by this provider)", + ), + ); + if (!report.buckets || report.buckets.length === 0) { + console.log(" Buckets: (none)"); + } else { + console.log(" Buckets:"); + for (const b of report.buckets) { + const period = SubsidyPeriod[b.period] ?? b.period; + const cap = b.unlimited ? "unlimited" : b.limit; + const reset = + b.resetsAt && b.resetsAt !== "0" ? ` resetsAt=${b.resetsAt}` : ""; + console.log( + ` - ${period}: limit=${cap} used=${b.used} remaining=${b.remaining}${reset}`, + ); + } + } + + console.log( + ` Remaining subsidy (claimable now): ${await view.remainingSubsidy( + payer, + tokenAddress, + )}`, + ); + console.log( + ` Contract available balance: ${await view.availableBalance( + tokenAddress, + )}`, + ); + if (nodeAddress) { + const nodeAllowed = await view.isNodeAllowed(nodeAddress); + console.log( + nodeAllowed + ? chalk.green( + ` Node allowed (isNodeAllowed, ${nodeAddress}): true`, + ) + : chalk.red( + ` Node allowed (isNodeAllowed, ${nodeAddress}): false (this node is not on the provider's node access list — it cannot use this subsidy provider)`, + ), + ); + } + if (jobType !== undefined) { + console.log( + ` Job type subsidized (${opts.jobType}): ${await view.isJobTypeSubsidized( + jobType, + )}`, + ); + } + + // Optional quote — needs the queried node's address, a job type and an amount. + if (opts.amount && nodeAddress && jobType !== undefined) { + const quote = await view.quoteSubsidy( + nodeAddress, + payer, + jobType, + tokenAddress, + opts.amount, + opts.amount, // subsidyNeeded: request the full amount; the contract caps it + ); + console.log( + ` Quote for amount ${opts.amount}: subsidy=${quote.subsidy} bonus=${quote.bonus}`, + ); + } + + // Kind-specific detail (subsidyBuckets already covers the core numbers). + if (kind === SubsidyKind.ROLLING_WINDOW) { + const opf = new OPFSubsidyProvider(this.signer, address, chainId); + const limits = await opf.getTokenLimits(tokenAddress); + console.log(" Rolling-window detail:"); + console.log( + ` token config: subsidy=${Number(limits.pctBps) / 100}%`, + ); + console.log( + ` remaining daily/weekly/monthly: ${await opf.remainingDaily( + payer, + tokenAddress, + )} / ${await opf.remainingWeekly( + payer, + tokenAddress, + )} / ${await opf.remainingMonthly(payer, tokenAddress)}`, + ); + console.log( + ` used daily/weekly/monthly: ${await opf.dailyUsedBy( + payer, + tokenAddress, + )} / ${await opf.weeklyUsedBy( + payer, + tokenAddress, + )} / ${await opf.monthlyUsedBy(payer, tokenAddress)}`, + ); + } else if (kind === SubsidyKind.ONE_TIME) { + const one = new OneTimeSubsidyProvider(this.signer, address, chainId); + const cfg = await one.getTokenConfig(tokenAddress); + console.log(" One-time detail:"); + console.log( + ` token config: subsidy=${Number(cfg.pctBps) / 100}% defaultCredit=${ + cfg.defaultCredit + }`, + ); + console.log( + ` effective/remaining/used credit: ${await one.effectiveCredit( + payer, + tokenAddress, + )} / ${await one.remainingCredit( + payer, + tokenAddress, + )} / ${await one.usedBy(payer, tokenAddress)}`, + ); + } + } catch (error) { + console.error( + chalk.red(` Error reading ${address}:`), + (error as Error).message ?? error, + ); + } + } + } + public async createAccessList(args: string[]): Promise { try { const name = args[0]; diff --git a/src/escrowHelpers.ts b/src/escrowHelpers.ts new file mode 100644 index 0000000..aeb2f06 --- /dev/null +++ b/src/escrowHelpers.ts @@ -0,0 +1,122 @@ +import { Contract, Signer, getAddress, isCallException, isError } from "ethers"; +import { EscrowContract } from "@oceanprotocol/lib"; + +type AbiEntry = { + type?: string; + name?: string; + outputs?: { components?: { name?: string }[] }[]; + [key: string]: unknown; +}; + +/** + * The escrow ABI as a legacy (pre-v2) deployment answers it: `getAuthorizations` returns the + * six-field `auth` tuple, without the trailing `expiryTimestamp` Escrow v2 added. Decoding a + * legacy reply with the seven-field ABI overruns the returned data and throws, so reads must + * use this shape. Everything else is left as-is. Pure. + */ +export function legacyEscrowAbi(abi: T[]): T[] { + return abi.map((entry) => { + const item = entry as AbiEntry; + if (item?.type !== "function" || item.name !== "getAuthorizations") { + return entry; + } + return { + ...item, + outputs: (item.outputs ?? []).map((out) => ({ + ...out, + components: (out.components ?? []).filter( + (c) => c.name !== "expiryTimestamp", + ), + })), + } as T; + }); +} + +/** + * A legacy escrow is one with no on-chain `version()` (the call reverts or returns no data) or + * one that reports version 1; Escrow v2 returns 2. Any other failure (RPC down, timeout) is NOT + * taken as "legacy": decoding a v2 reply with the six-field ABI would silently misread it, so + * when in doubt the current ABI is kept. + */ +export async function isLegacyEscrow( + address: string, + signer: Signer, +): Promise { + const probe = new Contract( + address, + ["function version() view returns (uint16)"], + signer, + ); + try { + return Number(await probe.version()) < 2; + } catch (error) { + return isCallException(error) || isError(error, "BAD_DATA"); + } +} + +const AUTH_FIELDS = [ + "payee", + "maxLockedAmount", + "currentLockedAmount", + "maxLockSeconds", + "maxLockCounts", + "currentLocks", +] as const; + +/** + * A six-field legacy authorization in the v2 shape: the same values by index and by name, + * plus `expiryTimestamp` = 0 (indefinite) as the seventh. Needed because an ethers `Result` + * THROWS on an out-of-range index, so the usual `auth.expiryTimestamp ?? auth[6] ?? 0` + * fallback (here and inside the lib's funds check) cannot be applied to the raw tuple. Pure. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export function withIndefiniteExpiry(auth: any): any { + const values: unknown[] = AUTH_FIELDS.map((_, i) => auth[i]); + values.push(0n); + const named: Record = { expiryTimestamp: 0n }; + AUTH_FIELDS.forEach((name, i) => (named[name] = values[i])); + return Object.assign(values, named); +} + +class LegacyEscrowContract extends EscrowContract { + async getAuthorizations( + token: string, + payer: string, + payee: string, + ): Promise { + const raw = await super.getAuthorizations(token, payer, payee); + return Array.from(raw ?? []).map(withIndefiniteExpiry); + } +} + +const legacyByEscrow = new Map>(); + +/** + * An `EscrowContract` whose authorization reads decode with the ABI matching the deployed + * escrow version: the six-field tuple for a legacy escrow, the lib's default ABI otherwise. + * Legacy authorizations come back in the v2 shape with `expiryTimestamp` = 0, so every reader + * (the CLI and the lib's own funds check) sees them as indefinite. The version probe is + * cached per chain and address. + */ +export async function escrowContractFor( + address: string, + signer: Signer, + chainId: number, +): Promise { + const escrowAddress = getAddress(address); + const escrow = new EscrowContract(escrowAddress, signer, chainId); + const key = `${chainId}:${escrowAddress}`; + let legacy = legacyByEscrow.get(key); + if (!legacy) { + legacy = isLegacyEscrow(escrowAddress, signer); + legacyByEscrow.set(key, legacy); + } + if (!(await legacy)) return escrow; + return new LegacyEscrowContract( + escrowAddress, + signer, + chainId, + undefined, + legacyEscrowAbi(escrow.getDefaultAbi()), + ); +} diff --git a/src/helpers.ts b/src/helpers.ts index a04900d..c1f2c80 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -23,6 +23,7 @@ import { ComputeAsset, createAsset, LoggerInstance, + JobSubsidyEstimate, } from "@oceanprotocol/lib"; import { createRequire } from "module"; @@ -262,7 +263,9 @@ export async function handleComputeOrder( const { services } = ddoInstance.getDDOFields(); const service = services?.[serviceIndex]; if (!Number.isInteger(serviceIndex) || serviceIndex < 0 || !service) { - throw new Error(`Service index ${serviceIndex} not found in asset ${asset.id}`); + throw new Error( + `Service index ${serviceIndex} not found in asset ${asset.id}`, + ); } // Validate new orders before approving fees. Reuse does not need indexed datatokens. let datatokenIndex: number; @@ -525,9 +528,10 @@ export async function resolveComputeInputs( }; } else if (algoToken && typeof algoToken === "object") { const rawAlgo = algoToken as unknown as ComputeAlgorithm; - if (!rawAlgo.fileObject) { + // The node accepts the code either as a file to fetch or inline in meta.rawcode. + if (!rawAlgo.fileObject && !rawAlgo.meta?.rawcode) { console.error( - "Error: raw algorithm must contain a 'fileObject'. Got: " + + "Error: raw algorithm must contain a 'fileObject' or 'meta.rawcode'. Got: " + JSON.stringify(algoToken), ); return null; @@ -743,8 +747,168 @@ export function summarizeComputeEnvFees(env: { const tokens = (fees[chainId] || []) .map((f) => f?.feeToken) .filter((t): t is string => typeof t === "string" && t.length > 0); - const tokenList = tokens.length > 0 ? tokens.join(", ") : "(no tokens listed)"; + const tokenList = + tokens.length > 0 ? tokens.join(", ") : "(no tokens listed)"; return ` chain ${chainId}: ${tokenList}`; }); return `${header}: pays on\n${lines.join("\n")}`; } + +/** + * Parse the `--subsidyProviders` CLI value into the tri-state the Ocean Node expects + * (ocean-node #1485, ocean.js #2160): + * - flag omitted -> `undefined` (the node uses its configured defaults) + * - `none` / empty string -> `[]` (explicitly claim with NO subsidy providers) + * - a CSV of addresses -> `string[]` (use exactly these, EIP-55 normalized) + * Preserving the `undefined` vs `[]` distinction is essential — the ocean.js request + * body is truthy-guarded (`if (subsidyProviders)`), and `[]` is truthy, so an empty + * array is transmitted while `undefined` is omitted. + * Throws on a malformed address. + */ +export function parseSubsidyProviders(raw?: string): string[] | undefined { + if (raw === undefined) return undefined; + const trimmed = raw.trim(); + if (trimmed === "" || trimmed.toLowerCase() === "none") return []; + return trimmed.split(",").map((a) => ethers.getAddress(a.trim())); +} + +export interface ResolvedSubsidyProviders { + /** Provider contracts to query (EIP-55, de-duplicated). */ + addresses: string[]; + /** Filter OFF: `--subsidy` addresses queried although the node does not advertise them. */ + notAdvertised: string[]; + /** Filter ON: `--subsidy` addresses dropped because the node would reject them. */ + ignored: string[]; +} + +/** + * Resolve the subsidy-provider contract addresses `getSubsidyStatus` reports on. The Ocean + * Node is the source of truth for what is usable, so nothing is read from bundled config / + * ADDRESS_FILE — the candidates are the node's status `subsidyProviders[chainId]` and the + * caller's own `--subsidy` list, and the node's `subsidyProviderFilter` decides how they mix: + * - no `--subsidy` -> the node's advertised list (error when it is empty); + * - `--subsidy` + filter OFF -> exactly the named addresses. The node accepts any provider + * a consumer names per request, so they are reported whether or not it advertises them + * (the ones it does not are returned in `notAdvertised`); + * - `--subsidy` + filter ON -> the named addresses narrowed to the node's list, since it + * rejects anything else (the rest are returned in `ignored`). + * Pure: the caller prints the notes. Throws on a malformed address or when nothing is usable. + */ +export function resolveSubsidyProviderAddresses( + chainId: number, + nodeProviders: Record | undefined, + filter: boolean, + override?: string, +): ResolvedSubsidyProviders { + const fromNode = [ + ...new Set( + (nodeProviders?.[String(chainId)] ?? []).map((a) => ethers.getAddress(a)), + ), + ]; + const wanted = [ + ...new Set( + (override ?? "") + .split(",") + .map((a) => a.trim()) + .filter(Boolean) + .map((a) => { + try { + return ethers.getAddress(a); + } catch { + throw new Error(`Invalid --subsidy address '${a}'.`); + } + }), + ), + ]; + const nodeSet = new Set(fromNode); + + if (!filter) { + if (wanted.length) { + return { + addresses: wanted, + notAdvertised: wanted.filter((a) => !nodeSet.has(a)), + ignored: [], + }; + } + if (fromNode.length === 0) { + throw new Error( + `This node supports subsidies but has no subsidy providers configured on chain ${chainId}. Pass --subsidy 0x... to check a specific provider (the node's provider filter is off, so it accepts providers named per request).`, + ); + } + return { addresses: fromNode, notAdvertised: [], ignored: [] }; + } + + if (fromNode.length === 0) { + throw new Error( + `This node does not support subsidy providers on chain ${chainId}: the provider filter is on and its configured list is empty, so no provider can be used.`, + ); + } + if (wanted.length === 0) { + return { addresses: fromNode, notAdvertised: [], ignored: [] }; + } + const kept = wanted.filter((a) => nodeSet.has(a)); + if (kept.length === 0) { + throw new Error( + `None of the --subsidy addresses are advertised by the node on chain ${chainId}, and its provider filter is on, so it would reject them.`, + ); + } + return { + addresses: kept, + notAdvertised: [], + ignored: wanted.filter((a) => !nodeSet.has(a)), + }; +} + +/** + * How much of a job's lock the subsidy providers would PRE-FUND, in token base units, + * read off an ocean.js `estimateJobSubsidy` result. What is left is the payer's own + * share — the only amount that has to sit in (and be authorized on) the payer's escrow. + * + * `requested` is the `--subsidyProviders` tri-state, and it decides which providers the + * node will actually put in the lock: + * - `undefined` -> the node's own set, which is what the estimate's prefunded scenario + * was built from, so its projected total is used as-is; + * - a list -> the node uses exactly those (a REPLACEMENT of its set), while the + * estimate quotes `advertised ∪ list`. Only the named providers are counted, so an + * advertised provider the user did not name never shrinks the payer's deposit; + * - `[]` -> no subsidy, nothing is pre-funded. + * + * An empty prefunded selection means no provider pre-funds (or the escrow has no + * lock-subsidy support) and yields 0. The result is capped at `lockUnits`, the node's + * authoritative lock amount, so a client-side cost estimate above it cannot push the + * payer share below zero. + */ +export function prefundedLockUnits( + estimate: Pick< + JobSubsidyEstimate, + "providers" | "scenarios" | "maxSponsorsPerLock" + >, + requested: string[] | undefined, + decimals: number, + lockUnits: bigint, +): bigint { + const scenario = estimate.scenarios.prefunded; + if (scenario.selected.length === 0) return 0n; + if (requested !== undefined && requested.length === 0) return 0n; + + let total: bigint; + if (requested === undefined) { + total = ethers.parseUnits(scenario.projectedTotalSubsidy, decimals); + } else { + // The node keeps the first `maxSponsorsPerLock` entries of the caller's list. + const named = new Set( + requested + .slice(0, estimate.maxSponsorsPerLock) + .map((a) => a.toLowerCase()), + ); + total = estimate.providers + .filter((p) => p.eligible && !p.dropped) + .filter((p) => named.has(p.address.toLowerCase())) + .reduce( + (sum, p) => + sum + ethers.parseUnits(p.quotes.prefunded.subsidy, decimals), + 0n, + ); + } + return total > lockUnits ? lockUnits : total; +} diff --git a/src/nodeConnection.ts b/src/nodeConnection.ts index 2ffde3d..81d3c08 100644 --- a/src/nodeConnection.ts +++ b/src/nodeConnection.ts @@ -268,3 +268,28 @@ export function nodeChainIds(status: NodeStatus): string[] { ]; return [...new Set(ids)]; } + +/** + * Subsidy-provider info the node advertises in its status (ocean-node #1479/#1485): + * `subsidyProviders` is a per-chain map (chainId -> checksummed contract addresses) and + * `subsidyProviderFilter` tells whether the node restricts user-supplied providers to that + * configured set. The node is the single source of truth for which providers are usable — + * a node may not support subsidies at all, in which case `providers` is `{}`. + * + * ocean.js's `NodeStatus` type may not (yet) declare these fields, but the node returns + * them at runtime, so we read them through a local narrowing cast rather than depend on + * the lib type. Older nodes that omit them yield `{}` / `false`. + */ +export function nodeSubsidyInfo(status: NodeStatus): { + providers: Record; + filter: boolean; +} { + const s = status as unknown as { + subsidyProviders?: Record; + subsidyProviderFilter?: boolean; + }; + return { + providers: s.subsidyProviders ?? {}, + filter: Boolean(s.subsidyProviderFilter), + }; +} diff --git a/src/serviceHelpers.ts b/src/serviceHelpers.ts index 9e1f06a..c4e0adb 100644 --- a/src/serviceHelpers.ts +++ b/src/serviceHelpers.ts @@ -1,9 +1,8 @@ import util from "util"; import chalk from "chalk"; -import { Signer, getAddress } from "ethers"; +import { Signer } from "ethers"; import { ProviderInstance, - EscrowContract, amountToUnits, unitsToAmount, getTokenDecimals, @@ -14,8 +13,12 @@ import { ServiceStatusNumber, ServiceTemplatePublic, TemplateResourceRequirement, + sizeSharedResources, + planGpuLayouts, + grantableAmount, } from "@oceanprotocol/lib"; import { getConfigFor } from "./rpcRegistry.js"; +import { escrowContractFor } from "./escrowHelpers.js"; // --------------------------------------------------------------------------- // 4.1 Status labels @@ -61,28 +64,44 @@ function colorForStatus(status: number, text: string): string { // --------------------------------------------------------------------------- // 4.2 Environment <-> template resource matching -// (ported from ocean.js test/integration/Services.test.ts) +// (delegates to ocean.js's unit-aware ServiceResources helpers) // --------------------------------------------------------------------------- +// +// ocean.js v10 replaced ServiceTemplatePublic.requiredResources with +// `recommendedResources`, and turned TemplateResourceRequirement into a +// discriminated union: cpu/ram/disk members carry `id` + `recommended` (cpu in +// `cores`, ram/disk in `GB`), while the GPU member carries `type: 'gpu'` + +// `layouts` and no `id`. Because ram/disk are now declared in GB while a +// compute environment reports those resources in bytes, matching must be +// unit-aware — so we lean on the library's `sizeSharedResources` / +// `planGpuLayouts` instead of comparing raw numbers. + +// Narrows a requirement to its shared (cpu/ram/disk) member — the GPU member is +// the only one without an `id`. +type SharedRequirement = Extract; +type GpuRequirement = Extract; + +function isSharedRequirement( + req: TemplateResourceRequirement, +): req is SharedRequirement { + return "id" in req; +} +// Whole units of a single shared requirement a new booking could still get. +// Only meaningful for cpu (cores) — ram/disk use byte-vs-GB sizing handled by +// the library — so this stays a best-effort display helper. export function availableFor( env: ComputeEnvironment, req: TemplateResourceRequirement, ): number { const resources: ComputeResource[] = env.resources ?? []; - if (req.id) { + if (isSharedRequirement(req)) { const r = resources.find((x) => x.id === req.id); - return r ? (r.total ?? 0) - (r.inUse ?? 0) : 0; + return r ? grantableAmount(r) : 0; } return resources - .filter((x) => x.kind === req.kind && (!req.type || x.type === req.type)) - .reduce((sum, x) => sum + ((x.total ?? 0) - (x.inUse ?? 0)), 0); -} - -export function envSatisfiesTemplate( - env: ComputeEnvironment, - reqs?: TemplateResourceRequirement[], -): boolean { - return (reqs ?? []).every((req) => availableFor(env, req) >= req.min); + .filter((x) => x.type === "gpu") + .reduce((sum, x) => sum + grantableAmount(x), 0); } // Human-readable reason a template does not fit an env (or null when it fits). @@ -91,25 +110,47 @@ export function templateMismatchReason( template?: ServiceTemplatePublic, ): string | null { if (!template) return null; - for (const req of template.requiredResources ?? []) { - const have = availableFor(env, req); - if (have < req.min) { - const what = - req.id ?? `${req.kind ?? "resource"}${req.type ? `/${req.type}` : ""}`; - return `${what}: need ${req.min}, have ${have}`; + const reqs = template.recommendedResources ?? []; + const resources = env.resources ?? []; + + // Shared cpu/ram/disk: unit-aware sizing (GB -> bytes) from the library. + const shared = reqs.filter(isSharedRequirement); + if (shared.length && sizeSharedResources(resources, shared) === null) { + // cpu is the only id we can compare in like units for a precise message. + const cpu = shared.find((r) => r.id === "cpu"); + if (cpu && availableFor(env, cpu) < cpu.recommended) { + return `cpu: recommended ${cpu.recommended} ${cpu.unit}, available ${availableFor( + env, + cpu, + )}`; + } + return "insufficient cpu/ram/disk for the template's recommended resources"; + } + + // GPU: layout planning from the library. + const gpu = reqs.find((r): r is GpuRequirement => !isSharedRequirement(r)); + if (gpu) { + const gpuResources = resources.filter((r) => r.type === "gpu"); + if (planGpuLayouts({ gpuResources, requirement: gpu }).length === 0) { + return `gpu: no layout on this environment satisfies the template's recommended ${gpu.recommended} ${gpu.unit} per GPU`; } } return null; } +export function envSatisfiesTemplate( + env: ComputeEnvironment, + template?: ServiceTemplatePublic, +): boolean { + return templateMismatchReason(env, template) === null; +} + export function findServiceEnvironments( envs: ComputeEnvironment[], template?: ServiceTemplatePublic, ): ComputeEnvironment[] { return (envs ?? []).filter( - (e) => - e.features?.services !== false && - (!template || envSatisfiesTemplate(e, template.requiredResources)), + (e) => e.features?.services !== false && envSatisfiesTemplate(e, template), ); } @@ -121,12 +162,18 @@ export function resolveServiceResources( template: ServiceTemplatePublic | undefined, env: ComputeEnvironment, ): ComputeResourceRequest[] { - const requiredById = (template?.requiredResources ?? []).filter( - (r) => typeof r.id === "string", + // Unit-aware sizing of the template's recommended cpu/ram/disk against the + // environment (converts the template's GB figures to the bytes the node + // expects, and drops zero amounts). GPU layout selection, when needed, is + // left to an explicit --resources selection. + const sizing = sizeSharedResources( + env.resources ?? [], + template?.recommendedResources, ); - if (requiredById.length) { - return requiredById.map((r) => ({ id: r.id as string, amount: r.min })); + if (sizing && sizing.requests.length) { + return sizing.requests; } + // Fallback: a minimal cpu + ram request. return (env.resources ?? []) .filter((r) => r.id === "cpu" || r.id === "ram") .map((r) => ({ id: r.id, amount: 1 })); @@ -247,16 +294,71 @@ export function describeUserDataKeys( } // --------------------------------------------------------------------------- -// 4.6 Escrow pre-verification +// 4.6 Escrow: quote the payer's share, then fund it // --------------------------------------------------------------------------- +// +// Two steps so the caller can ask for confirmation in between: the quote is read-only, +// and nothing is deposited or authorized until the user has seen what they pay. + +// Read-only. Returns the payer's own share of the cost (human units): the full cost, or +// less when subsidy providers pre-fund part of the lock (zero when fully sponsored). +// Prints the error and returns null when it cannot be worked out. +/** + * A JS number as a plain decimal string with at most `decimals` fraction digits — what + * `amountToUnits` accepts. `String(n)` does not qualify: a float cost such as 0.1 + 0.2 + * prints 17 fraction digits (more than a 6-decimal token allows) and a tiny one prints in + * exponent form, and both make the conversion throw. Rounds to nearest. Pure. + */ +export function toTokenPrecision(amount: number, decimals: number): string { + if (!Number.isFinite(amount) || amount < 0) { + throw new Error(`Invalid cost amount: ${amount}`); + } + return amount.toFixed(Math.min(Math.max(Math.trunc(decimals), 0), 100)); +} + +export async function quoteServicePayerShare( + signer: Signer, + token: string, + costHuman: number, // from estimateServiceCost + // Given the lock amount (base units), returns how much of it subsidy providers would + // pre-fund at lock time. Omitted = nothing is pre-funded, the payer funds it all. + quotePrefunded?: (lockUnits: bigint) => Promise, +): Promise { + try { + const decimals = await getTokenDecimals(signer, token); + const lockUnits = BigInt( + ( + await amountToUnits( + signer, + token, + toTokenPrecision(costHuman, Number(decimals)), + decimals, + ) + ).toString(), + ); + let prefundedUnits = quotePrefunded ? await quotePrefunded(lockUnits) : 0n; + if (prefundedUnits > lockUnits) prefundedUnits = lockUnits; + return await unitsToAmount( + signer, + token, + (lockUnits - prefundedUnits).toString(), + decimals, + ); + } catch (error) { + console.error(chalk.red("Error estimating the escrow amount:"), error); + return null; + } +} -// Prints actionable errors and returns false when escrow is not ready. -export async function verifyServiceEscrow( +// Sends transactions: deposits whatever part of the payer's share is missing from +// escrow and creates or repairs the node's authorization. Call it only after the user +// confirmed. Prints actionable errors and returns false when escrow is not ready. +export async function fundServiceEscrow( signer: Signer, chainId: number, token: string, payee: string, // env.consumerAddress - costHuman: number, // from estimateServiceCost + payerShareHuman: string, // from quoteServicePayerShare durationSeconds: number, ): Promise { try { @@ -269,31 +371,18 @@ export async function verifyServiceEscrow( ); return false; } - const escrow = new EscrowContract( - getAddress(config.escrow), - signer, - chainId, - ); - const decimals = await getTokenDecimals(signer, token); - const amountUnits = await amountToUnits( - signer, - token, - String(costHuman), - decimals, - ); - const availableHuman = await unitsToAmount( - signer, - token, - amountUnits.toString(), - decimals, - ); + // Version-matched ABI, so the funds check can read a legacy escrow's authorizations. + const escrow = await escrowContractFor(config.escrow, signer, chainId); const minLockSeconds = durationSeconds + 3600; // node getMinLockTime margin + // Both amounts are HUMAN units (the lib compares them directly). Called even for a + // payer share of 0: it deposits nothing then, but still creates or repairs the + // authorization the node needs to create the lock. const validation = await escrow.verifyFundsForEscrowPayment( token, payee, - availableHuman, - amountUnits.toString(), + payerShareHuman, + payerShareHuman, String(minLockSeconds), "10", ); diff --git a/test/accessList.test.ts b/test/accessList.test.ts index 382b6b1..6f0a232 100644 --- a/test/accessList.test.ts +++ b/test/accessList.test.ts @@ -84,7 +84,7 @@ describe("Ocean CLI Access List", function () { expect(error.stderr || error.message).to.satisfy( (msg: string) => msg.includes("error: missing required argument") || - msg.includes("Name and symbol are required"), + msg.includes("A name and symbol are required"), ); } }); @@ -118,7 +118,7 @@ describe("Ocean CLI Access List", function () { expect(error.stderr || error.message).to.satisfy( (msg: string) => msg.includes("error: missing required argument") || - msg.includes("at least one user are required"), + msg.includes("An access-list address and user(s) are required"), ); } }); diff --git a/test/escrow.test.ts b/test/escrow.test.ts index 2582225..5a88d2b 100644 --- a/test/escrow.test.ts +++ b/test/escrow.test.ts @@ -36,6 +36,21 @@ describe("Ocean CLI Escrow", function () { await runCommand(`npm run cli -- mintOcean`); }); + // The expiryTimestamp stored on-chain for the payer -> payee authorization (Escrow v2). + async function storedExpiry(): Promise { + const escrow = new EscrowContract( + getAddress(escrowAddress), + payer, + chainConfig.chainId, + ); + const authorizations = await escrow.getAuthorizations( + tokenAddress, + payer.address, + payee.address, + ); + return Number(authorizations[0].expiryTimestamp); + } + it("should deposit tokens into escrow", async function () { const depositAmount = "1"; @@ -137,5 +152,60 @@ describe("Ocean CLI Escrow", function () { expect(output).to.include("Max locked amount: 1"); expect(output).to.include("Max lock seconds: 3600"); expect(output).to.include("Max lock counts: 10"); + // Escrow v2: the authorization now carries an expiry; the one set above was indefinite. + expect(output).to.include("Expiry:"); + expect(output).to.include("indefinite (0)"); + expect(await storedExpiry()).to.equal(0); + }); + + it("should re-authorize a payee with an expiry (Escrow v2 overwrite)", async function () { + // A future expiry. authorize() in Escrow v2 overwrites the existing record instead of + // no-op'ing, so this renews the authorization with a bounded expiry. + const expiry = Math.floor(Date.now() / 1000) + 3600; + + const output = await runCommand( + `npm run cli -- authorizeEscrow ${tokenAddress} ${payee.address} 1 3600 10 --expiry ${expiry}`, + ); + expect(output).to.include("Authorization successful"); + + const info = await runCommand( + `npm run cli getAuthorizationsEscrow ${tokenAddress} ${payee.address}`, + ); + // Expiry is now a concrete timestamp, not "indefinite (0)". + expect(info).to.include("Expiry:"); + expect(info).to.not.include("indefinite (0)"); + expect(await storedExpiry()).to.equal(expiry); + }); + + it("should revoke a payee with a past expiry (Escrow v2)", async function () { + // A timestamp in the past revokes: the payee can no longer create new locks, but existing + // locks stay claimable/cancellable. + const output = await runCommand( + `npm run cli -- authorizeEscrow ${tokenAddress} ${payee.address} 1 3600 10 --expiry 1`, + ); + expect(output).to.include("Authorization successful"); + + const info = await runCommand( + `npm run cli getAuthorizationsEscrow ${tokenAddress} ${payee.address}`, + ); + expect(info).to.include("EXPIRED/revoked"); + expect(await storedExpiry()).to.equal(1); + }); + + it("should reject a non-numeric expiry", async function () { + const output = await runCommand( + `npm run cli -- authorizeEscrow ${tokenAddress} ${payee.address} 1 3600 10 --expiry not-a-timestamp`, + ); + expect(output).to.include("Authorization failed"); + }); + + it("should report escrow capabilities via getEscrowInfo", async function () { + const output = await runCommand( + `npm run cli getEscrowInfo ${tokenAddress}`, + ); + // Against the Escrow v2 deployment this prints the version and the ERC-165 capability flags. + expect(output).to.include("Version:"); + expect(output).to.include("Lock-time sponsorship (IEscrowLockSubsidy):"); + expect(output).to.include("Enterprise (IEscrowEnterprise):"); }); }); diff --git a/test/escrowHelpers.unit.test.ts b/test/escrowHelpers.unit.test.ts new file mode 100644 index 0000000..406b385 --- /dev/null +++ b/test/escrowHelpers.unit.test.ts @@ -0,0 +1,103 @@ +import { expect } from "chai"; +import { createRequire } from "module"; +import { AbiCoder, Interface } from "ethers"; +import { legacyEscrowAbi, withIndefiniteExpiry } from "../src/escrowHelpers.js"; +import { toTokenPrecision } from "../src/serviceHelpers.js"; + +// Pure unit tests — no infra needed. +const require = createRequire(import.meta.url); +const { + abi, +} = require("@oceanprotocol/contracts/artifacts/contracts/escrow/Escrow.sol/Escrow.json"); + +const PAYEE = "0x4Fd5ECf4Af8490418462A7d80e90A0530eFb9ac5"; +const coder = AbiCoder.defaultAbiCoder(); +// What a legacy (v1) escrow returns: auth[] with six fields, no expiryTimestamp. +const legacyReply = coder.encode( + ["tuple(address,uint256,uint256,uint256,uint256,uint256)[]"], + [[[PAYEE, 100n, 5n, 3600n, 10n, 1n]]], +); +const v2Reply = coder.encode( + ["tuple(address,uint256,uint256,uint256,uint256,uint256,uint256)[]"], + [[[PAYEE, 100n, 5n, 3600n, 10n, 1n, 1234n]]], +); + +describe("legacyEscrowAbi", () => { + it("drops only expiryTimestamp from the getAuthorizations tuple", () => { + const legacy = legacyEscrowAbi(abi); + expect(legacy).to.have.length(abi.length); + const fields = (list: any[]) => + list + .find((e) => e.name === "getAuthorizations") + .outputs[0].components.map((c: any) => c.name); + expect(fields(abi)).to.include("expiryTimestamp"); + expect(fields(legacy)).to.deep.equal([ + "payee", + "maxLockedAmount", + "currentLockedAmount", + "maxLockSeconds", + "maxLockCounts", + "currentLocks", + ]); + // Every other entry is passed through untouched (authorize keeps its v2 signature). + const others = (list: any[]) => + list.filter((e) => e.name !== "getAuthorizations"); + expect(others(legacy)).to.deep.equal(others(abi)); + }); + + it("decodes a legacy reply the default ABI cannot", () => { + expect(() => + new Interface(abi).decodeFunctionResult("getAuthorizations", legacyReply), + ).to.throw(); + const [auths] = new Interface(legacyEscrowAbi(abi)).decodeFunctionResult( + "getAuthorizations", + legacyReply, + ); + expect(auths).to.have.length(1); + expect(auths[0].payee).to.equal(PAYEE); + expect(auths[0].maxLockedAmount).to.equal(100n); + expect(auths[0].currentLocks).to.equal(1n); + // The raw six-field Result throws on index 6, so the usual + // `expiryTimestamp ?? [6] ?? 0` fallback only works on the normalized shape. + expect(() => auths[0][6]).to.throw(RangeError); + const auth = withIndefiniteExpiry(auths[0]); + expect(Number(auth.expiryTimestamp ?? auth[6] ?? "0")).to.equal(0); + expect(auth[6]).to.equal(0n); + expect(auth).to.have.length(7); + expect(auth.payee).to.equal(PAYEE); + expect(auth[1]).to.equal(100n); + expect(auth.currentLockedAmount).to.equal(5n); + expect(auth.maxLockSeconds).to.equal(3600n); + expect(auth.maxLockCounts).to.equal(10n); + expect(auth.currentLocks).to.equal(1n); + }); + + it("leaves the default ABI reading a v2 reply with its expiry", () => { + const [auths] = new Interface(abi).decodeFunctionResult( + "getAuthorizations", + v2Reply, + ); + expect(auths[0].expiryTimestamp).to.equal(1234n); + }); +}); + +describe("toTokenPrecision", () => { + it("trims float artifacts to the token's decimals", () => { + expect(String(0.1 + 0.2)).to.equal("0.30000000000000004"); + expect(toTokenPrecision(0.1 + 0.2, 6)).to.equal("0.300000"); + expect(toTokenPrecision(1.0000005, 6)).to.equal("1.000001"); + expect(toTokenPrecision(12.5, 18)).to.equal("12.500000000000000000"); + }); + + it("never emits exponent notation", () => { + expect(String(1e-7)).to.equal("1e-7"); + expect(toTokenPrecision(1e-7, 6)).to.equal("0.000000"); + expect(toTokenPrecision(1e-7, 18)).to.equal("0.000000100000000000"); + }); + + it("handles zero-decimal tokens and rejects bad amounts", () => { + expect(toTokenPrecision(2.4, 0)).to.equal("2"); + expect(() => toTokenPrecision(NaN, 6)).to.throw("Invalid cost amount"); + expect(() => toTokenPrecision(-1, 6)).to.throw("Invalid cost amount"); + }); +}); diff --git a/test/replMenu.test.ts b/test/replMenu.test.ts index 90788d7..28408fe 100644 --- a/test/replMenu.test.ts +++ b/test/replMenu.test.ts @@ -54,10 +54,11 @@ describe("Ocean CLI interactive menu (REPL)", function () { }); it("survives a command with a missing required argument", async function () { - // getDDO requires ; the parse error must not terminate the REPL, and a + // downloadJobResults requires (positional-only, no + // option alternative); the parse error must not terminate the REPL, and a // subsequent command must still run. const { output, code } = await runRepl([ - "getDDO", + "downloadJobResults", "definitelyNotACommand", "exit", ]); diff --git a/test/resolveComputeInputs.test.ts b/test/resolveComputeInputs.test.ts index ce8fe50..3b4b28c 100644 --- a/test/resolveComputeInputs.test.ts +++ b/test/resolveComputeInputs.test.ts @@ -176,7 +176,23 @@ describe("resolveComputeInputs", function () { expect(res).to.equal(null); }); - it("fails (returns null) when a raw algorithm object lacks a fileObject", async function () { + it("accepts a raw algorithm that carries inline meta.rawcode instead of a fileObject", async function () { + const res = await resolveComputeInputs( + "[]", + JSON.stringify({ + meta: { rawcode: "print(1)", container: { image: "python" } }, + }), + makeAquarius(), + indexingParams, + FALLBACK, + ); + expect(res.algoDdo).to.equal(null); + expect(res.algo.fileObject).to.equal(undefined); + expect(res.algo.meta.rawcode).to.equal("print(1)"); + expect(res.assets).to.have.length(0); + }); + + it("fails (returns null) when a raw algorithm object has neither a fileObject nor meta.rawcode", async function () { const res = await resolveComputeInputs( "did:op:dataset1", JSON.stringify({ meta: { container: {} } }), diff --git a/test/subsidyProviders.test.ts b/test/subsidyProviders.test.ts new file mode 100644 index 0000000..ae91854 --- /dev/null +++ b/test/subsidyProviders.test.ts @@ -0,0 +1,235 @@ +import { expect } from "chai"; +import { + parseSubsidyProviders, + prefundedLockUnits, + resolveSubsidyProviderAddresses, +} from "../src/helpers.js"; + +// Pure unit test — no infra needed. Verifies the tri-state parsing of the +// `--subsidyProviders` CLI value and EIP-55 address normalization. +describe("parseSubsidyProviders", () => { + it("returns undefined when the flag is omitted (node default)", () => { + expect(parseSubsidyProviders(undefined)).to.equal(undefined); + }); + + it("returns [] for 'none' (explicitly no subsidy)", () => { + expect(parseSubsidyProviders("none")).to.deep.equal([]); + expect(parseSubsidyProviders("NONE")).to.deep.equal([]); + }); + + it("returns [] for an empty / whitespace string", () => { + expect(parseSubsidyProviders("")).to.deep.equal([]); + expect(parseSubsidyProviders(" ")).to.deep.equal([]); + }); + + it("parses a single address", () => { + const a = "0x4344d4bc29531db736378e9a3da85bf1eff0cb22"; + expect(parseSubsidyProviders(a)).to.deep.equal([ + "0x4344D4Bc29531DB736378e9A3dA85BF1eff0CB22", + ]); + }); + + it("parses and normalizes a comma-separated list, trimming whitespace", () => { + const raw = + " 0x4344d4bc29531db736378e9a3da85bf1eff0cb22 , 0x0000000000000000000000000000000000000001 "; + expect(parseSubsidyProviders(raw)).to.deep.equal([ + "0x4344D4Bc29531DB736378e9A3dA85BF1eff0CB22", + "0x0000000000000000000000000000000000000001", + ]); + }); + + it("throws on a malformed address", () => { + expect(() => parseSubsidyProviders("0xnot-an-address")).to.throw(); + }); +}); + +// Pure unit test — no infra needed. `prefundedLockUnits` reads an ocean.js +// `estimateJobSubsidy` result and returns how much of the lock is pre-funded. +describe("prefundedLockUnits", () => { + const A = "0x4344D4Bc29531DB736378e9A3dA85BF1eff0CB22"; + const B = "0x0000000000000000000000000000000000000001"; + const C = "0x0000000000000000000000000000000000000002"; + const DECIMALS = 6; + const LOCK = 400000n; // 0.4 + + const quote = (address: string, prefunded: string, eligible = true) => ({ + address, + subsidyKind: null, + version: 2, + isV2: true, + gates: { + imageAllowed: eligible, + isNodeAllowed: true, + isUserAllowed: true, + isJobTypeSubsidized: true, + }, + eligible, + ...(eligible ? {} : { dropped: "image_not_allowed" as const }), + quotes: { + reimbursement: { subsidy: "0", bonus: "0" }, + prefunded: { subsidy: prefunded, bonus: "0" }, + }, + }); + + const estimate = ( + providers: ReturnType[], + selected: string[], + projected: string, + maxSponsorsPerLock = 10, + ) => ({ + providers, + maxSponsorsPerLock, + scenarios: { + reimbursement: { + mode: 0, + selected: [], + projectedTotalSubsidy: "0", + meetsSubsidyNeeded: false, + escrowNeeded: "0.4", + escrowAvailable: "0", + escrowShortfall: "0.4", + }, + prefunded: { + mode: 1, + selected, + projectedTotalSubsidy: projected, + meetsSubsidyNeeded: true, + escrowNeeded: "0", + escrowAvailable: "0", + escrowShortfall: "0", + }, + }, + }); + + it("uses the node-set projection when the flag is omitted (full cover)", () => { + const e = estimate([quote(A, "0.4")], [A], "0.4"); + expect(prefundedLockUnits(e, undefined, DECIMALS, LOCK)).to.equal(LOCK); + }); + + it("returns the partial cover, leaving the rest to the payer", () => { + const e = estimate([quote(A, "0.1")], [A], "0.1"); + expect(prefundedLockUnits(e, undefined, DECIMALS, LOCK)).to.equal(100000n); + }); + + it("returns 0 for an explicit empty list (no subsidy)", () => { + const e = estimate([quote(A, "0.4")], [A], "0.4"); + expect(prefundedLockUnits(e, [], DECIMALS, LOCK)).to.equal(0n); + }); + + it("returns 0 when nothing is pre-funded (refund-only or no lock-subsidy escrow)", () => { + const e = estimate([quote(A, "0")], [], "0"); + expect(prefundedLockUnits(e, undefined, DECIMALS, LOCK)).to.equal(0n); + expect(prefundedLockUnits(e, [A], DECIMALS, LOCK)).to.equal(0n); + }); + + it("counts only the providers the user named, not the rest of the node's set", () => { + const e = estimate([quote(A, "0.3"), quote(B, "0.1")], [A, B], "0.4"); + expect(prefundedLockUnits(e, [B], DECIMALS, LOCK)).to.equal(100000n); + expect( + prefundedLockUnits(e, [B.toLowerCase(), A], DECIMALS, LOCK), + ).to.equal(LOCK); + }); + + it("ignores a named provider the estimate dropped", () => { + const e = estimate([quote(A, "0.3", false), quote(B, "0.1")], [B], "0.1"); + expect(prefundedLockUnits(e, [A, B], DECIMALS, LOCK)).to.equal(100000n); + }); + + it("counts only the first maxSponsorsPerLock named providers", () => { + const e = estimate( + [quote(A, "0.1"), quote(B, "0.1"), quote(C, "0.1")], + [A, B], + "0.2", + 2, + ); + expect(prefundedLockUnits(e, [A, B, C], DECIMALS, LOCK)).to.equal(200000n); + }); + + it("caps the result at the node's lock amount", () => { + const e = estimate([quote(A, "0.9")], [A], "0.9"); + expect(prefundedLockUnits(e, undefined, DECIMALS, LOCK)).to.equal(LOCK); + expect(prefundedLockUnits(e, [A], DECIMALS, LOCK)).to.equal(LOCK); + }); +}); + +// Which provider contracts `getSubsidyStatus` reports on: the node's advertised list and the +// caller's `--subsidy` list, mixed according to the node's provider filter. +describe("resolveSubsidyProviderAddresses", () => { + const CHAIN = 8453; + const A = "0x4Fd5ECf4Af8490418462A7d80e90A0530eFb9ac5"; + const B = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; + const node = (list: string[]) => ({ [String(CHAIN)]: list }); + + it("filter off: queries a named provider even when the node advertises none", () => { + for (const providers of [node([]), {}, undefined]) { + expect( + resolveSubsidyProviderAddresses( + CHAIN, + providers, + false, + A.toLowerCase(), + ), + ).to.deep.equal({ addresses: [A], notAdvertised: [A], ignored: [] }); + } + }); + + it("filter off: allows named providers outside the node list and flags them", () => { + expect( + resolveSubsidyProviderAddresses( + CHAIN, + node([A]), + false, + `${A}, ${B},${A}`, + ), + ).to.deep.equal({ addresses: [A, B], notAdvertised: [B], ignored: [] }); + }); + + it("filter off: no --subsidy and an empty node list errors with a --subsidy hint", () => { + expect(() => resolveSubsidyProviderAddresses(CHAIN, node([]), false)) + .to.throw("has no subsidy providers configured on chain 8453") + .and.to.match(/--subsidy/); + }); + + it("no --subsidy: returns the node's de-duplicated list, whatever the filter", () => { + for (const filter of [false, true]) { + expect( + resolveSubsidyProviderAddresses( + CHAIN, + node([A.toLowerCase(), A, B]), + filter, + " ", + ), + ).to.deep.equal({ addresses: [A, B], notAdvertised: [], ignored: [] }); + } + }); + + it("filter on: narrows --subsidy to the node list and reports the rest", () => { + expect( + resolveSubsidyProviderAddresses(CHAIN, node([A]), true, `${A},${B}`), + ).to.deep.equal({ addresses: [A], notAdvertised: [], ignored: [B] }); + }); + + it("filter on: errors when no named provider is advertised", () => { + expect(() => + resolveSubsidyProviderAddresses(CHAIN, node([A]), true, B), + ).to.throw("None of the --subsidy addresses are advertised"); + }); + + it("filter on: an empty node list is unsupported, even with --subsidy", () => { + expect(() => + resolveSubsidyProviderAddresses(CHAIN, node([]), true, A), + ).to.throw("does not support subsidy providers on chain 8453"); + }); + + it("only reads the requested chain", () => { + expect(() => resolveSubsidyProviderAddresses(1, node([A]), false)).to.throw( + "no subsidy providers configured on chain 1", + ); + }); + + it("throws a readable error on a malformed --subsidy address", () => { + expect(() => + resolveSubsidyProviderAddresses(CHAIN, node([A]), false, "0xnope"), + ).to.throw("Invalid --subsidy address '0xnope'"); + }); +});