@oceanprotocol/lib 10.0.0 → 11.0.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,6 +22,20 @@ export interface ComputeResourceRequest {
22
22
  id: string;
23
23
  amount: number;
24
24
  }
25
+ /** Result of `estimateServiceCost` — mirrors ocean-node's `calculateResourcesCost`. */
26
+ export interface ServiceCostEstimate {
27
+ /** Cost in human token units, computed with the node's own arithmetic. */
28
+ costHuman: number;
29
+ /** `feeToken` verbatim as the env advertised it (send this back, not the caller's casing). */
30
+ feeToken: string;
31
+ /** Duration after the env minimum-duration floor clamp. */
32
+ effectiveDurationSeconds: number;
33
+ /** `ceil(effectiveDuration / 60)` — what the node actually bills. */
34
+ minutesBilled: number;
35
+ resources: ComputeResourceRequest[];
36
+ /** Resource ids the env has no price for; the node prices these at 0 silently. */
37
+ unpricedResourceIds: string[];
38
+ }
25
39
  export interface ComputeResource {
26
40
  id: string;
27
41
  type?: ComputeResourceType;
@@ -50,6 +64,7 @@ export interface ComputeEnvironmentFreeOptions {
50
64
  export interface ComputeEnvFeatures {
51
65
  computeJobs?: boolean;
52
66
  services?: boolean;
67
+ secureTls?: boolean;
53
68
  }
54
69
  export interface ComputeEnvironment {
55
70
  id: string;
@@ -70,6 +70,18 @@ export interface NodeStatus {
70
70
  provider: NodeStatusProvider[];
71
71
  indexer: NodeStatusIndexer[];
72
72
  escrowAddress: Record<string, string>;
73
+ /** chainId -> subsidy-provider contract addresses the node applies. Absent on older nodes. */
74
+ subsidyProviders?: Record<string, string[]>;
75
+ /**
76
+ * When true, a caller-supplied `subsidyProviders` list must be a subset of the node's
77
+ * `subsidyProviders` for the chain (the node rejects the request otherwise). Absent on older nodes.
78
+ */
79
+ subsidyProviderFilter?: boolean;
80
+ /**
81
+ * Per-provider-contract image allowlist (provider address -> allowed docker refs). A provider
82
+ * only subsidizes a job whose image matches; `{}` / absent = unrestricted. Absent on older nodes.
83
+ */
84
+ subsidyProviderAllowedImages?: Record<string, string[]>;
73
85
  /** Maintenance (drain) mode. Absent on nodes that predate the feature. */
74
86
  maintenance?: NodeStatusMaintenance;
75
87
  supportedStorage: Record<string, boolean>;
@@ -76,6 +76,7 @@ export interface ServiceJobEndpoint {
76
76
  containerPort: number;
77
77
  hostPort: number;
78
78
  url: string;
79
+ tls?: boolean;
79
80
  }
80
81
  export declare enum ServiceStatusNumber {
81
82
  Starting = 10,// DB record created by the start handler; awaits background processing
@@ -138,6 +139,7 @@ export interface ServiceJob {
138
139
  metadata?: ComputeJobMetadata;
139
140
  outputBucketId?: string;
140
141
  outputArchives?: ServiceOutputArchive[];
142
+ secureTls?: number[];
141
143
  }
142
144
  export type ServiceJobListed = Omit<ServiceJob, 'dockerCmd' | 'dockerEntrypoint' | 'dockerfile' | 'additionalDockerFiles' | 'runtimeMetrics' | 'outputArchives'>;
143
145
  export interface ServiceListFilters {
@@ -161,6 +163,7 @@ export interface ServiceContainerSpec {
161
163
  dockerCmd?: string[];
162
164
  dockerEntrypoint?: string[];
163
165
  metadata?: ComputeJobMetadata;
166
+ secureTls?: number[];
164
167
  }
165
168
  export type ServiceRestartParams = ServiceContainerSpec;
166
169
  export interface ServiceStartParams extends ServiceContainerSpec {
@@ -0,0 +1,112 @@
1
+ import type { Signer } from 'ethers';
2
+ import type { Config } from '../config/index.js';
3
+ import type { ComputeResourceRequest } from './Compute.js';
4
+ import type { OceanNode } from './Provider.js';
5
+ import type { SubsidyKind, SubsidyMode, SubsidyQuote } from './SubsidyView.js';
6
+ import type { SubsidyImageContainer } from '../utils/SubsidyImage.js';
7
+ import type { BaseProvider } from '../services/providers/BaseProvider.js';
8
+ /** Why a subsidy-provider candidate was excluded from the selection. */
9
+ export type SubsidyDropReason = 'image_not_allowed' | 'outside_node_set' | 'node_not_allowed' | 'user_not_allowed' | 'job_type_not_subsidized' | 'zero_quote' | 'error';
10
+ export interface EstimateJobSubsidyParams {
11
+ signer: Signer;
12
+ chainId: number;
13
+ /** Payer (consumer) address. */
14
+ payer: string;
15
+ /** Works over HTTP or P2P (the provider façade dispatches). */
16
+ node: OceanNode;
17
+ token: string;
18
+ environmentId: string;
19
+ /** Caller-supplied resources (no auto-selection). */
20
+ resources: ComputeResourceRequest[];
21
+ durationSeconds: number;
22
+ /** REQUIRED — ocean-node numbering: COMPUTE=1, SERVICE=2. */
23
+ jobType: number | string;
24
+ /** The image gate needs tag/checksum/dockerfile, not just an image name. */
25
+ container: SubsidyImageContainer;
26
+ /**
27
+ * Set true when the job must NOT be subsidized under a provider's image allowlist because the
28
+ * workload is not the trusted operator image. The caller computes it with the node's OWN predicate
29
+ * for the job type (the helper takes no algorithm/task object, so it cannot derive this):
30
+ * - service: `isNonEmpty(dockerEntrypoint) || isNonEmpty(dockerCmd)`
31
+ * - compute: `isNonEmpty(algorithm.meta.container.entrypoint) || hasUserSuppliedAlgorithm(algorithm)`
32
+ * where a user-supplied algorithm (rawcode, a `fileObject`, or a `documentId`/`serviceId` DID) is
33
+ * untrusted and must set this true. Omitting it for compute would subsidize an attacker algorithm
34
+ * run against a trusted image's allowlist. Default false.
35
+ */
36
+ hasCustomEntrypoint?: boolean;
37
+ /**
38
+ * Compute-only: the env's queue max wait (seconds). Added to the lock duration used for
39
+ * `minLockSeconds` (the node locks for job duration + queue wait), NOT to the billed cost.
40
+ * Default 0.
41
+ */
42
+ queueMaxWaitTime?: number;
43
+ /** Added to what the node advertises (see the filter semantics on `estimateJobSubsidy`). */
44
+ customSubsidyProviders?: string[];
45
+ /** Human token units; default = the job cost. */
46
+ subsidyNeeded?: string;
47
+ tokenDecimals?: number;
48
+ config?: Config;
49
+ /** Defaults to the shared `ProviderInstance`. */
50
+ provider?: BaseProvider;
51
+ signal?: AbortSignal;
52
+ }
53
+ export interface JobSubsidyProviderQuote {
54
+ /** Checksummed address (raw input when it was not a valid address). */
55
+ address: string;
56
+ subsidyKind: SubsidyKind | null;
57
+ version: number | null;
58
+ isV2: boolean;
59
+ gates: {
60
+ /** Gate off OR address unlisted OR an allowlist entry matches. */
61
+ imageAllowed: boolean;
62
+ /** null = the provider does not expose the check (unknown, NOT disqualifying). */
63
+ isNodeAllowed: boolean | null;
64
+ isUserAllowed: boolean | null;
65
+ isJobTypeSubsidized: boolean | null;
66
+ };
67
+ /** Image allowed AND no gate is an explicit false. */
68
+ eligible: boolean;
69
+ dropped?: SubsidyDropReason;
70
+ reason?: string;
71
+ /** Human token units; a v1 provider's prefunded leg is '0'. */
72
+ quotes: {
73
+ reimbursement: SubsidyQuote;
74
+ prefunded: SubsidyQuote;
75
+ };
76
+ }
77
+ export interface JobSubsidyScenario {
78
+ mode: SubsidyMode;
79
+ /** THE list to pass as `subsidyProviders` at start. */
80
+ selected: string[];
81
+ /** Sum of the selected providers under this mode, capped at the cost. */
82
+ projectedTotalSubsidy: string;
83
+ meetsSubsidyNeeded: boolean;
84
+ /** REIMBURSEMENT = cost; PREFUNDED = max(0, cost - projectedTotalSubsidy). */
85
+ escrowNeeded: string;
86
+ /** Payer's withdrawable escrow balance for the token. */
87
+ escrowAvailable: string;
88
+ /** max(0, escrowNeeded - escrowAvailable). */
89
+ escrowShortfall: string;
90
+ }
91
+ export interface JobSubsidyEstimate {
92
+ chainId: number;
93
+ /** Payee (node status `address`). */
94
+ node: string;
95
+ token: string;
96
+ /** Human token units (the node is authoritative at start). */
97
+ cost: string;
98
+ costBaseUnits: string;
99
+ minutesBilled: number;
100
+ minLockSeconds: number;
101
+ escrowAddress: string;
102
+ maxSponsorsPerLock: number;
103
+ subsidyProviderFilter: boolean;
104
+ subsidyNeeded: string;
105
+ unpricedResourceIds: string[];
106
+ providers: JobSubsidyProviderQuote[];
107
+ scenarios: {
108
+ reimbursement: JobSubsidyScenario;
109
+ prefunded: JobSubsidyScenario;
110
+ };
111
+ warnings: string[];
112
+ }
@@ -19,3 +19,4 @@ export * from './EscrowEvents.js';
19
19
  export * from './OPFSubsidyProvider.js';
20
20
  export * from './OneTimeSubsidyProvider.js';
21
21
  export * from './SubsidyView.js';
22
+ export * from './SubsidyEstimate.js';
@@ -66,7 +66,8 @@ export declare class EscrowContract extends SmartContractWithAddress {
66
66
  * to check that the shortfall is affordable. The payee is (re-)authorized up to the funding
67
67
  * target.
68
68
  * @param {String} token as payment token for escrow
69
- * @param {String} consumerAddress as consumerAddress for that environment
69
+ * @param {String} payee the node's address acting as the escrow payee, i.e. the account being
70
+ * authorized to create locks against the payer's (signer's) escrow funds
70
71
  * @param {String} amountToDeposit wanted deposit (human units). When omitted, the funding target
71
72
  * defaults to maxLockedAmount; only the shortfall from current escrow funds is deposited.
72
73
  * @param {String} maxLockedAmount amount necessary to be paid for starting compute job,
@@ -91,7 +92,7 @@ export declare class EscrowContract extends SmartContractWithAddress {
91
92
  * existing ceiling) and caps never lower than the existing record's (counts also leave a free slot).
92
93
  * @return {Promise<ValidationResponse>} validation response
93
94
  */
94
- verifyFundsForEscrowPayment(token: string, consumerAddress: string, amountToDeposit?: string, maxLockedAmount?: string, maxLockSeconds?: string, maxLockCounts?: string, tokenDecimals?: number, expiryTimestamp?: string): Promise<ValidationResponse>;
95
+ verifyFundsForEscrowPayment(token: string, payee: string, amountToDeposit?: string, maxLockedAmount?: string, maxLockSeconds?: string, maxLockCounts?: string, tokenDecimals?: number, expiryTimestamp?: string): Promise<ValidationResponse>;
95
96
  /**
96
97
  * Pure helper: merges a required authorization with the prior record (authorize() overwrites in
97
98
  * place, keeping currentLocked/currentLocks). Never shrinks the prior ceiling/caps, leaves room
@@ -0,0 +1,30 @@
1
+ import type { ComputeEnvironment, ComputeResourceRequest, ServiceCostEstimate } from '../@types/Compute.js';
2
+ /** Assumed `claimDurationTimeout` (seconds) — per-node config that no protocol command exposes. */
3
+ export declare const DEFAULT_CLAIM_DURATION_TIMEOUT_SECONDS = 3600;
4
+ /**
5
+ * Reimplementation of ocean-node's `C2DEngine.calculateResourcesCost` — there is no server-side
6
+ * quote command, so the cost has to be derived client-side:
7
+ * `cost = sum(price(id) * amount * ceil(effectiveDuration / 60))`, with
8
+ * `effectiveDuration = max(duration, floor)` where floor is `env.minJobDuration` for COMPUTE
9
+ * (`jobType` 1) and `env.minServiceDuration` otherwise (SERVICE, the default).
10
+ *
11
+ * `feeToken` is matched case-insensitively but the env's OWN spelling is returned (the node
12
+ * compares with `===`). An unknown resource id is priced 0 (as the node does) and reported in
13
+ * `unpricedResourceIds`. Returns `null` when the env advertises no fee schedule for
14
+ * `(chainId, token)`.
15
+ *
16
+ * Advisory: the node recomputes cost at start and is authoritative.
17
+ */
18
+ export declare function estimateServiceCost(env: ComputeEnvironment, chainId: number, token: string, resources: ComputeResourceRequest[], durationSeconds: number, jobType?: number | string): ServiceCostEstimate | null;
19
+ /**
20
+ * Human token amount -> raw base units as a decimal STRING (never a JS number). When the value
21
+ * has more fraction digits than the token has decimals, the remainder is rounded UP by one base
22
+ * unit — an estimate that rounds down would under-authorize.
23
+ */
24
+ export declare function toRawAmount(costHuman: number, decimals: number): string;
25
+ /**
26
+ * `minLockSeconds` for a service of `durationSeconds`. ocean-node's rule is
27
+ * `d + claimDurationTimeout` with a per-node, unexposed timeout (default 3600), so this is a
28
+ * padded lower bound: `d + max(3600, ceil(0.25 * d))`.
29
+ */
30
+ export declare function serviceMinLockSeconds(durationSeconds: number): number;
@@ -0,0 +1,41 @@
1
+ import type { EstimateJobSubsidyParams, JobSubsidyEstimate } from '../@types/SubsidyEstimate.js';
2
+ /**
3
+ * Absolute ceiling on how many candidate providers are examined (image gate + quoting), no matter
4
+ * how many a node advertises or the caller supplies. It is independent of the node-supplied
5
+ * `maxSponsorsPerLock`: a hostile node could otherwise make the client fire thousands of RPC
6
+ * reads. Only the first N candidates (advertised first, then custom) are considered beyond it.
7
+ */
8
+ export declare const MAX_SUBSIDY_CANDIDATES_QUOTED = 25;
9
+ /**
10
+ * Read-only pre-flight: how much subsidy would this job get, per subsidy-provider contract and
11
+ * delivery mode, and how much must the payer hold in escrow?
12
+ *
13
+ * Reads the node's status and compute environments (HTTP or P2P), derives the job cost with
14
+ * `estimateServiceCost`, resolves the candidate subsidy providers, applies the node's image
15
+ * gate, then quotes each provider through `SubsidyView` (v2 `quoteSubsidyModes`, else the v1
16
+ * `quoteSubsidy` as REIMBURSEMENT only). It builds one scenario per delivery mode.
17
+ *
18
+ * Candidate set (additive): `advertised ∪ customSubsidyProviders`, where advertised is
19
+ * `status.subsidyProviders[chainId]`. When the node's `subsidyProviderFilter` is on, a custom
20
+ * address outside the advertised set is dropped as `outside_node_set` (the node would reject the
21
+ * whole request). Pass a scenario's `selected` list as `subsidyProviders` at start: the node
22
+ * treats a non-empty list as a REPLACEMENT of its own set, so it then applies exactly that list.
23
+ * An empty `selected` means no subsidy — pass it verbatim as `subsidyProviders: []` (an explicit
24
+ * opt-out); OMITTING the argument instead makes the node fall back to its own configured providers.
25
+ *
26
+ * A gate that returns `null` (provider does not expose it) is unknown, NOT disqualifying; only
27
+ * an explicit `false` drops a provider. At most `min(escrow maxSponsorsPerLock, 10)` providers
28
+ * are selected per scenario.
29
+ *
30
+ * Untrusted node data: the node status is attacker-controlled when the caller points at an
31
+ * arbitrary node. Only the first {@link MAX_SUBSIDY_CANDIDATES_QUOTED} candidates (advertised
32
+ * first, then custom) are examined, with a warning when more exist. The returned `escrowAddress`
33
+ * is whatever the node advertised: it is verified only when `params.config.escrow` is set (a
34
+ * mismatch throws, fail-closed); otherwise a warning says it is unverified. RE-VERIFY it against
35
+ * your configured escrow before any deposit or authorization. Genuine RPC failures propagate;
36
+ * only "contract does not implement this" is degraded to a per-provider `error` drop.
37
+ *
38
+ * All amounts are human-readable token units. Advisory only: the node recomputes cost and the
39
+ * escrow/subsidy contracts settle subsidy at start. Never signs or sends a transaction.
40
+ */
41
+ export declare function estimateJobSubsidy(params: EstimateJobSubsidyParams): Promise<JobSubsidyEstimate>;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Subsidy image gate — ported VERBATIM from ocean-node
3
+ * (`core/utils/subsidyProviders.ts` + `c2d/serviceResourceMatching.ts`). Keep the matching rules
4
+ * identical to the node: this is an exact-string matcher, not an image-reference parser.
5
+ */
6
+ /**
7
+ * The subset of a docker container spec the image gate matches against. A dockerfile-built image
8
+ * is user-built (NOT a trusted operator image), so a non-empty `dockerfile` always makes the gate
9
+ * match nothing — even when `image`/`tag` are also supplied.
10
+ */
11
+ export interface SubsidyImageContainer {
12
+ image?: string;
13
+ tag?: string;
14
+ checksum?: string;
15
+ dockerfile?: string;
16
+ }
17
+ /**
18
+ * Resolves the final Docker image reference from a service start spec.
19
+ * Priority: dockerfile > checksum > tag > default "latest".
20
+ */
21
+ export declare function resolveServiceImage(image: string, tag?: string, checksum?: string, dockerfile?: string, serviceId?: string): string;
22
+ /**
23
+ * A docker entrypoint/cmd override is "custom" when it is non-empty. Handles both the service
24
+ * shape (`string[]`) and the compute container shape (`string`); whitespace-only strings count
25
+ * as empty.
26
+ */
27
+ export declare function isNonEmpty(value: string | string[] | null | undefined): boolean;
28
+ /**
29
+ * True when `entry` (an operator allowlist docker reference) matches `container`.
30
+ *
31
+ * Compared against the SINGLE reference the node would resolve `container` to (dockerfile >
32
+ * checksum > tag): a non-empty `dockerfile` matches NOTHING; else a `checksum` gives
33
+ * `image@checksum` (tag ignored); else `image:${tag ?? 'latest'}`.
34
+ *
35
+ * WILDCARD TAG: an entry `name:*` matches ANY tag or digest of the exact image `name` (the name
36
+ * may contain a registry `host:port`; only the trailing `:*` is special). Case-sensitive.
37
+ */
38
+ export declare function imageReferenceMatches(container: SubsidyImageContainer | null | undefined, entry: string): boolean;
39
+ /**
40
+ * Apply the per-address image gate (`subsidyProviderAllowedImages`) to an effective subsidy list.
41
+ *
42
+ * - `!allowedImages || zero keys` -> gate OFF; every address kept (`{}` means "no restrictions").
43
+ * - otherwise, per address: NOT a key in the map -> kept; a key -> kept ONLY when the job has
44
+ * no custom entrypoint/cmd AND its image matches one of that address's allowed refs.
45
+ *
46
+ * Map keys are checksum-normalized (and merged) before lookup. Pure: no network.
47
+ */
48
+ export declare function filterSubsidyByAllowedImages(effective: string[], container: SubsidyImageContainer | null | undefined, hasCustomEntrypoint: boolean, allowedImages: Record<string, string[]> | null | undefined): {
49
+ kept: string[];
50
+ dropped: string[];
51
+ };
@@ -15,3 +15,6 @@ export * from './Addresses.js';
15
15
  export * from './bytes.js';
16
16
  export * from './C2dCapability.js';
17
17
  export * from './ServiceResources.js';
18
+ export * from './ServiceCost.js';
19
+ export * from './SubsidyImage.js';
20
+ export * from './SubsidyEstimate.js';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@oceanprotocol/lib",
3
3
  "source": "./src/index.ts",
4
- "version": "10.0.0",
4
+ "version": "11.0.0-next.1",
5
5
  "description": "JavaScript client library for Ocean Protocol",
6
6
  "module": "./dist/lib.module.mjs",
7
7
  "type": "module",
@@ -91,10 +91,9 @@
91
91
  "@libp2p/websockets": "^10.1.21",
92
92
  "@multiformats/multiaddr": "^13.0.3",
93
93
  "@oasisprotocol/sapphire-ethers-v6": "^6.0.1",
94
- "@oceanprotocol/ddo-js": "^1.0.0",
94
+ "@oceanprotocol/ddo-js": "^1.1.0",
95
95
  "bignumber.js": "^11.1.5",
96
96
  "cross-fetch": "^4.1.0",
97
- "crypto-js": "^4.2.0",
98
97
  "decimal.js": "^10.6.0",
99
98
  "eciesjs": "^0.5.0",
100
99
  "ethers": "^6.17.0",
@@ -114,6 +113,7 @@
114
113
  "@types/node": "^26.2.0",
115
114
  "auto-changelog": "^2.6.0",
116
115
  "chai": "^6.2.2",
116
+ "crypto-js": "^4.2.0",
117
117
  "eslint": "^10.8.1",
118
118
  "eslint-config-prettier": "^10.1.8",
119
119
  "eslint-plugin-prettier": "^5.5.6",
@@ -125,7 +125,7 @@
125
125
  "prettier": "^3.9.6",
126
126
  "release-it": "^21.0.2",
127
127
  "source-map-support": "^0.5.21",
128
- "tsup": "^8.5.1",
128
+ "tsup": "^9.0.0",
129
129
  "tsx": "^4.23.12",
130
130
  "typedoc": "^0.28.20",
131
131
  "typedoc-plugin-markdown": "^4.12.0",