import {z} from 'zod' export type AssetIDTarget = {type: 'asset_id', identifier: string}; export type ContractCallMetric = {type: 'contract_call', target: AssetIDTarget, function_name: string, function_args?: Array | undefined, return_field_index?: number | undefined}; export type ReadObjectMetric = {type: 'read_object', target: AssetIDTarget, field_path: string}; export type HMACAuthentication = {type: 'hmac', hmac_secret: string}; export type AuthorizationHeaderAuthentication = {type: 'authorization_header', value: string}; export type APIKeyAuthorization = {type: 'api_key', header_name: string, api_key: string}; export type BasicAuth = {type: 'basic_auth', username: string, password: string}; export type Authentication = HMACAuthentication | AuthorizationHeaderAuthentication | APIKeyAuthorization | BasicAuth; export type APICallMetric = {type: 'api_call', url: string, method: 'GET' | 'POST', authentication?: Authentication | undefined, query_params?: Record | undefined, content_type: 'application/json' | 'text/plain', extra_headers?: Record | undefined, sample_interval_seconds: number, field_path: string, body?: string | undefined}; export type AssetTagTarget = {type: 'asset_tag', identifier: string}; export type TransferMetric = {type: 'transfer', from: {operator: 'in' | 'not_in', target: Array}, to: {operator: 'in' | 'not_in', target: Array}}; export type ComputedMetric = {type: 'computed_metric', metrics: Array<{symbol: string, metric_id: string}>, formula: string}; export type EventMetric = {type: 'event_metric', target: AssetIDTarget, event_name: string, output_field: string, event_filters?: (Array<{parameter_name: string, parameter_value: string | number}>) | undefined}; export type SolanaAccountInfoReadMetric = {type: 'solana_account_info_read', target: AssetIDTarget, abi: {metadata: {offset: number, length: number}, field_path: string}}; export type SolanaInstructionMetric = {type: 'solana_instruction', target: AssetIDTarget, instruction_name: string, output_field: string, instruction_filters?: Array<{parameter_name: string, parameter_value: string}> | undefined}; export type MetricsRequest = ContractCallMetric | ReadObjectMetric | APICallMetric | TransferMetric | ComputedMetric | EventMetric | SolanaAccountInfoReadMetric | SolanaInstructionMetric; export type PatchApiV0PlatformMetricsIdArgs = {id: string, body: {name?: string | undefined, data?: MetricsRequest | undefined}}; export type PatchApiV0PlatformMetricsIdOptions = {baseUrl?: string | undefined, APIKey?: string | undefined, fetch?: typeof fetch | undefined}; export const assetIDTarget = z.object({type: z.literal("asset_id"), identifier: z.string()}); export const contractCallMetric = z.object({type: z.literal("contract_call"), target: assetIDTarget, function_name: z.string(), function_args: z.array(z.string()).optional(), return_field_index: z.number().int().optional()}); export const readObjectMetric = z.object({type: z.literal("read_object"), target: assetIDTarget, field_path: z.string()}); export const hMACAuthentication = z.object({type: z.literal("hmac"), hmac_secret: z.string()}); export const authorizationHeaderAuthentication = z.object({type: z.literal("authorization_header"), value: z.string()}); export const aPIKeyAuthorization = z.object({type: z.literal("api_key"), header_name: z.string(), api_key: z.string()}); export const basicAuth = z.object({type: z.literal("basic_auth"), username: z.string(), password: z.string()}); export const authentication = z.union([hMACAuthentication, authorizationHeaderAuthentication, aPIKeyAuthorization, basicAuth]); export const aPICallMetric = z.object({type: z.literal("api_call"), url: z.string(), method: z.enum(["GET", "POST"]), authentication: authentication.optional(), query_params: z.object({}).optional(), content_type: z.enum(["application/json", "text/plain"]), extra_headers: z.object({}).optional(), sample_interval_seconds: z.number().int(), field_path: z.string(), body: z.string().optional()}); export const assetTagTarget = z.object({type: z.literal("asset_tag"), identifier: z.string()}); export const transferMetric = z.object({type: z.literal("transfer"), from: z.object({operator: z.enum(["in", "not_in"]), target: z.array(z.union([assetTagTarget, assetIDTarget]))}), to: z.object({operator: z.enum(["in", "not_in"]), target: z.array(z.union([assetTagTarget, assetIDTarget]))})}); export const computedMetric = z.object({type: z.literal("computed_metric"), metrics: z.array(z.object({symbol: z.string(), metric_id: z.string()})), formula: z.string()}); export const eventMetric = z.object({type: z.literal("event_metric"), target: assetIDTarget, event_name: z.string(), output_field: z.string(), event_filters: z.array(z.object({parameter_name: z.string(), parameter_value: z.union([z.string(), z.number().int()])})).optional()}); export const solanaAccountInfoReadMetric = z.object({type: z.literal("solana_account_info_read"), target: assetIDTarget, abi: z.object({metadata: z.object({offset: z.number().int(), length: z.number().int()}), field_path: z.string()})}); export const solanaInstructionMetric = z.object({type: z.literal("solana_instruction"), target: assetIDTarget, instruction_name: z.string(), output_field: z.string(), instruction_filters: z.array(z.object({parameter_name: z.string(), parameter_value: z.string()})).optional()}); export const metricsResponse = z.union([contractCallMetric, readObjectMetric, aPICallMetric, transferMetric, computedMetric, eventMetric, solanaAccountInfoReadMetric, solanaInstructionMetric]); export const metricObject = z.object({kind: z.literal("metric"), id: z.string(), name: z.string(), data: metricsResponse, created_at: z.string(), added_by: z.string(), skipped_asset_ids: z.array(z.string()).nullable().optional()}); export const assetLabelTarget = z.object({type: z.literal("asset_label"), identifier: z.string()}); export const assetIDExcludeTarget = z.object({type: z.literal("exclude_asset_id"), identifier: z.string()}); export const metricParentObject = z.object({kind: z.literal("metric_parent"), id: z.string(), name: z.string(), sampler_type: z.string().nullable().optional(), runtime: z.string().nullable().optional(), target: z.array(z.union([assetIDTarget, assetTagTarget, assetLabelTarget, assetIDExcludeTarget])), data: metricsResponse.optional(), function_signature: z.string().nullable().optional(), created_at: z.string(), added_by: z.string().nullable().optional(), skipped_asset_ids: z.array(z.string()).nullable().optional()}); export const patchApiV0PlatformMetricsIdResponse = z.discriminatedUnion("kind", [metricObject, metricParentObject]); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Update Metric * * PATCH /v0/platform/metrics/{id} * * Also accepts auth: ClientID, JWT */ export const patchApiV0PlatformMetricsId = async (args: PatchApiV0PlatformMetricsIdArgs, options?: PatchApiV0PlatformMetricsIdOptions) => { const {baseUrl = "https://api.blockaid.io", fetch: fetchFn = fetch, APIKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (APIKey !== undefined) headers.set("X-API-Key", APIKey) const url = `${baseUrl.replace(/\/+$/, '')}/v0/platform/metrics/${encodeURIComponent(String(args.id))}${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "PATCH", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(patchApiV0PlatformMetricsIdResponse, await res.json()) };