@cosmosapp/pay_sdk 1.2.0 → 2.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/LICENSE +0 -75
  3. package/NOTICE +8 -0
  4. package/README.md +15 -18
  5. package/dist/chunk-AYVWYEOK.js +62 -0
  6. package/dist/chunk-AYVWYEOK.js.map +1 -0
  7. package/dist/{chunk-TZDZBVFS.js → chunk-TM4HAKWE.js} +5 -3
  8. package/dist/chunk-TM4HAKWE.js.map +1 -0
  9. package/dist/cosmosProvider-CFASjnd5.d.cts +100 -0
  10. package/dist/cosmosProvider-CFASjnd5.d.ts +100 -0
  11. package/dist/index.cjs +739 -3
  12. package/dist/index.cjs.map +1 -1
  13. package/dist/index.d.cts +618 -6
  14. package/dist/index.d.ts +618 -6
  15. package/dist/index.js +731 -5
  16. package/dist/index.js.map +1 -1
  17. package/dist/intent-input-BtUp3tFN.d.cts +1697 -0
  18. package/dist/intent-input-BtUp3tFN.d.ts +1697 -0
  19. package/dist/swk/index.cjs +170 -0
  20. package/dist/swk/index.cjs.map +1 -0
  21. package/dist/swk/index.d.cts +207 -0
  22. package/dist/swk/index.d.ts +207 -0
  23. package/dist/swk/index.js +106 -0
  24. package/dist/swk/index.js.map +1 -0
  25. package/dist/web/index.cjs +129 -2
  26. package/dist/web/index.cjs.map +1 -1
  27. package/dist/web/index.d.cts +49 -4
  28. package/dist/web/index.d.ts +49 -4
  29. package/dist/web/index.js +67 -4
  30. package/dist/web/index.js.map +1 -1
  31. package/llms/03-quickstart.md +4 -4
  32. package/llms/05-payment-intents.md +6 -2
  33. package/llms/08-products-customers.md +1 -1
  34. package/llms/13-types-reference.md +1 -1
  35. package/llms/14-recipes.md +14 -8
  36. package/llms/llms-full.txt +26 -16
  37. package/package.json +17 -6
  38. package/dist/chunk-TZDZBVFS.js.map +0 -1
  39. package/dist/intent-input-Ch8ogEg-.d.cts +0 -750
  40. package/dist/intent-input-Ch8ogEg-.d.ts +0 -750
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/managers/AnalyticsManager.ts","../src/structures/Base.ts","../src/structures/Customer.ts","../src/managers/BaseManager.ts","../src/managers/CustomerManager.ts","../src/managers/HealthManager.ts","../src/types/index.ts","../src/structures/PaymentIntent.ts","../src/common/addresses.ts","../src/common/assets.ts","../src/common/intent-input.ts","../src/managers/PaymentIntentManager.ts","../src/structures/Product.ts","../src/managers/ProductManager.ts","../src/structures/Swap.ts","../src/managers/SwapManager.ts","../src/structures/WebhookDelivery.ts","../src/structures/WebhookEndpoint.ts","../src/util/Constants.ts","../src/util/Webhooks.ts","../src/managers/WebhookManager.ts","../src/errors/CosmosPayError.ts","../src/rest/REST.ts","../src/util/shared.ts","../src/client/Client.ts","../src/common/wallets.ts"],"names":["EventEmitter","createHmac","timingSafeEqual"],"mappings":";;;;;;;;AAaO,IAAM,mBAAN,MAAuB;AAAA,EAG5B,YAAY,MAAA,EAAgB;AAC1B,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AAAA,EAEA,IAAY,IAAA,GAAa;AACvB,IAAA,OAAO,KAAK,MAAA,CAAO,IAAA;AAAA,EACrB;AAAA;AAAA,EAGO,OAAA,GAAyC;AAC9C,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAA0B,UAAU,CAAA;AAAA,EACvD;AAAA;AAAA,EAGO,QAAA,GAA2C;AAChD,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAA2B,WAAW,CAAA;AAAA,EACzD;AAAA;AAAA,EAGO,OAAA,GAAgC;AACrC,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAAiB,OAAO,CAAA;AAAA,EAC3C;AAAA;AAAA,EAGO,WAAA,GAAwC;AAC7C,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAAqB,gBAAgB,CAAA;AAAA,EACxD;AACF;;;ACpCO,IAA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AAI,CAAA;AACjC,IAAA,IAAA,CAAK,SAAA,GAAY,IAAI,eAAA,CAAgB,IAAI,CAAA;AACzC,IAAA,IAAA,CAAK,SAAA,GAAY,IAAI,gBAAA,CAAiB,IAAI,CAAA;AAC1C,IAAA,IAAA,CAAK,MAAA,GAAS,IAAI,aAAA,CAAc,IAAI,CAAA;AAAA,EACtC;AAAA;AAAA,EAGO,UAAU,MAAA,EAAsB;AACrC,IAAA,IAAA,CAAK,IAAA,CAAK,UAAU,MAAM,CAAA;AAC1B,IAAA,OAAO,IAAA;AAAA,EACT;AAAA;AAAA,EAGO,iBAAiB,MAAA,EAAsB;AAC5C,IAAA,IAAA,CAAK,aAAA,GAAgB,MAAA;AACrB,IAAA,OAAO,IAAA;AAAA,EACT;AAAA;AAAA,EAGO,qBAAA,CAAsB,QAAgB,gBAAA,EAAgC;AAC3E,IAAA,IAAA,CAAK,IAAA,CAAK,qBAAA,CAAsB,MAAA,EAAQ,gBAAgB,CAAA;AACxD,IAAA,OAAO,IAAA;AAAA,EACT;AACF;;;ACpMO,IAAM,OAAA,GAAU;AAAA,EACrB,SAAA,EAAW,WAAA;AAAA,EACX,KAAA,EAAO,OAAA;AAAA,EACP,KAAA,EAAO,OAAA;AAAA,EACP,MAAA,EAAQ,QAAA;AAAA,EACR,MAAA,EAAQ;AACV","file":"index.cjs","sourcesContent":["import type { Client } from '@/client/Client';\nimport type { REST } from '@/rest/REST';\nimport type {\n AnalyticsBalancesData,\n AnalyticsSummaryData,\n ApiLogsData,\n WebhookLogsData,\n} from '@/types/index';\n\n/**\n * Read-only analytics derived from the consumer's intents and deliveries —\n * `client.analytics`. Powers dashboard-style Overview / Balances / Logs views.\n */\nexport class AnalyticsManager {\n public readonly client: Client;\n\n constructor(client: Client) {\n this.client = client;\n }\n\n private get rest(): REST {\n return this.client.rest;\n }\n\n /** Overview metrics: totals, settled volume, webhook health, 30-day series. */\n public summary(): Promise<AnalyticsSummaryData> {\n return this.rest.get<AnalyticsSummaryData>('/summary');\n }\n\n /** Settled (and pending) amount per asset. */\n public balances(): Promise<AnalyticsBalancesData> {\n return this.rest.get<AnalyticsBalancesData>('/balances');\n }\n\n /** Recent API requests reaching the service (with details). */\n public apiLogs(): Promise<ApiLogsData> {\n return this.rest.get<ApiLogsData>('/logs');\n }\n\n /** Recent webhook deliveries across all endpoints (with details). */\n public webhookLogs(): Promise<WebhookLogsData> {\n return this.rest.get<WebhookLogsData>('/logs/webhooks');\n }\n}\n","import type { Client } from '@/client/Client';\n\n/**\n * Root of every API structure. Holds a back-reference to the {@link Client} so\n * instances can perform their own actions (e.g. `paymentIntent.delete()`), and\n * provides the `_patch`/`toJSON` plumbing shared by all structures.\n */\nexport abstract class Base<Data extends { id: string }> {\n /** The client that instantiated this structure. */\n public readonly client: Client;\n /** Unique identifier of the resource. */\n public id!: string;\n\n protected constructor(client: Client, data: Data) {\n this.client = client;\n this._patch(data);\n }\n\n /** Merge raw API data onto this instance. Subclasses override and call super. */\n protected _patch(data: Data): this {\n this.id = data.id;\n return this;\n }\n\n /** Return the raw API representation of this structure. */\n public abstract toJSON(): Data;\n\n /** Allow `String(structure)` / template literals to resolve to the id. */\n public valueOf(): string {\n return this.id;\n }\n}\n","import type { Client } from '@/client/Client';\nimport type { CustomerData, UpdateCustomerOptions } from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/** A customer record, optionally enriched with on-chain payment stats. */\nexport class Customer extends Base<CustomerData> {\n public consumerId!: string;\n public name!: string;\n public alias!: string | null;\n public note!: string | null;\n public email!: string | null;\n /** Optional Stellar account associated with the customer. */\n public account!: string | null;\n public reference!: string | null;\n public createdAt!: Date;\n public updatedAt!: Date;\n /** Number of payment intents from this customer's account (list view only). */\n public payments: number | null = null;\n /** Number of succeeded payments (list view only). */\n public succeeded: number | null = null;\n /** Total settled amount as a decimal string (list view only). */\n public total: string | null = null;\n\n constructor(client: Client, data: CustomerData) {\n super(client, data);\n }\n\n protected override _patch(data: CustomerData): this {\n super._patch(data);\n this.consumerId = data.consumerId;\n this.name = data.name;\n this.alias = data.alias;\n this.note = data.note;\n this.email = data.email;\n this.account = data.account;\n this.reference = data.reference;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n if (data.payments !== undefined) this.payments = data.payments;\n if (data.succeeded !== undefined) this.succeeded = data.succeeded;\n if (data.total !== undefined) this.total = data.total;\n return this;\n }\n\n /** Re-fetch this customer. */\n public fetch(): Promise<Customer> {\n return this.client.customers.fetch(this.id);\n }\n\n /** Update this customer. Mutates and returns this. */\n public async edit(options: UpdateCustomerOptions): Promise<this> {\n const updated = await this.client.customers.update(this.id, options);\n return this._patch(updated.toJSON());\n }\n\n /** Delete this customer. */\n public delete() {\n return this.client.customers.delete(this.id);\n }\n\n public toJSON(): CustomerData {\n return {\n id: this.id,\n consumerId: this.consumerId,\n name: this.name,\n alias: this.alias,\n note: this.note,\n email: this.email,\n account: this.account,\n reference: this.reference,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n ...(this.payments !== null ? { payments: this.payments } : {}),\n ...(this.succeeded !== null ? { succeeded: this.succeeded } : {}),\n ...(this.total !== null ? { total: this.total } : {}),\n };\n }\n}\n","import { EventEmitter } from 'node:events';\nimport type { Client } from '@/client/Client';\nimport type { REST } from '@/rest/REST';\n\n/**\n * Base class for all resource managers. Each manager owns a slice of the API\n * (payment intents, webhooks, ...) and a lightweight in-memory cache of the\n * structures it has materialized — an atomic, per-resource manager pattern.\n *\n * Extends EventEmitter so managers that surface real-time events (e.g. the\n * webhook listener) can `emit`/`on` without extra plumbing.\n */\nexport abstract class BaseManager<\n Structure extends { id: string },\n> extends EventEmitter {\n public readonly client: Client;\n /** Cache of structures keyed by id, populated on fetch/create. */\n public readonly cache: Map<string, Structure> = new Map();\n\n constructor(client: Client) {\n super();\n this.client = client;\n }\n\n /** Shortcut to the shared REST instance. */\n protected get rest(): REST {\n return this.client.rest;\n }\n\n /** Store a structure in the cache and return it. */\n protected _add(structure: Structure): Structure {\n this.cache.set(structure.id, structure);\n return structure;\n }\n\n /** Resolve an id from either a raw id or a structure instance. */\n public resolveId(idOrStructure: string | { id: string }): string {\n return typeof idOrStructure === 'string' ? idOrStructure : idOrStructure.id;\n }\n}\n","import { Customer } from '@/structures/Customer';\nimport type {\n CreateCustomerOptions,\n CustomerData,\n CustomerListData,\n UpdateCustomerOptions,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\n\ntype CustomerDeletedData = { id: string; deleted: boolean };\n\n/**\n * Manages customers — `client.customers`.\n *\n * @example\n * const customer = await client.customers.create({\n * name: 'Acme Inc.', email: 'billing@acme.com',\n * });\n */\nexport class CustomerManager extends BaseManager<Customer> {\n private readonly route = '/customers';\n\n /** Create a customer. */\n public async create(options: CreateCustomerOptions): Promise<Customer> {\n const data = await this.rest.post<CustomerData>(this.route, { body: options });\n return this._add(new Customer(this.client, data));\n }\n\n /** List the consumer's customers (with payment stats). */\n public async list(): Promise<Customer[]> {\n const data = await this.rest.get<CustomerListData>(this.route);\n return data.data.map((d) => this._add(new Customer(this.client, d)));\n }\n\n /** Get a customer by id. */\n public async fetch(id: string): Promise<Customer> {\n const data = await this.rest.get<CustomerData>(`${this.route}/${id}`);\n return this._add(new Customer(this.client, data));\n }\n\n /** Update a customer. */\n public async update(\n id: string,\n options: UpdateCustomerOptions,\n ): Promise<Customer> {\n const data = await this.rest.patch<CustomerData>(`${this.route}/${id}`, {\n body: options,\n });\n return this._add(new Customer(this.client, data));\n }\n\n /** Delete a customer. */\n public async delete(id: string): Promise<CustomerDeletedData> {\n const result = await this.rest.delete<CustomerDeletedData>(\n `${this.route}/${id}`,\n );\n this.cache.delete(id);\n return result;\n }\n}\n","import type { Client } from '@/client/Client';\nimport type { REST } from '@/rest/REST';\nimport type { HealthCheckData } from '@/types/index';\n\n/**\n * Service health probes — `client.health`. These routes are public (they don't\n * require an authenticated consumer).\n */\nexport class HealthManager {\n public readonly client: Client;\n\n constructor(client: Client) {\n this.client = client;\n }\n\n private get rest(): REST {\n return this.client.rest;\n }\n\n /** Liveness probe — resolves when the service is up. */\n public async liveness(): Promise<boolean> {\n await this.rest.get<unknown>('/health/liveness');\n return true;\n }\n\n /** Readiness probe (checks the database). Returns the health report. */\n public readiness(): Promise<HealthCheckData> {\n return this.rest.get<HealthCheckData>('/health/readiness');\n }\n}\n","/**\n * Type definitions for the Cosmos Pay Payments API.\n *\n * These mirror the server's OpenAPI schema (Stellar SEP-7 payment intents,\n * webhooks, products, customers and analytics). Every type is exported so\n * TypeScript consumers get full intellisense; JavaScript consumers can ignore\n * them entirely.\n */\n\nimport type { AssetRef } from '@/common/assets';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Enums (provided both as runtime objects and as string-literal unions)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Lifecycle state of a payment intent. */\nexport const PaymentIntentStatus = {\n Pending: 'PENDING',\n Submitted: 'SUBMITTED',\n Succeeded: 'SUCCEEDED',\n Failed: 'FAILED',\n Cancelled: 'CANCELLED',\n Expired: 'EXPIRED',\n} as const;\nexport type PaymentIntentStatus =\n (typeof PaymentIntentStatus)[keyof typeof PaymentIntentStatus];\n\n/** SEP-7 operation a payment intent represents. */\nexport const PaymentIntentKind = {\n /** Source account is known → unsigned XDR + `web+stellar:tx` URI. */\n Tx: 'TX',\n /** No source → `web+stellar:pay` URI only (wallet picks the source). */\n Pay: 'PAY',\n} as const;\nexport type PaymentIntentKind =\n (typeof PaymentIntentKind)[keyof typeof PaymentIntentKind];\n\n/** Domain events an integrator can subscribe a webhook to. */\nexport const WebhookEventType = {\n PaymentIntentCreated: 'PAYMENT_INTENT_CREATED',\n PaymentIntentUpdated: 'PAYMENT_INTENT_UPDATED',\n PaymentIntentSucceeded: 'PAYMENT_INTENT_SUCCEEDED',\n PaymentIntentFailed: 'PAYMENT_INTENT_FAILED',\n PaymentIntentCancelled: 'PAYMENT_INTENT_CANCELLED',\n PaymentIntentDeleted: 'PAYMENT_INTENT_DELETED',\n} as const;\nexport type WebhookEventType =\n (typeof WebhookEventType)[keyof typeof WebhookEventType];\n\n/** Delivery state of a single webhook attempt. */\nexport const WebhookDeliveryStatus = {\n Pending: 'PENDING',\n Succeeded: 'SUCCEEDED',\n Failed: 'FAILED',\n} as const;\nexport type WebhookDeliveryStatus =\n (typeof WebhookDeliveryStatus)[keyof typeof WebhookDeliveryStatus];\n\n/** Product billing kind. */\nexport const ProductKind = {\n Recurring: 'recurring',\n OneTime: 'one_time',\n Link: 'link',\n} as const;\nexport type ProductKind = (typeof ProductKind)[keyof typeof ProductKind];\n\n/** Lifecycle state of a swap. */\nexport const SwapStatus = {\n Pending: 'PENDING',\n Submitted: 'SUBMITTED',\n Succeeded: 'SUCCEEDED',\n Failed: 'FAILED',\n Expired: 'EXPIRED',\n} as const;\nexport type SwapStatus = (typeof SwapStatus)[keyof typeof SwapStatus];\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Payment intents\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/payment-intents/tx`. */\nexport interface CreateTxPaymentIntentOptions {\n /** Payer's Stellar account — the transaction source. A registered address-book name also works. */\n source: string;\n /** Payee's Stellar account. A registered address-book name also works. */\n destination: string;\n /** Amount as a decimal string (max 7 decimals). */\n amount: string;\n /**\n * Typed asset (e.g. `Assets.USDC` or `defineAsset(...)`) — fills `assetCode`\n * and `assetIssuer` for you. Takes a back seat to explicit code/issuer below.\n */\n asset?: AssetRef;\n /** Asset code. Omit (or `XLM`/`native`) for native lumens. */\n assetCode?: string;\n /** Issuer account for a non-native asset. */\n assetIssuer?: string;\n /** MEMO_ID (numeric uint64) for idempotency + on-chain identification. Auto-generated when omitted. */\n memo?: string;\n /** SEP-7 `msg`: shown to the user in their wallet (≤ 300 chars). */\n msg?: string;\n /** SEP-7 `callback` where the wallet POSTs the signed XDR, e.g. `url:https://...`. */\n callback?: string;\n}\n\n/** Body for `POST /v1/payment-intents/pay`. */\nexport interface CreatePayPaymentIntentOptions {\n /** Payee's Stellar account. A registered address-book name also works. */\n destination: string;\n /** Amount the destination should receive. Omit to let the user enter it (e.g. donations). */\n amount?: string;\n /**\n * Typed asset (e.g. `Assets.USDC` or `defineAsset(...)`) — fills `assetCode`\n * and `assetIssuer` for you. Takes a back seat to explicit code/issuer below.\n */\n asset?: AssetRef;\n /** Asset code the destination receives. Omit for native lumens (XLM). */\n assetCode?: string;\n /** Issuer account for a non-native asset. */\n assetIssuer?: string;\n /** MEMO_ID (numeric uint64) for idempotency + on-chain identification. Auto-generated when omitted. */\n memo?: string;\n /** SEP-7 `msg`: shown to the user in their wallet (≤ 300 chars). */\n msg?: string;\n /** SEP-7 `callback`, e.g. `url:https://...`. */\n callback?: string;\n}\n\n/** Body for `PATCH /v1/payment-intents/:id`. */\nexport interface UpdatePaymentIntentOptions {\n status?: PaymentIntentStatus;\n /** Stellar transaction hash once the signed tx is submitted. */\n txHash?: string;\n /** Merchant reference. */\n reference?: string;\n}\n\n/** Query for `GET /v1/payment-intents`. */\nexport interface ListPaymentIntentsOptions {\n status?: PaymentIntentStatus;\n /** Page size (max 100, default 20). */\n take?: number;\n /** Offset (default 0). */\n skip?: number;\n}\n\n/** Raw payment intent payload returned by the API. */\nexport interface PaymentIntentData {\n id: string;\n kind: PaymentIntentKind;\n status: PaymentIntentStatus;\n network: string;\n source: string | null;\n destination: string;\n amount: string | null;\n asset: string;\n assetIssuer: string | null;\n memo: string;\n msg: string | null;\n callback: string | null;\n xdr: string | null;\n uri: string;\n qr: string;\n txHash: string | null;\n reference: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\n/** Raw paginated list of payment intents. */\nexport interface PaymentIntentListData {\n data: PaymentIntentData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Body for `POST /v1/payment-intents/:id/validate`. */\nexport interface ValidatePaymentIntentOptions {\n /** Hash of the submitted Stellar transaction to validate against this intent. */\n txHash: string;\n}\n\n/** Raw outcome of a validation attempt. */\nexport interface ValidationOutcomeData {\n valid: boolean;\n status: PaymentIntentStatus;\n reason?: string | null;\n paymentIntent?: PaymentIntentData;\n}\n\n/** Raw `{ id, deleted }` response. */\nexport interface DeletedData {\n id: string;\n deleted: boolean;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Webhooks\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/webhooks`. */\nexport interface CreateWebhookEndpointOptions {\n /** HTTPS URL that will receive POSTed event notifications. */\n url: string;\n description?: string;\n /** Event types to subscribe to. Omit/empty to receive all events. */\n eventTypes?: WebhookEventType[];\n}\n\n/** Body for `PATCH /v1/webhooks/:id`. */\nexport interface UpdateWebhookEndpointOptions {\n url?: string;\n description?: string;\n /** Pause/resume deliveries to this endpoint. */\n enabled?: boolean;\n eventTypes?: WebhookEventType[];\n}\n\n/** Raw webhook endpoint payload. */\nexport interface WebhookEndpointData {\n id: string;\n url: string;\n description: string | null;\n enabled: boolean;\n eventTypes: WebhookEventType[];\n createdAt: string;\n updatedAt: string;\n}\n\n/** Raw webhook endpoint payload including the one-time signing secret. */\nexport interface WebhookEndpointWithSecretData extends WebhookEndpointData {\n /** HMAC signing secret — shown once. Store it securely. */\n secret: string;\n}\n\n/** Raw result of a webhook ping. */\nexport interface WebhookPingData {\n ok: boolean;\n responseStatus: number | null;\n error: string | null;\n}\n\n/** Raw webhook delivery (audit) record. */\nexport interface WebhookDeliveryData {\n id: string;\n endpointId: string;\n eventType: WebhookEventType;\n eventId: string;\n payload: Record<string, unknown>;\n status: WebhookDeliveryStatus;\n attempts: number;\n responseStatus: number | null;\n error: string | null;\n lastAttemptAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\n/** Raw paginated list of webhook deliveries. */\nexport interface WebhookDeliveryListData {\n data: WebhookDeliveryData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Query for `GET /v1/webhooks/:id/deliveries`. */\nexport interface ListWebhookDeliveriesOptions {\n status?: WebhookDeliveryStatus;\n take?: number;\n skip?: number;\n}\n\n/** Shape of the JSON body POSTed to an integrator's webhook URL. */\nexport interface WebhookEvent<T = PaymentIntentData> {\n /** Stable event id (use for idempotency). */\n id: string;\n type: WebhookEventType;\n createdAt: string;\n data: T;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Products\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/products`. */\nexport interface CreateProductOptions {\n name: string;\n description?: string;\n /** Decimal price (≤ 7 decimals). Omit for a customer-set amount. */\n amount?: string;\n /** Asset code the price is in. Omit for native lumens (XLM). */\n assetCode?: string;\n kind?: ProductKind;\n active?: boolean;\n reference?: string;\n}\n\n/** Body for `PATCH /v1/products/:id`. */\nexport type UpdateProductOptions = Partial<CreateProductOptions>;\n\n/** Raw product payload. */\nexport interface ProductData {\n id: string;\n name: string;\n description: string | null;\n amount: string | null;\n asset: string;\n kind: ProductKind;\n active: boolean;\n reference: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Customers\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/customers`. */\nexport interface CreateCustomerOptions {\n name: string;\n alias?: string;\n note?: string;\n email?: string;\n /** Optional Stellar account to associate the customer with. */\n account?: string;\n reference?: string;\n}\n\n/** Body for `PATCH /v1/customers/:id`. */\nexport type UpdateCustomerOptions = Partial<CreateCustomerOptions>;\n\n/** Raw customer payload. */\nexport interface CustomerData {\n id: string;\n consumerId: string;\n name: string;\n alias: string | null;\n note: string | null;\n email: string | null;\n account: string | null;\n reference: string | null;\n createdAt: string;\n updatedAt: string;\n /** Derived on-chain stats (present in list responses). */\n payments?: number;\n succeeded?: number;\n total?: string;\n}\n\n/** Raw `{ data, total }` list of customers. */\nexport interface CustomerListData {\n data: CustomerData[];\n total: number;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Analytics\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface AnalyticsVolumeEntry {\n asset: string;\n amount: string;\n count: number;\n}\n\nexport interface AnalyticsSeriesPoint {\n date: string;\n count: number;\n volume: string;\n}\n\nexport interface AnalyticsRecentRow {\n id: string;\n kind: string;\n status: PaymentIntentStatus;\n amount: string | null;\n asset: string;\n destination: string;\n createdAt: string;\n}\n\n/** Raw overview metrics returned by `GET /v1/summary`. */\nexport interface AnalyticsSummaryData {\n totals: {\n all: number;\n succeeded: number;\n pending: number;\n submitted: number;\n failed: number;\n cancelled: number;\n expired: number;\n successRate: number;\n };\n volume: AnalyticsVolumeEntry[];\n webhooks: {\n endpoints: number;\n deliveries: number;\n failedDeliveries: number;\n };\n customers: number;\n series: AnalyticsSeriesPoint[];\n recent: AnalyticsRecentRow[];\n}\n\nexport interface AnalyticsBalanceEntry {\n asset: string;\n amount: string;\n pending: string;\n count: number;\n}\n\n/** Raw balances returned by `GET /v1/balances`. */\nexport interface AnalyticsBalancesData {\n data: AnalyticsBalanceEntry[];\n total: number;\n}\n\nexport interface ApiLogRow {\n id: string;\n method: string;\n path: string;\n statusCode: number;\n durationMs: number;\n ip: string | null;\n userAgent: string | null;\n status: 'ok' | 'pending' | 'fail';\n at: string;\n}\n\n/** Raw API request log returned by `GET /v1/logs`. */\nexport interface ApiLogsData {\n data: ApiLogRow[];\n total: number;\n}\n\nexport interface WebhookLogRow {\n id: string;\n endpointId: string;\n url: string | null;\n eventType: WebhookEventType;\n eventId: string;\n attempts: number;\n responseStatus: number | null;\n error: string | null;\n status: 'ok' | 'pending' | 'fail';\n at: string;\n}\n\n/** Raw webhook delivery log returned by `GET /v1/logs/webhooks`. */\nexport interface WebhookLogsData {\n data: WebhookLogRow[];\n total: number;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Health\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface HealthCheckData {\n status: string;\n info?: Record<string, { status: string } & Record<string, unknown>> | null;\n error?: Record<string, { status: string } & Record<string, unknown>> | null;\n details?: Record<string, { status: string } & Record<string, unknown>>;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Swaps\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/swaps/quote` (pricing only; no fee parameter — the fee is enforced server-side per organization). */\nexport interface QuoteSwapOptions {\n /** Amount to send, as a decimal string (max 7 decimals). */\n amount: string;\n /** Source asset code. Omit (or `XLM`/`native`) for native lumens. */\n sourceAssetCode?: string;\n /** Issuer account for a non-native source asset. */\n sourceAssetIssuer?: string;\n /** Destination asset code the swap should deliver. */\n destAssetCode: string;\n /** Issuer account for a non-native destination asset. */\n destAssetIssuer?: string;\n /** Allowed slippage in basis points. */\n slippageBps?: number;\n}\n\n/** Body for `POST /v1/swaps`. */\nexport interface CreateSwapOptions extends QuoteSwapOptions {\n /** Source account performing the swap. A registered address-book name also works. */\n source: string;\n /** Destination account that receives the swapped asset. Defaults to the source. */\n destination?: string;\n /** MEMO_ID (numeric uint64) for idempotency + on-chain identification. */\n memo?: string;\n}\n\n/** Body for `POST /v1/swaps/:id/submit`. */\nexport interface SubmitSwapOptions {\n /** Signed transaction envelope (base64 XDR) to relay to the network. */\n signedXdr: string;\n}\n\n/** Query for `GET /v1/swaps`. */\nexport interface ListSwapsOptions {\n status?: SwapStatus;\n /** Page size (max 100, default 20). */\n take?: number;\n /** Offset (default 0). */\n skip?: number;\n}\n\n/** Raw swap payload returned by the API. */\nexport interface SwapData {\n id: string;\n status: SwapStatus;\n network: string;\n source: string;\n destination: string;\n sendAsset: string;\n sendAssetIssuer: string | null;\n sendAmount: string;\n feeAmount: string;\n feeBps: number;\n swapAmount: string;\n destAsset: string;\n destAssetIssuer: string | null;\n destEstimated: string;\n destMin: string;\n slippageBps: number;\n path: { code: string; issuer: string | null }[];\n memo: string | null;\n xdr: string;\n uri: string;\n txHash: string;\n qr: string;\n createdAt: string;\n updatedAt: string;\n}\n\n/** Raw paginated list of swaps. */\nexport interface SwapListData {\n data: SwapData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Raw pricing quote returned by `POST /v1/swaps/quote`. */\nexport interface SwapQuoteData {\n network: string;\n source: { asset: string; issuer: string | null; amount: string };\n fee: { asset: string; issuer: string | null; amount: string; bps: number; wallet: string | null };\n swap: { asset: string; issuer: string | null; amount: string };\n destination: {\n asset: string;\n issuer: string | null;\n estimated: string;\n minimum: string;\n slippageBps: number;\n };\n path: { code: string; issuer: string | null }[];\n}\n\n/** Raw outcome of relaying a signed swap transaction. */\nexport interface SwapSubmitOutcomeData {\n submitted: boolean;\n status: SwapStatus;\n txHash?: string;\n reason?: string;\n resultCodes?: string[];\n swap: SwapData;\n}\n","import type { Client } from '@/client/Client';\nimport {\n PaymentIntentKind,\n PaymentIntentStatus,\n type PaymentIntentData,\n type UpdatePaymentIntentOptions,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/**\n * A Stellar SEP-7 payment intent.\n *\n * Wraps the raw API payload with typed accessors and atomic action methods so\n * you can operate on it directly: `await intent.validate(txHash)`,\n * `await intent.cancel()`, `await intent.delete()`.\n */\nexport class PaymentIntent extends Base<PaymentIntentData> {\n public kind!: PaymentIntentKind;\n public status!: PaymentIntentStatus;\n public network!: string;\n /** Payer account (null for PAY intents). */\n public source!: string | null;\n public destination!: string;\n public amount!: string | null;\n /** Asset code, or `native` for XLM. */\n public asset!: string;\n public assetIssuer!: string | null;\n /** Mandatory MEMO_ID. */\n public memo!: string;\n public msg!: string | null;\n public callback!: string | null;\n /** Unsigned transaction envelope (base64 XDR); null for PAY intents. */\n public xdr!: string | null;\n /** SEP-7 deep link (`tx` or `pay`). */\n public uri!: string;\n /** QR code of the SEP-7 URI (PNG data URL). */\n public qr!: string;\n public txHash!: string | null;\n public reference!: string | null;\n public createdAt!: Date;\n public updatedAt!: Date;\n\n constructor(client: Client, data: PaymentIntentData) {\n super(client, data);\n }\n\n protected override _patch(data: PaymentIntentData): this {\n super._patch(data);\n this.kind = data.kind;\n this.status = data.status;\n this.network = data.network;\n this.source = data.source;\n this.destination = data.destination;\n this.amount = data.amount;\n this.asset = data.asset;\n this.assetIssuer = data.assetIssuer;\n this.memo = data.memo;\n this.msg = data.msg;\n this.callback = data.callback;\n this.xdr = data.xdr;\n this.uri = data.uri;\n this.qr = data.qr;\n this.txHash = data.txHash;\n this.reference = data.reference;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n /** Whether this is a SEP-7 `tx` intent (known source, has XDR). */\n public get isTx(): boolean {\n return this.kind === PaymentIntentKind.Tx;\n }\n\n /** Whether this is a SEP-7 `pay` intent (no source). */\n public get isPay(): boolean {\n return this.kind === PaymentIntentKind.Pay;\n }\n\n /** Whether the payment has settled on-chain. */\n public get isSucceeded(): boolean {\n return this.status === PaymentIntentStatus.Succeeded;\n }\n\n /** Whether the intent is still awaiting payment. */\n public get isPending(): boolean {\n return this.status === PaymentIntentStatus.Pending;\n }\n\n /** Human-readable asset label (`XLM` for native). */\n public get assetLabel(): string {\n return !this.asset || this.asset === 'native' ? 'XLM' : this.asset;\n }\n\n /** Re-fetch this intent from the API, returning a fresh instance. */\n public fetch(): Promise<PaymentIntent> {\n return this.client.paymentIntents.fetch(this.id);\n }\n\n /** Update this intent (status / txHash / reference). Mutates and returns it. */\n public async edit(options: UpdatePaymentIntentOptions): Promise<this> {\n const updated = await this.client.paymentIntents.update(this.id, options);\n return this._patch(updated.toJSON());\n }\n\n /**\n * Validate a submitted transaction against this intent. On a match the status\n * is finalized server-side and the webhook fires.\n */\n public validate(txHash: string) {\n return this.client.paymentIntents.validate(this.id, { txHash });\n }\n\n /** Mark this intent as cancelled. */\n public cancel(): Promise<this> {\n return this.edit({ status: PaymentIntentStatus.Cancelled });\n }\n\n /** Delete this intent. */\n public delete() {\n return this.client.paymentIntents.delete(this.id);\n }\n\n public toJSON(): PaymentIntentData {\n return {\n id: this.id,\n kind: this.kind,\n status: this.status,\n network: this.network,\n source: this.source,\n destination: this.destination,\n amount: this.amount,\n asset: this.asset,\n assetIssuer: this.assetIssuer,\n memo: this.memo,\n msg: this.msg,\n callback: this.callback,\n xdr: this.xdr,\n uri: this.uri,\n qr: this.qr,\n txHash: this.txHash,\n reference: this.reference,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","/**\n * Stellar address helpers + a tiny named-address book.\n *\n * So integrators don't have to sprinkle raw `G...` strings everywhere (and risk\n * typos), they can name the accounts they care about once and reference them by\n * name. A plain address string always keeps working — `resolveAddress` only\n * substitutes registered names and otherwise passes the value straight through.\n */\n\n// Stellar strkeys are base32 (RFC 4648 alphabet, no padding). These checks are\n// length/prefix sanity checks, not full checksum validation.\nconst G_ADDRESS = /^G[A-Z2-7]{55}$/; // ed25519 public key (account)\nconst M_ADDRESS = /^M[A-Z2-7]{68}$/; // muxed account\nconst C_ADDRESS = /^C[A-Z2-7]{55}$/; // contract id\n\n/** Whether a value looks like a Stellar account address (`G…`). */\nexport function isStellarAddress(value: unknown): value is string {\n return typeof value === 'string' && G_ADDRESS.test(value);\n}\n\n/** Whether a value looks like a muxed account address (`M…`). */\nexport function isMuxedAddress(value: unknown): value is string {\n return typeof value === 'string' && M_ADDRESS.test(value);\n}\n\n/** Whether a value looks like a Soroban contract id (`C…`). */\nexport function isContractAddress(value: unknown): value is string {\n return typeof value === 'string' && C_ADDRESS.test(value);\n}\n\n/** Whether a value is any kind of Stellar address (account, muxed or contract). */\nexport function isAddress(value: unknown): value is string {\n return isStellarAddress(value) || isMuxedAddress(value) || isContractAddress(value);\n}\n\n/** Throw unless `value` is a valid Stellar account/muxed/contract address. */\nexport function assertAddress(value: unknown, label = 'address'): string {\n if (!isAddress(value)) {\n throw new TypeError(`Invalid Stellar ${label}: ${String(value)}`);\n }\n return value;\n}\n\n/**\n * A registry of named Stellar addresses. Register the accounts you use a lot —\n * your merchant payout account, a treasury, frequent counterparties — and refer\n * to them by name anywhere an address is accepted.\n *\n * @example\n * addresses.define('merchant', 'GC...');\n * await client.paymentIntents.createPay({ destination: 'merchant', amount: '10' });\n */\nexport class AddressBook {\n private readonly entries = new Map<string, string>();\n\n constructor(initial: Record<string, string> = {}) {\n for (const [name, address] of Object.entries(initial)) {\n this.define(name, address);\n }\n }\n\n /** Register (or overwrite) a named address. The address is validated. */\n public define(name: string, address: string): this {\n this.entries.set(name, assertAddress(address, `address for \"${name}\"`));\n return this;\n }\n\n /** Whether a name is registered. */\n public has(name: string): boolean {\n return this.entries.has(name);\n }\n\n /** Look up a registered address by name. */\n public get(name: string): string | undefined {\n return this.entries.get(name);\n }\n\n /** Remove a named address. */\n public delete(name: string): boolean {\n return this.entries.delete(name);\n }\n\n /** All registered names. */\n public names(): string[] {\n return [...this.entries.keys()];\n }\n\n /**\n * Resolve a reference to a concrete address: a registered name is substituted,\n * any other string is returned unchanged (so raw `G…`, muxed `M…`, federation\n * `name*domain`, etc. all keep working).\n */\n public resolve(ref: string): string {\n return this.entries.get(ref) ?? ref;\n }\n}\n\n/** Process-wide default address book. Use `addresses.define(...)` to populate it. */\nexport const addresses = new AddressBook();\n\n/** Anything accepted where an address is expected: a raw address or a name in a book. */\nexport type AddressRef = string;\n\n/**\n * Resolve an {@link AddressRef} using the given book (the shared {@link addresses}\n * by default). Lenient: unknown strings pass through unchanged.\n */\nexport function resolveAddress(ref: AddressRef, book: AddressBook = addresses): string {\n return book.resolve(ref);\n}\n","/**\n * A typed, extensible catalog of Stellar assets.\n *\n * Instead of hunting down an asset's issuer (or pasting the wrong one), use the\n * built-in catalog — `Assets.USDC`, `Assets.EURC`, `Assets.XLM` — which carries\n * the verified issuer for you. Need something else? `defineAsset(...)` makes a\n * typed asset you can reuse. And a plain code string still works everywhere.\n *\n * ⚠️ Issuers are network-specific. The {@link Assets} catalog targets **mainnet**;\n * {@link TestnetAssets} carries the testnet issuers. Bare code strings (e.g.\n * `'USDC'`) are treated as *code only* (no issuer) for backwards compatibility —\n * use the catalog object or `defineAsset` when you want the issuer filled in.\n */\n\nimport { isStellarAddress } from '@/common/addresses';\n\n/** A fully-described Stellar asset. */\nexport interface AssetDefinition {\n /** Asset code, e.g. `USDC`. Use `XLM` (or omit the issuer) for native lumens. */\n code: string;\n /** Issuer account (`G…`). `null`/omitted means the native asset (XLM). */\n issuer?: string | null;\n /** Optional Soroban contract id (`C…`) for the SAC / token contract. */\n contract?: string;\n /** Human-readable name. */\n name?: string;\n /** Network the `issuer` is valid on. */\n network?: 'public' | 'testnet';\n}\n\n/** Anything accepted where an asset is expected: a code string or a definition. */\nexport type AssetRef = string | AssetDefinition;\n\n/** Normalized asset: a code plus a concrete issuer (or `null` for native). */\nexport interface ResolvedAsset {\n /** `XLM` for the native asset, otherwise the asset code. */\n code: string;\n /** Issuer `G…`, or `null` for the native asset. */\n issuer: string | null;\n /** Optional Soroban contract id. */\n contract?: string;\n}\n\nconst NATIVE: AssetDefinition = { code: 'XLM', issuer: null, name: 'Stellar Lumens' };\n\n/**\n * Built-in **mainnet** assets with verified issuers. Extend with your own via\n * {@link defineAsset}. Issuers sourced from the official issuers (Circle for\n * USDC/EURC).\n */\nexport const Assets = {\n /** Native lumens. */\n XLM: NATIVE,\n /** USD Coin by Circle (mainnet). */\n USDC: {\n code: 'USDC',\n issuer: 'GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN',\n name: 'USD Coin',\n network: 'public',\n },\n /** Euro Coin by Circle (mainnet). */\n EURC: {\n code: 'EURC',\n issuer: 'GDHU6WRG4IEQXM5NZ4BMPKOXHW76MZM4Y2IEMFDVXBSDP6SJY4ITNPP2',\n name: 'Euro Coin',\n network: 'public',\n },\n} as const satisfies Record<string, AssetDefinition>;\n\n/** Built-in **testnet** assets (Circle's Test SDF Network issuers). */\nexport const TestnetAssets = {\n XLM: NATIVE,\n USDC: {\n code: 'USDC',\n issuer: 'GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5',\n name: 'USD Coin',\n network: 'testnet',\n },\n EURC: {\n code: 'EURC',\n issuer: 'GB3Q6QDZYTHWT7E5PVS3W7FUT5GVAFC5KSZFFLPU25GO7VTC3NM2ZTVO',\n name: 'Euro Coin',\n network: 'testnet',\n },\n} as const satisfies Record<string, AssetDefinition>;\n\n/** Whether a reference denotes the native asset (XLM). */\nexport function isNativeAsset(ref: AssetRef): boolean {\n if (typeof ref === 'string') {\n const code = ref.trim().toLowerCase();\n return code === '' || code === 'xlm' || code === 'native';\n }\n return !ref.issuer || isNativeAsset(ref.code);\n}\n\n/**\n * Create a reusable, typed custom asset. Validates the issuer/contract format so\n * a typo surfaces immediately rather than on-chain.\n *\n * @example\n * const AQUA = defineAsset({ code: 'AQUA', issuer: 'GBNZ...', name: 'Aquarius' });\n * await client.paymentIntents.createPay({ destination, amount: '5', asset: AQUA });\n */\nexport function defineAsset(def: AssetDefinition): AssetDefinition {\n if (!def.code) throw new TypeError('defineAsset requires a `code`.');\n if (def.issuer != null && !isStellarAddress(def.issuer)) {\n throw new TypeError(`defineAsset: invalid issuer for ${def.code}: ${def.issuer}`);\n }\n if (def.contract != null && !/^C[A-Z2-7]{55}$/.test(def.contract)) {\n throw new TypeError(`defineAsset: invalid contract for ${def.code}: ${def.contract}`);\n }\n return Object.freeze({ ...def });\n}\n\n/**\n * Normalize an {@link AssetRef} into `{ code, issuer, contract }`.\n *\n * - A bare string is treated as *code only* (`issuer: null`) — pass a catalog\n * object or `defineAsset(...)` result when you want the issuer included.\n * - The native asset normalizes to `{ code: 'XLM', issuer: null }`.\n */\nexport function resolveAsset(ref: AssetRef): ResolvedAsset {\n if (isNativeAsset(ref)) return { code: 'XLM', issuer: null };\n if (typeof ref === 'string') return { code: ref, issuer: null };\n return {\n code: ref.code,\n issuer: ref.issuer ?? null,\n ...(ref.contract ? { contract: ref.contract } : {}),\n };\n}\n","/**\n * Shared resolution of \"create intent\" input, used by both the server SDK and\n * the web client so the convenience layers behave identically: a typed\n * {@link AssetRef} (e.g. `Assets.USDC`) is expanded into `assetCode`/`assetIssuer`,\n * and named addresses are substituted via an {@link AddressBook}.\n */\n\nimport { addresses as defaultBook, AddressBook, resolveAddress } from '@/common/addresses';\nimport { resolveAsset, type AssetRef } from '@/common/assets';\n\n/** Fields the resolver understands (everything else passes through untouched). */\nexport interface ResolvableIntentInput {\n destination?: string;\n source?: string;\n /** Typed asset (`Assets.USDC`, `defineAsset(...)`) — fills code + issuer. */\n asset?: AssetRef;\n assetCode?: string;\n assetIssuer?: string;\n}\n\n/**\n * Expand `asset` into `assetCode`/`assetIssuer` and resolve named\n * `destination`/`source` addresses. Existing `assetCode`/`assetIssuer` win over a\n * provided `asset`; native assets leave the code unset (the API treats an omitted\n * asset as native XLM). Returns a new object — the input is not mutated.\n */\nexport function resolveIntentBody<T extends ResolvableIntentInput>(\n options: T,\n book: AddressBook = defaultBook,\n): Omit<T, 'asset'> {\n const out: Record<string, unknown> = { ...(options as Record<string, unknown>) };\n\n if (typeof out['destination'] === 'string') {\n out['destination'] = resolveAddress(out['destination'], book);\n }\n if (typeof out['source'] === 'string') {\n out['source'] = resolveAddress(out['source'], book);\n }\n\n if (out['asset'] != null) {\n const { code, issuer } = resolveAsset(out['asset'] as AssetRef);\n delete out['asset'];\n if (issuer) {\n // Non-native: fill code + issuer unless the caller set them explicitly.\n out['assetCode'] ??= code;\n out['assetIssuer'] ??= issuer;\n }\n // Native (issuer == null) → leave assetCode/assetIssuer omitted = native XLM.\n }\n\n return out as Omit<T, 'asset'>;\n}\n","import { PaymentIntent } from '@/structures/PaymentIntent';\nimport type {\n CreatePayPaymentIntentOptions,\n CreateTxPaymentIntentOptions,\n DeletedData,\n ListPaymentIntentsOptions,\n PaymentIntentData,\n PaymentIntentListData,\n UpdatePaymentIntentOptions,\n ValidatePaymentIntentOptions,\n ValidationOutcomeData,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\nimport { resolveIntentBody } from '@/common/intent-input';\n\n/** A page of payment intents plus its pagination metadata. */\nexport interface PaymentIntentPage {\n items: PaymentIntent[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Validation outcome with the (optional) refreshed intent materialized. */\nexport interface ValidationOutcome {\n valid: boolean;\n status: ValidationOutcomeData['status'];\n reason: string | null;\n paymentIntent: PaymentIntent | null;\n}\n\n/**\n * Manages Stellar payment intents — `client.paymentIntents`.\n *\n * @example\n * const intent = await client.paymentIntents.createTx({\n * source: 'G...', destination: 'G...', amount: '25.5',\n * });\n * console.log(intent.uri, intent.qr);\n */\nexport class PaymentIntentManager extends BaseManager<PaymentIntent> {\n private readonly route = '/payment-intents';\n\n /** Create a SEP-7 `tx` intent (source known → unsigned XDR + tx URI + QR). */\n public async createTx(\n options: CreateTxPaymentIntentOptions,\n ): Promise<PaymentIntent> {\n const data = await this.rest.post<PaymentIntentData>(`${this.route}/tx`, {\n body: resolveIntentBody(options),\n });\n return this._add(new PaymentIntent(this.client, data));\n }\n\n /** Create a SEP-7 `pay` intent (no source → pay URI + QR, no XDR). */\n public async createPay(\n options: CreatePayPaymentIntentOptions,\n ): Promise<PaymentIntent> {\n const data = await this.rest.post<PaymentIntentData>(`${this.route}/pay`, {\n body: resolveIntentBody(options),\n });\n return this._add(new PaymentIntent(this.client, data));\n }\n\n /** Get a single payment intent by id. */\n public async fetch(id: string): Promise<PaymentIntent> {\n const data = await this.rest.get<PaymentIntentData>(`${this.route}/${id}`);\n return this._add(new PaymentIntent(this.client, data));\n }\n\n /** List the consumer's payment intents (paginated). */\n public async list(\n options: ListPaymentIntentsOptions = {},\n ): Promise<PaymentIntentPage> {\n const data = await this.rest.get<PaymentIntentListData>(this.route, {\n query: {\n status: options.status,\n take: options.take,\n skip: options.skip,\n },\n });\n return {\n items: data.data.map((d) => this._add(new PaymentIntent(this.client, d))),\n total: data.total,\n take: data.take,\n skip: data.skip,\n };\n }\n\n /** Update a payment intent (status / txHash / reference). */\n public async update(\n id: string,\n options: UpdatePaymentIntentOptions,\n ): Promise<PaymentIntent> {\n const data = await this.rest.patch<PaymentIntentData>(`${this.route}/${id}`, {\n body: options,\n });\n return this._add(new PaymentIntent(this.client, data));\n }\n\n /** Delete a payment intent. */\n public async delete(id: string): Promise<DeletedData> {\n const result = await this.rest.delete<DeletedData>(`${this.route}/${id}`);\n this.cache.delete(id);\n return result;\n }\n\n /**\n * Validate a submitted transaction against the intent (tx success +\n * destination + amount + memo). Finalizes status server-side and fires events.\n */\n public async validate(\n id: string,\n options: ValidatePaymentIntentOptions,\n ): Promise<ValidationOutcome> {\n const data = await this.rest.post<ValidationOutcomeData>(\n `${this.route}/${id}/validate`,\n { body: options },\n );\n const paymentIntent = data.paymentIntent\n ? this._add(new PaymentIntent(this.client, data.paymentIntent))\n : null;\n return {\n valid: data.valid,\n status: data.status,\n reason: data.reason ?? null,\n paymentIntent,\n };\n }\n}\n","import type { Client } from '@/client/Client';\nimport {\n ProductKind,\n type ProductData,\n type UpdateProductOptions,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/** A product / price the consumer can charge for. */\nexport class Product extends Base<ProductData> {\n public name!: string;\n public description!: string | null;\n public amount!: string | null;\n /** Asset code, or `native` for XLM. */\n public asset!: string;\n public kind!: ProductKind;\n public active!: boolean;\n public reference!: string | null;\n public createdAt!: Date;\n public updatedAt!: Date;\n\n constructor(client: Client, data: ProductData) {\n super(client, data);\n }\n\n protected override _patch(data: ProductData): this {\n super._patch(data);\n this.name = data.name;\n this.description = data.description;\n this.amount = data.amount;\n this.asset = data.asset;\n this.kind = data.kind;\n this.active = data.active;\n this.reference = data.reference;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n /** Human-readable asset label (`XLM` for native). */\n public get assetLabel(): string {\n return !this.asset || this.asset === 'native' ? 'XLM' : this.asset;\n }\n\n /** Re-fetch this product. */\n public fetch(): Promise<Product> {\n return this.client.products.fetch(this.id);\n }\n\n /** Update this product. Mutates and returns this. */\n public async edit(options: UpdateProductOptions): Promise<this> {\n const updated = await this.client.products.update(this.id, options);\n return this._patch(updated.toJSON());\n }\n\n /** Mark the product active. */\n public activate(): Promise<this> {\n return this.edit({ active: true });\n }\n\n /** Mark the product inactive. */\n public deactivate(): Promise<this> {\n return this.edit({ active: false });\n }\n\n /** Delete this product. */\n public delete() {\n return this.client.products.delete(this.id);\n }\n\n public toJSON(): ProductData {\n return {\n id: this.id,\n name: this.name,\n description: this.description,\n amount: this.amount,\n asset: this.asset,\n kind: this.kind,\n active: this.active,\n reference: this.reference,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","import { Product } from '@/structures/Product';\nimport type {\n CreateProductOptions,\n ProductData,\n UpdateProductOptions,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\n\ntype ProductDeletedData = { id: string; deleted: boolean };\n\n/**\n * Manages products / prices — `client.products`.\n *\n * @example\n * const product = await client.products.create({\n * name: 'Pro plan — monthly', amount: '49.00', assetCode: 'USDC',\n * });\n */\nexport class ProductManager extends BaseManager<Product> {\n private readonly route = '/products';\n\n /** Create a product. */\n public async create(options: CreateProductOptions): Promise<Product> {\n const data = await this.rest.post<ProductData>(this.route, { body: options });\n return this._add(new Product(this.client, data));\n }\n\n /** List the consumer's products. */\n public async list(): Promise<Product[]> {\n const data = await this.rest.get<ProductData[]>(this.route);\n return data.map((d) => this._add(new Product(this.client, d)));\n }\n\n /** Get a product by id. */\n public async fetch(id: string): Promise<Product> {\n const data = await this.rest.get<ProductData>(`${this.route}/${id}`);\n return this._add(new Product(this.client, data));\n }\n\n /** Update a product. */\n public async update(\n id: string,\n options: UpdateProductOptions,\n ): Promise<Product> {\n const data = await this.rest.patch<ProductData>(`${this.route}/${id}`, {\n body: options,\n });\n return this._add(new Product(this.client, data));\n }\n\n /** Delete a product. */\n public async delete(id: string): Promise<ProductDeletedData> {\n const result = await this.rest.delete<ProductDeletedData>(\n `${this.route}/${id}`,\n );\n this.cache.delete(id);\n return result;\n }\n}\n","import type { Client } from '@/client/Client';\nimport {\n SwapStatus,\n type SubmitSwapOptions,\n type SwapData,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\nimport type { SwapSubmitOutcome } from '@/managers/SwapManager';\n\n/**\n * A Stellar path-payment swap.\n *\n * Wraps the raw API payload with typed accessors and atomic action methods so\n * you can operate on it directly: `await swap.fetch()`,\n * `await swap.submit({ signedXdr })`.\n */\nexport class Swap extends Base<SwapData> {\n public status!: SwapStatus;\n public network!: string;\n /** Account performing the swap. */\n public source!: string;\n /** Account that receives the swapped asset. */\n public destination!: string;\n /** Asset code being sent, or `native` for XLM. */\n public sendAsset!: string;\n public sendAssetIssuer!: string | null;\n public sendAmount!: string;\n public feeAmount!: string;\n public feeBps!: number;\n /** Amount swapped after the fee is deducted. */\n public swapAmount!: string;\n /** Asset code being received, or `native` for XLM. */\n public destAsset!: string;\n public destAssetIssuer!: string | null;\n public destEstimated!: string;\n public destMin!: string;\n public slippageBps!: number;\n public path!: { code: string; issuer: string | null }[];\n public memo!: string | null;\n /** Unsigned transaction envelope (base64 XDR). */\n public xdr!: string;\n /** SEP-7 deep link. */\n public uri!: string;\n public txHash!: string;\n /** QR code of the SEP-7 URI (PNG data URL). */\n public qr!: string;\n public createdAt!: Date;\n public updatedAt!: Date;\n\n constructor(client: Client, data: SwapData) {\n super(client, data);\n }\n\n protected override _patch(data: SwapData): this {\n super._patch(data);\n this.status = data.status;\n this.network = data.network;\n this.source = data.source;\n this.destination = data.destination;\n this.sendAsset = data.sendAsset;\n this.sendAssetIssuer = data.sendAssetIssuer;\n this.sendAmount = data.sendAmount;\n this.feeAmount = data.feeAmount;\n this.feeBps = data.feeBps;\n this.swapAmount = data.swapAmount;\n this.destAsset = data.destAsset;\n this.destAssetIssuer = data.destAssetIssuer;\n this.destEstimated = data.destEstimated;\n this.destMin = data.destMin;\n this.slippageBps = data.slippageBps;\n this.path = data.path;\n this.memo = data.memo;\n this.xdr = data.xdr;\n this.uri = data.uri;\n this.txHash = data.txHash;\n this.qr = data.qr;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n /** Whether the swap has settled on-chain. */\n public get isSucceeded(): boolean {\n return this.status === SwapStatus.Succeeded;\n }\n\n /** Whether the swap is still awaiting submission. */\n public get isPending(): boolean {\n return this.status === SwapStatus.Pending;\n }\n\n /** Human-readable send asset label (`XLM` for native). */\n public get sendAssetLabel(): string {\n return !this.sendAsset || this.sendAsset === 'native' ? 'XLM' : this.sendAsset;\n }\n\n /** Human-readable destination asset label (`XLM` for native). */\n public get destAssetLabel(): string {\n return !this.destAsset || this.destAsset === 'native' ? 'XLM' : this.destAsset;\n }\n\n /** Re-fetch this swap from the API, returning a fresh instance. */\n public fetch(): Promise<Swap> {\n return this.client.swaps.fetch(this.id);\n }\n\n /**\n * Relay the signed transaction for this swap. Mutates this instance from the\n * refreshed swap in the outcome and returns the outcome.\n */\n public async submit(options: SubmitSwapOptions): Promise<SwapSubmitOutcome> {\n const outcome = await this.client.swaps.submit(this.id, options);\n this._patch(outcome.swap.toJSON());\n return outcome;\n }\n\n public toJSON(): SwapData {\n return {\n id: this.id,\n status: this.status,\n network: this.network,\n source: this.source,\n destination: this.destination,\n sendAsset: this.sendAsset,\n sendAssetIssuer: this.sendAssetIssuer,\n sendAmount: this.sendAmount,\n feeAmount: this.feeAmount,\n feeBps: this.feeBps,\n swapAmount: this.swapAmount,\n destAsset: this.destAsset,\n destAssetIssuer: this.destAssetIssuer,\n destEstimated: this.destEstimated,\n destMin: this.destMin,\n slippageBps: this.slippageBps,\n path: this.path,\n memo: this.memo,\n xdr: this.xdr,\n uri: this.uri,\n txHash: this.txHash,\n qr: this.qr,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","import { Swap } from '@/structures/Swap';\nimport type {\n CreateSwapOptions,\n ListSwapsOptions,\n QuoteSwapOptions,\n SubmitSwapOptions,\n SwapData,\n SwapListData,\n SwapQuoteData,\n SwapStatus,\n SwapSubmitOutcomeData,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\n\n/** A page of swaps plus its pagination metadata. */\nexport interface SwapPage {\n items: Swap[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Submission outcome with the refreshed swap materialized. */\nexport interface SwapSubmitOutcome {\n submitted: boolean;\n status: SwapStatus;\n txHash: string | null;\n reason: string | null;\n resultCodes: string[] | null;\n swap: Swap;\n}\n\n/**\n * Manages Stellar swaps — `client.swaps`.\n *\n * @example\n * const quote = await client.swaps.quote({\n * amount: '100', destAssetCode: 'USDC',\n * });\n * const swap = await client.swaps.create({\n * amount: '100', destAssetCode: 'USDC', source: 'G...',\n * });\n * console.log(swap.uri, swap.qr);\n */\nexport class SwapManager extends BaseManager<Swap> {\n private readonly route = '/swaps';\n\n /** Price a swap without creating it. Returns a plain quote (not a {@link Swap}). */\n public async quote(options: QuoteSwapOptions): Promise<SwapQuoteData> {\n return this.rest.post<SwapQuoteData>(`${this.route}/quote`, {\n body: options,\n });\n }\n\n /** Create a swap (unsigned XDR + SEP-7 URI + QR). */\n public async create(options: CreateSwapOptions): Promise<Swap> {\n const data = await this.rest.post<SwapData>(this.route, { body: options });\n return this._add(new Swap(this.client, data));\n }\n\n /** Get a single swap by id. */\n public async fetch(id: string): Promise<Swap> {\n const data = await this.rest.get<SwapData>(`${this.route}/${id}`);\n return this._add(new Swap(this.client, data));\n }\n\n /** List the consumer's swaps (paginated). */\n public async list(options: ListSwapsOptions = {}): Promise<SwapPage> {\n const data = await this.rest.get<SwapListData>(this.route, {\n query: {\n status: options.status,\n take: options.take,\n skip: options.skip,\n },\n });\n return {\n items: data.data.map((d) => this._add(new Swap(this.client, d))),\n total: data.total,\n take: data.take,\n skip: data.skip,\n };\n }\n\n /**\n * Relay a signed swap transaction to the network. Finalizes status\n * server-side and returns the outcome with the refreshed swap materialized.\n */\n public async submit(\n id: string,\n options: SubmitSwapOptions,\n ): Promise<SwapSubmitOutcome> {\n const data = await this.rest.post<SwapSubmitOutcomeData>(\n `${this.route}/${id}/submit`,\n { body: options },\n );\n return {\n submitted: data.submitted,\n status: data.status,\n txHash: data.txHash ?? null,\n reason: data.reason ?? null,\n resultCodes: data.resultCodes ?? null,\n swap: this._add(new Swap(this.client, data.swap)),\n };\n }\n}\n","import type { Client } from '@/client/Client';\nimport {\n WebhookDeliveryStatus,\n WebhookEventType,\n type WebhookDeliveryData,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/** A single attempt to deliver an event to a webhook endpoint (audit record). */\nexport class WebhookDelivery extends Base<WebhookDeliveryData> {\n public endpointId!: string;\n public eventType!: WebhookEventType;\n public eventId!: string;\n public payload!: Record<string, unknown>;\n public status!: WebhookDeliveryStatus;\n public attempts!: number;\n public responseStatus!: number | null;\n public error!: string | null;\n public lastAttemptAt!: Date | null;\n public createdAt!: Date;\n public updatedAt!: Date;\n\n constructor(client: Client, data: WebhookDeliveryData) {\n super(client, data);\n }\n\n protected override _patch(data: WebhookDeliveryData): this {\n super._patch(data);\n this.endpointId = data.endpointId;\n this.eventType = data.eventType;\n this.eventId = data.eventId;\n this.payload = data.payload;\n this.status = data.status;\n this.attempts = data.attempts;\n this.responseStatus = data.responseStatus;\n this.error = data.error;\n this.lastAttemptAt = data.lastAttemptAt ? new Date(data.lastAttemptAt) : null;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n public get isSucceeded(): boolean {\n return this.status === WebhookDeliveryStatus.Succeeded;\n }\n\n /** Manually re-send this delivery. */\n public redeliver(): Promise<WebhookDelivery> {\n return this.client.webhooks.redeliver(this.endpointId, this.id);\n }\n\n public toJSON(): WebhookDeliveryData {\n return {\n id: this.id,\n endpointId: this.endpointId,\n eventType: this.eventType,\n eventId: this.eventId,\n payload: this.payload,\n status: this.status,\n attempts: this.attempts,\n responseStatus: this.responseStatus,\n error: this.error,\n lastAttemptAt: this.lastAttemptAt ? this.lastAttemptAt.toISOString() : null,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","import type { Client } from '@/client/Client';\nimport type {\n ListWebhookDeliveriesOptions,\n UpdateWebhookEndpointOptions,\n WebhookEndpointData,\n WebhookEndpointWithSecretData,\n WebhookEventType,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/**\n * A registered webhook endpoint.\n *\n * Note: the signing `secret` is only ever present on the instance returned by\n * `create()` / `rotateSecret()` — list/get responses never include it.\n */\nexport class WebhookEndpoint extends Base<WebhookEndpointData> {\n public url!: string;\n public description!: string | null;\n public enabled!: boolean;\n public eventTypes!: WebhookEventType[];\n public createdAt!: Date;\n public updatedAt!: Date;\n /** HMAC signing secret — only set on create/rotate responses. */\n public readonly secret: string | null;\n\n constructor(\n client: Client,\n data: WebhookEndpointData | WebhookEndpointWithSecretData,\n ) {\n super(client, data);\n this.secret = 'secret' in data ? data.secret : null;\n }\n\n protected override _patch(\n data: WebhookEndpointData | WebhookEndpointWithSecretData,\n ): this {\n super._patch(data);\n this.url = data.url;\n this.description = data.description;\n this.enabled = data.enabled;\n this.eventTypes = data.eventTypes;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n /** Whether the endpoint receives all events (empty subscription). */\n public get receivesAllEvents(): boolean {\n return this.eventTypes.length === 0;\n }\n\n /** Re-fetch this endpoint. */\n public fetch(): Promise<WebhookEndpoint> {\n return this.client.webhooks.fetch(this.id);\n }\n\n /** Update url/description/enabled/eventTypes. Mutates and returns this. */\n public async edit(options: UpdateWebhookEndpointOptions): Promise<this> {\n const updated = await this.client.webhooks.update(this.id, options);\n return this._patch(updated.toJSON());\n }\n\n /** Pause deliveries to this endpoint. */\n public disable(): Promise<this> {\n return this.edit({ enabled: false });\n }\n\n /** Resume deliveries to this endpoint. */\n public enable(): Promise<this> {\n return this.edit({ enabled: true });\n }\n\n /** Rotate the signing secret (returns a new instance carrying the secret). */\n public rotateSecret(): Promise<WebhookEndpoint> {\n return this.client.webhooks.rotateSecret(this.id);\n }\n\n /** Send a test event to verify the endpoint. */\n public ping() {\n return this.client.webhooks.ping(this.id);\n }\n\n /** List delivery attempts for this endpoint. */\n public fetchDeliveries(options?: ListWebhookDeliveriesOptions) {\n return this.client.webhooks.fetchDeliveries(this.id, options);\n }\n\n /** Delete this endpoint. */\n public delete() {\n return this.client.webhooks.delete(this.id);\n }\n\n public toJSON(): WebhookEndpointData {\n return {\n id: this.id,\n url: this.url,\n description: this.description,\n enabled: this.enabled,\n eventTypes: this.eventTypes,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","/** Library version, kept in sync with package.json. */\nexport const version = '1.2.0';\n\n/**\n * Default base URL of the Cosmos Pay gateway. Maintained by Cosmos Pay — users\n * never need to set this; it's part of the {@link shared} configuration. Override\n * only when self-hosting or pointing at a staging gateway.\n *\n * This is the public APISIX gateway: requests under `/cosmos-api/*` are\n * authenticated (API key) and proxied to the Payments API. The version segment\n * (`/v1`, see {@link DEFAULT_VERSION}) is appended by the REST layer, producing\n * e.g. `https://api.cosmospay.lat/cosmos-api/v1/payment-intents/pay`.\n */\nexport const DEFAULT_BASE_URL = 'https://api.cosmospay.lat/cosmos-api';\n\n/** Default API version segment prefixed to every route (`/v1/...`). */\nexport const DEFAULT_VERSION = 'v1';\n\n/** Default request timeout in milliseconds. */\nexport const DEFAULT_TIMEOUT = 30_000;\n\n/** Default number of retries for transient failures (network / 429 / 5xx). */\nexport const DEFAULT_RETRIES = 2;\n\n/** Default HMAC signature header sent by the Cosmos Pay webhook dispatcher. */\nexport const SIGNATURE_HEADER = 'x-cosmos-signature';\n\n/**\n * Client debug/telemetry events. The {@link Client} extends EventEmitter and\n * emits these for observability (`debug`/`rateLimit`-style events).\n */\nexport const Events = {\n Debug: 'debug',\n Request: 'request',\n Response: 'response',\n RateLimited: 'rateLimited',\n} as const;\nexport type ClientEvent = (typeof Events)[keyof typeof Events];\n","import { createHmac, timingSafeEqual } from 'node:crypto';\nimport { SIGNATURE_HEADER } from '@/util/Constants';\nimport type { WebhookEvent } from '@/types/index';\n\n/** Options for {@link Webhooks.verify} / {@link Webhooks.constructEvent}. */\nexport interface VerifyWebhookOptions {\n /**\n * Tolerance in seconds between the signed timestamp and now. Protects against\n * replay attacks. Defaults to 300 (5 minutes). Pass 0 to disable the check.\n */\n toleranceSeconds?: number;\n /** Override \"now\" (unix seconds) — useful for testing. */\n now?: number;\n}\n\n/** Thrown when a webhook signature fails verification. */\nexport class WebhookSignatureError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WebhookSignatureError';\n }\n}\n\n/**\n * Stateless helpers to verify the HMAC signatures the Cosmos Pay dispatcher\n * sends with each webhook delivery, and to safely parse the event body.\n *\n * The dispatcher signs each POST with:\n * `X-Cosmos-Signature: t=<unixSeconds>,v1=<hexHmacSha256>`\n * where the HMAC-SHA256 is computed over `${t}.${rawBody}` using the endpoint's\n * `whsec_...` secret.\n *\n * @example\n * // Express raw-body handler\n * app.post('/hooks', express.raw({ type: '*​/*' }), (req, res) => {\n * try {\n * const event = Webhooks.constructEvent(\n * req.body, // the RAW body (Buffer/string)\n * req.header('X-Cosmos-Signature'),\n * process.env.WEBHOOK_SECRET,\n * );\n * // event.type, event.data ...\n * res.sendStatus(200);\n * } catch {\n * res.sendStatus(400);\n * }\n * });\n */\nexport const Webhooks = {\n /** Header name the dispatcher uses for the signature. */\n SIGNATURE_HEADER,\n\n /**\n * Verify a webhook signature. Returns `true` on success, throws\n * {@link WebhookSignatureError} on any failure (so it never silently passes).\n */\n verify(\n rawBody: string | Uint8Array,\n signatureHeader: string | null | undefined,\n secret: string,\n options: VerifyWebhookOptions = {},\n ): boolean {\n if (!signatureHeader) {\n throw new WebhookSignatureError('Missing signature header.');\n }\n if (!secret) {\n throw new WebhookSignatureError('Missing signing secret.');\n }\n\n const { timestamp, signature } = parseSignatureHeader(signatureHeader);\n const payload = typeof rawBody === 'string' ? rawBody : decode(rawBody);\n\n const expected = createHmac('sha256', secret)\n .update(`${timestamp}.${payload}`)\n .digest('hex');\n\n if (!safeEqualHex(expected, signature)) {\n throw new WebhookSignatureError('Signature mismatch.');\n }\n\n const tolerance = options.toleranceSeconds ?? 300;\n if (tolerance > 0) {\n const now = options.now ?? Math.floor(Date.now() / 1000);\n if (Math.abs(now - timestamp) > tolerance) {\n throw new WebhookSignatureError(\n `Timestamp outside tolerance (${tolerance}s).`,\n );\n }\n }\n\n return true;\n },\n\n /**\n * Verify the signature and return the parsed {@link WebhookEvent}. Throws\n * {@link WebhookSignatureError} if verification fails.\n */\n constructEvent<T = unknown>(\n rawBody: string | Uint8Array,\n signatureHeader: string | null | undefined,\n secret: string,\n options: VerifyWebhookOptions = {},\n ): WebhookEvent<T> {\n this.verify(rawBody, signatureHeader, secret, options);\n const payload = typeof rawBody === 'string' ? rawBody : decode(rawBody);\n try {\n return JSON.parse(payload) as WebhookEvent<T>;\n } catch {\n throw new WebhookSignatureError('Body is not valid JSON.');\n }\n },\n};\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nfunction parseSignatureHeader(header: string): {\n timestamp: number;\n signature: string;\n} {\n let timestamp: number | undefined;\n let signature: string | undefined;\n for (const part of header.split(',')) {\n const [key, value] = part.split('=');\n if (!key || value === undefined) continue;\n const k = key.trim();\n if (k === 't') timestamp = Number(value.trim());\n else if (k === 'v1') signature = value.trim();\n }\n if (timestamp === undefined || Number.isNaN(timestamp) || !signature) {\n throw new WebhookSignatureError('Malformed signature header.');\n }\n return { timestamp, signature };\n}\n\nfunction safeEqualHex(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n try {\n return timingSafeEqual(Buffer.from(a, 'hex'), Buffer.from(b, 'hex'));\n } catch {\n return false;\n }\n}\n\nfunction decode(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('utf8');\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { WebhookDelivery } from '@/structures/WebhookDelivery';\nimport { WebhookEndpoint } from '@/structures/WebhookEndpoint';\nimport type {\n CreateWebhookEndpointOptions,\n ListWebhookDeliveriesOptions,\n PaymentIntentData,\n UpdateWebhookEndpointOptions,\n WebhookDeliveryData,\n WebhookDeliveryListData,\n WebhookEndpointData,\n WebhookEndpointWithSecretData,\n WebhookEvent,\n WebhookPingData,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\nimport { Webhooks, WebhookSignatureError } from '@/util/Webhooks';\nimport { SIGNATURE_HEADER } from '@/util/Constants';\n\n// Local alias — the deleted shape mirrors DeletedData.\ntype WebhookDeletedData = { id: string; deleted: boolean };\n\n/** A page of webhook deliveries plus its pagination metadata. */\nexport interface WebhookDeliveryPage {\n items: WebhookDelivery[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Options for verifying + dispatching an incoming webhook. */\nexport interface WebhookProcessOptions {\n /** Signing secret. Falls back to the client's `webhookSecret` when omitted. */\n secret?: string;\n /** Replay tolerance in seconds (default 300; 0 disables). */\n toleranceSeconds?: number;\n}\n\n/** Options for the built-in HTTP webhook handlers. */\nexport type WebhookHandlerOptions = WebhookProcessOptions;\n\n/**\n * Listener signatures for {@link WebhookManager}. You can subscribe with the raw\n * event type (`PAYMENT_INTENT_SUCCEEDED`), its camelCase alias\n * (`paymentIntentSucceeded`), or `event` to catch them all.\n */\nexport interface WebhookListenerEvents {\n event: [WebhookEvent<PaymentIntentData>];\n\n PAYMENT_INTENT_CREATED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_UPDATED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_SUCCEEDED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_FAILED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_CANCELLED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_DELETED: [WebhookEvent<PaymentIntentData>];\n\n paymentIntentCreated: [WebhookEvent<PaymentIntentData>];\n paymentIntentUpdated: [WebhookEvent<PaymentIntentData>];\n paymentIntentSucceeded: [WebhookEvent<PaymentIntentData>];\n paymentIntentFailed: [WebhookEvent<PaymentIntentData>];\n paymentIntentCancelled: [WebhookEvent<PaymentIntentData>];\n paymentIntentDeleted: [WebhookEvent<PaymentIntentData>];\n}\n\n/** Minimal Express-like request (so we don't depend on `@types/express`). */\ninterface RequestLike {\n headers: Record<string, string | string[] | undefined>;\n body?: unknown;\n rawBody?: unknown;\n [key: string]: unknown;\n}\n\n/** Minimal Express-like response. */\ninterface ResponseLike {\n status(code: number): ResponseLike;\n send(body?: unknown): unknown;\n end(body?: unknown): unknown;\n}\n\n// Typed event overloads (declaration merging onto the class).\nexport interface WebhookManager {\n on<E extends keyof WebhookListenerEvents>(\n event: E,\n listener: (...args: WebhookListenerEvents[E]) => void,\n ): this;\n once<E extends keyof WebhookListenerEvents>(\n event: E,\n listener: (...args: WebhookListenerEvents[E]) => void,\n ): this;\n off<E extends keyof WebhookListenerEvents>(\n event: E,\n listener: (...args: WebhookListenerEvents[E]) => void,\n ): this;\n emit<E extends keyof WebhookListenerEvents>(\n event: E,\n ...args: WebhookListenerEvents[E]\n ): boolean;\n}\n\n/**\n * Manages webhook endpoints, their delivery audit trail, **and** the incoming\n * event listener — `client.webhooks`.\n *\n * Registering endpoints (server-side CRUD):\n * @example\n * const endpoint = await client.webhooks.create({\n * url: 'https://me.example.com/hooks',\n * eventTypes: ['PAYMENT_INTENT_SUCCEEDED'],\n * });\n * console.log(endpoint.secret); // shown once — store it!\n *\n * Receiving events (listener):\n * @example\n * client.webhooks.on('paymentIntentSucceeded', (event) => {\n * console.log('Paid!', event.data.id);\n * });\n *\n * import { createServer } from 'node:http';\n * createServer(client.webhooks.createHandler()).listen(4242);\n */\nexport class WebhookManager extends BaseManager<WebhookEndpoint> {\n private readonly route = '/webhooks';\n\n // ── Endpoint CRUD ───────────────────────────────────────────────────────────\n\n /** Register a webhook endpoint (the returned instance carries the secret once). */\n public async create(\n options: CreateWebhookEndpointOptions,\n ): Promise<WebhookEndpoint> {\n const data = await this.rest.post<WebhookEndpointWithSecretData>(this.route, {\n body: options,\n });\n return this._add(new WebhookEndpoint(this.client, data));\n }\n\n /** List the consumer's webhook endpoints. */\n public async list(): Promise<WebhookEndpoint[]> {\n const data = await this.rest.get<WebhookEndpointData[]>(this.route);\n return data.map((d) => this._add(new WebhookEndpoint(this.client, d)));\n }\n\n /** Get a webhook endpoint by id. */\n public async fetch(id: string): Promise<WebhookEndpoint> {\n const data = await this.rest.get<WebhookEndpointData>(`${this.route}/${id}`);\n return this._add(new WebhookEndpoint(this.client, data));\n }\n\n /** Update a webhook endpoint (url/description/enabled/eventTypes). */\n public async update(\n id: string,\n options: UpdateWebhookEndpointOptions,\n ): Promise<WebhookEndpoint> {\n const data = await this.rest.patch<WebhookEndpointData>(\n `${this.route}/${id}`,\n { body: options },\n );\n return this._add(new WebhookEndpoint(this.client, data));\n }\n\n /** Delete a webhook endpoint. */\n public async delete(id: string): Promise<WebhookDeletedData> {\n const result = await this.rest.delete<WebhookDeletedData>(\n `${this.route}/${id}`,\n );\n this.cache.delete(id);\n return result;\n }\n\n /** Rotate the signing secret (returns a new instance carrying the secret). */\n public async rotateSecret(id: string): Promise<WebhookEndpoint> {\n const data = await this.rest.post<WebhookEndpointWithSecretData>(\n `${this.route}/${id}/rotate-secret`,\n );\n return this._add(new WebhookEndpoint(this.client, data));\n }\n\n /** Send a test event to verify the endpoint. */\n public ping(id: string): Promise<WebhookPingData> {\n return this.rest.post<WebhookPingData>(`${this.route}/${id}/ping`);\n }\n\n /** List delivery attempts for an endpoint (audit trail). */\n public async fetchDeliveries(\n id: string,\n options: ListWebhookDeliveriesOptions = {},\n ): Promise<WebhookDeliveryPage> {\n const data = await this.rest.get<WebhookDeliveryListData>(\n `${this.route}/${id}/deliveries`,\n {\n query: {\n status: options.status,\n take: options.take,\n skip: options.skip,\n },\n },\n );\n return {\n items: data.data.map((d) => new WebhookDelivery(this.client, d)),\n total: data.total,\n take: data.take,\n skip: data.skip,\n };\n }\n\n /** Manually re-send a past delivery. */\n public async redeliver(\n id: string,\n deliveryId: string,\n ): Promise<WebhookDelivery> {\n const data = await this.rest.post<WebhookDeliveryData>(\n `${this.route}/${id}/deliveries/${deliveryId}/redeliver`,\n );\n return new WebhookDelivery(this.client, data);\n }\n\n // ── Incoming event listener ──────────────────────────────────────────────────\n\n /**\n * Verify a raw incoming webhook request and dispatch it to the listeners\n * registered via {@link WebhookManager.on}. Returns the parsed event.\n *\n * Emits, in order: the raw type (`PAYMENT_INTENT_SUCCEEDED`), the camelCase\n * alias (`paymentIntentSucceeded`) and the catch-all `event`.\n *\n * @throws {WebhookSignatureError} when the signature is missing/invalid.\n */\n public process(\n rawBody: string | Uint8Array,\n signatureHeader: string | null | undefined,\n options: WebhookProcessOptions = {},\n ): WebhookEvent<PaymentIntentData> {\n const secret = options.secret ?? this.client.webhookSecret;\n if (!secret) {\n throw new WebhookSignatureError(\n 'No webhook secret configured. Pass `{ secret }` or set `webhookSecret` on the client.',\n );\n }\n\n const event = Webhooks.constructEvent<PaymentIntentData>(\n rawBody,\n signatureHeader,\n secret,\n { toleranceSeconds: options.toleranceSeconds },\n );\n\n this.emit(event.type, event);\n this.emit(toCamelEvent(event.type), event);\n this.emit('event', event);\n return event;\n }\n\n /**\n * Build a Node.js `http`/`https` request handler that verifies the signature,\n * dispatches the event to your listeners, and replies `200`/`400`.\n *\n * @example\n * import { createServer } from 'node:http';\n * createServer(client.webhooks.createHandler({ secret })).listen(4242);\n */\n public createHandler(\n options: WebhookHandlerOptions = {},\n ): (req: IncomingMessage, res: ServerResponse) => void {\n return (req, res) => {\n void this.collectBody(req)\n .then((raw) => {\n const sig = headerValue(req.headers[SIGNATURE_HEADER]);\n this.process(raw, sig, options);\n res.statusCode = 200;\n res.end('ok');\n })\n .catch((err: unknown) => {\n res.statusCode = err instanceof WebhookSignatureError ? 400 : 500;\n res.end(\n err instanceof WebhookSignatureError ? 'invalid signature' : 'error',\n );\n });\n };\n }\n\n /**\n * Express-style middleware. Expects the **raw** body (e.g. mounted with\n * `express.raw({ type: '*​/*' })`). On success it attaches the parsed event to\n * `req.cosmosEvent` and calls `next()`; on a bad signature it replies `400`.\n *\n * @example\n * app.post('/hooks', express.raw({ type: '*​/*' }), client.webhooks.middleware({ secret }));\n */\n public middleware(\n options: WebhookHandlerOptions = {},\n ): (req: RequestLike, res: ResponseLike, next: (err?: unknown) => void) => void {\n return (req, res, next) => {\n try {\n const raw = extractRawBody(req);\n const sig = headerValue(req.headers[SIGNATURE_HEADER]);\n const event = this.process(raw, sig, options);\n req.cosmosEvent = event;\n next();\n } catch (err) {\n if (err instanceof WebhookSignatureError) {\n res.status(400).send('invalid signature');\n return;\n }\n next(err);\n }\n };\n }\n\n /** Read a Node.js request stream into a single Buffer. */\n private collectBody(req: IncomingMessage): Promise<Buffer> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on('data', (chunk: Buffer) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n req.on('error', reject);\n });\n }\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\n/** `PAYMENT_INTENT_SUCCEEDED` → `paymentIntentSucceeded`. */\nfunction toCamelEvent(type: string): keyof WebhookListenerEvents {\n return type\n .toLowerCase()\n .replace(/_([a-z])/g, (_, c: string) =>\n c.toUpperCase(),\n ) as keyof WebhookListenerEvents;\n}\n\nfunction headerValue(value: string | string[] | undefined): string | undefined {\n return Array.isArray(value) ? value[0] : value;\n}\n\nfunction extractRawBody(req: RequestLike): string | Uint8Array {\n const candidate = req.rawBody ?? req.body;\n if (typeof candidate === 'string' || candidate instanceof Uint8Array) {\n return candidate;\n }\n // express.json() already parsed it — re-stringify so the signature still matches\n // only if the original raw body is unavailable (best-effort).\n if (candidate && typeof candidate === 'object') {\n return JSON.stringify(candidate);\n }\n return '';\n}\n","/**\n * Error thrown when the Cosmos Pay API responds with a non-2xx status.\n *\n * Carries the HTTP status, the parsed response body and the request context so\n * callers can branch on `error.status` (e.g. 404 → not found, 403 → gateway).\n */\nexport class CosmosPayAPIError extends Error {\n /** HTTP status code returned by the API. */\n public readonly status: number;\n /** HTTP method of the failed request. */\n public readonly method: string;\n /** Absolute URL of the failed request. */\n public readonly url: string;\n /** Parsed response body (object when JSON, string otherwise, or null). */\n public readonly body: unknown;\n /** Machine-readable error code extracted from the body when present. */\n public readonly code: string | undefined;\n\n constructor(options: {\n status: number;\n method: string;\n url: string;\n body: unknown;\n }) {\n const message = CosmosPayAPIError.resolveMessage(options.status, options.body);\n super(message);\n this.name = 'CosmosPayAPIError';\n this.status = options.status;\n this.method = options.method;\n this.url = options.url;\n this.body = options.body;\n this.code = CosmosPayAPIError.resolveCode(options.body);\n Error.captureStackTrace?.(this, CosmosPayAPIError);\n }\n\n private static resolveMessage(status: number, body: unknown): string {\n if (body && typeof body === 'object') {\n const maybe = body as { message?: unknown; error?: unknown };\n const msg = maybe.message ?? maybe.error;\n if (Array.isArray(msg)) return `[${status}] ${msg.join(', ')}`;\n if (typeof msg === 'string') return `[${status}] ${msg}`;\n }\n if (typeof body === 'string' && body.length) return `[${status}] ${body}`;\n return `[${status}] Request failed`;\n }\n\n private static resolveCode(body: unknown): string | undefined {\n if (body && typeof body === 'object') {\n const maybe = body as { code?: unknown; error?: unknown };\n if (typeof maybe.code === 'string') return maybe.code;\n if (typeof maybe.error === 'string') return maybe.error;\n }\n return undefined;\n }\n}\n\n/**\n * Error thrown when a request never reaches the API: network failure, abort or\n * timeout. Distinct from {@link CosmosPayAPIError}, which always has a status.\n */\nexport class CosmosPayRequestError extends Error {\n public readonly method: string;\n public readonly url: string;\n public readonly cause: unknown;\n\n constructor(options: { method: string; url: string; cause: unknown }) {\n const reason =\n options.cause instanceof Error ? options.cause.message : String(options.cause);\n super(`Request to ${options.method} ${options.url} failed: ${reason}`);\n this.name = 'CosmosPayRequestError';\n this.method = options.method;\n this.url = options.url;\n this.cause = options.cause;\n Error.captureStackTrace?.(this, CosmosPayRequestError);\n }\n}\n","import { EventEmitter } from 'node:events';\nimport {\n CosmosPayAPIError,\n CosmosPayRequestError,\n} from '@/errors/CosmosPayError';\nimport {\n DEFAULT_RETRIES,\n DEFAULT_TIMEOUT,\n DEFAULT_VERSION,\n Events,\n version,\n} from '@/util/Constants';\n\n/** A `fetch`-compatible function (defaults to the global `fetch`). */\nexport type FetchLike = typeof fetch;\n\n/** Options accepted when constructing a {@link REST} instance. */\nexport interface RESTOptions {\n /**\n * Base URL of the Cosmos Pay gateway (no trailing slash), e.g.\n * `https://api.cosmospay.lat/cosmos-api`. The version segment is appended\n * automatically.\n */\n baseURL: string;\n /**\n * API key issued by the Cosmos developer platform. Sent as\n * `Authorization: Bearer <apiKey>` (and `apikey: <apiKey>`) to the gateway.\n */\n apiKey?: string;\n /**\n * Shared gateway secret (`X-Gateway-Secret`). Only needed when calling the\n * service directly (bypassing APISIX) — typically local development.\n */\n gatewaySecret?: string;\n /**\n * Authenticated consumer username (`X-Consumer-Username`). Pair with\n * `gatewaySecret` for direct service access.\n */\n consumerUsername?: string;\n /**\n * API version segment prefixed to every route. Defaults to `v1`. Set to an\n * empty string when your gateway already injects the version.\n */\n version?: string;\n /** Per-request timeout in milliseconds (default 30000). */\n timeout?: number;\n /** Retries for transient failures — network errors, 429 and 5xx (default 2). */\n retries?: number;\n /** Extra headers merged into every request. */\n headers?: Record<string, string>;\n /** Custom fetch implementation (e.g. a polyfill on old runtimes). */\n fetch?: FetchLike;\n}\n\n/** Internal options for a single request. */\nexport interface RequestOptions {\n /** Query string parameters; `undefined`/`null` values are dropped. */\n query?: Record<string, string | number | boolean | undefined | null>;\n /** JSON body to send. */\n body?: unknown;\n /** Per-request header overrides. */\n headers?: Record<string, string>;\n /** Per-request AbortSignal. */\n signal?: AbortSignal;\n}\n\nconst RETRYABLE_STATUS = new Set([408, 429, 500, 502, 503, 504]);\n\n/**\n * The HTTP layer. Owns the base URL, authentication and retry/timeout policy,\n * and exposes thin verb helpers (`get`/`post`/`patch`/`delete`). Managers call\n * these — they never touch `fetch` directly.\n */\nexport class REST extends EventEmitter {\n public baseURL: string;\n public readonly version: string;\n private readonly timeout: number;\n private readonly retries: number;\n private readonly fetchFn: FetchLike;\n private readonly extraHeaders: Record<string, string>;\n private apiKey?: string;\n private gatewaySecret?: string;\n private consumerUsername?: string;\n\n constructor(options: RESTOptions) {\n super();\n if (!options.baseURL) {\n throw new TypeError('REST requires a `baseURL`.');\n }\n this.baseURL = options.baseURL.replace(/\\/+$/, '');\n this.version = options.version ?? DEFAULT_VERSION;\n this.timeout = options.timeout ?? DEFAULT_TIMEOUT;\n this.retries = options.retries ?? DEFAULT_RETRIES;\n this.extraHeaders = options.headers ?? {};\n this.apiKey = options.apiKey;\n this.gatewaySecret = options.gatewaySecret;\n this.consumerUsername = options.consumerUsername;\n\n const fetchFn = options.fetch ?? globalThis.fetch;\n if (typeof fetchFn !== 'function') {\n throw new TypeError(\n 'No global `fetch` found. Use Node.js >= 18 or pass a `fetch` implementation in the client options.',\n );\n }\n this.fetchFn = fetchFn.bind(globalThis);\n }\n\n /** Replace the API key used for subsequent requests. */\n public setApiKey(apiKey: string): this {\n this.apiKey = apiKey;\n return this;\n }\n\n /** Set direct-access gateway credentials (local/dev usage). */\n public setGatewayCredentials(secret: string, consumerUsername: string): this {\n this.gatewaySecret = secret;\n this.consumerUsername = consumerUsername;\n return this;\n }\n\n public get<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return this.request<T>('GET', path, options);\n }\n\n public post<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return this.request<T>('POST', path, options);\n }\n\n public patch<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return this.request<T>('PATCH', path, options);\n }\n\n public delete<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return this.request<T>('DELETE', path, options);\n }\n\n /** Build the absolute URL for a route, applying the version prefix + query. */\n public buildURL(path: string, query?: RequestOptions['query']): string {\n const clean = path.startsWith('/') ? path : `/${path}`;\n const prefix = this.version ? `/${this.version}` : '';\n const url = new URL(`${this.baseURL}${prefix}${clean}`);\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue;\n url.searchParams.set(key, String(value));\n }\n }\n return url.toString();\n }\n\n private buildHeaders(extra?: Record<string, string>): Record<string, string> {\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'User-Agent': `@cosmosapp/pay_sdk/${version}`,\n ...this.extraHeaders,\n };\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`;\n headers['apikey'] = this.apiKey;\n }\n if (this.gatewaySecret) headers['X-Gateway-Secret'] = this.gatewaySecret;\n if (this.consumerUsername) {\n headers['X-Consumer-Username'] = this.consumerUsername;\n }\n return { ...headers, ...extra };\n }\n\n /** Core request with retry, timeout and structured error handling. */\n public async request<T>(\n method: string,\n path: string,\n options: RequestOptions = {},\n ): Promise<T> {\n const url = this.buildURL(path, options.query);\n const headers = this.buildHeaders(options.headers);\n\n let serializedBody: string | undefined;\n if (options.body !== undefined) {\n serializedBody = JSON.stringify(options.body);\n headers['Content-Type'] = 'application/json';\n }\n\n let attempt = 0;\n let lastError: unknown;\n\n while (attempt <= this.retries) {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeout);\n const signal = options.signal\n ? anySignal([options.signal, controller.signal])\n : controller.signal;\n\n this.emit(Events.Request, { method, url, attempt });\n\n try {\n const response = await this.fetchFn(url, {\n method,\n headers,\n body: serializedBody,\n signal,\n });\n clearTimeout(timer);\n\n this.emit(Events.Response, {\n method,\n url,\n status: response.status,\n attempt,\n });\n\n if (response.status === 429) {\n this.emit(Events.RateLimited, { method, url, attempt });\n }\n\n if (!response.ok) {\n const body = await safeParse(response);\n if (RETRYABLE_STATUS.has(response.status) && attempt < this.retries) {\n await this.backoff(response, attempt);\n attempt++;\n continue;\n }\n throw new CosmosPayAPIError({ status: response.status, method, url, body });\n }\n\n return (await safeParse(response)) as T;\n } catch (error) {\n clearTimeout(timer);\n if (error instanceof CosmosPayAPIError) throw error;\n\n // Network/abort/timeout → retry, then surface as a request error.\n lastError = error;\n if (attempt < this.retries) {\n await sleep(backoffDelay(attempt));\n attempt++;\n continue;\n }\n throw new CosmosPayRequestError({ method, url, cause: error });\n }\n }\n\n throw new CosmosPayRequestError({ method, url, cause: lastError });\n }\n\n private async backoff(response: Response, attempt: number): Promise<void> {\n const retryAfter = response.headers.get('retry-after');\n const ms = retryAfter\n ? Number(retryAfter) * 1000\n : backoffDelay(attempt);\n await sleep(Number.isFinite(ms) ? ms : backoffDelay(attempt));\n }\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nfunction backoffDelay(attempt: number): number {\n return Math.min(1000 * 2 ** attempt, 8000);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function safeParse(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) return null;\n const contentType = response.headers.get('content-type') ?? '';\n if (contentType.includes('application/json')) {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n return text;\n}\n\n/** Combine multiple AbortSignals into one (first to abort wins). */\nfunction anySignal(signals: AbortSignal[]): AbortSignal {\n const controller = new AbortController();\n const onAbort = (signal: AbortSignal) => () => controller.abort(signal.reason);\n for (const signal of signals) {\n if (signal.aborted) {\n controller.abort(signal.reason);\n break;\n }\n signal.addEventListener('abort', onAbort(signal), { once: true });\n }\n return controller.signal;\n}\n","import { DEFAULT_BASE_URL, DEFAULT_VERSION } from '@/util/Constants';\n\n/**\n * Internal (\"shared\") configuration that Cosmos Pay maintains on the user's\n * behalf. These are the gateway / infrastructure details an integrator should\n * **not** have to know about — they're pre-filled here so that, in practice, the\n * only credential a user provides is their `apiKey`.\n *\n * Every value is overridable (per-client via {@link ClientOptions}, or globally\n * via {@link Client.shared}) for self-hosting, staging or local development.\n */\nexport interface SharedConfig {\n /** Base URL of the Cosmos Pay gateway. */\n baseURL: string;\n /** API version segment prefixed to every route (`/v1/...`). */\n version: string;\n /**\n * Shared gateway secret (`X-Gateway-Secret`). Only used when talking to the\n * service directly, bypassing the gateway (local development). Internal.\n */\n gatewaySecret?: string;\n /**\n * Authenticated consumer username (`X-Consumer-Username`). Paired with\n * `gatewaySecret` for direct service access. Internal.\n */\n consumerUsername?: string;\n /**\n * Default webhook signing secret used by the webhook listener\n * (`client.webhooks.process` / handlers) when no secret is passed explicitly.\n */\n webhookSecret?: string;\n}\n\n/**\n * The mutable, process-wide defaults. Cosmos Pay ships sane values here; you can\n * tweak them once at startup (e.g. `Client.shared.baseURL = '...'`) and every\n * client created afterwards inherits them.\n */\nexport const shared: SharedConfig = {\n baseURL: DEFAULT_BASE_URL,\n version: DEFAULT_VERSION,\n};\n\n/** Merge a partial override on top of the current shared defaults. */\nexport function resolveShared(overrides: Partial<SharedConfig> = {}): SharedConfig {\n const defined: Partial<SharedConfig> = {};\n for (const key of Object.keys(overrides) as (keyof SharedConfig)[]) {\n const value = overrides[key];\n if (value !== undefined) {\n Object.assign(defined, { [key]: value });\n }\n }\n return { ...shared, ...defined };\n}\n","import { EventEmitter } from 'node:events';\nimport { AnalyticsManager } from '@/managers/AnalyticsManager';\nimport { CustomerManager } from '@/managers/CustomerManager';\nimport { HealthManager } from '@/managers/HealthManager';\nimport { PaymentIntentManager } from '@/managers/PaymentIntentManager';\nimport { ProductManager } from '@/managers/ProductManager';\nimport { SwapManager } from '@/managers/SwapManager';\nimport { WebhookManager } from '@/managers/WebhookManager';\nimport { REST, type FetchLike } from '@/rest/REST';\nimport { version } from '@/util/Constants';\nimport { resolveShared, shared, type SharedConfig } from '@/util/shared';\n\n/**\n * Options accepted by the {@link Client} constructor.\n *\n * In practice the only value you provide is `apiKey` — everything else (the\n * gateway URL, version and other infrastructure details) is pre-filled from the\n * {@link Client.shared} defaults that Cosmos Pay maintains for you.\n */\nexport interface ClientOptions {\n /**\n * Your Cosmos Pay API key. Sent to the gateway as `Authorization: Bearer\n * <apiKey>`. The key type determines the network (`dv_` → testnet, `prod_` →\n * mainnet). This is the only credential a typical integration needs.\n */\n apiKey: string;\n\n /**\n * Default webhook signing secret used by the webhook listener\n * (`client.webhooks.on(...)` + handlers) when you don't pass one explicitly.\n */\n webhookSecret?: string;\n\n /** Per-request timeout in milliseconds (default 30000). */\n timeout?: number;\n /** Retries for transient failures — network errors, 429 and 5xx (default 2). */\n retries?: number;\n /** Extra headers merged into every request. */\n headers?: Record<string, string>;\n /** Custom fetch implementation (e.g. a polyfill on old runtimes). */\n fetch?: FetchLike;\n\n // ── Advanced / internal overrides (you normally never set these) ────────────\n /**\n * Override the gateway base URL. Defaults to {@link Client.shared}`.baseURL`.\n * Only needed for self-hosting or a staging gateway.\n * @internal\n */\n baseURL?: string;\n /**\n * Override the API version segment. Defaults to `v1`.\n * @internal\n */\n version?: string;\n /**\n * Shared gateway secret (`X-Gateway-Secret`) for direct, gateway-bypassing\n * access (local development). Maintained internally.\n * @internal\n */\n gatewaySecret?: string;\n /**\n * Consumer username (`X-Consumer-Username`) for direct access. Internal.\n * @internal\n */\n consumerUsername?: string;\n}\n\n/** Payloads emitted by the {@link Client} for observability. */\nexport interface ClientEvents {\n request: [{ method: string; url: string; attempt: number }];\n response: [{ method: string; url: string; status: number; attempt: number }];\n rateLimited: [{ method: string; url: string; attempt: number }];\n debug: [message: string];\n}\n\nexport interface Client {\n on<E extends keyof ClientEvents>(\n event: E,\n listener: (...args: ClientEvents[E]) => void,\n ): this;\n once<E extends keyof ClientEvents>(\n event: E,\n listener: (...args: ClientEvents[E]) => void,\n ): this;\n off<E extends keyof ClientEvents>(\n event: E,\n listener: (...args: ClientEvents[E]) => void,\n ): this;\n emit<E extends keyof ClientEvents>(\n event: E,\n ...args: ClientEvents[E]\n ): boolean;\n}\n\n/**\n * The main entry point of the SDK — a single, atomic client that exposes every\n * resource through its own manager — an atomic, single-client design.\n *\n * @example\n * import { Client } from '@cosmosapp/pay_sdk';\n *\n * // The user only provides their API key — the gateway is handled for them.\n * const client = new Client({ apiKey: process.env.COSMOS_PAY_API_KEY });\n *\n * const intent = await client.paymentIntents.createPay({ destination: 'G...', amount: '10' });\n * console.log(intent.uri);\n */\nexport class Client extends EventEmitter {\n /** Library version. */\n public static readonly version = version;\n\n /**\n * Process-wide shared defaults maintained by Cosmos Pay (gateway URL, version,\n * internal secrets). Mutate once at startup to change them for every client\n * (e.g. self-hosting): `Client.shared.baseURL = 'https://gateway.your-domain.com'`.\n */\n public static readonly shared: SharedConfig = shared;\n\n /** Resolved shared configuration for this client instance. */\n public readonly shared: SharedConfig;\n\n /** Default webhook signing secret for the webhook listener (if configured). */\n public webhookSecret: string | undefined;\n\n /** The underlying HTTP layer. Shared by every manager. */\n public readonly rest: REST;\n\n /** Stellar payment intents — create/list/fetch/update/delete/validate. */\n public readonly paymentIntents: PaymentIntentManager;\n /** Webhook endpoints, delivery audit trail, and the event listener. */\n public readonly webhooks: WebhookManager;\n /** Products / prices. */\n public readonly products: ProductManager;\n /** Stellar swaps — quote/create/fetch/list/submit. */\n public readonly swaps: SwapManager;\n /** Customers. */\n public readonly customers: CustomerManager;\n /** Read-only analytics (summary, balances, logs). */\n public readonly analytics: AnalyticsManager;\n /** Service health probes (public). */\n public readonly health: HealthManager;\n\n constructor(options: ClientOptions) {\n super();\n if (!options || !options.apiKey) {\n throw new TypeError('Client requires an `apiKey` option.');\n }\n\n // Fill the infrastructure details from the shared defaults; the user only\n // had to bring their apiKey.\n this.shared = resolveShared({\n baseURL: options.baseURL,\n version: options.version,\n gatewaySecret: options.gatewaySecret,\n consumerUsername: options.consumerUsername,\n webhookSecret: options.webhookSecret,\n });\n this.webhookSecret = this.shared.webhookSecret;\n\n this.rest = new REST({\n baseURL: this.shared.baseURL,\n apiKey: options.apiKey,\n gatewaySecret: this.shared.gatewaySecret,\n consumerUsername: this.shared.consumerUsername,\n version: this.shared.version,\n timeout: options.timeout,\n retries: options.retries,\n headers: options.headers,\n fetch: options.fetch,\n });\n\n // Re-emit REST telemetry through the client so consumers can subscribe to\n // `client.on('request' | 'response' | 'rateLimited' | 'debug', ...)`.\n this.rest.on('request', (p) => this.emit('request', p));\n this.rest.on('response', (p) => this.emit('response', p));\n this.rest.on('rateLimited', (p) => this.emit('rateLimited', p));\n\n this.paymentIntents = new PaymentIntentManager(this);\n this.webhooks = new WebhookManager(this);\n this.products = new ProductManager(this);\n this.swaps = new SwapManager(this);\n this.customers = new CustomerManager(this);\n this.analytics = new AnalyticsManager(this);\n this.health = new HealthManager(this);\n }\n\n /** Update the API key used for subsequent requests. */\n public setApiKey(apiKey: string): this {\n this.rest.setApiKey(apiKey);\n return this;\n }\n\n /** Set the default webhook signing secret for the webhook listener. */\n public setWebhookSecret(secret: string): this {\n this.webhookSecret = secret;\n return this;\n }\n\n /** Set direct-access gateway credentials (internal / local dev usage). */\n public setGatewayCredentials(secret: string, consumerUsername: string): this {\n this.rest.setGatewayCredentials(secret, consumerUsername);\n return this;\n }\n}\n","/**\n * Typed identifiers for the wallets the web client knows about, so you can write\n * `Wallets.FREIGHTER` instead of remembering the `'freighter'` magic string —\n * while any custom adapter id still works.\n */\n\n/** Built-in wallet ids (matches each adapter's `id`). */\nexport const Wallets = {\n FREIGHTER: 'freighter',\n XBULL: 'xbull',\n RABET: 'rabet',\n LOBSTR: 'lobstr',\n ALBEDO: 'albedo',\n} as const;\n\n/** A known wallet id, or any custom adapter id (autocomplete for the built-ins). */\nexport type WalletId = (typeof Wallets)[keyof typeof Wallets] | (string & {});\n"]}
1
+ {"version":3,"sources":["../src/managers/AnalyticsManager.ts","../src/structures/Base.ts","../src/structures/Customer.ts","../src/managers/BaseManager.ts","../src/managers/CustomerManager.ts","../src/managers/HealthManager.ts","../src/types/index.ts","../src/structures/LiquidityOperation.ts","../src/managers/LiquidityManager.ts","../src/managers/OnrampManager.ts","../src/managers/OfframpManager.ts","../src/managers/ActivityManager.ts","../src/structures/Receiver.ts","../src/managers/KycManager.ts","../src/managers/PollarManager.ts","../src/structures/PaymentIntent.ts","../src/common/addresses.ts","../src/common/assets.ts","../src/common/intent-input.ts","../src/managers/PaymentIntentManager.ts","../src/structures/Product.ts","../src/managers/ProductManager.ts","../src/structures/Swap.ts","../src/managers/SwapManager.ts","../src/structures/WebhookDelivery.ts","../src/structures/WebhookEndpoint.ts","../src/util/Constants.ts","../src/util/Webhooks.ts","../src/managers/WebhookManager.ts","../src/errors/CosmosPayError.ts","../src/rest/REST.ts","../src/util/shared.ts","../src/client/Client.ts","../src/common/wallets.ts"],"names":["EventEmitter","createHmac","timingSafeEqual"],"mappings":";;;;;;;;AAaO,IAAM,mBAAN,MAAuB;AAAA,EAG5B,YAAY,MAAA,EAAgB;AAC1B,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AAAA,EAEA,IAAY,IAAA,GAAa;AACvB,IAAA,OAAO,KAAK,MAAA,CAAO,IAAA;AAAA,EACrB;AAAA;AAAA,EAGO,OAAA,GAAyC;AAC9C,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAA0B,UAAU,CAAA;AAAA,EACvD;AAAA;AAAA,EAGO,QAAA,GAA2C;AAChD,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAA2B,WAAW,CAAA;AAAA,EACzD;AAAA;AAAA,EAGO,OAAA,GAAgC;AACrC,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAAiB,OAAO,CAAA;AAAA,EAC3C;AAAA;AAAA,EAGO,WAAA,GAAwC;AAC7C,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAAqB,gBAAgB,CAAA;AAAA,EACxD;AACF;;;ACpCO,IAAe,OAAf,MAAiD;AAAA,EAM5C,WAAA,CAAY,QAAgB,IAAA,EAAY;AAChD,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,OAAO,IAAI,CAAA;AAAA,EAClB;AAAA;AAAA,EAGU,OAAO,IAAA,EAAkB;AACjC,IAAA,IAAA,CAAK,KAAK,IAAA,CAAK,EAAA;AACf,IAAA,OAAO,IAAA;AAAA,EACT;AAAA;AAAA,EAMO,OAAA,GAAkB;AACvB,IAAA,OAAO,IAAA,CAAK,EAAA;AAAA,EACd;AACF;;;AC1BO,IAAM,QAAA,GAAN,cAAuB,IAAA,CAAmB;AAAA,EA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ent":["import type { Client } from '@/client/Client';\nimport type { REST } from '@/rest/REST';\nimport type {\n AnalyticsBalancesData,\n AnalyticsSummaryData,\n ApiLogsData,\n WebhookLogsData,\n} from '@/types/index';\n\n/**\n * Read-only analytics derived from the consumer's intents and deliveries —\n * `client.analytics`. Powers dashboard-style Overview / Balances / Logs views.\n */\nexport class AnalyticsManager {\n public readonly client: Client;\n\n constructor(client: Client) {\n this.client = client;\n }\n\n private get rest(): REST {\n return this.client.rest;\n }\n\n /** Overview metrics: totals, settled volume, webhook health, 30-day series. */\n public summary(): Promise<AnalyticsSummaryData> {\n return this.rest.get<AnalyticsSummaryData>('/summary');\n }\n\n /** Settled (and pending) amount per asset. */\n public balances(): Promise<AnalyticsBalancesData> {\n return this.rest.get<AnalyticsBalancesData>('/balances');\n }\n\n /** Recent API requests reaching the service (with details). */\n public apiLogs(): Promise<ApiLogsData> {\n return this.rest.get<ApiLogsData>('/logs');\n }\n\n /** Recent webhook deliveries across all endpoints (with details). */\n public webhookLogs(): Promise<WebhookLogsData> {\n return this.rest.get<WebhookLogsData>('/logs/webhooks');\n }\n}\n","import type { Client } from '@/client/Client';\n\n/**\n * Root of every API structure. Holds a back-reference to the {@link Client} so\n * instances can perform their own actions (e.g. `paymentIntent.delete()`), and\n * provides the `_patch`/`toJSON` plumbing shared by all structures.\n */\nexport abstract class Base<Data extends { id: string }> {\n /** The client that instantiated this structure. */\n public readonly client: Client;\n /** Unique identifier of the resource. */\n public id!: string;\n\n protected constructor(client: Client, data: Data) {\n this.client = client;\n this._patch(data);\n }\n\n /** Merge raw API data onto this instance. Subclasses override and call super. */\n protected _patch(data: Data): this {\n this.id = data.id;\n return this;\n }\n\n /** Return the raw API representation of this structure. */\n public abstract toJSON(): Data;\n\n /** Allow `String(structure)` / template literals to resolve to the id. */\n public valueOf(): string {\n return this.id;\n }\n}\n","import type { Client } from '@/client/Client';\nimport type { CustomerData, UpdateCustomerOptions } from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/** A customer record, optionally enriched with on-chain payment stats. */\nexport class Customer extends Base<CustomerData> {\n public name!: string;\n public alias!: string | null;\n public note!: string | null;\n public email!: string | null;\n /** Optional Stellar account associated with the customer. */\n public account!: string | null;\n public reference!: string | null;\n public createdAt!: Date;\n public updatedAt!: Date;\n /** Number of payment intents from this customer's account (list view only). */\n public payments: number | null = null;\n /** Number of succeeded payments (list view only). */\n public succeeded: number | null = null;\n /** Total settled amount as a decimal string (list view only). */\n public total: string | null = null;\n\n constructor(client: Client, data: CustomerData) {\n super(client, data);\n }\n\n protected override _patch(data: CustomerData): this {\n super._patch(data);\n this.name = data.name;\n this.alias = data.alias;\n this.note = data.note;\n this.email = data.email;\n this.account = data.account;\n this.reference = data.reference;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n if (data.payments !== undefined) this.payments = data.payments;\n if (data.succeeded !== undefined) this.succeeded = data.succeeded;\n if (data.total !== undefined) this.total = data.total;\n return this;\n }\n\n /** Re-fetch this customer. */\n public fetch(): Promise<Customer> {\n return this.client.customers.fetch(this.id);\n }\n\n /** Update this customer. Mutates and returns this. */\n public async edit(options: UpdateCustomerOptions): Promise<this> {\n const updated = await this.client.customers.update(this.id, options);\n return this._patch(updated.toJSON());\n }\n\n /** Delete this customer. */\n public delete() {\n return this.client.customers.delete(this.id);\n }\n\n public toJSON(): CustomerData {\n return {\n id: this.id,\n name: this.name,\n alias: this.alias,\n note: this.note,\n email: this.email,\n account: this.account,\n reference: this.reference,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n ...(this.payments !== null ? { payments: this.payments } : {}),\n ...(this.succeeded !== null ? { succeeded: this.succeeded } : {}),\n ...(this.total !== null ? { total: this.total } : {}),\n };\n }\n}\n","import { EventEmitter } from 'node:events';\nimport type { Client } from '@/client/Client';\nimport type { REST } from '@/rest/REST';\n\n/**\n * Base class for all resource managers. Each manager owns a slice of the API\n * (payment intents, webhooks, ...) and a lightweight in-memory cache of the\n * structures it has materialized — an atomic, per-resource manager pattern.\n *\n * Extends EventEmitter so managers that surface real-time events (e.g. the\n * webhook listener) can `emit`/`on` without extra plumbing.\n */\nexport abstract class BaseManager<\n Structure extends { id: string },\n> extends EventEmitter {\n public readonly client: Client;\n /** Cache of structures keyed by id, populated on fetch/create. */\n public readonly cache: Map<string, Structure> = new Map();\n\n constructor(client: Client) {\n super();\n this.client = client;\n }\n\n /** Shortcut to the shared REST instance. */\n protected get rest(): REST {\n return this.client.rest;\n }\n\n /** Store a structure in the cache and return it. */\n protected _add(structure: Structure): Structure {\n this.cache.set(structure.id, structure);\n return structure;\n }\n\n /** Resolve an id from either a raw id or a structure instance. */\n public resolveId(idOrStructure: string | { id: string }): string {\n return typeof idOrStructure === 'string' ? idOrStructure : idOrStructure.id;\n }\n}\n","import { Customer } from '@/structures/Customer';\nimport type {\n CreateCustomerOptions,\n CustomerData,\n CustomerListData,\n UpdateCustomerOptions,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\n\ntype CustomerDeletedData = { id: string; deleted: boolean };\n\n/**\n * Manages customers — `client.customers`.\n *\n * @example\n * const customer = await client.customers.create({\n * name: 'Acme Inc.', email: 'billing@acme.com',\n * });\n */\nexport class CustomerManager extends BaseManager<Customer> {\n private readonly route = '/customers';\n\n /** Create a customer. */\n public async create(options: CreateCustomerOptions): Promise<Customer> {\n const data = await this.rest.post<CustomerData>(this.route, { body: options });\n return this._add(new Customer(this.client, data));\n }\n\n /** List the consumer's customers (with payment stats). */\n public async list(): Promise<Customer[]> {\n const data = await this.rest.get<CustomerListData>(this.route);\n return data.data.map((d) => this._add(new Customer(this.client, d)));\n }\n\n /** Get a customer by id. */\n public async fetch(id: string): Promise<Customer> {\n const data = await this.rest.get<CustomerData>(`${this.route}/${id}`);\n return this._add(new Customer(this.client, data));\n }\n\n /** Update a customer. */\n public async update(\n id: string,\n options: UpdateCustomerOptions,\n ): Promise<Customer> {\n const data = await this.rest.patch<CustomerData>(`${this.route}/${id}`, {\n body: options,\n });\n return this._add(new Customer(this.client, data));\n }\n\n /** Delete a customer. */\n public async delete(id: string): Promise<CustomerDeletedData> {\n const result = await this.rest.delete<CustomerDeletedData>(\n `${this.route}/${id}`,\n );\n this.cache.delete(id);\n return result;\n }\n}\n","import type { Client } from '@/client/Client';\nimport type { REST } from '@/rest/REST';\nimport type { HealthCheckData } from '@/types/index';\n\n/**\n * Service health probes — `client.health`. These routes are public (they don't\n * require an authenticated consumer).\n */\nexport class HealthManager {\n public readonly client: Client;\n\n constructor(client: Client) {\n this.client = client;\n }\n\n private get rest(): REST {\n return this.client.rest;\n }\n\n /** Liveness probe — resolves when the service is up. */\n public async liveness(): Promise<boolean> {\n await this.rest.get<unknown>('/health/liveness');\n return true;\n }\n\n /** Readiness probe (checks the database). Returns the health report. */\n public readiness(): Promise<HealthCheckData> {\n return this.rest.get<HealthCheckData>('/health/readiness');\n }\n}\n","/**\n * Type definitions for the Cosmos Pay Payments API.\n *\n * These mirror the server's OpenAPI schema (Stellar SEP-7 payment intents,\n * webhooks, products, customers and analytics). Every type is exported so\n * TypeScript consumers get full intellisense; JavaScript consumers can ignore\n * them entirely.\n */\n\nimport type { AssetRef } from '@/common/assets';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Enums (provided both as runtime objects and as string-literal unions)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Lifecycle state of a payment intent. */\nexport const PaymentIntentStatus = {\n Pending: 'PENDING',\n Submitted: 'SUBMITTED',\n Succeeded: 'SUCCEEDED',\n Failed: 'FAILED',\n Cancelled: 'CANCELLED',\n Expired: 'EXPIRED',\n} as const;\nexport type PaymentIntentStatus =\n (typeof PaymentIntentStatus)[keyof typeof PaymentIntentStatus];\n\n/** SEP-7 operation a payment intent represents. */\nexport const PaymentIntentKind = {\n /** Source account is known → unsigned XDR + `web+stellar:tx` URI. */\n Tx: 'TX',\n /** No source → `web+stellar:pay` URI only (wallet picks the source). */\n Pay: 'PAY',\n} as const;\nexport type PaymentIntentKind =\n (typeof PaymentIntentKind)[keyof typeof PaymentIntentKind];\n\n/** Domain events an integrator can subscribe a webhook to. */\nexport const WebhookEventType = {\n PaymentIntentCreated: 'PAYMENT_INTENT_CREATED',\n PaymentIntentUpdated: 'PAYMENT_INTENT_UPDATED',\n PaymentIntentSucceeded: 'PAYMENT_INTENT_SUCCEEDED',\n PaymentIntentFailed: 'PAYMENT_INTENT_FAILED',\n PaymentIntentCancelled: 'PAYMENT_INTENT_CANCELLED',\n PaymentIntentDeleted: 'PAYMENT_INTENT_DELETED',\n} as const;\nexport type WebhookEventType =\n (typeof WebhookEventType)[keyof typeof WebhookEventType];\n\n/** Delivery state of a single webhook attempt. */\nexport const WebhookDeliveryStatus = {\n Pending: 'PENDING',\n Succeeded: 'SUCCEEDED',\n Failed: 'FAILED',\n} as const;\nexport type WebhookDeliveryStatus =\n (typeof WebhookDeliveryStatus)[keyof typeof WebhookDeliveryStatus];\n\n/** Product billing kind. */\nexport const ProductKind = {\n Recurring: 'recurring',\n OneTime: 'one_time',\n Link: 'link',\n} as const;\nexport type ProductKind = (typeof ProductKind)[keyof typeof ProductKind];\n\n/** Lifecycle state of a swap. */\nexport const SwapStatus = {\n Pending: 'PENDING',\n Submitted: 'SUBMITTED',\n Succeeded: 'SUCCEEDED',\n Failed: 'FAILED',\n Expired: 'EXPIRED',\n} as const;\nexport type SwapStatus = (typeof SwapStatus)[keyof typeof SwapStatus];\n\n/** Which side of a pool an operation is on. */\nexport const LiquidityOperationKind = {\n Deposit: 'DEPOSIT',\n Withdraw: 'WITHDRAW',\n} as const;\nexport type LiquidityOperationKind =\n (typeof LiquidityOperationKind)[keyof typeof LiquidityOperationKind];\n\n/** Lifecycle state of a liquidity pool operation. */\nexport const LiquidityOperationStatus = {\n Pending: 'PENDING',\n Submitted: 'SUBMITTED',\n Succeeded: 'SUCCEEDED',\n Failed: 'FAILED',\n Expired: 'EXPIRED',\n} as const;\nexport type LiquidityOperationStatus =\n (typeof LiquidityOperationStatus)[keyof typeof LiquidityOperationStatus];\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Payment intents\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/payment-intents/tx`. */\nexport interface CreateTxPaymentIntentOptions {\n /** Payer's Stellar account — the transaction source. A registered address-book name also works. */\n source: string;\n /** Payee's Stellar account. A registered address-book name also works. */\n destination: string;\n /** Amount as a decimal string (max 7 decimals). */\n amount: string;\n /**\n * Typed asset (e.g. `Assets.USDC` or `defineAsset(...)`) — fills `assetCode`\n * and `assetIssuer` for you. Takes a back seat to explicit code/issuer below.\n */\n asset?: AssetRef;\n /** Asset code. Omit (or `XLM`/`native`) for native lumens. */\n assetCode?: string;\n /** Issuer account for a non-native asset. */\n assetIssuer?: string;\n /** MEMO_ID (numeric uint64) for idempotency + on-chain identification. Auto-generated when omitted. */\n memo?: string;\n /** SEP-7 `msg`: shown to the user in their wallet (≤ 300 chars). */\n msg?: string;\n /** SEP-7 `callback` where the wallet POSTs the signed XDR, e.g. `url:https://...`. */\n callback?: string;\n}\n\n/** Body for `POST /v1/payment-intents/pay`. */\nexport interface CreatePayPaymentIntentOptions {\n /** Payee's Stellar account. A registered address-book name also works. */\n destination: string;\n /** Amount the destination should receive. Omit to let the user enter it (e.g. donations). */\n amount?: string;\n /**\n * Typed asset (e.g. `Assets.USDC` or `defineAsset(...)`) — fills `assetCode`\n * and `assetIssuer` for you. Takes a back seat to explicit code/issuer below.\n */\n asset?: AssetRef;\n /** Asset code the destination receives. Omit for native lumens (XLM). */\n assetCode?: string;\n /** Issuer account for a non-native asset. */\n assetIssuer?: string;\n /** MEMO_ID (numeric uint64) for idempotency + on-chain identification. Auto-generated when omitted. */\n memo?: string;\n /** SEP-7 `msg`: shown to the user in their wallet (≤ 300 chars). */\n msg?: string;\n /** SEP-7 `callback`, e.g. `url:https://...`. */\n callback?: string;\n}\n\n/** Body for `PATCH /v1/payment-intents/:id`. */\nexport interface UpdatePaymentIntentOptions {\n status?: PaymentIntentStatus;\n /** Stellar transaction hash once the signed tx is submitted. */\n txHash?: string;\n /** Merchant reference. */\n reference?: string;\n}\n\n/** Query for `GET /v1/payment-intents`. */\nexport interface ListPaymentIntentsOptions {\n status?: PaymentIntentStatus;\n /** Page size (max 100, default 20). */\n take?: number;\n /** Offset (default 0). */\n skip?: number;\n}\n\n/** Raw payment intent payload returned by the API. */\nexport interface PaymentIntentData {\n id: string;\n kind: PaymentIntentKind;\n status: PaymentIntentStatus;\n network: string;\n source: string | null;\n destination: string;\n amount: string | null;\n asset: string;\n assetIssuer: string | null;\n memo: string;\n msg: string | null;\n callback: string | null;\n xdr: string | null;\n uri: string;\n qr: string;\n txHash: string | null;\n reference: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\n/** Raw paginated list of payment intents. */\nexport interface PaymentIntentListData {\n data: PaymentIntentData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Body for `POST /v1/payment-intents/:id/validate`. */\nexport interface ValidatePaymentIntentOptions {\n /** Hash of the submitted Stellar transaction to validate against this intent. */\n txHash: string;\n}\n\n/** Raw outcome of a validation attempt. */\nexport interface ValidationOutcomeData {\n valid: boolean;\n status: PaymentIntentStatus;\n reason?: string | null;\n paymentIntent?: PaymentIntentData;\n}\n\n/** Raw `{ id, deleted }` response. */\nexport interface DeletedData {\n id: string;\n deleted: boolean;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Webhooks\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/webhooks`. */\nexport interface CreateWebhookEndpointOptions {\n /** HTTPS URL that will receive POSTed event notifications. */\n url: string;\n description?: string;\n /** Event types to subscribe to. Omit/empty to receive all events. */\n eventTypes?: WebhookEventType[];\n}\n\n/** Body for `PATCH /v1/webhooks/:id`. */\nexport interface UpdateWebhookEndpointOptions {\n url?: string;\n description?: string;\n /** Pause/resume deliveries to this endpoint. */\n enabled?: boolean;\n eventTypes?: WebhookEventType[];\n}\n\n/** Raw webhook endpoint payload. */\nexport interface WebhookEndpointData {\n id: string;\n url: string;\n description: string | null;\n enabled: boolean;\n eventTypes: WebhookEventType[];\n createdAt: string;\n updatedAt: string;\n}\n\n/** Raw webhook endpoint payload including the one-time signing secret. */\nexport interface WebhookEndpointWithSecretData extends WebhookEndpointData {\n /** HMAC signing secret — shown once. Store it securely. */\n secret: string;\n}\n\n/** Raw result of a webhook ping. */\nexport interface WebhookPingData {\n ok: boolean;\n responseStatus: number | null;\n error: string | null;\n}\n\n/** Raw webhook delivery (audit) record. */\nexport interface WebhookDeliveryData {\n id: string;\n endpointId: string;\n eventType: WebhookEventType;\n eventId: string;\n payload: Record<string, unknown>;\n status: WebhookDeliveryStatus;\n attempts: number;\n responseStatus: number | null;\n error: string | null;\n lastAttemptAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\n/** Raw paginated list of webhook deliveries. */\nexport interface WebhookDeliveryListData {\n data: WebhookDeliveryData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Query for `GET /v1/webhooks/:id/deliveries`. */\nexport interface ListWebhookDeliveriesOptions {\n status?: WebhookDeliveryStatus;\n take?: number;\n skip?: number;\n}\n\n/** Shape of the JSON body POSTed to an integrator's webhook URL. */\nexport interface WebhookEvent<T = PaymentIntentData> {\n /** Stable event id (use for idempotency). */\n id: string;\n type: WebhookEventType;\n createdAt: string;\n data: T;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Products\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/products`. */\nexport interface CreateProductOptions {\n name: string;\n description?: string;\n /** Decimal price (≤ 7 decimals). Omit for a customer-set amount. */\n amount?: string;\n /** Asset code the price is in. Omit for native lumens (XLM). */\n assetCode?: string;\n kind?: ProductKind;\n active?: boolean;\n reference?: string;\n}\n\n/** Body for `PATCH /v1/products/:id`. */\nexport type UpdateProductOptions = Partial<CreateProductOptions>;\n\n/** Raw product payload. */\nexport interface ProductData {\n id: string;\n name: string;\n description: string | null;\n amount: string | null;\n asset: string;\n kind: ProductKind;\n active: boolean;\n reference: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Customers\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/customers`. */\nexport interface CreateCustomerOptions {\n name: string;\n alias?: string;\n note?: string;\n email?: string;\n /** Optional Stellar account to associate the customer with. */\n account?: string;\n reference?: string;\n}\n\n/** Body for `PATCH /v1/customers/:id`. */\nexport type UpdateCustomerOptions = Partial<CreateCustomerOptions>;\n\n/**\n * Raw customer payload.\n *\n * There is no `consumerId`: the API stopped sending it, because the owning\n * consumer is the key that made the call and an internal id is not part of the\n * contract.\n */\nexport interface CustomerData {\n id: string;\n name: string;\n alias: string | null;\n note: string | null;\n email: string | null;\n account: string | null;\n reference: string | null;\n createdAt: string;\n updatedAt: string;\n /** Derived on-chain stats (present in list responses). */\n payments?: number;\n succeeded?: number;\n total?: string;\n}\n\n/** Raw `{ data, total }` list of customers. */\nexport interface CustomerListData {\n data: CustomerData[];\n total: number;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Analytics\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface AnalyticsVolumeEntry {\n asset: string;\n amount: string;\n count: number;\n}\n\nexport interface AnalyticsSeriesPoint {\n date: string;\n count: number;\n volume: string;\n}\n\nexport interface AnalyticsRecentRow {\n id: string;\n kind: string;\n status: PaymentIntentStatus;\n amount: string | null;\n asset: string;\n destination: string;\n createdAt: string;\n}\n\n/** Raw overview metrics returned by `GET /v1/summary`. */\nexport interface AnalyticsSummaryData {\n totals: {\n all: number;\n succeeded: number;\n pending: number;\n submitted: number;\n failed: number;\n cancelled: number;\n expired: number;\n successRate: number;\n };\n volume: AnalyticsVolumeEntry[];\n webhooks: {\n endpoints: number;\n deliveries: number;\n failedDeliveries: number;\n };\n customers: number;\n series: AnalyticsSeriesPoint[];\n recent: AnalyticsRecentRow[];\n}\n\nexport interface AnalyticsBalanceEntry {\n asset: string;\n amount: string;\n pending: string;\n count: number;\n}\n\n/** Raw balances returned by `GET /v1/balances`. */\nexport interface AnalyticsBalancesData {\n data: AnalyticsBalanceEntry[];\n total: number;\n}\n\nexport interface ApiLogRow {\n id: string;\n method: string;\n path: string;\n statusCode: number;\n durationMs: number;\n ip: string | null;\n userAgent: string | null;\n status: 'ok' | 'pending' | 'fail';\n at: string;\n}\n\n/** Raw API request log returned by `GET /v1/logs`. */\nexport interface ApiLogsData {\n data: ApiLogRow[];\n total: number;\n}\n\nexport interface WebhookLogRow {\n id: string;\n endpointId: string;\n url: string | null;\n eventType: WebhookEventType;\n eventId: string;\n attempts: number;\n responseStatus: number | null;\n error: string | null;\n status: 'ok' | 'pending' | 'fail';\n at: string;\n}\n\n/** Raw webhook delivery log returned by `GET /v1/logs/webhooks`. */\nexport interface WebhookLogsData {\n data: WebhookLogRow[];\n total: number;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Health\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface HealthCheckData {\n status: string;\n info?: Record<string, { status: string } & Record<string, unknown>> | null;\n error?: Record<string, { status: string } & Record<string, unknown>> | null;\n details?: Record<string, { status: string } & Record<string, unknown>>;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Swaps\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/swaps/quote` (pricing only; no fee parameter — the fee is enforced server-side per organization). */\nexport interface QuoteSwapOptions {\n /** Amount to send, as a decimal string (max 7 decimals). */\n amount: string;\n /** Source asset code. Omit (or `XLM`/`native`) for native lumens. */\n sourceAssetCode?: string;\n /** Issuer account for a non-native source asset. */\n sourceAssetIssuer?: string;\n /** Destination asset code the swap should deliver. */\n destAssetCode: string;\n /** Issuer account for a non-native destination asset. */\n destAssetIssuer?: string;\n /** Allowed slippage in basis points. */\n slippageBps?: number;\n}\n\n/** Body for `POST /v1/swaps`. */\nexport interface CreateSwapOptions extends QuoteSwapOptions {\n /** Source account performing the swap. A registered address-book name also works. */\n source: string;\n /** Destination account that receives the swapped asset. Defaults to the source. */\n destination?: string;\n /** MEMO_ID (numeric uint64) for idempotency + on-chain identification. */\n memo?: string;\n}\n\n/** Body for `POST /v1/swaps/:id/submit`. */\nexport interface SubmitSwapOptions {\n /** Signed transaction envelope (base64 XDR) to relay to the network. */\n signedXdr: string;\n}\n\n/** Query for `GET /v1/swaps`. */\nexport interface ListSwapsOptions {\n status?: SwapStatus;\n /** Page size (max 100, default 20). */\n take?: number;\n /** Offset (default 0). */\n skip?: number;\n}\n\n/** Raw swap payload returned by the API. */\nexport interface SwapData {\n id: string;\n status: SwapStatus;\n network: string;\n source: string;\n destination: string;\n sendAsset: string;\n sendAssetIssuer: string | null;\n sendAmount: string;\n feeAmount: string;\n feeBps: number;\n swapAmount: string;\n destAsset: string;\n destAssetIssuer: string | null;\n destEstimated: string;\n destMin: string;\n slippageBps: number;\n path: { code: string; issuer: string | null }[];\n memo: string | null;\n xdr: string;\n uri: string;\n txHash: string;\n qr: string;\n createdAt: string;\n updatedAt: string;\n}\n\n/** Raw paginated list of swaps. */\nexport interface SwapListData {\n data: SwapData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Raw pricing quote returned by `POST /v1/swaps/quote`. */\nexport interface SwapQuoteData {\n network: string;\n source: { asset: string; issuer: string | null; amount: string };\n fee: { asset: string; issuer: string | null; amount: string; bps: number; wallet: string | null };\n swap: { asset: string; issuer: string | null; amount: string };\n destination: {\n asset: string;\n issuer: string | null;\n estimated: string;\n minimum: string;\n slippageBps: number;\n };\n path: { code: string; issuer: string | null }[];\n}\n\n/** Raw outcome of relaying a signed swap transaction. */\nexport interface SwapSubmitOutcomeData {\n submitted: boolean;\n status: SwapStatus;\n txHash?: string;\n reason?: string;\n resultCodes?: string[];\n swap: SwapData;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Liquidity pools\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Body for `POST /v1/liquidity-pools/deposit`. */\nexport interface DepositLiquidityOptions {\n /** Account whose funds go in, and which signs. An address-book name also works. */\n source: string;\n /** Asset A code. Omit (or `XLM`/`native`) for native lumens. */\n assetACode?: string;\n /** Issuer for a non-native asset A. */\n assetAIssuer?: string;\n /** Asset B code. */\n assetBCode?: string;\n /** Issuer for a non-native asset B. */\n assetBIssuer?: string;\n /** Ceiling on how much of asset A may go in, as a decimal string. */\n maxAmountA: string;\n /** Ceiling on how much of asset B may go in. */\n maxAmountB: string;\n /** Allowed price movement in basis points. */\n slippageBps?: number;\n /** MEMO_ID (numeric uint64) for on-chain identification. */\n memo?: string;\n /**\n * Idempotency token. Sent both as the body field and as the `Idempotency-Key`\n * header, which is what makes a retried deposit return the FIRST operation\n * instead of building a second one against the same funds.\n */\n idempotencyKey?: string;\n}\n\n/** Body for `POST /v1/liquidity-pools/withdraw`. */\nexport interface WithdrawLiquidityOptions {\n /** Account holding the shares, and which signs. */\n source: string;\n /** The pool to withdraw from (hex id). */\n poolId: string;\n /** Pool shares to burn, as a decimal string. */\n shares: string;\n /** Allowed price movement in basis points. */\n slippageBps?: number;\n memo?: string;\n /** See {@link DepositLiquidityOptions.idempotencyKey}. */\n idempotencyKey?: string;\n}\n\n/** Body for `POST /v1/liquidity-pools/operations/:id/submit`. */\nexport interface SubmitLiquidityOptions {\n /** Signed transaction envelope (base64 XDR) to relay to the network. */\n signedXdr: string;\n}\n\n/** Query for `GET /v1/liquidity-pools/operations`. */\nexport interface ListLiquidityOperationsOptions {\n kind?: LiquidityOperationKind;\n status?: LiquidityOperationStatus;\n /** Page size (max 100, default 20). */\n take?: number;\n /** Offset (default 0). */\n skip?: number;\n}\n\n/** Query for `GET /v1/liquidity-pools` (Horizon proxy). */\nexport interface BrowseLiquidityPoolsOptions {\n assetACode?: string;\n assetAIssuer?: string;\n assetBCode?: string;\n assetBIssuer?: string;\n /** Only pools this account holds shares in. */\n account?: string;\n /** Horizon paging cursor from a previous page. */\n cursor?: string;\n limit?: number;\n}\n\n/** One side of a pool's reserves. */\nexport interface LiquidityReserveData {\n asset: string;\n issuer: string | null;\n amount: string;\n}\n\n/** Raw on-chain pool payload (Horizon proxy). */\nexport interface LiquidityPoolData {\n id: string;\n network: string;\n /** Pool fee in basis points — 30 for every constant-product pool today. */\n feeBp: number;\n totalTrustlines: string;\n totalShares: string;\n reserves: LiquidityReserveData[];\n}\n\n/** Raw cursor-paginated list of pools. */\nexport interface LiquidityPoolListData {\n data: LiquidityPoolData[];\n cursor?: string | null;\n}\n\n/** One account's stake in one pool. */\nexport interface LiquidityPositionData {\n poolId: string;\n /** Shares this account holds. */\n shares: string;\n /** Shares in existence. */\n totalShares: string;\n /** The account's share of the pool, in basis points. */\n shareOfPoolBps: number;\n reserves: LiquidityReserveData[];\n /** What those shares would redeem for right now. */\n redeemable: LiquidityReserveData[];\n}\n\n/** Raw payload of `GET /v1/liquidity-pools/positions`. */\nexport interface LiquidityPositionsData {\n account: string;\n network: string;\n data: LiquidityPositionData[];\n}\n\n/** Raw liquidity operation payload returned by the API. */\nexport interface LiquidityOperationData {\n id: string;\n kind: LiquidityOperationKind;\n status: LiquidityOperationStatus;\n network: string;\n source: string;\n poolId: string;\n assetA: string;\n assetAIssuer: string | null;\n assetB: string;\n assetBIssuer: string | null;\n amountA: string;\n amountB: string;\n shares: string | null;\n minPrice: string | null;\n maxPrice: string | null;\n slippageBps: number;\n idempotencyKey: string | null;\n feeBps: number;\n feeAmountA: string;\n feeAmountB: string;\n feeWallet: string | null;\n commissionMemo: string | null;\n xdr: string;\n uri: string;\n txHash: string;\n qr: string;\n expiresAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\n/** Raw paginated list of liquidity operations. */\nexport interface LiquidityOperationListData {\n data: LiquidityOperationData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Raw outcome of relaying a signed liquidity transaction. */\nexport interface LiquiditySubmitOutcomeData {\n submitted: boolean;\n status: LiquidityOperationStatus;\n txHash?: string;\n reason?: string;\n resultCodes?: string[];\n operation: LiquidityOperationData;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Activity (client event stream)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Where an event came from. */\nexport type ActivitySource = 'wallet' | 'dashboard' | 'server' | 'sdk';\n\n/** Severity of an event. */\nexport type ActivityLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/** One event to report. Always batched — see {@link ReportActivityOptions}. */\nexport interface ActivityEventInput {\n /** Dotted event name, e.g. `payment.submitted`. */\n type: string;\n /**\n * Client-generated id. The service de-duplicates on it, which is what makes a\n * retried batch safe: the second delivery is counted as a duplicate rather than\n * stored twice.\n */\n eventId?: string;\n source?: ActivitySource;\n level?: ActivityLevel;\n category?: string;\n message?: string;\n sessionId?: string;\n distinctId?: string;\n appVersion?: string;\n platform?: string;\n network?: string;\n durationMs?: number;\n /** Free-form properties. Never put secrets or memo text here. */\n props?: Record<string, unknown>;\n /** When it happened (ISO-8601). Defaults to arrival time. */\n occurredAt?: string;\n}\n\n/** Body for `POST /v1/activity/events`. */\nexport interface ReportActivityOptions {\n events: ActivityEventInput[];\n}\n\n/** Raw outcome of a reported batch. */\nexport interface ActivityReportData {\n accepted: number;\n /** Events whose `eventId` had already been stored. */\n duplicates: number;\n}\n\n/** Query for `GET /v1/activity/events`. */\nexport interface ListActivityOptions {\n take?: number;\n skip?: number;\n source?: ActivitySource;\n level?: ActivityLevel;\n category?: string;\n type?: string;\n network?: string;\n /** ISO-8601 lower bound (inclusive). */\n since?: string;\n /** ISO-8601 upper bound (exclusive). */\n until?: string;\n}\n\n/** One stored event. */\nexport interface ActivityEventData {\n id: string;\n source: string;\n level: string;\n category: string;\n type: string;\n message: string | null;\n sessionId: string | null;\n distinctId: string | null;\n appVersion: string | null;\n platform: string | null;\n network: string | null;\n durationMs: number | null;\n props: Record<string, unknown> | null;\n ip: string | null;\n userAgent: string | null;\n /** When it happened. */\n at: string;\n /** When the service stored it. */\n receivedAt: string;\n}\n\n/** Raw paginated list of events. */\nexport interface ActivityListData {\n data: ActivityEventData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** One `{ key, count }` bucket of an activity summary. */\nexport interface ActivityBucket {\n key: string;\n count: number;\n}\n\n/** Raw payload of `GET /v1/activity/summary`. */\nexport interface ActivitySummaryData {\n total: number;\n sessions: number;\n devices: number;\n levels: ActivityBucket[];\n sources: ActivityBucket[];\n categories: ActivityBucket[];\n topTypes: ActivityBucket[];\n topErrors: ActivityBucket[];\n series: { date: string; count: number; errors: number }[];\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// On-ramp (fiat -> stablecoin)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Stablecoins the ramps settle in. */\nexport type RampToken = 'USDC' | 'USDT' | 'USDB';\n\n/** Which side of a quote the requested amount refers to. */\nexport type CurrencyType = 'sender' | 'receiver';\n\n/** Fiat rails a payin can arrive over. */\nexport type PayinMethod =\n | 'ach'\n | 'wire'\n | 'pix'\n | 'ted'\n | 'spei'\n | 'transfers'\n | 'pse'\n | 'international_swift'\n | 'rtp';\n\n/** Payer restrictions, for the rails that require them. */\nexport interface PayinPayerRules {\n pix_allowed_tax_ids?: string[];\n transfers_allowed_tax_id?: string;\n pse_allowed_tax_ids?: string[];\n pse_full_name?: string;\n pse_document_type?: string;\n pse_document_number?: string;\n pse_email?: string;\n pse_phone?: string;\n pse_bank_code?: string;\n}\n\n/**\n * Body for `POST /v1/onramp/quotes`.\n *\n * The field names are snake_case because they are the RAMP PROVIDER's, and the\n * service passes them through unchanged. Renaming them here would look tidier and\n * would put a translation layer between two systems that already agree.\n */\nexport interface CreatePayinQuoteOptions {\n /** Wallet that receives the converted stablecoin. */\n blockchain_wallet_id: string;\n currency_type: CurrencyType;\n payment_method: PayinMethod;\n token: RampToken;\n /** Amount in MINOR units (e.g. cents). */\n request_amount: number;\n cover_fees?: boolean;\n payer_rules?: PayinPayerRules;\n is_otc?: boolean;\n partner_fee_id?: string;\n wallet_id?: string;\n}\n\n/** Raw payin quote. Expires quickly — read `expires_at` before acting on it. */\nexport interface PayinQuoteData {\n id: string;\n /** Unix seconds (~5 minutes out). */\n expires_at: number;\n commercial_quotation?: number;\n receiver_amount?: number;\n sender_amount?: number;\n}\n\n/** Body for `POST /v1/onramp/payins`. */\nexport interface CreatePayinOptions {\n payin_quote_id: string;\n}\n\n/** Query for `GET /v1/onramp/payins`. */\nexport interface ListPayinsOptions {\n take?: number;\n skip?: number;\n}\n\n/**\n * Raw payin. The scalar fields are mirrored locally; `instructions` is passed\n * through from the provider verbatim (memo / CLABE / PIX code / CBU / PSE link…),\n * so its shape depends on `paymentMethod` and is deliberately not narrowed here.\n */\nexport interface PayinData {\n id: string;\n blindpayId: string;\n status: string | null;\n token: string | null;\n network: string | null;\n paymentMethod: string | null;\n /** Minor units, as a decimal string. */\n senderAmount: string | null;\n receiverAmount: string | null;\n instructions: unknown;\n createdAt: string;\n}\n\n/** Raw paginated list of payins. */\nexport interface PayinListData {\n data: PayinData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Body for `POST /v1/onramp/trustline`. */\nexport interface CreateTrustlineOptions {\n /** Stellar address that needs the asset trustline. */\n address: string;\n}\n\n/**\n * Raw trustline response — a provider passthrough, which is why it is an open\n * shape. It carries the unsigned envelope the customer signs; a wallet reads `xdr`\n * off it and must put that through its own signing guard before signing.\n */\nexport interface TrustlineData {\n xdr?: string;\n [key: string]: unknown;\n}\n\n/** Banking partners a virtual account can be opened with. */\nexport type BankingPartner = 'jpmorgan' | 'citi' | 'hsbc' | 'cfsb';\n\n/** Body for `POST /v1/onramp/receivers/:receiverId/virtual-accounts`. */\nexport interface CreateVirtualAccountOptions {\n banking_partner: BankingPartner;\n token: RampToken;\n /** Cosmos Pay wallet id that receives the converted stablecoin. */\n blockchain_wallet_id: string;\n signed_agreement_id?: string;\n sole_proprietor_doc_type?: string;\n sole_proprietor_doc_file?: string;\n}\n\n/** Raw virtual account — a provider passthrough. */\nexport type VirtualAccountData = Record<string, unknown>;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Off-ramp (stablecoin -> fiat)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Chains a payout can be funded from. */\nexport type PayoutNetwork =\n | 'ethereum'\n | 'base'\n | 'arbitrum'\n | 'polygon'\n | 'stellar'\n | 'solana'\n | 'tron'\n | 'sepolia'\n | 'base_sepolia'\n | 'arbitrum_sepolia'\n | 'polygon_amoy'\n | 'stellar_testnet'\n | 'solana_devnet';\n\n/** Chain families the authorize / create steps distinguish. */\nexport type PayoutChain = 'evm' | 'stellar' | 'solana';\n\n/** Body for `POST /v1/offramp/quotes`. */\nexport interface CreatePayoutQuoteOptions {\n /** Destination bank account, belonging to a verified receiver. */\n bank_account_id: string;\n currency_type: CurrencyType;\n cover_fees?: boolean;\n /** Amount in MINOR units. */\n request_amount: number;\n network: PayoutNetwork;\n token: RampToken;\n description?: string;\n partner_fee_id?: string;\n}\n\n/** Raw payout quote. */\nexport interface PayoutQuoteData {\n id: string;\n /** Unix seconds (~5 minutes out). */\n expires_at: number;\n sender_amount?: number;\n /** Local fiat amount to receive, in minor units. */\n receiver_amount?: number;\n receiver_local_amount?: number;\n /** EVM `approve` payload to sign (abi, address, functionName, amount). */\n contract?: unknown;\n}\n\n/** Body for `POST /v1/offramp/payouts/authorize`. */\nexport interface AuthorizePayoutOptions {\n quote_id: string;\n sender_wallet_address: string;\n /** Only the chains that need an unsigned transaction built for them. */\n chain: 'stellar' | 'solana';\n}\n\n/**\n * Raw authorize response — the unsigned transaction, passed through from the\n * provider. Its `xdr` (Stellar) is what a wallet must bound against the quote the\n * user actually confirmed before signing it.\n */\nexport interface AuthorizePayoutData {\n xdr?: string;\n [key: string]: unknown;\n}\n\n/** Body for `POST /v1/offramp/payouts`. */\nexport interface CreatePayoutOptions {\n quote_id: string;\n sender_wallet_address: string;\n chain: PayoutChain;\n /** The signed transaction produced from `authorize` (or the EVM approval). */\n signed_transaction?: string;\n}\n\n/** Query for `GET /v1/offramp/payouts`. */\nexport interface ListPayoutsOptions {\n take?: number;\n skip?: number;\n}\n\n/** Raw payout. Same mirroring rules as {@link PayinData}. */\nexport interface PayoutData {\n id: string;\n blindpayId: string;\n status: string | null;\n token: string | null;\n network: string | null;\n /** Fiat rail the money lands on. */\n rail: string | null;\n senderAmount: string | null;\n receiverAmount: string | null;\n senderWalletAddress: string | null;\n createdAt: string;\n}\n\n/** Raw paginated list of payouts. */\nexport interface PayoutListData {\n data: PayoutData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Body for `POST /v1/offramp/payouts/:id/documents`. */\nexport interface AttachPayoutDocumentOptions {\n transaction_document_type?: string;\n transaction_document_id?: string;\n /** Base64 (or data URL) of the document itself. */\n transaction_document_file?: string;\n description?: string;\n}\n\n/** Raw document response — a provider passthrough. */\nexport type PayoutDocumentData = Record<string, unknown>;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// KYC / KYB (receivers, wallets, bank accounts)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** A receiver is a person or a company. */\nexport type ReceiverType = 'individual' | 'business';\n\n/** How deep the verification goes. */\nexport type KycType = 'light' | 'standard' | 'enhanced';\n\n/** One beneficial owner of a business receiver. */\nexport interface ReceiverOwner {\n role?: string;\n first_name?: string;\n last_name?: string;\n date_of_birth?: string;\n tax_id?: string;\n country?: string;\n address_line_1?: string;\n address_line_2?: string;\n city?: string;\n state_province_region?: string;\n postal_code?: string;\n /** Ownership percentage. */\n ownership_percentage?: number;\n title?: string;\n id_doc_country?: string;\n id_doc_type?: string;\n /** `file_url` from `POST /v1/kyc/upload`. */\n id_doc_front_file?: string;\n id_doc_back_file?: string;\n proof_of_address_doc_type?: string;\n /** `file_url` from `POST /v1/kyc/upload`. */\n proof_of_address_doc_file?: string;\n /** The owner's tax id type. */\n tax_type?: string;\n}\n\n/**\n * Body for `POST /v1/kyc/receivers`.\n *\n * Every `*_file` field takes a `file_url` returned by {@link KycManager.upload} —\n * not the bytes. Upload first, then create the receiver with the URLs.\n */\nexport interface CreateReceiverOptions {\n type: ReceiverType;\n kyc_type: KycType;\n email: string;\n /** ISO 3166-1 alpha-2 country code. */\n country: string;\n first_name?: string;\n last_name?: string;\n /** ISO-8601 datetime. A date-only value is rejected upstream. */\n date_of_birth?: string;\n tax_id?: string;\n occupation?: string;\n id_doc_country?: string;\n id_doc_type?: string;\n /** `file_url` from `POST /v1/kyc/upload`. */\n id_doc_front_file?: string;\n id_doc_back_file?: string;\n selfie_file?: string;\n account_purpose?: string;\n account_purpose_other?: string;\n source_of_funds_doc_type?: string;\n source_of_funds_doc_file?: string;\n source_of_wealth?: string;\n /** `master_service_agreement` | `salary_slip` | `bank_statement`. */\n sole_proprietor_doc_type?: string;\n proof_of_address_doc_type?: string;\n proof_of_address_doc_file?: string;\n recipient_relationship?: string;\n purpose_of_transactions?: string;\n purpose_of_transactions_explanation?: string;\n legal_name?: string;\n alternate_name?: string;\n business_type?: string;\n business_industry?: string;\n business_description?: string;\n formation_date?: string;\n estimated_annual_revenue?: string;\n publicly_traded?: boolean;\n website?: string;\n incorporation_doc_file?: string;\n proof_of_ownership_doc_file?: string;\n owners?: ReceiverOwner[];\n address_line_1?: string;\n address_line_2?: string;\n city?: string;\n state_province_region?: string;\n postal_code?: string;\n phone_number?: string;\n ip_address?: string;\n /** Your own id for this receiver. */\n external_id?: string;\n image_url?: string;\n /**\n * Accepted terms-of-service id, from the redirect of\n * {@link KycManager.termsOfService}. The provider requires it to create a\n * receiver, which is why ToS is the FIRST step of the flow rather than the last.\n */\n tos_id?: string;\n}\n\n/**\n * Body for `PATCH /v1/kyc/receivers/:id` — the same fields, all optional.\n *\n * Identity is reviewed before it reaches the provider, edits included. Until the\n * receiver is enabled, an edit that touches KYC data sends it back to\n * `pending_review`. Once it exists at the provider, a tenant key may change only\n * `external_id` and `image_url`; any other field is `403 kyc_review_required` unless\n * the key is elevated (`X-Consumer-Role: admin`), because that edit rewrites the\n * identity at the provider directly.\n */\nexport type UpdateReceiverOptions = Partial<CreateReceiverOptions>;\n\n/** Body for `POST /v1/kyc/receivers/:id/approve`. */\nexport interface ApproveReceiverOptions {\n redirect_url?: string;\n /**\n * The {@link ReceiverData.dossierVersion} this approval is for.\n *\n * Approving is a statement about KYC data someone read and accepted, and the\n * tenant can edit that data in between: an edit leaves the receiver in\n * `pending_review`, so without a version the approval lands on whatever is\n * stored when the request arrives and nobody can tell. Send it and a dossier\n * that moved on is a `409 kyc_state_invalid` — re-read, review again, approve\n * that version.\n *\n * {@link Receiver.approve} fills this in from the instance; omit it there only\n * if you mean \"approve whatever is stored now\".\n */\n expected_version?: number;\n}\n\n/** Body for `POST /v1/kyc/receivers/:id/tos`. */\nexport interface RequestTosOptions {\n /** `code` returns the URL to show; `email` sends it to the receiver. */\n channel: 'code' | 'email';\n redirect_url?: string;\n}\n\n/** Body for `POST /v1/kyc/receivers/:id/enable`. */\nexport interface EnableReceiverOptions {\n /** An accepted terms-of-service id. */\n tos_id: string;\n}\n\n/** Body for `PATCH /v1/kyc/receivers/:id/access`. */\nexport interface SetReceiverAccessOptions {\n /** `true` cuts this receiver off from both ramps — an admin kill switch. */\n disabled: boolean;\n}\n\n/** Query for the paginated KYC collections. */\nexport interface ListKycOptions {\n take?: number;\n skip?: number;\n}\n\n/** Raw receiver payload. `kycStatus` is refreshed from the provider on read. */\nexport interface ReceiverData {\n id: string;\n blindpayId: string;\n type: string;\n kycType: string | null;\n kycStatus: string | null;\n email: string | null;\n name: string | null;\n country: string | null;\n externalId: string | null;\n /** True when the receiver is cut off from the ramps. */\n disabled: boolean;\n /**\n * How many times the submitted KYC data has been written. Send it back as\n * `expected_version` when approving, so the approval cannot land on a dossier\n * nobody read.\n */\n dossierVersion: number;\n /**\n * The `dossierVersion` a reviewer approved, or null while unapproved. The\n * receiver cannot be enabled until it equals {@link ReceiverData.dossierVersion}\n * again, so an edit after approval sends it back through review.\n */\n reviewedVersion: number | null;\n createdAt: string;\n updatedAt: string;\n}\n\n/** Raw paginated list of receivers. */\nexport interface ReceiverListData {\n data: ReceiverData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Chains a receiver wallet can be registered on. */\nexport type ReceiverWalletNetwork =\n | 'ethereum'\n | 'base'\n | 'arbitrum'\n | 'polygon'\n | 'stellar'\n | 'solana'\n | 'tron'\n | 'sepolia';\n\n/** Body for `POST /v1/kyc/receivers/:receiverId/wallets`. */\nexport interface CreateReceiverWalletOptions {\n name?: string;\n network: ReceiverWalletNetwork;\n address: string;\n /**\n * Proof the receiver controls the address, for the secure-wallet flow: the hash\n * of the transaction that signed the message from\n * {@link KycManager.walletSignMessage}.\n */\n signature_tx_hash?: string;\n is_account_abstraction?: boolean;\n}\n\n/** Raw receiver wallet payload. */\nexport interface ReceiverWalletData {\n id: string;\n blindpayId: string;\n name: string | null;\n network: string;\n address: string | null;\n isAccountAbstraction: boolean;\n createdAt: string;\n}\n\n/** Raw paginated list of receiver wallets. */\nexport interface ReceiverWalletListData {\n data: ReceiverWalletData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Fiat rails a bank account can be opened on. */\nexport type BankRail =\n | 'wire'\n | 'ach'\n | 'rtp'\n | 'pix'\n | 'pix_safe'\n | 'ted'\n | 'spei_bitso'\n | 'transfers_bitso';\n\n/**\n * Body for `POST /v1/kyc/receivers/:receiverId/bank-accounts`.\n *\n * Only the fields every rail shares are named here. The rest — `pix_*`, `ted_*`,\n * `spei_*`, `swift_*`, `sepa_*`, `ach_cop_*`, some seventy of them — depend on\n * `type`, and the authority on which ones a given rail needs is\n * {@link KycManager.bankDetails}, at runtime. Enumerating them in a published type\n * would freeze a provider's field list into a release of this SDK and break the\n * day it adds a rail.\n */\nexport interface CreateBankAccountOptions {\n type: BankRail;\n /** Label for the account. */\n name: string;\n account_class?: 'individual' | 'business';\n account_type?: 'checking' | 'saving';\n beneficiary_name?: string;\n recipient_relationship?: string;\n account_number?: string;\n routing_number?: string;\n business_industry?: string;\n phone_number?: string;\n tax_id?: string;\n address_line_1?: string;\n address_line_2?: string;\n city?: string;\n state_province_region?: string;\n country?: string;\n postal_code?: string;\n /** Rail-specific fields. See `bankDetails(rail)` for the ones a rail requires. */\n [key: string]: unknown;\n}\n\n/** Raw bank account payload. */\nexport interface BankAccountData {\n id: string;\n blindpayId: string;\n rail: string | null;\n name: string | null;\n country: string | null;\n createdAt: string;\n}\n\n/** Raw paginated list of bank accounts. */\nexport interface BankAccountListData {\n data: BankAccountData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Body for `POST /v1/kyc/terms-of-service`. */\nexport interface InitiateTosOptions {\n redirect_url?: string;\n /** Attach the acceptance to an existing receiver. */\n receiver_id?: string;\n idempotency_key?: string;\n}\n\n/**\n * Raw terms-of-service response — a provider passthrough carrying the hosted URL\n * the receiver has to visit.\n */\nexport interface TermsOfServiceData {\n url?: string;\n [key: string]: unknown;\n}\n\n/** Raw upload response. `file_url` is what every `*_file` field expects. */\nexport interface KycUploadData {\n file_url?: string;\n [key: string]: unknown;\n}\n\n/** Raw response of the rails catalogue / a rail's field schema — passthroughs. */\nexport type KycRailsData = unknown;\nexport type BankDetailsData = unknown;\n\n/** Raw response of the wallet sign-message challenge — a provider passthrough. */\nexport interface WalletSignMessageData {\n message?: string;\n [key: string]: unknown;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Pollar (social login + custodial wallets)\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Identity providers a Pollar login can go through. */\nexport type PollarProvider = 'google' | 'github';\n\n/** State of a login, polled between the redirect and the token exchange. */\nexport type PollarLoginStatus =\n | 'pending'\n | 'authorized'\n | 'exchanging'\n | 'consumed'\n | 'failed'\n | 'expired';\n\n/** A Pollar wallet, as returned alongside a session or a registration. */\nexport interface PollarWalletData {\n type: 'internal' | 'smart' | 'external';\n address: string | null;\n chain: 'STELLAR' | 'POLYGON' | 'SOLANA';\n /** False until the reserve is funded — see {@link PollarManager.activateWallet}. */\n exists_on_stellar?: boolean;\n funding_mode?: 'IMMEDIATE' | 'DEFERRED';\n network?: string;\n}\n\n/** The public half of the DPoP key a client binds its session to. */\nexport interface PollarDpopJwk {\n kty: 'EC';\n crv: 'P-256';\n x: string;\n y: string;\n}\n\n/** The fields both login flows accept. */\nexport interface PollarAuthorizeBaseOptions {\n provider: PollarProvider;\n code_challenge_method?: 'S256';\n /** Binds the resulting session to a key this client holds. */\n dpop_jwk?: PollarDpopJwk;\n /** Shown to the user in their session list. */\n device_label?: string;\n}\n\n/**\n * Body for `POST /v1/pollar/oauth/authorize`.\n *\n * The code that comes back is redeemed with the `code_verifier` the challenge was\n * derived from, so an intercepted code is worth nothing without the client that\n * started the flow. How much that matters depends on the flow, and the type follows:\n *\n * - **Redirect** (`redirect_uri` set): `code_challenge` is required. The code crosses\n * a browser, and the public callback hands it to whoever presents `state` — which\n * is inside `authorization_url` — so the service answers `400 validation_failed`\n * to a redirect-flow authorize without one.\n * - **Poll** (no `redirect_uri`): the code only travels over your authenticated\n * channel, so PKCE is optional. Send it anyway.\n */\nexport type PollarAuthorizeOptions =\n | (PollarAuthorizeBaseOptions & {\n /** Where the browser lands with the code. Must be allow-listed for the consumer. */\n redirect_uri: string;\n /** Base64url SHA-256 of the verifier held by the client. */\n code_challenge: string;\n })\n | (PollarAuthorizeBaseOptions & {\n redirect_uri?: undefined;\n /** Base64url SHA-256 of the verifier held by the client. */\n code_challenge?: string;\n });\n\n/** Raw authorize response — where to send the user, and what to poll. */\nexport interface PollarAuthorizeData {\n /** Correlates the login. Poll `sessions/{state}` with it. */\n state: string;\n /** The URL to open for the user. */\n authorization_url: string;\n provider: PollarProvider;\n redirect_uri: string | null;\n expires_at: string;\n}\n\n/** Raw polling response for a login in progress. */\nexport interface PollarLoginSessionData {\n status: PollarLoginStatus;\n state: string;\n /** The bridge code to redeem — present once `status` is `authorized`. */\n code?: string;\n code_expires_at?: string | null;\n error_code?: string | null;\n}\n\n/** Body for `POST /v1/pollar/oauth/token`. */\nexport interface PollarTokenOptions {\n /** The bridge code collected from the polled session. */\n code: string;\n /** The PKCE verifier the challenge was derived from. Required when `authorize` sent a `code_challenge`. */\n code_verifier?: string;\n}\n\n/** A user profile as Pollar knows it. */\nexport interface PollarProfileData {\n email?: string;\n first_name?: string;\n last_name?: string;\n avatar?: string;\n [key: string]: unknown;\n}\n\n/** Raw Pollar session — the tokens, the wallets and the profile. */\nexport interface PollarSessionData {\n access_token: string;\n refresh_token?: string;\n token_type?: 'Bearer' | 'DPoP';\n /** Unix seconds. */\n expires_at?: number;\n user_id?: string | null;\n /** The primary wallet; `wallets` carries the rest. */\n wallet?: PollarWalletData;\n wallets?: PollarWalletData[];\n profile?: PollarProfileData;\n}\n\n/** Body for `POST /v1/pollar/oauth/refresh`. */\nexport interface PollarRefreshOptions {\n refresh_token: string;\n}\n\n/** Raw rotated token pair. */\nexport interface PollarRefreshData {\n access_token: string;\n refresh_token?: string;\n token_type?: 'Bearer';\n expires_at?: number;\n}\n\n/** Body for `POST /v1/pollar/oauth/logout`. */\nexport interface PollarLogoutOptions {\n access_token: string;\n /** Revoke every device, not just this one. */\n everywhere?: boolean;\n}\n\n/** How many sessions the logout revoked. */\nexport interface PollarLogoutData {\n revoked: number;\n}\n\n/** Body for `POST /v1/pollar/wallets/activate`. */\nexport interface ActivatePollarWalletOptions {\n public_key: string;\n}\n\n/** Raw activation result — the reserve that was funded. */\nexport interface PollarActivationData {\n public_key: string;\n /** XLM sent to cover the base reserve. */\n amount: string;\n activated: boolean;\n}\n\n/** One asset to enable on a wallet. */\nexport interface PollarTrustlineAsset {\n code: string;\n issuer: string;\n}\n\n/** Body for `POST /v1/pollar/wallets/:address/trustlines`. */\nexport interface PollarTrustlinesOptions {\n assets: PollarTrustlineAsset[];\n}\n\n/** Raw trustline result — a status code for the operation. */\nexport interface PollarTrustlineData {\n code: string;\n [key: string]: unknown;\n}\n\n/** Body for `POST /v1/pollar/users` and `/users/with-wallet`. */\nexport interface RegisterPollarUserOptions {\n /** Your own id for this user — how you find them again. */\n external_id: string;\n email?: string;\n first_name?: string;\n last_name?: string;\n avatar?: string;\n}\n\n/** Raw registration result. */\nexport interface PollarUserData {\n external_id: string;\n code: 'SERVER_USER_REGISTERED' | 'SERVER_USER_WALLET_CREATED';\n user_id: string | null;\n wallet?: PollarWalletData;\n}\n\n/** Body for `POST /v1/pollar/tokens/verify`. */\nexport interface VerifyPollarTokenOptions {\n token: string;\n}\n\n/** Raw verification result — who the token belongs to, and until when. */\nexport interface PollarTokenVerificationData {\n user_id: string;\n application_id: string;\n /** Unix seconds. */\n expires_at: number;\n network?: string;\n auth_provider?: string;\n wallet?: PollarWalletData;\n}\n","import type { Client } from '@/client/Client';\nimport {\n LiquidityOperationKind,\n LiquidityOperationStatus,\n type LiquidityOperationData,\n type SubmitLiquidityOptions,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\nimport type { LiquiditySubmitOutcome } from '@/managers/LiquidityManager';\n\n/**\n * One deposit into, or withdrawal from, a Stellar liquidity pool.\n *\n * The server builds the envelope and the wallet signs it, so an operation is a\n * two-step object: it arrives `PENDING` carrying an unsigned `xdr`, and reaches\n * `SUBMITTED`/`SUCCEEDED` only once the signed envelope comes back through\n * `submit()`. Both steps are available on the instance —\n * `await operation.submit({ signedXdr })` — so a caller never has to keep the id\n * and the manager in scope alongside it.\n */\nexport class LiquidityOperation extends Base<LiquidityOperationData> {\n /** Deposit or withdrawal. */\n public kind!: LiquidityOperationKind;\n public status!: LiquidityOperationStatus;\n public network!: string;\n /** Account whose funds move, and which must sign. */\n public source!: string;\n /** The pool this operation acts on (hex id). */\n public poolId!: string;\n public assetA!: string;\n public assetAIssuer!: string | null;\n public assetB!: string;\n public assetBIssuer!: string | null;\n /** Maximum of asset A put in (deposit), or minimum taken out (withdrawal). */\n public amountA!: string;\n public amountB!: string;\n /** Pool shares minted or burned; null until the network settles a deposit. */\n public shares!: string | null;\n /** Price band a deposit executes within, as decimal strings. */\n public minPrice!: string | null;\n public maxPrice!: string | null;\n public slippageBps!: number;\n public idempotencyKey!: string | null;\n public feeBps!: number;\n public feeAmountA!: string;\n public feeAmountB!: string;\n public feeWallet!: string | null;\n public commissionMemo!: string | null;\n /** Unsigned transaction envelope (base64 XDR) — what the wallet signs. */\n public xdr!: string;\n /** SEP-7 `web+stellar:tx` deep link for the same envelope. */\n public uri!: string;\n public txHash!: string;\n /** QR code of the SEP-7 URI (PNG data URL). */\n public qr!: string;\n /** When the built envelope stops being submittable. */\n public expiresAt!: Date | null;\n public createdAt!: Date;\n public updatedAt!: Date;\n\n constructor(client: Client, data: LiquidityOperationData) {\n super(client, data);\n }\n\n protected override _patch(data: LiquidityOperationData): this {\n super._patch(data);\n this.kind = data.kind;\n this.status = data.status;\n this.network = data.network;\n this.source = data.source;\n this.poolId = data.poolId;\n this.assetA = data.assetA;\n this.assetAIssuer = data.assetAIssuer ?? null;\n this.assetB = data.assetB;\n this.assetBIssuer = data.assetBIssuer ?? null;\n this.amountA = data.amountA;\n this.amountB = data.amountB;\n this.shares = data.shares ?? null;\n this.minPrice = data.minPrice ?? null;\n this.maxPrice = data.maxPrice ?? null;\n this.slippageBps = data.slippageBps;\n this.idempotencyKey = data.idempotencyKey ?? null;\n this.feeBps = data.feeBps;\n this.feeAmountA = data.feeAmountA;\n this.feeAmountB = data.feeAmountB;\n this.feeWallet = data.feeWallet ?? null;\n this.commissionMemo = data.commissionMemo ?? null;\n this.xdr = data.xdr;\n this.uri = data.uri;\n this.txHash = data.txHash;\n this.qr = data.qr;\n this.expiresAt = data.expiresAt ? new Date(data.expiresAt) : null;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n /** True while the envelope still needs a signature. */\n public get isPending(): boolean {\n return this.status === LiquidityOperationStatus.Pending;\n }\n\n /** True once the network accepted it. */\n public get isSucceeded(): boolean {\n return this.status === LiquidityOperationStatus.Succeeded;\n }\n\n /** True for a deposit, false for a withdrawal. */\n public get isDeposit(): boolean {\n return this.kind === LiquidityOperationKind.Deposit;\n }\n\n /** Re-fetch this operation and patch it in place. */\n public async fetch(): Promise<this> {\n const data = await this.client.liquidity.fetchRaw(this.id);\n return this._patch(data);\n }\n\n /** Relay the signed envelope to the network and patch this instance with the result. */\n public async submit(options: SubmitLiquidityOptions): Promise<LiquiditySubmitOutcome> {\n const outcome = await this.client.liquidity.submit(this.id, options);\n // Patch in place: the caller is holding THIS object, and leaving it showing\n // `PENDING` after a successful submit is the kind of staleness that gets\n // rendered straight into a UI.\n this._patch(outcome.operation.toJSON());\n return outcome;\n }\n\n public toJSON(): LiquidityOperationData {\n return {\n id: this.id,\n kind: this.kind,\n status: this.status,\n network: this.network,\n source: this.source,\n poolId: this.poolId,\n assetA: this.assetA,\n assetAIssuer: this.assetAIssuer,\n assetB: this.assetB,\n assetBIssuer: this.assetBIssuer,\n amountA: this.amountA,\n amountB: this.amountB,\n shares: this.shares,\n minPrice: this.minPrice,\n maxPrice: this.maxPrice,\n slippageBps: this.slippageBps,\n idempotencyKey: this.idempotencyKey,\n feeBps: this.feeBps,\n feeAmountA: this.feeAmountA,\n feeAmountB: this.feeAmountB,\n feeWallet: this.feeWallet,\n commissionMemo: this.commissionMemo,\n xdr: this.xdr,\n uri: this.uri,\n txHash: this.txHash,\n qr: this.qr,\n expiresAt: this.expiresAt ? this.expiresAt.toISOString() : null,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","import { LiquidityOperation } from '@/structures/LiquidityOperation';\nimport type {\n BrowseLiquidityPoolsOptions,\n DepositLiquidityOptions,\n LiquidityOperationData,\n LiquidityOperationListData,\n LiquidityOperationStatus,\n LiquidityPoolData,\n LiquidityPoolListData,\n LiquidityPositionsData,\n LiquiditySubmitOutcomeData,\n ListLiquidityOperationsOptions,\n SubmitLiquidityOptions,\n WithdrawLiquidityOptions,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\n\n/** A page of liquidity operations plus its pagination metadata. */\nexport interface LiquidityOperationPage {\n items: LiquidityOperation[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** A page of on-chain pools. Horizon paginates by cursor, not by offset. */\nexport interface LiquidityPoolPage {\n items: LiquidityPoolData[];\n /** Pass back as `cursor` to get the next page; null when there is none. */\n cursor: string | null;\n}\n\n/** Submission outcome with the refreshed operation materialized. */\nexport interface LiquiditySubmitOutcome {\n submitted: boolean;\n status: LiquidityOperationStatus;\n txHash: string | null;\n reason: string | null;\n resultCodes: string[] | null;\n operation: LiquidityOperation;\n}\n\n/**\n * Liquidity pools — `client.liquidity`.\n *\n * Two surfaces in one manager, because they are two halves of the same job:\n * *browsing* pools and positions (read-only, straight off Horizon), and\n * *operating* on them (deposit / withdraw), which produces an unsigned envelope\n * for a wallet to sign and a `submit()` to relay it back.\n *\n * The managed structure is the OPERATION, not the pool: a pool is a public\n * on-chain object with no lifecycle of its own, while an operation is a thing this\n * consumer created, can re-read and can push to the network.\n *\n * @example\n * const op = await client.liquidity.deposit({\n * source: 'G…',\n * assetACode: 'XLM',\n * assetBCode: 'USDC',\n * assetBIssuer: 'GA5Z…',\n * maxAmountA: '100',\n * maxAmountB: '25',\n * });\n * // …wallet signs op.xdr…\n * const { status, txHash } = await op.submit({ signedXdr });\n */\nexport class LiquidityManager extends BaseManager<LiquidityOperation> {\n private readonly route = '/liquidity-pools';\n\n /**\n * Build a deposit into the pool formed by the two assets → unsigned XDR, SEP-7\n * URI and QR.\n *\n * The pool is DERIVED from the two assets rather than named: a constant-product\n * pool id is a hash of its (assetA, assetB, fee) in CAP-38 order, so there is\n * exactly one pool the pair can form and no id for a caller to get wrong.\n */\n public async deposit(options: DepositLiquidityOptions): Promise<LiquidityOperation> {\n const { idempotencyKey, ...body } = options;\n const data = await this.rest.post<LiquidityOperationData>(`${this.route}/deposit`, {\n body: { ...body, ...(idempotencyKey ? { idempotencyKey } : {}) },\n // Sent as a header too: the service accepts either, and the header is what\n // makes a retried POST safe when the body was already consumed upstream.\n ...(idempotencyKey ? { headers: { 'Idempotency-Key': idempotencyKey } } : {}),\n });\n return this._add(new LiquidityOperation(this.client, data));\n }\n\n /** Build a withdrawal (burn shares) from a pool → unsigned XDR, SEP-7 URI and QR. */\n public async withdraw(options: WithdrawLiquidityOptions): Promise<LiquidityOperation> {\n const { idempotencyKey, ...body } = options;\n const data = await this.rest.post<LiquidityOperationData>(`${this.route}/withdraw`, {\n body: { ...body, ...(idempotencyKey ? { idempotencyKey } : {}) },\n ...(idempotencyKey ? { headers: { 'Idempotency-Key': idempotencyKey } } : {}),\n });\n return this._add(new LiquidityOperation(this.client, data));\n }\n\n /** An account's pool share positions, with what each is redeemable for right now. */\n public positions(account: string): Promise<LiquidityPositionsData> {\n return this.rest.get<LiquidityPositionsData>(`${this.route}/positions`, {\n query: { account },\n });\n }\n\n /** Browse on-chain pools (Horizon proxy). Filter by asset pair or by holder. */\n public async browse(options: BrowseLiquidityPoolsOptions = {}): Promise<LiquidityPoolPage> {\n const data = await this.rest.get<LiquidityPoolListData>(this.route, {\n query: {\n assetACode: options.assetACode,\n assetAIssuer: options.assetAIssuer,\n assetBCode: options.assetBCode,\n assetBIssuer: options.assetBIssuer,\n account: options.account,\n cursor: options.cursor,\n limit: options.limit,\n },\n });\n return { items: data.data, cursor: data.cursor ?? null };\n }\n\n /** One on-chain pool by its hex id (Horizon proxy). */\n public pool(poolId: string): Promise<LiquidityPoolData> {\n return this.rest.get<LiquidityPoolData>(`${this.route}/${poolId}`);\n }\n\n /** List this consumer's pool operations (paginated). */\n public async operations(\n options: ListLiquidityOperationsOptions = {},\n ): Promise<LiquidityOperationPage> {\n const data = await this.rest.get<LiquidityOperationListData>(`${this.route}/operations`, {\n query: {\n kind: options.kind,\n status: options.status,\n take: options.take,\n skip: options.skip,\n },\n });\n return {\n items: data.data.map((d) => this._add(new LiquidityOperation(this.client, d))),\n total: data.total,\n take: data.take,\n skip: data.skip,\n };\n }\n\n /** Get one operation by id, materialized. */\n public async fetch(id: string): Promise<LiquidityOperation> {\n return this._add(new LiquidityOperation(this.client, await this.fetchRaw(id)));\n }\n\n /**\n * The raw payload for one operation. Exists so {@link LiquidityOperation.fetch}\n * can patch itself in place instead of materializing a second instance of the\n * thing the caller is already holding.\n */\n public fetchRaw(id: string): Promise<LiquidityOperationData> {\n return this.rest.get<LiquidityOperationData>(`${this.route}/operations/${id}`);\n }\n\n /**\n * Relay a signed operation to the network. The service checks the envelope's\n * hash against the one it built, so a signed envelope that is not the one this\n * operation describes is refused rather than broadcast.\n */\n public async submit(\n id: string,\n options: SubmitLiquidityOptions,\n ): Promise<LiquiditySubmitOutcome> {\n const data = await this.rest.post<LiquiditySubmitOutcomeData>(\n `${this.route}/operations/${id}/submit`,\n { body: options },\n );\n return {\n submitted: data.submitted,\n status: data.status,\n txHash: data.txHash ?? null,\n reason: data.reason ?? null,\n resultCodes: data.resultCodes ?? null,\n operation: this._add(new LiquidityOperation(this.client, data.operation)),\n };\n }\n}\n","import type { Client } from '@/client/Client';\nimport type { REST } from '@/rest/REST';\nimport type {\n CreatePayinOptions,\n CreatePayinQuoteOptions,\n CreateTrustlineOptions,\n CreateVirtualAccountOptions,\n ListPayinsOptions,\n PayinData,\n PayinListData,\n PayinQuoteData,\n TrustlineData,\n VirtualAccountData,\n} from '@/types/index';\n\n/** A page of payins plus its pagination metadata. */\nexport interface PayinPage {\n items: PayinData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/**\n * Fiat → stablecoin — `client.onramp`.\n *\n * Three steps, in this order and no other: **quote** (a price, valid for about\n * five minutes), **payin** (created FROM that quote, and what returns the funding\n * instructions the payer acts on), then the money arrives off-band and the payin\n * status moves on its own.\n *\n * There is no structure class here on purpose. A payin has no action of its own —\n * it is a mirror of the provider's record, read and re-read — so an object with a\n * client back-reference would carry a `fetch()` and nothing else.\n *\n * @example\n * const quote = await client.onramp.quote({\n * blockchain_wallet_id: 'w_123',\n * currency_type: 'sender',\n * payment_method: 'pix',\n * token: 'USDC',\n * request_amount: 10_000, // minor units\n * });\n * const payin = await client.onramp.createPayin({ payin_quote_id: quote.id });\n * console.log(payin.instructions);\n */\nexport class OnrampManager {\n public readonly client: Client;\n private readonly route = '/onramp';\n\n constructor(client: Client) {\n this.client = client;\n }\n\n private get rest(): REST {\n return this.client.rest;\n }\n\n /** Price a payin. The quote expires — check `expires_at` before using it. */\n public quote(options: CreatePayinQuoteOptions): Promise<PayinQuoteData> {\n return this.rest.post<PayinQuoteData>(`${this.route}/quotes`, { body: options });\n }\n\n /** Create a payin from a quote. The response carries the funding instructions. */\n public createPayin(options: CreatePayinOptions): Promise<PayinData> {\n return this.rest.post<PayinData>(`${this.route}/payins`, { body: options });\n }\n\n /** List this consumer's payins (paginated). */\n public async payins(options: ListPayinsOptions = {}): Promise<PayinPage> {\n const data = await this.rest.get<PayinListData>(`${this.route}/payins`, {\n query: { take: options.take, skip: options.skip },\n });\n return { items: data.data, total: data.total, take: data.take, skip: data.skip };\n }\n\n /**\n * One payin. Served from the local mirror, refreshed from the provider when it\n * is stale — so this is the right call to poll, not the provider's own API.\n */\n public payin(id: string): Promise<PayinData> {\n return this.rest.get<PayinData>(`${this.route}/payins/${id}`);\n }\n\n /**\n * Build the unsigned trustline transaction an address needs before it can hold\n * the stablecoin the ramp pays out in.\n *\n * The envelope comes from the gateway, so a wallet signing it must decode and\n * bound it first — the issuer it names is the one the payout will use, and it is\n * not known to the caller in advance.\n */\n public createTrustline(options: CreateTrustlineOptions): Promise<TrustlineData> {\n return this.rest.post<TrustlineData>(`${this.route}/trustline`, { body: options });\n }\n\n /** Open a virtual account (a permanent bank reference) for a verified receiver. */\n public createVirtualAccount(\n receiverId: string,\n options: CreateVirtualAccountOptions,\n ): Promise<VirtualAccountData> {\n return this.rest.post<VirtualAccountData>(\n `${this.route}/receivers/${receiverId}/virtual-accounts`,\n { body: options },\n );\n }\n\n /** A receiver's virtual accounts. */\n public virtualAccounts(\n receiverId: string,\n options: ListPayinsOptions = {},\n ): Promise<VirtualAccountData> {\n return this.rest.get<VirtualAccountData>(\n `${this.route}/receivers/${receiverId}/virtual-accounts`,\n { query: { take: options.take, skip: options.skip } },\n );\n }\n}\n","import type { Client } from '@/client/Client';\nimport type { REST } from '@/rest/REST';\nimport type {\n AttachPayoutDocumentOptions,\n AuthorizePayoutData,\n AuthorizePayoutOptions,\n CreatePayoutOptions,\n CreatePayoutQuoteOptions,\n ListPayoutsOptions,\n PayoutData,\n PayoutDocumentData,\n PayoutListData,\n PayoutQuoteData,\n} from '@/types/index';\n\n/** A page of payouts plus its pagination metadata. */\nexport interface PayoutPage {\n items: PayoutData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/**\n * Stablecoin → fiat — `client.offramp`.\n *\n * Four steps, and the middle one is the one people miss: **quote**, **authorize**\n * (which builds the unsigned transaction that moves the stablecoin), the wallet\n * signs it, and only then **create the payout** with that signature attached. A\n * payout created without a signed transfer is a payout with nothing behind it.\n *\n * `authorize` is for the chains that need a transaction built for them (Stellar,\n * Solana). On EVM the quote itself carries the `approve` contract payload, so the\n * caller signs that instead and goes straight to `createPayout`.\n *\n * @example\n * const quote = await client.offramp.quote({\n * bank_account_id: 'ba_123',\n * currency_type: 'sender',\n * request_amount: 5_000,\n * network: 'stellar',\n * token: 'USDC',\n * });\n * const { xdr } = await client.offramp.authorize({\n * quote_id: quote.id,\n * sender_wallet_address: 'G…',\n * chain: 'stellar',\n * });\n * // …wallet signs `xdr`, after bounding it against `quote`…\n * const payout = await client.offramp.createPayout({\n * quote_id: quote.id,\n * sender_wallet_address: 'G…',\n * chain: 'stellar',\n * signed_transaction: signedXdr,\n * });\n */\nexport class OfframpManager {\n public readonly client: Client;\n private readonly route = '/offramp';\n\n constructor(client: Client) {\n this.client = client;\n }\n\n private get rest(): REST {\n return this.client.rest;\n }\n\n /** Price a payout. Expires in about five minutes. */\n public quote(options: CreatePayoutQuoteOptions): Promise<PayoutQuoteData> {\n return this.rest.post<PayoutQuoteData>(`${this.route}/quotes`, { body: options });\n }\n\n /**\n * Build the unsigned transfer for a Stellar or Solana payout.\n *\n * What comes back is built by the gateway, not by the caller: bound it against\n * the quote the user confirmed before signing, or the amount that leaves is\n * whatever the response says it is.\n */\n public authorize(options: AuthorizePayoutOptions): Promise<AuthorizePayoutData> {\n return this.rest.post<AuthorizePayoutData>(`${this.route}/payouts/authorize`, {\n body: options,\n });\n }\n\n /** Create the payout from a quote, with the signed transfer attached. */\n public createPayout(options: CreatePayoutOptions): Promise<PayoutData> {\n return this.rest.post<PayoutData>(`${this.route}/payouts`, { body: options });\n }\n\n /** List this consumer's payouts (paginated). */\n public async payouts(options: ListPayoutsOptions = {}): Promise<PayoutPage> {\n const data = await this.rest.get<PayoutListData>(`${this.route}/payouts`, {\n query: { take: options.take, skip: options.skip },\n });\n return { items: data.data, total: data.total, take: data.take, skip: data.skip };\n }\n\n /** One payout. Served from the local mirror, refreshed when stale. */\n public payout(id: string): Promise<PayoutData> {\n return this.rest.get<PayoutData>(`${this.route}/payouts/${id}`);\n }\n\n /**\n * Attach a compliance document to a payout — an invoice or proof of funds the\n * rail asks for before it will settle.\n */\n public attachDocument(\n id: string,\n options: AttachPayoutDocumentOptions,\n ): Promise<PayoutDocumentData> {\n return this.rest.post<PayoutDocumentData>(`${this.route}/payouts/${id}/documents`, {\n body: options,\n });\n }\n}\n","import type { Client } from '@/client/Client';\nimport type { REST } from '@/rest/REST';\nimport type {\n ActivityEventInput,\n ActivityListData,\n ActivityReportData,\n ActivitySummaryData,\n ListActivityOptions,\n ReportActivityOptions,\n} from '@/types/index';\n\n/** A page of events plus its pagination metadata. */\nexport interface ActivityPage {\n items: ActivityListData['data'];\n total: number;\n take: number;\n skip: number;\n}\n\n/**\n * The client event stream — `client.activity`.\n *\n * This is the trail the wallet, the dashboard and your own server write to: errors,\n * screen views, timings, the operations they built. It exists because a console is\n * not a trail — an extension popup's console dies with the popup and a phone's\n * WebView console needs a cable — and because the failures worth having are the\n * ones that never reach the API at all.\n *\n * Two rules the writers are expected to keep, and neither is enforceable here:\n * report only what the user consented to, and never put memo text or anything that\n * names a counterparty in `props`.\n *\n * @example\n * await client.activity.report([\n * { type: 'checkout.opened', source: 'server', level: 'info', eventId: crypto.randomUUID() },\n * ]);\n */\nexport class ActivityManager {\n public readonly client: Client;\n private readonly route = '/activity';\n\n constructor(client: Client) {\n this.client = client;\n }\n\n private get rest(): REST {\n return this.client.rest;\n }\n\n /**\n * Report a batch of events.\n *\n * Accepts the array directly or the full body. Give each event an `eventId`: the\n * service de-duplicates on it, which is the difference between a retried batch\n * and a double-counted one.\n */\n public report(\n events: ActivityEventInput[] | ReportActivityOptions,\n ): Promise<ActivityReportData> {\n const body: ReportActivityOptions = Array.isArray(events) ? { events } : events;\n return this.rest.post<ActivityReportData>(`${this.route}/events`, { body });\n }\n\n /** Recent events for this consumer, newest first. */\n public async events(options: ListActivityOptions = {}): Promise<ActivityPage> {\n const data = await this.rest.get<ActivityListData>(`${this.route}/events`, {\n query: {\n take: options.take,\n skip: options.skip,\n source: options.source,\n level: options.level,\n category: options.category,\n type: options.type,\n network: options.network,\n since: options.since,\n until: options.until,\n },\n });\n return { items: data.data, total: data.total, take: data.take, skip: data.skip };\n }\n\n /** Counts, top event types, top errors and a daily series. */\n public summary(options: { days?: number; source?: string } = {}): Promise<ActivitySummaryData> {\n return this.rest.get<ActivitySummaryData>(`${this.route}/summary`, {\n query: { days: options.days, source: options.source },\n });\n }\n}\n","import type { Client } from '@/client/Client';\nimport type {\n ApproveReceiverOptions,\n BankAccountData,\n CreateBankAccountOptions,\n CreateReceiverWalletOptions,\n EnableReceiverOptions,\n ListKycOptions,\n ReceiverData,\n ReceiverWalletData,\n RequestTosOptions,\n TermsOfServiceData,\n UpdateReceiverOptions,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\nimport type { BankAccountPage, ReceiverWalletPage } from '@/managers/KycManager';\n\n/**\n * A verified identity — the thing both ramps hang off.\n *\n * Everything a receiver owns is reachable from the instance\n * (`receiver.addBankAccount(…)`, `receiver.wallets()`), because the alternative is\n * carrying a receiver id and a manager reference side by side through a KYC flow\n * that already has enough moving parts.\n */\nexport class Receiver extends Base<ReceiverData> {\n public blindpayId!: string;\n /** `individual` or `business`. */\n public type!: string;\n public kycType!: string | null;\n /** Verification state, refreshed from upstream on every read. */\n public kycStatus!: string | null;\n public email!: string | null;\n public name!: string | null;\n public country!: string | null;\n /** Your own id for this receiver, if you set one. */\n public externalId!: string | null;\n /** True when the receiver is cut off from both ramps. */\n public disabled!: boolean;\n /** How many times the submitted KYC data has been written. */\n public dossierVersion!: number;\n /** The version a reviewer approved, or null while unapproved. */\n public reviewedVersion!: number | null;\n public createdAt!: Date;\n public updatedAt!: Date;\n\n constructor(client: Client, data: ReceiverData) {\n super(client, data);\n }\n\n protected override _patch(data: ReceiverData): this {\n super._patch(data);\n this.blindpayId = data.blindpayId;\n this.type = data.type;\n this.kycType = data.kycType ?? null;\n this.kycStatus = data.kycStatus ?? null;\n this.email = data.email ?? null;\n this.name = data.name ?? null;\n this.country = data.country ?? null;\n this.externalId = data.externalId ?? null;\n this.disabled = data.disabled;\n this.dossierVersion = data.dossierVersion;\n this.reviewedVersion = data.reviewedVersion ?? null;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n /** True once verification has passed and the ramps will act on this receiver. */\n public get isApproved(): boolean {\n return this.kycStatus === 'approved';\n }\n\n /** Re-read this receiver, refreshing `kycStatus`, and patch it in place. */\n public async fetch(): Promise<this> {\n return this._patch(await this.client.kyc.fetchReceiverRaw(this.id));\n }\n\n /** Update and patch in place. */\n public async update(options: UpdateReceiverOptions): Promise<this> {\n const updated = await this.client.kyc.updateReceiver(this.id, options);\n return this._patch(updated.toJSON());\n }\n\n /** Delete this receiver. */\n public delete(): Promise<void> {\n return this.client.kyc.deleteReceiver(this.id);\n }\n\n /**\n * Approve it out of review (admin-only).\n *\n * Pinned to the dossier THIS instance holds: `expected_version` defaults to\n * {@link Receiver.dossierVersion}, so approving a receiver that was edited since\n * you read it is a `409 kyc_state_invalid` rather than a silent approval of data\n * you never saw. Call {@link Receiver.fetch} and review again, or pass\n * `expected_version` yourself — including `undefined`, which approves whatever\n * is stored now.\n */\n public approve(options: ApproveReceiverOptions = {}): Promise<ReceiverData> {\n const pinned: ApproveReceiverOptions =\n 'expected_version' in options\n ? options\n : { ...options, expected_version: this.dossierVersion };\n return this.client.kyc.approveReceiver(this.id, pinned);\n }\n\n /** Ask for a terms-of-service link for this receiver. */\n public requestTos(options: RequestTosOptions): Promise<TermsOfServiceData> {\n return this.client.kyc.requestTos(this.id, options);\n }\n\n /** Enable it with an accepted terms-of-service id, and patch in place. */\n public async enable(options: EnableReceiverOptions): Promise<this> {\n const enabled = await this.client.kyc.enableReceiver(this.id, options);\n return this._patch(enabled.toJSON());\n }\n\n /** Cut this receiver off from both ramps, or let it back in. */\n public async setAccess(disabled: boolean): Promise<this> {\n const updated = await this.client.kyc.setReceiverAccess(this.id, { disabled });\n return this._patch(updated.toJSON());\n }\n\n /** Register a blockchain wallet for this receiver. */\n public addWallet(options: CreateReceiverWalletOptions): Promise<ReceiverWalletData> {\n return this.client.kyc.addWallet(this.id, options);\n }\n\n /** This receiver's wallets. */\n public wallets(options: ListKycOptions = {}): Promise<ReceiverWalletPage> {\n return this.client.kyc.wallets(this.id, options);\n }\n\n /** Add a fiat bank account — where an off-ramp pays out. */\n public addBankAccount(options: CreateBankAccountOptions): Promise<BankAccountData> {\n return this.client.kyc.addBankAccount(this.id, options);\n }\n\n /** This receiver's bank accounts. */\n public bankAccounts(options: ListKycOptions = {}): Promise<BankAccountPage> {\n return this.client.kyc.bankAccounts(this.id, options);\n }\n\n public toJSON(): ReceiverData {\n return {\n id: this.id,\n blindpayId: this.blindpayId,\n type: this.type,\n kycType: this.kycType,\n kycStatus: this.kycStatus,\n email: this.email,\n name: this.name,\n country: this.country,\n externalId: this.externalId,\n disabled: this.disabled,\n dossierVersion: this.dossierVersion,\n reviewedVersion: this.reviewedVersion,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","import type { Client } from '@/client/Client';\nimport type { REST } from '@/rest/REST';\nimport { Receiver } from '@/structures/Receiver';\nimport { BaseManager } from '@/managers/BaseManager';\nimport type {\n ApproveReceiverOptions,\n BankAccountData,\n BankAccountListData,\n BankDetailsData,\n CreateBankAccountOptions,\n CreateReceiverOptions,\n CreateReceiverWalletOptions,\n EnableReceiverOptions,\n InitiateTosOptions,\n KycRailsData,\n KycUploadData,\n ListKycOptions,\n ReceiverData,\n ReceiverListData,\n ReceiverWalletData,\n ReceiverWalletListData,\n RequestTosOptions,\n SetReceiverAccessOptions,\n TermsOfServiceData,\n UpdateReceiverOptions,\n WalletSignMessageData,\n} from '@/types/index';\n\n/** A page of receivers plus its pagination metadata. */\nexport interface ReceiverPage {\n items: Receiver[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** A page of a receiver's wallets. */\nexport interface ReceiverWalletPage {\n items: ReceiverWalletData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** A page of a receiver's bank accounts. */\nexport interface BankAccountPage {\n items: BankAccountData[];\n total: number;\n take: number;\n skip: number;\n}\n\n/**\n * KYC / KYB — `client.kyc`.\n *\n * A receiver is the verified identity both ramps hang off: an on-ramp pays INTO\n * one of its wallets, an off-ramp pays OUT to one of its bank accounts, and\n * neither works until verification passes.\n *\n * The order is not obvious and the API will not guess it for you:\n *\n * 1. `termsOfService()` — the acceptance the provider requires up front, which\n * returns a `tos_id`.\n * 2. `upload()` each document, keeping the `file_url` it returns.\n * 3. `createReceiver()` with those URLs and the `tos_id`.\n * 4. `addWallet()` / `addBankAccount()` for where money should land.\n * 5. verification runs; `fetchReceiver()` refreshes `kycStatus` from upstream.\n *\n * @example\n * const tos = await client.kyc.termsOfService({ redirect_url: 'https://app/kyc/done' });\n * const { file_url } = await client.kyc.upload(fileBase64);\n * const receiver = await client.kyc.createReceiver({\n * type: 'individual', kyc_type: 'standard', email: 'a@b.com', country: 'BR',\n * id_doc_front_file: file_url, tos_id: tosId,\n * });\n */\nexport class KycManager extends BaseManager<Receiver> {\n private readonly route = '/kyc';\n\n /* ----------------------------- receivers ------------------------------- */\n\n /** Create a receiver and start verification. */\n public async createReceiver(options: CreateReceiverOptions): Promise<Receiver> {\n const data = await this.rest.post<ReceiverData>(`${this.route}/receivers`, { body: options });\n return this._add(new Receiver(this.client, data));\n }\n\n /** List this consumer's receivers (paginated). */\n public async receivers(options: ListKycOptions = {}): Promise<ReceiverPage> {\n const data = await this.rest.get<ReceiverListData>(`${this.route}/receivers`, {\n query: { take: options.take, skip: options.skip },\n });\n return {\n items: data.data.map((d) => this._add(new Receiver(this.client, d))),\n total: data.total,\n take: data.take,\n skip: data.skip,\n };\n }\n\n /** One receiver, materialized. Reading it refreshes `kycStatus` upstream. */\n public async fetchReceiver(id: string): Promise<Receiver> {\n return this._add(new Receiver(this.client, await this.fetchReceiverRaw(id)));\n }\n\n /** The raw payload, so a {@link Receiver} can patch itself in place. */\n public fetchReceiverRaw(id: string): Promise<ReceiverData> {\n return this.rest.get<ReceiverData>(`${this.route}/receivers/${id}`);\n }\n\n /**\n * Update a receiver — the same fields as creation, all optional. Once the receiver\n * exists at the provider, identity fields need an elevated key; see\n * {@link UpdateReceiverOptions}.\n */\n public async updateReceiver(id: string, options: UpdateReceiverOptions): Promise<Receiver> {\n const data = await this.rest.patch<ReceiverData>(`${this.route}/receivers/${id}`, {\n body: options,\n });\n return this._add(new Receiver(this.client, data));\n }\n\n /** Delete a receiver. */\n public async deleteReceiver(id: string): Promise<void> {\n await this.rest.delete<unknown>(`${this.route}/receivers/${id}`);\n this.cache.delete(id);\n }\n\n /**\n * Approve a receiver sitting in review. Admin-only: it is the human gate on a\n * verification the provider could not decide by itself.\n */\n public approveReceiver(id: string, options: ApproveReceiverOptions = {}): Promise<ReceiverData> {\n return this.rest.post<ReceiverData>(`${this.route}/receivers/${id}/approve`, { body: options });\n }\n\n /**\n * Ask for a terms-of-service link for an existing receiver. `channel: 'code'`\n * returns the URL to render; `'email'` sends it to the receiver instead.\n */\n public requestTos(id: string, options: RequestTosOptions): Promise<TermsOfServiceData> {\n return this.rest.post<TermsOfServiceData>(`${this.route}/receivers/${id}/tos`, {\n body: options,\n });\n }\n\n /** Enable an inactive receiver with an accepted terms-of-service id. */\n public async enableReceiver(id: string, options: EnableReceiverOptions): Promise<Receiver> {\n const data = await this.rest.post<ReceiverData>(`${this.route}/receivers/${id}/enable`, {\n body: options,\n });\n return this._add(new Receiver(this.client, data));\n }\n\n /**\n * Cut a receiver off from both ramps, or let it back in. Admin-only, and the\n * fastest lever there is when something is wrong with an account.\n */\n public async setReceiverAccess(\n id: string,\n options: SetReceiverAccessOptions,\n ): Promise<Receiver> {\n const data = await this.rest.patch<ReceiverData>(`${this.route}/receivers/${id}/access`, {\n body: options,\n });\n return this._add(new Receiver(this.client, data));\n }\n\n /* ------------------------------ wallets -------------------------------- */\n\n /**\n * The message a receiver must sign to prove it controls an address. Sign it,\n * then pass the resulting transaction hash as `signature_tx_hash` to\n * {@link addWallet}.\n */\n public walletSignMessage(receiverId: string): Promise<WalletSignMessageData> {\n return this.rest.get<WalletSignMessageData>(\n `${this.route}/receivers/${receiverId}/wallets/sign-message`,\n );\n }\n\n /** Register a blockchain wallet for a receiver. */\n public addWallet(\n receiverId: string,\n options: CreateReceiverWalletOptions,\n ): Promise<ReceiverWalletData> {\n return this.rest.post<ReceiverWalletData>(`${this.route}/receivers/${receiverId}/wallets`, {\n body: options,\n });\n }\n\n /** A receiver's wallets (paginated). */\n public async wallets(\n receiverId: string,\n options: ListKycOptions = {},\n ): Promise<ReceiverWalletPage> {\n const data = await this.rest.get<ReceiverWalletListData>(\n `${this.route}/receivers/${receiverId}/wallets`,\n { query: { take: options.take, skip: options.skip } },\n );\n return { items: data.data, total: data.total, take: data.take, skip: data.skip };\n }\n\n /** Delete one of a receiver's wallets. */\n public async deleteWallet(receiverId: string, id: string): Promise<void> {\n await this.rest.delete<unknown>(`${this.route}/receivers/${receiverId}/wallets/${id}`);\n }\n\n /* ---------------------------- bank accounts ---------------------------- */\n\n /** Add a fiat bank account for a receiver — where an off-ramp pays out. */\n public addBankAccount(\n receiverId: string,\n options: CreateBankAccountOptions,\n ): Promise<BankAccountData> {\n return this.rest.post<BankAccountData>(\n `${this.route}/receivers/${receiverId}/bank-accounts`,\n { body: options },\n );\n }\n\n /** A receiver's bank accounts (paginated). */\n public async bankAccounts(\n receiverId: string,\n options: ListKycOptions = {},\n ): Promise<BankAccountPage> {\n const data = await this.rest.get<BankAccountListData>(\n `${this.route}/receivers/${receiverId}/bank-accounts`,\n { query: { take: options.take, skip: options.skip } },\n );\n return { items: data.data, total: data.total, take: data.take, skip: data.skip };\n }\n\n /** Delete one of a receiver's bank accounts. */\n public async deleteBankAccount(receiverId: string, id: string): Promise<void> {\n await this.rest.delete<unknown>(`${this.route}/receivers/${receiverId}/bank-accounts/${id}`);\n }\n\n /* ------------------------------ the rest ------------------------------- */\n\n /**\n * Upload a KYC document and get back the `file_url` every `*_file` field\n * expects. Documents are uploaded first and referenced by URL — the receiver\n * payload never carries bytes.\n */\n public upload(file: unknown): Promise<KycUploadData> {\n return this.rest.post<KycUploadData>(`${this.route}/upload`, { body: file });\n }\n\n /**\n * Start terms-of-service acceptance and get the hosted URL. This is the FIRST\n * step of the flow: the provider will not create a receiver without the `tos_id`\n * it produces.\n */\n public termsOfService(options: InitiateTosOptions = {}): Promise<TermsOfServiceData> {\n return this.rest.post<TermsOfServiceData>(`${this.route}/terms-of-service`, { body: options });\n }\n\n /** The bank rails available to this consumer. */\n public rails(): Promise<KycRailsData> {\n return this.rest.get<KycRailsData>(`${this.route}/rails`);\n }\n\n /**\n * The field schema a given rail requires. The authority on which of the ~70\n * rail-specific bank-account fields to send — read it at runtime rather than\n * hard-coding a rail's shape.\n */\n public bankDetails(rail: string): Promise<BankDetailsData> {\n return this.rest.get<BankDetailsData>(`${this.route}/bank-details`, { query: { rail } });\n }\n\n protected get rest(): REST {\n return this.client.rest;\n }\n}\n","import type { Client } from '@/client/Client';\nimport type { REST } from '@/rest/REST';\nimport type {\n ActivatePollarWalletOptions,\n PollarActivationData,\n PollarAuthorizeData,\n PollarAuthorizeOptions,\n PollarLoginSessionData,\n PollarLogoutData,\n PollarLogoutOptions,\n PollarRefreshData,\n PollarRefreshOptions,\n PollarSessionData,\n PollarTokenOptions,\n PollarTokenVerificationData,\n PollarTrustlineData,\n PollarTrustlinesOptions,\n PollarUserData,\n RegisterPollarUserOptions,\n VerifyPollarTokenOptions,\n} from '@/types/index';\n\n/**\n * Pollar — social login and the custodial wallets behind it — `client.pollar`.\n *\n * The login is a three-legged flow, and the middle leg is the one that surprises\n * people: the browser leaves for the provider and comes back to POLLAR, not to\n * you, so a client cannot simply await a redirect. It polls instead.\n *\n * 1. `authorize()` → a `state` and the `authorization_url` to open.\n * 2. `session(state)` until `status` is `authorized`, which carries a bridge `code`.\n * 3. `token({ code, code_verifier })` → the session, its wallets and the profile.\n *\n * Use PKCE. The code travels through a redirect a client does not control, and the\n * `code_verifier` is the only reason an intercepted one is worth nothing. With a\n * `redirect_uri` it is not a choice: the service refuses that authorize without a\n * `code_challenge` (`400 validation_failed`).\n *\n * The session only comes back to the account that owns the API key. Every tenant\n * shares one Pollar application, so `token()` compares the email the login reports\n * with the key's account email and refuses a login someone else completed with\n * `403 pollar_identity_mismatch` — the session is revoked, never returned. A key\n * whose account has no verified email gets `403 pollar_identity_required` at\n * `authorize()`.\n *\n * The two callback routes (`/oauth/callback…`) are deliberately absent from this\n * manager: they are where a BROWSER lands, not something a server calls. Polling\n * `session()` is the programmatic half of the same step.\n *\n * @example\n * const { state, authorization_url } = await client.pollar.authorize({\n * provider: 'google',\n * code_challenge: challenge,\n * code_challenge_method: 'S256',\n * });\n * // open `authorization_url`, then poll:\n * const polled = await client.pollar.session(state);\n * if (polled.status === 'authorized') {\n * const session = await client.pollar.token({ code: polled.code, code_verifier: verifier });\n * }\n */\nexport class PollarManager {\n public readonly client: Client;\n private readonly route = '/pollar';\n\n constructor(client: Client) {\n this.client = client;\n }\n\n private get rest(): REST {\n return this.client.rest;\n }\n\n /* -------------------------------- login -------------------------------- */\n\n /** Start a login and get the URL to send the user to. */\n public authorize(options: PollarAuthorizeOptions): Promise<PollarAuthorizeData> {\n return this.rest.post<PollarAuthorizeData>(`${this.route}/oauth/authorize`, { body: options });\n }\n\n /**\n * Poll a login. `status: 'authorized'` carries the bridge `code` to redeem;\n * `pending` means keep waiting; anything else is over.\n */\n public session(state: string): Promise<PollarLoginSessionData> {\n return this.rest.get<PollarLoginSessionData>(`${this.route}/oauth/sessions/${state}`);\n }\n\n /** Redeem the bridge code for a session. Single use — a consumed code is dead. */\n public token(options: PollarTokenOptions): Promise<PollarSessionData> {\n return this.rest.post<PollarSessionData>(`${this.route}/oauth/token`, { body: options });\n }\n\n /**\n * Rotate the token pair. The old refresh token stops working, so store what\n * comes back before using it — a rotation you lose is a session you lose.\n */\n public refresh(options: PollarRefreshOptions): Promise<PollarRefreshData> {\n return this.rest.post<PollarRefreshData>(`${this.route}/oauth/refresh`, { body: options });\n }\n\n /** Revoke a session — this device, or every one of them. */\n public logout(options: PollarLogoutOptions): Promise<PollarLogoutData> {\n return this.rest.post<PollarLogoutData>(`${this.route}/oauth/logout`, { body: options });\n }\n\n /** Validate an end-user access token and learn whose it is. */\n public verifyToken(options: VerifyPollarTokenOptions): Promise<PollarTokenVerificationData> {\n return this.rest.post<PollarTokenVerificationData>(`${this.route}/tokens/verify`, {\n body: options,\n });\n }\n\n /* ------------------------------- wallets ------------------------------- */\n\n /**\n * Fund a wallet's XLM base reserve. A Stellar account does not exist until\n * something pays for it, which is why a fresh Pollar wallet can have an address\n * and still not be on the network.\n */\n public activateWallet(options: ActivatePollarWalletOptions): Promise<PollarActivationData> {\n return this.rest.post<PollarActivationData>(`${this.route}/wallets/activate`, {\n body: options,\n });\n }\n\n /** Enable the application's configured assets on a wallet. */\n public addDefaultTrustlines(address: string): Promise<PollarTrustlineData> {\n return this.rest.post<PollarTrustlineData>(\n `${this.route}/wallets/${address}/trustlines/default`,\n );\n }\n\n /** Enable specific assets on a wallet. */\n public addTrustlines(\n address: string,\n options: PollarTrustlinesOptions,\n ): Promise<PollarTrustlineData> {\n return this.rest.post<PollarTrustlineData>(`${this.route}/wallets/${address}/trustlines`, {\n body: options,\n });\n }\n\n /**\n * Remove a trustline. An asset is `(code, issuer)`, and both are in the path for\n * that reason: a bare code names no asset.\n */\n public removeTrustline(\n address: string,\n code: string,\n issuer: string,\n ): Promise<PollarTrustlineData> {\n return this.rest.delete<PollarTrustlineData>(\n `${this.route}/wallets/${address}/trustlines/${code}/${issuer}`,\n );\n }\n\n /* -------------------------------- users -------------------------------- */\n\n /**\n * Register a user with Pollar ahead of their first login. Needs an elevated\n * (admin) key: the Pollar user directory is shared by every tenant, so a tenant\n * key gets `403 elevated_key_required`.\n */\n public registerUser(options: RegisterPollarUserOptions): Promise<PollarUserData> {\n return this.rest.post<PollarUserData>(`${this.route}/users`, { body: options });\n }\n\n /**\n * Register a user AND provision their Stellar wallet in one call — the variant\n * to use when the user should be able to receive before they ever log in. Needs\n * an elevated (admin) key, like {@link registerUser}.\n */\n public registerUserWithWallet(options: RegisterPollarUserOptions): Promise<PollarUserData> {\n return this.rest.post<PollarUserData>(`${this.route}/users/with-wallet`, { body: options });\n }\n}\n","import type { Client } from '@/client/Client';\nimport {\n PaymentIntentKind,\n PaymentIntentStatus,\n type PaymentIntentData,\n type UpdatePaymentIntentOptions,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/**\n * A Stellar SEP-7 payment intent.\n *\n * Wraps the raw API payload with typed accessors and atomic action methods so\n * you can operate on it directly: `await intent.validate(txHash)`,\n * `await intent.cancel()`, `await intent.delete()`.\n */\nexport class PaymentIntent extends Base<PaymentIntentData> {\n public kind!: PaymentIntentKind;\n public status!: PaymentIntentStatus;\n public network!: string;\n /** Payer account (null for PAY intents). */\n public source!: string | null;\n public destination!: string;\n public amount!: string | null;\n /** Asset code, or `native` for XLM. */\n public asset!: string;\n public assetIssuer!: string | null;\n /** Mandatory MEMO_ID. */\n public memo!: string;\n public msg!: string | null;\n public callback!: string | null;\n /** Unsigned transaction envelope (base64 XDR); null for PAY intents. */\n public xdr!: string | null;\n /** SEP-7 deep link (`tx` or `pay`). */\n public uri!: string;\n /** QR code of the SEP-7 URI (PNG data URL). */\n public qr!: string;\n public txHash!: string | null;\n public reference!: string | null;\n public createdAt!: Date;\n public updatedAt!: Date;\n\n constructor(client: Client, data: PaymentIntentData) {\n super(client, data);\n }\n\n protected override _patch(data: PaymentIntentData): this {\n super._patch(data);\n this.kind = data.kind;\n this.status = data.status;\n this.network = data.network;\n this.source = data.source;\n this.destination = data.destination;\n this.amount = data.amount;\n this.asset = data.asset;\n this.assetIssuer = data.assetIssuer;\n this.memo = data.memo;\n this.msg = data.msg;\n this.callback = data.callback;\n this.xdr = data.xdr;\n this.uri = data.uri;\n this.qr = data.qr;\n this.txHash = data.txHash;\n this.reference = data.reference;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n /** Whether this is a SEP-7 `tx` intent (known source, has XDR). */\n public get isTx(): boolean {\n return this.kind === PaymentIntentKind.Tx;\n }\n\n /** Whether this is a SEP-7 `pay` intent (no source). */\n public get isPay(): boolean {\n return this.kind === PaymentIntentKind.Pay;\n }\n\n /** Whether the payment has settled on-chain. */\n public get isSucceeded(): boolean {\n return this.status === PaymentIntentStatus.Succeeded;\n }\n\n /** Whether the intent is still awaiting payment. */\n public get isPending(): boolean {\n return this.status === PaymentIntentStatus.Pending;\n }\n\n /** Human-readable asset label (`XLM` for native). */\n public get assetLabel(): string {\n return !this.asset || this.asset === 'native' ? 'XLM' : this.asset;\n }\n\n /** Re-fetch this intent from the API, returning a fresh instance. */\n public fetch(): Promise<PaymentIntent> {\n return this.client.paymentIntents.fetch(this.id);\n }\n\n /** Update this intent (status / txHash / reference). Mutates and returns it. */\n public async edit(options: UpdatePaymentIntentOptions): Promise<this> {\n const updated = await this.client.paymentIntents.update(this.id, options);\n return this._patch(updated.toJSON());\n }\n\n /**\n * Validate a submitted transaction against this intent. On a match the status\n * is finalized server-side and the webhook fires.\n */\n public validate(txHash: string) {\n return this.client.paymentIntents.validate(this.id, { txHash });\n }\n\n /** Mark this intent as cancelled. */\n public cancel(): Promise<this> {\n return this.edit({ status: PaymentIntentStatus.Cancelled });\n }\n\n /** Delete this intent. */\n public delete() {\n return this.client.paymentIntents.delete(this.id);\n }\n\n public toJSON(): PaymentIntentData {\n return {\n id: this.id,\n kind: this.kind,\n status: this.status,\n network: this.network,\n source: this.source,\n destination: this.destination,\n amount: this.amount,\n asset: this.asset,\n assetIssuer: this.assetIssuer,\n memo: this.memo,\n msg: this.msg,\n callback: this.callback,\n xdr: this.xdr,\n uri: this.uri,\n qr: this.qr,\n txHash: this.txHash,\n reference: this.reference,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","/**\n * Stellar address helpers + a tiny named-address book.\n *\n * So integrators don't have to sprinkle raw `G...` strings everywhere (and risk\n * typos), they can name the accounts they care about once and reference them by\n * name. A plain address string always keeps working — `resolveAddress` only\n * substitutes registered names and otherwise passes the value straight through.\n */\n\n// Stellar strkeys are base32 (RFC 4648 alphabet, no padding). These checks are\n// length/prefix sanity checks, not full checksum validation.\nconst G_ADDRESS = /^G[A-Z2-7]{55}$/; // ed25519 public key (account)\nconst M_ADDRESS = /^M[A-Z2-7]{68}$/; // muxed account\nconst C_ADDRESS = /^C[A-Z2-7]{55}$/; // contract id\n\n/** Whether a value looks like a Stellar account address (`G…`). */\nexport function isStellarAddress(value: unknown): value is string {\n return typeof value === 'string' && G_ADDRESS.test(value);\n}\n\n/** Whether a value looks like a muxed account address (`M…`). */\nexport function isMuxedAddress(value: unknown): value is string {\n return typeof value === 'string' && M_ADDRESS.test(value);\n}\n\n/** Whether a value looks like a Soroban contract id (`C…`). */\nexport function isContractAddress(value: unknown): value is string {\n return typeof value === 'string' && C_ADDRESS.test(value);\n}\n\n/** Whether a value is any kind of Stellar address (account, muxed or contract). */\nexport function isAddress(value: unknown): value is string {\n return isStellarAddress(value) || isMuxedAddress(value) || isContractAddress(value);\n}\n\n/** Throw unless `value` is a valid Stellar account/muxed/contract address. */\nexport function assertAddress(value: unknown, label = 'address'): string {\n if (!isAddress(value)) {\n throw new TypeError(`Invalid Stellar ${label}: ${String(value)}`);\n }\n return value;\n}\n\n/**\n * A registry of named Stellar addresses. Register the accounts you use a lot —\n * your merchant payout account, a treasury, frequent counterparties — and refer\n * to them by name anywhere an address is accepted.\n *\n * @example\n * addresses.define('merchant', 'GC...');\n * await client.paymentIntents.createPay({ destination: 'merchant', amount: '10' });\n */\nexport class AddressBook {\n private readonly entries = new Map<string, string>();\n\n constructor(initial: Record<string, string> = {}) {\n for (const [name, address] of Object.entries(initial)) {\n this.define(name, address);\n }\n }\n\n /** Register (or overwrite) a named address. The address is validated. */\n public define(name: string, address: string): this {\n this.entries.set(name, assertAddress(address, `address for \"${name}\"`));\n return this;\n }\n\n /** Whether a name is registered. */\n public has(name: string): boolean {\n return this.entries.has(name);\n }\n\n /** Look up a registered address by name. */\n public get(name: string): string | undefined {\n return this.entries.get(name);\n }\n\n /** Remove a named address. */\n public delete(name: string): boolean {\n return this.entries.delete(name);\n }\n\n /** All registered names. */\n public names(): string[] {\n return [...this.entries.keys()];\n }\n\n /**\n * Resolve a reference to a concrete address: a registered name is substituted,\n * any other string is returned unchanged (so raw `G…`, muxed `M…`, federation\n * `name*domain`, etc. all keep working).\n */\n public resolve(ref: string): string {\n return this.entries.get(ref) ?? ref;\n }\n}\n\n/** Process-wide default address book. Use `addresses.define(...)` to populate it. */\nexport const addresses = new AddressBook();\n\n/** Anything accepted where an address is expected: a raw address or a name in a book. */\nexport type AddressRef = string;\n\n/**\n * Resolve an {@link AddressRef} using the given book (the shared {@link addresses}\n * by default). Lenient: unknown strings pass through unchanged.\n */\nexport function resolveAddress(ref: AddressRef, book: AddressBook = addresses): string {\n return book.resolve(ref);\n}\n","/**\n * A typed, extensible catalog of Stellar assets.\n *\n * Instead of hunting down an asset's issuer (or pasting the wrong one), use the\n * built-in catalog — `Assets.USDC`, `Assets.EURC`, `Assets.XLM` — which carries\n * the verified issuer for you. Need something else? `defineAsset(...)` makes a\n * typed asset you can reuse. And a plain code string still works everywhere.\n *\n * ⚠️ Issuers are network-specific. The {@link Assets} catalog targets **mainnet**;\n * {@link TestnetAssets} carries the testnet issuers. Bare code strings (e.g.\n * `'USDC'`) are treated as *code only* (no issuer) for backwards compatibility —\n * use the catalog object or `defineAsset` when you want the issuer filled in.\n */\n\nimport { isStellarAddress } from '@/common/addresses';\n\n/** A fully-described Stellar asset. */\nexport interface AssetDefinition {\n /** Asset code, e.g. `USDC`. Use `XLM` (or omit the issuer) for native lumens. */\n code: string;\n /** Issuer account (`G…`). `null`/omitted means the native asset (XLM). */\n issuer?: string | null;\n /** Optional Soroban contract id (`C…`) for the SAC / token contract. */\n contract?: string;\n /** Human-readable name. */\n name?: string;\n /** Network the `issuer` is valid on. */\n network?: 'public' | 'testnet';\n}\n\n/** Anything accepted where an asset is expected: a code string or a definition. */\nexport type AssetRef = string | AssetDefinition;\n\n/** Normalized asset: a code plus a concrete issuer (or `null` for native). */\nexport interface ResolvedAsset {\n /** `XLM` for the native asset, otherwise the asset code. */\n code: string;\n /** Issuer `G…`, or `null` for the native asset. */\n issuer: string | null;\n /** Optional Soroban contract id. */\n contract?: string;\n}\n\nconst NATIVE: AssetDefinition = { code: 'XLM', issuer: null, name: 'Stellar Lumens' };\n\n/**\n * Built-in **mainnet** assets with verified issuers. Extend with your own via\n * {@link defineAsset}. Issuers sourced from the official issuers (Circle for\n * USDC/EURC).\n */\nexport const Assets = {\n /** Native lumens. */\n XLM: NATIVE,\n /** USD Coin by Circle (mainnet). */\n USDC: {\n code: 'USDC',\n issuer: 'GA5ZSEJYB37JRC5AVCIA5MOP4RHTM335X2KGX3IHOJAPP5RE34K4KZVN',\n name: 'USD Coin',\n network: 'public',\n },\n /** Euro Coin by Circle (mainnet). */\n EURC: {\n code: 'EURC',\n issuer: 'GDHU6WRG4IEQXM5NZ4BMPKOXHW76MZM4Y2IEMFDVXBSDP6SJY4ITNPP2',\n name: 'Euro Coin',\n network: 'public',\n },\n} as const satisfies Record<string, AssetDefinition>;\n\n/** Built-in **testnet** assets (Circle's Test SDF Network issuers). */\nexport const TestnetAssets = {\n XLM: NATIVE,\n USDC: {\n code: 'USDC',\n issuer: 'GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5',\n name: 'USD Coin',\n network: 'testnet',\n },\n EURC: {\n code: 'EURC',\n issuer: 'GB3Q6QDZYTHWT7E5PVS3W7FUT5GVAFC5KSZFFLPU25GO7VTC3NM2ZTVO',\n name: 'Euro Coin',\n network: 'testnet',\n },\n} as const satisfies Record<string, AssetDefinition>;\n\n/** Whether a reference denotes the native asset (XLM). */\nexport function isNativeAsset(ref: AssetRef): boolean {\n if (typeof ref === 'string') {\n const code = ref.trim().toLowerCase();\n return code === '' || code === 'xlm' || code === 'native';\n }\n return !ref.issuer || isNativeAsset(ref.code);\n}\n\n/**\n * Create a reusable, typed custom asset. Validates the issuer/contract format so\n * a typo surfaces immediately rather than on-chain.\n *\n * @example\n * const AQUA = defineAsset({ code: 'AQUA', issuer: 'GBNZ...', name: 'Aquarius' });\n * await client.paymentIntents.createPay({ destination, amount: '5', asset: AQUA });\n */\nexport function defineAsset(def: AssetDefinition): AssetDefinition {\n if (!def.code) throw new TypeError('defineAsset requires a `code`.');\n if (def.issuer != null && !isStellarAddress(def.issuer)) {\n throw new TypeError(`defineAsset: invalid issuer for ${def.code}: ${def.issuer}`);\n }\n if (def.contract != null && !/^C[A-Z2-7]{55}$/.test(def.contract)) {\n throw new TypeError(`defineAsset: invalid contract for ${def.code}: ${def.contract}`);\n }\n return Object.freeze({ ...def });\n}\n\n/**\n * Normalize an {@link AssetRef} into `{ code, issuer, contract }`.\n *\n * - A bare string is treated as *code only* (`issuer: null`) — pass a catalog\n * object or `defineAsset(...)` result when you want the issuer included.\n * - The native asset normalizes to `{ code: 'XLM', issuer: null }`.\n */\nexport function resolveAsset(ref: AssetRef): ResolvedAsset {\n if (isNativeAsset(ref)) return { code: 'XLM', issuer: null };\n if (typeof ref === 'string') return { code: ref, issuer: null };\n return {\n code: ref.code,\n issuer: ref.issuer ?? null,\n ...(ref.contract ? { contract: ref.contract } : {}),\n };\n}\n","/**\n * Shared resolution of \"create intent\" input, used by both the server SDK and\n * the web client so the convenience layers behave identically: a typed\n * {@link AssetRef} (e.g. `Assets.USDC`) is expanded into `assetCode`/`assetIssuer`,\n * and named addresses are substituted via an {@link AddressBook}.\n */\n\nimport { addresses as defaultBook, AddressBook, resolveAddress } from '@/common/addresses';\nimport { resolveAsset, type AssetRef } from '@/common/assets';\n\n/** Fields the resolver understands (everything else passes through untouched). */\nexport interface ResolvableIntentInput {\n destination?: string;\n source?: string;\n /** Typed asset (`Assets.USDC`, `defineAsset(...)`) — fills code + issuer. */\n asset?: AssetRef;\n assetCode?: string;\n assetIssuer?: string;\n}\n\n/**\n * Expand `asset` into `assetCode`/`assetIssuer` and resolve named\n * `destination`/`source` addresses. Existing `assetCode`/`assetIssuer` win over a\n * provided `asset`; native assets leave the code unset (the API treats an omitted\n * asset as native XLM). Returns a new object — the input is not mutated.\n */\nexport function resolveIntentBody<T extends ResolvableIntentInput>(\n options: T,\n book: AddressBook = defaultBook,\n): Omit<T, 'asset'> {\n const out: Record<string, unknown> = { ...(options as Record<string, unknown>) };\n\n if (typeof out['destination'] === 'string') {\n out['destination'] = resolveAddress(out['destination'], book);\n }\n if (typeof out['source'] === 'string') {\n out['source'] = resolveAddress(out['source'], book);\n }\n\n if (out['asset'] != null) {\n const { code, issuer } = resolveAsset(out['asset'] as AssetRef);\n delete out['asset'];\n if (issuer) {\n // Non-native: fill code + issuer unless the caller set them explicitly.\n out['assetCode'] ??= code;\n out['assetIssuer'] ??= issuer;\n }\n // Native (issuer == null) → leave assetCode/assetIssuer omitted = native XLM.\n }\n\n return out as Omit<T, 'asset'>;\n}\n","import { PaymentIntent } from '@/structures/PaymentIntent';\nimport type {\n CreatePayPaymentIntentOptions,\n CreateTxPaymentIntentOptions,\n DeletedData,\n ListPaymentIntentsOptions,\n PaymentIntentData,\n PaymentIntentListData,\n UpdatePaymentIntentOptions,\n ValidatePaymentIntentOptions,\n ValidationOutcomeData,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\nimport { resolveIntentBody } from '@/common/intent-input';\n\n/** A page of payment intents plus its pagination metadata. */\nexport interface PaymentIntentPage {\n items: PaymentIntent[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Validation outcome with the (optional) refreshed intent materialized. */\nexport interface ValidationOutcome {\n valid: boolean;\n status: ValidationOutcomeData['status'];\n reason: string | null;\n paymentIntent: PaymentIntent | null;\n}\n\n/**\n * Manages Stellar payment intents — `client.paymentIntents`.\n *\n * @example\n * const intent = await client.paymentIntents.createTx({\n * source: 'G...', destination: 'G...', amount: '25.5',\n * });\n * console.log(intent.uri, intent.qr);\n */\nexport class PaymentIntentManager extends BaseManager<PaymentIntent> {\n private readonly route = '/payment-intents';\n\n /** Create a SEP-7 `tx` intent (source known → unsigned XDR + tx URI + QR). */\n public async createTx(\n options: CreateTxPaymentIntentOptions,\n ): Promise<PaymentIntent> {\n const data = await this.rest.post<PaymentIntentData>(`${this.route}/tx`, {\n body: resolveIntentBody(options),\n });\n return this._add(new PaymentIntent(this.client, data));\n }\n\n /** Create a SEP-7 `pay` intent (no source → pay URI + QR, no XDR). */\n public async createPay(\n options: CreatePayPaymentIntentOptions,\n ): Promise<PaymentIntent> {\n const data = await this.rest.post<PaymentIntentData>(`${this.route}/pay`, {\n body: resolveIntentBody(options),\n });\n return this._add(new PaymentIntent(this.client, data));\n }\n\n /** Get a single payment intent by id. */\n public async fetch(id: string): Promise<PaymentIntent> {\n const data = await this.rest.get<PaymentIntentData>(`${this.route}/${id}`);\n return this._add(new PaymentIntent(this.client, data));\n }\n\n /** List the consumer's payment intents (paginated). */\n public async list(\n options: ListPaymentIntentsOptions = {},\n ): Promise<PaymentIntentPage> {\n const data = await this.rest.get<PaymentIntentListData>(this.route, {\n query: {\n status: options.status,\n take: options.take,\n skip: options.skip,\n },\n });\n return {\n items: data.data.map((d) => this._add(new PaymentIntent(this.client, d))),\n total: data.total,\n take: data.take,\n skip: data.skip,\n };\n }\n\n /** Update a payment intent (status / txHash / reference). */\n public async update(\n id: string,\n options: UpdatePaymentIntentOptions,\n ): Promise<PaymentIntent> {\n const data = await this.rest.patch<PaymentIntentData>(`${this.route}/${id}`, {\n body: options,\n });\n return this._add(new PaymentIntent(this.client, data));\n }\n\n /** Delete a payment intent. */\n public async delete(id: string): Promise<DeletedData> {\n const result = await this.rest.delete<DeletedData>(`${this.route}/${id}`);\n this.cache.delete(id);\n return result;\n }\n\n /**\n * Validate a submitted transaction against the intent (tx success +\n * destination + amount + memo). Finalizes status server-side and fires events.\n */\n public async validate(\n id: string,\n options: ValidatePaymentIntentOptions,\n ): Promise<ValidationOutcome> {\n const data = await this.rest.post<ValidationOutcomeData>(\n `${this.route}/${id}/validate`,\n { body: options },\n );\n const paymentIntent = data.paymentIntent\n ? this._add(new PaymentIntent(this.client, data.paymentIntent))\n : null;\n return {\n valid: data.valid,\n status: data.status,\n reason: data.reason ?? null,\n paymentIntent,\n };\n }\n}\n","import type { Client } from '@/client/Client';\nimport {\n ProductKind,\n type ProductData,\n type UpdateProductOptions,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/** A product / price the consumer can charge for. */\nexport class Product extends Base<ProductData> {\n public name!: string;\n public description!: string | null;\n public amount!: string | null;\n /** Asset code, or `native` for XLM. */\n public asset!: string;\n public kind!: ProductKind;\n public active!: boolean;\n public reference!: string | null;\n public createdAt!: Date;\n public updatedAt!: Date;\n\n constructor(client: Client, data: ProductData) {\n super(client, data);\n }\n\n protected override _patch(data: ProductData): this {\n super._patch(data);\n this.name = data.name;\n this.description = data.description;\n this.amount = data.amount;\n this.asset = data.asset;\n this.kind = data.kind;\n this.active = data.active;\n this.reference = data.reference;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n /** Human-readable asset label (`XLM` for native). */\n public get assetLabel(): string {\n return !this.asset || this.asset === 'native' ? 'XLM' : this.asset;\n }\n\n /** Re-fetch this product. */\n public fetch(): Promise<Product> {\n return this.client.products.fetch(this.id);\n }\n\n /** Update this product. Mutates and returns this. */\n public async edit(options: UpdateProductOptions): Promise<this> {\n const updated = await this.client.products.update(this.id, options);\n return this._patch(updated.toJSON());\n }\n\n /** Mark the product active. */\n public activate(): Promise<this> {\n return this.edit({ active: true });\n }\n\n /** Mark the product inactive. */\n public deactivate(): Promise<this> {\n return this.edit({ active: false });\n }\n\n /** Delete this product. */\n public delete() {\n return this.client.products.delete(this.id);\n }\n\n public toJSON(): ProductData {\n return {\n id: this.id,\n name: this.name,\n description: this.description,\n amount: this.amount,\n asset: this.asset,\n kind: this.kind,\n active: this.active,\n reference: this.reference,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","import { Product } from '@/structures/Product';\nimport type {\n CreateProductOptions,\n ProductData,\n UpdateProductOptions,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\n\ntype ProductDeletedData = { id: string; deleted: boolean };\n\n/**\n * Manages products / prices — `client.products`.\n *\n * @example\n * const product = await client.products.create({\n * name: 'Pro plan — monthly', amount: '49.00', assetCode: 'USDC',\n * });\n */\nexport class ProductManager extends BaseManager<Product> {\n private readonly route = '/products';\n\n /** Create a product. */\n public async create(options: CreateProductOptions): Promise<Product> {\n const data = await this.rest.post<ProductData>(this.route, { body: options });\n return this._add(new Product(this.client, data));\n }\n\n /** List the consumer's products. */\n public async list(): Promise<Product[]> {\n const data = await this.rest.get<ProductData[]>(this.route);\n return data.map((d) => this._add(new Product(this.client, d)));\n }\n\n /** Get a product by id. */\n public async fetch(id: string): Promise<Product> {\n const data = await this.rest.get<ProductData>(`${this.route}/${id}`);\n return this._add(new Product(this.client, data));\n }\n\n /** Update a product. */\n public async update(\n id: string,\n options: UpdateProductOptions,\n ): Promise<Product> {\n const data = await this.rest.patch<ProductData>(`${this.route}/${id}`, {\n body: options,\n });\n return this._add(new Product(this.client, data));\n }\n\n /** Delete a product. */\n public async delete(id: string): Promise<ProductDeletedData> {\n const result = await this.rest.delete<ProductDeletedData>(\n `${this.route}/${id}`,\n );\n this.cache.delete(id);\n return result;\n }\n}\n","import type { Client } from '@/client/Client';\nimport {\n SwapStatus,\n type SubmitSwapOptions,\n type SwapData,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\nimport type { SwapSubmitOutcome } from '@/managers/SwapManager';\n\n/**\n * A Stellar path-payment swap.\n *\n * Wraps the raw API payload with typed accessors and atomic action methods so\n * you can operate on it directly: `await swap.fetch()`,\n * `await swap.submit({ signedXdr })`.\n */\nexport class Swap extends Base<SwapData> {\n public status!: SwapStatus;\n public network!: string;\n /** Account performing the swap. */\n public source!: string;\n /** Account that receives the swapped asset. */\n public destination!: string;\n /** Asset code being sent, or `native` for XLM. */\n public sendAsset!: string;\n public sendAssetIssuer!: string | null;\n public sendAmount!: string;\n public feeAmount!: string;\n public feeBps!: number;\n /** Amount swapped after the fee is deducted. */\n public swapAmount!: string;\n /** Asset code being received, or `native` for XLM. */\n public destAsset!: string;\n public destAssetIssuer!: string | null;\n public destEstimated!: string;\n public destMin!: string;\n public slippageBps!: number;\n public path!: { code: string; issuer: string | null }[];\n public memo!: string | null;\n /** Unsigned transaction envelope (base64 XDR). */\n public xdr!: string;\n /** SEP-7 deep link. */\n public uri!: string;\n public txHash!: string;\n /** QR code of the SEP-7 URI (PNG data URL). */\n public qr!: string;\n public createdAt!: Date;\n public updatedAt!: Date;\n\n constructor(client: Client, data: SwapData) {\n super(client, data);\n }\n\n protected override _patch(data: SwapData): this {\n super._patch(data);\n this.status = data.status;\n this.network = data.network;\n this.source = data.source;\n this.destination = data.destination;\n this.sendAsset = data.sendAsset;\n this.sendAssetIssuer = data.sendAssetIssuer;\n this.sendAmount = data.sendAmount;\n this.feeAmount = data.feeAmount;\n this.feeBps = data.feeBps;\n this.swapAmount = data.swapAmount;\n this.destAsset = data.destAsset;\n this.destAssetIssuer = data.destAssetIssuer;\n this.destEstimated = data.destEstimated;\n this.destMin = data.destMin;\n this.slippageBps = data.slippageBps;\n this.path = data.path;\n this.memo = data.memo;\n this.xdr = data.xdr;\n this.uri = data.uri;\n this.txHash = data.txHash;\n this.qr = data.qr;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n /** Whether the swap has settled on-chain. */\n public get isSucceeded(): boolean {\n return this.status === SwapStatus.Succeeded;\n }\n\n /** Whether the swap is still awaiting submission. */\n public get isPending(): boolean {\n return this.status === SwapStatus.Pending;\n }\n\n /** Human-readable send asset label (`XLM` for native). */\n public get sendAssetLabel(): string {\n return !this.sendAsset || this.sendAsset === 'native' ? 'XLM' : this.sendAsset;\n }\n\n /** Human-readable destination asset label (`XLM` for native). */\n public get destAssetLabel(): string {\n return !this.destAsset || this.destAsset === 'native' ? 'XLM' : this.destAsset;\n }\n\n /** Re-fetch this swap from the API, returning a fresh instance. */\n public fetch(): Promise<Swap> {\n return this.client.swaps.fetch(this.id);\n }\n\n /**\n * Relay the signed transaction for this swap. Mutates this instance from the\n * refreshed swap in the outcome and returns the outcome.\n */\n public async submit(options: SubmitSwapOptions): Promise<SwapSubmitOutcome> {\n const outcome = await this.client.swaps.submit(this.id, options);\n this._patch(outcome.swap.toJSON());\n return outcome;\n }\n\n public toJSON(): SwapData {\n return {\n id: this.id,\n status: this.status,\n network: this.network,\n source: this.source,\n destination: this.destination,\n sendAsset: this.sendAsset,\n sendAssetIssuer: this.sendAssetIssuer,\n sendAmount: this.sendAmount,\n feeAmount: this.feeAmount,\n feeBps: this.feeBps,\n swapAmount: this.swapAmount,\n destAsset: this.destAsset,\n destAssetIssuer: this.destAssetIssuer,\n destEstimated: this.destEstimated,\n destMin: this.destMin,\n slippageBps: this.slippageBps,\n path: this.path,\n memo: this.memo,\n xdr: this.xdr,\n uri: this.uri,\n txHash: this.txHash,\n qr: this.qr,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","import { Swap } from '@/structures/Swap';\nimport type {\n CreateSwapOptions,\n ListSwapsOptions,\n QuoteSwapOptions,\n SubmitSwapOptions,\n SwapData,\n SwapListData,\n SwapQuoteData,\n SwapStatus,\n SwapSubmitOutcomeData,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\n\n/** A page of swaps plus its pagination metadata. */\nexport interface SwapPage {\n items: Swap[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Submission outcome with the refreshed swap materialized. */\nexport interface SwapSubmitOutcome {\n submitted: boolean;\n status: SwapStatus;\n txHash: string | null;\n reason: string | null;\n resultCodes: string[] | null;\n swap: Swap;\n}\n\n/**\n * Manages Stellar swaps — `client.swaps`.\n *\n * @example\n * const quote = await client.swaps.quote({\n * amount: '100', destAssetCode: 'USDC',\n * });\n * const swap = await client.swaps.create({\n * amount: '100', destAssetCode: 'USDC', source: 'G...',\n * });\n * console.log(swap.uri, swap.qr);\n */\nexport class SwapManager extends BaseManager<Swap> {\n private readonly route = '/swaps';\n\n /** Price a swap without creating it. Returns a plain quote (not a {@link Swap}). */\n public async quote(options: QuoteSwapOptions): Promise<SwapQuoteData> {\n return this.rest.post<SwapQuoteData>(`${this.route}/quote`, {\n body: options,\n });\n }\n\n /** Create a swap (unsigned XDR + SEP-7 URI + QR). */\n public async create(options: CreateSwapOptions): Promise<Swap> {\n const data = await this.rest.post<SwapData>(this.route, { body: options });\n return this._add(new Swap(this.client, data));\n }\n\n /** Get a single swap by id. */\n public async fetch(id: string): Promise<Swap> {\n const data = await this.rest.get<SwapData>(`${this.route}/${id}`);\n return this._add(new Swap(this.client, data));\n }\n\n /** List the consumer's swaps (paginated). */\n public async list(options: ListSwapsOptions = {}): Promise<SwapPage> {\n const data = await this.rest.get<SwapListData>(this.route, {\n query: {\n status: options.status,\n take: options.take,\n skip: options.skip,\n },\n });\n return {\n items: data.data.map((d) => this._add(new Swap(this.client, d))),\n total: data.total,\n take: data.take,\n skip: data.skip,\n };\n }\n\n /**\n * Relay a signed swap transaction to the network. Finalizes status\n * server-side and returns the outcome with the refreshed swap materialized.\n */\n public async submit(\n id: string,\n options: SubmitSwapOptions,\n ): Promise<SwapSubmitOutcome> {\n const data = await this.rest.post<SwapSubmitOutcomeData>(\n `${this.route}/${id}/submit`,\n { body: options },\n );\n return {\n submitted: data.submitted,\n status: data.status,\n txHash: data.txHash ?? null,\n reason: data.reason ?? null,\n resultCodes: data.resultCodes ?? null,\n swap: this._add(new Swap(this.client, data.swap)),\n };\n }\n}\n","import type { Client } from '@/client/Client';\nimport {\n WebhookDeliveryStatus,\n WebhookEventType,\n type WebhookDeliveryData,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/** A single attempt to deliver an event to a webhook endpoint (audit record). */\nexport class WebhookDelivery extends Base<WebhookDeliveryData> {\n public endpointId!: string;\n public eventType!: WebhookEventType;\n public eventId!: string;\n public payload!: Record<string, unknown>;\n public status!: WebhookDeliveryStatus;\n public attempts!: number;\n public responseStatus!: number | null;\n public error!: string | null;\n public lastAttemptAt!: Date | null;\n public createdAt!: Date;\n public updatedAt!: Date;\n\n constructor(client: Client, data: WebhookDeliveryData) {\n super(client, data);\n }\n\n protected override _patch(data: WebhookDeliveryData): this {\n super._patch(data);\n this.endpointId = data.endpointId;\n this.eventType = data.eventType;\n this.eventId = data.eventId;\n this.payload = data.payload;\n this.status = data.status;\n this.attempts = data.attempts;\n this.responseStatus = data.responseStatus;\n this.error = data.error;\n this.lastAttemptAt = data.lastAttemptAt ? new Date(data.lastAttemptAt) : null;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n public get isSucceeded(): boolean {\n return this.status === WebhookDeliveryStatus.Succeeded;\n }\n\n /** Manually re-send this delivery. */\n public redeliver(): Promise<WebhookDelivery> {\n return this.client.webhooks.redeliver(this.endpointId, this.id);\n }\n\n public toJSON(): WebhookDeliveryData {\n return {\n id: this.id,\n endpointId: this.endpointId,\n eventType: this.eventType,\n eventId: this.eventId,\n payload: this.payload,\n status: this.status,\n attempts: this.attempts,\n responseStatus: this.responseStatus,\n error: this.error,\n lastAttemptAt: this.lastAttemptAt ? this.lastAttemptAt.toISOString() : null,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","import type { Client } from '@/client/Client';\nimport type {\n ListWebhookDeliveriesOptions,\n UpdateWebhookEndpointOptions,\n WebhookEndpointData,\n WebhookEndpointWithSecretData,\n WebhookEventType,\n} from '@/types/index';\nimport { Base } from '@/structures/Base';\n\n/**\n * A registered webhook endpoint.\n *\n * Note: the signing `secret` is only ever present on the instance returned by\n * `create()` / `rotateSecret()` — list/get responses never include it.\n */\nexport class WebhookEndpoint extends Base<WebhookEndpointData> {\n public url!: string;\n public description!: string | null;\n public enabled!: boolean;\n public eventTypes!: WebhookEventType[];\n public createdAt!: Date;\n public updatedAt!: Date;\n /** HMAC signing secret — only set on create/rotate responses. */\n public readonly secret: string | null;\n\n constructor(\n client: Client,\n data: WebhookEndpointData | WebhookEndpointWithSecretData,\n ) {\n super(client, data);\n this.secret = 'secret' in data ? data.secret : null;\n }\n\n protected override _patch(\n data: WebhookEndpointData | WebhookEndpointWithSecretData,\n ): this {\n super._patch(data);\n this.url = data.url;\n this.description = data.description;\n this.enabled = data.enabled;\n this.eventTypes = data.eventTypes;\n this.createdAt = new Date(data.createdAt);\n this.updatedAt = new Date(data.updatedAt);\n return this;\n }\n\n /** Whether the endpoint receives all events (empty subscription). */\n public get receivesAllEvents(): boolean {\n return this.eventTypes.length === 0;\n }\n\n /** Re-fetch this endpoint. */\n public fetch(): Promise<WebhookEndpoint> {\n return this.client.webhooks.fetch(this.id);\n }\n\n /** Update url/description/enabled/eventTypes. Mutates and returns this. */\n public async edit(options: UpdateWebhookEndpointOptions): Promise<this> {\n const updated = await this.client.webhooks.update(this.id, options);\n return this._patch(updated.toJSON());\n }\n\n /** Pause deliveries to this endpoint. */\n public disable(): Promise<this> {\n return this.edit({ enabled: false });\n }\n\n /** Resume deliveries to this endpoint. */\n public enable(): Promise<this> {\n return this.edit({ enabled: true });\n }\n\n /** Rotate the signing secret (returns a new instance carrying the secret). */\n public rotateSecret(): Promise<WebhookEndpoint> {\n return this.client.webhooks.rotateSecret(this.id);\n }\n\n /** Send a test event to verify the endpoint. */\n public ping() {\n return this.client.webhooks.ping(this.id);\n }\n\n /** List delivery attempts for this endpoint. */\n public fetchDeliveries(options?: ListWebhookDeliveriesOptions) {\n return this.client.webhooks.fetchDeliveries(this.id, options);\n }\n\n /** Delete this endpoint. */\n public delete() {\n return this.client.webhooks.delete(this.id);\n }\n\n public toJSON(): WebhookEndpointData {\n return {\n id: this.id,\n url: this.url,\n description: this.description,\n enabled: this.enabled,\n eventTypes: this.eventTypes,\n createdAt: this.createdAt.toISOString(),\n updatedAt: this.updatedAt.toISOString(),\n };\n }\n}\n","/** Library version, kept in sync with package.json. */\nexport const version = '2.0.0';\n\n/**\n * Default base URL of the Cosmos Pay gateway. Maintained by Cosmos Pay — users\n * never need to set this; it's part of the {@link shared} configuration. Override\n * only when self-hosting or pointing at a staging gateway.\n *\n * This is the public APISIX gateway: requests under `/cosmos-api/*` are\n * authenticated (API key) and proxied to the Payments API. The version segment\n * (`/v1`, see {@link DEFAULT_VERSION}) is appended by the REST layer, producing\n * e.g. `https://api.cosmospay.lat/cosmos-api/v1/payment-intents/pay`.\n */\nexport const DEFAULT_BASE_URL = 'https://api.cosmospay.lat/cosmos-api';\n\n/** Default API version segment prefixed to every route (`/v1/...`). */\nexport const DEFAULT_VERSION = 'v1';\n\n/** Default request timeout in milliseconds. */\nexport const DEFAULT_TIMEOUT = 30_000;\n\n/** Default number of retries for transient failures (network / 429 / 5xx). */\nexport const DEFAULT_RETRIES = 2;\n\n/** Default HMAC signature header sent by the Cosmos Pay webhook dispatcher. */\nexport const SIGNATURE_HEADER = 'x-cosmos-signature';\n\n/**\n * Client debug/telemetry events. The {@link Client} extends EventEmitter and\n * emits these for observability (`debug`/`rateLimit`-style events).\n */\nexport const Events = {\n Debug: 'debug',\n Request: 'request',\n Response: 'response',\n RateLimited: 'rateLimited',\n} as const;\nexport type ClientEvent = (typeof Events)[keyof typeof Events];\n","import { createHmac, timingSafeEqual } from 'node:crypto';\nimport { SIGNATURE_HEADER } from '@/util/Constants';\nimport type { WebhookEvent } from '@/types/index';\n\n/** Options for {@link Webhooks.verify} / {@link Webhooks.constructEvent}. */\nexport interface VerifyWebhookOptions {\n /**\n * Tolerance in seconds between the signed timestamp and now. Protects against\n * replay attacks. Defaults to 300 (5 minutes). Pass 0 to disable the check.\n */\n toleranceSeconds?: number;\n /** Override \"now\" (unix seconds) — useful for testing. */\n now?: number;\n}\n\n/** Thrown when a webhook signature fails verification. */\nexport class WebhookSignatureError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WebhookSignatureError';\n }\n}\n\n/**\n * Stateless helpers to verify the HMAC signatures the Cosmos Pay dispatcher\n * sends with each webhook delivery, and to safely parse the event body.\n *\n * The dispatcher signs each POST with:\n * `X-Cosmos-Signature: t=<unixSeconds>,v1=<hexHmacSha256>`\n * where the HMAC-SHA256 is computed over `${t}.${rawBody}` using the endpoint's\n * `whsec_...` secret.\n *\n * @example\n * // Express raw-body handler\n * app.post('/hooks', express.raw({ type: '*​/*' }), (req, res) => {\n * try {\n * const event = Webhooks.constructEvent(\n * req.body, // the RAW body (Buffer/string)\n * req.header('X-Cosmos-Signature'),\n * process.env.WEBHOOK_SECRET,\n * );\n * // event.type, event.data ...\n * res.sendStatus(200);\n * } catch {\n * res.sendStatus(400);\n * }\n * });\n */\nexport const Webhooks = {\n /** Header name the dispatcher uses for the signature. */\n SIGNATURE_HEADER,\n\n /**\n * Verify a webhook signature. Returns `true` on success, throws\n * {@link WebhookSignatureError} on any failure (so it never silently passes).\n */\n verify(\n rawBody: string | Uint8Array,\n signatureHeader: string | null | undefined,\n secret: string,\n options: VerifyWebhookOptions = {},\n ): boolean {\n if (!signatureHeader) {\n throw new WebhookSignatureError('Missing signature header.');\n }\n if (!secret) {\n throw new WebhookSignatureError('Missing signing secret.');\n }\n\n const { timestamp, signature } = parseSignatureHeader(signatureHeader);\n const payload = typeof rawBody === 'string' ? rawBody : decode(rawBody);\n\n const expected = createHmac('sha256', secret)\n .update(`${timestamp}.${payload}`)\n .digest('hex');\n\n if (!safeEqualHex(expected, signature)) {\n throw new WebhookSignatureError('Signature mismatch.');\n }\n\n const tolerance = options.toleranceSeconds ?? 300;\n if (tolerance > 0) {\n const now = options.now ?? Math.floor(Date.now() / 1000);\n if (Math.abs(now - timestamp) > tolerance) {\n throw new WebhookSignatureError(\n `Timestamp outside tolerance (${tolerance}s).`,\n );\n }\n }\n\n return true;\n },\n\n /**\n * Verify the signature and return the parsed {@link WebhookEvent}. Throws\n * {@link WebhookSignatureError} if verification fails.\n */\n constructEvent<T = unknown>(\n rawBody: string | Uint8Array,\n signatureHeader: string | null | undefined,\n secret: string,\n options: VerifyWebhookOptions = {},\n ): WebhookEvent<T> {\n this.verify(rawBody, signatureHeader, secret, options);\n const payload = typeof rawBody === 'string' ? rawBody : decode(rawBody);\n try {\n return JSON.parse(payload) as WebhookEvent<T>;\n } catch {\n throw new WebhookSignatureError('Body is not valid JSON.');\n }\n },\n};\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nfunction parseSignatureHeader(header: string): {\n timestamp: number;\n signature: string;\n} {\n let timestamp: number | undefined;\n let signature: string | undefined;\n for (const part of header.split(',')) {\n const [key, value] = part.split('=');\n if (!key || value === undefined) continue;\n const k = key.trim();\n if (k === 't') timestamp = Number(value.trim());\n else if (k === 'v1') signature = value.trim();\n }\n if (timestamp === undefined || Number.isNaN(timestamp) || !signature) {\n throw new WebhookSignatureError('Malformed signature header.');\n }\n return { timestamp, signature };\n}\n\nfunction safeEqualHex(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n try {\n return timingSafeEqual(Buffer.from(a, 'hex'), Buffer.from(b, 'hex'));\n } catch {\n return false;\n }\n}\n\nfunction decode(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('utf8');\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { WebhookDelivery } from '@/structures/WebhookDelivery';\nimport { WebhookEndpoint } from '@/structures/WebhookEndpoint';\nimport type {\n CreateWebhookEndpointOptions,\n ListWebhookDeliveriesOptions,\n PaymentIntentData,\n UpdateWebhookEndpointOptions,\n WebhookDeliveryData,\n WebhookDeliveryListData,\n WebhookEndpointData,\n WebhookEndpointWithSecretData,\n WebhookEvent,\n WebhookPingData,\n} from '@/types/index';\nimport { BaseManager } from '@/managers/BaseManager';\nimport { Webhooks, WebhookSignatureError } from '@/util/Webhooks';\nimport { SIGNATURE_HEADER } from '@/util/Constants';\n\n// Local alias — the deleted shape mirrors DeletedData.\ntype WebhookDeletedData = { id: string; deleted: boolean };\n\n/** A page of webhook deliveries plus its pagination metadata. */\nexport interface WebhookDeliveryPage {\n items: WebhookDelivery[];\n total: number;\n take: number;\n skip: number;\n}\n\n/** Options for verifying + dispatching an incoming webhook. */\nexport interface WebhookProcessOptions {\n /** Signing secret. Falls back to the client's `webhookSecret` when omitted. */\n secret?: string;\n /** Replay tolerance in seconds (default 300; 0 disables). */\n toleranceSeconds?: number;\n}\n\n/** Options for the built-in HTTP webhook handlers. */\nexport type WebhookHandlerOptions = WebhookProcessOptions;\n\n/**\n * Listener signatures for {@link WebhookManager}. You can subscribe with the raw\n * event type (`PAYMENT_INTENT_SUCCEEDED`), its camelCase alias\n * (`paymentIntentSucceeded`), or `event` to catch them all.\n */\nexport interface WebhookListenerEvents {\n event: [WebhookEvent<PaymentIntentData>];\n\n PAYMENT_INTENT_CREATED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_UPDATED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_SUCCEEDED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_FAILED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_CANCELLED: [WebhookEvent<PaymentIntentData>];\n PAYMENT_INTENT_DELETED: [WebhookEvent<PaymentIntentData>];\n\n paymentIntentCreated: [WebhookEvent<PaymentIntentData>];\n paymentIntentUpdated: [WebhookEvent<PaymentIntentData>];\n paymentIntentSucceeded: [WebhookEvent<PaymentIntentData>];\n paymentIntentFailed: [WebhookEvent<PaymentIntentData>];\n paymentIntentCancelled: [WebhookEvent<PaymentIntentData>];\n paymentIntentDeleted: [WebhookEvent<PaymentIntentData>];\n}\n\n/** Minimal Express-like request (so we don't depend on `@types/express`). */\ninterface RequestLike {\n headers: Record<string, string | string[] | undefined>;\n body?: unknown;\n rawBody?: unknown;\n [key: string]: unknown;\n}\n\n/** Minimal Express-like response. */\ninterface ResponseLike {\n status(code: number): ResponseLike;\n send(body?: unknown): unknown;\n end(body?: unknown): unknown;\n}\n\n// Typed event overloads (declaration merging onto the class).\nexport interface WebhookManager {\n on<E extends keyof WebhookListenerEvents>(\n event: E,\n listener: (...args: WebhookListenerEvents[E]) => void,\n ): this;\n once<E extends keyof WebhookListenerEvents>(\n event: E,\n listener: (...args: WebhookListenerEvents[E]) => void,\n ): this;\n off<E extends keyof WebhookListenerEvents>(\n event: E,\n listener: (...args: WebhookListenerEvents[E]) => void,\n ): this;\n emit<E extends keyof WebhookListenerEvents>(\n event: E,\n ...args: WebhookListenerEvents[E]\n ): boolean;\n}\n\n/**\n * Manages webhook endpoints, their delivery audit trail, **and** the incoming\n * event listener — `client.webhooks`.\n *\n * Registering endpoints (server-side CRUD):\n * @example\n * const endpoint = await client.webhooks.create({\n * url: 'https://me.example.com/hooks',\n * eventTypes: ['PAYMENT_INTENT_SUCCEEDED'],\n * });\n * console.log(endpoint.secret); // shown once — store it!\n *\n * Receiving events (listener):\n * @example\n * client.webhooks.on('paymentIntentSucceeded', (event) => {\n * console.log('Paid!', event.data.id);\n * });\n *\n * import { createServer } from 'node:http';\n * createServer(client.webhooks.createHandler()).listen(4242);\n */\nexport class WebhookManager extends BaseManager<WebhookEndpoint> {\n private readonly route = '/webhooks';\n\n // ── Endpoint CRUD ───────────────────────────────────────────────────────────\n\n /** Register a webhook endpoint (the returned instance carries the secret once). */\n public async create(\n options: CreateWebhookEndpointOptions,\n ): Promise<WebhookEndpoint> {\n const data = await this.rest.post<WebhookEndpointWithSecretData>(this.route, {\n body: options,\n });\n return this._add(new WebhookEndpoint(this.client, data));\n }\n\n /** List the consumer's webhook endpoints. */\n public async list(): Promise<WebhookEndpoint[]> {\n const data = await this.rest.get<WebhookEndpointData[]>(this.route);\n return data.map((d) => this._add(new WebhookEndpoint(this.client, d)));\n }\n\n /** Get a webhook endpoint by id. */\n public async fetch(id: string): Promise<WebhookEndpoint> {\n const data = await this.rest.get<WebhookEndpointData>(`${this.route}/${id}`);\n return this._add(new WebhookEndpoint(this.client, data));\n }\n\n /** Update a webhook endpoint (url/description/enabled/eventTypes). */\n public async update(\n id: string,\n options: UpdateWebhookEndpointOptions,\n ): Promise<WebhookEndpoint> {\n const data = await this.rest.patch<WebhookEndpointData>(\n `${this.route}/${id}`,\n { body: options },\n );\n return this._add(new WebhookEndpoint(this.client, data));\n }\n\n /** Delete a webhook endpoint. */\n public async delete(id: string): Promise<WebhookDeletedData> {\n const result = await this.rest.delete<WebhookDeletedData>(\n `${this.route}/${id}`,\n );\n this.cache.delete(id);\n return result;\n }\n\n /** Rotate the signing secret (returns a new instance carrying the secret). */\n public async rotateSecret(id: string): Promise<WebhookEndpoint> {\n const data = await this.rest.post<WebhookEndpointWithSecretData>(\n `${this.route}/${id}/rotate-secret`,\n );\n return this._add(new WebhookEndpoint(this.client, data));\n }\n\n /** Send a test event to verify the endpoint. */\n public ping(id: string): Promise<WebhookPingData> {\n return this.rest.post<WebhookPingData>(`${this.route}/${id}/ping`);\n }\n\n /** List delivery attempts for an endpoint (audit trail). */\n public async fetchDeliveries(\n id: string,\n options: ListWebhookDeliveriesOptions = {},\n ): Promise<WebhookDeliveryPage> {\n const data = await this.rest.get<WebhookDeliveryListData>(\n `${this.route}/${id}/deliveries`,\n {\n query: {\n status: options.status,\n take: options.take,\n skip: options.skip,\n },\n },\n );\n return {\n items: data.data.map((d) => new WebhookDelivery(this.client, d)),\n total: data.total,\n take: data.take,\n skip: data.skip,\n };\n }\n\n /** Manually re-send a past delivery. */\n public async redeliver(\n id: string,\n deliveryId: string,\n ): Promise<WebhookDelivery> {\n const data = await this.rest.post<WebhookDeliveryData>(\n `${this.route}/${id}/deliveries/${deliveryId}/redeliver`,\n );\n return new WebhookDelivery(this.client, data);\n }\n\n // ── Incoming event listener ──────────────────────────────────────────────────\n\n /**\n * Verify a raw incoming webhook request and dispatch it to the listeners\n * registered via {@link WebhookManager.on}. Returns the parsed event.\n *\n * Emits, in order: the raw type (`PAYMENT_INTENT_SUCCEEDED`), the camelCase\n * alias (`paymentIntentSucceeded`) and the catch-all `event`.\n *\n * @throws {WebhookSignatureError} when the signature is missing/invalid.\n */\n public process(\n rawBody: string | Uint8Array,\n signatureHeader: string | null | undefined,\n options: WebhookProcessOptions = {},\n ): WebhookEvent<PaymentIntentData> {\n const secret = options.secret ?? this.client.webhookSecret;\n if (!secret) {\n throw new WebhookSignatureError(\n 'No webhook secret configured. Pass `{ secret }` or set `webhookSecret` on the client.',\n );\n }\n\n const event = Webhooks.constructEvent<PaymentIntentData>(\n rawBody,\n signatureHeader,\n secret,\n { toleranceSeconds: options.toleranceSeconds },\n );\n\n this.emit(event.type, event);\n this.emit(toCamelEvent(event.type), event);\n this.emit('event', event);\n return event;\n }\n\n /**\n * Build a Node.js `http`/`https` request handler that verifies the signature,\n * dispatches the event to your listeners, and replies `200`/`400`.\n *\n * @example\n * import { createServer } from 'node:http';\n * createServer(client.webhooks.createHandler({ secret })).listen(4242);\n */\n public createHandler(\n options: WebhookHandlerOptions = {},\n ): (req: IncomingMessage, res: ServerResponse) => void {\n return (req, res) => {\n void this.collectBody(req)\n .then((raw) => {\n const sig = headerValue(req.headers[SIGNATURE_HEADER]);\n this.process(raw, sig, options);\n res.statusCode = 200;\n res.end('ok');\n })\n .catch((err: unknown) => {\n res.statusCode = err instanceof WebhookSignatureError ? 400 : 500;\n res.end(\n err instanceof WebhookSignatureError ? 'invalid signature' : 'error',\n );\n });\n };\n }\n\n /**\n * Express-style middleware. Expects the **raw** body (e.g. mounted with\n * `express.raw({ type: '*​/*' })`). On success it attaches the parsed event to\n * `req.cosmosEvent` and calls `next()`; on a bad signature it replies `400`.\n *\n * @example\n * app.post('/hooks', express.raw({ type: '*​/*' }), client.webhooks.middleware({ secret }));\n */\n public middleware(\n options: WebhookHandlerOptions = {},\n ): (req: RequestLike, res: ResponseLike, next: (err?: unknown) => void) => void {\n return (req, res, next) => {\n try {\n const raw = extractRawBody(req);\n const sig = headerValue(req.headers[SIGNATURE_HEADER]);\n const event = this.process(raw, sig, options);\n req.cosmosEvent = event;\n next();\n } catch (err) {\n if (err instanceof WebhookSignatureError) {\n res.status(400).send('invalid signature');\n return;\n }\n next(err);\n }\n };\n }\n\n /** Read a Node.js request stream into a single Buffer. */\n private collectBody(req: IncomingMessage): Promise<Buffer> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on('data', (chunk: Buffer) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n req.on('error', reject);\n });\n }\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\n/** `PAYMENT_INTENT_SUCCEEDED` → `paymentIntentSucceeded`. */\nfunction toCamelEvent(type: string): keyof WebhookListenerEvents {\n return type\n .toLowerCase()\n .replace(/_([a-z])/g, (_, c: string) =>\n c.toUpperCase(),\n ) as keyof WebhookListenerEvents;\n}\n\nfunction headerValue(value: string | string[] | undefined): string | undefined {\n return Array.isArray(value) ? value[0] : value;\n}\n\nfunction extractRawBody(req: RequestLike): string | Uint8Array {\n const candidate = req.rawBody ?? req.body;\n if (typeof candidate === 'string' || candidate instanceof Uint8Array) {\n return candidate;\n }\n // express.json() already parsed it — re-stringify so the signature still matches\n // only if the original raw body is unavailable (best-effort).\n if (candidate && typeof candidate === 'object') {\n return JSON.stringify(candidate);\n }\n return '';\n}\n","/**\n * Error thrown when the Cosmos Pay API responds with a non-2xx status.\n *\n * Carries the HTTP status, the parsed response body and the request context so\n * callers can branch on `error.status` (e.g. 404 → not found, 403 → gateway).\n */\nexport class CosmosPayAPIError extends Error {\n /** HTTP status code returned by the API. */\n public readonly status: number;\n /** HTTP method of the failed request. */\n public readonly method: string;\n /** Absolute URL of the failed request. */\n public readonly url: string;\n /** Parsed response body (object when JSON, string otherwise, or null). */\n public readonly body: unknown;\n /** Machine-readable error code extracted from the body when present. */\n public readonly code: string | undefined;\n\n constructor(options: {\n status: number;\n method: string;\n url: string;\n body: unknown;\n }) {\n const message = CosmosPayAPIError.resolveMessage(options.status, options.body);\n super(message);\n this.name = 'CosmosPayAPIError';\n this.status = options.status;\n this.method = options.method;\n this.url = options.url;\n this.body = options.body;\n this.code = CosmosPayAPIError.resolveCode(options.body);\n Error.captureStackTrace?.(this, CosmosPayAPIError);\n }\n\n private static resolveMessage(status: number, body: unknown): string {\n if (body && typeof body === 'object') {\n const maybe = body as { message?: unknown; error?: unknown };\n const msg = maybe.message ?? maybe.error;\n if (Array.isArray(msg)) return `[${status}] ${msg.join(', ')}`;\n if (typeof msg === 'string') return `[${status}] ${msg}`;\n }\n if (typeof body === 'string' && body.length) return `[${status}] ${body}`;\n return `[${status}] Request failed`;\n }\n\n private static resolveCode(body: unknown): string | undefined {\n if (body && typeof body === 'object') {\n const maybe = body as { code?: unknown; error?: unknown };\n if (typeof maybe.code === 'string') return maybe.code;\n if (typeof maybe.error === 'string') return maybe.error;\n }\n return undefined;\n }\n}\n\n/**\n * Error thrown when a request never reaches the API: network failure, abort or\n * timeout. Distinct from {@link CosmosPayAPIError}, which always has a status.\n */\nexport class CosmosPayRequestError extends Error {\n public readonly method: string;\n public readonly url: string;\n public readonly cause: unknown;\n\n constructor(options: { method: string; url: string; cause: unknown }) {\n const reason =\n options.cause instanceof Error ? options.cause.message : String(options.cause);\n super(`Request to ${options.method} ${options.url} failed: ${reason}`);\n this.name = 'CosmosPayRequestError';\n this.method = options.method;\n this.url = options.url;\n this.cause = options.cause;\n Error.captureStackTrace?.(this, CosmosPayRequestError);\n }\n}\n","import { EventEmitter } from 'node:events';\nimport {\n CosmosPayAPIError,\n CosmosPayRequestError,\n} from '@/errors/CosmosPayError';\nimport {\n DEFAULT_RETRIES,\n DEFAULT_TIMEOUT,\n DEFAULT_VERSION,\n Events,\n version,\n} from '@/util/Constants';\n\n/** A `fetch`-compatible function (defaults to the global `fetch`). */\nexport type FetchLike = typeof fetch;\n\n/** Options accepted when constructing a {@link REST} instance. */\nexport interface RESTOptions {\n /**\n * Base URL of the Cosmos Pay gateway (no trailing slash), e.g.\n * `https://api.cosmospay.lat/cosmos-api`. The version segment is appended\n * automatically.\n */\n baseURL: string;\n /**\n * API key issued by the Cosmos developer platform. Sent as\n * `Authorization: Bearer <apiKey>` (and `apikey: <apiKey>`) to the gateway.\n */\n apiKey?: string;\n /**\n * Shared gateway secret (`X-Gateway-Secret`). Only needed when calling the\n * service directly (bypassing APISIX) — typically local development.\n */\n gatewaySecret?: string;\n /**\n * Authenticated consumer username (`X-Consumer-Username`). Pair with\n * `gatewaySecret` for direct service access.\n */\n consumerUsername?: string;\n /**\n * API version segment prefixed to every route. Defaults to `v1`. Set to an\n * empty string when your gateway already injects the version.\n */\n version?: string;\n /** Per-request timeout in milliseconds (default 30000). */\n timeout?: number;\n /** Retries for transient failures — network errors, 429 and 5xx (default 2). */\n retries?: number;\n /** Extra headers merged into every request. */\n headers?: Record<string, string>;\n /** Custom fetch implementation (e.g. a polyfill on old runtimes). */\n fetch?: FetchLike;\n}\n\n/** Internal options for a single request. */\nexport interface RequestOptions {\n /** Query string parameters; `undefined`/`null` values are dropped. */\n query?: Record<string, string | number | boolean | undefined | null>;\n /** JSON body to send. */\n body?: unknown;\n /** Per-request header overrides. */\n headers?: Record<string, string>;\n /** Per-request AbortSignal. */\n signal?: AbortSignal;\n}\n\nconst RETRYABLE_STATUS = new Set([408, 429, 500, 502, 503, 504]);\n\n/**\n * The HTTP layer. Owns the base URL, authentication and retry/timeout policy,\n * and exposes thin verb helpers (`get`/`post`/`patch`/`delete`). Managers call\n * these — they never touch `fetch` directly.\n */\nexport class REST extends EventEmitter {\n public baseURL: string;\n public readonly version: string;\n private readonly timeout: number;\n private readonly retries: number;\n private readonly fetchFn: FetchLike;\n private readonly extraHeaders: Record<string, string>;\n private apiKey?: string;\n private gatewaySecret?: string;\n private consumerUsername?: string;\n\n constructor(options: RESTOptions) {\n super();\n if (!options.baseURL) {\n throw new TypeError('REST requires a `baseURL`.');\n }\n this.baseURL = options.baseURL.replace(/\\/+$/, '');\n this.version = options.version ?? DEFAULT_VERSION;\n this.timeout = options.timeout ?? DEFAULT_TIMEOUT;\n this.retries = options.retries ?? DEFAULT_RETRIES;\n this.extraHeaders = options.headers ?? {};\n this.apiKey = options.apiKey;\n this.gatewaySecret = options.gatewaySecret;\n this.consumerUsername = options.consumerUsername;\n\n const fetchFn = options.fetch ?? globalThis.fetch;\n if (typeof fetchFn !== 'function') {\n throw new TypeError(\n 'No global `fetch` found. Use Node.js >= 18 or pass a `fetch` implementation in the client options.',\n );\n }\n this.fetchFn = fetchFn.bind(globalThis);\n }\n\n /** Replace the API key used for subsequent requests. */\n public setApiKey(apiKey: string): this {\n this.apiKey = apiKey;\n return this;\n }\n\n /** Set direct-access gateway credentials (local/dev usage). */\n public setGatewayCredentials(secret: string, consumerUsername: string): this {\n this.gatewaySecret = secret;\n this.consumerUsername = consumerUsername;\n return this;\n }\n\n public get<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return this.request<T>('GET', path, options);\n }\n\n public post<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return this.request<T>('POST', path, options);\n }\n\n public patch<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return this.request<T>('PATCH', path, options);\n }\n\n public delete<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return this.request<T>('DELETE', path, options);\n }\n\n /** Build the absolute URL for a route, applying the version prefix + query. */\n public buildURL(path: string, query?: RequestOptions['query']): string {\n const clean = path.startsWith('/') ? path : `/${path}`;\n const prefix = this.version ? `/${this.version}` : '';\n const url = new URL(`${this.baseURL}${prefix}${clean}`);\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue;\n url.searchParams.set(key, String(value));\n }\n }\n return url.toString();\n }\n\n private buildHeaders(extra?: Record<string, string>): Record<string, string> {\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'User-Agent': `@cosmosapp/pay_sdk/${version}`,\n ...this.extraHeaders,\n };\n if (this.apiKey) {\n headers['Authorization'] = `Bearer ${this.apiKey}`;\n headers['apikey'] = this.apiKey;\n }\n if (this.gatewaySecret) headers['X-Gateway-Secret'] = this.gatewaySecret;\n if (this.consumerUsername) {\n headers['X-Consumer-Username'] = this.consumerUsername;\n }\n return { ...headers, ...extra };\n }\n\n /** Core request with retry, timeout and structured error handling. */\n public async request<T>(\n method: string,\n path: string,\n options: RequestOptions = {},\n ): Promise<T> {\n const url = this.buildURL(path, options.query);\n const headers = this.buildHeaders(options.headers);\n\n let serializedBody: string | undefined;\n if (options.body !== undefined) {\n serializedBody = JSON.stringify(options.body);\n headers['Content-Type'] = 'application/json';\n }\n\n let attempt = 0;\n let lastError: unknown;\n\n while (attempt <= this.retries) {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeout);\n const signal = options.signal\n ? anySignal([options.signal, controller.signal])\n : controller.signal;\n\n this.emit(Events.Request, { method, url, attempt });\n\n try {\n const response = await this.fetchFn(url, {\n method,\n headers,\n body: serializedBody,\n signal,\n });\n clearTimeout(timer);\n\n this.emit(Events.Response, {\n method,\n url,\n status: response.status,\n attempt,\n });\n\n if (response.status === 429) {\n this.emit(Events.RateLimited, { method, url, attempt });\n }\n\n if (!response.ok) {\n const body = await safeParse(response);\n if (RETRYABLE_STATUS.has(response.status) && attempt < this.retries) {\n await this.backoff(response, attempt);\n attempt++;\n continue;\n }\n throw new CosmosPayAPIError({ status: response.status, method, url, body });\n }\n\n return (await safeParse(response)) as T;\n } catch (error) {\n clearTimeout(timer);\n if (error instanceof CosmosPayAPIError) throw error;\n\n // Network/abort/timeout → retry, then surface as a request error.\n lastError = error;\n if (attempt < this.retries) {\n await sleep(backoffDelay(attempt));\n attempt++;\n continue;\n }\n throw new CosmosPayRequestError({ method, url, cause: error });\n }\n }\n\n throw new CosmosPayRequestError({ method, url, cause: lastError });\n }\n\n private async backoff(response: Response, attempt: number): Promise<void> {\n const retryAfter = response.headers.get('retry-after');\n const ms = retryAfter\n ? Number(retryAfter) * 1000\n : backoffDelay(attempt);\n await sleep(Number.isFinite(ms) ? ms : backoffDelay(attempt));\n }\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nfunction backoffDelay(attempt: number): number {\n return Math.min(1000 * 2 ** attempt, 8000);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function safeParse(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) return null;\n const contentType = response.headers.get('content-type') ?? '';\n if (contentType.includes('application/json')) {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n return text;\n}\n\n/** Combine multiple AbortSignals into one (first to abort wins). */\nfunction anySignal(signals: AbortSignal[]): AbortSignal {\n const controller = new AbortController();\n const onAbort = (signal: AbortSignal) => () => controller.abort(signal.reason);\n for (const signal of signals) {\n if (signal.aborted) {\n controller.abort(signal.reason);\n break;\n }\n signal.addEventListener('abort', onAbort(signal), { once: true });\n }\n return controller.signal;\n}\n","import { DEFAULT_BASE_URL, DEFAULT_VERSION } from '@/util/Constants';\n\n/**\n * Internal (\"shared\") configuration that Cosmos Pay maintains on the user's\n * behalf. These are the gateway / infrastructure details an integrator should\n * **not** have to know about — they're pre-filled here so that, in practice, the\n * only credential a user provides is their `apiKey`.\n *\n * Every value is overridable (per-client via {@link ClientOptions}, or globally\n * via {@link Client.shared}) for self-hosting, staging or local development.\n */\nexport interface SharedConfig {\n /** Base URL of the Cosmos Pay gateway. */\n baseURL: string;\n /** API version segment prefixed to every route (`/v1/...`). */\n version: string;\n /**\n * Shared gateway secret (`X-Gateway-Secret`). Only used when talking to the\n * service directly, bypassing the gateway (local development). Internal.\n */\n gatewaySecret?: string;\n /**\n * Authenticated consumer username (`X-Consumer-Username`). Paired with\n * `gatewaySecret` for direct service access. Internal.\n */\n consumerUsername?: string;\n /**\n * Default webhook signing secret used by the webhook listener\n * (`client.webhooks.process` / handlers) when no secret is passed explicitly.\n */\n webhookSecret?: string;\n}\n\n/**\n * The mutable, process-wide defaults. Cosmos Pay ships sane values here; you can\n * tweak them once at startup (e.g. `Client.shared.baseURL = '...'`) and every\n * client created afterwards inherits them.\n */\nexport const shared: SharedConfig = {\n baseURL: DEFAULT_BASE_URL,\n version: DEFAULT_VERSION,\n};\n\n/** Merge a partial override on top of the current shared defaults. */\nexport function resolveShared(overrides: Partial<SharedConfig> = {}): SharedConfig {\n const defined: Partial<SharedConfig> = {};\n for (const key of Object.keys(overrides) as (keyof SharedConfig)[]) {\n const value = overrides[key];\n if (value !== undefined) {\n Object.assign(defined, { [key]: value });\n }\n }\n return { ...shared, ...defined };\n}\n","import { EventEmitter } from 'node:events';\nimport { AnalyticsManager } from '@/managers/AnalyticsManager';\nimport { CustomerManager } from '@/managers/CustomerManager';\nimport { HealthManager } from '@/managers/HealthManager';\nimport { LiquidityManager } from '@/managers/LiquidityManager';\nimport { OnrampManager } from '@/managers/OnrampManager';\nimport { OfframpManager } from '@/managers/OfframpManager';\nimport { ActivityManager } from '@/managers/ActivityManager';\nimport { KycManager } from '@/managers/KycManager';\nimport { PollarManager } from '@/managers/PollarManager';\nimport { PaymentIntentManager } from '@/managers/PaymentIntentManager';\nimport { ProductManager } from '@/managers/ProductManager';\nimport { SwapManager } from '@/managers/SwapManager';\nimport { WebhookManager } from '@/managers/WebhookManager';\nimport { REST, type FetchLike } from '@/rest/REST';\nimport { version } from '@/util/Constants';\nimport { resolveShared, shared, type SharedConfig } from '@/util/shared';\n\n/**\n * Options accepted by the {@link Client} constructor.\n *\n * In practice the only value you provide is `apiKey` — everything else (the\n * gateway URL, version and other infrastructure details) is pre-filled from the\n * {@link Client.shared} defaults that Cosmos Pay maintains for you.\n */\nexport interface ClientOptions {\n /**\n * Your Cosmos Pay API key. Sent to the gateway as `Authorization: Bearer\n * <apiKey>`. The key type determines the network (`dv_` → testnet, `prod_` →\n * mainnet). This is the only credential a typical integration needs.\n */\n apiKey: string;\n\n /**\n * Default webhook signing secret used by the webhook listener\n * (`client.webhooks.on(...)` + handlers) when you don't pass one explicitly.\n */\n webhookSecret?: string;\n\n /** Per-request timeout in milliseconds (default 30000). */\n timeout?: number;\n /** Retries for transient failures — network errors, 429 and 5xx (default 2). */\n retries?: number;\n /** Extra headers merged into every request. */\n headers?: Record<string, string>;\n /** Custom fetch implementation (e.g. a polyfill on old runtimes). */\n fetch?: FetchLike;\n\n // ── Advanced / internal overrides (you normally never set these) ────────────\n /**\n * Override the gateway base URL. Defaults to {@link Client.shared}`.baseURL`.\n * Only needed for self-hosting or a staging gateway.\n * @internal\n */\n baseURL?: string;\n /**\n * Override the API version segment. Defaults to `v1`.\n * @internal\n */\n version?: string;\n /**\n * Shared gateway secret (`X-Gateway-Secret`) for direct, gateway-bypassing\n * access (local development). Maintained internally.\n * @internal\n */\n gatewaySecret?: string;\n /**\n * Consumer username (`X-Consumer-Username`) for direct access. Internal.\n * @internal\n */\n consumerUsername?: string;\n}\n\n/** Payloads emitted by the {@link Client} for observability. */\nexport interface ClientEvents {\n request: [{ method: string; url: string; attempt: number }];\n response: [{ method: string; url: string; status: number; attempt: number }];\n rateLimited: [{ method: string; url: string; attempt: number }];\n debug: [message: string];\n}\n\nexport interface Client {\n on<E extends keyof ClientEvents>(\n event: E,\n listener: (...args: ClientEvents[E]) => void,\n ): this;\n once<E extends keyof ClientEvents>(\n event: E,\n listener: (...args: ClientEvents[E]) => void,\n ): this;\n off<E extends keyof ClientEvents>(\n event: E,\n listener: (...args: ClientEvents[E]) => void,\n ): this;\n emit<E extends keyof ClientEvents>(\n event: E,\n ...args: ClientEvents[E]\n ): boolean;\n}\n\n/**\n * The main entry point of the SDK — a single, atomic client that exposes every\n * resource through its own manager — an atomic, single-client design.\n *\n * @example\n * import { Client } from '@cosmosapp/pay_sdk';\n *\n * // The user only provides their API key — the gateway is handled for them.\n * const client = new Client({ apiKey: process.env.COSMOS_PAY_API_KEY });\n *\n * const intent = await client.paymentIntents.createPay({ destination: 'G...', amount: '10' });\n * console.log(intent.uri);\n */\nexport class Client extends EventEmitter {\n /** Library version. */\n public static readonly version = version;\n\n /**\n * Process-wide shared defaults maintained by Cosmos Pay (gateway URL, version,\n * internal secrets). Mutate once at startup to change them for every client\n * (e.g. self-hosting): `Client.shared.baseURL = 'https://gateway.your-domain.com'`.\n */\n public static readonly shared: SharedConfig = shared;\n\n /** Resolved shared configuration for this client instance. */\n public readonly shared: SharedConfig;\n\n /** Default webhook signing secret for the webhook listener (if configured). */\n public webhookSecret: string | undefined;\n\n /** The underlying HTTP layer. Shared by every manager. */\n public readonly rest: REST;\n\n /** Stellar payment intents — create/list/fetch/update/delete/validate. */\n public readonly paymentIntents: PaymentIntentManager;\n /** Webhook endpoints, delivery audit trail, and the event listener. */\n public readonly webhooks: WebhookManager;\n /** Products / prices. */\n public readonly products: ProductManager;\n /** Stellar swaps — quote/create/fetch/list/submit. */\n public readonly swaps: SwapManager;\n /** Liquidity pools: browse, positions, deposit / withdraw. */\n public readonly liquidity: LiquidityManager;\n /** Fiat -> stablecoin: quotes, payins, trustlines, virtual accounts. */\n public readonly onramp: OnrampManager;\n /** Stablecoin -> fiat: quotes, authorize, payouts, compliance documents. */\n public readonly offramp: OfframpManager;\n /** The client event stream: report events, read them back, summarize. */\n public readonly activity: ActivityManager;\n /** KYC / KYB: receivers, their wallets and their bank accounts. */\n public readonly kyc: KycManager;\n /** Pollar: social login, its sessions, and the custodial wallets behind them. */\n public readonly pollar: PollarManager;\n /** Customers. */\n public readonly customers: CustomerManager;\n /** Read-only analytics (summary, balances, logs). */\n public readonly analytics: AnalyticsManager;\n /** Service health probes (public). */\n public readonly health: HealthManager;\n\n constructor(options: ClientOptions) {\n super();\n if (!options || !options.apiKey) {\n throw new TypeError('Client requires an `apiKey` option.');\n }\n\n // Fill the infrastructure details from the shared defaults; the user only\n // had to bring their apiKey.\n this.shared = resolveShared({\n baseURL: options.baseURL,\n version: options.version,\n gatewaySecret: options.gatewaySecret,\n consumerUsername: options.consumerUsername,\n webhookSecret: options.webhookSecret,\n });\n this.webhookSecret = this.shared.webhookSecret;\n\n this.rest = new REST({\n baseURL: this.shared.baseURL,\n apiKey: options.apiKey,\n gatewaySecret: this.shared.gatewaySecret,\n consumerUsername: this.shared.consumerUsername,\n version: this.shared.version,\n timeout: options.timeout,\n retries: options.retries,\n headers: options.headers,\n fetch: options.fetch,\n });\n\n // Re-emit REST telemetry through the client so consumers can subscribe to\n // `client.on('request' | 'response' | 'rateLimited' | 'debug', ...)`.\n this.rest.on('request', (p) => this.emit('request', p));\n this.rest.on('response', (p) => this.emit('response', p));\n this.rest.on('rateLimited', (p) => this.emit('rateLimited', p));\n\n this.paymentIntents = new PaymentIntentManager(this);\n this.webhooks = new WebhookManager(this);\n this.products = new ProductManager(this);\n this.swaps = new SwapManager(this);\n this.liquidity = new LiquidityManager(this);\n this.onramp = new OnrampManager(this);\n this.offramp = new OfframpManager(this);\n this.activity = new ActivityManager(this);\n this.kyc = new KycManager(this);\n this.pollar = new PollarManager(this);\n this.customers = new CustomerManager(this);\n this.analytics = new AnalyticsManager(this);\n this.health = new HealthManager(this);\n }\n\n /** Update the API key used for subsequent requests. */\n public setApiKey(apiKey: string): this {\n this.rest.setApiKey(apiKey);\n return this;\n }\n\n /** Set the default webhook signing secret for the webhook listener. */\n public setWebhookSecret(secret: string): this {\n this.webhookSecret = secret;\n return this;\n }\n\n /** Set direct-access gateway credentials (internal / local dev usage). */\n public setGatewayCredentials(secret: string, consumerUsername: string): this {\n this.rest.setGatewayCredentials(secret, consumerUsername);\n return this;\n }\n}\n","/**\n * Typed identifiers for the wallets the web client knows about, so you can write\n * `Wallets.FREIGHTER` instead of remembering the `'freighter'` magic string —\n * while any custom adapter id still works.\n */\n\n/** Built-in wallet ids (matches each adapter's `id`). */\nexport const Wallets = {\n /** Cosmos Pay's own wallet — extension, or the hosted build (see CosmosWalletAdapter). */\n COSMOS: 'cosmos',\n FREIGHTER: 'freighter',\n XBULL: 'xbull',\n RABET: 'rabet',\n LOBSTR: 'lobstr',\n ALBEDO: 'albedo',\n} as const;\n\n/** A known wallet id, or any custom adapter id (autocomplete for the built-ins). */\nexport type WalletId = (typeof Wallets)[keyof typeof Wallets] | (string & {});\n"]}