@buildaureon/sdk 0.1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/fetch-adapter.ts","../src/constants/defaults.ts","../src/constants/endpoints.ts","../src/errors/codes.ts","../src/errors/base.ts","../src/errors/http.ts","../src/transport/url.ts","../src/transport/http.ts","../src/types/client-options.ts","../src/types/market.ts","../src/validation/market-input.ts","../src/types/objective.ts","../src/validation/objective-input.ts","../src/client/aureon-client.ts","../src/client/factory.ts","../src/auth/session.ts","../src/formatting/display.ts","../src/types/health.ts","../src/types/timeline.ts","../src/types/execution.ts","../src/adapters/logging-adapter.ts"],"names":["DEFAULT_TIMEOUT_MS"],"mappings":";AAMO,SAAS,aAAa,MAAA,EAA+B;AAC1D,EAAA,IAAI,MAAA,EAAQ,OAAO,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA;AACrC,EAAA,IAAI,OAAO,UAAA,CAAW,KAAA,KAAU,UAAA,EAAY;AAC1C,IAAA,MAAM,IAAI,MAAM,mDAAmD,CAAA;AAAA,EACrE;AACA,EAAA,OAAO,UAAA,CAAW,KAAA,CAAM,IAAA,CAAK,UAAU,CAAA;AACzC;AASO,SAAS,gBAAgB,OAAA,EAAyC;AACvE,EAAA,OAAO,EAAE,cAAA,EAAgB,CAAA,iBAAA,EAAoB,OAAO,CAAA,CAAA,EAAG;AACzD;;;AClBO,IAAM,oBAAA,GAAuB;AAG7B,IAAM,kBAAA,GAAqB;AAE3B,IAAM,kBAAA,GAAqB;AAC3B,IAAM,WAAA,GAAc;AACpB,IAAM,QAAA,GAAW;AACjB,IAAM,YAAA,GAAe;AACrB,IAAM,eAAA,GACX;AAKK,IAAM,cAAA,GAAiB;;;AChBvB,IAAM,SAAA,GAAY;AAAA,EACvB,OAAA,EAAS,UAAA;AAAA,EACT,QAAA,EAAU,WAAA;AAAA,EACV,SAAA,EAAW,YAAA;AAAA,EACX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;;;ACKO,SAAS,kBAAkB,OAAA,EAAoC;AACpE,EAAA,OAAO,QAAQ,UAAA,KAAe,OAAA;AAChC;;;AC1CO,IAAM,YAAA,GAA6B;AAAA,EACxC,KAAA,GAAQ;AAAA,EAAC,CAAA;AAAA,EACT,IAAA,GAAO;AAAA,EAAC,CAAA;AAAA,EACR,IAAA,GAAO;AAAA,EAAC,CAAA;AAAA,EACR,KAAA,GAAQ;AAAA,EAAC;AACX;AAEO,SAAS,mBAAA,CAAoB,SAAS,YAAA,EAA4B;AACvE,EAAA,MAAM,KAAA,GAAQ,CAAC,KAAA,EAAiB,OAAA,EAAiB,OAAA,KAAsC;AACrF,IAAA,MAAM,IAAA,GAAO,CAAA,CAAA,EAAI,MAAM,CAAA,EAAA,EAAK,OAAO,CAAA,CAAA;AACnC,IAAA,IAAI,UAAU,OAAA,EAAS,OAAA,CAAQ,KAAA,CAAM,IAAA,EAAM,WAAW,EAAE,CAAA;AAAA,SAAA,IAC/C,UAAU,MAAA,EAAQ,OAAA,CAAQ,IAAA,CAAK,IAAA,EAAM,WAAW,EAAE,CAAA;AAAA,SACtD,OAAA,CAAQ,GAAA,CAAI,IAAA,EAAM,OAAA,IAAW,EAAE,CAAA;AAAA,EACtC,CAAA;AACA,EAAA,OAAO;AAAA,IACL,OAAO,CAAC,CAAA,EAAG,MAAM,KAAA,CAAM,OAAA,EAAS,GAAG,CAAC,CAAA;AAAA,IACpC,MAAM,CAAC,CAAA,EAAG,MAAM,KAAA,CAAM,MAAA,EAAQ,GAAG,CAAC,CAAA;AAAA,IAClC,MAAM,CAAC,CAAA,EAAG,MAAM,KAAA,CAAM,MAAA,EAAQ,GAAG,CAAC,CAAA;AAAA,IAClC,OAAO,CAAC,CAAA,EAAG,MAAM,KAAA,CAAM,OAAA,EAAS,GAAG,CAAC;AAAA,GACtC;AACF","file":"index.js","sourcesContent":["/**\n * @fileoverview Fetch adapter helpers for browser and Node runtimes.\n */\n\nexport type FetchLike = typeof fetch;\n\nexport function resolveFetch(custom?: FetchLike): FetchLike {\n if (custom) return custom.bind(custom);\n if (typeof globalThis.fetch !== \"function\") {\n throw new Error(\"No fetch implementation available in this runtime\");\n }\n return globalThis.fetch.bind(globalThis);\n}\n\nexport function mergeHeaders(\n base: Record<string, string>,\n extra?: Record<string, string>\n): Record<string, string> {\n return { ...base, ...(extra ?? {}) };\n}\n\nexport function userAgentHeader(version: string): Record<string, string> {\n return { \"X-Aureon-SDK\": `@buildaureon/sdk/${version}` };\n}\n","/**\n * @fileoverview Default runtime values for SDK clients and examples.\n */\n\n/** Production AUREON API (public integrators). */\nexport const DEFAULT_API_BASE_URL = \"https://api.aureonlabs.network\";\n\n/** Local monorepo preview only; not for public docs. */\nexport const LOCAL_API_BASE_URL = \"http://127.0.0.1:8787\";\n\nexport const DEFAULT_TIMEOUT_MS = 30_000;\nexport const SDK_VERSION = \"0.1.0\";\nexport const SDK_NAME = \"@buildaureon/sdk\";\nexport const PRODUCT_NAME = \"AUREON\";\nexport const PRODUCT_TAGLINE =\n \"Financial Compass for Robinhood Chain\";\n\nexport const REFERENCE_SYMBOLS = [\"USDG\", \"NVDA\", \"AAPL\", \"GOOGL\", \"ETH\"] as const;\n\n/** HTTP header for product API keys. */\nexport const API_KEY_HEADER = \"X-Aureon-Api-Key\";\n","/**\n * @fileoverview API path constants for AureonClient methods.\n */\n\nexport const ENDPOINTS = {\n healthz: \"/healthz\",\n overview: \"/overview\",\n portfolio: \"/portfolio\",\n portfolioClear: \"/portfolio/clear\",\n portfolioSync: \"/portfolio/sync\",\n watchdogRefresh: \"/watchdog/refresh\",\n objectives: \"/objectives\",\n health: \"/health\",\n timeline: \"/timeline\",\n executions: \"/executions\",\n executionsRun: \"/executions/run\",\n marketEvents: \"/market/events\",\n marketPresets: \"/market/presets\",\n vault: \"/vault\",\n vaultStatus: \"/vault/status\",\n vaultPrepareDeposit: \"/vault/prepare-deposit\",\n vaultPrepareWithdraw: \"/vault/prepare-withdraw\",\n authNonce: \"/auth/nonce\",\n authVerify: \"/auth/verify\",\n authLogout: \"/auth/logout\",\n authDevLogin: \"/auth/dev-login\",\n authMe: \"/auth/me\",\n developerApiKeys: \"/developer/api-keys\",\n} as const;\n\nexport function objectivePath(id: string): string {\n return `${ENDPOINTS.objectives}/${encodeURIComponent(id)}`;\n}\n\nexport function objectivePausePath(id: string): string {\n return `${objectivePath(id)}/pause`;\n}\n\nexport function objectiveResumePath(id: string): string {\n return `${objectivePath(id)}/resume`;\n}\n\nexport function objectiveRestorePlanPath(id: string): string {\n return `${objectivePath(id)}/restore-plan`;\n}\n\nexport function objectiveRestorePath(id: string): string {\n return `${objectivePath(id)}/restore`;\n}\n\nexport function developerApiKeyPath(id: string): string {\n return `${ENDPOINTS.developerApiKeys}/${encodeURIComponent(id)}`;\n}\n","/**\n * @fileoverview Stable machine-readable error codes for @buildaureon/sdk.\n */\n\nexport type AureonErrorCode =\n | \"NETWORK_ERROR\"\n | \"TIMEOUT\"\n | \"VALIDATION_ERROR\"\n | \"NOT_FOUND\"\n | \"CONFLICT\"\n | \"UNAUTHORIZED\"\n | \"RATE_LIMITED\"\n | \"SERVER_ERROR\"\n | \"UNEXPECTED_RESPONSE\"\n | \"ABORTED\";\n\nexport const RETRYABLE_CODES: readonly AureonErrorCode[] = [\n \"NETWORK_ERROR\",\n \"TIMEOUT\",\n \"RATE_LIMITED\",\n \"SERVER_ERROR\",\n] as const;\n\nexport function isRetryableCode(code: AureonErrorCode): boolean {\n return (RETRYABLE_CODES as readonly string[]).includes(code);\n}\n\nexport function defaultMessageForStatus(status: number): string {\n switch (status) {\n case 400:\n return \"The request failed validation\";\n case 401:\n return \"Authentication is required\";\n case 403:\n return \"Access is forbidden for this resource\";\n case 404:\n return \"The requested resource was not found\";\n case 409:\n return \"The request conflicts with the current resource state\";\n case 429:\n return \"Rate limit exceeded\";\n default:\n if (status >= 500) return \"The server encountered an error\";\n return `Unexpected HTTP status ${status}`;\n }\n}\n","/**\n * @fileoverview Base and specialized error classes for the AUREON SDK.\n */\n\nimport { isRetryableCode, type AureonErrorCode } from \"./codes.js\";\n\nexport class AureonError extends Error {\n readonly code: AureonErrorCode;\n readonly status: number | null;\n readonly details: Record<string, unknown> | null;\n\n constructor(\n message: string,\n code: AureonErrorCode,\n status: number | null = null,\n details: Record<string, unknown> | null = null\n ) {\n super(message);\n this.name = \"AureonError\";\n this.code = code;\n this.status = status;\n this.details = details;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n get retryable(): boolean {\n return isRetryableCode(this.code);\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n status: this.status,\n details: this.details,\n retryable: this.retryable,\n };\n }\n}\n\nexport class AureonValidationError extends AureonError {\n constructor(message: string, details: Record<string, unknown> | null = null) {\n super(message, \"VALIDATION_ERROR\", 400, details);\n this.name = \"AureonValidationError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class AureonNotFoundError extends AureonError {\n constructor(message: string, details: Record<string, unknown> | null = null) {\n super(message, \"NOT_FOUND\", 404, details);\n this.name = \"AureonNotFoundError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class AureonConflictError extends AureonError {\n constructor(message: string, details: Record<string, unknown> | null = null) {\n super(message, \"CONFLICT\", 409, details);\n this.name = \"AureonConflictError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class AureonNetworkError extends AureonError {\n constructor(message: string, details: Record<string, unknown> | null = null) {\n super(message, \"NETWORK_ERROR\", null, details);\n this.name = \"AureonNetworkError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class AureonTimeoutError extends AureonError {\n constructor(message = \"Request timed out\", details: Record<string, unknown> | null = null) {\n super(message, \"TIMEOUT\", null, details);\n this.name = \"AureonTimeoutError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","/**\n * @fileoverview Maps HTTP responses into typed AureonError instances.\n */\n\nimport {\n AureonConflictError,\n AureonError,\n AureonNotFoundError,\n AureonValidationError,\n} from \"./base.js\";\nimport { defaultMessageForStatus } from \"./codes.js\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction extractMessage(body: unknown): string | null {\n if (!isRecord(body)) return null;\n if (typeof body.message === \"string\") return body.message;\n if (typeof body.error === \"string\") return body.error;\n if (isRecord(body.error) && typeof body.error.message === \"string\") {\n return body.error.message;\n }\n return null;\n}\n\nexport function errorFromHttpStatus(status: number, body: unknown): AureonError {\n const message = extractMessage(body) ?? defaultMessageForStatus(status);\n const details = isRecord(body) ? body : { body };\n\n if (status === 400) return new AureonValidationError(message, details);\n if (status === 404) return new AureonNotFoundError(message, details);\n if (status === 409) return new AureonConflictError(message, details);\n if (status === 401 || status === 403) {\n return new AureonError(message, \"UNAUTHORIZED\", status, details);\n }\n if (status === 429) {\n return new AureonError(message, \"RATE_LIMITED\", status, details);\n }\n if (status >= 500) {\n return new AureonError(message, \"SERVER_ERROR\", status, details);\n }\n return new AureonError(message, \"UNEXPECTED_RESPONSE\", status, details);\n}\n\nexport function isAureonError(value: unknown): value is AureonError {\n return value instanceof AureonError;\n}\n","/**\n * @fileoverview URL helpers for the AUREON HTTP transport.\n */\n\nimport { AureonError } from \"../errors/base.js\";\n\nexport function joinUrl(baseUrl: string, path: string): string {\n const base = baseUrl.replace(/\\/+$/, \"\");\n const suffix = path.startsWith(\"/\") ? path : `/${path}`;\n return `${base}${suffix}`;\n}\n\nexport function assertBaseUrl(baseUrl: string): string {\n const trimmed = baseUrl.trim().replace(/\\/+$/, \"\");\n if (!/^https?:\\/\\//i.test(trimmed)) {\n throw new AureonError(\n \"baseUrl must be an absolute http(s) URL\",\n \"VALIDATION_ERROR\",\n 400,\n { baseUrl }\n );\n }\n return trimmed;\n}\n\nexport function withQuery(\n path: string,\n query: Record<string, string | undefined>\n): string {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined && value !== \"\") params.set(key, value);\n }\n const qs = params.toString();\n if (!qs) return path;\n return path.includes(\"?\") ? `${path}&${qs}` : `${path}?${qs}`;\n}\n","/**\n * @fileoverview JSON HTTP transport used by AureonClient.\n */\n\nimport type { AureonLogger } from \"../adapters/logging-adapter.js\";\nimport {\n AureonError,\n AureonNetworkError,\n AureonTimeoutError,\n} from \"../errors/base.js\";\nimport { errorFromHttpStatus } from \"../errors/http.js\";\nimport { joinUrl } from \"./url.js\";\n\nexport interface TransportOptions {\n baseUrl: string;\n fetchImpl: typeof fetch;\n headers: Record<string, string>;\n timeoutMs: number;\n maxRetries?: number;\n retryDelayMs?: number;\n logger?: AureonLogger;\n getAccessToken?: () =>\n | string\n | null\n | undefined\n | Promise<string | null | undefined>;\n getApiKey?: () =>\n | string\n | null\n | undefined\n | Promise<string | null | undefined>;\n}\n\nexport interface RequestOptions {\n method?: string;\n body?: unknown;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n}\n\nfunction safeParseJson(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return { message: text };\n }\n}\n\nfunction isAbortError(error: unknown): boolean {\n return (\n (error instanceof DOMException && error.name === \"AbortError\") ||\n (error instanceof Error && error.name === \"AbortError\")\n );\n}\n\nfunction isRetryableError(error: unknown): boolean {\n if (error instanceof AureonNetworkError || error instanceof AureonTimeoutError) {\n return true;\n }\n if (error instanceof AureonError) {\n return (\n typeof error.status === \"number\" &&\n (error.status >= 500 || error.status === 429)\n );\n }\n return false;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport async function requestJson<T>(\n transport: TransportOptions,\n path: string,\n options: RequestOptions = {}\n): Promise<T> {\n const url = joinUrl(transport.baseUrl, path);\n const maxRetries = transport.maxRetries ?? 0;\n const retryDelayMs = transport.retryDelayMs ?? 250;\n let attempt = 0;\n\n while (true) {\n attempt += 1;\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), transport.timeoutMs);\n const onAbort = () => controller.abort();\n\n if (options.signal) {\n if (options.signal.aborted) {\n clearTimeout(timeout);\n throw new AureonError(\"Request aborted\", \"ABORTED\");\n }\n options.signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n try {\n const token = transport.getAccessToken\n ? await transport.getAccessToken()\n : null;\n const authHeaders: Record<string, string> = {};\n if (typeof token === \"string\" && token.trim().length > 0) {\n authHeaders.Authorization = `Bearer ${token.trim()}`;\n }\n\n const apiKey = transport.getApiKey\n ? await transport.getApiKey()\n : null;\n if (typeof apiKey === \"string\" && apiKey.trim().length > 0) {\n authHeaders[\"X-Aureon-Api-Key\"] = apiKey.trim();\n }\n\n transport.logger?.debug(\"aureon.request\", {\n method: options.method ?? (options.body !== undefined ? \"POST\" : \"GET\"),\n path,\n attempt,\n });\n\n const response = await transport.fetchImpl(url, {\n method: options.method ?? (options.body !== undefined ? \"POST\" : \"GET\"),\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n ...transport.headers,\n ...authHeaders,\n ...options.headers,\n },\n body:\n options.body !== undefined ? JSON.stringify(options.body) : undefined,\n signal: controller.signal,\n });\n\n const text = await response.text();\n const parsed = text.length > 0 ? safeParseJson(text) : null;\n\n if (!response.ok) {\n throw errorFromHttpStatus(response.status, parsed ?? { message: text });\n }\n\n return parsed as T;\n } catch (error) {\n if (error instanceof AureonError && !isRetryableError(error)) {\n throw error;\n }\n if (isAbortError(error)) {\n const timeoutError = new AureonTimeoutError(\n \"Request timed out or was aborted\",\n { url, timeoutMs: transport.timeoutMs }\n );\n if (attempt <= maxRetries) {\n transport.logger?.warn(\"aureon.retry\", {\n path,\n attempt,\n reason: \"timeout\",\n });\n await sleep(retryDelayMs);\n continue;\n }\n throw timeoutError;\n }\n if (error instanceof AureonError) {\n if (attempt <= maxRetries && isRetryableError(error)) {\n transport.logger?.warn(\"aureon.retry\", {\n path,\n attempt,\n code: error.code,\n status: error.status,\n });\n await sleep(retryDelayMs);\n continue;\n }\n throw error;\n }\n const networkError = new AureonNetworkError(\n error instanceof Error ? error.message : \"Network request failed\",\n { url }\n );\n if (attempt <= maxRetries) {\n transport.logger?.warn(\"aureon.retry\", {\n path,\n attempt,\n reason: \"network\",\n });\n await sleep(retryDelayMs);\n continue;\n }\n throw networkError;\n } finally {\n clearTimeout(timeout);\n if (options.signal) options.signal.removeEventListener(\"abort\", onAbort);\n }\n }\n}\n","/**\n * @fileoverview Client configuration types for AureonClient.\n */\n\nimport type { AureonLogger } from \"../adapters/logging-adapter.js\";\nimport { API_KEY_HEADER } from \"../constants/defaults.js\";\n\nexport interface AureonClientOptions {\n /**\n * Base URL of the AUREON API.\n * Defaults to `https://api.aureonlabs.network`.\n */\n baseUrl?: string;\n /**\n * Product API key sent as `X-Aureon-Api-Key` on every request.\n * Required for SDK / CLI / code when keys are enforced and there is no\n * wallet Bearer yet. The operator utility uses wallet Bearer only.\n */\n apiKey?: string | null;\n /**\n * Called before each request to resolve the product API key.\n * Prefer this for automations that load keys from env or a secret store.\n */\n getApiKey?: () => string | null | undefined | Promise<string | null | undefined>;\n /** Optional fetch implementation for non-browser runtimes. */\n fetch?: typeof fetch;\n /** Optional default headers merged into every request. */\n headers?: Record<string, string>;\n /** Request timeout in milliseconds. Defaults to 30000. */\n timeoutMs?: number;\n /**\n * Static Bearer session token. Prefer `getAccessToken` for apps that refresh\n * or clear sessions at runtime.\n */\n authToken?: string | null;\n /**\n * Called before each request to resolve the current Bearer token.\n * Return null/undefined to send the request without Authorization.\n */\n getAccessToken?: () => string | null | undefined | Promise<string | null | undefined>;\n /** Optional structured logger for request lifecycle diagnostics. */\n logger?: AureonLogger;\n /**\n * Extra attempts after the first failure for retryable errors\n * (network, timeout, 429, 5xx). Defaults to 0.\n */\n maxRetries?: number;\n /** Delay in ms between retries. Defaults to 250. */\n retryDelayMs?: number;\n}\n\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n\nexport function resolveTimeoutMs(options: AureonClientOptions): number {\n const value = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(\"timeoutMs must be a positive finite number\");\n }\n return value;\n}\n\nexport function resolveHeaders(\n options: AureonClientOptions\n): Record<string, string> {\n const headers: Record<string, string> = { ...(options.headers ?? {}) };\n const key = options.apiKey?.trim();\n if (key) {\n headers[API_KEY_HEADER] = key;\n }\n return headers;\n}\n\nexport function resolveMaxRetries(options: AureonClientOptions): number {\n const value = options.maxRetries ?? 0;\n if (!Number.isInteger(value) || value < 0) {\n throw new Error(\"maxRetries must be a non-negative integer\");\n }\n return value;\n}\n\nexport function resolveRetryDelayMs(options: AureonClientOptions): number {\n const value = options.retryDelayMs ?? 250;\n if (!Number.isFinite(value) || value < 0) {\n throw new Error(\"retryDelayMs must be a non-negative finite number\");\n }\n return value;\n}\n","/**\n * @fileoverview Controlled market event types for operator demos and rehearsals.\n */\n\nexport interface MarketEvent {\n id: string;\n name: string;\n description: string;\n symbol: string;\n priceChangeRatio: number;\n appliedAt: string;\n}\n\nexport interface MarketPreset {\n name: string;\n description: string;\n symbol: string;\n priceChangeRatio: number;\n}\n\nexport interface ApplyMarketEventInput {\n name?: string;\n description?: string;\n symbol: string;\n priceChangeRatio: number;\n autoRestore?: boolean;\n}\n\nexport interface DashboardOverview {\n activeObjectives: number;\n healthyCount: number;\n warningCount: number;\n violationCount: number;\n pausedCount: number;\n totalNotionalUsd: number;\n stableWeight: number;\n /** Holdings count from the capital book. */\n assetCount: number;\n /** Absolute USD change vs prior UTC day snapshot; null when baseline only. */\n change24hUsd: number | null;\n /** Fractional change (0.05 = +5%); null when baseline only. */\n change24hPct: number | null;\n /** True when no prior-day snapshot exists yet. */\n change24hBaselineOnly: boolean;\n /** True when today's snapshot row exists. */\n change24hHasSnapshot: boolean;\n /** Average health score across non-paused objectives; null when none. */\n globalHealthScore: number | null;\n /** Persisted health samples (oldest → newest), up to ~90 days. */\n healthHistory: Array<{ at: string; score: number }>;\n /** warning + violation count. */\n attentionCount: number;\n /** Last successful live-mark watchdog evaluation (not overview poll). */\n lastEvaluationAt: string | null;\n /** lastEvaluationAt + watchdog interval when continuous monitor is configured. */\n nextEvaluationAt: string | null;\n watchdogIntervalMs: number | null;\n /** Last background/manual watchdog failure message, if any. */\n lastWatchdogError: string | null;\n lastSyncedAt: string | null;\n recentExecutions: import(\"./execution.js\").ExecutionReceipt[];\n recentEvents: import(\"./timeline.js\").TimelineEvent[];\n}\n\nexport function normalizeSymbol(symbol: string): string {\n return symbol.trim().toUpperCase();\n}\n\nexport function describeMarketMove(event: MarketEvent): string {\n const pct = (event.priceChangeRatio * 100).toFixed(2);\n return `${event.symbol} mark moved ${pct}% (${event.name})`;\n}\n","/**\n * @fileoverview Validation for controlled market event inputs.\n */\n\nimport { AureonValidationError } from \"../errors/base.js\";\nimport type { ApplyMarketEventInput } from \"../types/market.js\";\nimport { normalizeSymbol } from \"../types/market.js\";\n\nexport function normalizeApplyMarketEventInput(\n input: ApplyMarketEventInput\n): ApplyMarketEventInput {\n const symbol = normalizeSymbol(input.symbol ?? \"\");\n if (!symbol) throw new AureonValidationError(\"symbol is required\");\n if (!Number.isFinite(input.priceChangeRatio)) {\n throw new AureonValidationError(\"priceChangeRatio must be a finite number\");\n }\n if (input.priceChangeRatio <= -0.95) {\n throw new AureonValidationError(\n \"priceChangeRatio is too extreme for preview runtime\"\n );\n }\n return {\n ...input,\n symbol,\n autoRestore: input.autoRestore !== false,\n name: input.name?.trim() || undefined,\n description: input.description?.trim() || undefined,\n };\n}\n","/**\n * @fileoverview Objective domain types for Financial Compass Objectives.\n */\n\n/** Lifecycle status for a Financial Compass Objective (FCO). */\nexport type ObjectiveStatus =\n | \"draft\"\n | \"validated\"\n | \"active\"\n | \"paused\"\n | \"cancelled\"\n | \"completed\";\n\n/** Supported objective kinds for Phase 1 operator workflows. */\nexport type ObjectiveKind =\n | \"stable_allocation\"\n | \"balanced_portfolio\"\n | \"risk_ceiling\"\n | \"reward_reinvestment\";\n\n/** Priority influences evaluation ordering when multiple objectives compete. */\nexport type ObjectivePriority = \"low\" | \"medium\" | \"high\" | \"critical\";\n\n/**\n * Per-objective restore behaviour as stored on the API.\n *\n * SDK / agent integrations create objectives as **Automatic** (default).\n * `\"manual\"` exists so the operator utility can require an Approve click;\n * it is not part of the recommended SDK integration path.\n */\nexport type ObjectiveAutomationMode = \"manual\" | \"auto\";\n\n/** Policy rules attached to an objective. */\nexport interface ObjectivePolicy {\n targetWeight: number;\n tolerance: number;\n maxRiskScore?: number;\n reinvestRatio?: number;\n /** Holding symbol when the objective tracks a specific asset weight. */\n targetSymbol?: string;\n summary: string;\n}\n\n/** Financial Compass Objective record. */\nexport interface Objective {\n id: string;\n name: string;\n kind: ObjectiveKind;\n status: ObjectiveStatus;\n priority: ObjectivePriority;\n /**\n * Restore mode for this objective.\n * SDK creates always set `\"auto\"`. `\"manual\"` is operator-utility only.\n */\n automationMode: ObjectiveAutomationMode;\n policy: ObjectivePolicy;\n ownerId: string;\n createdAt: string;\n updatedAt: string;\n lastEvaluatedAt: string | null;\n lastExecutionId: string | null;\n}\n\n/**\n * Input for creating a new objective.\n *\n * SDK create always sends `automationMode: \"auto\"` (Automatic restore).\n * Manual Approve is an operator-utility concern; do not rely on it in\n * agent / SDK loops.\n */\nexport interface CreateObjectiveInput {\n name: string;\n kind: ObjectiveKind;\n priority?: ObjectivePriority;\n targetWeight: number;\n tolerance: number;\n maxRiskScore?: number;\n reinvestRatio?: number;\n targetSymbol?: string | null;\n /**\n * @deprecated For SDK integrations omit this; create always uses Automatic.\n * The operator utility may still pass `\"manual\"` for Approve UX.\n */\n automationMode?: ObjectiveAutomationMode;\n}\n\n/** Partial update for an existing objective. */\nexport interface UpdateObjectiveInput {\n name?: string;\n priority?: ObjectivePriority;\n targetWeight?: number;\n tolerance?: number;\n maxRiskScore?: number;\n reinvestRatio?: number;\n targetSymbol?: string | null;\n /**\n * @deprecated Rejected on update; mode is fixed at create to avoid restore-flow issues.\n * Recreate the objective to switch Manual ↔ Automatic.\n */\n automationMode?: never;\n}\n\nexport const OBJECTIVE_KINDS: readonly ObjectiveKind[] = [\n \"stable_allocation\",\n \"balanced_portfolio\",\n \"risk_ceiling\",\n \"reward_reinvestment\",\n] as const;\n\nexport const OBJECTIVE_PRIORITIES: readonly ObjectivePriority[] = [\n \"low\",\n \"medium\",\n \"high\",\n \"critical\",\n] as const;\n\nexport function isObjectiveKind(value: string): value is ObjectiveKind {\n return (OBJECTIVE_KINDS as readonly string[]).includes(value);\n}\n\nexport function isObjectivePriority(value: string): value is ObjectivePriority {\n return (OBJECTIVE_PRIORITIES as readonly string[]).includes(value);\n}\n","/**\n * @fileoverview Validation and normalization for objective create/update payloads.\n */\n\nimport { AureonValidationError } from \"../errors/base.js\";\nimport type {\n CreateObjectiveInput,\n UpdateObjectiveInput,\n} from \"../types/objective.js\";\nimport { isObjectiveKind, isObjectivePriority } from \"../types/objective.js\";\n\nexport function buildPolicySummary(\n kind: CreateObjectiveInput[\"kind\"],\n targetWeight: number,\n tolerance: number\n): string {\n const targetPct = (targetWeight * 100).toFixed(1);\n const tolPct = (tolerance * 100).toFixed(1);\n switch (kind) {\n case \"stable_allocation\":\n return `Maintain ${targetPct}% stable allocation within ±${tolPct}%`;\n case \"balanced_portfolio\":\n return `Hold balanced weights near ${targetPct}% primary sleeve within ±${tolPct}%`;\n case \"risk_ceiling\":\n return `Keep portfolio risk at or below configured ceiling with ${tolPct}% buffer`;\n case \"reward_reinvestment\":\n return `Reinvest available rewards toward ${targetPct}% target sleeve`;\n default:\n return `Objective policy target ${targetPct}% ±${tolPct}%`;\n }\n}\n\nexport function normalizeCreateObjectiveInput(\n input: CreateObjectiveInput\n): CreateObjectiveInput {\n const name = input.name?.trim();\n if (!name || name.length < 3) {\n throw new AureonValidationError(\"Objective name must be at least 3 characters\");\n }\n if (!isObjectiveKind(input.kind)) {\n throw new AureonValidationError(`Unsupported objective kind: ${input.kind}`);\n }\n if (input.targetWeight < 0 || input.targetWeight > 1) {\n throw new AureonValidationError(\"targetWeight must be between 0 and 1\");\n }\n if (input.tolerance < 0 || input.tolerance > 0.5) {\n throw new AureonValidationError(\"tolerance must be between 0 and 0.5\");\n }\n const priority = input.priority ?? \"high\";\n if (!isObjectivePriority(priority)) {\n throw new AureonValidationError(`Unsupported priority: ${priority}`);\n }\n if (input.kind === \"balanced_portfolio\") {\n const symbol = input.targetSymbol?.trim().toUpperCase();\n if (!symbol) {\n throw new AureonValidationError(\n \"balanced_portfolio requires targetSymbol\"\n );\n }\n return {\n ...input,\n name,\n priority,\n targetSymbol: symbol,\n // SDK / agent path defaults to Automatic. Explicit \"manual\" is reserved\n // for the operator utility Approve UX; not recommended for integrations.\n automationMode: input.automationMode === \"manual\" ? \"manual\" : \"auto\",\n };\n }\n return {\n ...input,\n name,\n priority,\n targetSymbol: null,\n automationMode: input.automationMode === \"manual\" ? \"manual\" : \"auto\",\n };\n}\n\nexport function normalizeUpdateObjectiveInput(\n input: UpdateObjectiveInput\n): UpdateObjectiveInput {\n const next: UpdateObjectiveInput = { ...input };\n if (next.name !== undefined) {\n const name = next.name.trim();\n if (name.length < 3) {\n throw new AureonValidationError(\"Objective name must be at least 3 characters\");\n }\n next.name = name;\n }\n if (next.targetWeight !== undefined) {\n if (next.targetWeight < 0 || next.targetWeight > 1) {\n throw new AureonValidationError(\"targetWeight must be between 0 and 1\");\n }\n }\n if (next.tolerance !== undefined) {\n if (next.tolerance < 0 || next.tolerance > 0.5) {\n throw new AureonValidationError(\"tolerance must be between 0 and 0.5\");\n }\n }\n if (next.priority !== undefined && !isObjectivePriority(next.priority)) {\n throw new AureonValidationError(`Unsupported priority: ${next.priority}`);\n }\n if (next.automationMode !== undefined) {\n throw new AureonValidationError(\n \"automationMode cannot be changed after create: recreate the objective instead\"\n );\n }\n return next;\n}\n\nexport function assertId(value: string, label: string): void {\n if (!value || typeof value !== \"string\" || value.trim().length < 8) {\n throw new AureonValidationError(`Invalid ${label}`);\n }\n}\n","/**\n * @fileoverview AureonClient: primary entry point for @buildaureon/sdk.\n *\n * Typed HTTP client for the hosted AUREON API. Wallet Bearer sessions identify\n * the operator; `apiKey` (`X-Aureon-Api-Key`) unlocks product access.\n *\n * Objectives default to Automatic automation mode. Vault deposit and withdraw\n * are prepare-calldata steps for wallet signing; not server-side broadcasts.\n * Restorative execution receipts may use `settlement: \"vault\"` or\n * `settlement: \"staged\"` depending on the restore path.\n */\n\nimport { resolveFetch, userAgentHeader } from \"../adapters/fetch-adapter.js\";\nimport {\n DEFAULT_API_BASE_URL,\n SDK_VERSION,\n} from \"../constants/defaults.js\";\nimport {\n ENDPOINTS,\n developerApiKeyPath,\n objectivePath,\n objectivePausePath,\n objectiveResumePath,\n objectiveRestorePath,\n objectiveRestorePlanPath,\n} from \"../constants/endpoints.js\";\nimport { AureonValidationError } from \"../errors/base.js\";\nimport {\n assertBaseUrl,\n requestJson,\n withQuery,\n type TransportOptions,\n} from \"../transport/index.js\";\nimport type { AureonClientOptions } from \"../types/client-options.js\";\nimport {\n resolveHeaders,\n resolveMaxRetries,\n resolveRetryDelayMs,\n resolveTimeoutMs,\n} from \"../types/client-options.js\";\nimport type { ExecutionReceipt, RestorePlan } from \"../types/execution.js\";\nimport type { ObjectiveHealth } from \"../types/health.js\";\nimport type {\n ApplyMarketEventInput,\n DashboardOverview,\n MarketEvent,\n MarketPreset,\n} from \"../types/market.js\";\nimport type {\n CreateObjectiveInput,\n Objective,\n UpdateObjectiveInput,\n} from \"../types/objective.js\";\nimport type { PortfolioPositionInput, PortfolioSnapshot } from \"../types/portfolio.js\";\nimport type {\n VaultDepositSymbol,\n VaultOverview,\n VaultPrepareResult,\n VaultStatus,\n} from \"../types/vault.js\";\nimport type { WatchdogRefreshResult } from \"../types/watchdog.js\";\nimport type { TimelineEvent } from \"../types/timeline.js\";\nimport { normalizeApplyMarketEventInput } from \"../validation/market-input.js\";\nimport {\n assertId,\n normalizeCreateObjectiveInput,\n normalizeUpdateObjectiveInput,\n} from \"../validation/objective-input.js\";\n\nexport interface AuthNonceResponse {\n walletAddress: string;\n nonce: string;\n message: string;\n expiresAt: string;\n}\n\nexport interface AuthSessionResponse {\n token: string;\n walletAddress: string;\n expiresAt: string;\n sessionId: string;\n mode?: string;\n}\n\nexport interface AuthMeResponse {\n walletAddress: string;\n}\n\nexport interface SyncPortfolioResult {\n portfolio: PortfolioSnapshot;\n chainId: number;\n skippedZero: string[];\n}\n\nexport interface DeveloperApiKey {\n id: string;\n name: string;\n prefix: string;\n status: string;\n createdAt: string;\n revokedAt: string | null;\n}\n\nexport interface CreatedDeveloperApiKey extends DeveloperApiKey {\n /** Plaintext secret; only returned once at creation. */\n secret: string;\n}\n\n/**\n * High-level SDK client for AUREON operator and developer integrations.\n */\nexport class AureonClient {\n private readonly transport: TransportOptions;\n\n constructor(options: AureonClientOptions = {}) {\n const baseUrl = options.baseUrl ?? DEFAULT_API_BASE_URL;\n\n const staticToken = options.authToken;\n const getAccessToken =\n options.getAccessToken ??\n (staticToken\n ? () => staticToken\n : undefined);\n\n const staticApiKey = options.apiKey;\n const getApiKey =\n options.getApiKey ??\n (staticApiKey\n ? () => staticApiKey\n : undefined);\n\n this.transport = {\n baseUrl: assertBaseUrl(baseUrl),\n fetchImpl: resolveFetch(options.fetch),\n headers: {\n ...userAgentHeader(SDK_VERSION),\n ...resolveHeaders({ ...options, apiKey: undefined }),\n },\n timeoutMs: resolveTimeoutMs(options),\n maxRetries: resolveMaxRetries(options),\n retryDelayMs: resolveRetryDelayMs(options),\n logger: options.logger,\n getAccessToken,\n getApiKey,\n };\n }\n\n /** Returns the resolved API base URL. */\n get baseUrl(): string {\n return this.transport.baseUrl;\n }\n\n /** Health probe for connectivity checks. No auth required. */\n async ping(): Promise<{ ok: true; service: string; version: string }> {\n return requestJson(this.transport, ENDPOINTS.healthz);\n }\n\n /**\n * Requests a single-use wallet auth nonce/message for the given address.\n * No Bearer token required.\n */\n async getAuthNonce(address: string): Promise<AuthNonceResponse> {\n const trimmed = address?.trim();\n if (!trimmed) {\n throw new AureonValidationError(\"address is required\");\n }\n return requestJson(\n this.transport,\n withQuery(ENDPOINTS.authNonce, { address: trimmed })\n );\n }\n\n /**\n * Verifies a wallet signature and returns a Bearer session.\n * No Bearer token required on the request itself.\n */\n async verifyWallet(input: {\n address: string;\n message: string;\n signature: string;\n }): Promise<AuthSessionResponse> {\n const address = input.address?.trim();\n const message = input.message?.trim();\n const signature = input.signature?.trim();\n if (!address || !message || !signature) {\n throw new AureonValidationError(\n \"address, message, and signature are required\"\n );\n }\n return requestJson(this.transport, ENDPOINTS.authVerify, {\n method: \"POST\",\n body: { address, message, signature },\n });\n }\n\n /**\n * Local preview login without a wallet signature.\n * Only succeeds when the backend has `AUREON_ALLOW_DEV_LOGIN=1`.\n */\n async devLogin(): Promise<AuthSessionResponse> {\n return requestJson(this.transport, ENDPOINTS.authDevLogin, {\n method: \"POST\",\n });\n }\n\n /** Revokes the current Bearer session on the server. */\n async logout(): Promise<{ ok: true }> {\n return requestJson(this.transport, ENDPOINTS.authLogout, {\n method: \"POST\",\n });\n }\n\n /** Returns the wallet bound to the current Bearer session. Auth required. */\n async me(): Promise<AuthMeResponse> {\n return requestJson(this.transport, ENDPOINTS.authMe);\n }\n\n /**\n * Creates and activates a Financial Compass Objective (FCO).\n * SDK / agent path always prefers Automatic (`automationMode` omitted → `\"auto\"`).\n * Mode cannot be changed later via `updateObjective`; recreate instead.\n * Passing `\"manual\"` is reserved for the operator utility Approve UX.\n * Auth required.\n */\n async createObjective(input: CreateObjectiveInput): Promise<Objective> {\n const body = normalizeCreateObjectiveInput(input);\n return requestJson(this.transport, ENDPOINTS.objectives, {\n method: \"POST\",\n body,\n });\n }\n\n /** Lists objectives for the authenticated wallet. Auth required. */\n async listObjectives(): Promise<Objective[]> {\n const result = await requestJson<{ objectives: Objective[] }>(\n this.transport,\n ENDPOINTS.objectives\n );\n return result.objectives;\n }\n\n /** Fetches a single objective by id. Auth required. */\n async getObjective(id: string): Promise<Objective> {\n assertId(id, \"objective id\");\n return requestJson(this.transport, objectivePath(id));\n }\n\n /**\n * Applies a partial update to an objective policy or metadata.\n * Does **not** accept `automationMode` (mode is locked at create).\n * Auth required.\n */\n async updateObjective(\n id: string,\n input: UpdateObjectiveInput\n ): Promise<Objective> {\n assertId(id, \"objective id\");\n const body = normalizeUpdateObjectiveInput(input);\n return requestJson(this.transport, objectivePath(id), {\n method: \"PATCH\",\n body,\n });\n }\n\n /** Pauses continuous evaluation for an objective. Auth required. */\n async pauseObjective(id: string): Promise<Objective> {\n assertId(id, \"objective id\");\n return requestJson(this.transport, objectivePausePath(id), {\n method: \"POST\",\n });\n }\n\n /** Resumes evaluation for a paused objective. Auth required. */\n async resumeObjective(id: string): Promise<Objective> {\n assertId(id, \"objective id\");\n return requestJson(this.transport, objectiveResumePath(id), {\n method: \"POST\",\n });\n }\n\n /** Returns health for one objective or all objectives when id is omitted. Auth required. */\n async getHealth(objectiveId?: string): Promise<ObjectiveHealth[]> {\n const path = withQuery(ENDPOINTS.health, { objectiveId });\n const result = await requestJson<{ health: ObjectiveHealth[] }>(\n this.transport,\n path\n );\n return result.health;\n }\n\n /** Returns timeline events, optionally filtered by objective. Auth required. */\n async getTimeline(objectiveId?: string): Promise<TimelineEvent[]> {\n const path = withQuery(ENDPOINTS.timeline, { objectiveId });\n const result = await requestJson<{ events: TimelineEvent[] }>(\n this.transport,\n path\n );\n return result.events;\n }\n\n /** Returns the current portfolio snapshot for the wallet. Auth required. */\n async getPortfolio(): Promise<PortfolioSnapshot> {\n return requestJson(this.transport, ENDPOINTS.portfolio);\n }\n\n /**\n * Replaces the wallet capital book with the provided positions.\n * Auth required. Does not invent holdings: every row must be supplied.\n */\n async setPortfolio(\n positions: PortfolioPositionInput[]\n ): Promise<PortfolioSnapshot> {\n if (!Array.isArray(positions) || positions.length === 0) {\n throw new AureonValidationError(\"positions must be a non-empty array\");\n }\n const result = await requestJson<{ portfolio: PortfolioSnapshot }>(\n this.transport,\n ENDPOINTS.portfolio,\n { method: \"PUT\", body: { positions } }\n );\n return result.portfolio;\n }\n\n /**\n * Clears all capital-book positions for the authenticated wallet.\n * Auth required. Does not invent seeded holdings.\n */\n async clearPortfolio(): Promise<PortfolioSnapshot> {\n const result = await requestJson<{ portfolio: PortfolioSnapshot }>(\n this.transport,\n ENDPOINTS.portfolioClear,\n { method: \"POST\" }\n );\n return result.portfolio;\n }\n\n /**\n * Replaces the capital book with on-chain balances for the session wallet\n * (Robinhood Chain via the AUREON API). Vault balances merge into the book.\n * Requires a wallet Bearer session; SDK clients should also send an API key\n * when keys are enforced. Does not invent holdings; only positive balances\n * returned by the API.\n */\n async syncPortfolio(): Promise<SyncPortfolioResult> {\n return requestJson(this.transport, ENDPOINTS.portfolioSync, {\n method: \"POST\",\n });\n }\n\n /**\n * Refreshes portfolio marks from live public market data, re-evaluates\n * objectives, optionally fires breach webhooks, and returns restore suggestions.\n * Auth required.\n */\n async refreshWatchdog(): Promise<WatchdogRefreshResult> {\n return requestJson(this.transport, ENDPOINTS.watchdogRefresh, {\n method: \"POST\",\n });\n }\n\n /** Returns dashboard overview aggregates. Auth required. */\n async getOverview(): Promise<DashboardOverview> {\n return requestJson(this.transport, ENDPOINTS.overview);\n }\n\n /**\n * Applies a controlled market event to portfolio marks.\n * When autoRestore is true, the API evaluates health and may run staged restorative execution.\n * Auth required.\n */\n async applyMarketEvent(input: ApplyMarketEventInput): Promise<{\n event: MarketEvent;\n portfolio: PortfolioSnapshot;\n health: ObjectiveHealth[];\n executions: ExecutionReceipt[];\n }> {\n const body = normalizeApplyMarketEventInput(input);\n return requestJson(this.transport, ENDPOINTS.marketEvents, {\n method: \"POST\",\n body,\n });\n }\n\n /** Lists controlled market event presets. Auth required. */\n async listMarketPresets(): Promise<MarketPreset[]> {\n const result = await requestJson<{ presets: MarketPreset[] }>(\n this.transport,\n ENDPOINTS.marketPresets\n );\n return result.presets;\n }\n\n /**\n * Returns the restore plan for an objective (wrap ETH, unwrap WETH, or vault swap).\n * Auth required.\n */\n async getRestorePlan(objectiveId: string): Promise<RestorePlan> {\n assertId(objectiveId, \"objective id\");\n const result = await requestJson<{ plan: RestorePlan }>(\n this.transport,\n objectiveRestorePlanPath(objectiveId)\n );\n return result.plan;\n }\n\n /**\n * Runs restorative execution for an objective currently outside policy.\n * Vault Sell A→Buy B when configured. ETH↔WETH wrap/unwrap is client-side\n * via getRestorePlan; this endpoint rejects those with action details.\n * Auth required.\n */\n async runExecution(objectiveId: string): Promise<ExecutionReceipt> {\n assertId(objectiveId, \"objective id\");\n return requestJson(this.transport, ENDPOINTS.executionsRun, {\n method: \"POST\",\n body: { objectiveId },\n });\n }\n\n /**\n * Runs vault-backed restorative execution for an objective outside policy.\n * Auth required.\n */\n async restoreObjective(objectiveId: string): Promise<ExecutionReceipt> {\n assertId(objectiveId, \"objective id\");\n return requestJson(this.transport, objectiveRestorePath(objectiveId), {\n method: \"POST\",\n });\n }\n\n /** Lists recent execution receipts. Auth required. */\n async listExecutions(objectiveId?: string): Promise<ExecutionReceipt[]> {\n const path = withQuery(ENDPOINTS.executions, { objectiveId });\n const result = await requestJson<{ executions: ExecutionReceipt[] }>(\n this.transport,\n path\n );\n return result.executions;\n }\n\n /** Returns the vault overview for the authenticated wallet. Auth required. */\n async getVault(): Promise<VaultOverview> {\n return requestJson(this.transport, ENDPOINTS.vault);\n }\n\n /** Returns compact vault funding status before restore. Auth required. */\n async getVaultStatus(): Promise<VaultStatus> {\n return requestJson(this.transport, ENDPOINTS.vaultStatus);\n }\n\n /**\n * Prepares wallet-signed calldata steps for a vault deposit.\n * Auth required.\n */\n async prepareVaultDeposit(input: {\n symbol: VaultDepositSymbol;\n amount: string;\n }): Promise<VaultPrepareResult> {\n const symbol = input.symbol?.trim();\n const amount = input.amount?.trim();\n if (!symbol) {\n throw new AureonValidationError(\n \"symbol is required (ETH or an allowlisted ERC-20)\"\n );\n }\n if (!amount) {\n throw new AureonValidationError(\"amount is required\");\n }\n return requestJson(this.transport, ENDPOINTS.vaultPrepareDeposit, {\n method: \"POST\",\n body: { symbol: symbol.toUpperCase(), amount },\n });\n }\n\n /**\n * Prepares wallet-signed calldata steps for a vault withdraw (any allowlisted ERC-20).\n * Auth required.\n */\n async prepareVaultWithdraw(input: {\n symbol?: string;\n amount: string;\n }): Promise<VaultPrepareResult> {\n const symbol = (input.symbol?.trim() || \"WETH\").toUpperCase();\n const amount = input.amount?.trim();\n if (!amount) {\n throw new AureonValidationError(\"amount is required\");\n }\n if (symbol === \"ETH\") {\n throw new AureonValidationError(\n 'withdraw symbol cannot be \"ETH\", use WETH'\n );\n }\n return requestJson(this.transport, ENDPOINTS.vaultPrepareWithdraw, {\n method: \"POST\",\n body: { symbol, amount },\n });\n }\n\n /**\n * Lists SDK API keys for the authenticated wallet.\n * Used by the operator utility Developer page.\n */\n async listApiKeys(): Promise<DeveloperApiKey[]> {\n const result = await requestJson<{ keys: DeveloperApiKey[] }>(\n this.transport,\n ENDPOINTS.developerApiKeys\n );\n return result.keys;\n }\n\n /**\n * Creates an SDK API key. `secret` is returned once; store it immediately.\n */\n async createApiKey(name: string): Promise<CreatedDeveloperApiKey> {\n const trimmed = name.trim();\n if (trimmed.length < 2) {\n throw new AureonValidationError(\"name must be at least 2 characters\");\n }\n return requestJson(this.transport, ENDPOINTS.developerApiKeys, {\n method: \"POST\",\n body: { name: trimmed },\n });\n }\n\n /** Revokes (deletes) an SDK API key owned by this wallet. */\n async revokeApiKey(keyId: string): Promise<DeveloperApiKey> {\n assertId(keyId, \"api key id\");\n return requestJson(this.transport, developerApiKeyPath(keyId), {\n method: \"DELETE\",\n });\n }\n\n /** Toggles the status (active/paused) of an SDK API key owned by this wallet. */\n async toggleApiKey(keyId: string): Promise<DeveloperApiKey> {\n assertId(keyId, \"api key id\");\n return requestJson(this.transport, `${developerApiKeyPath(keyId)}/toggle`, {\n method: \"POST\",\n });\n }\n}\n","/**\n * @fileoverview Factory helpers for constructing AureonClient instances.\n */\n\nimport {\n DEFAULT_API_BASE_URL,\n LOCAL_API_BASE_URL,\n} from \"../constants/defaults.js\";\nimport type { AureonClientOptions } from \"../types/client-options.js\";\nimport { AureonClient } from \"./aureon-client.js\";\n\n/**\n * Factory helper preferred by examples and quickstarts.\n * Defaults to the production AUREON API URL when `baseUrl` is omitted.\n */\nexport function createAureonClient(\n options: AureonClientOptions = {}\n): AureonClient {\n return new AureonClient({\n baseUrl: options.baseUrl ?? DEFAULT_API_BASE_URL,\n ...options,\n });\n}\n\n/**\n * Creates a client pointed at a local AUREON API process (monorepo operators).\n * Not advertised in the public README.\n */\nexport function createLocalAureonClient(\n overrides: Partial<AureonClientOptions> = {}\n): AureonClient {\n return new AureonClient({\n ...overrides,\n baseUrl: overrides.baseUrl ?? LOCAL_API_BASE_URL,\n });\n}\n","/**\r\n * @fileoverview Mutable bearer token holder for scripts and apps.\r\n */\r\n\r\n/** Mutable bearer token holder for scripts and apps. */\r\nexport function createSessionTokenProvider(initialToken?: string | null) {\r\n let token = initialToken ?? null;\r\n return {\r\n getAccessToken: () => token,\r\n setToken: (next: string | null) => {\r\n token = next;\r\n },\r\n clear: () => {\r\n token = null;\r\n },\r\n };\r\n}\r\n\r\nexport type SessionTokenProvider = ReturnType<typeof createSessionTokenProvider>;\r\n","/**\n * @fileoverview Display helpers shared by utility apps and CLI output.\n */\n\nimport type { HealthState } from \"../types/health.js\";\n\nexport function formatUsd(value: number): string {\n return new Intl.NumberFormat(\"en-US\", {\n style: \"currency\",\n currency: \"USD\",\n maximumFractionDigits: 2,\n }).format(value);\n}\n\nexport function formatWeight(weight: number): string {\n return `${(weight * 100).toFixed(1)}%`;\n}\n\nexport function healthTone(\n state: HealthState\n): \"positive\" | \"caution\" | \"critical\" | \"neutral\" {\n switch (state) {\n case \"healthy\":\n return \"positive\";\n case \"warning\":\n return \"caution\";\n case \"violation\":\n return \"critical\";\n case \"paused\":\n return \"neutral\";\n default:\n return \"neutral\";\n }\n}\n\nexport function formatSignedPercent(ratio: number): string {\n const pct = ratio * 100;\n const sign = pct > 0 ? \"+\" : \"\";\n return `${sign}${pct.toFixed(1)}%`;\n}\n\nexport function formatIsoTime(iso: string): string {\n try {\n return new Intl.DateTimeFormat(\"en-US\", {\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n }).format(new Date(iso));\n } catch {\n return iso;\n }\n}\n","/**\n * @fileoverview Health Engine result types.\n */\n\nexport type HealthState = \"healthy\" | \"warning\" | \"violation\" | \"paused\";\n\nexport interface ObjectiveHealth {\n objectiveId: string;\n state: HealthState;\n score: number;\n currentMetric: number;\n targetMetric: number;\n deviation: number;\n message: string;\n evaluatedAt: string;\n}\n\nexport function isHealthState(value: string): value is HealthState {\n return [\"healthy\", \"warning\", \"violation\", \"paused\"].includes(value);\n}\n\nexport function healthRank(state: HealthState): number {\n switch (state) {\n case \"healthy\":\n return 0;\n case \"warning\":\n return 1;\n case \"paused\":\n return 2;\n case \"violation\":\n return 3;\n default:\n return 99;\n }\n}\n\nexport function pickWorstHealth(records: ObjectiveHealth[]): ObjectiveHealth | null {\n if (records.length === 0) return null;\n return [...records].sort((a, b) => healthRank(b.state) - healthRank(a.state))[0] ?? null;\n}\n","/**\n * @fileoverview Timeline event contracts for append-only operator narratives.\n */\n\nexport type TimelineEventType =\n | \"objective_created\"\n | \"objective_updated\"\n | \"objective_paused\"\n | \"objective_resumed\"\n | \"health_changed\"\n | \"violation_detected\"\n | \"evaluation_started\"\n | \"execution_started\"\n | \"execution_completed\"\n | \"market_event_applied\"\n | \"objective_restored\"\n | \"capital_provisioned\"\n | \"capital_cleared\"\n | \"capital_synced\";\n\nexport interface TimelineEvent {\n id: string;\n objectiveId: string | null;\n type: TimelineEventType;\n message: string;\n payload: Record<string, unknown>;\n createdAt: string;\n}\n\nexport const TIMELINE_EVENT_TYPES: readonly TimelineEventType[] = [\n \"objective_created\",\n \"objective_updated\",\n \"objective_paused\",\n \"objective_resumed\",\n \"health_changed\",\n \"violation_detected\",\n \"evaluation_started\",\n \"execution_started\",\n \"execution_completed\",\n \"market_event_applied\",\n \"objective_restored\",\n \"capital_provisioned\",\n \"capital_cleared\",\n \"capital_synced\",\n] as const;\n\nexport function isTimelineEventType(value: string): value is TimelineEventType {\n return (TIMELINE_EVENT_TYPES as readonly string[]).includes(value);\n}\n\nexport function filterTimelineByObjective(\n events: TimelineEvent[],\n objectiveId: string\n): TimelineEvent[] {\n return events.filter((event) => event.objectiveId === objectiveId);\n}\n","/**\n * @fileoverview Execution receipt + restore-plan types.\n *\n * Receipts may settle as vault on-chain rebalance (`settlement: \"vault\"`) or\n * as a staged capital-book update (`settlement: \"staged\"`) when the vault\n * path is unavailable. Wrap/unwrap ETH↔WETH is client-side via RestorePlan.\n */\n\nexport interface ExecutionReceipt {\n id: string;\n objectiveId: string;\n status: \"pending\" | \"submitted\" | \"confirmed\" | \"failed\";\n transactionHash: string;\n action: string;\n notionalAdjustedUsd: number;\n result: string;\n createdAt: string;\n confirmedAt: string | null;\n /**\n * `\"vault\"`: keeper rebalance confirmed (or pending_vault_* then confirmed).\n * `\"staged\"`: capital-book restore only (honest non-finality label).\n */\n settlement?: \"staged\" | \"vault\";\n}\n\n/** Client-side restore action: wrap/unwrap ETH↔WETH or keeper vault swap. */\nexport type RestorePlanKind = \"wrap_eth\" | \"unwrap_weth\" | \"vault_swap\";\n\nexport interface RestorePlan {\n kind: RestorePlanKind;\n amountHuman: string;\n approxUsd: number;\n message: string;\n sellSymbol?: string;\n buySymbol?: string;\n}\n\nexport function isConfirmedExecution(receipt: ExecutionReceipt): boolean {\n return receipt.status === \"confirmed\" && Boolean(receipt.confirmedAt);\n}\n\nexport function shortTransactionHash(hash: string, head = 10, tail = 6): string {\n if (hash.length <= head + tail + 1) return hash;\n return `${hash.slice(0, head)}…${hash.slice(-tail)}`;\n}\n\nexport function sortExecutionsNewestFirst(\n receipts: ExecutionReceipt[]\n): ExecutionReceipt[] {\n return [...receipts].sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1));\n}\n\n/** True when the receipt claims vault (on-chain) settlement. */\nexport function isVaultSettlement(receipt: ExecutionReceipt): boolean {\n return receipt.settlement === \"vault\";\n}\n","/**\n * @fileoverview Optional structured logging hooks for SDK integrators.\n */\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport interface AureonLogger {\n debug(message: string, context?: Record<string, unknown>): void;\n info(message: string, context?: Record<string, unknown>): void;\n warn(message: string, context?: Record<string, unknown>): void;\n error(message: string, context?: Record<string, unknown>): void;\n}\n\nexport const silentLogger: AureonLogger = {\n debug() {},\n info() {},\n warn() {},\n error() {},\n};\n\nexport function createConsoleLogger(prefix = \"aureon-sdk\"): AureonLogger {\n const write = (level: LogLevel, message: string, context?: Record<string, unknown>) => {\n const line = `[${prefix}] ${message}`;\n if (level === \"error\") console.error(line, context ?? \"\");\n else if (level === \"warn\") console.warn(line, context ?? \"\");\n else console.log(line, context ?? \"\");\n };\n return {\n debug: (m, c) => write(\"debug\", m, c),\n info: (m, c) => write(\"info\", m, c),\n warn: (m, c) => write(\"warn\", m, c),\n error: (m, c) => write(\"error\", m, c),\n };\n}\n"]}
@@ -0,0 +1,205 @@
1
+ # Architecture Guide
2
+
3
+ This document provides a detailed breakdown of the AUREON system architecture. It outlines the components, data models, state machines, and cryptographic boundaries that govern the `@buildaureon/sdk` and its integration with the hosted AUREON API and the Robinhood Chain.
4
+
5
+ ---
6
+
7
+ ## 1. System Vision and Core Principles
8
+
9
+ AUREON acts as a decentralized, non-custodial "Financial Compass" (FCO) for digital assets. Instead of requiring users to execute manual, repetitive rebalancing trades or entrust their private keys to a centralized custodian, AUREON splits the system responsibilities:
10
+ 1. **Continuous Policy Tracking**: The AUREON Health and Watchdog Engines continuously monitor capital allocations against user-defined objectives (e.g. maintaining a 20% stablecoin sleeve).
11
+ 2. **Non-Custodial execution**: When allocations drift outside the allowed tolerance, the system generates execution plans. Rebalances are executed on-chain via Smart Vaults, but transaction signatures are produced locally by the user's wallet.
12
+
13
+ ---
14
+
15
+ ## 2. Component Architecture Overview
16
+
17
+ The system is organized into three major layers: the **Client Layer** (where the SDK resides), the **Gateway Layer** (which hosts the policy and pricing engines), and the **On-chain Layer** (where actual capital is settled).
18
+
19
+ ```mermaid
20
+ graph TB
21
+ subgraph ClientBoundary [Client / Host Application Boundary]
22
+ App[Agent / Operator Script]
23
+ SDK["@buildaureon/sdk Client"]
24
+ Session[Session Provider]
25
+ Signer[Local Wallet Signer]
26
+
27
+ App --> SDK
28
+ App --> Session
29
+ App --> Signer
30
+ end
31
+
32
+ subgraph GatewayBoundary [AUREON Hosted Gateway Layer]
33
+ API[AUREON API Gateway]
34
+ DB[(PostgreSQL / Ledger Store)]
35
+ Oracles[Price Oracle Indexer]
36
+
37
+ subgraph Engines [Core Engines]
38
+ Health[Health Evaluation Engine]
39
+ Watchdog[Watchdog Engine]
40
+ Planner[Restoration Planner]
41
+ end
42
+
43
+ API --> DB
44
+ API --> Engines
45
+ Oracles --> Engines
46
+ end
47
+
48
+ subgraph ChainBoundary [Robinhood Chain Blockchain Layer]
49
+ RPC[Secure Node RPC]
50
+ Vaults[AUREON Smart Vaults]
51
+ Keepers[Automated Keeper Network]
52
+
53
+ RPC --> Vaults
54
+ Keepers --> Vaults
55
+ end
56
+
57
+ %% Data and Control Flows
58
+ SDK -->|"HTTPS REST Calls"| API
59
+ Signer -->|"Broadcast Signed Steps"| RPC
60
+ API -->|"Read Blockchain State"| RPC
61
+ Keepers -->|"Automated Rebalance Swaps"| Vaults
62
+ ```
63
+
64
+ ### 2.1 The Client Layer
65
+ * **AureonClient**: The main class exported by `@buildaureon/sdk`. It coordinates REST requests, implements pre-flight input validation, maps HTTP errors to TypeScript classes, and manages retries.
66
+ * **Session Token Provider**: A stateful container that maintains the ephemeral JSON Web Token (JWT) retrieved during wallet signature verification.
67
+ * **Local Wallet Signer**: A private key management module (e.g. Viem, Ethers, or an HSM) controlled by the integrator. It signs transaction steps returned by the vault preparation endpoints.
68
+
69
+ ### 2.2 The Hosted Gateway Layer
70
+ * **API Gateway**: A Hono-based router exposing endpoints for managing objectives, synchronizing portfolio snapshots, preparing vault transactions, and querying timeline events.
71
+ * **Ledger Store**: A persistent relational database storing user-configured objectives, historic portfolio snapshots, execution receipts, and audit event logs.
72
+ * **Price Oracle Indexer**: Integrates with chain feeds to maintain real-time price feeds for all allowlisted vault assets.
73
+ * **Health Evaluation Engine**: Computes asset weights and checks deviations against objective targets.
74
+ * **Watchdog Engine**: Orchestrates the cron-like heartbeat check to verify if any active objective has entered a violation state.
75
+ * **Restoration Planner**: Computes the trade sizes and asset swaps needed to return a violating objective back to its target policy.
76
+
77
+ ### 2.3 The On-chain Layer
78
+ * **AUREON Smart Vaults**: ERC-20 and ERC-4626 compatible smart contracts deployed on the Robinhood Chain. They hold the user's custody-free rebalancing capital.
79
+ * **Automated Keeper Network**: Off-chain worker bots that listen for restoration plans, call the smart vaults with keeper signatures, and execute swaps via decentralized liquidity pools.
80
+
81
+ ---
82
+
83
+ ## 3. The Rebalancing Lifecycle
84
+
85
+ Rebalancing is the process of moving an objective from a `violation` state back to a `healthy` state. The lifecycle involves multiple steps between the SDK, the gateway, and the blockchain.
86
+
87
+ ```mermaid
88
+ sequenceDiagram
89
+ autonumber
90
+ participant Host as Host Agent / Script
91
+ participant SDK as Aureon SDK
92
+ participant API as Hosted API Gateway
93
+ participant Vault as Smart Vault (Robinhood Chain)
94
+
95
+ rect rgb(240, 248, 255)
96
+ Note over Host, API: Phase 1: Continuous Health Monitoring
97
+ Host->>SDK: refreshWatchdog()
98
+ SDK->>API: POST /watchdog/refresh
99
+ API->>API: Fetch current price feeds
100
+ API->>API: Evaluate active objective metrics
101
+ API-->>SDK: WatchdogRefreshResult (breaches array)
102
+ SDK-->>Host: Returns breaches & suggestions
103
+ end
104
+
105
+ rect rgb(255, 240, 245)
106
+ Note over Host, Vault: Phase 2: Restoration Planning
107
+ Host->>SDK: getRestorePlan(objectiveId)
108
+ SDK->>API: GET /objectives/:id/restore-plan
109
+ API->>API: Calculate optimal rebalance swaps
110
+ API-->>SDK: RestorePlan (vault_swap, amount, assets)
111
+ SDK-->>Host: Returns plan details
112
+ end
113
+
114
+ rect rgb(245, 255, 250)
115
+ Note over Host, Vault: Phase 3: Execution and Settlement
116
+ Host->>SDK: restoreObjective(objectiveId) (or runExecution)
117
+ SDK->>API: POST /executions/run
118
+ API->>Vault: Submit keeper-signed swap instruction
119
+ Vault->>Vault: Execute decentralized exchange swap
120
+ Vault-->>API: Emit Swap Log and TX Receipt
121
+ API-->>SDK: ExecutionReceipt (settlement: "vault", status: "confirmed")
122
+ SDK-->>Host: Return receipt with Transaction Hash
123
+ end
124
+ ```
125
+
126
+ ### 3.1 Step 1: Heartbeat Evaluation
127
+ The agent periodically calls `refreshWatchdog()`. The gateway retrieves the current token balances in the user's smart vault, fetches real-time mark prices, and computes the current allocation percentage.
128
+
129
+ ### 3.2 Step 2: Breach Detection
130
+ If the current allocation drifts beyond the tolerance window, the Health Engine flags the objective's state as `violation` and creates a `TimelineEvent` of type `violation_detected`.
131
+
132
+ ### 3.3 Step 3: Plan Generation
133
+ The restoration planner calculates the difference between the current weight and the target weight. It translates this difference into a target amount of tokens to buy or sell, package-wrapped inside a `RestorePlan`.
134
+
135
+ ### 3.4 Step 4: Execution
136
+ For automated objectives, calling `restoreObjective` instructs the gateway to dispatch a keeper rebalance transaction. The vault executes the trade using native liquidity, updating the token weights on-chain.
137
+
138
+ ### 3.5 Step 5: Confirmation
139
+ The transaction completes on the Robinhood Chain, and the gateway records an `ExecutionReceipt` with `settlement: "vault"` and `status: "confirmed"`, marking the objective status back to `healthy`.
140
+
141
+ ---
142
+
143
+ ## 4. Subsystem Details
144
+
145
+ ### 4.1 Health Evaluation Formulas
146
+ The Health Engine evaluates each of the four objective types using specific mathematical parameters:
147
+
148
+ 1. **Stable Allocation (`stable_allocation`)**:
149
+ * **Metric**: $W_{stable} = \frac{\sum \text{Notional}(StableCoins)}{\text{Total Portfolio Notional}}$
150
+ * **Condition**: Target Weight $T$ and Tolerance $t$. The sleeve is healthy if $|W_{stable} - T| \le t$.
151
+ * **Breach**: If $W_{stable} > T + t$, the planner generates a plan to sell stables. If $W_{stable} < T - t$, the planner generates a plan to buy stables.
152
+
153
+ 2. **Balanced Portfolio (`balanced_portfolio`)**:
154
+ * **Metric**: $W_{targetSymbol} = \frac{\text{Notional}(TargetSymbol)}{\text{Total Portfolio Notional}}$
155
+ * **Condition**: Target Weight $T$ and Tolerance $t$.
156
+ * **Breach**: Triggers rebalancing if the target asset drifts outside the tolerance window.
157
+
158
+ 3. **Risk Ceiling (`risk_ceiling`)**:
159
+ * **Metric**: $\text{RiskScore} = \sum (W_{asset} \times \text{VolatilityRisk}(Asset))$
160
+ * **Condition**: Risk Score must remain below $\text{maxRiskScore}$.
161
+ * **Breach**: Generates plans to swap highly volatile assets for stable assets if the portfolio risk exceeds the ceiling.
162
+
163
+ 4. **Reward Reinvestment (`reward_reinvestment`)**:
164
+ * **Metric**: $\text{AccumulatedRewards}$
165
+ * **Condition**: Automatically sweeps yield generated by vault positions.
166
+ * **Breach**: Triggers when accrued reward tokens exceed a cost-effective gas threshold, reinvesting them into the target sleeve.
167
+
168
+ ### 4.2 Non-Custodial Vault Deposits and Withdrawals
169
+ While rebalancing is handled by automated keepers, adding or removing funds from the vault requires manual developer wallet signatures.
170
+
171
+ ```mermaid
172
+ flowchart TD
173
+ Host[Host Application] -->|1. Request Calldata| SDK[Aureon SDK]
174
+ SDK -->|2. POST /vault/prepare-deposit| API[Aureon Gateway]
175
+ API -->|3. Compile ABI steps| SDK
176
+ SDK -->|4. Return Unsigned Steps| Host
177
+ Host -->|5. Sign steps locally| Wallet[Local Private Key]
178
+ Wallet -->|6. Broadcast Signed Calldata| Chain[Robinhood Chain RPC]
179
+ ```
180
+
181
+ 1. **Allowance Validation**: The SDK checks if the vault contract is approved to spend the target token. If not, it includes an `approve` step.
182
+ 2. **Deposit Compilation**: The gateway builds the transaction data for `deposit(amount)` or `depositETH(value)` calls.
183
+ 3. **Execution**: The host signs and broadcasts the steps. The vault smart contract issues shares to the user's address, which are subsequently indexed by the gateway's sync loops.
184
+
185
+ ---
186
+
187
+ ## 5. Trust and Security Postures
188
+
189
+ Integrators must understand the boundary lines between AUREON infrastructure and host applications:
190
+
191
+ * **API Key Scope**: API keys authenticate gateway access but cannot perform asset transfers. Compromising an API key does not give access to vault funds because withdrawals require direct owner signatures.
192
+ * **Signature Isolation**: Transactions are signed client-side. `@buildaureon/sdk` does not expose methods for loading private keys, keeping key storage isolated.
193
+ * **Keeper Swaps**: Keepers can only execute swaps within the allowlisted trading paths of the smart vault. They cannot transfer vault assets to third-party addresses.
194
+
195
+ ---
196
+
197
+ ## 6. Network Specifications
198
+
199
+ AUREON is deployed on the following network infrastructure:
200
+
201
+ * **Chain Name**: Robinhood Chain Testnet
202
+ * **Chain ID**: `46630`
203
+ * **Gas Token**: Native WETH / ETH
204
+ * **Block Explorer**: `https://explorer.robinhoodnet.org`
205
+ * **Oracles**: Private decentralized feeds push updates to vault-registered adapter contracts.
package/docs/auth.md ADDED
@@ -0,0 +1,215 @@
1
+ # Cryptographic Authentication Guide
2
+
3
+ AUREON combines classic API authentication with Web3 signature verification. This guide provides an in-depth technical explanation of the handshake flow, JWT payloads, and client integrations using standard EVM libraries.
4
+
5
+ ---
6
+
7
+ ## 1. Authentication Topology
8
+
9
+ Requests are validated using a dual-token header model.
10
+
11
+ ```mermaid
12
+ graph TD
13
+ Request[Client Request] --> KeyCheck{Has API Key?}
14
+ KeyCheck -->|No| Reject1[401 Unauthorized: Missing API Key]
15
+ KeyCheck -->|Yes| RouteCheck{Is Route Public?}
16
+ RouteCheck -->|Yes| Allow[Process Request]
17
+ RouteCheck -->|No| BearerCheck{Has Valid Bearer JWT?}
18
+ BearerCheck -->|No| Reject2[401 Unauthorized: Missing Session Token]
19
+ BearerCheck -->|Yes| ScopeCheck{Is Token Bound to Target Wallet?}
20
+ ScopeCheck -->|No| Reject3[403 Forbidden: Wallet Mismatch]
21
+ ScopeCheck -->|Yes| Process[Process request]
22
+ ```
23
+
24
+ * **API Key (`X-Aureon-Api-Key`)**: Sent in the headers to identify your product subscription or server deployment. It is generated in the developer dashboard.
25
+ * **Bearer JWT (`Authorization: Bearer <token>`)**: Establishes session ownership. It is generated dynamically by signing a server-issued challenge message with your private key.
26
+
27
+ ---
28
+
29
+ ## 2. EIP-191 Cryptographic Handshake
30
+
31
+ The signature validation relies on the EIP-191 standard for signing personal messages. The process prevents replay attacks and ensures session integrity.
32
+
33
+ ```mermaid
34
+ sequenceDiagram
35
+ autonumber
36
+ participant Client as SDK Client
37
+ participant Gateway as Aureon Gateway
38
+ participant Signer as Wallet Signer (EIP-191)
39
+
40
+ Client->>Gateway: GET /auth/nonce?address=0x742...
41
+ Gateway->>Gateway: Generate unique nonce & expiresAt
42
+ Gateway-->>Client: Challenge (nonce, message, expiresAt)
43
+ Client->>Signer: Request signature over message
44
+ Signer->>Signer: Sign message using private key (personal_sign)
45
+ Signer-->>Client: Cryptographic Signature (65-byte hex string)
46
+ Client->>Gateway: POST /auth/verify { address, message, signature }
47
+ Gateway->>Gateway: Recover signer address from signature
48
+ alt Recovered Address == Input Address and Not Expired
49
+ Gateway->>Gateway: Generate JWT (Expires in 24 hours)
50
+ Gateway-->>Client: AuthSessionResponse (token, expiresAt)
51
+ else Validation Failed
52
+ Gateway-->>Client: Throw 401 ValidationError
53
+ end
54
+ ```
55
+
56
+ ### 2.1 The Challenge Message Schema
57
+ The message returned by `/auth/nonce` follows a strict structure:
58
+ ```text
59
+ AUREON Login Challenge
60
+ Wallet: 0x742d35Cc6634C0532925a3b844Bc454e4438f44e
61
+ Nonce: c8a99478fcd9185a494f
62
+ Timestamp: 2026-07-15T22:45:00.000Z
63
+ Expires: 2026-07-15T22:50:00.000Z
64
+
65
+ Sign this message to prove ownership of the wallet.
66
+ ```
67
+ * **Nonce**: A cryptographically secure random string preventing replay attacks.
68
+ * **Expires**: The timestamp (5-minute TTL) after which the challenge becomes invalid.
69
+
70
+ ---
71
+
72
+ ## 3. JWT Payload Structure
73
+
74
+ Upon successful signature recovery, the gateway issues a JSON Web Token containing the session metadata:
75
+
76
+ ```json
77
+ {
78
+ "sub": "0x742d35cc6634c0532925a3b844bc454e4438f44e",
79
+ "iss": "aureon-auth-service",
80
+ "iat": 1784155500,
81
+ "exp": 1784241900,
82
+ "sid": "sess_01h8v12x8p8p3z2v1q45r3m2e1",
83
+ "scope": "operator"
84
+ }
85
+ ```
86
+
87
+ * **`sub` (Subject)**: The lowercase Ethereum address of the authenticated wallet.
88
+ * **`exp` (Expiration)**: Unix timestamp set exactly 24 hours after token issuance.
89
+ * **`scope`**: Defines operational permissions (e.g. `operator`, `read-only`).
90
+
91
+ ---
92
+
93
+ ## 4. Multi-Framework Integration Examples
94
+
95
+ ### 4.1 Integration via Viem (TypeScript / Node.js)
96
+ Ideal for background cron daemons, keepers, and automated scripts.
97
+
98
+ ```ts
99
+ import { createAureonClient, createSessionTokenProvider } from "@buildaureon/sdk";
100
+ import { createWalletClient, http } from "viem";
101
+ import { privateKeyToAccount } from "viem/accounts";
102
+ import { mainnet } from "viem/chains";
103
+
104
+ async function authenticateAgent() {
105
+ const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
106
+ const wallet = createWalletClient({
107
+ account,
108
+ chain: mainnet,
109
+ transport: http()
110
+ });
111
+
112
+ const session = createSessionTokenProvider(null);
113
+ const aureon = createAureonClient({
114
+ apiKey: process.env.AUREON_API_KEY,
115
+ getAccessToken: session.getAccessToken
116
+ });
117
+
118
+ // 1. Get nonce
119
+ const { message } = await aureon.getAuthNonce(account.address);
120
+
121
+ // 2. Sign EIP-191 message
122
+ const signature = await wallet.signMessage({ message });
123
+
124
+ // 3. Verify on server
125
+ const login = await aureon.verifyWallet({
126
+ address: account.address,
127
+ message,
128
+ signature
129
+ });
130
+
131
+ session.setToken(login.token);
132
+ return aureon;
133
+ }
134
+ ```
135
+
136
+ ### 4.2 Integration via Ethers.js v6
137
+ Useful for traditional Node.js servers or scripts using Ethers.
138
+
139
+ ```ts
140
+ import { createAureonClient, createSessionTokenProvider } from "@buildaureon/sdk";
141
+ import { Wallet } from "ethers";
142
+
143
+ async function authenticateEthers() {
144
+ const wallet = new Wallet(process.env.PRIVATE_KEY!);
145
+ const session = createSessionTokenProvider(null);
146
+ const aureon = createAureonClient({
147
+ apiKey: process.env.AUREON_API_KEY,
148
+ getAccessToken: session.getAccessToken
149
+ });
150
+
151
+ const { message } = await aureon.getAuthNonce(wallet.address);
152
+ const signature = await wallet.signMessage(message);
153
+
154
+ const login = await aureon.verifyWallet({
155
+ address: wallet.address,
156
+ message,
157
+ signature
158
+ });
159
+
160
+ session.setToken(login.token);
161
+ return aureon;
162
+ }
163
+ ```
164
+
165
+ ### 4.3 Integration in Browser Frontends (window.ethereum)
166
+ Suitable for operator portals and user-facing dashboards.
167
+
168
+ ```ts
169
+ import { createAureonClient, createSessionTokenProvider } from "@buildaureon/sdk";
170
+
171
+ async function loginBrowser() {
172
+ if (!window.ethereum) throw new Error("No provider found");
173
+
174
+ const [address] = await window.ethereum.request({ method: "eth_requestAccounts" });
175
+ const session = createSessionTokenProvider(localStorage.getItem("aureon_token"));
176
+
177
+ const aureon = createAureonClient({
178
+ apiKey: process.env.AUREON_API_KEY,
179
+ getAccessToken: session.getAccessToken
180
+ });
181
+
182
+ try {
183
+ // Validate current token
184
+ await aureon.me();
185
+ } catch (err) {
186
+ // Fetch new challenge
187
+ const { message } = await aureon.getAuthNonce(address);
188
+
189
+ // Sign using browser extension wallet
190
+ const signature = await window.ethereum.request({
191
+ method: "personal_sign",
192
+ params: [message, address]
193
+ });
194
+
195
+ const login = await aureon.verifyWallet({ address, message, signature });
196
+ session.setToken(login.token);
197
+ localStorage.setItem("aureon_token", login.token);
198
+ }
199
+
200
+ return aureon;
201
+ }
202
+ ```
203
+
204
+ ---
205
+
206
+ ## 5. Token Lifecycle and Recovery
207
+
208
+ * **Handling Token Expirations**: When a session token expires, the gateway returns a `401 UNAUTHORIZED` error. Integrators should register a callback in their request loops to renew the token automatically.
209
+ * **Multi-Wallet Routing**: If your application manages multiple vaults, instantiate separate `AureonClient` instances for each session token provider. Portfolios are partitioned by wallet address.
210
+ * **Logout Mechanics**: Invoking `aureon.logout()` invalidates the JWT on the gateway. The local cache should be cleared immediately:
211
+ ```ts
212
+ await aureon.logout();
213
+ session.clear();
214
+ localStorage.removeItem("aureon_token");
215
+ ```