@opendatalabs/vana-sdk 3.23.0 → 4.0.0
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.
- package/README.md +57 -0
- package/dist/auth/errors.cjs +1 -1
- package/dist/auth/web3-signed.cjs +1 -1
- package/dist/crypto/envelope/job-stream.test.d.ts +1 -0
- package/dist/crypto/envelope/job.cjs +593 -38
- package/dist/crypto/envelope/job.cjs.map +1 -1
- package/dist/crypto/envelope/job.d.ts +44 -27
- package/dist/crypto/envelope/job.js +589 -37
- package/dist/crypto/envelope/job.js.map +1 -1
- package/dist/direct/access-request-client.cjs +1 -1
- package/dist/direct/connect-flow.cjs +43 -1
- package/dist/direct/connect-flow.cjs.map +1 -1
- package/dist/direct/connect-flow.d.ts +12 -0
- package/dist/direct/connect-flow.js +43 -1
- package/dist/direct/connect-flow.js.map +1 -1
- package/dist/direct/controller.cjs +1 -1
- package/dist/direct/errors.cjs +1 -1
- package/dist/direct/escrow-payment.cjs.map +1 -1
- package/dist/direct/escrow-payment.d.ts +2 -2
- package/dist/direct/escrow-payment.js.map +1 -1
- package/dist/direct/personal-server-read.cjs +2 -2
- package/dist/direct/use-direct-vana-connect.cjs +2 -1
- package/dist/direct/use-direct-vana-connect.cjs.map +1 -1
- package/dist/direct/use-direct-vana-connect.d.ts +3 -1
- package/dist/direct/use-direct-vana-connect.js +2 -1
- package/dist/direct/use-direct-vana-connect.js.map +1 -1
- package/dist/error-entry-points.test.d.ts +1 -0
- package/dist/errors.cjs +7 -0
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.ts +10 -0
- package/dist/errors.js +6 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.browser.d.ts +4 -4
- package/dist/index.browser.js +882 -518
- package/dist/index.browser.js.map +4 -4
- package/dist/index.node.cjs +1035 -705
- package/dist/index.node.cjs.map +4 -4
- package/dist/index.node.d.ts +4 -4
- package/dist/index.node.js +989 -567
- package/dist/index.node.js.map +4 -4
- package/dist/protocol/data-point-deletion.cjs +1 -1
- package/dist/protocol/derivative-questions.cjs +1 -1
- package/dist/protocol/derivative-status.cjs +1 -1
- package/dist/protocol/eip712.cjs +28 -2
- package/dist/protocol/eip712.cjs.map +1 -1
- package/dist/protocol/eip712.d.ts +70 -0
- package/dist/protocol/eip712.js +24 -1
- package/dist/protocol/eip712.js.map +1 -1
- package/dist/protocol/escrow.cjs +154 -2
- package/dist/protocol/escrow.cjs.map +1 -1
- package/dist/protocol/escrow.d.ts +145 -2
- package/dist/protocol/escrow.js +152 -1
- package/dist/protocol/escrow.js.map +1 -1
- package/dist/protocol/fixtures/moksha-identity.json +20 -0
- package/dist/protocol/gateway.cjs +1 -1
- package/dist/protocol/gateway.cjs.map +1 -1
- package/dist/protocol/gateway.d.ts +8 -38
- package/dist/protocol/gateway.js.map +1 -1
- package/dist/protocol/identity.cjs +7 -2
- package/dist/protocol/identity.cjs.map +1 -1
- package/dist/protocol/identity.js +7 -2
- package/dist/protocol/identity.js.map +1 -1
- package/dist/protocol/jobs-client.cjs +73 -21
- package/dist/protocol/jobs-client.cjs.map +1 -1
- package/dist/protocol/jobs-client.d.ts +7 -5
- package/dist/protocol/jobs-client.js +74 -21
- package/dist/protocol/jobs-client.js.map +1 -1
- package/dist/protocol/jobs.cjs +0 -3
- package/dist/protocol/jobs.cjs.map +1 -1
- package/dist/protocol/jobs.d.ts +21 -13
- package/dist/protocol/jobs.js +0 -2
- package/dist/protocol/jobs.js.map +1 -1
- package/dist/protocol/lineage.cjs +1 -1
- package/dist/protocol/personal-server-data.cjs +1 -1
- package/dist/protocol/personal-server-write.cjs +1 -1
- package/dist/protocol/write-request.cjs +1 -1
- package/dist/protocol/write-signer.cjs +1 -1
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/react.js.map +1 -1
- package/dist/session-relay/client.cjs +1 -1
- package/dist/session-relay/errors.cjs +1 -1
- package/dist/session-relay/index.cjs +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/direct/connect-flow.ts"],"sourcesContent":["/**\n * Framework-agnostic connect-flow state machine for the browser two-tab helper.\n *\n * @remarks\n * This is the testable core behind {@link useDirectVanaConnect}. It is pure\n * TypeScript (no React, no DOM-only APIs beyond an injectable window opener and\n * timers) so the full flow — create request, open Vana, poll status, read data —\n * can be exercised in a Node test environment.\n *\n * The React hook is a thin `useSyncExternalStore` binding over this store.\n *\n * @category Direct\n * @module direct/connect-flow\n */\n\nimport type {\n AccessRequest,\n AccessRequestStatus,\n AccessRequestStatusValue,\n ApprovedDataResult,\n} from \"./types\";\nimport { normalizeMobileContinuationUrl } from \"./types\";\n\n/**\n * Caller-supplied transports. These typically `fetch` the app's own backend\n * routes, which in turn delegate to a {@link DirectDataController}.\n */\nexport interface DirectConnectTransports<T = unknown> {\n /** Ask the backend to create an access request. */\n createRequest: () => Promise<AccessRequest>;\n /** Ask the backend for the current status of a request. */\n getStatus: (requestId: string) => Promise<AccessRequestStatus>;\n /** Ask the backend to read the approved data. */\n readResult: (requestId: string) => Promise<ApprovedDataResult<T>>;\n}\n\n/**\n * A handle to a tab opened synchronously under the user's click gesture.\n *\n * @remarks\n * The flow opens this tab *before* it knows the approval URL (popup blockers\n * only allow `window.open()` during the click's transient activation), then\n * navigates it once `createRequest` resolves.\n */\nexport interface ConnectWindow {\n /** Point the already-open tab at the approval URL. */\n navigate(url: string): void;\n /** Close the tab (used to clean up an un-navigated tab on failure/reset). */\n close(): void;\n}\n\n/** Browser class used only to choose the destination returned by Vana. */\nexport type DirectBrowserPlatform = \"desktop\" | \"mobile\";\n\n/** Injectable browser-platform policy; it never asserts whether an app exists. */\nexport interface DirectBrowserPlatformPolicy {\n current(): DirectBrowserPlatform;\n}\n\n/** Tunables for the connect flow. */\nexport interface DirectConnectOptions {\n /** Status poll interval in ms. Defaults to 1500. */\n pollIntervalMs?: number;\n /**\n * Overall timeout in ms before giving up. Defaults to 300000 (5 min).\n * Used only when the access request does not carry an authoritative\n * `expiresAt` value.\n */\n timeoutMs?: number;\n /**\n * Synchronously open a blank tab under the click's transient activation and\n * return a handle to navigate later, or `null` if the browser blocked it.\n * Defaults to `window.open(\"\", \"_blank\")` (with `opener` severed). Injectable\n * for tests.\n *\n * @remarks\n * Renamed from the pre-3.8 `openWindow?: (url) => void`. The old contract was\n * the BUI-622 bug itself (it was called with the URL *after* an `await`, so\n * the popup blocker suppressed it); it cannot be preserved while fixing the\n * bug. Custom openers must now open synchronously and return a navigable\n * handle.\n */\n openApprovalWindow?: () => ConnectWindow | null;\n /** SDK-owned mobile/desktop policy. Injectable for deterministic tests. */\n browserPlatformPolicy?: DirectBrowserPlatformPolicy;\n /** `setTimeout`. Injectable for tests. Defaults to `globalThis.setTimeout`. */\n setTimeoutFn?: (cb: () => void, ms: number) => unknown;\n /** `clearTimeout`. Injectable for tests. Defaults to `globalThis.clearTimeout`. */\n clearTimeoutFn?: (handle: unknown) => void;\n /** Clock source in ms. Injectable for tests. Defaults to `Date.now`. */\n now?: () => number;\n}\n\n/**\n * Discriminated connect-flow state.\n *\n * @remarks\n * `type` matches the builder guide: it starts at `\"idle\"` and is non-idle while\n * connecting. The intermediate phases give richer UIs something to render.\n *\n * Desktop and light-data requests move through `\"awaiting_approval\"` (Vana Web\n * opens in a popup). A deep Direct request on a mobile browser moves through\n * `\"ready_to_open\"` instead: the SDK exposes a plain HTTPS\n * `mobileContinuationUrl` for the UI to render as a primary \"Open Vana\" link,\n * never launching it automatically, and keeps polling in memory.\n */\nexport type DirectConnectState<T = unknown> =\n | { type: \"idle\" }\n | { type: \"creating\" }\n | {\n type: \"awaiting_approval\";\n request: AccessRequest;\n /**\n * `true` when the popup was blocked. The UI should render the universal\n * HTTPS `request.approvalUrl` as a manual \"Open approval\" link.\n */\n popupBlocked: boolean;\n }\n | {\n type: \"ready_to_open\";\n request: AccessRequest;\n /**\n * Validated HTTPS continuation URL the mobile UI renders as the primary\n * \"Open Vana\" tap. Polling continues while it is shown; its embedded\n * ticket may rotate to a fresh URL between polls.\n */\n mobileContinuationUrl: string;\n }\n | { type: \"reading\"; request: AccessRequest }\n | { type: \"done\"; result: ApprovedDataResult<T> }\n | { type: \"error\"; error: Error };\n\n/** The store returned by {@link createDirectConnectFlow}. */\nexport interface DirectConnectFlow<T = unknown> {\n /** Current state. */\n getState(): DirectConnectState<T>;\n /** Subscribe to state changes; returns an unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** Begin the flow. No-op if already running. */\n start(): Promise<void>;\n /** Reset to `idle` and stop any in-flight polling. */\n reset(): void;\n}\n\nconst DEFAULT_POLL_INTERVAL_MS = 1500;\nconst DEFAULT_TIMEOUT_MS = 300_000;\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\n}\n\nfunction isReadReadyStatus(status: AccessRequestStatusValue): boolean {\n return status === \"approved\" || status === \"ready_for_read\";\n}\n\nconst MOBILE_USER_AGENT =\n /Android|iPhone|iPad|iPod|Mobile|Silk|Kindle|Opera Mini|IEMobile/i;\n\nfunction defaultBrowserPlatformPolicy(): DirectBrowserPlatformPolicy {\n return {\n current() {\n if (typeof navigator === \"undefined\") return \"desktop\";\n const isTouchCapableIpad =\n navigator.platform === \"MacIntel\" && navigator.maxTouchPoints > 1;\n return MOBILE_USER_AGENT.test(navigator.userAgent) || isTouchCapableIpad\n ? \"mobile\"\n : \"desktop\";\n },\n };\n}\n\n/**\n * Default {@link DirectConnectOptions.openApprovalWindow}: open a blank tab\n * synchronously (inside the click gesture) and return a handle to navigate\n * once the approval URL is known. Returns `null` when blocked or non-DOM.\n */\nfunction defaultOpenApprovalWindow(): ConnectWindow | null {\n if (typeof window === \"undefined\" || !window.open) return null;\n // We can't pass the \"noopener\"/\"noreferrer\" feature string here: it makes\n // window.open() return null, which would throw away the handle we need to\n // navigate later. So we open plain and re-create both protections by hand.\n const opened = window.open(\"\", \"_blank\");\n if (!opened) return null;\n // Sever the opener link while the tab is still about:blank, so the approval\n // page can't reach back into the app (reverse tab-nabbing).\n try {\n opened.opener = null;\n } catch {\n // Some environments make `opener` read-only; best-effort only.\n }\n return {\n navigate(url: string) {\n // Restore the no-referrer protection the old \"noreferrer\" feature gave:\n // tag the blank document so the upcoming navigation sends no Referer to\n // the approval page (best-effort; the blank doc is same-origin here).\n try {\n const meta = opened.document.createElement(\"meta\");\n meta.name = \"referrer\";\n meta.content = \"no-referrer\";\n (opened.document.head ?? opened.document.documentElement)?.appendChild(\n meta,\n );\n } catch {\n // Cross-origin/unavailable document: skip, navigation still proceeds.\n }\n opened.location.href = url;\n },\n close() {\n opened.close();\n },\n };\n}\n\n/**\n * Create a connect-flow store.\n *\n * @param transports - Backend transports (`createRequest`, `getStatus`, `readResult`).\n * @param options - Polling/timeout tunables and injectable side effects.\n * @returns A {@link DirectConnectFlow} store.\n */\nexport function createDirectConnectFlow<T = unknown>(\n transports: DirectConnectTransports<T>,\n options: DirectConnectOptions = {},\n): DirectConnectFlow<T> {\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n // `openApprovalWindow` and `browserPlatformPolicy` are resolved lazily at\n // start() (see below) so options swapped in after construction are still\n // honoured — matching the latest-callback pattern the React hook uses for its\n // transports.\n const setTimeoutFn =\n options.setTimeoutFn ??\n ((cb: () => void, ms: number) => globalThis.setTimeout(cb, ms));\n const clearTimeoutFn =\n options.clearTimeoutFn ??\n ((handle: unknown) => {\n globalThis.clearTimeout(handle as never);\n });\n const now = options.now ?? (() => Date.now());\n let state: DirectConnectState<T> = { type: \"idle\" };\n const listeners = new Set<() => void>();\n let pollHandle: unknown = null;\n let running = false;\n // Monotonic id for the current start() invocation. reset() (and an\n // immediately following start()) bumps it, so a previous run whose async\n // createRequest is still in flight can detect it has been superseded and\n // avoid touching shared state / the newer run's tab.\n let activeRunId = 0;\n // Holds the tab we opened only while it is still blank (un-navigated). Once\n // navigated to the approval URL we drop the reference so reset/cleanup never\n // closes the live approval tab the user is interacting with.\n let openedWindow: ConnectWindow | null = null;\n\n function emit(): void {\n for (const listener of listeners) listener();\n }\n\n function setState(next: DirectConnectState<T>): void {\n state = next;\n emit();\n }\n\n function clearPoll(): void {\n if (pollHandle !== null) {\n clearTimeoutFn(pollHandle);\n pollHandle = null;\n }\n }\n\n /** Close the opened tab if it is still blank (never navigated). */\n function closeUnnavigatedWindow(): void {\n if (openedWindow) {\n openedWindow.close();\n openedWindow = null;\n }\n }\n\n function isRunningPhase(): boolean {\n return (\n state.type === \"creating\" ||\n state.type === \"awaiting_approval\" ||\n state.type === \"ready_to_open\" ||\n state.type === \"reading\"\n );\n }\n\n async function readAndFinish(request: AccessRequest): Promise<void> {\n setState({ type: \"reading\", request });\n try {\n const result = await transports.readResult(request.requestId);\n if (!running) return;\n setState({ type: \"done\", result });\n } catch (err) {\n if (!running) return;\n setState({ type: \"error\", error: toError(err) });\n } finally {\n running = false;\n }\n }\n\n function scheduleNextPoll(request: AccessRequest, deadline: number): void {\n pollHandle = setTimeoutFn(() => {\n void poll(request, deadline);\n }, pollIntervalMs);\n }\n\n function requestDeadline(request: AccessRequest): number {\n if (request.expiresAt !== undefined) {\n const expiresAt = Date.parse(request.expiresAt);\n if (Number.isFinite(expiresAt)) return expiresAt;\n }\n return now() + timeoutMs;\n }\n\n /**\n * Enter the polling loop from the given initial state (either\n * `awaiting_approval` for desktop/light or `ready_to_open` for mobile-deep).\n * Errors out immediately if the request has already expired.\n */\n function startPolling(\n request: AccessRequest,\n initialState: DirectConnectState<T>,\n ): void {\n setState(initialState);\n const deadline = requestDeadline(request);\n if (now() >= deadline) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(\"Access request expired\"),\n });\n return;\n }\n scheduleNextPoll(request, deadline);\n }\n\n async function poll(request: AccessRequest, deadline: number): Promise<void> {\n if (!running) return;\n if (now() >= deadline) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(\"Timed out waiting for approval\"),\n });\n return;\n }\n let status: AccessRequestStatus;\n try {\n status = await transports.getStatus(request.requestId);\n } catch (err) {\n if (!running) return;\n running = false;\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (!running) return;\n\n // A pending deep-mobile status may rotate the continuation ticket. Adopt a\n // fresh, still-valid URL so the rendered \"Open Vana\" link always points at a\n // live ticket; ignore it on the desktop/light path.\n if (status.status === \"pending\" && state.type === \"ready_to_open\") {\n const refreshed = normalizeMobileContinuationUrl(\n status.mobileContinuationUrl,\n );\n if (refreshed && refreshed !== state.mobileContinuationUrl) {\n request = { ...request, mobileContinuationUrl: refreshed };\n setState({\n type: \"ready_to_open\",\n request,\n mobileContinuationUrl: refreshed,\n });\n }\n }\n\n if (isReadReadyStatus(status.status)) {\n clearPoll();\n await readAndFinish(request);\n return;\n }\n if (\n status.status === \"completed\" ||\n status.status === \"denied\" ||\n status.status === \"expired\"\n ) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(`Access request ${status.status}`),\n });\n return;\n }\n scheduleNextPoll(request, deadline);\n }\n\n return {\n getState() {\n return state;\n },\n\n subscribe(listener: () => void) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n\n async start(): Promise<void> {\n if (running || isRunningPhase()) return;\n running = true;\n const runId = ++activeRunId;\n // Read the platform policy at start time, like openApprovalWindow below,\n // so a policy swapped in after construction (a React rerender forwards\n // options through a ref) still decides this run's destination.\n const browserPlatform = (\n options.browserPlatformPolicy ?? defaultBrowserPlatformPolicy()\n ).current();\n\n // Desktop preserves the pre-mobile synchronous popup contract: open a\n // blank tab while the click's transient activation is live, then navigate\n // it once createRequest returns the approval URL (BUI-622). Mobile never\n // creates that transient tab; deep requests expose one explicit HTTPS\n // link, while light requests retain the manual approvalUrl fallback.\n // Read the opener option at start time so a swapped-in custom opener is\n // still honored for desktop flows.\n const approvalWindow =\n browserPlatform === \"desktop\"\n ? (options.openApprovalWindow ?? defaultOpenApprovalWindow)()\n : null;\n openedWindow = approvalWindow;\n\n setState({ type: \"creating\" });\n\n let request: AccessRequest;\n try {\n request = await transports.createRequest();\n } catch (err) {\n // If we were superseded (reset, possibly + a newer start()) while this\n // request was in flight, only clean up our own tab — never the shared\n // state or the newer run's window.\n if (runId !== activeRunId) {\n approvalWindow?.close();\n return;\n }\n running = false;\n closeUnnavigatedWindow();\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (runId !== activeRunId) {\n approvalWindow?.close();\n return;\n }\n // Re-validate the continuation URL at the SDK boundary (defense in depth\n // for custom transports that bypass the default client).\n request = {\n ...request,\n mobileContinuationUrl: normalizeMobileContinuationUrl(\n request.mobileContinuationUrl,\n ),\n };\n\n // The SDK owns only the small mobile-versus-desktop destination choice.\n // A deep Direct request on mobile carries a validated continuation URL;\n // desktop keeps its popup contract, while mobile light exposes the HTTPS\n // approval URL as the existing manual fallback without opening a tab.\n const mobileContinuationUrl =\n browserPlatform === \"mobile\"\n ? request.mobileContinuationUrl\n : undefined;\n\n if (mobileContinuationUrl) {\n // Do not auto-launch: DCR creation is async, so the original Connect\n // gesture can no longer be trusted to retain iOS user activation. Let\n // the UI render an explicit primary \"Open Vana\" link; polling continues\n // in this tab.\n startPolling(request, {\n type: \"ready_to_open\",\n request,\n mobileContinuationUrl,\n });\n return;\n }\n\n // Desktop/light: navigate the synchronously-opened tab to the HTTPS\n // approval URL. `approvalWindow === null` means the popup was blocked;\n // surface it so the UI renders request.approvalUrl as a visible manual\n // \"Open approval\" link instead of hanging. We poll either way, so a manual\n // open still resolves the flow, and the timeout still bounds the wait.\n if (approvalWindow) {\n approvalWindow.navigate(request.approvalUrl);\n // Hand the tab off to the user; we no longer own/close it.\n openedWindow = null;\n }\n startPolling(request, {\n type: \"awaiting_approval\",\n request,\n popupBlocked: approvalWindow === null,\n });\n },\n\n reset(): void {\n running = false;\n // Invalidate any in-flight start() so a late createRequest can't clobber\n // a subsequent run.\n activeRunId++;\n clearPoll();\n closeUnnavigatedWindow();\n setState({ type: \"idle\" });\n },\n };\n}\n"],"mappings":"AAqBA,SAAS,sC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AAM;AAAA,QACN;AAAA,QACA,cAAc,mBAAmB;AAAA,MACnC,CAAC;AAAA,IACH;AAAA,IAEA,QAAc;AACZ,gBAAU;AAGV;AACA,gBAAU;AACV,6BAAuB;AACvB,eAAS,EAAE,MAAM,OAAO,CAAC;AAAA,IAC3B;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/direct/connect-flow.ts"],"sourcesContent":["/**\n * Framework-agnostic connect-flow state machine for the browser two-tab helper.\n *\n * @remarks\n * This is the testable core behind {@link useDirectVanaConnect}. It is pure\n * TypeScript (no React, no DOM-only APIs beyond an injectable window opener and\n * timers) so the full flow — create request, open Vana, poll status, read data —\n * can be exercised in a Node test environment.\n *\n * The React hook is a thin `useSyncExternalStore` binding over this store.\n *\n * @category Direct\n * @module direct/connect-flow\n */\n\nimport type {\n AccessRequest,\n AccessRequestStatus,\n AccessRequestStatusValue,\n ApprovedDataResult,\n} from \"./types\";\nimport { normalizeMobileContinuationUrl } from \"./types\";\n\n/**\n * Caller-supplied transports. These typically `fetch` the app's own backend\n * routes, which in turn delegate to a {@link DirectDataController}.\n */\nexport interface DirectConnectTransports<T = unknown> {\n /** Ask the backend to create an access request. */\n createRequest: () => Promise<AccessRequest>;\n /** Ask the backend for the current status of a request. */\n getStatus: (requestId: string) => Promise<AccessRequestStatus>;\n /** Ask the backend to read the approved data. */\n readResult: (requestId: string) => Promise<ApprovedDataResult<T>>;\n}\n\n/**\n * A handle to a tab opened synchronously under the user's click gesture.\n *\n * @remarks\n * The flow opens this tab *before* it knows the approval URL (popup blockers\n * only allow `window.open()` during the click's transient activation), then\n * navigates it once `createRequest` resolves.\n */\nexport interface ConnectWindow {\n /** Point the already-open tab at the approval URL. */\n navigate(url: string): void;\n /** Close the tab (used to clean up an un-navigated tab on failure/reset). */\n close(): void;\n}\n\n/** Browser class used only to choose the destination returned by Vana. */\nexport type DirectBrowserPlatform = \"desktop\" | \"mobile\";\n\n/** Injectable browser-platform policy; it never asserts whether an app exists. */\nexport interface DirectBrowserPlatformPolicy {\n current(): DirectBrowserPlatform;\n}\n\n/** Tunables for the connect flow. */\nexport interface DirectConnectOptions {\n /** Status poll interval in ms. Defaults to 1500. */\n pollIntervalMs?: number;\n /**\n * Overall timeout in ms before giving up. Defaults to 300000 (5 min).\n * Used only when the access request does not carry an authoritative\n * `expiresAt` value.\n */\n timeoutMs?: number;\n /**\n * Synchronously open a blank tab under the click's transient activation and\n * return a handle to navigate later, or `null` if the browser blocked it.\n * Defaults to `window.open(\"\", \"_blank\")` (with `opener` severed). Injectable\n * for tests.\n *\n * @remarks\n * Renamed from the pre-3.8 `openWindow?: (url) => void`. The old contract was\n * the BUI-622 bug itself (it was called with the URL *after* an `await`, so\n * the popup blocker suppressed it); it cannot be preserved while fixing the\n * bug. Custom openers must now open synchronously and return a navigable\n * handle.\n */\n openApprovalWindow?: () => ConnectWindow | null;\n /** SDK-owned mobile/desktop policy. Injectable for deterministic tests. */\n browserPlatformPolicy?: DirectBrowserPlatformPolicy;\n /** `setTimeout`. Injectable for tests. Defaults to `globalThis.setTimeout`. */\n setTimeoutFn?: (cb: () => void, ms: number) => unknown;\n /** `clearTimeout`. Injectable for tests. Defaults to `globalThis.clearTimeout`. */\n clearTimeoutFn?: (handle: unknown) => void;\n /** Clock source in ms. Injectable for tests. Defaults to `Date.now`. */\n now?: () => number;\n}\n\n/**\n * Discriminated connect-flow state.\n *\n * @remarks\n * `type` matches the builder guide: it starts at `\"idle\"` and is non-idle while\n * connecting. The intermediate phases give richer UIs something to render.\n *\n * Desktop and light-data requests move through `\"awaiting_approval\"` (Vana Web\n * opens in a popup). A deep Direct request on a mobile browser moves through\n * `\"ready_to_open\"` instead: the SDK exposes a plain HTTPS\n * `mobileContinuationUrl` for the UI to render as a primary \"Open Vana\" link,\n * never launching it automatically, and keeps polling in memory.\n */\nexport type DirectConnectState<T = unknown> =\n | { type: \"idle\" }\n | { type: \"creating\" }\n | {\n type: \"awaiting_approval\";\n request: AccessRequest;\n /**\n * `true` when the popup was blocked. The UI should render the universal\n * HTTPS `request.approvalUrl` as a manual \"Open approval\" link.\n */\n popupBlocked: boolean;\n }\n | {\n type: \"ready_to_open\";\n request: AccessRequest;\n /**\n * Validated HTTPS continuation URL the mobile UI renders as the primary\n * \"Open Vana\" tap. Polling continues while it is shown; its embedded\n * ticket may rotate to a fresh URL between polls.\n */\n mobileContinuationUrl: string;\n }\n | { type: \"reading\"; request: AccessRequest }\n | { type: \"done\"; result: ApprovedDataResult<T> }\n | { type: \"error\"; error: Error };\n\n/** Whether an explicit read retry reused consent or started fresh approval. */\nexport type DirectConnectRetryOutcome =\n | \"retried_existing_grant\"\n | \"fresh_approval_required\";\n\n/** The store returned by {@link createDirectConnectFlow}. */\nexport interface DirectConnectFlow<T = unknown> {\n /** Current state. */\n getState(): DirectConnectState<T>;\n /** Subscribe to state changes; returns an unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** Begin the flow. No-op if already running. */\n start(): Promise<void>;\n /**\n * Retry a failed read, reusing a still-live approved request when possible.\n *\n * @remarks\n * This explicit path avoids the observed double-approval symptom where\n * \"Try that again\" minted a new request after a transient read failure.\n * The return value tells callers whether existing consent was reused or a\n * fresh approval was required.\n */\n retryRead(): Promise<DirectConnectRetryOutcome>;\n /** Reset to `idle` and stop any in-flight polling. */\n reset(): void;\n}\n\nconst DEFAULT_POLL_INTERVAL_MS = 1500;\nconst DEFAULT_TIMEOUT_MS = 300_000;\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\n}\n\nfunction isReadReadyStatus(status: AccessRequestStatusValue): boolean {\n return status === \"approved\" || status === \"ready_for_read\";\n}\n\nconst MOBILE_USER_AGENT =\n /Android|iPhone|iPad|iPod|Mobile|Silk|Kindle|Opera Mini|IEMobile/i;\n\nfunction defaultBrowserPlatformPolicy(): DirectBrowserPlatformPolicy {\n return {\n current() {\n if (typeof navigator === \"undefined\") return \"desktop\";\n const isTouchCapableIpad =\n navigator.platform === \"MacIntel\" && navigator.maxTouchPoints > 1;\n return MOBILE_USER_AGENT.test(navigator.userAgent) || isTouchCapableIpad\n ? \"mobile\"\n : \"desktop\";\n },\n };\n}\n\n/**\n * Default {@link DirectConnectOptions.openApprovalWindow}: open a blank tab\n * synchronously (inside the click gesture) and return a handle to navigate\n * once the approval URL is known. Returns `null` when blocked or non-DOM.\n */\nfunction defaultOpenApprovalWindow(): ConnectWindow | null {\n if (typeof window === \"undefined\" || !window.open) return null;\n // We can't pass the \"noopener\"/\"noreferrer\" feature string here: it makes\n // window.open() return null, which would throw away the handle we need to\n // navigate later. So we open plain and re-create both protections by hand.\n const opened = window.open(\"\", \"_blank\");\n if (!opened) return null;\n // Sever the opener link while the tab is still about:blank, so the approval\n // page can't reach back into the app (reverse tab-nabbing).\n try {\n opened.opener = null;\n } catch {\n // Some environments make `opener` read-only; best-effort only.\n }\n return {\n navigate(url: string) {\n // Restore the no-referrer protection the old \"noreferrer\" feature gave:\n // tag the blank document so the upcoming navigation sends no Referer to\n // the approval page (best-effort; the blank doc is same-origin here).\n try {\n const meta = opened.document.createElement(\"meta\");\n meta.name = \"referrer\";\n meta.content = \"no-referrer\";\n (opened.document.head ?? opened.document.documentElement)?.appendChild(\n meta,\n );\n } catch {\n // Cross-origin/unavailable document: skip, navigation still proceeds.\n }\n opened.location.href = url;\n },\n close() {\n opened.close();\n },\n };\n}\n\n/**\n * Create a connect-flow store.\n *\n * @param transports - Backend transports (`createRequest`, `getStatus`, `readResult`).\n * @param options - Polling/timeout tunables and injectable side effects.\n * @returns A {@link DirectConnectFlow} store.\n */\nexport function createDirectConnectFlow<T = unknown>(\n transports: DirectConnectTransports<T>,\n options: DirectConnectOptions = {},\n): DirectConnectFlow<T> {\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n // `openApprovalWindow` and `browserPlatformPolicy` are resolved lazily at\n // start() (see below) so options swapped in after construction are still\n // honoured — matching the latest-callback pattern the React hook uses for its\n // transports.\n const setTimeoutFn =\n options.setTimeoutFn ??\n ((cb: () => void, ms: number) => globalThis.setTimeout(cb, ms));\n const clearTimeoutFn =\n options.clearTimeoutFn ??\n ((handle: unknown) => {\n globalThis.clearTimeout(handle as never);\n });\n const now = options.now ?? (() => Date.now());\n let state: DirectConnectState<T> = { type: \"idle\" };\n const listeners = new Set<() => void>();\n let pollHandle: unknown = null;\n let running = false;\n // Retained only after status proved this request had a read-ready grant.\n // A retry rechecks that status before trusting the prior consent.\n let approvedRequest: AccessRequest | null = null;\n // Monotonic id for the current start() invocation. reset() (and an\n // immediately following start()) bumps it, so a previous run whose async\n // createRequest is still in flight can detect it has been superseded and\n // avoid touching shared state / the newer run's tab.\n let activeRunId = 0;\n // Holds the tab we opened only while it is still blank (un-navigated). Once\n // navigated to the approval URL we drop the reference so reset/cleanup never\n // closes the live approval tab the user is interacting with.\n let openedWindow: ConnectWindow | null = null;\n\n function emit(): void {\n for (const listener of listeners) listener();\n }\n\n function setState(next: DirectConnectState<T>): void {\n state = next;\n emit();\n }\n\n function clearPoll(): void {\n if (pollHandle !== null) {\n clearTimeoutFn(pollHandle);\n pollHandle = null;\n }\n }\n\n /** Close the opened tab if it is still blank (never navigated). */\n function closeUnnavigatedWindow(): void {\n if (openedWindow) {\n openedWindow.close();\n openedWindow = null;\n }\n }\n\n function isRunningPhase(): boolean {\n return (\n state.type === \"creating\" ||\n state.type === \"awaiting_approval\" ||\n state.type === \"ready_to_open\" ||\n state.type === \"reading\"\n );\n }\n\n async function readAndFinish(request: AccessRequest): Promise<void> {\n setState({ type: \"reading\", request });\n try {\n const result = await transports.readResult(request.requestId);\n if (!running) return;\n setState({ type: \"done\", result });\n } catch (err) {\n if (!running) return;\n setState({ type: \"error\", error: toError(err) });\n } finally {\n running = false;\n }\n }\n\n function scheduleNextPoll(request: AccessRequest, deadline: number): void {\n pollHandle = setTimeoutFn(() => {\n void poll(request, deadline);\n }, pollIntervalMs);\n }\n\n function requestDeadline(request: AccessRequest): number {\n if (request.expiresAt !== undefined) {\n const expiresAt = Date.parse(request.expiresAt);\n if (Number.isFinite(expiresAt)) return expiresAt;\n }\n return now() + timeoutMs;\n }\n\n /**\n * Enter the polling loop from the given initial state (either\n * `awaiting_approval` for desktop/light or `ready_to_open` for mobile-deep).\n * Errors out immediately if the request has already expired.\n */\n function startPolling(\n request: AccessRequest,\n initialState: DirectConnectState<T>,\n ): void {\n setState(initialState);\n const deadline = requestDeadline(request);\n if (now() >= deadline) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(\"Access request expired\"),\n });\n return;\n }\n scheduleNextPoll(request, deadline);\n }\n\n async function poll(request: AccessRequest, deadline: number): Promise<void> {\n if (!running) return;\n if (now() >= deadline) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(\"Timed out waiting for approval\"),\n });\n return;\n }\n let status: AccessRequestStatus;\n try {\n status = await transports.getStatus(request.requestId);\n } catch (err) {\n if (!running) return;\n running = false;\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (!running) return;\n\n // A pending deep-mobile status may rotate the continuation ticket. Adopt a\n // fresh, still-valid URL so the rendered \"Open Vana\" link always points at a\n // live ticket; ignore it on the desktop/light path.\n if (status.status === \"pending\" && state.type === \"ready_to_open\") {\n const refreshed = normalizeMobileContinuationUrl(\n status.mobileContinuationUrl,\n );\n if (refreshed && refreshed !== state.mobileContinuationUrl) {\n request = { ...request, mobileContinuationUrl: refreshed };\n setState({\n type: \"ready_to_open\",\n request,\n mobileContinuationUrl: refreshed,\n });\n }\n }\n\n if (isReadReadyStatus(status.status)) {\n clearPoll();\n approvedRequest = request;\n await readAndFinish(request);\n return;\n }\n if (\n status.status === \"completed\" ||\n status.status === \"denied\" ||\n status.status === \"expired\"\n ) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(`Access request ${status.status}`),\n });\n return;\n }\n scheduleNextPoll(request, deadline);\n }\n\n const flow: DirectConnectFlow<T> = {\n getState() {\n return state;\n },\n\n subscribe(listener: () => void) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n\n async start(): Promise<void> {\n if (running || isRunningPhase()) return;\n running = true;\n // start() deliberately keeps its established first-run semantics: every\n // explicit start creates a request. Only retryRead() may reuse consent.\n approvedRequest = null;\n const runId = ++activeRunId;\n // Read the platform policy at start time, like openApprovalWindow below,\n // so a policy swapped in after construction (a React rerender forwards\n // options through a ref) still decides this run's destination.\n const browserPlatform = (\n options.browserPlatformPolicy ?? defaultBrowserPlatformPolicy()\n ).current();\n\n // Desktop preserves the pre-mobile synchronous popup contract: open a\n // blank tab while the click's transient activation is live, then navigate\n // it once createRequest returns the approval URL (BUI-622). Mobile never\n // creates that transient tab; deep requests expose one explicit HTTPS\n // link, while light requests retain the manual approvalUrl fallback.\n // Read the opener option at start time so a swapped-in custom opener is\n // still honored for desktop flows.\n const approvalWindow =\n browserPlatform === \"desktop\"\n ? (options.openApprovalWindow ?? defaultOpenApprovalWindow)()\n : null;\n openedWindow = approvalWindow;\n\n setState({ type: \"creating\" });\n\n let request: AccessRequest;\n try {\n request = await transports.createRequest();\n } catch (err) {\n // If we were superseded (reset, possibly + a newer start()) while this\n // request was in flight, only clean up our own tab — never the shared\n // state or the newer run's window.\n if (runId !== activeRunId) {\n approvalWindow?.close();\n return;\n }\n running = false;\n closeUnnavigatedWindow();\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (runId !== activeRunId) {\n approvalWindow?.close();\n return;\n }\n // Re-validate the continuation URL at the SDK boundary (defense in depth\n // for custom transports that bypass the default client).\n request = {\n ...request,\n mobileContinuationUrl: normalizeMobileContinuationUrl(\n request.mobileContinuationUrl,\n ),\n };\n\n // The SDK owns only the small mobile-versus-desktop destination choice.\n // A deep Direct request on mobile carries a validated continuation URL;\n // desktop keeps its popup contract, while mobile light exposes the HTTPS\n // approval URL as the existing manual fallback without opening a tab.\n const mobileContinuationUrl =\n browserPlatform === \"mobile\"\n ? request.mobileContinuationUrl\n : undefined;\n\n if (mobileContinuationUrl) {\n // Do not auto-launch: DCR creation is async, so the original Connect\n // gesture can no longer be trusted to retain iOS user activation. Let\n // the UI render an explicit primary \"Open Vana\" link; polling continues\n // in this tab.\n startPolling(request, {\n type: \"ready_to_open\",\n request,\n mobileContinuationUrl,\n });\n return;\n }\n\n // Desktop/light: navigate the synchronously-opened tab to the HTTPS\n // approval URL. `approvalWindow === null` means the popup was blocked;\n // surface it so the UI renders request.approvalUrl as a visible manual\n // \"Open approval\" link instead of hanging. We poll either way, so a manual\n // open still resolves the flow, and the timeout still bounds the wait.\n if (approvalWindow) {\n approvalWindow.navigate(request.approvalUrl);\n // Hand the tab off to the user; we no longer own/close it.\n openedWindow = null;\n }\n startPolling(request, {\n type: \"awaiting_approval\",\n request,\n popupBlocked: approvalWindow === null,\n });\n },\n\n async retryRead(): Promise<DirectConnectRetryOutcome> {\n if (running || isRunningPhase()) {\n throw new Error(\n \"Cannot retry a read while the connect flow is running\",\n );\n }\n\n const request = approvedRequest;\n const parsedExpiry = request?.expiresAt\n ? Date.parse(request.expiresAt)\n : Number.NaN;\n const requestExpired =\n Number.isFinite(parsedExpiry) && now() >= parsedExpiry;\n\n if (request && !requestExpired) {\n running = true;\n const runId = ++activeRunId;\n let status: AccessRequestStatus;\n try {\n status = await transports.getStatus(request.requestId);\n } catch (err) {\n if (runId !== activeRunId) {\n throw new Error(\"Read retry was superseded\");\n }\n running = false;\n const error = toError(err);\n setState({ type: \"error\", error });\n throw error;\n }\n if (runId !== activeRunId) {\n throw new Error(\"Read retry was superseded\");\n }\n if (isReadReadyStatus(status.status)) {\n await readAndFinish(request);\n return \"retried_existing_grant\";\n }\n running = false;\n }\n\n approvedRequest = null;\n await flow.start();\n return \"fresh_approval_required\";\n },\n\n reset(): void {\n running = false;\n approvedRequest = null;\n // Invalidate any in-flight start() so a late createRequest can't clobber\n // a subsequent run.\n activeRunId++;\n clearPoll();\n closeUnnavigatedWindow();\n setState({ type: \"idle\" });\n },\n };\n\n return flow;\n}\n"],"mappings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,SAAS,QAAQ,WAAW;AAE3C,uBAAe;AAAA,MACjB;AACA,mBAAa,SAAS;AAAA,QACpB,MAAM;AAAA,QACN;AAAA,QACA,cAAc,mBAAmB;AAAA,MACnC,CAAC;AAAA,IACH;AAAA,IAEA,MAAM,YAAgD;AACpD,UAAI,WAAW,eAAe,GAAG;AAC/B,cAAM,IAAI;AAAA,UACR;AAAA,QACF;AAAA,MACF;AAEA,YAAM,UAAU;AAChB,YAAM,eAAe,SAAS,YAC1B,KAAK,MAAM,QAAQ,SAAS,IAC5B,OAAO;AACX,YAAM,iBACJ,OAAO,SAAS,YAAY,KAAK,IAAI,KAAK;AAE5C,UAAI,WAAW,CAAC,gBAAgB;AAC9B,kBAAU;AACV,cAAM,QAAQ,EAAE;AAChB,YAAI;AACJ,YAAI;AACF,mBAAS,MAAM,WAAW,UAAU,QAAQ,SAAS;AAAA,QACvD,SAAS,KAAK;AACZ,cAAI,UAAU,aAAa;AACzB,kBAAM,IAAI,MAAM,2BAA2B;AAAA,UAC7C;AACA,oBAAU;AACV,gBAAM,QAAQ,QAAQ,GAAG;AACzB,mBAAS,EAAE,MAAM,SAAS,MAAM,CAAC;AACjC,gBAAM;AAAA,QACR;AACA,YAAI,UAAU,aAAa;AACzB,gBAAM,IAAI,MAAM,2BAA2B;AAAA,QAC7C;AACA,YAAI,kBAAkB,OAAO,MAAM,GAAG;AACpC,gBAAM,cAAc,OAAO;AAC3B,iBAAO;AAAA,QACT;AACA,kBAAU;AAAA,MACZ;AAEA,wBAAkB;AAClB,YAAM,KAAK,MAAM;AACjB,aAAO;AAAA,IACT;AAAA,IAEA,QAAc;AACZ,gBAAU;AACV,wBAAkB;AAGlB;AACA,gBAAU;AACV,6BAAuB;AACvB,eAAS,EAAE,MAAM,OAAO,CAAC;AAAA,IAC3B;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
|
|
@@ -28,7 +28,7 @@ var import_escrow = require("../protocol/escrow");
|
|
|
28
28
|
var import_addresses = require("../generated/addresses");
|
|
29
29
|
var import_access_request_client = require("./access-request-client");
|
|
30
30
|
var import_endpoints = require("./endpoints");
|
|
31
|
-
var import_errors = require("./errors");
|
|
31
|
+
var import_errors = require("./errors.cjs");
|
|
32
32
|
var import_personal_server_read = require("./personal-server-read");
|
|
33
33
|
function isHexPrivateKey(value) {
|
|
34
34
|
return /^0x[0-9a-fA-F]{64}$/.test(value);
|
package/dist/direct/errors.cjs
CHANGED
|
@@ -25,7 +25,7 @@ __export(errors_exports, {
|
|
|
25
25
|
ScopeNotApprovedError: () => ScopeNotApprovedError
|
|
26
26
|
});
|
|
27
27
|
module.exports = __toCommonJS(errors_exports);
|
|
28
|
-
var import_errors = require("../errors");
|
|
28
|
+
var import_errors = require("../errors.cjs");
|
|
29
29
|
class DirectConfigError extends import_errors.VanaError {
|
|
30
30
|
constructor(message, details) {
|
|
31
31
|
super(message, "DIRECT_CONFIG_ERROR");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/direct/escrow-payment.ts"],"sourcesContent":["/**\n * Escrow-backed payment authorization for the Direct Data Controller.\n *\n * @remarks\n * Builds on the DPv2 escrow surface added in `protocol/escrow`. When a Personal\n * Server read returns `402 Payment Required`, the controller settles the\n * challenged operation through the escrow gateway:\n *\n * 1. Sign the challenge's `GenericPayment` EIP-712 message with the app key.\n * 2. POST it to the gateway's `/v1/escrow/pay` via {@link EscrowGatewayClient}.\n * 3. Map the gateway's {@link EscrowPayResult} into a typed\n * {@link DirectPaymentReceipt} for the caller to inspect.\n *\n * This module supports legacy `\"grant\"` operations and receipt-bound\n * `\"data_access\"` operations. It adapts the escrow `payForOp` flow to the\n * direct-read use case; it does not define its own payment scheme.\n *\n * @category Direct\n * @module direct/escrow-payment\n */\n\nimport {\n GENERIC_PAYMENT_TYPES,\n NATIVE_ASSET_ADDRESS,\n genericPaymentDomain,\n type EscrowAccessRecord,\n type EscrowGatewayClient,\n type EscrowPayResult,\n type PaymentBreakdown,\n} from \"../protocol/escrow\";\nimport type {\n DirectFeeBreakdown,\n DirectPaymentReceipt,\n DirectPaymentResponseMetadata,\n PersonalServerPaymentOperation,\n PersonalServerPaymentRequired,\n} from \"./types\";\n\n/** The escrow `GenericPayment.opType` used for grant-lifecycle payments. */\nexport const GRANT_OP_TYPE = \"grant\" as const;\n/** The escrow `GenericPayment.opType` used for receipt-bound data access. */\nexport const DATA_ACCESS_OP_TYPE = \"data_access\" as const;\n\n/**\n * EIP-712 typed-data signer (e.g. viem `account.signTypedData`).\n *\n * @remarks\n * Kept structurally minimal so any viem account/wallet client satisfies it\n * without the SDK depending on viem's exact `signTypedData` overload set.\n */\nexport type SignTypedDataFn = (args: {\n domain: ReturnType<typeof genericPaymentDomain>;\n types: typeof GENERIC_PAYMENT_TYPES;\n primaryType: \"GenericPayment\";\n message: {\n payerAddress: `0x${string}`;\n opType: string;\n opId: `0x${string}`;\n asset: `0x${string}`;\n amount: bigint;\n paymentNonce: bigint;\n };\n}) => Promise<`0x${string}`>;\n\n/** Supplies a monotonically-increasing payment nonce per payer. */\nexport type PaymentNonceSource = (\n payerAddress: string,\n) => Promise<bigint> | bigint;\n\ninterface EscrowPaymentMessage {\n payerAddress: `0x${string}`;\n opType: typeof GRANT_OP_TYPE | typeof DATA_ACCESS_OP_TYPE;\n opId: `0x${string}`;\n asset: `0x${string}`;\n amount: string;\n paymentNonce: string;\n}\n\ninterface SignedEscrowPayment {\n message: EscrowPaymentMessage;\n signature: `0x${string}`;\n accessRecord?: EscrowAccessRecord;\n}\n\ninterface X402PaymentHeader {\n x402Version: 1;\n scheme: \"vana-escrow-grant\";\n network: string;\n payload: SignedEscrowPayment;\n}\n\n/** Configuration required to sign an escrow X-PAYMENT header. */\nexport interface EscrowPaymentHeaderConfig {\n /** Deployed `DataPortabilityEscrow` contract address. */\n escrowContract: `0x${string}`;\n /** Chain id for the EIP-712 domain (1480 mainnet, 14800 moksha). */\n chainId: number;\n /** App EIP-712 signer. */\n signTypedData: SignTypedDataFn;\n /**\n * Supplies the next payment nonce for a payer. Defaults to a process-local\n * monotonic counter seeded at 1. Provide a durable source in production so\n * nonces survive restarts (the gateway rejects reused (payer, nonce) pairs).\n */\n nonceSource?: PaymentNonceSource;\n}\n\n/**\n * Escrow settlement configuration for gateway authorization.\n *\n * @remarks\n * Extends the header-signing boundary with the gateway client used by\n * {@link authorizeEscrowPayment}. Existing controller and legacy wrapper\n * callers can continue to provide this full configuration.\n */\nexport interface EscrowPaymentConfig extends EscrowPaymentHeaderConfig {\n /** Client for the gateway escrow endpoints (`/v1/escrow/*`). */\n client: EscrowGatewayClient;\n}\n\n/** Map the gateway {@link PaymentBreakdown} into the public {@link DirectFeeBreakdown}. */\nexport function toDirectFeeBreakdown(\n breakdown: PaymentBreakdown,\n): DirectFeeBreakdown {\n return {\n registrationFee: breakdown.registrationFee,\n dataAccessFee: breakdown.dataAccessFee,\n registrationPaid: breakdown.registrationPaid,\n };\n}\n\n/** Map a gateway {@link EscrowPayResult} into the public {@link DirectPaymentReceipt}. */\nexport function toDirectPaymentReceipt(\n result: EscrowPayResult,\n): DirectPaymentReceipt {\n return {\n opType: result.opType,\n opId: result.opId,\n asset: result.asset,\n amount: result.amount,\n paymentNonce: result.paymentNonce,\n breakdown: toDirectFeeBreakdown(result.breakdown),\n paidAt: result.paidAt,\n };\n}\n\n/** Default in-process monotonic nonce counter (seeded at 1 per payer). */\nexport function createDefaultNonceSource(): PaymentNonceSource {\n const counters = new Map<string, bigint>();\n return (payerAddress: string): bigint => {\n const key = payerAddress.toLowerCase();\n const next = (counters.get(key) ?? 0n) + 1n;\n counters.set(key, next);\n return next;\n };\n}\n\nconst processLocalNonceSource = createDefaultNonceSource();\nconst UINT256_MAX = (1n << 256n) - 1n;\nconst ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;\nconst BYTES32_RE = /^0x[0-9a-fA-F]{64}$/;\nconst SIGNATURE_RE = /^0x[0-9a-fA-F]{130}$/;\n\nfunction isUint256Decimal(value: string, allowZero: boolean): boolean {\n const pattern = allowZero ? /^(0|[1-9]\\d*)$/ : /^[1-9]\\d*$/;\n return (\n value.length <= UINT256_MAX.toString().length &&\n pattern.test(value) &&\n BigInt(value) <= UINT256_MAX\n );\n}\n\nfunction isValidAccessRecord(record: EscrowAccessRecord): boolean {\n return (\n BYTES32_RE.test(record.dataPointId) &&\n isUint256Decimal(record.version, false) &&\n ADDRESS_RE.test(record.accessor) &&\n BYTES32_RE.test(record.recordId) &&\n SIGNATURE_RE.test(record.signature)\n );\n}\n\nfunction validateSigningOperation(\n payerAddress: `0x${string}`,\n required: PersonalServerPaymentOperation,\n): void {\n if (!ADDRESS_RE.test(payerAddress)) {\n throw new Error(\"Payment payer must be a 20-byte EVM address\");\n }\n if (!BYTES32_RE.test(required.opId)) {\n throw new Error(\"Payment operation id must be a 32-byte hex value\");\n }\n if (!ADDRESS_RE.test(required.asset || NATIVE_ASSET_ADDRESS)) {\n throw new Error(\"Payment asset must be a 20-byte EVM address\");\n }\n if (!isUint256Decimal(required.amount, true)) {\n throw new Error(\"Payment amount must be a canonical uint256 decimal\");\n }\n if (\n required.paymentNonce !== undefined &&\n !isUint256Decimal(required.paymentNonce, false)\n ) {\n throw new Error(\"Payment nonce must be a positive uint256 decimal\");\n }\n\n const accessRecord = required.accessRecord;\n if (required.opType === DATA_ACCESS_OP_TYPE) {\n if (!accessRecord || !isValidAccessRecord(accessRecord)) {\n throw new Error(\"Data-access payment requires a valid access record\");\n }\n if (required.opId.toLowerCase() !== accessRecord.recordId.toLowerCase()) {\n throw new Error(\n \"Data-access payment operation id must equal the access record id\",\n );\n }\n if (accessRecord.accessor.toLowerCase() !== payerAddress.toLowerCase()) {\n throw new Error(\n \"Data-access payment accessor must equal the payment payer address\",\n );\n }\n return;\n }\n\n if (required.amount === \"0\") {\n if (\n !accessRecord ||\n !isValidAccessRecord(accessRecord) ||\n accessRecord.accessor.toLowerCase() !== payerAddress.toLowerCase()\n ) {\n throw new Error(\n \"Zero-amount grant payments require a valid access record for the payer\",\n );\n }\n }\n}\n\nfunction base64EncodeJson(value: unknown): string {\n const bytes = new TextEncoder().encode(JSON.stringify(value));\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction base64DecodeJson(value: string): unknown {\n const binary = atob(value);\n const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));\n return JSON.parse(new TextDecoder().decode(bytes));\n}\n\nasync function signEscrowPayment(params: {\n payerAddress: `0x${string}`;\n required: PersonalServerPaymentOperation;\n config: EscrowPaymentHeaderConfig;\n}): Promise<SignedEscrowPayment> {\n const { payerAddress, required, config } = params;\n validateSigningOperation(payerAddress, required);\n const nonceSource = config.nonceSource ?? processLocalNonceSource;\n const paymentNonce = BigInt(\n required.paymentNonce ?? (await nonceSource(payerAddress)),\n );\n const asset = (required.asset || NATIVE_ASSET_ADDRESS) as `0x${string}`;\n const opId = required.opId as `0x${string}`;\n const amount = BigInt(required.amount);\n if (amount < 0n || amount > UINT256_MAX) {\n throw new Error(\"Payment amount must be a uint256\");\n }\n if (paymentNonce <= 0n || paymentNonce > UINT256_MAX) {\n throw new Error(\"Payment nonce must be a positive uint256\");\n }\n\n const message = {\n payerAddress,\n opType: required.opType,\n opId,\n asset,\n amount,\n paymentNonce,\n };\n\n const signature = await config.signTypedData({\n domain: genericPaymentDomain(config.chainId, config.escrowContract),\n types: GENERIC_PAYMENT_TYPES,\n primaryType: \"GenericPayment\",\n message,\n });\n\n return {\n message: {\n ...message,\n amount: amount.toString(),\n paymentNonce: paymentNonce.toString(),\n },\n signature,\n ...(required.accessRecord ? { accessRecord: required.accessRecord } : {}),\n };\n}\n\n/**\n * Build the canonical X-PAYMENT header for a validated escrow operation.\n *\n * @remarks\n * Supports both legacy grant payments and receipt-bound data-access payments.\n * Signing is injected through {@link EscrowPaymentHeaderConfig.signTypedData}.\n */\nexport async function buildEscrowPaymentHeader(params: {\n /** Address whose escrow balance pays for the operation. */\n payerAddress: `0x${string}`;\n /** Validated operation parsed from the Personal Server challenge. */\n required: PersonalServerPaymentOperation;\n /** Escrow contract, chain, signer, and nonce configuration. */\n config: EscrowPaymentHeaderConfig;\n}): Promise<string> {\n const network = params.required.network ?? `vana:${params.config.chainId}`;\n if (network !== `vana:${params.config.chainId}`) {\n throw new Error(\"Payment network must match the configured chain\");\n }\n\n const signed = await signEscrowPayment(params);\n const payment: X402PaymentHeader = {\n x402Version: 1,\n scheme: \"vana-escrow-grant\",\n network,\n payload: signed,\n };\n return base64EncodeJson(payment);\n}\n\n/** Build a legacy grant X-PAYMENT header. */\nexport async function buildGrantPaymentHeader(params: {\n payerAddress: `0x${string}`;\n required: PersonalServerPaymentRequired;\n config: EscrowPaymentConfig;\n}): Promise<string> {\n return buildEscrowPaymentHeader({\n ...params,\n required: {\n ...params.required,\n opType: GRANT_OP_TYPE,\n opId: params.required.grantId,\n },\n });\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nfunction stringField(\n value: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n const field = value?.[key];\n return typeof field === \"string\" ? field : undefined;\n}\n\nfunction isCanonicalIsoTimestamp(value: string): boolean {\n try {\n return new Date(value).toISOString() === value;\n } catch {\n return false;\n }\n}\n\n/**\n * Parse shape-validated payment response metadata echoed by a Personal Server.\n *\n * @remarks\n * This metadata is not authenticated by the gateway. It is suitable for\n * display and debugging, not as proof that a payment occurred.\n */\nexport function paymentResponseMetadataFromHeader(\n header: string | null | undefined,\n): DirectPaymentResponseMetadata | undefined {\n if (!header) return undefined;\n try {\n const result = asRecord(base64DecodeJson(header));\n const breakdown = asRecord(result?.breakdown);\n const opType = stringField(result, \"opType\");\n const opId = stringField(result, \"opId\");\n const payerAddress = stringField(result, \"payerAddress\");\n const asset = stringField(result, \"asset\");\n const amount = stringField(result, \"amount\");\n const paymentNonce = stringField(result, \"paymentNonce\");\n const registrationFee = stringField(breakdown, \"registrationFee\");\n const dataAccessFee = stringField(breakdown, \"dataAccessFee\");\n const paidAt = stringField(result, \"paidAt\");\n if (\n result?.success !== true ||\n !opType ||\n !opId ||\n !BYTES32_RE.test(opId) ||\n !payerAddress ||\n !ADDRESS_RE.test(payerAddress) ||\n !asset ||\n !ADDRESS_RE.test(asset) ||\n !amount ||\n !isUint256Decimal(amount, true) ||\n !paymentNonce ||\n !isUint256Decimal(paymentNonce, false) ||\n !registrationFee ||\n !isUint256Decimal(registrationFee, true) ||\n !dataAccessFee ||\n !isUint256Decimal(dataAccessFee, true) ||\n typeof breakdown?.registrationPaid !== \"boolean\" ||\n !paidAt ||\n !isCanonicalIsoTimestamp(paidAt)\n ) {\n return undefined;\n }\n return {\n opType,\n opId,\n asset,\n amount,\n paymentNonce,\n breakdown: {\n registrationFee,\n dataAccessFee,\n registrationPaid: breakdown.registrationPaid,\n },\n paidAt,\n };\n } catch {\n return undefined;\n }\n}\n\n/**\n * @deprecated Use {@link paymentResponseMetadataFromHeader}. A Personal\n * Server response header is untrusted metadata, not a gateway-authenticated\n * receipt.\n */\nexport function paymentReceiptFromHeader(\n header: string | null | undefined,\n): DirectPaymentResponseMetadata | undefined {\n return paymentResponseMetadataFromHeader(header);\n}\n\n/**\n * Authorize an escrow payment for a grant data-access fee.\n *\n * @param params - The payment requirement, the payer address, and escrow config.\n * @returns The gateway's {@link EscrowPayResult} as a typed\n * {@link DirectPaymentReceipt}.\n */\nexport async function authorizeGrantPayment(params: {\n payerAddress: `0x${string}`;\n required: PersonalServerPaymentRequired;\n config: EscrowPaymentConfig;\n}): Promise<DirectPaymentReceipt> {\n return authorizeEscrowPayment({\n ...params,\n required: {\n ...params.required,\n opType: GRANT_OP_TYPE,\n opId: params.required.grantId,\n },\n });\n}\n\n/**\n * Authorize a validated grant or data-access operation through the escrow\n * gateway.\n */\nexport async function authorizeEscrowPayment(params: {\n /** Address whose escrow balance pays for the operation. */\n payerAddress: `0x${string}`;\n /** Validated operation to authorize. */\n required: PersonalServerPaymentOperation;\n /** Escrow gateway and signing configuration. */\n config: EscrowPaymentConfig;\n}): Promise<DirectPaymentReceipt> {\n const { payerAddress, config } = params;\n const signed = await signEscrowPayment(params);\n\n const result = await config.client.payForOp({\n payerAddress,\n opType: signed.message.opType,\n opId: signed.message.opId,\n asset: signed.message.asset,\n amount: signed.message.amount,\n paymentNonce: signed.message.paymentNonce,\n signature: signed.signature,\n accessRecord: signed.accessRecord,\n });\n\n return toDirectPaymentReceipt(result);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBA,oBAQO;AAUA,MAAM,gBAAgB;AAEtB,MAAM,sBAAsB;AAgF5B,SAAS,qBACd,WACoB;AACpB,SAAO;AAAA,IACL,iBAAiB,UAAU;AAAA,IAC3B,eAAe,UAAU;AAAA,IACzB,kBAAkB,UAAU;AAAA,EAC9B;AACF;AAGO,SAAS,uBACd,QACsB;AACtB,SAAO;AAAA,IACL,QAAQ,OAAO;AAAA,IACf,MAAM,OAAO;AAAA,IACb,OAAO,OAAO;AAAA,IACd,QAAQ,OAAO;AAAA,IACf,cAAc,OAAO;AAAA,IACrB,WAAW,qBAAqB,OAAO,SAAS;AAAA,IAChD,QAAQ,OAAO;AAAA,EACjB;AACF;AAGO,SAAS,2BAA+C;AAC7D,QAAM,WAAW,oBAAI,IAAoB;AACzC,SAAO,CAAC,iBAAiC;AACvC,UAAM,MAAM,aAAa,YAAY;AACrC,UAAM,QAAQ,SAAS,IAAI,GAAG,KAAK,MAAM;AACzC,aAAS,IAAI,KAAK,IAAI;AACtB,WAAO;AAAA,EACT;AACF;AAEA,MAAM,0BAA0B,yBAAyB;AACzD,MAAM,eAAe,MAAM,QAAQ;AACnC,MAAM,aAAa;AACnB,MAAM,aAAa;AACnB,MAAM,eAAe;AAErB,SAAS,iBAAiB,OAAe,WAA6B;AACpE,QAAM,UAAU,YAA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,MACR,MAAM,OAAO,SAAS;AAAA,IACxB;AAAA,EACF,CAAC;AACH;AAMA,eAAsB,uBAAuB,QAOX;AAChC,QAAM,EAAE,cAAc,OAAO,IAAI;AACjC,QAAM,SAAS,MAAM,kBAAkB,MAAM;AAE7C,QAAM,SAAS,MAAM,OAAO,OAAO,SAAS;AAAA,IAC1C;AAAA,IACA,QAAQ,OAAO,QAAQ;AAAA,IACvB,MAAM,OAAO,QAAQ;AAAA,IACrB,OAAO,OAAO,QAAQ;AAAA,IACtB,QAAQ,OAAO,QAAQ;AAAA,IACvB,cAAc,OAAO,QAAQ;AAAA,IAC7B,WAAW,OAAO;AAAA,IAClB,cAAc,OAAO;AAAA,EACvB,CAAC;AAED,SAAO,uBAAuB,MAAM;AACtC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/direct/escrow-payment.ts"],"sourcesContent":["/**\n * Escrow-backed payment authorization for the Direct Data Controller.\n *\n * @remarks\n * Builds on the DPv2 escrow surface added in `protocol/escrow`. When a Personal\n * Server read returns `402 Payment Required`, the controller settles the\n * challenged operation through the escrow gateway:\n *\n * 1. Sign the challenge's `GenericPayment` EIP-712 message with the app key.\n * 2. POST it to the gateway's `/v1/escrow/pay` via {@link EscrowGatewayClient}.\n * 3. Map the gateway's {@link EscrowPayResult} into a typed\n * {@link DirectPaymentReceipt} for the caller to inspect.\n *\n * This module supports legacy `\"grant\"` operations and receipt-bound\n * `\"data_access\"` operations. It adapts the escrow `payForOp` flow to the\n * direct-read use case; it does not define its own payment scheme.\n *\n * @category Direct\n * @module direct/escrow-payment\n */\n\nimport {\n GENERIC_PAYMENT_TYPES,\n NATIVE_ASSET_ADDRESS,\n genericPaymentDomain,\n type EscrowAccessRecord,\n type EscrowPaymentClient,\n type EscrowPayResult,\n type PaymentBreakdown,\n} from \"../protocol/escrow\";\nimport type {\n DirectFeeBreakdown,\n DirectPaymentReceipt,\n DirectPaymentResponseMetadata,\n PersonalServerPaymentOperation,\n PersonalServerPaymentRequired,\n} from \"./types\";\n\n/** The escrow `GenericPayment.opType` used for grant-lifecycle payments. */\nexport const GRANT_OP_TYPE = \"grant\" as const;\n/** The escrow `GenericPayment.opType` used for receipt-bound data access. */\nexport const DATA_ACCESS_OP_TYPE = \"data_access\" as const;\n\n/**\n * EIP-712 typed-data signer (e.g. viem `account.signTypedData`).\n *\n * @remarks\n * Kept structurally minimal so any viem account/wallet client satisfies it\n * without the SDK depending on viem's exact `signTypedData` overload set.\n */\nexport type SignTypedDataFn = (args: {\n domain: ReturnType<typeof genericPaymentDomain>;\n types: typeof GENERIC_PAYMENT_TYPES;\n primaryType: \"GenericPayment\";\n message: {\n payerAddress: `0x${string}`;\n opType: string;\n opId: `0x${string}`;\n asset: `0x${string}`;\n amount: bigint;\n paymentNonce: bigint;\n };\n}) => Promise<`0x${string}`>;\n\n/** Supplies a monotonically-increasing payment nonce per payer. */\nexport type PaymentNonceSource = (\n payerAddress: string,\n) => Promise<bigint> | bigint;\n\ninterface EscrowPaymentMessage {\n payerAddress: `0x${string}`;\n opType: typeof GRANT_OP_TYPE | typeof DATA_ACCESS_OP_TYPE;\n opId: `0x${string}`;\n asset: `0x${string}`;\n amount: string;\n paymentNonce: string;\n}\n\ninterface SignedEscrowPayment {\n message: EscrowPaymentMessage;\n signature: `0x${string}`;\n accessRecord?: EscrowAccessRecord;\n}\n\ninterface X402PaymentHeader {\n x402Version: 1;\n scheme: \"vana-escrow-grant\";\n network: string;\n payload: SignedEscrowPayment;\n}\n\n/** Configuration required to sign an escrow X-PAYMENT header. */\nexport interface EscrowPaymentHeaderConfig {\n /** Deployed `DataPortabilityEscrow` contract address. */\n escrowContract: `0x${string}`;\n /** Chain id for the EIP-712 domain (1480 mainnet, 14800 moksha). */\n chainId: number;\n /** App EIP-712 signer. */\n signTypedData: SignTypedDataFn;\n /**\n * Supplies the next payment nonce for a payer. Defaults to a process-local\n * monotonic counter seeded at 1. Provide a durable source in production so\n * nonces survive restarts (the gateway rejects reused (payer, nonce) pairs).\n */\n nonceSource?: PaymentNonceSource;\n}\n\n/**\n * Escrow settlement configuration for gateway authorization.\n *\n * @remarks\n * Extends the header-signing boundary with the gateway client used by\n * {@link authorizeEscrowPayment}. Existing controller and legacy wrapper\n * callers can continue to provide this full configuration.\n */\nexport interface EscrowPaymentConfig extends EscrowPaymentHeaderConfig {\n /** Client for the gateway escrow endpoints (`/v1/escrow/*`). */\n client: EscrowPaymentClient;\n}\n\n/** Map the gateway {@link PaymentBreakdown} into the public {@link DirectFeeBreakdown}. */\nexport function toDirectFeeBreakdown(\n breakdown: PaymentBreakdown,\n): DirectFeeBreakdown {\n return {\n registrationFee: breakdown.registrationFee,\n dataAccessFee: breakdown.dataAccessFee,\n registrationPaid: breakdown.registrationPaid,\n };\n}\n\n/** Map a gateway {@link EscrowPayResult} into the public {@link DirectPaymentReceipt}. */\nexport function toDirectPaymentReceipt(\n result: EscrowPayResult,\n): DirectPaymentReceipt {\n return {\n opType: result.opType,\n opId: result.opId,\n asset: result.asset,\n amount: result.amount,\n paymentNonce: result.paymentNonce,\n breakdown: toDirectFeeBreakdown(result.breakdown),\n paidAt: result.paidAt,\n };\n}\n\n/** Default in-process monotonic nonce counter (seeded at 1 per payer). */\nexport function createDefaultNonceSource(): PaymentNonceSource {\n const counters = new Map<string, bigint>();\n return (payerAddress: string): bigint => {\n const key = payerAddress.toLowerCase();\n const next = (counters.get(key) ?? 0n) + 1n;\n counters.set(key, next);\n return next;\n };\n}\n\nconst processLocalNonceSource = createDefaultNonceSource();\nconst UINT256_MAX = (1n << 256n) - 1n;\nconst ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;\nconst BYTES32_RE = /^0x[0-9a-fA-F]{64}$/;\nconst SIGNATURE_RE = /^0x[0-9a-fA-F]{130}$/;\n\nfunction isUint256Decimal(value: string, allowZero: boolean): boolean {\n const pattern = allowZero ? /^(0|[1-9]\\d*)$/ : /^[1-9]\\d*$/;\n return (\n value.length <= UINT256_MAX.toString().length &&\n pattern.test(value) &&\n BigInt(value) <= UINT256_MAX\n );\n}\n\nfunction isValidAccessRecord(record: EscrowAccessRecord): boolean {\n return (\n BYTES32_RE.test(record.dataPointId) &&\n isUint256Decimal(record.version, false) &&\n ADDRESS_RE.test(record.accessor) &&\n BYTES32_RE.test(record.recordId) &&\n SIGNATURE_RE.test(record.signature)\n );\n}\n\nfunction validateSigningOperation(\n payerAddress: `0x${string}`,\n required: PersonalServerPaymentOperation,\n): void {\n if (!ADDRESS_RE.test(payerAddress)) {\n throw new Error(\"Payment payer must be a 20-byte EVM address\");\n }\n if (!BYTES32_RE.test(required.opId)) {\n throw new Error(\"Payment operation id must be a 32-byte hex value\");\n }\n if (!ADDRESS_RE.test(required.asset || NATIVE_ASSET_ADDRESS)) {\n throw new Error(\"Payment asset must be a 20-byte EVM address\");\n }\n if (!isUint256Decimal(required.amount, true)) {\n throw new Error(\"Payment amount must be a canonical uint256 decimal\");\n }\n if (\n required.paymentNonce !== undefined &&\n !isUint256Decimal(required.paymentNonce, false)\n ) {\n throw new Error(\"Payment nonce must be a positive uint256 decimal\");\n }\n\n const accessRecord = required.accessRecord;\n if (required.opType === DATA_ACCESS_OP_TYPE) {\n if (!accessRecord || !isValidAccessRecord(accessRecord)) {\n throw new Error(\"Data-access payment requires a valid access record\");\n }\n if (required.opId.toLowerCase() !== accessRecord.recordId.toLowerCase()) {\n throw new Error(\n \"Data-access payment operation id must equal the access record id\",\n );\n }\n if (accessRecord.accessor.toLowerCase() !== payerAddress.toLowerCase()) {\n throw new Error(\n \"Data-access payment accessor must equal the payment payer address\",\n );\n }\n return;\n }\n\n if (required.amount === \"0\") {\n if (\n !accessRecord ||\n !isValidAccessRecord(accessRecord) ||\n accessRecord.accessor.toLowerCase() !== payerAddress.toLowerCase()\n ) {\n throw new Error(\n \"Zero-amount grant payments require a valid access record for the payer\",\n );\n }\n }\n}\n\nfunction base64EncodeJson(value: unknown): string {\n const bytes = new TextEncoder().encode(JSON.stringify(value));\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction base64DecodeJson(value: string): unknown {\n const binary = atob(value);\n const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));\n return JSON.parse(new TextDecoder().decode(bytes));\n}\n\nasync function signEscrowPayment(params: {\n payerAddress: `0x${string}`;\n required: PersonalServerPaymentOperation;\n config: EscrowPaymentHeaderConfig;\n}): Promise<SignedEscrowPayment> {\n const { payerAddress, required, config } = params;\n validateSigningOperation(payerAddress, required);\n const nonceSource = config.nonceSource ?? processLocalNonceSource;\n const paymentNonce = BigInt(\n required.paymentNonce ?? (await nonceSource(payerAddress)),\n );\n const asset = (required.asset || NATIVE_ASSET_ADDRESS) as `0x${string}`;\n const opId = required.opId as `0x${string}`;\n const amount = BigInt(required.amount);\n if (amount < 0n || amount > UINT256_MAX) {\n throw new Error(\"Payment amount must be a uint256\");\n }\n if (paymentNonce <= 0n || paymentNonce > UINT256_MAX) {\n throw new Error(\"Payment nonce must be a positive uint256\");\n }\n\n const message = {\n payerAddress,\n opType: required.opType,\n opId,\n asset,\n amount,\n paymentNonce,\n };\n\n const signature = await config.signTypedData({\n domain: genericPaymentDomain(config.chainId, config.escrowContract),\n types: GENERIC_PAYMENT_TYPES,\n primaryType: \"GenericPayment\",\n message,\n });\n\n return {\n message: {\n ...message,\n amount: amount.toString(),\n paymentNonce: paymentNonce.toString(),\n },\n signature,\n ...(required.accessRecord ? { accessRecord: required.accessRecord } : {}),\n };\n}\n\n/**\n * Build the canonical X-PAYMENT header for a validated escrow operation.\n *\n * @remarks\n * Supports both legacy grant payments and receipt-bound data-access payments.\n * Signing is injected through {@link EscrowPaymentHeaderConfig.signTypedData}.\n */\nexport async function buildEscrowPaymentHeader(params: {\n /** Address whose escrow balance pays for the operation. */\n payerAddress: `0x${string}`;\n /** Validated operation parsed from the Personal Server challenge. */\n required: PersonalServerPaymentOperation;\n /** Escrow contract, chain, signer, and nonce configuration. */\n config: EscrowPaymentHeaderConfig;\n}): Promise<string> {\n const network = params.required.network ?? `vana:${params.config.chainId}`;\n if (network !== `vana:${params.config.chainId}`) {\n throw new Error(\"Payment network must match the configured chain\");\n }\n\n const signed = await signEscrowPayment(params);\n const payment: X402PaymentHeader = {\n x402Version: 1,\n scheme: \"vana-escrow-grant\",\n network,\n payload: signed,\n };\n return base64EncodeJson(payment);\n}\n\n/** Build a legacy grant X-PAYMENT header. */\nexport async function buildGrantPaymentHeader(params: {\n payerAddress: `0x${string}`;\n required: PersonalServerPaymentRequired;\n config: EscrowPaymentConfig;\n}): Promise<string> {\n return buildEscrowPaymentHeader({\n ...params,\n required: {\n ...params.required,\n opType: GRANT_OP_TYPE,\n opId: params.required.grantId,\n },\n });\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nfunction stringField(\n value: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n const field = value?.[key];\n return typeof field === \"string\" ? field : undefined;\n}\n\nfunction isCanonicalIsoTimestamp(value: string): boolean {\n try {\n return new Date(value).toISOString() === value;\n } catch {\n return false;\n }\n}\n\n/**\n * Parse shape-validated payment response metadata echoed by a Personal Server.\n *\n * @remarks\n * This metadata is not authenticated by the gateway. It is suitable for\n * display and debugging, not as proof that a payment occurred.\n */\nexport function paymentResponseMetadataFromHeader(\n header: string | null | undefined,\n): DirectPaymentResponseMetadata | undefined {\n if (!header) return undefined;\n try {\n const result = asRecord(base64DecodeJson(header));\n const breakdown = asRecord(result?.breakdown);\n const opType = stringField(result, \"opType\");\n const opId = stringField(result, \"opId\");\n const payerAddress = stringField(result, \"payerAddress\");\n const asset = stringField(result, \"asset\");\n const amount = stringField(result, \"amount\");\n const paymentNonce = stringField(result, \"paymentNonce\");\n const registrationFee = stringField(breakdown, \"registrationFee\");\n const dataAccessFee = stringField(breakdown, \"dataAccessFee\");\n const paidAt = stringField(result, \"paidAt\");\n if (\n result?.success !== true ||\n !opType ||\n !opId ||\n !BYTES32_RE.test(opId) ||\n !payerAddress ||\n !ADDRESS_RE.test(payerAddress) ||\n !asset ||\n !ADDRESS_RE.test(asset) ||\n !amount ||\n !isUint256Decimal(amount, true) ||\n !paymentNonce ||\n !isUint256Decimal(paymentNonce, false) ||\n !registrationFee ||\n !isUint256Decimal(registrationFee, true) ||\n !dataAccessFee ||\n !isUint256Decimal(dataAccessFee, true) ||\n typeof breakdown?.registrationPaid !== \"boolean\" ||\n !paidAt ||\n !isCanonicalIsoTimestamp(paidAt)\n ) {\n return undefined;\n }\n return {\n opType,\n opId,\n asset,\n amount,\n paymentNonce,\n breakdown: {\n registrationFee,\n dataAccessFee,\n registrationPaid: breakdown.registrationPaid,\n },\n paidAt,\n };\n } catch {\n return undefined;\n }\n}\n\n/**\n * @deprecated Use {@link paymentResponseMetadataFromHeader}. A Personal\n * Server response header is untrusted metadata, not a gateway-authenticated\n * receipt.\n */\nexport function paymentReceiptFromHeader(\n header: string | null | undefined,\n): DirectPaymentResponseMetadata | undefined {\n return paymentResponseMetadataFromHeader(header);\n}\n\n/**\n * Authorize an escrow payment for a grant data-access fee.\n *\n * @param params - The payment requirement, the payer address, and escrow config.\n * @returns The gateway's {@link EscrowPayResult} as a typed\n * {@link DirectPaymentReceipt}.\n */\nexport async function authorizeGrantPayment(params: {\n payerAddress: `0x${string}`;\n required: PersonalServerPaymentRequired;\n config: EscrowPaymentConfig;\n}): Promise<DirectPaymentReceipt> {\n return authorizeEscrowPayment({\n ...params,\n required: {\n ...params.required,\n opType: GRANT_OP_TYPE,\n opId: params.required.grantId,\n },\n });\n}\n\n/**\n * Authorize a validated grant or data-access operation through the escrow\n * gateway.\n */\nexport async function authorizeEscrowPayment(params: {\n /** Address whose escrow balance pays for the operation. */\n payerAddress: `0x${string}`;\n /** Validated operation to authorize. */\n required: PersonalServerPaymentOperation;\n /** Escrow gateway and signing configuration. */\n config: EscrowPaymentConfig;\n}): Promise<DirectPaymentReceipt> {\n const { payerAddress, config } = params;\n const signed = await signEscrowPayment(params);\n\n const result = await config.client.payForOp({\n payerAddress,\n opType: signed.message.opType,\n opId: signed.message.opId,\n asset: signed.message.asset,\n amount: signed.message.amount,\n paymentNonce: signed.message.paymentNonce,\n signature: signed.signature,\n accessRecord: signed.accessRecord,\n });\n\n return toDirectPaymentReceipt(result);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBA,oBAQO;AAUA,MAAM,gBAAgB;AAEtB,MAAM,sBAAsB;AAgF5B,SAAS,qBACd,WACoB;AACpB,SAAO;AAAA,IACL,iBAAiB,UAAU;AAAA,IAC3B,eAAe,UAAU;AAAA,IACzB,kBAAkB,UAAU;AAAA,EAC9B;AACF;AAGO,SAAS,uBACd,QACsB;AACtB,SAAO;AAAA,IACL,QAAQ,OAAO;AAAA,IACf,MAAM,OAAO;AAAA,IACb,OAAO,OAAO;AAAA,IACd,QAAQ,OAAO;AAAA,IACf,cAAc,OAAO;AAAA,IACrB,WAAW,qBAAqB,OAAO,SAAS;AAAA,IAChD,QAAQ,OAAO;AAAA,EACjB;AACF;AAGO,SAAS,2BAA+C;AAC7D,QAAM,WAAW,oBAAI,IAAoB;AACzC,SAAO,CAAC,iBAAiC;AACvC,UAAM,MAAM,aAAa,YAAY;AACrC,UAAM,QAAQ,SAAS,IAAI,GAAG,KAAK,MAAM;AACzC,aAAS,IAAI,KAAK,IAAI;AACtB,WAAO;AAAA,EACT;AACF;AAEA,MAAM,0BAA0B,yBAAyB;AACzD,MAAM,eAAe,MAAM,QAAQ;AACnC,MAAM,aAAa;AACnB,MAAM,aAAa;AACnB,MAAM,eAAe;AAErB,SAAS,iBAAiB,OAAe,WAA6B;AACpE,QAAM,UAAU,YAAY,mBAAmB;AAC/C,SACE,MAAM,UAAU,YAAY,SAAS,EAAE,UACvC,QAAQ,KAAK,KAAK,KAClB,OAAO,KAAK,KAA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AE,cAAc,OAAO,IAAI;AACjC,QAAM,SAAS,MAAM,kBAAkB,MAAM;AAE7C,QAAM,SAAS,MAAM,OAAO,OAAO,SAAS;AAAA,IAC1C;AAAA,IACA,QAAQ,OAAO,QAAQ;AAAA,IACvB,MAAM,OAAO,QAAQ;AAAA,IACrB,OAAO,OAAO,QAAQ;AAAA,IACtB,QAAQ,OAAO,QAAQ;AAAA,IACvB,cAAc,OAAO,QAAQ;AAAA,IAC7B,WAAW,OAAO;AAAA,IAClB,cAAc,OAAO;AAAA,EACvB,CAAC;AAED,SAAO,uBAAuB,MAAM;AACtC;","names":[]}
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
* @category Direct
|
|
19
19
|
* @module direct/escrow-payment
|
|
20
20
|
*/
|
|
21
|
-
import { GENERIC_PAYMENT_TYPES, genericPaymentDomain, type
|
|
21
|
+
import { GENERIC_PAYMENT_TYPES, genericPaymentDomain, type EscrowPaymentClient, type EscrowPayResult, type PaymentBreakdown } from "../protocol/escrow.js";
|
|
22
22
|
import type { DirectFeeBreakdown, DirectPaymentReceipt, DirectPaymentResponseMetadata, PersonalServerPaymentOperation, PersonalServerPaymentRequired } from "./types.js";
|
|
23
23
|
/** The escrow `GenericPayment.opType` used for grant-lifecycle payments. */
|
|
24
24
|
export declare const GRANT_OP_TYPE: "grant";
|
|
@@ -71,7 +71,7 @@ export interface EscrowPaymentHeaderConfig {
|
|
|
71
71
|
*/
|
|
72
72
|
export interface EscrowPaymentConfig extends EscrowPaymentHeaderConfig {
|
|
73
73
|
/** Client for the gateway escrow endpoints (`/v1/escrow/*`). */
|
|
74
|
-
client:
|
|
74
|
+
client: EscrowPaymentClient;
|
|
75
75
|
}
|
|
76
76
|
/** Map the gateway {@link PaymentBreakdown} into the public {@link DirectFeeBreakdown}. */
|
|
77
77
|
export declare function toDirectFeeBreakdown(breakdown: PaymentBreakdown): DirectFeeBreakdown;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/direct/escrow-payment.ts"],"sourcesContent":["/**\n * Escrow-backed payment authorization for the Direct Data Controller.\n *\n * @remarks\n * Builds on the DPv2 escrow surface added in `protocol/escrow`. When a Personal\n * Server read returns `402 Payment Required`, the controller settles the\n * challenged operation through the escrow gateway:\n *\n * 1. Sign the challenge's `GenericPayment` EIP-712 message with the app key.\n * 2. POST it to the gateway's `/v1/escrow/pay` via {@link EscrowGatewayClient}.\n * 3. Map the gateway's {@link EscrowPayResult} into a typed\n * {@link DirectPaymentReceipt} for the caller to inspect.\n *\n * This module supports legacy `\"grant\"` operations and receipt-bound\n * `\"data_access\"` operations. It adapts the escrow `payForOp` flow to the\n * direct-read use case; it does not define its own payment scheme.\n *\n * @category Direct\n * @module direct/escrow-payment\n */\n\nimport {\n GENERIC_PAYMENT_TYPES,\n NATIVE_ASSET_ADDRESS,\n genericPaymentDomain,\n type EscrowAccessRecord,\n type EscrowGatewayClient,\n type EscrowPayResult,\n type PaymentBreakdown,\n} from \"../protocol/escrow\";\nimport type {\n DirectFeeBreakdown,\n DirectPaymentReceipt,\n DirectPaymentResponseMetadata,\n PersonalServerPaymentOperation,\n PersonalServerPaymentRequired,\n} from \"./types\";\n\n/** The escrow `GenericPayment.opType` used for grant-lifecycle payments. */\nexport const GRANT_OP_TYPE = \"grant\" as const;\n/** The escrow `GenericPayment.opType` used for receipt-bound data access. */\nexport const DATA_ACCESS_OP_TYPE = \"data_access\" as const;\n\n/**\n * EIP-712 typed-data signer (e.g. viem `account.signTypedData`).\n *\n * @remarks\n * Kept structurally minimal so any viem account/wallet client satisfies it\n * without the SDK depending on viem's exact `signTypedData` overload set.\n */\nexport type SignTypedDataFn = (args: {\n domain: ReturnType<typeof genericPaymentDomain>;\n types: typeof GENERIC_PAYMENT_TYPES;\n primaryType: \"GenericPayment\";\n message: {\n payerAddress: `0x${string}`;\n opType: string;\n opId: `0x${string}`;\n asset: `0x${string}`;\n amount: bigint;\n paymentNonce: bigint;\n };\n}) => Promise<`0x${string}`>;\n\n/** Supplies a monotonically-increasing payment nonce per payer. */\nexport type PaymentNonceSource = (\n payerAddress: string,\n) => Promise<bigint> | bigint;\n\ninterface EscrowPaymentMessage {\n payerAddress: `0x${string}`;\n opType: typeof GRANT_OP_TYPE | typeof DATA_ACCESS_OP_TYPE;\n opId: `0x${string}`;\n asset: `0x${string}`;\n amount: string;\n paymentNonce: string;\n}\n\ninterface SignedEscrowPayment {\n message: EscrowPaymentMessage;\n signature: `0x${string}`;\n accessRecord?: EscrowAccessRecord;\n}\n\ninterface X402PaymentHeader {\n x402Version: 1;\n scheme: \"vana-escrow-grant\";\n network: string;\n payload: SignedEscrowPayment;\n}\n\n/** Configuration required to sign an escrow X-PAYMENT header. */\nexport interface EscrowPaymentHeaderConfig {\n /** Deployed `DataPortabilityEscrow` contract address. */\n escrowContract: `0x${string}`;\n /** Chain id for the EIP-712 domain (1480 mainnet, 14800 moksha). */\n chainId: number;\n /** App EIP-712 signer. */\n signTypedData: SignTypedDataFn;\n /**\n * Supplies the next payment nonce for a payer. Defaults to a process-local\n * monotonic counter seeded at 1. Provide a durable source in production so\n * nonces survive restarts (the gateway rejects reused (payer, nonce) pairs).\n */\n nonceSource?: PaymentNonceSource;\n}\n\n/**\n * Escrow settlement configuration for gateway authorization.\n *\n * @remarks\n * Extends the header-signing boundary with the gateway client used by\n * {@link authorizeEscrowPayment}. Existing controller and legacy wrapper\n * callers can continue to provide this full configuration.\n */\nexport interface EscrowPaymentConfig extends EscrowPaymentHeaderConfig {\n /** Client for the gateway escrow endpoints (`/v1/escrow/*`). */\n client: EscrowGatewayClient;\n}\n\n/** Map the gateway {@link PaymentBreakdown} into the public {@link DirectFeeBreakdown}. */\nexport function toDirectFeeBreakdown(\n breakdown: PaymentBreakdown,\n): DirectFeeBreakdown {\n return {\n registrationFee: breakdown.registrationFee,\n dataAccessFee: breakdown.dataAccessFee,\n registrationPaid: breakdown.registrationPaid,\n };\n}\n\n/** Map a gateway {@link EscrowPayResult} into the public {@link DirectPaymentReceipt}. */\nexport function toDirectPaymentReceipt(\n result: EscrowPayResult,\n): DirectPaymentReceipt {\n return {\n opType: result.opType,\n opId: result.opId,\n asset: result.asset,\n amount: result.amount,\n paymentNonce: result.paymentNonce,\n breakdown: toDirectFeeBreakdown(result.breakdown),\n paidAt: result.paidAt,\n };\n}\n\n/** Default in-process monotonic nonce counter (seeded at 1 per payer). */\nexport function createDefaultNonceSource(): PaymentNonceSource {\n const counters = new Map<string, bigint>();\n return (payerAddress: string): bigint => {\n const key = payerAddress.toLowerCase();\n const next = (counters.get(key) ?? 0n) + 1n;\n counters.set(key, next);\n return next;\n };\n}\n\nconst processLocalNonceSource = createDefaultNonceSource();\nconst UINT256_MAX = (1n << 256n) - 1n;\nconst ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;\nconst BYTES32_RE = /^0x[0-9a-fA-F]{64}$/;\nconst SIGNATURE_RE = /^0x[0-9a-fA-F]{130}$/;\n\nfunction isUint256Decimal(value: string, allowZero: boolean): boolean {\n const pattern = allowZero ? /^(0|[1-9]\\d*)$/ : /^[1-9]\\d*$/;\n return (\n value.length <= UINT256_MAX.toString().length &&\n pattern.test(value) &&\n BigInt(value) <= UINT256_MAX\n );\n}\n\nfunction isValidAccessRecord(record: EscrowAccessRecord): boolean {\n return (\n BYTES32_RE.test(record.dataPointId) &&\n isUint256Decimal(record.version, false) &&\n ADDRESS_RE.test(record.accessor) &&\n BYTES32_RE.test(record.recordId) &&\n SIGNATURE_RE.test(record.signature)\n );\n}\n\nfunction validateSigningOperation(\n payerAddress: `0x${string}`,\n required: PersonalServerPaymentOperation,\n): void {\n if (!ADDRESS_RE.test(payerAddress)) {\n throw new Error(\"Payment payer must be a 20-byte EVM address\");\n }\n if (!BYTES32_RE.test(required.opId)) {\n throw new Error(\"Payment operation id must be a 32-byte hex value\");\n }\n if (!ADDRESS_RE.test(required.asset || NATIVE_ASSET_ADDRESS)) {\n throw new Error(\"Payment asset must be a 20-byte EVM address\");\n }\n if (!isUint256Decimal(required.amount, true)) {\n throw new Error(\"Payment amount must be a canonical uint256 decimal\");\n }\n if (\n required.paymentNonce !== undefined &&\n !isUint256Decimal(required.paymentNonce, false)\n ) {\n throw new Error(\"Payment nonce must be a positive uint256 decimal\");\n }\n\n const accessRecord = required.accessRecord;\n if (required.opType === DATA_ACCESS_OP_TYPE) {\n if (!accessRecord || !isValidAccessRecord(accessRecord)) {\n throw new Error(\"Data-access payment requires a valid access record\");\n }\n if (required.opId.toLowerCase() !== accessRecord.recordId.toLowerCase()) {\n throw new Error(\n \"Data-access payment operation id must equal the access record id\",\n );\n }\n if (accessRecord.accessor.toLowerCase() !== payerAddress.toLowerCase()) {\n throw new Error(\n \"Data-access payment accessor must equal the payment payer address\",\n );\n }\n return;\n }\n\n if (required.amount === \"0\") {\n if (\n !accessRecord ||\n !isValidAccessRecord(accessRecord) ||\n accessRecord.accessor.toLowerCase() !== payerAddress.toLowerCase()\n ) {\n throw new Error(\n \"Zero-amount grant payments require a valid access record for the payer\",\n );\n }\n }\n}\n\nfunction base64EncodeJson(value: unknown): string {\n const bytes = new TextEncoder().encode(JSON.stringify(value));\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction base64DecodeJson(value: string): unknown {\n const binary = atob(value);\n const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));\n return JSON.parse(new TextDecoder().decode(bytes));\n}\n\nasync function signEscrowPayment(params: {\n payerAddress: `0x${string}`;\n required: PersonalServerPaymentOperation;\n config: EscrowPaymentHeaderConfig;\n}): Promise<SignedEscrowPayment> {\n const { payerAddress, required, config } = params;\n validateSigningOperation(payerAddress, required);\n const nonceSource = config.nonceSource ?? processLocalNonceSource;\n const paymentNonce = BigInt(\n required.paymentNonce ?? (await nonceSource(payerAddress)),\n );\n const asset = (required.asset || NATIVE_ASSET_ADDRESS) as `0x${string}`;\n const opId = required.opId as `0x${string}`;\n const amount = BigInt(required.amount);\n if (amount < 0n || amount > UINT256_MAX) {\n throw new Error(\"Payment amount must be a uint256\");\n }\n if (paymentNonce <= 0n || paymentNonce > UINT256_MAX) {\n throw new Error(\"Payment nonce must be a positive uint256\");\n }\n\n const message = {\n payerAddress,\n opType: required.opType,\n opId,\n asset,\n amount,\n paymentNonce,\n };\n\n const signature = await config.signTypedData({\n domain: genericPaymentDomain(config.chainId, config.escrowContract),\n types: GENERIC_PAYMENT_TYPES,\n primaryType: \"GenericPayment\",\n message,\n });\n\n return {\n message: {\n ...message,\n amount: amount.toString(),\n paymentNonce: paymentNonce.toString(),\n },\n signature,\n ...(required.accessRecord ? { accessRecord: required.accessRecord } : {}),\n };\n}\n\n/**\n * Build the canonical X-PAYMENT header for a validated escrow operation.\n *\n * @remarks\n * Supports both legacy grant payments and receipt-bound data-access payments.\n * Signing is injected through {@link EscrowPaymentHeaderConfig.signTypedData}.\n */\nexport async function buildEscrowPaymentHeader(params: {\n /** Address whose escrow balance pays for the operation. */\n payerAddress: `0x${string}`;\n /** Validated operation parsed from the Personal Server challenge. */\n required: PersonalServerPaymentOperation;\n /** Escrow contract, chain, signer, and nonce configuration. */\n config: EscrowPaymentHeaderConfig;\n}): Promise<string> {\n const network = params.required.network ?? `vana:${params.config.chainId}`;\n if (network !== `vana:${params.config.chainId}`) {\n throw new Error(\"Payment network must match the configured chain\");\n }\n\n const signed = await signEscrowPayment(params);\n const payment: X402PaymentHeader = {\n x402Version: 1,\n scheme: \"vana-escrow-grant\",\n network,\n payload: signed,\n };\n return base64EncodeJson(payment);\n}\n\n/** Build a legacy grant X-PAYMENT header. */\nexport async function buildGrantPaymentHeader(params: {\n payerAddress: `0x${string}`;\n required: PersonalServerPaymentRequired;\n config: EscrowPaymentConfig;\n}): Promise<string> {\n return buildEscrowPaymentHeader({\n ...params,\n required: {\n ...params.required,\n opType: GRANT_OP_TYPE,\n opId: params.required.grantId,\n },\n });\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nfunction stringField(\n value: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n const field = value?.[key];\n return typeof field === \"string\" ? field : undefined;\n}\n\nfunction isCanonicalIsoTimestamp(value: string): boolean {\n try {\n return new Date(value).toISOString() === value;\n } catch {\n return false;\n }\n}\n\n/**\n * Parse shape-validated payment response metadata echoed by a Personal Server.\n *\n * @remarks\n * This metadata is not authenticated by the gateway. It is suitable for\n * display and debugging, not as proof that a payment occurred.\n */\nexport function paymentResponseMetadataFromHeader(\n header: string | null | undefined,\n): DirectPaymentResponseMetadata | undefined {\n if (!header) return undefined;\n try {\n const result = asRecord(base64DecodeJson(header));\n const breakdown = asRecord(result?.breakdown);\n const opType = stringField(result, \"opType\");\n const opId = stringField(result, \"opId\");\n const payerAddress = stringField(result, \"payerAddress\");\n const asset = stringField(result, \"asset\");\n const amount = stringField(result, \"amount\");\n const paymentNonce = stringField(result, \"paymentNonce\");\n const registrationFee = stringField(breakdown, \"registrationFee\");\n const dataAccessFee = stringField(breakdown, \"dataAccessFee\");\n const paidAt = stringField(result, \"paidAt\");\n if (\n result?.success !== true ||\n !opType ||\n !opId ||\n !BYTES32_RE.test(opId) ||\n !payerAddress ||\n !ADDRESS_RE.test(payerAddress) ||\n !asset ||\n !ADDRESS_RE.test(asset) ||\n !amount ||\n !isUint256Decimal(amount, true) ||\n !paymentNonce ||\n !isUint256Decimal(paymentNonce, false) ||\n !registrationFee ||\n !isUint256Decimal(registrationFee, true) ||\n !dataAccessFee ||\n !isUint256Decimal(dataAccessFee, true) ||\n typeof breakdown?.registrationPaid !== \"boolean\" ||\n !paidAt ||\n !isCanonicalIsoTimestamp(paidAt)\n ) {\n return undefined;\n }\n return {\n opType,\n opId,\n asset,\n amount,\n paymentNonce,\n breakdown: {\n registrationFee,\n dataAccessFee,\n registrationPaid: breakdown.registrationPaid,\n },\n paidAt,\n };\n } catch {\n return undefined;\n }\n}\n\n/**\n * @deprecated Use {@link paymentResponseMetadataFromHeader}. A Personal\n * Server response header is untrusted metadata, not a gateway-authenticated\n * receipt.\n */\nexport function paymentReceiptFromHeader(\n header: string | null | undefined,\n): DirectPaymentResponseMetadata | undefined {\n return paymentResponseMetadataFromHeader(header);\n}\n\n/**\n * Authorize an escrow payment for a grant data-access fee.\n *\n * @param params - The payment requirement, the payer address, and escrow config.\n * @returns The gateway's {@link EscrowPayResult} as a typed\n * {@link DirectPaymentReceipt}.\n */\nexport async function authorizeGrantPayment(params: {\n payerAddress: `0x${string}`;\n required: PersonalServerPaymentRequired;\n config: EscrowPaymentConfig;\n}): Promise<DirectPaymentReceipt> {\n return authorizeEscrowPayment({\n ...params,\n required: {\n ...params.required,\n opType: GRANT_OP_TYPE,\n opId: params.required.grantId,\n },\n });\n}\n\n/**\n * Authorize a validated grant or data-access operation through the escrow\n * gateway.\n */\nexport async function authorizeEscrowPayment(params: {\n /** Address whose escrow balance pays for the operation. */\n payerAddress: `0x${string}`;\n /** Validated operation to authorize. */\n required: PersonalServerPaymentOperation;\n /** Escrow gateway and signing configuration. */\n config: EscrowPaymentConfig;\n}): Promise<DirectPaymentReceipt> {\n const { payerAddress, config } = params;\n const signed = await signEscrowPayment(params);\n\n const result = await config.client.payForOp({\n payerAddress,\n opType: signed.message.opType,\n opId: signed.message.opId,\n asset: signed.message.asset,\n amount: signed.message.amount,\n paymentNonce: signed.message.paymentNonce,\n signature: signed.signature,\n accessRecord: signed.accessRecord,\n });\n\n return toDirectPaymentReceipt(result);\n}\n"],"mappings":"AAqBA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAKK;AAUA,MAAM,gBAAgB;AAEtB,MAAM,sBAAsB;AAgF5B,SAAS,qBACd,WACoB;AACpB,SAAO;AAAA,IACL,iBAAiB,UAAU;AAAA,IAC3B,eAAe,UAAU;AAAA,IACzB,kBAAkB,UAAU;AAAA,EAC9B;AACF;AAGO,SAAS,uBACd,QACsB;AACtB,SAAO;AAAA,IACL,QAAQ,OAAO;AAAA,IACf,MAAM,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AiB,IAAI,KACvC,CAAC,iBACD,CAAC,iBAAiB,eAAe,IAAI,KACrC,OAAO,WAAW,qBAAqB,aACvC,CAAC,UACD,CAAC,wBAAwB,MAAM,GAC/B;AACA,aAAO;AAAA,IACT;AACA,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,WAAW;AAAA,QACT;AAAA,QACA;AAAA,QACA,kBAAkB,UAAU;AAAA,MAC9B;AAAA,MACA;AAAA,IACF;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAOO,SAAS,yBACd,QAC2C;AAC3C,SAAO,kCAAkC,MAAM;AACjD;AASA,eAAsB,sBAAsB,QAIV;AAChC,SAAO,uBAAuB;AAAA,IAC5B,GAAG;AAAA,IACH,UAAU;AAAA,MACR,GAAG,OAAO;AAAA,MACV,QAAQ;AAAA,MACR,MAAM,OAAO,SAAS;AAAA,IACxB;AAAA,EACF,CAAC;AACH;AAMA,eAAsB,uBAAuB,QAOX;AAChC,QAAM,EAAE,cAAc,OAAO,IAAI;AACjC,QAAM,SAAS,MAAM,kBAAkB,MAAM;AAE7C,QAAM,SAAS,MAAM,OAAO,OAAO,SAAS;AAAA,IAC1C;AAAA,IACA,QAAQ,OAAO,QAAQ;AAAA,IACvB,MAAM,OAAO,QAAQ;AAAA,IACrB,OAAO,OAAO,QAAQ;AAAA,IACtB,QAAQ,OAAO,QAAQ;AAAA,IACvB,cAAc,OAAO,QAAQ;AAAA,IAC7B,WAAW,OAAO;AAAA,IAClB,cAAc,OAAO;AAAA,EACvB,CAAC;AAED,SAAO,uBAAuB,MAAM;AACtC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/direct/escrow-payment.ts"],"sourcesContent":["/**\n * Escrow-backed payment authorization for the Direct Data Controller.\n *\n * @remarks\n * Builds on the DPv2 escrow surface added in `protocol/escrow`. When a Personal\n * Server read returns `402 Payment Required`, the controller settles the\n * challenged operation through the escrow gateway:\n *\n * 1. Sign the challenge's `GenericPayment` EIP-712 message with the app key.\n * 2. POST it to the gateway's `/v1/escrow/pay` via {@link EscrowGatewayClient}.\n * 3. Map the gateway's {@link EscrowPayResult} into a typed\n * {@link DirectPaymentReceipt} for the caller to inspect.\n *\n * This module supports legacy `\"grant\"` operations and receipt-bound\n * `\"data_access\"` operations. It adapts the escrow `payForOp` flow to the\n * direct-read use case; it does not define its own payment scheme.\n *\n * @category Direct\n * @module direct/escrow-payment\n */\n\nimport {\n GENERIC_PAYMENT_TYPES,\n NATIVE_ASSET_ADDRESS,\n genericPaymentDomain,\n type EscrowAccessRecord,\n type EscrowPaymentClient,\n type EscrowPayResult,\n type PaymentBreakdown,\n} from \"../protocol/escrow\";\nimport type {\n DirectFeeBreakdown,\n DirectPaymentReceipt,\n DirectPaymentResponseMetadata,\n PersonalServerPaymentOperation,\n PersonalServerPaymentRequired,\n} from \"./types\";\n\n/** The escrow `GenericPayment.opType` used for grant-lifecycle payments. */\nexport const GRANT_OP_TYPE = \"grant\" as const;\n/** The escrow `GenericPayment.opType` used for receipt-bound data access. */\nexport const DATA_ACCESS_OP_TYPE = \"data_access\" as const;\n\n/**\n * EIP-712 typed-data signer (e.g. viem `account.signTypedData`).\n *\n * @remarks\n * Kept structurally minimal so any viem account/wallet client satisfies it\n * without the SDK depending on viem's exact `signTypedData` overload set.\n */\nexport type SignTypedDataFn = (args: {\n domain: ReturnType<typeof genericPaymentDomain>;\n types: typeof GENERIC_PAYMENT_TYPES;\n primaryType: \"GenericPayment\";\n message: {\n payerAddress: `0x${string}`;\n opType: string;\n opId: `0x${string}`;\n asset: `0x${string}`;\n amount: bigint;\n paymentNonce: bigint;\n };\n}) => Promise<`0x${string}`>;\n\n/** Supplies a monotonically-increasing payment nonce per payer. */\nexport type PaymentNonceSource = (\n payerAddress: string,\n) => Promise<bigint> | bigint;\n\ninterface EscrowPaymentMessage {\n payerAddress: `0x${string}`;\n opType: typeof GRANT_OP_TYPE | typeof DATA_ACCESS_OP_TYPE;\n opId: `0x${string}`;\n asset: `0x${string}`;\n amount: string;\n paymentNonce: string;\n}\n\ninterface SignedEscrowPayment {\n message: EscrowPaymentMessage;\n signature: `0x${string}`;\n accessRecord?: EscrowAccessRecord;\n}\n\ninterface X402PaymentHeader {\n x402Version: 1;\n scheme: \"vana-escrow-grant\";\n network: string;\n payload: SignedEscrowPayment;\n}\n\n/** Configuration required to sign an escrow X-PAYMENT header. */\nexport interface EscrowPaymentHeaderConfig {\n /** Deployed `DataPortabilityEscrow` contract address. */\n escrowContract: `0x${string}`;\n /** Chain id for the EIP-712 domain (1480 mainnet, 14800 moksha). */\n chainId: number;\n /** App EIP-712 signer. */\n signTypedData: SignTypedDataFn;\n /**\n * Supplies the next payment nonce for a payer. Defaults to a process-local\n * monotonic counter seeded at 1. Provide a durable source in production so\n * nonces survive restarts (the gateway rejects reused (payer, nonce) pairs).\n */\n nonceSource?: PaymentNonceSource;\n}\n\n/**\n * Escrow settlement configuration for gateway authorization.\n *\n * @remarks\n * Extends the header-signing boundary with the gateway client used by\n * {@link authorizeEscrowPayment}. Existing controller and legacy wrapper\n * callers can continue to provide this full configuration.\n */\nexport interface EscrowPaymentConfig extends EscrowPaymentHeaderConfig {\n /** Client for the gateway escrow endpoints (`/v1/escrow/*`). */\n client: EscrowPaymentClient;\n}\n\n/** Map the gateway {@link PaymentBreakdown} into the public {@link DirectFeeBreakdown}. */\nexport function toDirectFeeBreakdown(\n breakdown: PaymentBreakdown,\n): DirectFeeBreakdown {\n return {\n registrationFee: breakdown.registrationFee,\n dataAccessFee: breakdown.dataAccessFee,\n registrationPaid: breakdown.registrationPaid,\n };\n}\n\n/** Map a gateway {@link EscrowPayResult} into the public {@link DirectPaymentReceipt}. */\nexport function toDirectPaymentReceipt(\n result: EscrowPayResult,\n): DirectPaymentReceipt {\n return {\n opType: result.opType,\n opId: result.opId,\n asset: result.asset,\n amount: result.amount,\n paymentNonce: result.paymentNonce,\n breakdown: toDirectFeeBreakdown(result.breakdown),\n paidAt: result.paidAt,\n };\n}\n\n/** Default in-process monotonic nonce counter (seeded at 1 per payer). */\nexport function createDefaultNonceSource(): PaymentNonceSource {\n const counters = new Map<string, bigint>();\n return (payerAddress: string): bigint => {\n const key = payerAddress.toLowerCase();\n const next = (counters.get(key) ?? 0n) + 1n;\n counters.set(key, next);\n return next;\n };\n}\n\nconst processLocalNonceSource = createDefaultNonceSource();\nconst UINT256_MAX = (1n << 256n) - 1n;\nconst ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;\nconst BYTES32_RE = /^0x[0-9a-fA-F]{64}$/;\nconst SIGNATURE_RE = /^0x[0-9a-fA-F]{130}$/;\n\nfunction isUint256Decimal(value: string, allowZero: boolean): boolean {\n const pattern = allowZero ? /^(0|[1-9]\\d*)$/ : /^[1-9]\\d*$/;\n return (\n value.length <= UINT256_MAX.toString().length &&\n pattern.test(value) &&\n BigInt(value) <= UINT256_MAX\n );\n}\n\nfunction isValidAccessRecord(record: EscrowAccessRecord): boolean {\n return (\n BYTES32_RE.test(record.dataPointId) &&\n isUint256Decimal(record.version, false) &&\n ADDRESS_RE.test(record.accessor) &&\n BYTES32_RE.test(record.recordId) &&\n SIGNATURE_RE.test(record.signature)\n );\n}\n\nfunction validateSigningOperation(\n payerAddress: `0x${string}`,\n required: PersonalServerPaymentOperation,\n): void {\n if (!ADDRESS_RE.test(payerAddress)) {\n throw new Error(\"Payment payer must be a 20-byte EVM address\");\n }\n if (!BYTES32_RE.test(required.opId)) {\n throw new Error(\"Payment operation id must be a 32-byte hex value\");\n }\n if (!ADDRESS_RE.test(required.asset || NATIVE_ASSET_ADDRESS)) {\n throw new Error(\"Payment asset must be a 20-byte EVM address\");\n }\n if (!isUint256Decimal(required.amount, true)) {\n throw new Error(\"Payment amount must be a canonical uint256 decimal\");\n }\n if (\n required.paymentNonce !== undefined &&\n !isUint256Decimal(required.paymentNonce, false)\n ) {\n throw new Error(\"Payment nonce must be a positive uint256 decimal\");\n }\n\n const accessRecord = required.accessRecord;\n if (required.opType === DATA_ACCESS_OP_TYPE) {\n if (!accessRecord || !isValidAccessRecord(accessRecord)) {\n throw new Error(\"Data-access payment requires a valid access record\");\n }\n if (required.opId.toLowerCase() !== accessRecord.recordId.toLowerCase()) {\n throw new Error(\n \"Data-access payment operation id must equal the access record id\",\n );\n }\n if (accessRecord.accessor.toLowerCase() !== payerAddress.toLowerCase()) {\n throw new Error(\n \"Data-access payment accessor must equal the payment payer address\",\n );\n }\n return;\n }\n\n if (required.amount === \"0\") {\n if (\n !accessRecord ||\n !isValidAccessRecord(accessRecord) ||\n accessRecord.accessor.toLowerCase() !== payerAddress.toLowerCase()\n ) {\n throw new Error(\n \"Zero-amount grant payments require a valid access record for the payer\",\n );\n }\n }\n}\n\nfunction base64EncodeJson(value: unknown): string {\n const bytes = new TextEncoder().encode(JSON.stringify(value));\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\nfunction base64DecodeJson(value: string): unknown {\n const binary = atob(value);\n const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));\n return JSON.parse(new TextDecoder().decode(bytes));\n}\n\nasync function signEscrowPayment(params: {\n payerAddress: `0x${string}`;\n required: PersonalServerPaymentOperation;\n config: EscrowPaymentHeaderConfig;\n}): Promise<SignedEscrowPayment> {\n const { payerAddress, required, config } = params;\n validateSigningOperation(payerAddress, required);\n const nonceSource = config.nonceSource ?? processLocalNonceSource;\n const paymentNonce = BigInt(\n required.paymentNonce ?? (await nonceSource(payerAddress)),\n );\n const asset = (required.asset || NATIVE_ASSET_ADDRESS) as `0x${string}`;\n const opId = required.opId as `0x${string}`;\n const amount = BigInt(required.amount);\n if (amount < 0n || amount > UINT256_MAX) {\n throw new Error(\"Payment amount must be a uint256\");\n }\n if (paymentNonce <= 0n || paymentNonce > UINT256_MAX) {\n throw new Error(\"Payment nonce must be a positive uint256\");\n }\n\n const message = {\n payerAddress,\n opType: required.opType,\n opId,\n asset,\n amount,\n paymentNonce,\n };\n\n const signature = await config.signTypedData({\n domain: genericPaymentDomain(config.chainId, config.escrowContract),\n types: GENERIC_PAYMENT_TYPES,\n primaryType: \"GenericPayment\",\n message,\n });\n\n return {\n message: {\n ...message,\n amount: amount.toString(),\n paymentNonce: paymentNonce.toString(),\n },\n signature,\n ...(required.accessRecord ? { accessRecord: required.accessRecord } : {}),\n };\n}\n\n/**\n * Build the canonical X-PAYMENT header for a validated escrow operation.\n *\n * @remarks\n * Supports both legacy grant payments and receipt-bound data-access payments.\n * Signing is injected through {@link EscrowPaymentHeaderConfig.signTypedData}.\n */\nexport async function buildEscrowPaymentHeader(params: {\n /** Address whose escrow balance pays for the operation. */\n payerAddress: `0x${string}`;\n /** Validated operation parsed from the Personal Server challenge. */\n required: PersonalServerPaymentOperation;\n /** Escrow contract, chain, signer, and nonce configuration. */\n config: EscrowPaymentHeaderConfig;\n}): Promise<string> {\n const network = params.required.network ?? `vana:${params.config.chainId}`;\n if (network !== `vana:${params.config.chainId}`) {\n throw new Error(\"Payment network must match the configured chain\");\n }\n\n const signed = await signEscrowPayment(params);\n const payment: X402PaymentHeader = {\n x402Version: 1,\n scheme: \"vana-escrow-grant\",\n network,\n payload: signed,\n };\n return base64EncodeJson(payment);\n}\n\n/** Build a legacy grant X-PAYMENT header. */\nexport async function buildGrantPaymentHeader(params: {\n payerAddress: `0x${string}`;\n required: PersonalServerPaymentRequired;\n config: EscrowPaymentConfig;\n}): Promise<string> {\n return buildEscrowPaymentHeader({\n ...params,\n required: {\n ...params.required,\n opType: GRANT_OP_TYPE,\n opId: params.required.grantId,\n },\n });\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nfunction stringField(\n value: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n const field = value?.[key];\n return typeof field === \"string\" ? field : undefined;\n}\n\nfunction isCanonicalIsoTimestamp(value: string): boolean {\n try {\n return new Date(value).toISOString() === value;\n } catch {\n return false;\n }\n}\n\n/**\n * Parse shape-validated payment response metadata echoed by a Personal Server.\n *\n * @remarks\n * This metadata is not authenticated by the gateway. It is suitable for\n * display and debugging, not as proof that a payment occurred.\n */\nexport function paymentResponseMetadataFromHeader(\n header: string | null | undefined,\n): DirectPaymentResponseMetadata | undefined {\n if (!header) return undefined;\n try {\n const result = asRecord(base64DecodeJson(header));\n const breakdown = asRecord(result?.breakdown);\n const opType = stringField(result, \"opType\");\n const opId = stringField(result, \"opId\");\n const payerAddress = stringField(result, \"payerAddress\");\n const asset = stringField(result, \"asset\");\n const amount = stringField(result, \"amount\");\n const paymentNonce = stringField(result, \"paymentNonce\");\n const registrationFee = stringField(breakdown, \"registrationFee\");\n const dataAccessFee = stringField(breakdown, \"dataAccessFee\");\n const paidAt = stringField(result, \"paidAt\");\n if (\n result?.success !== true ||\n !opType ||\n !opId ||\n !BYTES32_RE.test(opId) ||\n !payerAddress ||\n !ADDRESS_RE.test(payerAddress) ||\n !asset ||\n !ADDRESS_RE.test(asset) ||\n !amount ||\n !isUint256Decimal(amount, true) ||\n !paymentNonce ||\n !isUint256Decimal(paymentNonce, false) ||\n !registrationFee ||\n !isUint256Decimal(registrationFee, true) ||\n !dataAccessFee ||\n !isUint256Decimal(dataAccessFee, true) ||\n typeof breakdown?.registrationPaid !== \"boolean\" ||\n !paidAt ||\n !isCanonicalIsoTimestamp(paidAt)\n ) {\n return undefined;\n }\n return {\n opType,\n opId,\n asset,\n amount,\n paymentNonce,\n breakdown: {\n registrationFee,\n dataAccessFee,\n registrationPaid: breakdown.registrationPaid,\n },\n paidAt,\n };\n } catch {\n return undefined;\n }\n}\n\n/**\n * @deprecated Use {@link paymentResponseMetadataFromHeader}. A Personal\n * Server response header is untrusted metadata, not a gateway-authenticated\n * receipt.\n */\nexport function paymentReceiptFromHeader(\n header: string | null | undefined,\n): DirectPaymentResponseMetadata | undefined {\n return paymentResponseMetadataFromHeader(header);\n}\n\n/**\n * Authorize an escrow payment for a grant data-access fee.\n *\n * @param params - The payment requirement, the payer address, and escrow config.\n * @returns The gateway's {@link EscrowPayResult} as a typed\n * {@link DirectPaymentReceipt}.\n */\nexport async function authorizeGrantPayment(params: {\n payerAddress: `0x${string}`;\n required: PersonalServerPaymentRequired;\n config: EscrowPaymentConfig;\n}): Promise<DirectPaymentReceipt> {\n return authorizeEscrowPayment({\n ...params,\n required: {\n ...params.required,\n opType: GRANT_OP_TYPE,\n opId: params.required.grantId,\n },\n });\n}\n\n/**\n * Authorize a validated grant or data-access operation through the escrow\n * gateway.\n */\nexport async function authorizeEscrowPayment(params: {\n /** Address whose escrow balance pays for the operation. */\n payerAddress: `0x${string}`;\n /** Validated operation to authorize. */\n required: PersonalServerPaymentOperation;\n /** Escrow gateway and signing configuration. */\n config: EscrowPaymentConfig;\n}): Promise<DirectPaymentReceipt> {\n const { payerAddress, config } = params;\n const signed = await signEscrowPayment(params);\n\n const result = await config.client.payForOp({\n payerAddress,\n opType: signed.message.opType,\n opId: signed.message.opId,\n asset: signed.message.asset,\n amount: signed.message.amount,\n paymentNonce: signed.message.paymentNonce,\n signature: signed.signature,\n accessRecord: signed.accessRecord,\n });\n\n return toDirectPaymentReceipt(result);\n}\n"],"mappings":"AAqBA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAKK;AAUA,MAAM,gBAAgB;AAEtB,MAAM,sBAAsB;AAgF5B,SAAS,qBACd,WACoB;AACpB,SAAO;AAAA,IACL,iBAAiB,UAAU;AAAA,IAC3B,eAAe,UAAU;AAAA,IACzB,kBAAkB,UAAU;AAAA,EAC9B;AACF;AAGO,SAAS,uBACd,QACsB;AACtB,SAAO;AAAA,IACL,QAAQ,OAAO;AAAA,IACf,MAAM,OAAO;AAAA,IACb,OAAO,OAAO;AAAA,IACd,QAAQ,OAAO;AAAA,IACf,cAAc,OAAO;AAAA,IACrB,WAAW,qBAAqB,OAAO,SAAS;AAAA,IAChD,QAAQ,OAAO;AAAA,EACjB;AACF;AAGO,SAAS,2BAA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A,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,WAAW;AAAA,QACT;AAAA,QACA;AAAA,QACA,kBAAkB,UAAU;AAAA,MAC9B;AAAA,MACA;AAAA,IACF;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAOO,SAAS,yBACd,QAC2C;AAC3C,SAAO,kCAAkC,MAAM;AACjD;AASA,eAAsB,sBAAsB,QAIV;AAChC,SAAO,uBAAuB;AAAA,IAC5B,GAAG;AAAA,IACH,UAAU;AAAA,MACR,GAAG,OAAO;AAAA,MACV,QAAQ;AAAA,MACR,MAAM,OAAO,SAAS;AAAA,IACxB;AAAA,EACF,CAAC;AACH;AAMA,eAAsB,uBAAuB,QAOX;AAChC,QAAM,EAAE,cAAc,OAAO,IAAI;AACjC,QAAM,SAAS,MAAM,kBAAkB,MAAM;AAE7C,QAAM,SAAS,MAAM,OAAO,OAAO,SAAS;AAAA,IAC1C;AAAA,IACA,QAAQ,OAAO,QAAQ;AAAA,IACvB,MAAM,OAAO,QAAQ;AAAA,IACrB,OAAO,OAAO,QAAQ;AAAA,IACtB,QAAQ,OAAO,QAAQ;AAAA,IACvB,cAAc,OAAO,QAAQ;AAAA,IAC7B,WAAW,OAAO;AAAA,IAClB,cAAc,OAAO;AAAA,EACvB,CAAC;AAED,SAAO,uBAAuB,MAAM;AACtC;","names":[]}
|
|
@@ -27,8 +27,8 @@ module.exports = __toCommonJS(personal_server_read_exports);
|
|
|
27
27
|
var import_web3_signed_builder = require("../auth/web3-signed-builder");
|
|
28
28
|
var import_escrow = require("../protocol/escrow");
|
|
29
29
|
var import_escrow_payment = require("./escrow-payment");
|
|
30
|
-
var import_errors = require("./errors");
|
|
31
|
-
var import_errors2 = require("../errors");
|
|
30
|
+
var import_errors = require("./errors.cjs");
|
|
31
|
+
var import_errors2 = require("../errors.cjs");
|
|
32
32
|
var import_data_point_deletion = require("../protocol/data-point-deletion");
|
|
33
33
|
var import_response_body = require("../utils/response-body");
|
|
34
34
|
const TRANSPORT_RETRY_DEFAULTS = {
|
|
@@ -62,7 +62,8 @@ function useDirectVanaConnect(options) {
|
|
|
62
62
|
const reset = (0, import_react.useCallback)(() => {
|
|
63
63
|
flow.reset();
|
|
64
64
|
}, [flow]);
|
|
65
|
-
|
|
65
|
+
const retryRead = (0, import_react.useCallback)(() => flow.retryRead(), [flow]);
|
|
66
|
+
return { state, start, retryRead, reset };
|
|
66
67
|
}
|
|
67
68
|
// Annotate the CommonJS export names for ESM import in node:
|
|
68
69
|
0 && (module.exports = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/direct/use-direct-vana-connect.ts"],"sourcesContent":["/**\n * React hook for the browser side of the direct Data Portability flow.\n *\n * @remarks\n * `useDirectVanaConnect` is a thin `useSyncExternalStore` binding over the\n * framework-agnostic {@link createDirectConnectFlow} store. The browser never\n * sees the app private key and never chooses scopes — it only calls the app's\n * own backend routes via the injected transports.\n *\n * This module is browser-safe and imports nothing Node-only. `react` is a peer\n * dependency.\n *\n * @category Direct\n * @module direct/use-direct-vana-connect\n */\n\nimport { useCallback, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport {\n createDirectConnectFlow,\n type DirectConnectOptions,\n type DirectConnectState,\n type DirectConnectTransports,\n} from \"./connect-flow\";\n\n/** Options for {@link useDirectVanaConnect}: transports plus flow tunables. */\nexport type UseDirectVanaConnectOptions<T = unknown> =\n DirectConnectTransports<T> & DirectConnectOptions;\n\n/** Return value of {@link useDirectVanaConnect}. */\nexport interface UseDirectVanaConnectResult<T = unknown> {\n /** Current flow state (`state.type` is `\"idle\"` until `start()` is called). */\n state: DirectConnectState<T>;\n /** Begin the connect flow (create request, open Vana, poll, read). */\n start: () => void;\n /** Reset back to `idle` and cancel any in-flight polling. */\n reset: () => void;\n}\n\n/**\n * Drive the two-tab connect flow from a React component.\n *\n * @param options - The `createRequest`/`getStatus`/`readResult` transports plus\n * optional polling/timeout tunables.\n * @returns `{ state, start, reset }`.\n *\n * @example\n * ```tsx\n * const connect = useDirectVanaConnect({\n * createRequest: () => fetch(\"/api/vana/request\", { method: \"POST\" }).then((r) => r.json()),\n * getStatus: (id) => fetch(`/api/vana/status?requestId=${id}`).then((r) => r.json()),\n * readResult: (id) => fetch(`/api/vana/data?requestId=${id}`).then((r) => r.json()),\n * });\n * return <button disabled={connect.state.type !== \"idle\"} onClick={connect.start}>Connect</button>;\n * ```\n */\nexport function useDirectVanaConnect<T = unknown>(\n options: UseDirectVanaConnectOptions<T>,\n): UseDirectVanaConnectResult<T> {\n // Keep the latest options in a ref so the store reads current callbacks\n // without being recreated on every render.\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n const flow = useMemo(\n () =>\n createDirectConnectFlow<T>(\n {\n createRequest: () => optionsRef.current.createRequest(),\n getStatus: (id) => optionsRef.current.getStatus(id),\n readResult: (id) => optionsRef.current.readResult(id),\n },\n {\n get pollIntervalMs() {\n return optionsRef.current.pollIntervalMs;\n },\n get timeoutMs() {\n return optionsRef.current.timeoutMs;\n },\n get openApprovalWindow() {\n return optionsRef.current.openApprovalWindow;\n },\n get browserPlatformPolicy() {\n return optionsRef.current.browserPlatformPolicy;\n },\n },\n ),\n // Created once per component instance; callbacks are read via optionsRef.\n [],\n );\n\n const state = useSyncExternalStore(\n flow.subscribe,\n flow.getState,\n flow.getState,\n );\n\n const start = useCallback(() => {\n void flow.start();\n }, [flow]);\n\n const reset = useCallback(() => {\n flow.reset();\n }, [flow]);\n\n return { state, start, reset };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,mBAAmE;AACnE,
|
|
1
|
+
{"version":3,"sources":["../../src/direct/use-direct-vana-connect.ts"],"sourcesContent":["/**\n * React hook for the browser side of the direct Data Portability flow.\n *\n * @remarks\n * `useDirectVanaConnect` is a thin `useSyncExternalStore` binding over the\n * framework-agnostic {@link createDirectConnectFlow} store. The browser never\n * sees the app private key and never chooses scopes — it only calls the app's\n * own backend routes via the injected transports.\n *\n * This module is browser-safe and imports nothing Node-only. `react` is a peer\n * dependency.\n *\n * @category Direct\n * @module direct/use-direct-vana-connect\n */\n\nimport { useCallback, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport {\n createDirectConnectFlow,\n type DirectConnectOptions,\n type DirectConnectRetryOutcome,\n type DirectConnectState,\n type DirectConnectTransports,\n} from \"./connect-flow\";\n\n/** Options for {@link useDirectVanaConnect}: transports plus flow tunables. */\nexport type UseDirectVanaConnectOptions<T = unknown> =\n DirectConnectTransports<T> & DirectConnectOptions;\n\n/** Return value of {@link useDirectVanaConnect}. */\nexport interface UseDirectVanaConnectResult<T = unknown> {\n /** Current flow state (`state.type` is `\"idle\"` until `start()` is called). */\n state: DirectConnectState<T>;\n /** Begin the connect flow (create request, open Vana, poll, read). */\n start: () => void;\n /** Retry the read and report whether prior consent could be reused. */\n retryRead: () => Promise<DirectConnectRetryOutcome>;\n /** Reset back to `idle` and cancel any in-flight polling. */\n reset: () => void;\n}\n\n/**\n * Drive the two-tab connect flow from a React component.\n *\n * @param options - The `createRequest`/`getStatus`/`readResult` transports plus\n * optional polling/timeout tunables.\n * @returns `{ state, start, reset }`.\n *\n * @example\n * ```tsx\n * const connect = useDirectVanaConnect({\n * createRequest: () => fetch(\"/api/vana/request\", { method: \"POST\" }).then((r) => r.json()),\n * getStatus: (id) => fetch(`/api/vana/status?requestId=${id}`).then((r) => r.json()),\n * readResult: (id) => fetch(`/api/vana/data?requestId=${id}`).then((r) => r.json()),\n * });\n * return <button disabled={connect.state.type !== \"idle\"} onClick={connect.start}>Connect</button>;\n * ```\n */\nexport function useDirectVanaConnect<T = unknown>(\n options: UseDirectVanaConnectOptions<T>,\n): UseDirectVanaConnectResult<T> {\n // Keep the latest options in a ref so the store reads current callbacks\n // without being recreated on every render.\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n const flow = useMemo(\n () =>\n createDirectConnectFlow<T>(\n {\n createRequest: () => optionsRef.current.createRequest(),\n getStatus: (id) => optionsRef.current.getStatus(id),\n readResult: (id) => optionsRef.current.readResult(id),\n },\n {\n get pollIntervalMs() {\n return optionsRef.current.pollIntervalMs;\n },\n get timeoutMs() {\n return optionsRef.current.timeoutMs;\n },\n get openApprovalWindow() {\n return optionsRef.current.openApprovalWindow;\n },\n get browserPlatformPolicy() {\n return optionsRef.current.browserPlatformPolicy;\n },\n },\n ),\n // Created once per component instance; callbacks are read via optionsRef.\n [],\n );\n\n const state = useSyncExternalStore(\n flow.subscribe,\n flow.getState,\n flow.getState,\n );\n\n const start = useCallback(() => {\n void flow.start();\n }, [flow]);\n\n const reset = useCallback(() => {\n flow.reset();\n }, [flow]);\n\n const retryRead = useCallback(() => flow.retryRead(), [flow]);\n\n return { state, start, retryRead, reset };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,mBAAmE;AACnE,0BAMO;AAmCA,SAAS,qBACd,SAC+B;AAG/B,QAAM,iBAAa,qBAAO,OAAO;AACjC,aAAW,UAAU;AAErB,QAAM,WAAO;AAAA,IACX,UACE;AAAA,MACE;AAAA,QACE,eAAe,MAAM,WAAW,QAAQ,cAAc;AAAA,QACtD,WAAW,CAAC,OAAO,WAAW,QAAQ,UAAU,EAAE;AAAA,QAClD,YAAY,CAAC,OAAO,WAAW,QAAQ,WAAW,EAAE;AAAA,MACtD;AAAA,MACA;AAAA,QACE,IAAI,iBAAiB;AACnB,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,QACA,IAAI,YAAY;AACd,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,QACA,IAAI,qBAAqB;AACvB,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,QACA,IAAI,wBAAwB;AAC1B,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,MACF;AAAA,IACF;AAAA;AAAA,IAEF,CAAC;AAAA,EACH;AAEA,QAAM,YAAQ;AAAA,IACZ,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,EACP;AAEA,QAAM,YAAQ,0BAAY,MAAM;AAC9B,SAAK,KAAK,MAAM;AAAA,EAClB,GAAG,CAAC,IAAI,CAAC;AAET,QAAM,YAAQ,0BAAY,MAAM;AAC9B,SAAK,MAAM;AAAA,EACb,GAAG,CAAC,IAAI,CAAC;AAET,QAAM,gBAAY,0BAAY,MAAM,KAAK,UAAU,GAAG,CAAC,IAAI,CAAC;AAE5D,SAAO,EAAE,OAAO,OAAO,WAAW,MAAM;AAC1C;","names":[]}
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* @category Direct
|
|
14
14
|
* @module direct/use-direct-vana-connect
|
|
15
15
|
*/
|
|
16
|
-
import { type DirectConnectOptions, type DirectConnectState, type DirectConnectTransports } from "./connect-flow.js";
|
|
16
|
+
import { type DirectConnectOptions, type DirectConnectRetryOutcome, type DirectConnectState, type DirectConnectTransports } from "./connect-flow.js";
|
|
17
17
|
/** Options for {@link useDirectVanaConnect}: transports plus flow tunables. */
|
|
18
18
|
export type UseDirectVanaConnectOptions<T = unknown> = DirectConnectTransports<T> & DirectConnectOptions;
|
|
19
19
|
/** Return value of {@link useDirectVanaConnect}. */
|
|
@@ -22,6 +22,8 @@ export interface UseDirectVanaConnectResult<T = unknown> {
|
|
|
22
22
|
state: DirectConnectState<T>;
|
|
23
23
|
/** Begin the connect flow (create request, open Vana, poll, read). */
|
|
24
24
|
start: () => void;
|
|
25
|
+
/** Retry the read and report whether prior consent could be reused. */
|
|
26
|
+
retryRead: () => Promise<DirectConnectRetryOutcome>;
|
|
25
27
|
/** Reset back to `idle` and cancel any in-flight polling. */
|
|
26
28
|
reset: () => void;
|
|
27
29
|
}
|
|
@@ -41,7 +41,8 @@ function useDirectVanaConnect(options) {
|
|
|
41
41
|
const reset = useCallback(() => {
|
|
42
42
|
flow.reset();
|
|
43
43
|
}, [flow]);
|
|
44
|
-
|
|
44
|
+
const retryRead = useCallback(() => flow.retryRead(), [flow]);
|
|
45
|
+
return { state, start, retryRead, reset };
|
|
45
46
|
}
|
|
46
47
|
export {
|
|
47
48
|
useDirectVanaConnect
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/direct/use-direct-vana-connect.ts"],"sourcesContent":["/**\n * React hook for the browser side of the direct Data Portability flow.\n *\n * @remarks\n * `useDirectVanaConnect` is a thin `useSyncExternalStore` binding over the\n * framework-agnostic {@link createDirectConnectFlow} store. The browser never\n * sees the app private key and never chooses scopes — it only calls the app's\n * own backend routes via the injected transports.\n *\n * This module is browser-safe and imports nothing Node-only. `react` is a peer\n * dependency.\n *\n * @category Direct\n * @module direct/use-direct-vana-connect\n */\n\nimport { useCallback, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport {\n createDirectConnectFlow,\n type DirectConnectOptions,\n type DirectConnectState,\n type DirectConnectTransports,\n} from \"./connect-flow\";\n\n/** Options for {@link useDirectVanaConnect}: transports plus flow tunables. */\nexport type UseDirectVanaConnectOptions<T = unknown> =\n DirectConnectTransports<T> & DirectConnectOptions;\n\n/** Return value of {@link useDirectVanaConnect}. */\nexport interface UseDirectVanaConnectResult<T = unknown> {\n /** Current flow state (`state.type` is `\"idle\"` until `start()` is called). */\n state: DirectConnectState<T>;\n /** Begin the connect flow (create request, open Vana, poll, read). */\n start: () => void;\n /** Reset back to `idle` and cancel any in-flight polling. */\n reset: () => void;\n}\n\n/**\n * Drive the two-tab connect flow from a React component.\n *\n * @param options - The `createRequest`/`getStatus`/`readResult` transports plus\n * optional polling/timeout tunables.\n * @returns `{ state, start, reset }`.\n *\n * @example\n * ```tsx\n * const connect = useDirectVanaConnect({\n * createRequest: () => fetch(\"/api/vana/request\", { method: \"POST\" }).then((r) => r.json()),\n * getStatus: (id) => fetch(`/api/vana/status?requestId=${id}`).then((r) => r.json()),\n * readResult: (id) => fetch(`/api/vana/data?requestId=${id}`).then((r) => r.json()),\n * });\n * return <button disabled={connect.state.type !== \"idle\"} onClick={connect.start}>Connect</button>;\n * ```\n */\nexport function useDirectVanaConnect<T = unknown>(\n options: UseDirectVanaConnectOptions<T>,\n): UseDirectVanaConnectResult<T> {\n // Keep the latest options in a ref so the store reads current callbacks\n // without being recreated on every render.\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n const flow = useMemo(\n () =>\n createDirectConnectFlow<T>(\n {\n createRequest: () => optionsRef.current.createRequest(),\n getStatus: (id) => optionsRef.current.getStatus(id),\n readResult: (id) => optionsRef.current.readResult(id),\n },\n {\n get pollIntervalMs() {\n return optionsRef.current.pollIntervalMs;\n },\n get timeoutMs() {\n return optionsRef.current.timeoutMs;\n },\n get openApprovalWindow() {\n return optionsRef.current.openApprovalWindow;\n },\n get browserPlatformPolicy() {\n return optionsRef.current.browserPlatformPolicy;\n },\n },\n ),\n // Created once per component instance; callbacks are read via optionsRef.\n [],\n );\n\n const state = useSyncExternalStore(\n flow.subscribe,\n flow.getState,\n flow.getState,\n );\n\n const start = useCallback(() => {\n void flow.start();\n }, [flow]);\n\n const reset = useCallback(() => {\n flow.reset();\n }, [flow]);\n\n return { state, start, reset };\n}\n"],"mappings":"AAgBA,SAAS,aAAa,SAAS,QAAQ,4BAA4B;AACnE;AAAA,EACE;AAAA,
|
|
1
|
+
{"version":3,"sources":["../../src/direct/use-direct-vana-connect.ts"],"sourcesContent":["/**\n * React hook for the browser side of the direct Data Portability flow.\n *\n * @remarks\n * `useDirectVanaConnect` is a thin `useSyncExternalStore` binding over the\n * framework-agnostic {@link createDirectConnectFlow} store. The browser never\n * sees the app private key and never chooses scopes — it only calls the app's\n * own backend routes via the injected transports.\n *\n * This module is browser-safe and imports nothing Node-only. `react` is a peer\n * dependency.\n *\n * @category Direct\n * @module direct/use-direct-vana-connect\n */\n\nimport { useCallback, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport {\n createDirectConnectFlow,\n type DirectConnectOptions,\n type DirectConnectRetryOutcome,\n type DirectConnectState,\n type DirectConnectTransports,\n} from \"./connect-flow\";\n\n/** Options for {@link useDirectVanaConnect}: transports plus flow tunables. */\nexport type UseDirectVanaConnectOptions<T = unknown> =\n DirectConnectTransports<T> & DirectConnectOptions;\n\n/** Return value of {@link useDirectVanaConnect}. */\nexport interface UseDirectVanaConnectResult<T = unknown> {\n /** Current flow state (`state.type` is `\"idle\"` until `start()` is called). */\n state: DirectConnectState<T>;\n /** Begin the connect flow (create request, open Vana, poll, read). */\n start: () => void;\n /** Retry the read and report whether prior consent could be reused. */\n retryRead: () => Promise<DirectConnectRetryOutcome>;\n /** Reset back to `idle` and cancel any in-flight polling. */\n reset: () => void;\n}\n\n/**\n * Drive the two-tab connect flow from a React component.\n *\n * @param options - The `createRequest`/`getStatus`/`readResult` transports plus\n * optional polling/timeout tunables.\n * @returns `{ state, start, reset }`.\n *\n * @example\n * ```tsx\n * const connect = useDirectVanaConnect({\n * createRequest: () => fetch(\"/api/vana/request\", { method: \"POST\" }).then((r) => r.json()),\n * getStatus: (id) => fetch(`/api/vana/status?requestId=${id}`).then((r) => r.json()),\n * readResult: (id) => fetch(`/api/vana/data?requestId=${id}`).then((r) => r.json()),\n * });\n * return <button disabled={connect.state.type !== \"idle\"} onClick={connect.start}>Connect</button>;\n * ```\n */\nexport function useDirectVanaConnect<T = unknown>(\n options: UseDirectVanaConnectOptions<T>,\n): UseDirectVanaConnectResult<T> {\n // Keep the latest options in a ref so the store reads current callbacks\n // without being recreated on every render.\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n const flow = useMemo(\n () =>\n createDirectConnectFlow<T>(\n {\n createRequest: () => optionsRef.current.createRequest(),\n getStatus: (id) => optionsRef.current.getStatus(id),\n readResult: (id) => optionsRef.current.readResult(id),\n },\n {\n get pollIntervalMs() {\n return optionsRef.current.pollIntervalMs;\n },\n get timeoutMs() {\n return optionsRef.current.timeoutMs;\n },\n get openApprovalWindow() {\n return optionsRef.current.openApprovalWindow;\n },\n get browserPlatformPolicy() {\n return optionsRef.current.browserPlatformPolicy;\n },\n },\n ),\n // Created once per component instance; callbacks are read via optionsRef.\n [],\n );\n\n const state = useSyncExternalStore(\n flow.subscribe,\n flow.getState,\n flow.getState,\n );\n\n const start = useCallback(() => {\n void flow.start();\n }, [flow]);\n\n const reset = useCallback(() => {\n flow.reset();\n }, [flow]);\n\n const retryRead = useCallback(() => flow.retryRead(), [flow]);\n\n return { state, start, retryRead, reset };\n}\n"],"mappings":"AAgBA,SAAS,aAAa,SAAS,QAAQ,4BAA4B;AACnE;AAAA,EACE;AAAA,OAKK;AAmCA,SAAS,qBACd,SAC+B;AAG/B,QAAM,aAAa,OAAO,OAAO;AACjC,aAAW,UAAU;AAErB,QAAM,OAAO;AAAA,IACX,MACE;AAAA,MACE;AAAA,QACE,eAAe,MAAM,WAAW,QAAQ,cAAc;AAAA,QACtD,WAAW,CAAC,OAAO,WAAW,QAAQ,UAAU,EAAE;AAAA,QAClD,YAAY,CAAC,OAAO,WAAW,QAAQ,WAAW,EAAE;AAAA,MACtD;AAAA,MACA;AAAA,QACE,IAAI,iBAAiB;AACnB,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,QACA,IAAI,YAAY;AACd,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,QACA,IAAI,qBAAqB;AACvB,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,QACA,IAAI,wBAAwB;AAC1B,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,MACF;AAAA,IACF;AAAA;AAAA,IAEF,CAAC;AAAA,EACH;AAEA,QAAM,QAAQ;AAAA,IACZ,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,EACP;AAEA,QAAM,QAAQ,YAAY,MAAM;AAC9B,SAAK,KAAK,MAAM;AAAA,EAClB,GAAG,CAAC,IAAI,CAAC;AAET,QAAM,QAAQ,YAAY,MAAM;AAC9B,SAAK,MAAM;AAAA,EACb,GAAG,CAAC,IAAI,CAAC;AAET,QAAM,YAAY,YAAY,MAAM,KAAK,UAAU,GAAG,CAAC,IAAI,CAAC;AAE5D,SAAO,EAAE,OAAO,OAAO,WAAW,MAAM;AAC1C;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/errors.cjs
CHANGED
|
@@ -39,6 +39,7 @@ __export(errors_exports, {
|
|
|
39
39
|
JobNotFoundError: () => JobNotFoundError,
|
|
40
40
|
JobRejectedError: () => JobRejectedError,
|
|
41
41
|
JobRequestTooLargeError: () => JobRequestTooLargeError,
|
|
42
|
+
JobResultIntegrityError: () => JobResultIntegrityError,
|
|
42
43
|
JobTimeoutError: () => JobTimeoutError,
|
|
43
44
|
JobTransportError: () => JobTransportError,
|
|
44
45
|
JobsClientError: () => JobsClientError,
|
|
@@ -313,6 +314,11 @@ class JobTimeoutError extends JobsClientError {
|
|
|
313
314
|
super(message, "JOB_TIMEOUT", void 0, null, details);
|
|
314
315
|
}
|
|
315
316
|
}
|
|
317
|
+
class JobResultIntegrityError extends JobsClientError {
|
|
318
|
+
constructor(message, details) {
|
|
319
|
+
super(message, "JOB_RESULT_INTEGRITY", void 0, null, details);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
316
322
|
class JobRejectedError extends JobsClientError {
|
|
317
323
|
constructor(message, status, errorCode = null, details) {
|
|
318
324
|
super(message, "JOB_REJECTED", status, errorCode, details);
|
|
@@ -430,6 +436,7 @@ class DataPointVersionConflictError extends VanaError {
|
|
|
430
436
|
JobNotFoundError,
|
|
431
437
|
JobRejectedError,
|
|
432
438
|
JobRequestTooLargeError,
|
|
439
|
+
JobResultIntegrityError,
|
|
433
440
|
JobTimeoutError,
|
|
434
441
|
JobTransportError,
|
|
435
442
|
JobsClientError,
|