{"version":3,"sources":["../src/types/common.ts","../src/types/passkey.ts","../src/services/utility-service.ts","../src/api/grid-api-client.ts","../src/utils/encoding.ts","../src/utils/crypto/solana-crypto.ts","../src/managers/authentication-manager.ts","../src/managers/signing-manager.ts","../src/utils/event-emitter.ts","../src/managers/account-manager.ts","../src/services/account-service.ts","../src/utils/validation.ts","../src/services/auth-service.ts","../src/services/transaction-service.ts","../src/services/passkey-service.ts","../src/utils/period-mapper.ts","../src/services/spending-limit-service.ts","../src/services/banking-service.ts","../src/core/grid-client.ts"],"names":["bs58","headers","Keypair","signature","PublicKey","VersionedTransaction"],"mappings":";;;;;;;;;AAoCO,IAAM,UAAA,GAAN,MAAM,UAAA,SAAkB,KAAA,CAAM;AAAA,EACnC,YACE,OAAA,EACgB,IAAA,EACA,UAAA,EACA,OAAA,EACA,WACA,YAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AANG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AACA,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AACA,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA;AACA,IAAA,IAAA,CAAA,YAAA,GAAA,YAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AAAA,EACd;AAAA;AAAA,EAGA,mBAAA,GAA8B;AAC5B,IAAA,IAAI,YAAY,IAAA,CAAK,OAAA;AAErB,IAAA,IAAI,IAAA,CAAK,OAAA,IAAW,KAAA,CAAM,OAAA,CAAQ,IAAA,CAAK,OAAO,CAAA,IAAK,IAAA,CAAK,OAAA,CAAQ,MAAA,GAAS,CAAA,EAAG;AAC1E,MAAA,MAAM,WAAA,GAAc,IAAA,CAAK,OAAA,CACtB,MAAA,CAAO,YAAU,MAAA,CAAO,UAAA,IAAc,MAAA,CAAO,UAAA,CAAW,MAAM,CAAA,CAC9D,GAAA,CAAI,CAAA,MAAA,KAAU,OAAO,UAAU,CAAA;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CACJ,MAAA,EACA,WAAA,EACuC;AACvC,IAAA,OAAO,MAAM,IAAA,CAAK,cAAA,CAAe,oBAAA,CAAqB,QAAQ,WAAW,CAAA;AAAA,EAC3E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBA,cAAA,GAA2C;AACzC,IAAA,OAAO,KAAK,SAAA,CAAU,WAAA;AAAA,EACxB;AACF,CAAA;AArkDuD,MAAA,CAAA,WAAA,EAAA,YAAA,CAAA;AAAhD,IAAM,UAAA,GAAN","file":"index.mjs","sourcesContent":["import { GridApiConfig, GridEnvironment } from '../api/grid-api-client';\nimport {  TransactionPayload, TransactionResult } from '../managers/signing-manager';\n\n\n\n/////////// Providers ///////////\n\n/** @hidden */\nexport interface ProviderConfig {\n  apiKey?: string;\n  apiUrl?: string;\n  timeout?: number;\n  retryAttempts?: number;\n  metadata?: Record<string, unknown>;\n  environment?: string; // Auto-injected from factory function\n}\n\n/** @hidden */\nexport type AuthProvider = 'turnkey' | 'passkey' | 'solana' | 'privy';\n\n\n/////////// Errors ///////////\n\n/** @hidden */\nexport interface ErrorDetail {\n  field?: string;\n  code: string;\n  message: string;\n  suggestion: string;\n  documentation: string;\n}\n\n/**\n * Base error class for SDK operations with consistent error structure\n * @hidden\n */\nexport class GridError extends Error {\n  constructor(\n    message: string,\n    public readonly code: string,\n    public readonly statusCode?: number,\n    public readonly details?: ErrorDetail[] | any,\n    public readonly timestamp?: string,\n    public readonly lastResponse?: any\n  ) {\n    super(message);\n    this.name = 'GridError';\n  }\n\n  /** Format error with suggestions and documentation */\n  getFormattedMessage(): string {\n    let formatted = this.message;\n\n    if (this.details && Array.isArray(this.details) && this.details.length > 0) {\n      const suggestions = this.details\n        .filter(detail => detail.suggestion && detail.suggestion.trim())\n        .map(detail => detail.suggestion);\n\n      if (suggestions.length > 0) {\n        formatted += `\\n\\nSuggestions:\\n${suggestions.map(s => `• ${s}`).join('\\n')}`;\n      }\n\n      const docs = this.details\n        .filter(detail => detail.documentation && detail.documentation.trim())\n        .map(detail => detail.documentation);\n\n      if (docs.length > 0) {\n        formatted += `\\n\\nDocumentation: ${docs[0]}`;\n      }\n    }\n\n    return formatted;\n  }\n\n  /** Format error for detailed console output */\n  toString(): string {\n    let output = `${this.name}: ${this.message}`;\n\n    if (this.lastResponse?.requestId) {\n      output += `\\n  Request ID: ${this.lastResponse.requestId}`;\n    }\n\n    if (this.timestamp) {\n      output += `\\n  Timestamp: ${this.timestamp}`;\n    }\n\n    if (this.code) {\n      output += `\\n  Error Code: ${this.code}`;\n    }\n\n    if (this.statusCode) {\n      output += `\\n  Status Code: ${this.statusCode}`;\n    }\n\n    if (this.details && Array.isArray(this.details) && this.details.length > 0) {\n      output += `\\n  Details:`;\n      this.details.forEach(detail => {\n        if (detail.field) {\n          output += `\\n    - Field: ${detail.field}`;\n        }\n        if (detail.message) {\n          output += `\\n      Message: ${detail.message}`;\n        }\n        if (detail.suggestion) {\n          output += `\\n      Suggestion: ${detail.suggestion}`;\n        }\n      });\n    }\n\n    return output;\n  }\n}\n\n/**\n * @hidden\n */\nexport class AuthorizationError extends GridError {\n  constructor(\n    message: string,\n    code: string,\n    public readonly provider?: AuthProvider,\n    public readonly cause?: Error,\n    details?: ErrorDetail[],\n    timestamp?: string,\n    requestId?: string\n  ) {\n    super(message, code, undefined, details, timestamp, { requestId, provider, cause });\n    this.name = 'AuthorizationError';\n  }\n\n  // Override toString to include provider info\n  toString(): string {\n    let output = super.toString();\n\n    if (this.provider) {\n      output += `\\n  Provider: ${this.provider}`;\n    }\n\n    if (this.cause) {\n      output += `\\n  Caused by: ${this.cause.message}`;\n    }\n\n    return output;\n  }\n}\n\n/**\n * @hidden\n */\nexport class ProviderError extends GridError {\n  constructor(\n    message: string,\n    public readonly provider: AuthProvider,\n    statusCode?: number,\n    public readonly cause?: Error,\n    details?: ErrorDetail[],\n    timestamp?: string,\n    requestId?: string\n  ) {\n    super(message, 'PROVIDER_ERROR', statusCode, details, timestamp, { requestId, provider, cause });\n    this.name = 'ProviderError';\n  }\n\n  // Override toString to include provider and cause info\n  toString(): string {\n    let output = super.toString();\n\n    if (this.provider) {\n      output += `\\n  Provider: ${this.provider}`;\n    }\n\n    if (this.cause) {\n      output += `\\n  Caused by: ${this.cause.message}`;\n    }\n\n    return output;\n  }\n}\n\n/////////// Key Management ///////////\n\n/** Key pair for cryptographic operations (publicKeyUncompressed required for Turnkey signing) */\nexport interface UniversalKeyPair {\n  publicKey: string;\n  privateKey: string;\n  publicKeyUncompressed?: string;\n}\n\n/** @hidden */\nexport type KeyPairTag = 'primary' | 'backup' | 'solana' | 'passkey';\n\n/** @hidden */\nexport interface TaggedKeyPair extends UniversalKeyPair {\n  provider: SignerProvider;\n  tag: KeyPairTag;\n}\n\n/** @hidden */\nexport type SessionSecrets = TaggedKeyPair[];\n\n/////////// Types / Enums ///////////\n\n/** @hidden */\nexport type Env = 'devnet' | 'mainnet' | 'testnet';\n\n\n/////////// Authentication ///////////\n\n// Init Auth Request\nexport interface InitAuthRequest {\n  email?: string;\n  expiration?: number;\n  smartAccountAddress?: string;\n}\n\n/** Authentication initialization data for MPC providers (Privy, Turnkey, etc.) */\nexport interface InitAuthData {\n  type: string;\n  email: string;\n  status: string;\n  /** Whether OTP was sent successfully */\n  otpSent: boolean;\n  otpId?: string;\n  /** MPC provider type */\n  provider: 'privy' | 'dynamic' | 'passkey' | 'turnkey' | 'external';\n  /** Creation timestamp (ISO string) */\n  createdAt: string;\n  /** Expiration timestamp (ISO string) */\n  expiresAt: string;\n}\n\n/** Authentication initialization data for EOA/Solana wallets */\nexport interface InitAuthEOAData {\n  authenticated: boolean;\n  /** Provider type (typically 'solana') */\n  provider: string;\n  /** Wallet public key */\n  publicKey: string;\n}\n\n/**\n * API response metadata for request tracking and debugging\n *\n * This provides metadata\n * about the API request for troubleshooting and support queries.\n *\n * @category API\n *\n * @remarks\n * Use this metadata to:\n * - Track requests by requestId when contacting support\n * - Verify successful requests via statusCode\n * - Implement retry logic based on idempotencyKey\n * - Debug issues by inspecting response headers\n *\n * @example Logging request details\n * ```typescript\n * const response = await gridClient.getAccount(address);\n *\n * console.log('Request ID:', response.lastResponse?.requestId);\n * console.log('Status:', response.lastResponse?.statusCode);\n * console.log('All headers:', response.lastResponse?.headers);\n * ```\n */\nexport interface LastResponse {\n  /**\n   * Unique identifier from x-request-id header\n   *\n   * Use this when contacting support to help identify the specific request.\n   */\n  requestId: string;\n\n  /**\n   * HTTP status code (200, 201, 400, etc.)\n   *\n   * Indicates the success status of the request.\n   */\n  statusCode: number;\n\n  /**\n   * Idempotency key from x-idempotency-key header\n   *\n   * Used to safely retry requests without duplicate effects.\n   * Only present if the request included an idempotency key.\n   */\n  idempotencyKey?: string;\n\n  /**\n   * All response headers as key-value pairs\n   *\n   * Contains all HTTP headers returned by the server.\n   */\n  headers: Record<string, string>;\n}\n\n/**\n * Base interface for all API responses with data and metadata\n *\n * All successful API responses follow this wrapper pattern for consistency and debugging.\n * Errors throw GridError instead of returning error objects.\n *\n * @template T - Type of response data\n * @category API\n *\n * @remarks\n * The BaseResponse wrapper provides:\n * - **data**: The actual response payload from the API\n * - **lastResponse**: Request metadata for debugging and tracking\n *\n * This pattern making it easy to:\n * - Access response data via the `data` property\n * - Track requests using `lastResponse.requestId` for support queries\n * - Debug issues with status codes and headers\n * - Implement idempotency using `lastResponse.idempotencyKey`\n *\n * Note: Errors are NOT returned in the response. Instead, they throw GridError with similar metadata.\n *\n * @example Accessing response data\n * ```typescript\n * const response = await gridClient.getAccount(accountAddress);\n *\n * console.log(response.data.address);\n * console.log(response.data.policies);\n * ```\n *\n * @example Accessing request metadata for debugging\n * ```typescript\n * const response = await gridClient.createAccount({ email: 'user@example.com' });\n *\n * console.log('Request ID:', response.lastResponse?.requestId);\n * console.log('Status:', response.lastResponse?.statusCode);\n * console.log('Idempotency Key:', response.lastResponse?.idempotencyKey);\n * ```\n *\n * @example Error handling\n * ```typescript\n * try {\n *   const response = await gridClient.getAccount(accountAddress);\n *   console.log('Success:', response.data);\n * } catch (error) {\n *   if (error instanceof GridError) {\n *     console.error('Error:', error.message);\n *     console.error('Request ID:', error.lastResponse?.requestId);\n *   }\n * }\n * ```\n */\nexport interface BaseResponse<T = any> {\n  /**\n   * Response data from API\n   *\n   * Contains the actual payload returned by the API endpoint.\n   * The type varies based on the specific response interface.\n   */\n  data: T;\n\n  /**\n   * Response metadata with request ID and status code\n   *\n   * Useful for debugging and tracking requests. Contains:\n   * - requestId: Unique identifier for this request\n   * - statusCode: HTTP status code (200, 201, etc.)\n   * - headers: All response headers\n   * - idempotencyKey: Key for idempotent requests (if applicable)\n   *\n   * @see LastResponse\n   */\n  lastResponse?: LastResponse;\n}\n\n/** Authentication initialization response (data varies by provider type) */\nexport interface InitAuthResponse extends BaseResponse<InitAuthData | InitAuthEOAData> {}\n\n/** @hidden */\nexport interface CompleteAuthRequest {\n  expiration?: number;\n}\n\n/** Complete authentication request with OTP verification */\nexport interface CompleteAuthRequestWithOtp extends CompleteAuthRequest {\n  /** OTP code received by user */\n  otpCode: string;\n  user: GridClientUserContext;\n  /** Session-specific cryptographic secrets */\n  sessionSecrets: SessionSecrets;\n  /** Optional smart account address to scope authentication to a specific account */\n  smartAccountAddress?: string;\n}\n\n// Complete Auth Response\nexport interface CompleteAuthResponse extends BaseResponse<{\n  address: string;\n  policies: AccountPolicies;\n  gridUserId: string;\n  authentication: AuthenticationData;\n}> {}\n\n// Complete Auth And Create Account Request\nexport interface CompleteAuthAndCreateAccountRequest {\n  otpCode: string;\n  otpId?: string;\n  provider?: 'privy' | 'turnkey';\n  user: GridClientUserContext;\n  sessionSecrets: SessionSecrets;\n}\n\n/** @hidden */\nexport interface SignRequest {\n  transaction: string;\n  sessionSecrets: SessionSecrets;\n  // session?: any; // Generic session type, can be PrivySessionData or other provider sessions\n}\n\n/** Transaction submission request */\nexport interface SendTransactionRequest {\n  /** Signed transaction payload */\n  signedTransactionPayload: TransactionResult;\n  /** Target address */\n  address: string;\n}\n\n\n// Grid-specific payment intent types\n/** @hidden */\nexport interface ConfirmPayload {\n  intentPayload: string;\n  mpcPayload: string;\n}\n\n/** Spending limit period */\nexport type SpendingLimitPeriod = 'one_time' | 'daily' | 'weekly' | 'monthly';\n\n/** Create spending limit request */\nexport interface SpendingLimitRequest {\n  /** Amount (min: 1) */\n  amount: string | number;\n  /** Token mint address */\n  mint: string;\n  /** Spending limit period */\n  period: SpendingLimitPeriod;\n  /** Signers required to approve transaction (account addresses) */\n  transactionSigners?: string[];\n  /** Signers authorized to use this limit (account addresses) */\n  spendingLimitSigners: string[];\n  /** Allowed destination addresses (optional) */\n  destinations?: string[];\n  /** Unix timestamp expiration (optional) */\n  expiration?: number;\n}\n\n\n/** Transaction submission response */\nexport interface TransactionSubmissionResponse extends BaseResponse<{\n  /** Transaction signature */\n  transactionSignature: string;\n  /** Confirmation timestamp */\n  confirmedAt: string;\n}> {}\n\n/** Passkey permission */\nexport type PasskeyPermission = string;\n\n/** Passkey information */\nexport interface PasskeyInfo {\n  address: string;\n  role: string;\n  permissions: PasskeyPermission[];\n  provider: string;\n  /** ISO timestamp when passkey was added */\n  addedAt: string;\n}\n\n/** Get passkeys response */\nexport interface GetPasskeysResponse extends BaseResponse<{\n  accountAddress: string;\n  passkey: PasskeyInfo | null;\n}> {}\n\n/** Input data for adding a passkey signer */\nexport interface PasskeyInput {\n  /** Passkey public key address */\n  address: string;\n  /** Signer role (defaults to 'primary') */\n  role?: string;\n  /** Permissions granted to passkey (defaults to all permissions) */\n  permissions?: PasskeyPermission[];\n}\n\n/** Request to add passkey signer to account */\nexport interface AddPasskeyRequest {\n  /** Passkey configuration */\n  passkey: PasskeyInput;\n  /** Required transaction signers (account addresses) */\n  transactionSigners?: string[];\n}\n\n/** Query parameters for adding passkey */\nexport interface AddPasskeyQueryParams {\n  /** Whether to add as admin signer (defaults to false) */\n  admin?: boolean;\n}\n\n/** Add passkey response */\nexport interface AddPasskeyResponse extends BaseResponse<{\n  transaction: string;\n  passkey: PasskeyInfo;\n  threshold: number;\n  status: string;\n  /** ISO timestamp when transaction expires */\n  expiresAt: string;\n}> {}\n\n/** Signer role in multi-signature account */\nexport type SignerRole = 'primary' | 'backup';\n\n/**\n * Signer permissions in multi-signature account\n * - CAN_INITIATE: Initiate transactions\n * - CAN_EXECUTE: Execute approved transactions\n * - CAN_VOTE: Vote on pending transactions\n */\nexport type SignerPermission = 'CAN_INITIATE' | 'CAN_EXECUTE' | 'CAN_VOTE';\n\n/**\n * Signer in multi-signature account\n *\n * Note: role defaults to 'primary', provider defaults to 'external'\n *\n * @example\n * ```typescript\n * const signer: AccountSigner = {\n *   address: '5FHwkrdxntdK24hgQU8qgBjn35Y1zwhz1GZwCkP2UJnM',\n *   permissions: ['CAN_INITIATE', 'CAN_EXECUTE', 'CAN_VOTE']\n * };\n * const backupSigner: AccountSigner = {\n *   address: '...',\n *   role: 'backup',\n *   permissions: ['CAN_VOTE'],\n *   provider: 'turnkey'\n * };\n * ```\n */\nexport interface AccountSigner {\n  /** Public key address */\n  address: string;\n  /** Role (defaults to 'primary') */\n  role?: SignerRole;\n  /** Permissions granted to signer */\n  permissions: SignerPermission[];\n  /** Authentication provider (defaults to 'external') */\n  provider?: string;\n}\n\n/**\n * Update account configuration (all fields optional)\n *\n * @example\n * ```typescript\n * const update: UpdateAccountRequest = {\n *   threshold: 2,\n *   transactionSigners: ['5FHwkrdxntdK24hgQU8qgBjn35Y1zwhz1GZwCkP2UJnM']\n * };\n * const withSigners: UpdateAccountRequest = {\n *   signers: [{\n *     address: 'newSignerPublicKey',\n *     role: 'backup',\n *     permissions: ['CAN_VOTE']\n *   }],\n *   threshold: 2\n * };\n * ```\n */\nexport interface UpdateAccountRequest {\n  /** Signers (replaces existing if provided) */\n  signers?: AccountSigner[];\n  /** Approval threshold (must not exceed signers.length, range: 1-10) */\n  threshold?: number;\n  /** Time lock in seconds (range: 1 to u32::MAX) */\n  timeLock?: number;\n  /** Admin address (pass null to remove) */\n  adminAddress?: string | null;\n  /** Signer addresses that must approve this update */\n  transactionSigners?: string[];\n}\n\n/**\n * Simplified account creation input (provide email or signer)\n *\n * @example\n * ```typescript\n * const emailAccount: CreateAccountInput = { email: 'user@example.com' };\n * const signerAccount: CreateAccountInput = { signer: 'publicKeyString' };\n * ```\n */\nexport interface CreateAccountInput {\n  /** Email for email-based account */\n  email?: string;\n  /** Public key for signer-based account */\n  signer?: string;\n}\n\n/**\n * Full account creation request (discriminated union)\n *\n * Note: For simple creation, use {@link CreateAccountInput}. This type is for advanced use cases with full policy control.\n *\n * @see {@link EmailAccountRequest} for email accounts\n * @see {@link SignersAccountRequest} for signer accounts\n * @see {@link AccountPolicies} for direct policy configuration\n */\nexport type CreateAccountRequest = EmailAccountRequest | SignersAccountRequest | AccountPolicies;\n\n/** Email-based account creation request */\nexport interface EmailAccountRequest {\n  type: 'email';\n  email: string;\n}\n\n/** Signer-based account creation request with full policy control */\nexport interface SignersAccountRequest {\n  type: 'signers';\n  /** Account policies (signers, threshold, restrictions) */\n  policies: AccountPolicies;\n  memo?: string;\n}\n\n/**\n * Multi-signature account policies\n *\n * Important: Signers range: 1-10, threshold must not exceed signers.length (range: 1-10)\n */\nexport interface AccountPolicies {\n  /** Account signers (range: 1-10) */\n  signers: AccountSigner[];\n  /** Required signatures (must not exceed signers.length) */\n  threshold: number;\n  /** Time lock in seconds (range: 1 to u32::MAX) */\n  timeLock?: number | null;\n  /** Admin address for administrative functions */\n  adminAddress?: string | null;\n}\n\n/**\n * @deprecated Use {@link EmailAccountRequest} instead\n */\nexport interface EmailPayload {\n  email: string;\n}\n\n/**\n * @deprecated Use {@link SignersAccountRequest} instead\n */\nexport interface SignersPayload {\n  policies: AccountPolicies;\n}\n\n/**\n * Email account creation response\n *\n * Note: Requires authentication via initAuth and completeAuth before use\n * @hidden\n */\nexport interface EmailAccountResponse extends BaseResponse<{\n  type: 'email';\n  email: string;\n  status: string;\n  otpSent: boolean;\n  createdAt: string;\n  expiresAt: string;\n  memo?: string;\n  address?: string;\n  policies?: AccountPolicies;\n  gridUserId?: string;\n}> {}\n\n/**\n * Signer account creation response (immediately active)\n * @hidden\n */\nexport interface SignersAccountResponse extends BaseResponse<{\n  type: 'signers';\n  address: string;\n  policies: AccountPolicies;\n  gridUserId: string;\n  /** Optional memo for the account */\n  memo?: string;\n  /** Email address (only present for email accounts) */\n  email?: string;\n  /** Current status (only present for email accounts) */\n  status?: string;\n  /** Whether an OTP code was sent (only present for email accounts) */\n  otpSent?: boolean;\n  /** ISO timestamp when created (only present for email accounts) */\n  createdAt?: string;\n  /** ISO timestamp when expires (only present for email accounts) */\n  expiresAt?: string;\n}> {}\n\n/**\n * Account creation response (union type)\n *\n * @see {@link EmailAccountResponse} for email accounts\n * @see {@link SignersAccountResponse} for signer accounts\n */\nexport type CreateAccountResponse = EmailAccountResponse | SignersAccountResponse;\n\n/** Get account response */\nexport interface GetAccountResponse extends BaseResponse<{\n    type: 'signers' | 'email';\n    address: string;\n    /** Policies (optional for email accounts) */\n    policies?: AccountPolicies;\n    gridUserId: string;\n    memo?: string;\n    createdAt?: string;\n    /** Status (for email accounts) */\n    status?: string;\n}> {}\n\n/** Transaction in account history */\nexport interface AccountTransaction {\n  id: string;\n  /** Transaction signature hash */\n  signature: string;\n  status: string;\n  /** ISO timestamp when created */\n  createdAt: string;\n  /** ISO timestamp when confirmed */\n  confirmedAt?: string;\n}\n\n/** Get transactions response */\nexport interface GetTransactionsResponse extends BaseResponse<{\n  transactions?: AccountTransaction[];\n  error?: string;\n}> {}\n\n// Get Account Balances types\n/** @hidden */\nexport interface TokenBalance {\n  tokenAddress: string;\n  amount: bigint;\n  decimals: number;\n  amountDecimal: string;\n  symbol?: string;\n  name?: string;\n  logo?: string;\n}\n\n/** Query parameters for paginated balance requests */\nexport interface GetAccountBalancesQueryParams {\n  /** Results per page (default: 10) */\n  limit?: number;\n  /** Page number (default: 1) */\n  page?: number;\n}\n\n/** Account balances data with SOL and token balances */\nexport interface AccountBalancesData {\n  address: string;\n  lamports: bigint;\n  sol: number;\n  tokens: TokenBalance[];\n}\n\nexport interface AccountBalancesResponse extends BaseResponse<AccountBalancesData> {\n  data: AccountBalancesData;\n}\n\n\n/** Payment details for transfers */\nexport interface PaymentDetails {\n  /** Account (for source) */\n  account?: string;\n  /** Address (for crypto destination) */\n  address?: string;\n  currency: string;\n  /** Payment rail (for fiat destination, e.g., \"ach_push\") */\n  paymentRail?: string;\n  /** External account ID (for fiat destination) */\n  externalAccountId?: string;\n}\n\n/** Create payment intent request */\nexport interface CreatePaymentIntentRequest {\n  /** Transfer amount as a string (e.g., \"100.00\") */\n  amount: string;\n  /** Source account details */\n  source: PaymentDetails;\n  /** Destination account details */\n  destination: PaymentDetails;\n  /** Fee configuration. Required for non-Enterprise customers. Enterprise customers may omit this as fees are handled by their plan. */\n  feeConfig?: FeeConfig;\n}\n\n// Raw API response from server (matches Rust struct)\n/** @hidden */\nexport type CreatePaymentIntentApiResponse = any;\n\n// Client response (follows standard data pattern)\nexport interface CreatePaymentIntentResponse extends BaseResponse<{\n  transactionPayload?: TransactionPayload;\n  error?: string;\n} & Omit<CreatePaymentIntentApiResponse, 'kms_payloads' | 'transaction_signers' | 'transaction'>> {}\n\n/** KMS payload for transaction signing */\nexport interface KmsPayload {\n  /** KMS provider name (e.g., 'turnkey', 'privy') */\n  provider: string;\n  /** Signer's public key address */\n  address: string;\n  /** Encrypted signing payload */\n  payload: string;\n}\n\n/** Update spending limit request */\nexport interface UpdateSpendingLimitRequest {\n  /** Amount (min: 1) */\n  amount?: string | number;\n  mint?: string;\n  period?: SpendingLimitPeriod;\n  spendingLimitSigners?: string[];\n  destinations?: string[];\n  expiration?: number;\n  transactionSigners?: string[];\n}\n\n/** Use spending limit request (consume from existing limit) */\nexport interface UseSpendingLimitRequest {\n  /** Amount to use from limit (min: 1) */\n  amount: string | number;\n  /** Signer address authorized to use limit */\n  signerAddress: string;\n  /** Recipient address for transfer */\n  recipientAddress: string;\n}\n\n/** Create spending limit response */\nexport interface CreateSpendingLimitResponse extends BaseResponse<{\n  /** On-chain spending limit address */\n  spendingLimitAddress: string;\n  /** Serialized transaction for signing */\n  transaction: string;\n  /** KMS payloads for multi-party signing */\n  kmsPayloads: KmsPayload[];\n  transactionSigners: string[];\n}> {}\n\n/** Spending limit transaction response (for update/delete operations) */\nexport interface SpendingLimitTransactionResponse extends BaseResponse<{\n  /** Serialized transaction for signing */\n  transaction: string;\n  transactionSigners: string[];\n  /** KMS payloads for multi-party signing */\n  kmsPayloads: KmsPayload[];\n}> {}\n\n/** Spending limit data with configuration, usage, and metadata */\nexport interface SpendingLimit {\n  /** On-chain spending limit address */\n  address: string;\n  /** Settings account address */\n  settingsAddress: string;\n  /** Main smart account address */\n  mainAccountAddress: string;\n  /** Environment (sandbox or production) */\n  environment: string;\n  /** Token mint address */\n  mint: string;\n  /** Maximum amount per period */\n  amount: number;\n  /** Period type (0=one_time, 1=daily, 2=weekly, 3=monthly) */\n  period: number;\n  /** Remaining amount in current period */\n  remainingAmount: number;\n  status: string;\n  /** Unix timestamp of last reset */\n  lastReset: number;\n  /** Authorized signer addresses */\n  signers: string[];\n  /** Allowed destination addresses */\n  destinations: string[];\n  /** Unix timestamp of expiration (0 for no expiration) */\n  expiration: number;\n  /** Solana slot of last modification */\n  slot: number;\n  /** Block timestamp of last modification */\n  blockTime: string;\n  /** Last modification transaction signature */\n  lastModifiedSignature: string;\n}\n\n/** Get spending limit response */\nexport interface SpendingLimitResponse extends BaseResponse<SpendingLimit> {}\n\n/** Get spending limits response */\nexport interface SpendingLimitsResponse extends BaseResponse<SpendingLimit[]> {}\n\n/** KYC verification type */\nexport type KycType = 'individual' | 'business';\n\n/** KYC endorsement */\nexport type KycEndorsement = 'ach' | 'sepa';\n\n/** Request KYC link */\nexport interface RequestKycLinkRequest {\n  type: KycType;\n  email: string;\n  fullName: string;\n  endorsements?: KycEndorsement[];\n  redirectUri?: string;\n}\n\nexport interface KycLinkResponse extends BaseResponse<KycLink> {\n  data: KycLink;\n}\n\n/** KYC verification link data */\nexport interface KycLink {\n  id: string;\n  fullName: string;\n  email: string;\n  type: KycType;\n  /** URL for KYC identity verification */\n  kycLink: string;\n  /** URL for terms of service acceptance */\n  tosLink: string;\n  kycStatus: KycStatus;\n  /** Rejection reasons if KYC was rejected */\n  rejectionReasons: string[];\n  tosStatus: TosStatus;\n  /** ISO timestamp of creation */\n  createdAt: string;\n  /** External customer ID in KYC provider system */\n  customerId: string;\n  /** Persona inquiry type */\n  personaInquiryType: string;\n}\n\n\n// Get KYC Status types\n/** @hidden */\nexport type KycStatus = 'pending' | 'approved' | 'rejected' | 'under_review';\n/** @hidden */\nexport type TosStatus = 'pending' | 'approved' | 'rejected';\n\n/** @hidden */\nexport interface RejectionReason {\n  code: string;\n  message: string;\n}\n\nexport interface KycStatusResponse extends BaseResponse<KycStatusData> {\n  data: KycStatusData;\n}\n\n/** KYC verification status data */\nexport interface KycStatusData {\n  id: string;\n  account: string;\n  type: KycType;\n  status: KycStatus;\n  tosStatus: TosStatus;\n  /** Link to continue KYC if incomplete */\n  kycContinuationLink?: string;\n  /** Rejection reasons if rejected */\n  rejectionReasons: RejectionReason[];\n  /** Outstanding requirements to complete verification */\n  requirementsDue: string[];\n  /** ISO timestamp of creation */\n  createdAt: string;\n  /** ISO timestamp of last update */\n  updatedAt: string;\n}\n\n/** Currency type */\nexport type Currency = 'sol' | 'usdc' | 'usdt' | 'pyusd' | 'eurc';\n\n/** Fee configuration. Required for non-Enterprise customers when creating payment intents or preparing transactions. */\nexport interface FeeConfig {\n  /** Currency used to pay fees */\n  currency: Currency;\n  /** Public key address of the account paying fees */\n  payerAddress: string;\n  /** When true, fees are deducted from the payer account rather than being handled by Grid */\n  selfManagedFees?: boolean;\n}\n\n/** Prepare arbitrary transaction request */\nexport interface PrepareArbitraryTransactionRequest {\n  transaction: string;\n  /** @deprecated Use accountSigners instead */\n  transactionSigners?: string[];\n  accountSigners?: string[];\n  /** @deprecated Use feeConfig instead */\n  payerAddress?: string;\n  feeConfig?: FeeConfig;\n}\n\n/** Create proposal request */\nexport interface CreateProposalRequest {\n  transaction: string;\n  signer: string;\n  rentPayer?: string;\n}\n\n/** Create proposal response */\nexport interface CreateProposalResponse extends BaseResponse<{\n  transactions: string[];\n  signer: string;\n  rentPayer?: string;\n}> {}\n\n/** Vote action types for proposals */\nexport type VoteAction = 'approve' | 'reject' | 'cancel';\n\n/** Vote on proposal request */\nexport interface VoteProposalRequest {\n  /** Array of signer addresses that will vote (must have CAN_VOTE permission) */\n  signers: string[];\n  /** Vote action to perform */\n  action: VoteAction;\n}\n\n/** Vote on proposal response */\nexport interface VoteProposalResponse extends BaseResponse<{\n  /** Base64-encoded unsigned transaction */\n  transaction: string;\n  /** Signers that need to sign the transaction */\n  transactionSigners: string[];\n}> {}\n\n/** Execute proposal request */\nexport interface ExecuteProposalRequest {\n  /** Signer address that will execute (must have CAN_EXECUTE permission) */\n  signer: string;\n}\n\n/** Execute proposal response */\nexport interface ExecuteProposalResponse extends BaseResponse<{\n  /** Base64-encoded unsigned transactions */\n  transactions: string[];\n  signer: string;\n}> {}\n\n/** Query parameters for preparing arbitrary transactions */\nexport interface PrepareArbitraryTransactionQueryParams {\n  /** Enable debug mode (default: false) */\n  debug?: boolean;\n}\n\n// ============= Smart Transaction Types =============\n\n/**\n * Period types for spending limits and policies\n */\nexport type Period = 'OneTime' | 'Daily' | 'Weekly' | 'Monthly';\n\n/**\n * Policy expiration arguments\n */\nexport interface PolicyExpirationArgs {\n  /** Number of periods until expiration (e.g., 2 for \"2 weeks\" if period is Weekly) */\n  numPeriods: number;\n  /** Period type for expiration calculation */\n  period: Period;\n}\n\n/**\n * Signer permission types for policy signers\n */\nexport type PolicyPermission = 'CAN_INITIATE' | 'CAN_VOTE' | 'CAN_EXECUTE';\n\n/**\n * Policy signer configuration\n */\nexport interface PolicySigner {\n  /** Public key address of the signer */\n  address: string;\n  /** Permissions granted to this signer */\n  permissions: PolicyPermission[];\n}\n\n/**\n * Spending limit configuration for trade policies\n */\nexport interface SpendingLimitPolicy {\n  /** Maximum amount that can be spent (as string to handle large numbers) */\n  amount: string;\n  /** Token mint address */\n  mint: string;\n  /** Period type for the spending limit */\n  period: SpendingLimitPeriod;\n  /** Optional start timestamp (Unix timestamp) */\n  startTimestamp?: number;\n  /** Optional expiration timestamp (Unix timestamp) */\n  expirationTimestamp?: number;\n}\n\n/**\n * Trade instruction union type\n *\n * Currently supports Jupiter V6 swaps, extensible for other programs\n *\n * NOTE: The Rust API uses #[serde(flatten)] so instruction and args are at the same level as program,\n * not nested in a payload object.\n */\nexport type TradeInstruction = {\n  /** Program identifier */\n  program: 'jup-v6';\n  /** Instruction name (e.g., \"route_v2\", \"exact_out_route_v2\") */\n  instruction: string;\n  /** Instruction arguments as JSON - must match IDL arg names 1:1 */\n  args: Record<string, any>;\n};\n\n/**\n * Trade policies configuration\n */\nexport interface TradePolicies {\n  /** Array of signers authorized for this policy (minimum 1 required) */\n  signers: PolicySigner[];\n  /** Number of signatures required for approval (minimum 1, must not exceed signers.length) */\n  threshold: number;\n  /** Array of spending limits (minimum 1 required) */\n  spendingLimits: SpendingLimitPolicy[];\n  /** Optional start timestamp for the policy */\n  startTimestamp?: number;\n  /** Optional expiration arguments */\n  expirationArgs?: PolicyExpirationArgs;\n}\n\n/**\n * Request to prepare a trading automation transaction\n *\n * This endpoint prepares transactions with policy validation for automated trading.\n */\nexport interface PrepareTradingAutomationRequest {\n  /** Base64-encoded Solana transaction */\n  transaction: string;\n  /** Array of transaction signer public keys (optional, defaults to empty) */\n  transactionSigners?: string[];\n  /** Optional payer address for transaction fees */\n  payerAddress?: string;\n  /** Optional fee configuration */\n  feeConfig?: FeeConfig;\n}\n\n/**\n * Query parameters for prepare trading automation endpoint\n */\nexport interface PrepareTradingAutomationQueryParams {\n  /** Include simulation logs in response (defaults to false) */\n  debug?: boolean;\n}\n\n/**\n * Response from preparing a trading automation transaction\n */\nexport interface PrepareTradingAutomationResponse extends BaseResponse<{\n  /** Prepared transaction as base64 string */\n  transaction: string;\n  /** KMS payloads for signing */\n  kmsPayloads: KmsPayload[];\n  /** Optional simulation logs if debug=true */\n  simulationLogs?: string[];\n  /** Transaction signer addresses */\n  transactionSigners: string[];\n  /** Optional fee information */\n  fee?: {\n    amount: number;\n    currency: string;\n    breakdown: {\n      computeFee: number;\n      rentFee: number;\n    };\n  };\n}> {}\n\n// ============= Trade Smart Transaction Types =============\n\n/**\n * Trading venue/platform for quote retrieval and execution\n */\nexport type TradeVenue = 'jupiter';\n\n/**\n * Input token allowance configuration for trade policies\n */\nexport interface InputAllowance {\n  /** Maximum amount that can be spent in smallest units */\n  amount: string | number;\n  /** Period type for the allowance (OneTime, Daily, Weekly, Monthly) */\n  cadence: Period;\n}\n\n/**\n * Input token with optional spending allowance\n */\nexport interface InputWithAllowance {\n  /** Token mint address */\n  mint: string;\n  /** Optional spending allowance for this input token */\n  allowance?: InputAllowance;\n}\n\n/**\n * Trade rules configuration for smart transaction policies\n */\nexport interface TradeRules {\n  /** Allowed input tokens with optional spending allowances (minimum 1 required) */\n  allowedInputs: InputWithAllowance[];\n  /** Allowed output token mint addresses (can be empty for any output) */\n  allowedOutputs: string[];\n  /** Maximum slippage in basis points (e.g., 100 = 1%, default 0) */\n  maxSlippageBps: number;\n  /** Optional platform fees in basis points (e.g., 10 = 0.1%) */\n  feesBps?: number;\n  /** Optional trading venue selection (defaults to Jupiter) */\n  venue?: TradeVenue;\n}\n\n/**\n * Account policies for smart transactions\n *\n * Note: This is similar to TradePolicies but without spending limits,\n * as those are now part of TradeRules\n */\nexport interface AccountPoliciesSmartTransaction {\n  /** Array of signers authorized for this policy (minimum 1 required) */\n  signers: PolicySigner[];\n  /** Number of signatures required for approval (minimum 1, must not exceed signers.length) */\n  threshold: number;\n  /** Optional start timestamp for the policy */\n  startTimestamp?: number;\n  /** Optional expiration arguments */\n  expirationArgs?: PolicyExpirationArgs;\n}\n\n/**\n * Request to create a trade smart transaction policy\n *\n * @example\n * ```typescript\n * const request = {\n *   policies: {\n *     signers: [{\n *       address: '3ciascNndLTBrDQXvs8nzZgWAiaL33tGM6fx3zzM7Fxt',\n *       permissions: ['CAN_INITIATE', 'CAN_VOTE', 'CAN_EXECUTE']\n *     }],\n *     threshold: 1\n *   },\n *   rules: {\n *     allowedInputs: [{\n *       mint: 'So11111111111111111111111111111111111111112',\n *       allowance: {\n *         amount: '1000000000',\n *         cadence: 'Daily'\n *       }\n *     }],\n *     allowedOutputs: ['EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'],\n *     maxSlippageBps: 100,\n *     feesBps: 10\n *   }\n * };\n * const response = await client.createTradeSmartTransaction(accountAddress, request);\n * console.log(response.data.smartTransactionAddress);\n * ```\n */\nexport interface CreateTradeSmartTransactionRequest {\n  /** Account policies for signers and threshold */\n  policies: AccountPoliciesSmartTransaction;\n  /** Trade rules defining allowed inputs, outputs, and constraints */\n  rules: TradeRules;\n  /** Optional transaction signers for creating the policy */\n  transactionSigners?: string[];\n}\n\n/** Data returned from creating a trade smart transaction */\nexport interface CreateTradeSmartTransactionData {\n  /** The policy address (smart transaction address) */\n  smartTransactionAddress: string;\n  /** Prepared transaction as base64 string */\n  transaction: string;\n  /** KMS payloads for signing */\n  kmsPayloads: KmsPayload[];\n  /** Transaction signer addresses */\n  transactionSigners: string[];\n}\n\n/**\n * Response from creating a trade smart transaction\n */\nexport interface CreateTradeSmartTransactionResponse extends BaseResponse<CreateTradeSmartTransactionData> {}\n\n/**\n * Request to get a standalone trade quote (no policy required)\n *\n * @example\n * ```typescript\n * const request = {\n *   venue: 'jupiter',\n *   fromMint: 'So11111111111111111111111111111111111111112',\n *   toMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',\n *   amount: 1000000000,\n *   slippageBps: 50\n * };\n * const response = await client.getTradeQuote(request);\n * console.log(response.data.quote);\n * ```\n */\nexport interface GetTradeQuoteRequest {\n  /** Trading venue to get quote from */\n  venue: TradeVenue;\n  /** Input token mint address */\n  fromMint: string;\n  /** Output token mint address */\n  toMint: string;\n  /** Amount of input token in smallest units (e.g., lamports for SOL) */\n  amount: number | string;\n  /** Maximum slippage tolerance in basis points (e.g., 50 = 0.5%) */\n  slippageBps: number;\n}\n\n/** Data returned from trade quote request */\nexport interface GetTradeQuoteData {\n  /** The trading venue that provided this quote */\n  venue: TradeVenue;\n  /** The raw quote response from the venue */\n  quote: any;\n}\n\n/**\n * Response from getting a trade quote\n */\nexport interface GetTradeQuoteResponse extends BaseResponse<GetTradeQuoteData> {}\n\n/**\n * Request to get a policy-aware trade quote\n *\n * @example\n * ```typescript\n * const request = {\n *   venue: 'jupiter',\n *   fromMint: 'So11111111111111111111111111111111111111112',\n *   toMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',\n *   amount: 1000000000,\n *   slippageBps: 50\n * };\n * const response = await client.getSmartTransactionQuote(\n *   accountAddress,\n *   smartTransactionAddress,\n *   request\n * );\n * console.log(response.data.quote);\n * ```\n */\nexport interface TradeSmartTransactionQuoteRequest {\n  /** Trading venue to get quote from */\n  venue: TradeVenue;\n  /** Input token mint address */\n  fromMint: string;\n  /** Output token mint address */\n  toMint: string;\n  /** Amount of input token in smallest units */\n  amount: number | string;\n  /** Maximum slippage tolerance in basis points */\n  slippageBps: number;\n}\n\n/** Data returned from smart transaction quote */\nexport interface TradeSmartTransactionQuoteData {\n  /** The trading venue that provided this quote */\n  venue: TradeVenue;\n  /** The raw quote response from the venue */\n  quote: any;\n}\n\n/**\n * Response from getting a smart transaction quote\n */\nexport interface TradeSmartTransactionQuoteResponse extends BaseResponse<TradeSmartTransactionQuoteData> {}\n\n/**\n * Trade details for preparing a trade transaction\n */\nexport interface TradeDetails {\n  /** Input token mint address */\n  input: string;\n  /** Output token mint address */\n  output: string;\n  /** Amount in smallest units */\n  amount: number | string;\n  /** Slippage tolerance in basis points */\n  slippageBps: number;\n  /** Fee in basis points */\n  feeBps: number;\n}\n\n/**\n * Quote wrapper for preparing a trade transaction\n */\nexport interface TradeQuote {\n  /** Raw quote object from quote endpoint */\n  quote: any;\n}\n\n/**\n * Trade arguments union type\n *\n * Either provide trade details OR a pre-fetched quote\n */\nexport type TradeArgs =\n  | ({ type: 'arguments' } & TradeDetails)\n  | { type: 'quote'; quote: any };\n\n/**\n * Request to prepare a trade smart transaction\n *\n * @example Using trade details:\n * ```typescript\n * const request = {\n *   tradeArgs: {\n *     type: 'arguments',\n *     input: 'So11111111111111111111111111111111111111112',\n *     output: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',\n *     amount: 1000000000,\n *     slippageBps: 50,\n *     feeBps: 10\n *   },\n *   transactionSigners: ['signer-pubkey']\n * };\n * const response = await client.prepareTradeSmartTransaction(\n *   accountAddress,\n *   smartTransactionAddress,\n *   request,\n *   { debug: true }\n * );\n * ```\n *\n * @example Using pre-fetched quote:\n * ```typescript\n * const quoteResponse = await client.getSmartTransactionQuote(...);\n * const request = {\n *   tradeArgs: {\n *     type: 'quote',\n *     quote: quoteResponse.data.quote\n *   }\n * };\n * const response = await client.prepareTradeSmartTransaction(...);\n * ```\n */\nexport interface PrepareTradeSmartTransactionRequest {\n  /** Trade arguments (either details or quote) */\n  tradeArgs: TradeArgs;\n  /** Optional transaction signers */\n  transactionSigners?: string[];\n  /** Optional payer address for transaction fees */\n  payerAddress?: string;\n  /** Optional fee configuration */\n  feeConfig?: FeeConfig;\n}\n\n/**\n * Query parameters for prepare trade smart transaction\n */\nexport interface PrepareTradeSmartTransactionQueryParams {\n  /** Include simulation logs in response (defaults to false) */\n  debug?: boolean;\n}\n\n/** Data returned from preparing a trade smart transaction */\nexport interface PrepareTradeSmartTransactionData {\n  /** Prepared transaction as base64 string */\n  transaction: string;\n  /** KMS payloads for signing */\n  kmsPayloads: KmsPayload[];\n  /** Optional simulation logs if debug=true */\n  simulationLogs?: string[];\n  /** Transaction signer addresses */\n  transactionSigners: string[];\n  /** Optional fee information */\n  fee?: {\n    amount: number;\n    currency: string;\n    breakdown: {\n      computeFee: number;\n      rentFee: number;\n    };\n  };\n}\n\n/**\n * Response from preparing a trade smart transaction\n */\nexport interface PrepareTradeSmartTransactionResponse extends BaseResponse<PrepareTradeSmartTransactionData> {}\n\n/**\n * Allowed input token configuration from a trade policy\n */\nexport interface AllowedInput {\n  /** Token mint address */\n  mint: string;\n  /** Allowance information if set */\n  allowance?: {\n    /** Amount allowed */\n    amount: string;\n    /** Cadence/period */\n    cadence: Period;\n    /** Remaining amount available */\n    remaining: string;\n  };\n}\n\n/**\n * Tradable assets configuration from a trade policy\n */\nexport interface TradableAssets {\n  /** Array of allowed input tokens with allowance info */\n  allowedInputs: AllowedInput[];\n  /** Array of allowed output token mint addresses */\n  allowedOutputs: string[];\n}\n\n/**\n * Policy status enum\n */\nexport type PolicyStatus = 'active' | 'expired' | 'cancelled';\n\n/** Data returned from getting a trade smart transaction */\nexport interface GetTradeSmartTransactionData {\n  /** Policy address */\n  policyAddress: string;\n  /** Authorized signers as JSON */\n  signers: any;\n  /** Required number of signatures */\n  threshold: number;\n  /** Tradable assets configuration */\n  tradableAssets: TradableAssets;\n  /** Optional maximum slippage in basis points */\n  maxSlippageBps?: number;\n  /** Policy status */\n  status: PolicyStatus;\n}\n\n/**\n * Response from getting a trade smart transaction\n *\n * @example\n * ```typescript\n * const response = await client.getTradeSmartTransaction(\n *   accountAddress,\n *   smartTransactionAddress\n * );\n * console.log(response.data.tradableAssets);\n * console.log(response.data.status);\n * ```\n */\nexport interface GetTradeSmartTransactionResponse extends BaseResponse<GetTradeSmartTransactionData> {}\n\n/**\n * Remove Passkey Request\n */\nexport interface RemovePasskeyRequest {\n  transactionSigners?: string[]; // Option<Vec<Pubkey>> mapped to string array\n}\n\n/**\n * Remove Passkey Query Params\n */\nexport interface RemovePasskeyQueryParams {\n  admin?: boolean;              // Optional admin flag with default false\n}\n\n/**\n * Remove Passkey Response\n */\nexport interface RemovePasskeyResponse extends BaseResponse<{\n  transaction: string;\n  removedPasskey: PasskeyInfo; // Reuse existing PasskeyInfo type\n  threshold: number;            // u8 mapped to number\n  status: string;\n  expiresAt: string;           // DateTime<Utc> mapped to ISO string\n}> {}\n\n// Transfer State types\nexport type TransferState = \n  | 'awaiting_funds'\n  | 'in_review' \n  | 'funds_received'\n  | 'payment_submitted'\n  | 'payment_processed'\n  | 'canceled'\n  | 'error'\n  | 'undeliverable'\n  | 'returned'\n  | 'refunded';\n\n// Comprehensive Transfer types for get_transfers endpoint\nexport type ConfirmationStatus = 'pending' | 'confirmed';\nexport type TransferDirection = 'inflow' | 'outflow';\n\n// Receipt types\nexport interface Receipt {\n  id: string;\n  object: string;\n  createdAt: string; // ISO string from DateTime<Utc>\n}\n\n// Bridge Transfer types\nexport interface BridgeTransferSource {\n  paymentRail: PaymentRail;\n  currency: BridgeCurrency;\n  externalAccountId?: string;\n  bridgeWalletId?: string;\n  fromAddress?: string;\n  omad?: string;\n  imad?: string;\n  bankBeneficiaryName?: string;\n}\n\n// Bridge Transfer Destination\nexport interface BridgeTransferDestination {\n  currency: BridgeCurrency;\n  paymentRail: PaymentRail;\n  externalAccountId?: string;\n  bridgeWalletId?: string;\n  fromAddress?: string;\n  wireMessage?: string;\n  sepaReference?: string;\n  swiftReference?: string;\n}\n\n// Bridge Transfer Source Deposit Instructions\nexport interface BridgeTransferSourceDepositInstructions {\n  amount?: string; // Decimal from Rust\n  currency: BridgeCurrency;\n  depositMessage?: string;\n  paymentRail: PaymentRail;\n  fromAddress?: string;\n  toAddress?: string;\n  bankName?: string;\n  bankAddress?: string;\n  bankCity?: string;\n  bankCountry?: string;\n  bankPostalCode?: string;\n  iban?: string;\n  swiftBic?: string;\n  beneficiaryName?: string;\n  beneficiaryAddress?: string;\n  beneficiaryCity?: string;\n  beneficiaryCountry?: string;\n  beneficiaryPostalCode?: string;\n  routingNumber?: string;\n  accountNumber?: string;\n  accountType?: string;\n}\n\n/**\n * Bridge transfer data for fiat-to-crypto or crypto-to-fiat transfers\n *\n * Represents transfers processed through Bridge's payment rails, including\n * ACH, SEPA, wire transfers, and other traditional banking methods.\n */\nexport interface BridgeTransfer {\n  id: string;\n  state: TransferState;\n  onBehalfOf: string;\n  sourceDepositInstructions?: BridgeTransferSourceDepositInstructions;\n  amount: string; // Decimal from Rust\n  clientReferenceId?: string;\n  currency?: BridgeCurrency;\n  developerFee: string; // Decimal from Rust\n  source: BridgeTransferSource;\n  destination: BridgeTransferDestination;\n  receipt: Receipt;\n  blockchainMemo?: string;\n  createdAt: string; // ISO string from DateTime<Utc>\n  updatedAt: string; // ISO string from DateTime<Utc>\n}\n\n/** SPL token transfer data for on-chain Solana transfers (supports SPL Token and Token-2022) */\nexport interface SplTransfer {\n  id: string;\n  gridUserId: string;\n  mainAccountAddress: string;\n  mint: string;\n  isToken2022: boolean;\n  signature: string;\n  confirmationStatus: ConfirmationStatus;\n  fromAddress: string;\n  toAddress: string;\n  amount: string;\n  uiAmount: string;\n  decimals: number;\n  confirmedAt?: string;\n  createdAt: string;\n  updatedAt: string;\n  direction?: TransferDirection;\n  environment?: GridEnvironment;\n  instructionIndex?: number;\n}\n\n/**\n * Get transfers response\n *\n * @see {@link BridgeTransfer} for fiat-to-crypto transfers\n * @see {@link SplTransfer} for on-chain transfers\n */\nexport interface TransferResponse extends BaseResponse<(BridgeTransfer | SplTransfer)[]> {\n  data: (BridgeTransfer | SplTransfer)[];\n  /** Next page cursor */\n  nextCursor?: string;\n  /** More results available */\n  hasMore?: boolean;\n}\n\n// Options for get_transfers endpoint\nexport interface GetTransfersOptions {\n  paymentRail?: PaymentRail; // renamed from 'type' to avoid TypeScript keyword\n  status?: TransferState;\n  currency?: BridgeCurrency;\n  startDate?: string;\n  endDate?: string;\n  txHash?: string;\n  limit?: number;\n  cursor?: string;\n}\n\n\n// Currency types\nexport type BridgeCurrency = 'usd' | 'eur';\n\n/** Request virtual account */\nexport interface RequestVirtualAccountRequest {\n  currency: BridgeCurrency;\n}\n\n/** @hidden */\nexport interface SourceDepositInstructions {\n  currency: string;\n  bankBeneficiaryName: string;\n  bankName: string;\n  bankAddress: string;\n  bankRoutingNumber: string;\n  bankAccountNumber: string;\n  paymentRails: string[];\n}\n\n/** @hidden */\nexport interface VirtualAccountDestination {\n  currency: string;\n  paymentRail: string;\n  address: string;\n}\n\nexport interface VirtualAccount {\n  id: string;\n  customerId: string;\n  sourceDepositInstructions: SourceDepositInstructions;\n  destination: VirtualAccountDestination;\n  status: string;\n  developerFeePercent: string;\n}\n\n// Virtual Account types\nexport interface VirtualAccountResponse extends BaseResponse<VirtualAccount> {}\nexport interface VirtualAccountsResponse extends BaseResponse<VirtualAccount[]> {}\n\n/** Get virtual accounts query params */\nexport interface GetVirtualAccountsQueryParams {\n  sourceCurrency?: BridgeCurrency;\n  destinationCurrency?: BridgeCurrency;\n}\n\n/** Standing order frequency */\nexport type StandingOrderFrequency = 'weekly' | 'monthly';\n\n/** Standing order status */\nexport type StandingOrderStatus = 'active' | 'inactive' | 'cancelled' | 'completed';\n\n/** Payment rail type */\nexport type PaymentRail = 'ach_push' | 'ach_pull' | 'sepa' | 'faster_payments' | 'wire' | 'solana' | 'smart_account';\n\n/** Grid account details */\nexport interface GridAccountDetails {\n  account: string;\n  currency: string;\n  transactionSigners?: string[];\n}\n\n/** Solana address details */\nexport interface SolanaDetails {\n  address: string;\n  currency: string;\n}\n\n/**\n * New External Account Details\n */\nexport interface NewExternalAccountDetails {\n  paymentRail: PaymentRail;\n  currency: string;\n  details: any; // CreateExternalAccountRequest - would need proper typing\n}\n\n/**\n * Existing External Account Details\n */\nexport interface ExistingExternalAccountDetails {\n  paymentRail: PaymentRail;\n  currency: string;\n  externalAccountId: string;\n}\n\n/**\n * Details\n */\nexport type Details =\n  | GridAccountDetails           // has 'account' field\n  | SolanaDetails                // has 'address' field\n  | NewExternalAccountDetails    // has 'details' field\n  | ExistingExternalAccountDetails; // has 'external_account_id' field\n\n/**\n * Create Standing Order Request\n */\nexport interface CreateStandingOrderRequest {\n  amount: string;\n  source: Details;\n  destination: Details;\n  frequency: StandingOrderFrequency;\n  startDate: string; // ISO date string\n  endDate?: string; // Optional ISO date string\n}\n\n/** Create standing order response */\nexport interface CreateStandingOrderResponse extends BaseResponse<{\n    /** Standing order identifier */\n    id: string;\n    /** Amount as string */\n    amount: string;\n    /** Human-readable amount */\n    uiAmount: string;\n    /** Currency type */\n    currency: BridgeCurrency;\n    /** Payment rail used */\n    paymentRail: PaymentRail;\n    /** Source account details */\n    source: Details;\n    /** Destination account details */\n    destination: Details;\n    /** Recurrence frequency */\n    frequency: StandingOrderFrequency;\n    /** Start date (ISO string) */\n    startDate: string;\n    /** End date (ISO string, optional) */\n    endDate?: string;\n    /** Current status */\n    status: StandingOrderStatus;\n    /** Serialized transaction */\n    transaction: string;\n    kmsPayloads: KmsPayload[];\n    transactionSigners: string[];\n    validUntil: string;\n    createdAt: string;\n    transactionPayload: TransactionPayload;\n}> {}\n\n/**\n * Get Standing Orders Query Params\n */\nexport interface GetStandingOrdersQueryParams {\n  status?: StandingOrderStatus;\n  currency?: string;  // BridgeCurrency as string\n  startDate?: string;\n  endDate?: string;\n  txHash?: string;\n  limit?: number;\n  cursor?: string;\n}\n\n// Get Standing Orders types\nexport interface StandingOrder {\n  id: string;\n  amount: string;\n  currency: string;\n  period: StandingOrderFrequency;\n  destinations: string[];\n  status: StandingOrderStatus;\n  remainingAmount: string;\n  lastExecutionDate?: string;  // ISO date string\n  nextExecutionDate: string;    // ISO date string\n  createdAt: string;             // ISO date string\n}\n\nexport interface StandingOrderResponse extends BaseResponse<StandingOrder> {}\nexport interface StandingOrdersResponse extends BaseResponse<StandingOrder[]> {}\n\n/**\n * Available signer provider types for authentication and transaction signing.\n * @typedef {'privy' | 'turnkey' | 'solana' | 'passkey' | 'pending' | 'external'} SignerProvider\n */\nexport type SignerProvider = 'privy' | 'turnkey' | 'solana' | 'passkey' | 'pending' | 'external';\n\n// Grid Client Signer\nexport interface GridClientSigner {\n  address?: string;               // Optional - Solana/passkey signers have address\n  email?: string;                 // Optional - Privy/Turnkey signers may have email\n  sessionKey?: any;\n  type: 'primary' | 'backup';     // Signer priority/role\n  provider?: SignerProvider;      // Optional - The provider type for this signer\n}\n\n// Grid Client Context types\nexport interface GridClientUserContext {\n  // data: {\n    address?: string;          // The single smart account address (once created)\n    gridUserId?: string;           // Grid platform user ID\n    signers?: GridClientSigner[];  // Array of all signers who can authorize transactions\n    session?: Session;\n    email?: string;\n    otpId?: string;\n    provider?: SignerProvider | string;\n  // }\n}\n\n// @hidden\nexport interface EncryptedAuthorizationKey {\n  encryption_type: string;\n  encapsulated_key: string;\n  ciphertext: string;\n}\n\n/** @hidden */\nexport type WalletChainType =\n  | 'Solana'\n  | 'Ethereum'\n  | 'Cosmos'\n  | 'Stellar'\n  | 'Sui'\n  | 'Tron'\n  | 'bitcoin-segwit';\n\n/** @hidden */\nexport interface AdditionalSigner {\n  signerId: string;\n  overridePolicyIds?: string[]; // Optional Vec<String>\n}\n\n// Wallet created during registration\nexport interface Wallet {\n  id: string;\n  address: string;\n  publicKey?: string; // Option<String>\n  createdAt: number; // u64\n  chainType: WalletChainType;\n  policyIds: string[];\n  ownerId?: string; // Option<String>\n  additionalSigners: AdditionalSigner[];\n  exportedAt?: number; // Option<u64>\n  importedAt?: number; // Option<u64>\n}\n\n// Base session structure with authorization keys\nexport interface Session {\n  encryptedAuthorizationKey?: EncryptedAuthorizationKey; // Option<EncryptedAuthorizationKey>\n  authorizationKey?: string; // Option<String>\n  expiresAt: number; // u64\n  wallets: Wallet[];\n}\n\n// Refresh Session types\n/**\n * Privy-specific session data for refresh operations\n */\nexport interface PrivyRefreshSession {\n  /** Privy user identifier */\n  user_id: string;\n  /** Session data containing authorization keys and wallet information */\n  session: Session;\n  /** JWT token for Privy authentication */\n  token: string;\n  /** Privy platform access token */\n  privy_access_token: string;\n  /** Refresh token for obtaining new access tokens */\n  refresh_token: string;\n}\n\n/**\n * Turnkey session data for refresh\n *\n * Note: Turnkey refresh not yet implemented in API\n */\nexport interface TurnkeyRefreshSession {\n  userId: string;\n  api_key_id: string;\n  /** Encrypted credential bundle */\n  credential_bundle: string;\n}\n\n/** Provider session data (discriminated union by provider name) */\nexport type ProviderSessionData =\n  | { Privy: PrivyRefreshSession }\n  | { Turnkey: TurnkeyRefreshSession };\n\n/** Session provider entry with provider name and session data */\nexport interface SessionProvider {\n  /** Provider name (e.g., 'privy', 'turnkey', 'Passkey') */\n  provider: string;\n  /** Provider-specific session data */\n  session?: PrivyRefreshSession | TurnkeyRefreshSession | any;\n  /** Session key (Passkey provider only) */\n  sessionKey?: { key: any; expiration: number };\n  /** Passkey account address (Passkey provider only) */\n  passkeyAccount?: string;\n  /** Public key in base58 (Passkey provider only) */\n  pubkey?: string;\n  /** Relying party ID/domain (Passkey provider only) */\n  relyingPartyId?: string;\n  /** Passkey role */\n  role?: string;\n  /** Passkey permissions */\n  permissions?: string[];\n}\n\n/** Array of session providers from authentication endpoints */\nexport type AuthenticationData = SessionProvider[];\n\n/** KMS provider configuration for session refresh */\nexport interface RefreshSessionKmsProvider {\n  /** MPC provider type */\n  provider: string;\n  /** Provider-specific session data */\n  session: ProviderSessionData;\n}\n\n/**\n * Refresh session request (supports cookie-based and body-based flows)\n *\n * - Cookie-based (recommended): Omit kmsPayload, uses HTTP-only cookies\n * - Body-based (legacy): Include kmsPayload with tokens\n */\nexport interface RefreshSessionRequest {\n  /** KMS provider config (optional with HTTP-only cookies) */\n  kmsPayload?: RefreshSessionKmsProvider;\n  /** HPKE public key for response encryption */\n  encryptionPublicKey: string;\n}\n\n/** Refresh session response */\nexport interface RefreshSessionResponse extends BaseResponse<{\n  /** Updated KMS provider and session data */\n  kmsPayload: RefreshSessionKmsProvider;\n}> {}\n\n/** @hidden */\nexport interface ApiRefreshSessionResponse extends BaseResponse<{\n  kms_payload: RefreshSessionKmsProvider;\n}> {}\n\n/** @hidden */\nexport interface ClientContext {\n  environment: GridEnvironment;\n  config: GridApiConfig;\n  solanaRpcUrl?: string;\n}\n\n/** Grid client context */\nexport interface GridClientContext {\n  client: ClientContext;\n  user: GridClientUserContext;\n}\n\n/** Complete auth and create account response */\nexport interface CompleteAuthAndCreateAccountResponse extends BaseResponse<{\n  address: string;\n  status: string;\n  policies: AccountPolicies;\n  gridUserId: string;\n  authentication: AuthenticationData;\n}> {}\n\n/** Account state for reactive UI updates */\nexport interface AccountState {\n  /** Smart account address (if connected) */\n  accountAddress?: string;\n  /** Grid user ID (if connected) */\n  gridUserId?: string;\n  /** Whether account is connected */\n  isConnected: boolean;\n}\n","import { Env, ProviderConfig, InitAuthRequest, BaseResponse, AuthenticationData } from \"./common\";\nimport { GridEnvironment } from \"../api/grid-api-client\";\n\n/** @hidden */\nexport interface PasskeyConfig extends ProviderConfig {\n    // Clean interface - uses base ProviderConfig fields\n  }\n\n/** @hidden */\nexport interface CreatePasskeySessionRequest {\n  sessionKey: SessionKey;\n  env: Env | GridEnvironment;\n  metaInfo: Record<string, any>;\n}\n\n/** @hidden */\nexport interface CreatePasskeySessionResponse extends BaseResponse<{\n  url: string;\n}> {}\n\n/**\n * Session Key\n * @property {any} key - The key\n * @property {number} expiration - The expiration\n */\nexport interface SessionKey { key: any; expiration: number; }\n\n// Backend expects key as byte array for submit endpoint\n/** @hidden */\nexport interface SessionKeyBackend {\n  key: number[]; // Pubkey as byte array\n  expiration: number; // u64\n}\n\n/** @hidden */\nexport interface MetaInfo {\n  appName: string;\n  redirectUrl?: string;\n}\n\n/** @hidden */\nexport type CeremonyType = 'create' | 'auth';\n\n/**\n * Passkey Request\n */\nexport interface PasskeyRequest {\n  env: Env;\n  appName?: string;\n  userId?: string;\n  redirectUrl?: string;\n  challenge: string;\n  slotNumber: string;\n  sessionKey: string;\n  expirationInSeconds: string;\n}\n\n/**\n * Authorize Passkey Session Request\n */\nexport interface AuthorizePasskeySessionRequest {\n  sessionKey?: SessionKey;\n  metaInfo: MetaInfo;\n  baseUrl?: string;\n}\n\n/**\n * Authorize Passkey Session Response\n */\nexport interface AuthorizePasskeySessionResponse extends BaseResponse<{\n  url: string;\n}> {}\n\n// Submit Passkey Session\n/**\n * Submit Passkey Session Request\n */\nexport interface SubmitPasskeySessionRequest {\n  ceremonyType: CeremonyType;\n  sessionKey: SessionKeyBackend; // Backend expects byte array format\n  slotNumber: number;\n  authenticatorResponse: any; // JSON value from WebAuthn\n}\n\n/**\n * Submit Passkey Session Response\n * @property {string} passkeyAccount - The passkey signer account address\n * @property {string} address - The smart account address associated with this passkey\n * @property {SessionKey} sessionKey - Session key for transaction signing\n */\nexport interface SubmitPasskeySessionResponse extends BaseResponse<{\n  passkeyAccount: string;\n  smartAccount: {\n    address: string;  \n  };\n  sessionKey: SessionKey;\n}> {}\n\n// Find Passkey Account\n/**\n * Find Passkey Account Request\n */\nexport interface FindPasskeyAccountRequest {\n  sessionKey: SessionKey;\n  authenticatorResponse: any;\n}\n\n/**\n * Find Passkey Account Response\n * @property {string} passkeyAccount - The passkey signer account address\n * @property {string} address - The smart account address associated with this passkey\n * @property {SessionKey} sessionKey - Session key for transaction signing\n */\nexport interface FindPasskeyAccountResponse extends BaseResponse<{\n  passkeyAccount: string;\n  address: string;\n  sessionKey: SessionKey;\n}> {}\n\n/**\n * Get Passkey Session Response\n */\nexport interface GetPasskeySessionResponse extends BaseResponse<{\n  // TODO: Define based on backend response\n  session?: any;\n}> {}\n\n/**\n * Get Passkey Account Response\n * @property {string} relyingPartyId - The relying party ID (domain) associated with this passkey\n * @property {string} pubkey - The public key in base58 format\n * @property {SessionKey} [sessionKey] - Optional session key if not expired\n */\nexport interface GetPasskeyAccountResponse extends BaseResponse<{\n  relyingPartyId: string;\n  pubkey: string;\n  sessionKey?: SessionKey;\n}> {}\n\n/**\n * Create Passkey Account Request\n * Creates both the passkey account (externally signed account) and smart account in one call\n * @property {SessionKey} sessionKey - Session key for the passkey account\n * @property {number} slotNumber - Slot number for the passkey ceremony\n * @property {any} authenticatorResponse - WebAuthn authenticator response from passkey creation\n * @property {string} [adminAddress] - Optional admin address for settings authority\n * @property {string} [memo] - Optional memo for the account creation\n */\nexport interface CreatePasskeyAccountRequest {\n  sessionKey: SessionKey;\n  slotNumber: number;\n  authenticatorResponse: any;\n  adminAddress?: string;\n  memo?: string;\n}\n\n/**\n * Passkey Account Policies for newly created accounts\n * @property {number} threshold - Signature threshold for the account\n * @property {string} [adminAddress] - Optional admin address\n */\nexport interface PasskeyAccountPolicies {\n  threshold: number;\n  adminAddress?: string;\n}\n\n/**\n * Passkey Account Info returned from account creation\n * @property {string} passkeyAccount - The passkey account address\n * @property {string} pubkey - The public key in base58 format\n * @property {string} relyingPartyId - The relying party ID (domain)\n * @property {SessionKey} sessionKey - Session key associated with the passkey account\n */\nexport interface PasskeyAccountInfo {\n  passkeyAccount: string;\n  pubkey: string;\n  relyingPartyId: string;\n  sessionKey: SessionKey;\n}\n\n/**\n * Create Passkey Account Response\n * @property {string} address - The created smart account address\n * @property {string} type - Account type (always 'passkey')\n * @property {string} status - Account status (e.g., 'active')\n * @property {PasskeyAccountPolicies} policies - Account policies including threshold and admin\n * @property {AuthenticationData} authentication - Array of session providers with authentication data\n * @property {string} createdAt - ISO timestamp when account was created\n * @property {string} updatedAt - ISO timestamp when account was last updated\n */\nexport interface CreatePasskeyAccountResponse extends BaseResponse<{\n  address: string;\n  type: string;\n  status: string;\n  policies: PasskeyAccountPolicies;\n  authentication: AuthenticationData;\n  createdAt: string;\n  updatedAt: string;\n}> {}\n\n\n/** @hidden */\nexport const RP_NAME = 'Grid Auth'; // TODO: check if this is correct\n\n/**\n * Passkey Credential Data\n */\nexport interface PasskeyCredentialData {\n  id: ArrayBuffer;           // Raw ArrayBuffer for use in allowCredentials\n  publicKey: string;         // Base64 encoded public key\n  credentialId: string;      // Base64url encoded ID string\n}\n\n/**\n * Passkey Assertion Response\n */\nexport interface PasskeyAssertionResponse {\n  response: {\n    signature: string;\n    clientDataJSON: string;\n    authenticatorData: string;\n    publicKey?: string;      // Optional, only present when credentialData is provided\n  };\n}\n","import bs58 from \"bs58\";\n\nimport { SessionKey } from \"../types\";\n\n/**\n * @hidden\n * Service handling utility operations\n */\nexport class UtilityService {\n  /**\n   * @hidden\n   * Convert ArrayBuffer to base64url encoding\n   *\n   * @param buffer - ArrayBuffer containing binary data to encode\n   * @returns Base64url encoded string\n   *\n   * @example\n   * ```typescript\n   * const binaryData = new Uint8Array([1, 2, 3, 4]).buffer;\n   * const encoded = gridClient.bufferToBase64Url(binaryData);\n   * console.log(encoded);\n   * ```\n   *\n   * @category Utilities\n   */\n  bufferToBase64Url(buffer: ArrayBuffer): string {\n    const base64 = btoa(String.fromCharCode(...new Uint8Array(buffer)));\n    return base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n  }\n\n  /**\n   * Helper function to create session key object from string and expiration\n   *\n   * @param sessionKeyString - Base58-encoded session key string\n   * @param expirationInSeconds - Expiration time as a string (seconds since epoch)\n   * @returns SessionKey object with decoded key bytes and parsed expiration\n   *\n   * @example\n   * ```typescript\n   * const sessionKey = gridClient.getSessionKeyObject(\n   *   'base58-encoded-key',\n   *   '900'\n   * );\n   * ```\n   *\n   * @category Utilities\n   */\n  getSessionKeyObject(sessionKeyString: string, expirationInSeconds: string): SessionKey {\n    const keyBytes = bs58.decode(sessionKeyString);\n    const expiration = parseInt(expirationInSeconds, 10);\n\n    // TODO: double check this\n    // -expect-error - SessionKey type expects key to be string but we need to send raw bytes array\n    const sessionKey = {\n        key: Array.from(keyBytes),\n        expiration: expiration\n    } as SessionKey;\n\n    return sessionKey;\n  }\n\n  /**\n   * @hidden\n   * Convert all object keys from camelCase to snake_case recursively\n   *\n   * @param obj - Object with camelCase keys\n   * @returns Object with snake_case keys\n   *\n   * @example\n   * ```typescript\n   * const camelObj = { sessionKey: 'abc', slotNumber: 123 };\n   * const snakeObj = utilityService.toSnakeCaseObject(camelObj);\n   * // Returns: { session_key: 'abc', slot_number: 123 }\n   * ```\n   *\n   * @category Utilities\n   */\n  private snakeCase(str: string): string {\n    return str\n      .replace(/([a-z])([A-Z])/g, '$1_$2')\n      .replace(/[\\s\\-]+/g, '_')\n      .toLowerCase();\n  }\n\n  private camelCase(str: string): string {\n    return str\n      .replace(/[_\\-\\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''))\n      .replace(/^[A-Z]/, (c) => c.toLowerCase());\n  }\n\n  toSnakeCaseObject(obj: any): any {\n    if (obj === null || obj === undefined) {\n      return obj;\n    }\n\n    // Handle arrays\n    if (Array.isArray(obj)) {\n      return obj.map(item => this.toSnakeCaseObject(item));\n    }\n\n    // Handle plain objects (including null-prototype objects)\n    if (typeof obj === 'object' && Object.prototype.toString.call(obj) === '[object Object]') {\n      const result: Record<string, any> = {};\n      for (const [key, value] of Object.entries(obj)) {\n        const snakeKey = this.snakeCase(key);\n\n        // Skip transformation for authentication and session fields to preserve provider enum structure\n        if (key === 'authentication' || key === 'session') {\n          result[snakeKey] = value;\n        } else {\n          result[snakeKey] = this.toSnakeCaseObject(value);\n        }\n      }\n      return result;\n    }\n\n    // Return primitives as-is\n    return obj;\n  }\n\n  /**\n   * @hidden\n   * Convert all object keys from snake_case to camelCase recursively\n   *\n   * @param obj - Object with snake_case keys\n   * @returns Object with camelCase keys\n   *\n   * @example\n   * ```typescript\n   * const snakeObj = { session_key: 'abc', slot_number: 123 };\n   * const camelObj = utilityService.toCamelCaseObject(snakeObj);\n   * // Returns: { sessionKey: 'abc', slotNumber: 123 }\n   * ```\n   *\n   * @category Utilities\n   */\n  toCamelCaseObject(obj: any): any {\n    if (obj === null || obj === undefined) {\n      return obj;\n    }\n\n    // Handle arrays\n    if (Array.isArray(obj)) {\n      return obj.map(item => this.toCamelCaseObject(item));\n    }\n\n    // Handle plain objects (including null-prototype objects)\n    if (typeof obj === 'object' && Object.prototype.toString.call(obj) === '[object Object]') {\n      const result: Record<string, any> = {};\n      for (const [key, value] of Object.entries(obj)) {\n        const camelKey = this.camelCase(key);\n        \n        // Skip transformation for authentication field to preserve API structure for all providers\n        if (key === 'authentication') {\n          result[camelKey] = value;\n        } else {\n          result[camelKey] = this.toCamelCaseObject(value);\n        }\n      }\n      return result;\n    }\n\n    // Return primitives as-is\n    return obj;\n  }\n}\n","import { TransactionResponse } from \"../managers/signing-manager\";\nimport {\n  CreatePasskeySessionRequest,\n  CreatePasskeySessionResponse,\n  AuthorizePasskeySessionRequest,\n  AuthorizePasskeySessionResponse,\n  SubmitPasskeySessionRequest,\n  SubmitPasskeySessionResponse,\n  FindPasskeyAccountRequest,\n  FindPasskeyAccountResponse,\n  GetPasskeySessionResponse,\n  GetPasskeyAccountResponse,\n  CreatePasskeyAccountRequest,\n  CreatePasskeyAccountResponse,\n  TurnkeyInitAuthRequest,\n  TurnkeyCompleteAuthRequest,\n  ConfirmPayload,\n  PrivyInitAuthRequest,\n  PrivyCompleteAuthRequest,\n  GetPasskeysResponse,\n  AddPasskeyRequest,\n  AddPasskeyQueryParams,\n  AddPasskeyResponse,\n  UpdateAccountRequest,\n  CreateAccountRequest,\n  CreateAccountResponse,\n  GetAccountResponse,\n  GetAccountBalancesQueryParams,\n  GetTransfersOptions,\n  TransferResponse,\n  CreatePaymentIntentRequest,\n  CreatePaymentIntentApiResponse,\n  SpendingLimitRequest,\n  UpdateSpendingLimitRequest,\n  UseSpendingLimitRequest,\n  RequestKycLinkRequest,\n  KycLink,\n  PrepareArbitraryTransactionRequest,\n  PrepareArbitraryTransactionQueryParams,\n  RemovePasskeyRequest,\n  RemovePasskeyQueryParams,\n  RemovePasskeyResponse,\n  RequestVirtualAccountRequest,\n  GetVirtualAccountsQueryParams,\n  CreateStandingOrderRequest,\n  CreateStandingOrderResponse,\n  GetStandingOrdersQueryParams,\n  CompleteAuthAndCreateAccountResponse,\n  InitAuthResponse,\n  TransactionSubmissionResponse,\n  GetTransactionsResponse,\n  VirtualAccount,\n  RefreshSessionRequest,\n  RefreshSessionResponse,\n  ApiRefreshSessionResponse,\n  AuthorizationError,\n  GridError,\n  AccountBalancesResponse,\n  KycStatusResponse,\n  KycLinkResponse,\n  StandingOrdersResponse,\n  StandingOrderResponse,\n  VirtualAccountsResponse,\n  VirtualAccountResponse,\n  CreateSpendingLimitResponse,\n  SpendingLimitTransactionResponse,\n  SpendingLimitResponse,\n  SpendingLimitsResponse,\n  // Proposal types\n  CreateProposalRequest,\n  CreateProposalResponse,\n  VoteProposalRequest,\n  VoteProposalResponse,\n  ExecuteProposalRequest,\n  ExecuteProposalResponse,\n  // Trade smart transaction types\n  CreateTradeSmartTransactionRequest,\n  CreateTradeSmartTransactionResponse,\n  TradeSmartTransactionQuoteRequest,\n  TradeSmartTransactionQuoteResponse,\n  PrepareTradeSmartTransactionRequest,\n  PrepareTradeSmartTransactionQueryParams,\n  PrepareTradeSmartTransactionResponse,\n  GetTradeSmartTransactionResponse,\n} from \"../types\";\nimport { PrivyInternalSignRequest, PrivyCompleteAuthResponse } from \"../types/privy\";\nimport { TurnkeyCompleteAuthResponse } from \"../types/turnkey\";\nimport { UtilityService } from \"../services/utility-service\";\nimport * as uuid from \"uuid\";\n\n/** Error detail from API validation failures */\nexport interface GridErrorDetail {\n  /** Field that caused the validation error */\n  field: string;\n  /** Machine-readable error code */\n  code: string;\n  /** Human-readable error message */\n  message: string;\n  /** Suggestion for fixing the error */\n  suggestion?: string;\n  /** Link to relevant documentation */\n  documentation?: string;\n}\n\n/**\n * Grid API environment: `sandbox` (Devnet) or `production` (Mainnet)\n *\n * @category Configuration\n */\nexport type GridEnvironment = \"sandbox\" | \"production\";\n\n/**\n * Grid API client configuration\n *\n * Security:\n * - `apiKey`: Backend only - never expose in frontend code\n * - `appId`: Safe for frontend - requires domain whitelist configuration\n *\n * @category Configuration\n */\nexport interface GridApiConfig {\n  /** API key for backend authentication (never expose in frontend code) */\n  apiKey?: string;\n  /** Target environment (sandbox or production) */\n  environment: GridEnvironment;\n  /** Base URL for the Grid API */\n  baseUrl?: string;\n  /** Application ID for frontend (safe to expose, whitelist domains in dashboard) */\n  appId?: string;\n  /** Request timeout in milliseconds */\n  timeout?: number;\n  /** Retry attempts for failed requests */\n  retryAttempts?: number;\n  /** Solana RPC endpoint URL */\n  solanaRpcUrl?: string;\n  /** @internal For testing only - sets Origin header for appId validation */\n  __testOrigin?: string;\n}\n\n/**\n * @hidden\n * Low-level HTTP client for Grid API\n *\n * Handles authentication, request/response formatting, and error handling.\n * Most users should use GridClient instead.\n *\n * @category API\n */\nexport class GridApiClient {\n  private environment: GridEnvironment;\n  private config: GridApiConfig;\n  private baseUrl?: string;\n  private utilityService: UtilityService;\n\n  constructor(config: GridApiConfig) {\n    this.utilityService = new UtilityService();\n    // Validate environment if provided\n    if (\n      config.environment &&\n      ![\"sandbox\", \"production\", \"devnet\", \"mainnet\"].includes(config.environment)\n    ) {\n      throw new Error(\n        `Invalid Grid environment: '${config.environment}'. Must be 'sandbox' or 'production'.`\n      );\n    }\n\n    this.environment = config.environment || \"sandbox\";\n    this.baseUrl = `${config.baseUrl || \"https://grid.squads.xyz\"}/api/grid/v1`;\n    this.config = {\n      timeout: 10000,\n      retryAttempts: 3,\n      ...config,\n    };\n\n    // Log warning if no API key is provided\n    if (!this.config.apiKey && !this.config.appId) {\n      console.warn(\n        \"⚠️ GridApiClient initialized in Demo Mode.\"\n      );\n    }\n  }\n\n  private generateIdempotencyKey(): string {\n    return uuid.v4();\n  }\n\n  /**\n   * Check if API key is available\n   */\n  public hasApiKey(): boolean {\n    return Boolean(this.config.apiKey);\n  }\n\n  /**\n   * @internal\n   */\n  protected async request<T>(\n    endpoint: string,\n    options: {\n      method?: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\n      data?: any;\n      headers?: Record<string, string>;\n      skipTransform?: boolean;\n      skipTransformResponse?: boolean;\n    } = {}\n  ): Promise<T> {\n    const { method = \"GET\", data, headers = {}, skipTransform = false, skipTransformResponse = false } = options;\n\n    const url = `${this.baseUrl}${endpoint}`;\n    const requestHeaders: Record<string, string> = {\n      \"Content-Type\": \"application/json\",\n      \"x-grid-environment\": this.environment,\n      ...headers,\n    };\n\n    // Add idempotency key for POST/PUT/PATCH requests\n    if (method === \"POST\" || method === \"PUT\" || method === \"PATCH\") {\n      requestHeaders[\"x-idempotency-key\"] = this.generateIdempotencyKey();\n    }\n\n    // Add app ID header if provided\n    if (this.config.appId) {\n      requestHeaders[\"x-grid-app-id\"] = this.config.appId;\n    }\n\n    // Only add Authorization header if API key is provided\n    if (this.config.apiKey) {\n      requestHeaders[\"Authorization\"] = `Bearer ${this.config.apiKey}`;\n    }\n\n    // Add Origin header for testing (internal use only)\n    if (this.config.__testOrigin) {\n      requestHeaders[\"Origin\"] = this.config.__testOrigin;\n    }\n\n    try {\n      // Transform camelCase request body to snake_case for API (skip for passkey endpoints)\n      const requestBody = data \n        ? (skipTransform ? data : this.utilityService.toSnakeCaseObject(data)) \n        : undefined;\n      \n      const response = await fetch(url, {\n        method,\n        headers: requestHeaders,\n        body: requestBody ? JSON.stringify(requestBody) : undefined,\n        credentials: 'include', // Required for HTTP-only cookies to work cross-origin\n        // signal: AbortSignal.timeout(this.config.timeout!)\n      });\n\n      const requestId = response.headers.get('x-request-id') || '';\n      const idempotencyKey = response.headers.get('x-idempotency-key') || undefined;\n      const contentType = response.headers.get('content-type') || '';\n\n      // Capture all headers as an object (for both success and error)\n      const headers: Record<string, string> = {};\n      response.headers.forEach((value, key) => {\n        headers[key] = value;\n      });\n\n      // Parse response body based on content type\n      let result;\n      if (contentType.includes('application/json')) {\n        result = await response.json();\n      } else {\n        // Plain text response\n        const text = await response.text();\n        result = { message: text };\n      }\n\n      if (!response.ok) {\n        throw new GridError(\n          result?.message || \"Unknown error\",\n          response.status.toString(),\n          response.status, // status_code\n          result?.details, // details from API\n          result?.timestamp,\n          { requestId, statusCode: response.status, headers } // lastResponse with requestId, statusCode, and headers\n        );\n      }\n\n      // Extract the actual data (unwrap if API wrapped it in data)\n      const responseData = result.data ? result.data : result;\n\n      // Transform snake_case response to camelCase for SDK consumers\n      const transformedData = skipTransformResponse ? responseData : this.utilityService.toCamelCaseObject(responseData);\n\n      // Create lastResponse metadata \n      const lastResponse = {\n        requestId,\n        statusCode: response.status,\n        headers,\n        ...(idempotencyKey && { idempotencyKey })\n      };\n\n      // Always wrap in data + lastResponse pattern\n      return {\n        data: transformedData,\n        lastResponse\n      } as T;\n    } catch (error) {\n      // Re-throw GridError as-is to preserve error codes\n      if (error instanceof GridError) {\n        throw error;\n      }\n\n      // Only network/URL errors reach here (connection failures, etc.)\n      throw new GridError(error instanceof Error ? error.message : \"Unknown error\", \"NETWORK_ERROR\");\n    }\n  }\n\n  // Passkey session creation\n  async createPasskeySession(\n    params: CreatePasskeySessionRequest,\n    environment: string\n  ): Promise<CreatePasskeySessionResponse> {\n    return this.request<CreatePasskeySessionResponse>(\"/passkeys\", {\n      method: \"POST\",\n      headers: {\n        \"x-grid-environment\": environment,\n      },\n      data: params,\n      skipTransform: true,\n    });\n  }\n\n  // Authorize passkey session\n  async authorizePasskeySession(\n    params: AuthorizePasskeySessionRequest,\n    environment: string\n  ): Promise<AuthorizePasskeySessionResponse> {\n    return this.request<AuthorizePasskeySessionResponse>(\"/passkeys/auth\", {\n      method: \"POST\",\n      headers: {\n        \"x-grid-environment\": environment,\n      },\n      data: params,\n      skipTransform: true,\n    });\n  }\n\n  // Submit passkey session\n  async submitPasskeySession(\n    params: SubmitPasskeySessionRequest,\n    environment: string\n  ): Promise<SubmitPasskeySessionResponse> {\n    const requestBody = {\n      ceremonyType: params.ceremonyType,\n      sessionKey: params.sessionKey,\n      slotNumber: Number(params.slotNumber),\n      authenticatorResponse: params.authenticatorResponse,\n    };\n\n    return this.request<SubmitPasskeySessionResponse>(\"/passkeys/submit\", {\n      method: \"POST\",\n      headers: {\n        \"x-grid-environment\": environment,\n      },\n      data: requestBody,\n      skipTransform: true,\n    });\n  }\n\n  // Find passkey account\n  async findPasskeyAccount(\n    params: FindPasskeyAccountRequest,\n    environment: string\n  ): Promise<FindPasskeyAccountResponse> {\n    return this.request<FindPasskeyAccountResponse>(\"/passkeys/find\", {\n      method: \"POST\",\n      headers: {\n        \"x-grid-environment\": environment,\n      },\n      data: params,\n      skipTransform: true,\n    });\n  }\n\n  // Get passkey account\n  // Retrieves passkey account details including relying party ID, public key, and optional session key\n  async getPasskeyAccount(\n    passkeyAddress: string,\n    environment: string\n  ): Promise<GetPasskeyAccountResponse> {\n    return this.request<GetPasskeyAccountResponse>(`/passkeys/account/${passkeyAddress}`, {\n      method: \"GET\",\n      headers: {\n        \"x-grid-environment\": environment,\n      },\n    });\n  }\n\n  // Create passkey account (smart account with passkey signer)\n  // Creates a new smart account with the passkey as the initial signer\n  async createPasskeyAccount(\n    params: CreatePasskeyAccountRequest,\n    environment: string\n  ): Promise<CreatePasskeyAccountResponse> {\n    const response = await this.request<CreatePasskeyAccountResponse>(\"/passkeys/account\", {\n      method: \"POST\",\n      headers: {\n        \"x-grid-environment\": environment,\n      },\n      data: params,\n      skipTransform: true,\n    });\n\n    return response;\n  }\n\n  // Auth endpoints\n  async initAuthWithTurnkey(\n    request: TurnkeyInitAuthRequest\n  ): Promise<InitAuthResponse> {\n    // Transform camelCase to snake_case for API\n    const apiRequest: Record<string, unknown> = {\n      email: request.email,\n      // app_name: request.appName,\n      // app_icon_url: request.appIconUrl,\n      // expiration: request.expiration,\n      provider: request.provider,\n    };\n\n    if (request.smartAccountAddress) {\n      apiRequest.smart_account_address = request.smartAccountAddress;\n    }\n\n    return this.request<InitAuthResponse>(\"/auth\", {\n      method: \"POST\",\n      data: apiRequest,\n    });\n  }\n\n  async completeTurnkeyAuth(\n    data: TurnkeyCompleteAuthRequest\n  ): Promise<TurnkeyCompleteAuthResponse> {\n    const apiRequest: Record<string, unknown> = {\n      otp_code: data.otpCode,\n      kms_provider: \"turnkey\",\n      kms_provider_config: {\n        encryption_public_key: data.authPublicKey,\n        otp_id: data.otpId,\n      },\n      email: data.email,\n    };\n\n    if (data.smartAccountAddress) {\n      apiRequest.smart_account_address = data.smartAccountAddress;\n    }\n\n    return this.request<TurnkeyCompleteAuthResponse>(\"/auth/verify\", {\n      method: \"POST\",\n      data: apiRequest,\n    });\n  }\n\n  async completeTurnkeyAuthAndCreateAccount(\n    data: TurnkeyCompleteAuthRequest\n  ): Promise<CompleteAuthAndCreateAccountResponse> {\n    const apiRequest = {\n      mpc_primary_id: data.mpcPrimaryId,\n      otp_id: data.otpId,\n      otp_code: data.otpCode,\n      auth_public_key: data.authPublicKey,\n      expiration: data.expiration,\n    };\n    return this.request<CompleteAuthAndCreateAccountResponse>(\"/auth/complete-and-create-account\", {\n      method: \"POST\",\n      data: apiRequest,\n    });\n  }\n\n  // Privy Auth endpoints\n  async initAuthWithPrivy(\n    request: PrivyInitAuthRequest\n  ): Promise<InitAuthResponse> {\n    const apiRequest: Record<string, unknown> = {\n      email: request.email,\n      provider: request.provider || \"privy\",\n      expiration: request.expiration,\n    };\n\n    if (request.smartAccountAddress) {\n      apiRequest.smart_account_address = request.smartAccountAddress;\n    }\n\n    return this.request<InitAuthResponse>(\"/auth\", {\n      method: \"POST\",\n      data: apiRequest,\n    });\n  }\n\n  async completePrivyAuthAndCreateAccount(\n    data: PrivyCompleteAuthRequest\n  ): Promise<CompleteAuthAndCreateAccountResponse> {\n    const apiRequest = {\n      email: data.email,\n      otp_code: data.otpCode,\n      provider: \"privy\",\n      kms_provider_config: {\n        encryption_public_key: data.authPublicKey,\n      },\n      expiration: data.expiration,\n    };\n    return this.request<CompleteAuthAndCreateAccountResponse>(\"/accounts/verify\", {\n      method: \"POST\",\n      data: apiRequest,\n    });\n  }\n\n  async completePrivyAuth(\n    data: PrivyCompleteAuthRequest\n  ): Promise<PrivyCompleteAuthResponse> {\n    const apiRequest: Record<string, unknown> = {\n      email: data.email,\n      otp_code: data.otpCode,\n      kms_provider: \"privy\",\n      kms_provider_config: {\n        encryption_public_key: data.authPublicKey,\n      },\n      expiration: data.expiration,\n    };\n\n    if (data.smartAccountAddress) {\n      apiRequest.smart_account_address = data.smartAccountAddress;\n    }\n\n    return this.request<PrivyCompleteAuthResponse>(\"/auth/verify\", {\n      method: \"POST\",\n      data: apiRequest,\n    });\n  }\n\n  // Refresh session endpoint\n  async refreshSession(\n    request: RefreshSessionRequest\n  ): Promise<RefreshSessionResponse> {\n    const endpoint = \"/auth/refresh-session\";\n\n    const result = await this.request<ApiRefreshSessionResponse>(endpoint, {\n      method: \"POST\",\n      data: {\n        kms_payload: request.kmsPayload,\n        encryption_public_key: request.encryptionPublicKey,\n      },\n      skipTransform: true,\n      skipTransformResponse: true,\n    });\n\n    return {\n      data: {\n        kmsPayload: result.data.kms_payload,\n      },\n      lastResponse: result.lastResponse,\n    } as RefreshSessionResponse;\n  }\n\n  // Transaction endpoints (crypto-native terminology)\n  async sendTransaction(\n    address: string,\n    transactionId: string,\n    payload: ConfirmPayload\n  ): Promise<TransactionSubmissionResponse> {\n    const endpoint = `/accounts/${address}/transactions/${transactionId}/confirm?use-mpc-provider=true`;\n\n    return this.request<TransactionSubmissionResponse>(endpoint, {\n      method: \"POST\",\n      data: payload,\n    });\n  }\n\n  // Submit transaction with KMS payloads format (for Privy)\n  async submitPrivyTransaction(\n    smartAccountAddress: string,\n    submitPayload: any\n  ): Promise<TransactionSubmissionResponse> {\n    const endpoint = `/accounts/${smartAccountAddress}/submit`;\n\n    return this.request<TransactionSubmissionResponse>(endpoint, {\n      method: \"POST\",\n      data: submitPayload,\n    });\n  }\n\n  // Generic transaction submission\n  async submitTransaction(\n    smartAccountAddress: string,\n    submitPayload: any\n  ): Promise<TransactionSubmissionResponse> {\n    const endpoint = `/accounts/${smartAccountAddress}/submit`;\n\n    return this.request<TransactionSubmissionResponse>(endpoint, {\n      method: \"POST\",\n      data: submitPayload,\n      skipTransform: true,\n    });\n  }\n\n  // Account endpoints\n  async getAccount(address: string): Promise<GetAccountResponse> {\n    return this.request<GetAccountResponse>(`/accounts/${address}`, {\n      method: \"GET\",\n    });\n  }\n\n  async getTransactions(address: string): Promise<GetTransactionsResponse> {\n    return this.request<GetTransactionsResponse>(`/accounts/${address}/transactions`, {\n      method: \"GET\",\n    });\n  }\n\n  async getAccountBalances(\n    address: string,\n    queryParams?: GetAccountBalancesQueryParams\n  ): Promise<AccountBalancesResponse> {\n    let endpoint = `/accounts/${address}/balances`;\n\n    // Add query parameters if provided\n    if (queryParams) {\n      const params = new URLSearchParams();\n      if (queryParams.limit !== undefined) {\n        params.append(\"limit\", queryParams.limit.toString());\n      }\n      if (queryParams.page !== undefined) {\n        params.append(\"page\", queryParams.page.toString());\n      }\n      if (params.toString()) {\n        endpoint += `?${params.toString()}`;\n      }\n    }\n\n    return this.request<AccountBalancesResponse>(endpoint, {\n      method: \"GET\",\n    });\n  }\n\n  async getTransfers(\n    address: string,\n    options?: GetTransfersOptions\n  ): Promise<TransferResponse> {\n    let endpoint = `/accounts/${address}/transfers`;\n\n    // Add query parameters if provided (camelCase properties → snake_case API params)\n    if (options) {\n      const params = new URLSearchParams();\n      if (options.paymentRail !== undefined) {\n        params.append(\"type\", options.paymentRail); // API uses 'type' parameter\n      }\n      if (options.status !== undefined) {\n        params.append(\"status\", options.status);\n      }\n      if (options.currency !== undefined) {\n        params.append(\"currency\", options.currency);\n      }\n      if (options.startDate !== undefined) {\n        params.append(\"start_date\", options.startDate);\n      }\n      if (options.endDate !== undefined) {\n        params.append(\"end_date\", options.endDate);\n      }\n      if (options.txHash !== undefined) {\n        params.append(\"tx_hash\", options.txHash);\n      }\n      if (options.limit !== undefined) {\n        params.append(\"limit\", options.limit.toString());\n      }\n      if (options.cursor !== undefined) {\n        params.append(\"cursor\", options.cursor);\n      }\n      if (params.toString()) {\n        endpoint += `?${params.toString()}`;\n      }\n    }\n\n    return this.request<TransferResponse>(endpoint, {\n      method: \"GET\",\n    });\n  }\n\n  // Legacy method for backward compatibility TODO: is this true?\n  async getBalance(\n    address: string\n  ): Promise<AccountBalancesResponse> {\n    return this.getAccountBalances(address);\n  }\n\n  // Spending limit endpoint\n  async createSpendingLimit(\n    smartAccountAddress: string,\n    request: SpendingLimitRequest\n  ): Promise<CreateSpendingLimitResponse> {\n    const endpoint = `/accounts/${smartAccountAddress}/spending-limit`;\n\n    return this.request<CreateSpendingLimitResponse>(endpoint, {\n      method: \"POST\",\n      data: request,\n    });\n  }\n\n  // Update spending limit endpoint\n  async updateSpendingLimit(\n    accountAddress: string,\n    spendingLimitAddress: string,\n    request: UpdateSpendingLimitRequest\n  ): Promise<SpendingLimitTransactionResponse> {\n    const endpoint = `/accounts/${accountAddress}/spending-limit/${spendingLimitAddress}`;\n\n    return this.request<SpendingLimitTransactionResponse>(endpoint, {\n      method: \"PATCH\",\n      data: request,\n    });\n  }\n\n  // Delete spending limit endpoint\n  async deleteSpendingLimit(\n    accountAddress: string,\n    spendingLimitAddress: string\n  ): Promise<SpendingLimitTransactionResponse> {\n    const endpoint = `/accounts/${accountAddress}/spending-limit/${spendingLimitAddress}`;\n\n    return this.request<SpendingLimitTransactionResponse>(endpoint, {\n      method: \"DELETE\",\n      data: {\n        transaction_signers: [],\n      },\n    });\n  }\n\n  // Use spending limit endpoint\n  async useSpendingLimit(\n    accountAddress: string,\n    spendingLimitAddress: string,\n    request: UseSpendingLimitRequest\n  ): Promise<SpendingLimitTransactionResponse> {\n    const endpoint = `/accounts/${accountAddress}/spending-limit/${spendingLimitAddress}/transactions`;\n\n    return this.request<SpendingLimitTransactionResponse>(endpoint, {\n      method: \"POST\",\n      data: request,\n    });\n  }\n\n  // Get spending limit endpoint\n  async getSpendingLimit(\n    accountAddress: string,\n    spendingLimitAddress: string\n  ): Promise<SpendingLimitResponse> {\n    const endpoint = `/accounts/${accountAddress}/spending-limit/${spendingLimitAddress}`;\n\n    return this.request<SpendingLimitResponse>(endpoint, {\n      method: \"GET\",\n    });\n  }\n\n  // Get Spending Limits endpoint\n  async getSpendingLimits(\n    accountAddress: string\n  ): Promise<SpendingLimitsResponse> {\n    const endpoint = `/accounts/${accountAddress}/spending-limits`;\n\n    return this.request<SpendingLimitsResponse>(endpoint, {\n      method: \"GET\",\n    });\n  }\n\n  // Passkey endpoints\n  async getPasskeys(\n    accountAddress: string\n  ): Promise<GetPasskeysResponse> {\n    const endpoint = `/accounts/${accountAddress}/passkeys`;\n\n    return this.request<GetPasskeysResponse>(endpoint, {\n      method: \"GET\",\n    });\n  }\n\n  async addPasskey(\n    accountAddress: string,\n    request: AddPasskeyRequest,\n    queryParams?: AddPasskeyQueryParams\n  ): Promise<AddPasskeyResponse> {\n    const endpoint = `/accounts/${accountAddress}/passkeys/transaction`;\n    const params = queryParams?.admin ? \"?admin=true\" : \"\";\n\n    return this.request<AddPasskeyResponse>(endpoint + params, {\n      method: \"POST\",\n      data: request,\n    });\n  }\n\n  async removePasskey(\n    accountAddress: string,\n    passkeyAddress: string,\n    transactionSigners?: string[],\n    queryParams?: RemovePasskeyQueryParams\n  ): Promise<RemovePasskeyResponse> {\n    const endpoint = `/accounts/${accountAddress}/passkeys/${passkeyAddress}/transaction`;\n    const params = queryParams?.admin ? \"?admin=true\" : \"\";\n\n    return this.request<RemovePasskeyResponse>(endpoint + params, {\n      method: \"DELETE\",\n      data: {\n        transaction_signers: transactionSigners,\n      },\n    });\n  }\n\n  // Account creation endpoint\n  async createAccount(\n    request: CreateAccountRequest\n  ): Promise<CreateAccountResponse> {\n    const endpoint = \"/accounts\";\n\n    return this.request<CreateAccountResponse>(endpoint, {\n      method: \"POST\",\n      data: request,\n    });\n  }\n\n  // Account update endpoint\n  async updateAccount(\n    accountAddress: string,\n    request: UpdateAccountRequest,\n    admin?: boolean,\n  ): Promise<TransactionResponse> {\n    const endpoint = `/accounts/${accountAddress}`;\n    const params = admin ? \"?admin=true\" : \"\";\n\n    return this.request<TransactionResponse>(endpoint + params, {\n      method: \"PATCH\",\n      data: request,\n    });\n  }\n\n  // Payment intent endpoint\n  async createPaymentIntent(\n    accountAddress: string,\n    request: CreatePaymentIntentRequest\n  ): Promise<CreatePaymentIntentApiResponse> {\n    const endpoint = `/accounts/${accountAddress}/payment-intent`;\n\n    return this.request<CreatePaymentIntentApiResponse>(endpoint, {\n      method: \"POST\",\n      data: request,\n    });\n  }\n\n  // Request KYC Link endpoint\n  async requestKycLink(\n    accountAddress: string,\n    request: RequestKycLinkRequest\n  ): Promise<KycLinkResponse> {\n    const endpoint = `/accounts/${accountAddress}/kyc`;\n\n    return this.request<KycLinkResponse>(endpoint, {\n      method: \"POST\",\n      data: request,\n    });\n  }\n\n  // Get KYC Status endpoint\n  async getKycStatus(\n    accountAddress: string,\n    kycId: string\n  ): Promise<KycStatusResponse> {\n    const endpoint = `/accounts/${accountAddress}/kyc/${kycId}`;\n\n    return this.request<KycStatusResponse>(endpoint, {\n      method: \"GET\",\n    });\n  }\n\n  // Prepare Arbitrary Transaction endpoint\n  async prepareArbitraryTransaction(\n    accountAddress: string,\n    request: PrepareArbitraryTransactionRequest,\n    queryParams?: PrepareArbitraryTransactionQueryParams\n  ): Promise<TransactionResponse> {\n    let endpoint = `/accounts/${accountAddress}/transactions`;\n\n    // Add query parameters if provided\n    if (queryParams) {\n      const params = new URLSearchParams();\n      if (queryParams.debug !== undefined) {\n        params.append(\"debug\", queryParams.debug.toString());\n      }\n      if (params.toString()) {\n        endpoint += `?${params.toString()}`;\n      }\n    }\n\n    return this.request<TransactionResponse>(endpoint, {\n      method: \"POST\",\n      data: request,\n    });\n  }\n\n  // ============= Proposal Endpoints =============\n  async createProposal(\n    accountAddress: string,\n    request: CreateProposalRequest\n  ): Promise<CreateProposalResponse> {\n    const endpoint = `/accounts/${accountAddress}/proposals`;\n\n    return this.request<CreateProposalResponse>(endpoint, {\n      method: \"POST\",\n      data: request,\n    });\n  }\n\n  async voteProposal(\n    accountAddress: string,\n    proposalAddress: string,\n    request: VoteProposalRequest\n  ): Promise<VoteProposalResponse> {\n    const endpoint = `/accounts/${accountAddress}/proposals/${proposalAddress}/vote`;\n\n    return this.request<VoteProposalResponse>(endpoint, {\n      method: \"POST\",\n      data: request,\n    });\n  }\n\n  async executeProposal(\n    accountAddress: string,\n    proposalAddress: string,\n    request: ExecuteProposalRequest\n  ): Promise<ExecuteProposalResponse> {\n    const endpoint = `/accounts/${accountAddress}/proposals/${proposalAddress}/execute`;\n\n    return this.request<ExecuteProposalResponse>(endpoint, {\n      method: \"POST\",\n      data: request,\n    });\n  }\n\n  // ============= Trade Smart Transaction Endpoints =============\n\n  /**\n   * Create a trade smart transaction policy\n   * POST /accounts/{accountAddress}/trade/smart-transactions\n   */\n  async createTradeSmartTransaction(\n    accountAddress: string,\n    request: CreateTradeSmartTransactionRequest\n  ): Promise<CreateTradeSmartTransactionResponse> {\n    const endpoint = `/accounts/${accountAddress}/trade/smart-transactions`;\n\n    return this.request<CreateTradeSmartTransactionResponse>(endpoint, {\n      method: \"POST\",\n      data: request,\n    });\n  }\n\n  /**\n   * Get a policy-aware trade quote\n   * POST /accounts/{accountAddress}/trade/smart-transactions/{smartTransactionAddress}/quote\n   */\n  async getTradeSmartTransactionQuote(\n    accountAddress: string,\n    smartTransactionAddress: string,\n    request: TradeSmartTransactionQuoteRequest\n  ): Promise<TradeSmartTransactionQuoteResponse> {\n    const endpoint = `/accounts/${accountAddress}/trade/smart-transactions/${smartTransactionAddress}/quote`;\n\n    return this.request<TradeSmartTransactionQuoteResponse>(endpoint, {\n      method: \"POST\",\n      data: request,\n    });\n  }\n\n  /**\n   * Prepare a trade smart transaction\n   * POST /accounts/{accountAddress}/trade/smart-transactions/{smartTransactionAddress}\n   */\n  async prepareTradeSmartTransaction(\n    accountAddress: string,\n    smartTransactionAddress: string,\n    request: PrepareTradeSmartTransactionRequest,\n    queryParams?: PrepareTradeSmartTransactionQueryParams\n  ): Promise<PrepareTradeSmartTransactionResponse> {\n    let endpoint = `/accounts/${accountAddress}/trade/smart-transactions/${smartTransactionAddress}`;\n\n    // Add query parameters if provided\n    if (queryParams) {\n      const params = new URLSearchParams();\n      if (queryParams.debug !== undefined) {\n        params.append(\"debug\", queryParams.debug.toString());\n      }\n      if (params.toString()) {\n        endpoint += `?${params.toString()}`;\n      }\n    }\n\n    return this.request<PrepareTradeSmartTransactionResponse>(endpoint, {\n      method: \"POST\",\n      data: request,\n    });\n  }\n\n  /**\n   * Get a trade smart transaction policy\n   * GET /accounts/{accountAddress}/trade/smart-transactions/{smartTransactionAddress}\n   */\n  async getTradeSmartTransaction(\n    accountAddress: string,\n    smartTransactionAddress: string\n  ): Promise<GetTradeSmartTransactionResponse> {\n    const endpoint = `/accounts/${accountAddress}/trade/smart-transactions/${smartTransactionAddress}`;\n\n    return this.request<GetTradeSmartTransactionResponse>(endpoint, {\n      method: \"GET\",\n    });\n  }\n\n  // Request Virtual Account endpoint\n  async requestVirtualAccount(\n    accountAddress: string,\n    request: RequestVirtualAccountRequest\n  ): Promise<VirtualAccountResponse> {\n    const endpoint = `/accounts/${accountAddress}/virtual-account`;\n\n    return this.request<VirtualAccountResponse>(endpoint, {\n      method: \"POST\",\n      data: request,\n    });\n  }\n\n  // Get Virtual Accounts endpoint\n  async getVirtualAccounts(\n    accountAddress: string,\n    queryParams?: GetVirtualAccountsQueryParams\n  ): Promise<VirtualAccountsResponse> {\n    let endpoint = `/accounts/${accountAddress}/virtual-accounts`;\n\n    // Add query parameters if provided (camelCase properties → snake_case API params)\n    if (queryParams) {\n      const params = new URLSearchParams();\n      if (queryParams.sourceCurrency !== undefined) {\n        params.append(\"source_currency\", queryParams.sourceCurrency);\n      }\n      if (queryParams.destinationCurrency !== undefined) {\n        params.append(\"destination_currency\", queryParams.destinationCurrency);\n      }\n      if (params.toString()) {\n        endpoint += `?${params.toString()}`;\n      }\n    }\n\n    return this.request<VirtualAccountsResponse>(endpoint, {\n      method: \"GET\",\n    });\n  }\n\n  // Create Standing Order endpoint\n  async createStandingOrder(\n    accountAddress: string,\n    request: CreateStandingOrderRequest\n  ): Promise<CreateStandingOrderResponse> {\n    const endpoint = `/accounts/${accountAddress}/standing-order-intent`;\n\n    const res = await this.request<CreateStandingOrderResponse>(endpoint, {\n      method: \"POST\",\n      data: request,\n    });\n    return res;\n  }\n\n  // Get Standing Orders endpoint\n  async getStandingOrders(\n    accountAddress: string,\n    queryParams?: GetStandingOrdersQueryParams\n  ): Promise<StandingOrdersResponse> {\n    let endpoint = `/accounts/${accountAddress}/standing-orders`;\n\n    // Add query parameters if provided (camelCase properties → snake_case API params)\n    if (queryParams) {\n      const params = new URLSearchParams();\n      if (queryParams.status !== undefined) {\n        params.append(\"status\", queryParams.status);\n      }\n      if (queryParams.currency !== undefined) {\n        params.append(\"currency\", queryParams.currency);\n      }\n      if (queryParams.startDate !== undefined) {\n        params.append(\"start_date\", queryParams.startDate);\n      }\n      if (queryParams.endDate !== undefined) {\n        params.append(\"end_date\", queryParams.endDate);\n      }\n      if (queryParams.txHash !== undefined) {\n        params.append(\"tx_hash\", queryParams.txHash);\n      }\n      if (queryParams.limit !== undefined) {\n        params.append(\"limit\", queryParams.limit.toString());\n      }\n      if (queryParams.cursor !== undefined) {\n        params.append(\"cursor\", queryParams.cursor);\n      }\n\n      if (params.toString()) {\n        endpoint += `?${params.toString()}`;\n      }\n    }\n\n    return this.request<StandingOrdersResponse>(endpoint, {\n      method: \"GET\",\n    });\n  }\n\n  // Get Single Standing Order endpoint\n  async getStandingOrder(\n    accountAddress: string,\n    standingOrderId: string\n  ): Promise<StandingOrderResponse> {\n    const endpoint = `/accounts/${accountAddress}/standing-order/${standingOrderId}`;\n\n    return this.request<StandingOrderResponse>(endpoint, {\n      method: \"GET\",\n    });\n  }\n}\n","const B64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\nconst B64_LOOKUP = new Uint8Array(128);\nfor (let i = 0; i < B64_CHARS.length; i++) {\n  B64_LOOKUP[B64_CHARS.charCodeAt(i)] = i;\n}\n\nexport function base64ToBytes(base64: string): Uint8Array {\n  let str = base64.replace(/=+$/, '');\n  const len = str.length;\n  const bytes = new Uint8Array(Math.floor((len * 3) / 4));\n  let p = 0;\n\n  for (let i = 0; i < len; i += 4) {\n    const a = B64_LOOKUP[str.charCodeAt(i)];\n    const b = B64_LOOKUP[str.charCodeAt(i + 1)];\n    const c = B64_LOOKUP[str.charCodeAt(i + 2)];\n    const d = B64_LOOKUP[str.charCodeAt(i + 3)];\n\n    bytes[p++] = (a << 2) | (b >> 4);\n    if (i + 2 < len) bytes[p++] = ((b & 0x0f) << 4) | (c >> 2);\n    if (i + 3 < len) bytes[p++] = ((c & 0x03) << 6) | d;\n  }\n\n  return bytes;\n}\n\nexport function bytesToBase64(bytes: Uint8Array): string {\n  let result = '';\n  const len = bytes.length;\n\n  for (let i = 0; i < len; i += 3) {\n    const a = bytes[i];\n    const b = i + 1 < len ? bytes[i + 1] : 0;\n    const c = i + 2 < len ? bytes[i + 2] : 0;\n\n    result += B64_CHARS[a >> 2];\n    result += B64_CHARS[((a & 0x03) << 4) | (b >> 4)];\n    result += i + 1 < len ? B64_CHARS[((b & 0x0f) << 2) | (c >> 6)] : '=';\n    result += i + 2 < len ? B64_CHARS[c & 0x3f] : '=';\n  }\n\n  return result;\n}\n\nexport function hexToBytes(hex: string): Uint8Array {\n  const bytes = new Uint8Array(hex.length / 2);\n  for (let i = 0; i < bytes.length; i++) {\n    bytes[i] = parseInt(hex.substr(i * 2, 2), 16);\n  }\n  return bytes;\n}\n\nexport function bytesToHex(bytes: Uint8Array): string {\n  let result = '';\n  for (let i = 0; i < bytes.length; i++) {\n    result += bytes[i].toString(16).padStart(2, '0');\n  }\n  return result;\n}\n\nexport function base64ToUtf8(base64: string): string {\n  return new TextDecoder().decode(base64ToBytes(base64));\n}\n\nexport function utf8ToBytes(str: string): Uint8Array {\n  return new TextEncoder().encode(str);\n}\n","import { Keypair } from '@solana/web3.js';\nimport { base64ToBytes } from '../encoding';\n\nexport interface SolanaKeyPair extends Keypair {}\n\nexport const generateSolanaKeyPair = async (): Promise<SolanaKeyPair> => {\n  try {\n    const keypair = Keypair.generate();\n    \n    return keypair;\n  } catch (error) {\n    throw new Error(`Failed to generate Solana key pair: ${error}`);\n  }\n};\n\nexport const createKeypairFromPrivateKey = (privateKey: string): Keypair => {\n  try {\n    const secretKey = base64ToBytes(privateKey);\n    return Keypair.fromSecretKey(secretKey);\n  } catch (error) {\n    throw new Error(`Failed to create keypair from private key: ${error}`);\n  }\n};","import { GridApiClient } from '../api/grid-api-client';\nimport {\n  AuthorizationError,\n  InitAuthResponse,\n  CompleteAuthResponse,\n  UniversalKeyPair,\n  SessionSecrets,\n  CompleteAuthRequestWithOtp,\n  CompleteAuthAndCreateAccountRequest,\n  ProviderError,\n  SignerProvider,\n  TaggedKeyPair,\n  KeyPairTag,\n  CompleteAuthAndCreateAccountResponse,\n} from '../types';\nimport { PrivyInitAuthRequest, PrivyCompleteAuthRequest } from '../types/privy';\nimport { TurnkeyInitAuthRequest, TurnkeyCompleteAuthRequest } from '../types/turnkey';\nimport { generateHPKEKeyPair, generateTurnkeyKeyPair } from '@sqds/grid-crypto';\nimport { generateSolanaKeyPair } from '../utils/crypto/solana-crypto';\nimport { bytesToHex } from '../utils/encoding';\n\n/**\n * Authentication request parameters for various providers.\n * @property {string} [email] - User email for email-based authentication\n * @property {UniversalKeyPair} [keypair] - Key pair for cryptographic authentication\n * @property {string} [passkeyId] - Passkey identifier for passkey authentication\n * @property {SignerProvider} [provider] - Authentication provider type\n * @property {number} [expiration] - Authentication expiration timestamp\n */\nexport interface AuthenticationRequest {\n  email?: string;\n  keypair?: UniversalKeyPair;\n  passkeyId?: string;\n  provider?: SignerProvider;\n  expiration?: number;\n  smartAccountAddress?: string;\n}\n\n/**\n * @hidden\n */\nexport interface AuthenticationContext {\n  provider: SignerProvider;\n  sessionId?: string;\n  authPublicKey?: string;\n  email?: string;\n  keypair?: UniversalKeyPair;\n}\n\n/**\n * @hidden\n */\nexport class AuthenticationManager {\n  private gridApiClient: GridApiClient;\n  private currentContext?: AuthenticationContext;\n\n  constructor(apiClient: GridApiClient) {\n    this.gridApiClient = apiClient;\n  }\n\n  /**\n   * Smart authentication routing based on request type\n   */\n  async authenticate(request: AuthenticationRequest): Promise<InitAuthResponse> {\n    try {\n      // Determine authentication type\n      const authType = this.determineAuthType(request);\n      \n      switch (authType) {\n        case 'privy':\n        case 'turnkey':\n          return  await this.initiateEmailAuth(request.email!, authType, request.expiration, request.smartAccountAddress)\n        \n        case 'solana':\n          return await this.validateEOAWallet(request.keypair!)\n        \n        case 'passkey':\n          return await this.initiatePasskeyAuth(request.passkeyId!)\n        \n        default:\n          throw new AuthorizationError(`Unsupported authentication type: ${authType}`, 'UNSUPPORTED_AUTH_TYPE');\n      }\n    } catch (error: any) {\n      if (error instanceof AuthorizationError) throw error;\n      throw new AuthorizationError(\n        error.message || \"Authentication failed\",\n        'AUTHENTICATION_FAILED',\n        undefined,\n        error instanceof Error ? error : undefined\n      );\n    }\n  }\n\n  /**\n   * Complete authentication based on provider type\n   */\n  async complete(request: CompleteAuthRequestWithOtp | CompleteAuthAndCreateAccountRequest): Promise<CompleteAuthResponse> {\n    const { user } = request as CompleteAuthAndCreateAccountRequest;\n\n    // Simplified Privy-only implementation for now\n    if (user.provider === 'privy') {\n      return await this.completePrivyAuth(request);\n    } else if (user.provider === 'turnkey') {\n\n      return await this.completeTurnkeyAuth(request, user.otpId);\n    } else {\n      throw new AuthorizationError('Unsupported provider', 'UNSUPPORTED_PROVIDER');\n    }\n  }\n\n  /**\n   * Complete authentication and create account\n   */\n  async completeAndCreateAccount(request: CompleteAuthAndCreateAccountRequest): Promise<CompleteAuthAndCreateAccountResponse> {\n    // Simplified Privy-only implementation for now\n    return this.completePrivyAuthAndCreateAccount(request);\n  }\n\n  /**\n   * Generate keypairs for all supported providers with appropriate tagging\n   * Returns an array of tagged keypairs for privy (primary), turnkey (backup), solana, and passkey\n   */\n  async generateSessionSecrets(): Promise<SessionSecrets> {\n    const providers: Array<{ type: SignerProvider, tag: KeyPairTag }> = [\n      { type: 'privy', tag: 'primary' },\n      { type: 'turnkey', tag: 'backup' },\n      { type: 'solana', tag: 'solana' },\n      { type: 'passkey', tag: 'passkey' }\n    ];\n\n    const keyPairs: TaggedKeyPair[] = [];\n\n    for (const { type, tag } of providers) {\n      try {\n        const keyPair = await this.generateKeyPair(type);\n        keyPairs.push({\n          publicKey: keyPair.publicKey,\n          privateKey: keyPair.privateKey,\n          publicKeyUncompressed: keyPair.publicKeyUncompressed,\n          provider: type,\n          tag: tag\n        });\n      } catch (error: any) {\n        console.warn(`⚠️ Failed to generate keypair with ${type} provider:`, error.message);\n        // Continue with other providers instead of failing completely\n      }\n    }\n\n    if (keyPairs.length === 0) {\n      throw new ProviderError(\n        'Failed to generate keypairs with any provider. Please check provider configurations.',\n        'privy'\n      );\n    }\n\n    return keyPairs;\n  }\n\n  /**\n   * Generate keypair for specific provider\n   */\n  async generateKeyPair(provider: SignerProvider): Promise<UniversalKeyPair> {\n    switch (provider) {\n      case 'privy':\n        // For now, use HPKE key pair generation\n        const hpkeKeyPair = await generateHPKEKeyPair();\n        return {\n          publicKey: hpkeKeyPair.publicKey,\n          privateKey: hpkeKeyPair.privateKey\n        };\n      \n      case 'turnkey':\n        return generateTurnkeyKeyPair();\n      \n      case 'solana':\n        const solanaKp = await generateSolanaKeyPair();\n        return {\n          publicKey: solanaKp.publicKey.toString(),\n          privateKey: bytesToHex(solanaKp.secretKey)\n        };\n\n      case 'passkey':\n        const passkeyKp = await generateSolanaKeyPair();\n        return {\n          publicKey: passkeyKp.publicKey.toString(),\n          privateKey: bytesToHex(passkeyKp.secretKey)\n        };\n      \n      default:\n        throw new AuthorizationError(\n          `Keypair generation not supported for provider: ${provider}`,\n          'UNSUPPORTED_PROVIDER'\n        );\n    }\n  }\n\n  // Private methods for each authentication type\n\n  private async initiateEmailAuth(\n    email: string,\n    provider: 'privy' | 'turnkey',\n    expiration?: number,\n    smartAccountAddress?: string\n  ): Promise<InitAuthResponse> {\n\n    // Generate auth keypair for the provider\n    const authKeyPair = await this.generateKeyPair(provider);\n\n    // Store context\n    this.currentContext = {\n      provider,\n      email,\n      authPublicKey: authKeyPair.publicKey\n    };\n\n    // Call appropriate API method\n    if (provider === 'privy') {\n      const request: PrivyInitAuthRequest = {\n        email,\n        expiration,\n        smartAccountAddress\n      };\n      const response = await this.gridApiClient.initAuthWithPrivy(request);\n\n      return response;\n    } else {\n      const request: TurnkeyInitAuthRequest = {\n        email,\n        // expiration,\n        provider,\n        smartAccountAddress\n      };\n      const response = await this.gridApiClient.initAuthWithTurnkey(request);\n\n      return response;\n    }\n  }\n\n  private async validateEOAWallet(keypair: UniversalKeyPair): Promise<InitAuthResponse> {\n    // For EOA wallets, we just validate the keypair\n    if (!keypair.publicKey || !keypair.privateKey) {\n      throw new AuthorizationError(\n        'Invalid keypair: missing public or private key',\n        'INVALID_KEYPAIR'\n      );\n    }\n\n    // Store context\n    this.currentContext = {\n      provider: 'solana',\n      keypair\n    };\n\n    // No actual authentication needed for EOA\n    return {\n      data: {\n        authenticated: true,\n        provider: 'solana',\n        publicKey: keypair.publicKey\n      }\n    };\n  }\n\n  private async initiatePasskeyAuth(passkeyId: string): Promise<InitAuthResponse> {\n    throw new AuthorizationError(\n      'Passkey authentication not yet implemented',\n      'NOT_IMPLEMENTED'\n    );\n  }\n\n  private async completePrivyAuth(request: CompleteAuthRequestWithOtp | CompleteAuthAndCreateAccountRequest): Promise<any> {\n    const { otpCode, user, sessionSecrets } = request as CompleteAuthAndCreateAccountRequest;\n    \n    // Extract email from context or user\n    const email = user.email ?? this.currentContext?.email ;\n    if (!email) {\n      throw new AuthorizationError('Email is required for Privy authentication', 'MISSING_EMAIL');\n    }\n\n    // Find privy keypair\n    const privyKeypair = sessionSecrets.find(kp => kp.provider === 'privy');\n    if (!privyKeypair) {\n      throw new AuthorizationError('Privy keypair not found', 'MISSING_KEYPAIR');\n    }\n\n    const smartAccountAddress = (request as CompleteAuthRequestWithOtp).smartAccountAddress;\n\n    const privyRequest: PrivyCompleteAuthRequest = {\n      email,\n      otpCode,\n      authPublicKey: privyKeypair.publicKey,\n      smartAccountAddress\n    };\n\n    const response = await this.gridApiClient.completePrivyAuth(privyRequest);\n\n    return response;\n  }\n\n  private async completeTurnkeyAuth(request: CompleteAuthRequestWithOtp | CompleteAuthAndCreateAccountRequest, otpId?: string): Promise<any> {\n    const { otpCode, user, sessionSecrets } = request as CompleteAuthAndCreateAccountRequest;\n\n    // Extract email from context or user\n    const email = user.email ?? this.currentContext?.email;\n    if (!email) {\n      throw new AuthorizationError('Email is required for Turnkey authentication', 'MISSING_EMAIL');\n    }\n\n    // Validate required fields\n    if (!otpId) {\n      throw new AuthorizationError('OTP ID is required for Turnkey authentication', 'MISSING_OTP_ID');\n    }\n\n    // Find turnkey keypair\n    const turnkeyKeypair = sessionSecrets.find(kp => kp.provider === 'turnkey');\n    if (!turnkeyKeypair) {\n      throw new AuthorizationError('Turnkey keypair not found', 'MISSING_KEYPAIR');\n    }\n\n    if (!turnkeyKeypair.publicKeyUncompressed) {\n      throw new AuthorizationError('Turnkey public key uncompressed is required', 'MISSING_PUBLIC_KEY');\n    }\n\n    const smartAccountAddress = (request as CompleteAuthRequestWithOtp).smartAccountAddress;\n\n    // TODO: These would need to come from the initAuth response in real implementation\n    const turnkeyRequest: TurnkeyCompleteAuthRequest = {\n      otpId: otpId,\n      otpCode: otpCode,\n      email: email,\n      authPublicKey: turnkeyKeypair.publicKeyUncompressed,\n      smartAccountAddress\n    };\n\n    const response = await this.gridApiClient.completeTurnkeyAuth(turnkeyRequest);\n\n    return response;\n  }\n\n  private async completePrivyAuthAndCreateAccount(request: CompleteAuthAndCreateAccountRequest): Promise<CompleteAuthAndCreateAccountResponse> {\n    const { otpCode, user, sessionSecrets } = request;\n\n    const email = user.email ?? this.currentContext?.email;\n    if (!email) {\n      throw new AuthorizationError('Email is required', 'MISSING_EMAIL');\n    }\n\n    const privyKeypair = sessionSecrets.find(kp => kp.provider === 'privy');\n    if (!privyKeypair) {\n      throw new AuthorizationError('Privy keypair not found', 'MISSING_KEYPAIR');\n    }\n\n    const privyRequest: PrivyCompleteAuthRequest = {\n      email,\n      otpCode,\n      authPublicKey: privyKeypair.publicKey\n    };\n\n    const response = await this.gridApiClient.completePrivyAuthAndCreateAccount(privyRequest);\n\n    return response;\n  }\n\n  private determineAuthType(request: AuthenticationRequest): SignerProvider {\n    // Explicit provider\n    if (request.provider) {\n      return request.provider;\n    }\n\n    // Email-based auth (default to privy)\n    if (request.email) {\n      return 'privy';\n    }\n\n    // EOA wallet\n    if (request.keypair) {\n      return 'solana';\n    }\n\n    // Passkey\n    if (request.passkeyId) {\n      return 'passkey';\n    }\n\n    throw new AuthorizationError(\n      'Unable to determine authentication type from request',\n      'AMBIGUOUS_AUTH_REQUEST'\n    );\n  }\n  // Getters for current context\n  getCurrentProvider(): SignerProvider | undefined {\n    return this.currentContext?.provider;\n  }\n\n  getCurrentContext(): AuthenticationContext | undefined {\n    return this.currentContext;\n  }\n\n  clearContext(): void {\n    this.currentContext = undefined;\n  }\n}","import { Keypair, VersionedTransaction, PublicKey } from '@solana/web3.js';\nimport {\n  AuthorizationError,\n  UniversalKeyPair,\n  TaggedKeyPair,\n  SignerProvider,\n  KmsPayload,\n  BaseResponse\n\n} from '../types';\nimport { base64ToBytes, bytesToBase64, hexToBytes, base64ToUtf8 } from '../utils/encoding';\nimport { PrivyInternalSignRequest } from '../types/privy';\nimport { signWithDecryptedAuthorizationKey, decryptTurnkeyCredentials, getPublicKeyFromDecryptedData, signWithApiKey  } from '@sqds/grid-crypto';\n\n/**\n * Sign Request\n * @property {TaggedKeyPair[] | Keypair[]} sessionSecrets - Secrets generated via generateSessionSecrets()\n * @property {any[]} [session] - Optional session data from authentication via initAuth()\n * @property {TransactionPayload} transactionPayload - Transaction data to be signed and sent\n * @property {SignerProvider} provider - Provider to use for signing (privy, turnkey)\n */\nexport interface SignRequest {\n  sessionSecrets: TaggedKeyPair[] | Keypair[];\n  session?: any[];  // Session data from authentication\n  transactionPayload: TransactionPayload;\n  provider?: SignerProvider;\n}\n\n/**\n * Request to sign and send a transaction to the blockchain.\n * @property {TaggedKeyPair[] | Keypair[]} sessionSecrets - Cryptographic keys for signing\n * @property {any[]} [session] - Optional session data from authentication\n * @property {TransactionPayload} transactionPayload - Transaction data to be signed and sent\n * @property {string} address - Target address for the transaction\n */\nexport interface SignAndSendRequest {\n  sessionSecrets: TaggedKeyPair[] | Keypair[];\n  session?: any[];  // Session data from authentication\n  transactionPayload: TransactionPayload;\n  address: string;\n}\n\n/**\n * @hidden\n */\nexport interface SignatureResult {\n  provider: SignerProvider;\n  signature: string;\n  publicKey: string;\n  timestamp: number;\n}\n\n/**\n * @hidden\n */\nexport interface SignResult {\n  signatures: SignatureResult[];\n  payload?: string;\n  aggregatedSignature?: string;\n}\n\n/**\n * Transaction payload containing the transaction data and required signatures.\n * @property {string} transaction - Serialized transaction data\n * @property {string[]} transactionSigners - Array of signer public keys\n * @property {KmsPayload[]} kmsPayloads - Key management service payloads for signing\n *\n * @example\n * ```typescript\n * const payload: TransactionPayload = {\n *   transaction: 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAQABBCk...',\n *   transactionSigners: ['5FHwkrdxntdK24hgQU8qgBjn35Y1zwhz1GZwCkP2UJnM'],\n *   kmsPayloads: [\n *     {\n *       provider: 'privy',\n *       address: '5FHwkrdxntdK24hgQU8qgBjn35Y1zwhz1GZwCkP2UJnM',\n *       payload: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'\n *     }\n *   ]\n * };\n * ```\n */\nexport interface TransactionPayload {\n  transaction: string;\n  transactionSigners: string[];\n  kmsPayloads: KmsPayload[];\n}\n\nexport interface TransactionResponse extends BaseResponse <TransactionPayload> {}\n/**\n * @hidden\n */\nenum KmsProvider {\n  PRIVY = 'privy',\n  TURNKEY = 'turnkey'\n}\n\n/**\n * @hidden\n */\nexport interface TurnkeyKmsSignedPayload {\n  public_key: string;\n  signature: string;\n  timestamp_ms: string;\n}\n\n/**\n * @hidden\n */\nexport interface PrivyKmsSignedPayload {\n  signature: string;\n}\n\n/**\n * @hidden\n */\nexport interface KmsSingature {\n  provider: KmsProvider;\n  kms_signed_payload?: TurnkeyKmsSignedPayload | PrivyKmsSignedPayload;\n  signature?: string;\n}\n\n/**\n * Result of a transaction signing operation.\n * @property {string} transaction - The signed transaction data\n * @property {KmsSingature[]} kmsPayloads - Array of KMS signature payloads\n */\nexport interface TransactionResult {\n  transaction: string;\n  kmsPayloads: KmsSingature[];\n}\n\n/**\n * @hidden\n */\nexport class SigningManager {\n  constructor() {\n  }\n\n  /**\n   * Get signers that haven't signed the transaction yet\n   */\n  private getUnsignedSigners(transaction: string, requestedSigners: string[]): string[] {\n    try {\n      const transactionBytes = base64ToBytes(transaction);\n      const versionedTransaction = VersionedTransaction.deserialize(transactionBytes);\n\n      const accountKeys = versionedTransaction.message.staticAccountKeys;\n      const signatures = versionedTransaction.signatures;\n\n      console.log(`🔍 Transaction has ${signatures.length} signature slots for ${accountKeys.length} account keys`);\n\n      return requestedSigners.filter(signer => {\n        try {\n          const signerPubkey = new PublicKey(signer);\n          const signerIndex = accountKeys.findIndex(key => key.equals(signerPubkey));\n\n          if (signerIndex === -1) {\n            console.log(`❌ Signer ${signer} not found in transaction account keys`);\n            return false;\n          }\n\n          const signature = signatures[signerIndex];\n\n          // Check if signature is actually present and valid\n          const isValidSignature = signature !== null &&\n                                  signature.length > 0 &&\n                                  !this.isEmptySignature(signature);\n\n          console.log(`🔍 Signer ${signer} at index ${signerIndex}: signature ${isValidSignature ? 'present' : 'missing'}`);\n\n          // Return true if signer needs to sign (signature is missing or empty)\n          return !isValidSignature;\n        } catch (error) {\n          // Invalid public key, skip\n          console.warn(`Invalid public key in signer list: ${signer}`);\n          return false;\n        }\n      });\n    } catch (error) {\n      // If we can't deserialize the transaction, return all signers (fallback behavior)\n      console.warn('Failed to deserialize transaction for signature checking, falling back to all signers');\n      return requestedSigners;\n    }\n  }\n\n  /**\n   * Check if a signature is empty (all zeros or placeholder)\n   */\n  private isEmptySignature(signature: Uint8Array): boolean {\n    // Check if signature is all zeros (64 bytes for Ed25519)\n    if (signature.length !== 64) return true;\n\n    return signature.every(byte => byte === 0);\n  }\n\n  /**\n   * Check if a specific public key has already signed the transaction\n   */\n  private hasPublicKeySigned(transaction: string, pubkey: string): boolean {\n    try {\n      const transactionBytes = base64ToBytes(transaction);\n      const versionedTransaction = VersionedTransaction.deserialize(transactionBytes);\n\n      const accountKeys = versionedTransaction.message.staticAccountKeys;\n      const signatures = versionedTransaction.signatures;\n\n      const signerPubkey = new PublicKey(pubkey);\n      const signerIndex = accountKeys.findIndex(key => key.equals(signerPubkey));\n\n      if (signerIndex === -1) return false;\n\n      const signature = signatures[signerIndex];\n      const isValidSignature = signature !== null &&\n                              signature.length > 0 &&\n                              !this.isEmptySignature(signature);\n\n      return isValidSignature;\n    } catch (error) {\n      return false;\n    }\n  }\n\n  /**\n   * Smart signing with automatic provider selection based on session\n   */\n  async sign(request: SignRequest): Promise<TransactionResult> {\n    const provider = request.provider;\n    // Support both 'payload' and 'transaction' for backward compatibility\n    const transaction = request.transactionPayload.transaction;\n    const transactionSigners = request.transactionPayload.transactionSigners;\n    const kmsPayloads = request.transactionPayload.kmsPayloads;\n    const { sessionSecrets, session } = request;\n\n    // Validate inputs\n    if (!transaction && !kmsPayloads) {\n      throw new AuthorizationError('Payload is required for signing', 'MISSING_PAYLOAD');\n    }\n\n    if (!sessionSecrets || sessionSecrets.length === 0) {\n      throw new AuthorizationError('At least one keypair is required for signing', 'NO_KEYPAIRS');\n    }\n\n    const signatures: KmsSingature[] = [];\n    let signedTransaction = transaction;\n\n    // Filter out signers that have already signed the transaction\n    const unsignedSigners = this.getUnsignedSigners(transaction, transactionSigners);\n\n    console.log(`🔍 Signing check: ${transactionSigners.length} total signers, ${unsignedSigners.length} unsigned signers`);\n    if (transactionSigners.length > unsignedSigners.length) {\n      const alreadySigned = transactionSigners.filter(signer => !unsignedSigners.includes(signer));\n      console.log(`✅ Already signed by: ${alreadySigned.join(', ')}`);\n    }\n\n    if (unsignedSigners.length === 0) {\n      console.log('✅ All required signers have already signed the transaction');\n      return {\n        transaction: signedTransaction,\n        kmsPayloads: signatures\n      };\n    }\n\n    await Promise.all(unsignedSigners.map(async signer => {\n      \n      if (kmsPayloads && kmsPayloads.length > 0) {\n        const kmsPayload = kmsPayloads.find(kp => kp.address === signer) || kmsPayloads.find(kp => kp.provider === provider);  \n\n        if (kmsPayload) {\n          switch (kmsPayload.provider) {\n            case 'privy':\n              const keypair = sessionSecrets.find(kp => (kp as TaggedKeyPair).provider === 'privy');\n              \n              const signature = await this.signWithPrivyProvider(kmsPayload.payload, keypair as TaggedKeyPair, session);\n              signatures.push({\n                provider: KmsProvider.PRIVY,\n                signature\n              });\n              break;\n            case 'turnkey':\n              const turnkeyKeypair = sessionSecrets.find(kp => (kp as TaggedKeyPair).provider === 'turnkey');\n              const turnkeySignature = await this.signWithTurnkeyProvider(kmsPayload.payload, turnkeyKeypair as any, session, Date.now());\n              signatures.push({\n                provider: KmsProvider.TURNKEY,\n                kms_signed_payload: JSON.parse(turnkeySignature.signature) as TurnkeyKmsSignedPayload\n              });\n              break;\n            case 'passkey':\n              const passkeyKeypair = sessionSecrets.find(kp => (kp as TaggedKeyPair).provider === 'passkey') as TaggedKeyPair;\n              const secretKeyBytes = hexToBytes(passkeyKeypair.privateKey!);\n              // Create Solana Keypair from the secret key bytes\n              const convertedPasskeyKeypair = Keypair.fromSecretKey(secretKeyBytes);\n                if (!convertedPasskeyKeypair) {\n                  throw new AuthorizationError(\n                    `No keypair found for external signer: ${signer}`,\n                    'KEYPAIR_NOT_FOUND'\n                  );\n                }\n                signedTransaction = await this.signWithSolanaProvider(transaction, convertedPasskeyKeypair);\n              break;\n            case 'external':\n              const solanaKeypair = sessionSecrets.find(kp => (kp as Keypair).publicKey.toString() === signer) as Keypair;\n              if (!solanaKeypair) {\n                throw new AuthorizationError(\n                  `No keypair found for external signer: ${signer}`,\n                  'KEYPAIR_NOT_FOUND'\n                );\n              }\n              signedTransaction = await this.signWithSolanaProvider(transaction, solanaKeypair);\n              break;\n            default:\n              throw new AuthorizationError(\n                `Unsupported provider for signing`,\n                'UNSUPPORTED_PROVIDER'\n              );\n              \n          }\n        }\n      } else {\n        const solanaKeypair = sessionSecrets.find(kp => (kp as Keypair).publicKey.toString() === signer) as Keypair;\n        if (!solanaKeypair) {\n          throw new AuthorizationError(\n            `No keypair found for external signer: ${signer}`,\n            'KEYPAIR_NOT_FOUND'\n          );\n        }\n        signedTransaction = await this.signWithSolanaProvider(transaction, solanaKeypair);\n      }\n    }));\n\n    const transactionResult: TransactionResult = {\n      transaction: signedTransaction,\n      kmsPayloads: signatures\n    };\n\n    return transactionResult;\n  }\n\n  /**\n   * Privy signing implementation using local PrivyProvider\n   */\n  private async signWithPrivyProvider(\n    transaction: any,\n    keypair: TaggedKeyPair,\n    session: any[] | undefined,\n    // timestamp: number\n  ): Promise<string> {\n    // Check if we have session-based signing available\n    if (session && session.length > 0) {\n      // Find Privy session\n      const privySession = session.find(s => s.session?.Privy);\n      if (privySession?.session?.Privy?.session?.encrypted_authorization_key) {\n        // Use encrypted authorization key for signing\n        const authKey = privySession.session.Privy.session.encrypted_authorization_key;\n        const privyRequest: PrivyInternalSignRequest = {\n          transaction: typeof transaction === 'string' ? transaction : JSON.stringify(transaction),\n          sessionSecrets: [keypair],\n          signers: [keypair],\n          authorizationKey: authKey\n        };\n\n        // Extract the Privy signing logic directly\n        try {\n          // Decrypt the authorization key using ChaCha20-Poly1305 HPKE\n          // Dynamic import for platform-specific crypto\n          const { hpkeChachaDecryptRN } = await import('@sqds/grid-crypto');\n          const decryptedBytes = await hpkeChachaDecryptRN(\n            authKey,\n            keypair.privateKey\n          );\n          const decryptedAuthKey = new TextDecoder().decode(decryptedBytes);\n          // Sign the payload directly\n          const signature = signWithDecryptedAuthorizationKey(transaction, decryptedAuthKey);\n          return signature;\n        } catch (error) {\n          const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n          throw new AuthorizationError(\n            `Privy signing failed: ${errorMessage}`,\n            'SIGNING_FAILED'\n          );\n        }\n      }\n    }\n\n    // Fallback to local signing if no session\n    if (!keypair.privateKey) {\n      throw new AuthorizationError(\n        'Private key required for Privy signing without session',\n        'MISSING_PRIVATE_KEY'\n      );\n    }\n\n    // Use direct signing for fallback\n    const signature = signWithDecryptedAuthorizationKey(typeof transaction === 'string' ? transaction : JSON.stringify(transaction), keypair.privateKey);\n    \n    return signature;\n  }\n\n  /**\n   * Turnkey signing implementation using local TurnkeyProvider\n   */\n  private async signWithTurnkeyProvider(\n    transaction: string,\n    keypair: UniversalKeyPair,\n    session: any[] | undefined,\n    timestamp: number\n  ): Promise<SignatureResult> {\n    // Validate inputs\n    if (!keypair.privateKey) {\n      throw new AuthorizationError(\n        'Private key required for Turnkey signing',\n        'MISSING_PRIVATE_KEY'\n      );\n    }\n\n    if (!session || session.length === 0) {\n      throw new AuthorizationError(\n        'Session required for Turnkey signing',\n        'MISSING_SESSION'\n      );\n    }\n\n    const turnkeySession = session.find(s => s.provider === 'turnkey')?.session?.Turnkey;\n    if (!turnkeySession) {\n      throw new AuthorizationError(\n        'Turnkey session not found',\n        'INVALID_SESSION'\n      );\n    }\n\n    const credentials = turnkeySession.credential_bundle;\n    if (!credentials) {\n      throw new AuthorizationError(\n        'Credential bundle not found in session',\n        'MISSING_CREDENTIALS'\n      );\n    }\n\n    try {\n      // Decode the base64 payload to get the Turnkey request body\n      const requestBody = JSON.parse(base64ToUtf8(transaction));\n\n      // Decrypt credentials to get API key\n      const decryptedData = await decryptTurnkeyCredentials(credentials, keypair.privateKey);\n\n      // Get public key and sign the request\n      const publicKey = await getPublicKeyFromDecryptedData(decryptedData);\n      const signature = await signWithApiKey({\n        payload: JSON.stringify(requestBody),\n        privateKey: decryptedData,\n      });\n\n      // Return stamped request\n      return {\n        provider: 'turnkey',\n        signature: JSON.stringify({\n          public_key: publicKey,\n          signature: signature,\n          timestamp_ms: requestBody.timestampMs || timestamp.toString(),\n        }),\n        publicKey: keypair.publicKey,\n        timestamp\n      };\n    } catch (error) {\n      const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n      throw new AuthorizationError(\n        `Turnkey signing failed: ${errorMessage}`,\n        'SIGNING_FAILED'\n      );\n    }\n  }\n\n  /**\n   * Solana signing implementation\n   */\n  private async signWithSolanaProvider(\n    transaction: string,\n    keypair: Keypair\n  ): Promise<string> {\n    try {\n      const transactionBytes = base64ToBytes(transaction);\n      const versionedTransaction = VersionedTransaction.deserialize(transactionBytes);\n      versionedTransaction.sign([keypair]);\n      const serializedTransaction = versionedTransaction.serialize();\n      return bytesToBase64(serializedTransaction);\n    } catch (error: any) {\n      throw new AuthorizationError(\n        `Failed to sign with Solana provider: ${error.message}`,\n        'SIGNING_FAILED'\n      );\n    }\n  }\n\n  /**\n   * Passkey signing implementation\n   */\n  private async signWithPasskeyProvider(\n    transaction: any,\n    keypair: TaggedKeyPair,\n    timestamp: number\n  ): Promise<SignatureResult> {\n    throw new AuthorizationError(\n      'Passkey signing not yet implemented',\n      'NOT_IMPLEMENTED'\n    );\n  }\n\n  /**\n   * Select keypairs based on session data\n   * Prioritizes signers by role (primary > backup) and matches addresses with authenticated wallets\n   */\n  private selectKeypairsFromSession(\n    keypairs: TaggedKeyPair[],\n    session?: any[],\n    transaction_signers?: string[]\n  ): TaggedKeyPair[] {\n    \n    // If transaction_signers are provided, use them to determine which providers to use\n    if (transaction_signers && transaction_signers.length > 0 && session && session.length > 0) {\n      return this.selectKeypairsFromTransactionSigners(keypairs, session, transaction_signers);\n    }\n    \n    // If no session, return all keypairs (for non-session based signing like Solana)\n    if (!session || session.length === 0) {\n      // Filter for non-session based providers\n      const nonSessionKeypairs = keypairs.filter(kp => \n        kp.provider === 'solana' || kp.provider === 'passkey'\n      );\n      return nonSessionKeypairs.length > 0 ? nonSessionKeypairs : keypairs;\n    }\n\n    let selected: TaggedKeyPair[] = [];\n\n    // Check each session entry and match with appropriate keypairs\n    for (const sessionEntry of session) {\n      \n      // Check for Privy session\n      if (sessionEntry.provider === 'privy' || sessionEntry.session?.Privy) {\n        const privySession = sessionEntry.session?.Privy;\n        const authenticatedWallets = privySession?.session?.wallets || [];\n        \n        \n        // Find keypairs that match authenticated Privy wallet addresses\n        const matchingPrivyKeypairs = keypairs.filter(kp => {\n          if (kp.provider !== 'privy') return false;\n          \n          // Check if keypair address matches any authenticated wallet address\n          const matchesWallet = authenticatedWallets.some((wallet: any) => \n            wallet.address === kp.publicKey || wallet.public_key === kp.publicKey\n          );\n          \n          return matchesWallet;\n        });\n        \n        // Prioritize by role: primary > backup > others\n        const sortedPrivyKeypairs = matchingPrivyKeypairs.sort((a, b) => {\n          const roleOrder = { primary: 1, backup: 2, solana: 3, passkey: 4 };\n          return (roleOrder[a.tag] || 99) - (roleOrder[b.tag] || 99);\n        });\n        \n        if (sortedPrivyKeypairs.length > 0) {\n          const selectedPrivyKeypair = sortedPrivyKeypairs[0];\n          if (!selected.includes(selectedPrivyKeypair)) {\n            selected.push(selectedPrivyKeypair);\n          }\n        }\n      }\n      \n      // Check for Turnkey session\n      if (sessionEntry.provider === 'turnkey' || sessionEntry.session?.Turnkey) {\n        const turnkeySession = sessionEntry.session?.Turnkey;\n        \n        // For Turnkey, we need to match based on provider and available session data\n        const matchingTurnkeyKeypairs = keypairs.filter(kp => kp.provider === 'turnkey');\n        \n        // Prioritize by role: primary > backup > others\n        const sortedTurnkeyKeypairs = matchingTurnkeyKeypairs.sort((a, b) => {\n          const roleOrder = { primary: 1, backup: 2, solana: 3, passkey: 4 };\n          return (roleOrder[a.tag] || 99) - (roleOrder[b.tag] || 99);\n        });\n        \n        if (sortedTurnkeyKeypairs.length > 0) {\n          const selectedTurnkeyKeypair = sortedTurnkeyKeypairs[0];\n          if (!selected.includes(selectedTurnkeyKeypair)) {\n            selected.push(selectedTurnkeyKeypair);\n          }\n        }\n      }\n      \n      // Check for other providers...\n    }\n\n    // If no session-matched keypairs found, check for EOA wallets\n    if (selected.length === 0) {\n      const eoaKeypairs = keypairs.filter(kp => \n        kp.provider === 'solana' || kp.provider === 'external'\n      );\n      if (eoaKeypairs.length > 0) {\n        selected = eoaKeypairs;\n      }\n    }\n\n    // Default to primary role keypairs if no selection made\n    if (selected.length === 0) {\n      const primaryKeypairs = keypairs.filter(kp => kp.tag === 'primary');\n      selected = primaryKeypairs.length > 0 ? primaryKeypairs : keypairs;\n    }\n\n    return selected;\n  }\n\n  /**\n   * Select keypairs based on transaction_signers addresses\n   * Matches transaction_signers to session wallet addresses to determine providers\n   */\n  private selectKeypairsFromTransactionSigners(\n    keypairs: TaggedKeyPair[],\n    session: any[],\n    transactionSigners: string[]\n  ): TaggedKeyPair[] {\n    const selected: TaggedKeyPair[] = [];\n    \n    // For each required transaction signer\n    for (const signerAddress of transactionSigners) {\n      \n      // Search through all sessions to find which provider has this signer\n      let providerFound: SignerProvider | null = null;\n      \n      for (const sessionEntry of session) {\n        // Check Privy session\n        if (sessionEntry.provider === 'privy' || sessionEntry.session?.Privy) {\n          const privySession = sessionEntry.session?.Privy;\n          const authenticatedWallets = privySession?.session?.wallets || [];\n          \n          const hasThisSigner = authenticatedWallets.some((wallet: any) => \n            wallet.address === signerAddress\n          );\n          \n          if (hasThisSigner) {\n            providerFound = 'privy';\n            break;\n          }\n        }\n        \n      }\n      \n      if (providerFound) {\n        // Find a keypair for this provider\n        const matchingKeypairs = keypairs.filter(kp => kp.provider === providerFound);\n        \n        // Prioritize by role: primary > backup > others\n        const sortedKeypairs = matchingKeypairs.sort((a, b) => {\n          const roleOrder = { primary: 1, backup: 2, solana: 3, passkey: 4 };\n          return (roleOrder[a.tag] || 99) - (roleOrder[b.tag] || 99);\n        });\n        \n        if (sortedKeypairs.length > 0) {\n          const selectedKeypair = sortedKeypairs[0];\n          \n          if (!selected.includes(selectedKeypair)) {\n            selected.push(selectedKeypair);\n          }\n        } else {\n          console.log(`⚠️  No ${providerFound} keypairs available for signer ${signerAddress}`);\n        }\n      } else {\n        console.log(`❌ Could not find provider for signer ${signerAddress}`);\n      }\n    }\n    \n    return selected;\n  }\n\n  /**\n   * Aggregate multiple signatures (for future use)\n   */\n  private aggregateSignatures(signatures: SignatureResult[]): string | undefined {\n    // This would implement signature aggregation logic\n    // For now, return undefined\n    return undefined;\n  }\n}","/**\n * @hidden\n * Lightweight EventEmitter implementation for SDK internal use\n * Provides type-safe event subscription and emission\n */\nexport class EventEmitter<EventMap extends Record<string, any>> {\n  private listeners: Map<keyof EventMap, Set<(data: any) => void>>;\n\n  constructor() {\n    this.listeners = new Map();\n  }\n\n  /**\n   * Subscribe to an event\n   * @param event - Event name to listen for\n   * @param handler - Callback function to execute when event is emitted\n   */\n  on<K extends keyof EventMap>(\n    event: K,\n    handler: (data: EventMap[K]) => void\n  ): void {\n    if (!this.listeners.has(event)) {\n      this.listeners.set(event, new Set());\n    }\n    this.listeners.get(event)!.add(handler);\n  }\n\n  /**\n   * Unsubscribe from an event\n   * @param event - Event name to stop listening for\n   * @param handler - The specific handler to remove\n   */\n  off<K extends keyof EventMap>(\n    event: K,\n    handler: (data: EventMap[K]) => void\n  ): void {\n    const handlers = this.listeners.get(event);\n    if (handlers) {\n      handlers.delete(handler);\n      if (handlers.size === 0) {\n        this.listeners.delete(event);\n      }\n    }\n  }\n\n  /**\n   * Emit an event to all subscribers\n   * @param event - Event name to emit\n   * @param data - Data to pass to event handlers\n   */\n  emit<K extends keyof EventMap>(event: K, data: EventMap[K]): void {\n    const handlers = this.listeners.get(event);\n    if (handlers) {\n      handlers.forEach((handler) => handler(data));\n    }\n  }\n\n  /**\n   * Remove all listeners for all events\n   */\n  removeAllListeners(): void {\n    this.listeners.clear();\n  }\n}\n","import { EventEmitter } from \"../utils/event-emitter\";\nimport { GridClientContext, AccountState } from \"../types/common\";\n\n/**\n * @hidden\n * Event map for account state changes\n */\ninterface AccountEvents {\n  change: AccountState;\n}\n\n/**\n * @hidden\n * Manages account state with reactive updates via events\n *\n * Important: Does not cache state. Always derives from shared context for safe singleton usage.\n *\n * @example\n * ```typescript\n * const state = client.account.get();\n * console.log(state.accountAddress, state.isConnected);\n *\n * client.account.on('change', (state) => {\n *   console.log('Account changed:', state.accountAddress);\n * });\n *\n * client.account.set('account-address', 'grid-user-id');\n * client.account.disconnect();\n * ```\n */\nexport class AccountManager {\n  private context: GridClientContext;\n  private eventEmitter: EventEmitter<AccountEvents>;\n\n  constructor(context: GridClientContext) {\n    this.context = context;\n    this.eventEmitter = new EventEmitter<AccountEvents>();\n  }\n\n  /**\n   * Get current account state (always fresh from context)\n   *\n   * @returns Current account state\n   */\n  get(): AccountState {\n    const address = this.context.user?.address;\n    const gridUserId = this.context.user?.gridUserId;\n    const isConnected = !!(address && gridUserId);\n\n    return {\n      accountAddress: address,\n      gridUserId: gridUserId,\n      isConnected,\n    };\n  }\n\n  /**\n   * Set account state and emit change event\n   *\n   * @param address - Smart account address\n   * @param gridUserId - Grid user identifier\n   */\n  set(address: string, gridUserId: string): void {\n    if (!this.context.user) {\n      this.context.user = { signers: [] };\n    }\n\n    this.context.user.address = address;\n    this.context.user.gridUserId = gridUserId;\n\n    this.eventEmitter.emit('change', this.get());\n  }\n\n  /**\n   * Disconnect account and emit change event\n   *\n   * Note: Preserves other user context fields (signers, session, email) for re-authentication\n   */\n  disconnect(): void {\n    if (this.context.user) {\n      this.context.user.address = undefined;\n      this.context.user.gridUserId = undefined;\n    }\n\n    this.eventEmitter.emit('change', this.get());\n  }\n\n  /**\n   * Subscribe to account state changes\n   *\n   * @param event - Event name ('change')\n   * @param handler - Callback receiving new account state\n   */\n  on(event: 'change', handler: (state: AccountState) => void): void {\n    this.eventEmitter.on(event, handler);\n  }\n\n  /**\n   * Unsubscribe from account state changes\n   *\n   * @param event - Event name ('change')\n   * @param handler - Handler function to remove\n   */\n  off(event: 'change', handler: (state: AccountState) => void): void {\n    this.eventEmitter.off(event, handler);\n  }\n\n  /** @hidden Internal method to emit change events */\n  _emitChange(): void {\n    this.eventEmitter.emit('change', this.get());\n  }\n}\n","import { GridApiClient } from \"../api/grid-api-client\";\nimport {\n  AuthorizationError,\n  GridError,\n  UpdateAccountRequest,\n  GetAccountBalancesQueryParams,\n  GetTransfersOptions,\n  AccountBalancesData,\n  TransferResponse,\n  GetAccountResponse,\n  AccountBalancesResponse,\n  GetTransactionsResponse,\n} from \"../types\";\nimport {\n  GridClientContext,\n} from \"../types/common\";\nimport { TransactionPayload, TransactionResponse } from \"../managers/signing-manager\";\n\n/**\n * @hidden\n * Service handling account management operations\n */\nexport class AccountService {\n  private apiClient: GridApiClient;\n  private context: GridClientContext;\n\n  constructor(apiClient: GridApiClient, context: GridClientContext) {\n    this.apiClient = apiClient;\n    this.context = context;\n  }\n\n  /**\n   * Retrieves comprehensive account details including account type, policies,\n   * signers, thresholds, and metadata.\n   *\n   * @param accountAddress - The account address to retrieve information for\n   * @returns Promise resolving to account details\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const account = await gridClient.getAccount('account-address');\n   *   console.log('Account type:', account.type);\n   *   console.log('Signers:', account.policies?.signers);\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Failed to get account:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Account Management\n   */\n  async getAccount(accountAddress: string): Promise<GetAccountResponse> {\n    const response = await this.apiClient.getAccount(accountAddress);\n    return response;\n  }\n\n  /**\n   * Update account settings and configuration such as policies, signers, thresholds, and metadata.\n   *\n   * @param accountAddress - The account address to update\n   * @param request - Update request containing the fields to modify\n   * @param admin - Whether to perform the update with admin privileges (optional)\n   * @returns Promise resolving to transaction payload for the update operation\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const updateTx = await gridClient.updateAccount(accountAddress, {\n   *     threshold: 2\n   *   });\n   *   console.log('Update transaction:', updateTx.transaction);\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Failed to update account:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @example Admin update\n   * ```typescript\n   * const adminUpdateTx = await gridClient.updateAccount(\n   *   accountAddress,\n   *   { threshold: 1 },\n   *   true\n   * );\n   * ```\n   *\n   * @category Account Management\n   */\n  async updateAccount(\n    accountAddress: string,\n    request: UpdateAccountRequest,\n    admin?: boolean\n  ): Promise<TransactionResponse> {\n    const response = await this.apiClient.updateAccount(\n      accountAddress,\n      request,\n      admin\n    );\n    return response;\n  }\n\n  /**\n   * Get account token balances\n   *\n   * Retrieves the current token balances for an account, including both\n   * native SOL and SPL token balances. Supports filtering and pagination.\n   *\n   * @param accountAddress - The account address to get balances for\n   * @param queryParams - Optional query parameters for filtering and pagination\n   * @returns Promise resolving to account balances data\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const balances = await gridClient.getAccountBalances(accountAddress);\n   *   console.log('SOL balance:', balances.sol);\n   *   console.log('Token balances:', balances.tokens);\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Failed to get balances:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Account Management\n   */\n  async getAccountBalances(\n    accountAddress: string,\n    queryParams?: GetAccountBalancesQueryParams\n  ): Promise<AccountBalancesResponse> {\n    const response = await this.apiClient.getAccountBalances(\n      accountAddress,\n      queryParams\n    );\n\n    return response;\n  }\n\n  /**\n   * Retrieves the transaction history for an account, including incoming and\n   * outgoing transfers. Supports filtering by date range, token type, and pagination.\n   *\n   * @param accountAddress - The account address to get transfers for\n   * @param options - Optional filtering and pagination options\n   * @returns Promise resolving to array of transfer data\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const transfers = await gridClient.getTransfers(accountAddress);\n   *   transfers.forEach(transfer => {\n   *     console.log('Transfer:', transfer.id);\n   *   });\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Failed to get transfers:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @example With filtering\n   * ```typescript\n   * const transfers = await gridClient.getTransfers(accountAddress, {\n   *   limit: 10,\n   *   currency: 'usd'\n   * });\n   * ```\n   *\n   * @category Account Management\n   */\n  async getTransfers(\n    accountAddress: string,\n    options?: GetTransfersOptions\n  ): Promise<TransferResponse> {\n    const response = await this.apiClient.getTransfers(\n      accountAddress,\n      options\n    );\n    return response;\n  }\n\n  /**\n   * Retrieves the blockchain transaction history for an account\n   *\n   * Returns a list of Solana blockchain transactions associated with the account,\n   * including transaction signatures, statuses, and timestamps.\n   *\n   * @param accountAddress - The account address to get transactions for\n   * @returns Promise resolving to transaction history data\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const response = await gridClient.getTransactions(accountAddress);\n   *   if (response.data?.transactions) {\n   *     response.data.transactions.forEach(tx => {\n   *       console.log('Transaction:', tx.signature);\n   *       console.log('Status:', tx.status);\n   *       console.log('Created:', tx.createdAt);\n   *     });\n   *   }\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Failed to get transactions:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Account Management\n   */\n  async getTransactions(accountAddress: string): Promise<GetTransactionsResponse> {\n    const response = await this.apiClient.getTransactions(accountAddress);\n    return response;\n  }\n}\n","import { PublicKey } from '@solana/web3.js';\n\nexport class ValidationUtils {\n  static isValidPublicKey(publicKey: any): boolean {\n    try {\n      new PublicKey(publicKey);\n      return true;\n    } catch {\n      return false;\n    }\n  }\n\n  static isValidEmail(email: string): boolean {\n    const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n    return emailRegex.test(email);\n  }\n}","import { GridApiClient } from \"../api/grid-api-client\";\nimport {\n  AuthenticationManager,\n  AuthenticationRequest,\n} from \"../managers/authentication-manager\";\nimport { AccountManager } from \"../managers/account-manager\";\nimport {\n  InitAuthRequest,\n  InitAuthResponse,\n  CompleteAuthResponse,\n  UniversalKeyPair,\n  SessionSecrets,\n  CompleteAuthRequestWithOtp,\n  CompleteAuthAndCreateAccountRequest,\n  CompleteAuthAndCreateAccountResponse,\n  SignerProvider,\n  RefreshSessionRequest,\n  RefreshSessionResponse,\n  AuthorizationError,\n  GridError,\n  CreateAccountResponse,\n} from \"../types\";\nimport {\n  GridClientContext,\n  CreateAccountInput,\n  CreateAccountRequest,\n  EmailAccountRequest,\n  SignersAccountRequest,\n  AccountPolicies,\n} from \"../types/common\";\nimport { ValidationUtils } from \"../utils/validation\";\n\n/**\n * @hidden\n * Service handling authentication operations\n */\nexport class AuthService {\n  private apiClient: GridApiClient;\n  private authManager: AuthenticationManager;\n  private accountManager: AccountManager;\n  private context: GridClientContext;\n\n  constructor(\n    apiClient: GridApiClient,\n    authManager: AuthenticationManager,\n    accountManager: AccountManager,\n    context: GridClientContext\n  ) {\n    this.apiClient = apiClient;\n    this.authManager = authManager;\n    this.accountManager = accountManager;\n    this.context = context;\n  }\n\n  /**\n   * Initialize authentication for an existing user.\n   * This is the first step in the authentication process.\n   *\n   * Note: For new users, you must call createAccount first to create an account before initializing authentication. This method is only for authenticating existing users.\n   *\n   * @param request - Authentication request containing email, keypair, or passkey information\n   * @returns Promise resolving to authentication initialization response with OTP details\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const authData = await gridClient.initAuth({\n   *     email: 'user@example.com'\n   *   });\n   *   console.log('OTP sent:', authData.otpSent);\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Auth failed:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Authentication\n   */\n  async initAuth(\n    request: InitAuthRequest | AuthenticationRequest\n  ): Promise<InitAuthResponse> {\n    // Support both old and new request formats\n    const authRequest: AuthenticationRequest = {\n      email: (request as any).email,\n      keypair: (request as any).keypair,\n      passkeyId: (request as any).passkeyId,\n      provider: (request as any).provider,\n      expiration: (request as any).expiration,\n      smartAccountAddress: (request as any).smartAccountAddress,\n    };\n\n    const response = await this.authManager.authenticate(authRequest);\n\n    return response;\n  }\n\n  /**\n   * This is the second step in email-based authentication. Verifies the OTP\n   * code received via email and establishes an authenticated session.\n   *\n   * Note: For new users who need to create an account, use completeAuthAndCreateAccount instead, which completes authentication and creates the account in one step.\n   *\n   * @param request - Complete authentication request with OTP code and user context\n   * @returns Promise resolving to authentication completion response with session data\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const sessionSecrets = await gridClient.generateSessionSecrets();\n   *   const authResult = await gridClient.completeAuth({\n   *     otpCode: '123456',\n   *     user: userContext,\n   *     sessionSecrets: sessionSecrets\n   *   });\n   *   console.log('Authenticated address:', authResult.address);\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Authentication failed:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Authentication\n   */\n  async completeAuth(\n    request: CompleteAuthRequestWithOtp\n  ): Promise<CompleteAuthResponse> {\n    const result = await this.authManager.complete(request);\n\n    // Update account manager if auth was successful\n    if (result?.data?.address) {\n      const gridUserId = result.data.gridUserId;\n      if (gridUserId) {\n        this.accountManager.set(result.data.address, gridUserId);\n      }\n    }\n\n    return result;\n  }\n\n  /**\n   * Combines authentication completion with account creation for streamlined onboarding.\n   * This is useful when you want to authenticate and immediately create an account.\n   *\n   * @param request - Complete authentication and account creation request\n   * @returns Promise resolving to the created account information\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const sessionSecrets = await gridClient.generateSessionSecrets();\n   *   const account = await gridClient.completeAuthAndCreateAccount({\n   *     otpCode: '123456',\n   *     user: userContext,\n   *     sessionSecrets: sessionSecrets\n   *   });\n   *   console.log('Account created:', account.address);\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Account creation failed:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Authentication\n   */\n  async completeAuthAndCreateAccount(\n    request: CompleteAuthAndCreateAccountRequest\n  ): Promise<CompleteAuthAndCreateAccountResponse> {\n    const result = await this.authManager.completeAndCreateAccount(request);\n\n    // Update context with account info if available\n    if (result?.data.address) {\n      this.context.user.address = result.data.address;\n\n      // Update account manager (triggers events for useAccount hook)\n      const gridUserId = result.data.gridUserId;\n      if (gridUserId) {\n        this.accountManager.set(result.data.address, gridUserId);\n      }\n    }\n\n    return result;\n  }\n\n  /**\n   * Refreshes an MPC provider session to extend its lifetime\n   *\n   * This method refreshes authentication sessions for MPC providers like Privy,\n   * updating authorization keys and tokens. The refreshed session is automatically\n   * stored in the client context.\n   *\n   * Note: Currently only supports Privy sessions. Turnkey refresh is not yet implemented.\n   *\n   * @param request - Session refresh request with KMS provider and encryption key\n   * @returns Promise resolving to refreshed session data\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const refreshRequest: RefreshSessionRequest = {\n   *     kmsPayload: {\n   *       provider: 'privy',\n   *       session: {\n   *         userId: 'user-id',\n   *         session: currentSession,\n   *         token: 'jwt-token',\n   *         privyAccessToken: 'access-token',\n   *         refreshToken: 'refresh-token'\n   *       }\n   *     },\n   *     encryptionPublicKey: encryptionKey\n   *   };\n   *   const refreshedSession = await gridClient.refreshSession(refreshRequest);\n   *   console.log('Session refreshed successfully');\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Session refresh failed:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Authentication\n   */\n  async refreshSession(\n    request: RefreshSessionRequest\n  ): Promise<RefreshSessionResponse> {\n    const response = await this.apiClient.refreshSession(request);\n\n    // Update context with new session\n    const sessionData = response.data.kmsPayload.session;\n\n    // Extract the Session object based on provider type\n    if ('session' in sessionData) {\n      // This is a PrivyRefreshSession or TurnkeyRefreshSession\n      this.context.user.session = (sessionData as any).session;\n    }\n\n    return response;\n  }\n\n  /**\n   * Generate session secrets for all supported providers\n   *\n   * @returns Promise resolving to an array of secrets for different providers\n   *\n   * @example\n   * ```typescript\n   * const sessionSecrets = await gridClient.generateSessionSecrets();\n   * ```\n   *\n   * @category Key Management\n   */\n  async generateSessionSecrets(): Promise<SessionSecrets> {\n    return await this.authManager.generateSessionSecrets();\n  }\n\n  /**\n   * @hidden\n   * Generate a keypair for a specific provider\n   *\n   * Creates a new keypair for the specified authentication provider.\n   * If no provider is specified, defaults to Privy.\n   *\n   * @param provider - Optional provider type ('privy', 'turnkey', 'solana', 'passkey')\n   * @returns Promise resolving to a universal keypair with public and private keys\n   *\n   * @example\n   * ```typescript\n   * const keypair = await gridClient.generateKeyPair();\n   *\n   * const backupKeypair = await gridClient.generateKeyPair('turnkey');\n   *\n   * console.log(keypair.publicKey);\n   * ```\n   *\n   * @category Key Management\n   */\n  async generateKeyPair(provider?: SignerProvider): Promise<UniversalKeyPair> {\n    // Default to privy if no provider specified\n    const targetProvider = provider || \"privy\";\n    return await this.authManager.generateKeyPair(targetProvider);\n  }\n\n  /**\n   * Creates either an email-based account (requires OTP verification)\n   * or a signer-based account (immediately active).\n   *\n   * @param input - Account creation input (simplified) or full request object with policies\n   * @returns Promise resolving to created account information\n   *\n   * Note: When passing AccountPolicies with signers, role defaults to 'primary' and provider defaults to 'external' if not specified.\n   *\n   * @example Email account\n   * ```typescript\n   * try {\n   *   const emailAccount = await gridClient.createAccount({\n   *     email: 'user@example.com'\n   *   });\n   *   console.log('OTP sent to:', emailAccount.email);\n   * } catch (error) {\n   *   if (error instanceof GridError) {\n   *     console.error('Account creation failed:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @example Signer account (simplified)\n   * ```typescript\n   * const signerAccount = await gridClient.createAccount({\n   *   signer: 'BKKjHs7kKsWFm8GKuFz3HzNKBjH4K4HhjhwxDHrRfKjj'\n   * });\n   * ```\n   *\n   * @example Configure account policies\n   * ```typescript\n   * const signerAccount = await gridClient.createAccount({\n   *   signers: [\n   *     {\n   *       address: 'BKKjHs7kKsWFm8GKuFz3HzNKBjH4K4HhjhwxDHrRfKjj',\n   *       permissions: ['CAN_INITIATE', 'CAN_VOTE']\n   *     }\n   *   ],\n   *   threshold: 1,\n   *   timeLock: null,\n   *   adminAddress: null\n   * });\n   * ```\n   *\n   * @category Authentication\n   */\n  async createAccount(\n    input: CreateAccountInput | CreateAccountRequest\n  ): Promise<CreateAccountResponse> {\n    let request: CreateAccountRequest;\n\n    // Check if it's already a full request\n    if (\"type\" in input) {\n      request = input as CreateAccountRequest;\n    } else if (\"signers\" in input) {\n      // Convert AccountPolicies to SignersAccountRequest with defaults\n      const policies = input as AccountPolicies;\n      request = {\n        type: 'signers',\n        policies: {\n          ...policies,\n          signers: policies.signers.map(signer => ({\n            ...signer,\n            role: signer.role || 'primary',\n            provider: signer.provider || 'external'\n          }))\n        }\n      };\n    } else {\n      // Convert simplified input to full request\n      request = this.constructAccountPayload(input as CreateAccountInput);\n    }\n\n    const response = await this.apiClient.createAccount(request);\n\n    // Update context with account info\n    if (response.data.type === \"signers\" && response.data.address) {\n      this.context.user.address = response.data.address;\n    } else if (response.data.type === \"email\" && response.data.email) {\n      // Store email in context for later authentication\n      this.context.user.email = response.data.email;\n    }\n\n    return response;\n  }\n\n  /**\n   * Helper to construct account payload from simple input\n   */\n  private constructAccountPayload(\n    input: CreateAccountInput\n  ): CreateAccountRequest {\n    if (!input.email && !input.signer) {\n      throw new AuthorizationError(\n        \"Must provide either email or signer\",\n        \"INVALID_REQUEST\"\n      );\n    }\n\n    if (input.email && input.signer) {\n      throw new AuthorizationError(\n        \"Cannot provide both email and signer\",\n        \"AMBIGUOUS_REQUEST\"\n      );\n    }\n\n    if (input.email) {\n      if (!ValidationUtils.isValidEmail(input.email)) {\n        throw new AuthorizationError(\"Invalid email format\", \"INVALID_EMAIL\");\n      }\n\n      return {\n        type: \"email\",\n        email: input.email,\n      } as EmailAccountRequest;\n    }\n\n    if (input.signer) {\n      if (input.signer.length < 32 || input.signer.length > 44) {\n        throw new AuthorizationError(\n          \"Invalid signer address format\",\n          \"INVALID_REQUEST\"\n        );\n      }\n\n      const accountPolicies: AccountPolicies = {\n        signers: [\n          {\n            address: input.signer,\n            role: \"primary\",\n            permissions: [\"CAN_INITIATE\", \"CAN_EXECUTE\", \"CAN_VOTE\"],\n            provider: \"external\",\n          },\n        ],\n        threshold: 1,\n        timeLock: null,\n        adminAddress: null,\n      };\n\n      return {\n        type: \"signers\",\n        policies: accountPolicies,\n        gridUserId: null,\n        memo: undefined,\n      } as SignersAccountRequest;\n    }\n\n    throw new AuthorizationError(\"Invalid input parameters\", \"INVALID_REQUEST\");\n  }\n}\n","import { GridApiClient} from \"../api/grid-api-client\";\nimport {\n  SigningManager,\n  SignRequest,\n  TransactionPayload,\n  TransactionResult,\n  SignAndSendRequest,\n} from \"../managers/signing-manager\";\nimport { base64ToBytes, bytesToBase64 } from \"../utils/encoding\";\nimport {\n  AuthorizationError,\n  GridError,\n  SendTransactionRequest,\n  PrepareArbitraryTransactionRequest,\n  PrepareArbitraryTransactionQueryParams,\n} from \"../types\";\nimport {\n  TransactionSubmissionResponse,\n  CreateProposalRequest,\n  CreateProposalResponse,\n  VoteProposalRequest,\n  VoteProposalResponse,\n  ExecuteProposalRequest,\n  ExecuteProposalResponse\n} from \"../types/common\";\nimport { VersionedTransaction } from \"@solana/web3.js\";\nimport { TransactionResponse } from \"../managers/signing-manager\";\n\n/**\n * @hidden\n * Service handling transaction operations\n */\nexport class TransactionService {\n  private apiClient: GridApiClient;\n  private signingManager: SigningManager;\n\n  constructor(apiClient: GridApiClient, signingManager: SigningManager) {\n    this.apiClient = apiClient;\n    this.signingManager = signingManager;\n  }\n\n  /**\n   * Extract a Solana VersionedTransaction ready to be signed using solana web3.js\n   *\n   * @param transactionData - Grid transaction payload containing the transaction\n   * @returns Deserialized VersionedTransaction ready for signing\n   *\n   * @example\n   * ```typescript\n   * const preparedTx = await gridClient.prepareArbitraryTransaction(accountAddress, prepareRequest);\n   * const signableTransaction = gridClient.extractSignableTransaction(preparedTx);\n   * ```\n   */\n  extractSignableTransaction(transactionData: TransactionPayload): VersionedTransaction {\n    const preparedTxBytes = base64ToBytes(transactionData.transaction);\n    const preparedTransaction = VersionedTransaction.deserialize(preparedTxBytes);\n\n    return preparedTransaction;\n  }\n\n  /**\n   * Set an externally signed transaction into Grid transaction payload so you can submit it via grid api.\n   *\n   * @param transactionData - Original Grid transaction data\n   * @param externallySignedTransaction - The signed VersionedTransaction\n   * @returns Updated Grid transaction payload with signed transaction data\n   *\n   * @example\n   * ```typescript\n   * transaction.sign([externalSigner]);\n   *\n   * const signedTxData = gridClient.setExternallySignedTransaction(\n   *   originalTxData,\n   *   transaction\n   * );\n   * ```\n   */\n  setExternallySignedTransaction(transactionData: TransactionPayload, externallySignedTransaction: VersionedTransaction): TransactionPayload {\n    return {\n      transaction: bytesToBase64(externallySignedTransaction.serialize()),\n      transactionSigners: transactionData.transactionSigners,\n      kmsPayloads: transactionData.kmsPayloads\n    };\n  }\n\n  /**\n   * Automatically selects the appropriate authentication provider based on the\n   * session context and available session secrets.\n   *\n   * @param request - Sign request containing transaction payload and session secrets\n   * @returns Promise resolving to transaction result with signatures and metadata\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const authResult = await gridClient.completeAuth(payload);\n   *   const preparedTx = await gridClient.prepareArbitraryTransaction(accountAddress, {\n   *     transaction: 'base64-encoded-transaction'\n   *   });\n   *\n   *   const signResult = await gridClient.sign({\n   *     sessionSecrets: sessionSecrets,\n   *     transactionPayload: preparedTx,\n   *     session: authResult.authentication\n   *   });\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Signing failed:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Transaction Signing\n   */\n  async sign(request: SignRequest): Promise<TransactionResult> {\n    try {\n      const result = await this.signingManager.sign(request);\n      return result;\n    } catch (error: any) {\n      if (error instanceof AuthorizationError) {\n        throw error;\n      }\n      throw new AuthorizationError(\n        `Signing failed: ${error.message}`,\n        \"SIGNING_FAILED\"\n      );\n    }\n  }\n\n  /**\n   * Sign and send a transaction. Automatically selects the appropriate authentication provider based on the\n   * session context and available session secrets\n   *\n   * @param request - Sign and send request containing transaction payload and session secrets\n   * @returns Promise resolving to transaction submission result with blockchain signature\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const authResult = await gridClient.completeAuth(payload);\n   *   const preparedTx = await gridClient.prepareArbitraryTransaction(accountAddress, {\n   *     transaction: 'base64-encoded-transaction'\n   *   });\n   *\n   *   const result = await gridClient.signAndSend({\n   *     sessionSecrets: sessionSecrets,\n   *     transactionPayload: preparedTx,\n   *     session: authResult.authentication,\n   *     address: accountAddress\n   *   });\n   *   console.log('Transaction signature:', result.transactionSignature);\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Transaction failed:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Transaction Signing\n   */\n  async signAndSend(request: SignAndSendRequest): Promise<TransactionSubmissionResponse> {\n    try {\n      const signRequest: SignRequest = {\n        sessionSecrets: request.sessionSecrets,\n        transactionPayload: request.transactionPayload,\n        session: request.session,\n      };\n      const transactionResult = await this.signingManager.sign(signRequest);\n      const result = await this.send({\n        address: request.address,\n        signedTransactionPayload: transactionResult,\n      });\n\n      return result;\n    } catch (error: any) {\n      if (error instanceof AuthorizationError) {\n        throw error;\n      }\n      throw new AuthorizationError(\n        `Signing failed: ${error.message}`,\n        \"SIGNING_FAILED\"\n      );\n    }\n  }\n\n  /**\n   * Submits a previously signed transaction to the Solana blockchain through\n   * the Grid API.\n   *\n   * @param request - Send request containing the signed transaction and account address\n   * @returns Promise resolving to transaction submission result with signature\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const signedTx = await gridClient.sign({ ... });\n   *   const result = await gridClient.send({\n   *     signedTransactionPayload: signedTx,\n   *     address: 'account-address'\n   *   });\n   *   console.log('Blockchain signature:', result.transactionSignature);\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Submission failed:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Transaction Signing\n   */\n  async send(request: SendTransactionRequest): Promise<TransactionSubmissionResponse> {\n    const { signedTransactionPayload, address } = request;\n    const { transaction, kmsPayloads } = signedTransactionPayload;\n\n    // Create KMS payloads with provider information from SignResult\n    const submitPayload = {\n      transaction,\n      kms_payloads: kmsPayloads,\n    };\n\n    const response = await this.apiClient.submitTransaction(\n      address,\n      submitPayload\n    );\n\n    return response;\n  }\n\n  /**\n   * Prepares any Solana transaction for signing by adding necessary account\n   * metadata, fee calculations, and smart account integration.\n   *\n   * @param accountAddress - The account address that will sign the transaction\n   * @param request - Transaction preparation request with the raw transaction\n   * @param queryParams - Optional query parameters for transaction preparation\n   * @returns Promise resolving to prepared transaction payload ready for signing\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const preparedTx = await gridClient.prepareArbitraryTransaction(accountAddress, {\n   *     transaction: 'base64-encoded-solana-transaction'\n   *   });\n   *\n   *   const signedTx = await gridClient.sign({\n   *     sessionSecrets: sessionSecrets,\n   *     transactionPayload: preparedTx\n   *   });\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Preparation failed:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Transaction Processing\n   */\n  async prepareArbitraryTransaction(\n    accountAddress: string,\n    request: PrepareArbitraryTransactionRequest,\n    queryParams?: PrepareArbitraryTransactionQueryParams\n  ): Promise<TransactionResponse> {\n    const response = await this.apiClient.prepareArbitraryTransaction(\n      accountAddress,\n      request,\n      queryParams\n    );\n\n    const transactionData = response;\n\n    if (!transactionData.data.kmsPayloads) {\n      transactionData.data.kmsPayloads = [];\n    }\n\n    return transactionData;\n  }\n\n  /**\n   * Create a proposal\n   *\n   * @param accountAddress - account address\n   * @param request: CreateProposalRequest\n   *\n   * @returns Promise resolving to proposal response\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const proposal = await gridClient.createProposal(transaction, signer);\n   * } catch (error) {\n   *   console.error('Proposal creation failed:', error);\n   * }\n   * ```\n   */\n  async createProposal(accountAddress: string, request: CreateProposalRequest): Promise<CreateProposalResponse> {\n    const response = await this.apiClient.createProposal(accountAddress, request);\n    return response;\n  }\n\n  /**\n   * Vote on a proposal\n   *\n   * @param accountAddress - Smart account address\n   * @param proposalAddress - Proposal address\n   * @param request - Vote proposal request\n   *\n   * @returns Promise resolving to vote proposal response\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const voteResult = await gridClient.voteProposal(\n   *     accountAddress,\n   *     proposalAddress,\n   *     {\n   *       signers: ['signer-pubkey-1', 'signer-pubkey-2'],\n   *       action: 'approve'\n   *     }\n   *   );\n   * } catch (error) {\n   *   console.error('Vote failed:', error);\n   * }\n   * ```\n   */\n  async voteProposal(\n    accountAddress: string,\n    proposalAddress: string,\n    request: VoteProposalRequest\n  ): Promise<VoteProposalResponse> {\n    const response = await this.apiClient.voteProposal(accountAddress, proposalAddress, request);\n    return response;\n  }\n\n  /**\n   * Execute a proposal\n   *\n   * @param accountAddress - Smart account address\n   * @param proposalAddress - Proposal address\n   * @param request - Execute proposal request\n   *\n   * @returns Promise resolving to execute proposal response\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const executeResult = await gridClient.executeProposal(\n   *     accountAddress,\n   *     proposalAddress,\n   *     { signer: 'signer-pubkey' }\n   *   );\n   * } catch (error) {\n   *   console.error('Execute failed:', error);\n   * }\n   * ```\n   */\n  async executeProposal(\n    accountAddress: string,\n    proposalAddress: string,\n    request: ExecuteProposalRequest\n  ): Promise<ExecuteProposalResponse> {\n    const response = await this.apiClient.executeProposal(accountAddress, proposalAddress, request);\n    return response;\n  }\n}\n","import bs58 from \"bs58\";\nimport { GridApiClient } from \"../api/grid-api-client\";\nimport { base64ToBytes } from \"../utils/encoding\";\nimport { AccountManager } from \"../managers/account-manager\";\nimport {\n  AuthorizationError,\n  GetPasskeysResponse,\n  AddPasskeyRequest,\n  AddPasskeyQueryParams,\n  AddPasskeyResponse,\n  RemovePasskeyRequest,\n  RemovePasskeyQueryParams,\n  RemovePasskeyResponse,\n  PasskeyRequest,\n  SessionKey,\n  RP_NAME,\n  CreatePasskeySessionRequest,\n  CreatePasskeySessionResponse,\n  AuthorizePasskeySessionRequest,\n  AuthorizePasskeySessionResponse,\n  SubmitPasskeySessionRequest,\n  SubmitPasskeySessionResponse,\n  FindPasskeyAccountRequest,\n  FindPasskeyAccountResponse,\n  GetPasskeySessionResponse,\n  GetPasskeyAccountResponse,\n  CreatePasskeyAccountRequest,\n  CreatePasskeyAccountResponse,\n  PasskeyCredentialData,\n  PasskeyAssertionResponse,\n} from \"../types\";\n\n/**\n * @hidden\n * Service handling passkey operations\n */\nexport class PasskeyService {\n  private apiClient: GridApiClient;\n  private accountManager?: AccountManager;\n\n  constructor(apiClient: GridApiClient, accountManager?: AccountManager) {\n    this.apiClient = apiClient;\n    this.accountManager = accountManager;\n  }\n\n  /**\n   * Retrieves all passkeys for an account\n   *\n   * @param accountAddress - The account address to get passkeys for\n   * @returns Promise resolving to passkeys response with credential details\n   *\n   * @example\n   * ```typescript\n   * const passkeys = await gridClient.getPasskeys(accountAddress);\n   * ```\n   *\n   * @category Passkey Management\n   */\n  async getPasskeys(accountAddress: string): Promise<GetPasskeysResponse> {\n    const response = await this.apiClient.getPasskeys(accountAddress);\n    return response;\n  }\n\n  /**\n   * Registers a new passkey for an account.\n   *\n   * @param accountAddress - The account address to add the passkey to\n   * @param request - Passkey registration request with credential data\n   * @param queryParams - Optional query parameters for the registration\n   * @returns Promise resolving to passkey addition response\n   *\n   * @example\n   * ```typescript\n   * const passkeyResponse = await gridClient.addPasskey(accountAddress, {\n   *   passkey: {\n   *     address: \"2W6cUhpELHYhTi3Cn6SmHfVhJFKgqmUJLJ5V2DQNcaXE\",\n   *     role: \"secondary\",\n   *     permissions: [\"CAN_INITIATE\", \"CAN_VOTE\", \"CAN_EXECUTE\"]\n   *   }\n   * });\n   * ```\n   *\n   * @category Passkey Management\n   */\n  async addPasskey(\n    accountAddress: string,\n    request: AddPasskeyRequest,\n    queryParams?: AddPasskeyQueryParams\n  ): Promise<AddPasskeyResponse> {\n    const response = await this.apiClient.addPasskey(\n      accountAddress,\n      request,\n      queryParams\n    );\n    return response;\n  }\n\n  /**\n   * Removes an existing passkey credential from an account, revoking its\n   * ability to authorize transactions.\n   *\n   * @param accountAddress - The account address that owns the passkey\n   * @param passkeyAddress - The address of the passkey to remove\n   * @param request - Passkey removal request with authorization details\n   * @param queryParams - Optional query parameters for the removal\n   * @returns Promise resolving to passkey removal response\n   *\n   *\n   * @example\n   * ```typescript\n   * const removeResponse = await gridClient.removePasskey(\n   *   accountAddress,\n   *   passkeyAddress\n   * );\n   * ```\n   *\n   * @category Passkey Management\n   */\n  async removePasskey(\n    accountAddress: string,\n    passkeyAddress: string,\n    transactionSigners?: string[],\n    queryParams?: RemovePasskeyQueryParams\n  ): Promise<RemovePasskeyResponse> {\n    const response = await this.apiClient.removePasskey(\n      accountAddress,\n      passkeyAddress,\n      transactionSigners,\n      queryParams\n    );\n    return response;\n  }\n\n  /**\n   * Initiates the WebAuthn credential creation process, prompting the user\n   * to register a new passkey using their device's authenticator (fingerprint,\n   * face recognition, or security key).\n   *\n   * @param params - Passkey creation parameters including challenge and user info\n   * @returns Promise resolving to credential data with public key and credential ID\n   *\n   *\n   * @example\n   * ```typescript\n   * const credentialData = await gridClient.createPasskeyCredentials({\n   *   env: 'production',\n   *   challenge: 'base64-encoded-challenge',\n   *   slotNumber: '123',\n   *   sessionKey: 'session-public-key-base58',\n   *   expirationInSeconds: '3600',\n   *   appName: 'My App',\n   *   userId: 'user-identifier',\n   *   redirectUrl: 'your-redirect-url'\n   * });\n   * ```\n   * Note: You can use extractPasskeyCreateParams to extract the parameters from the URL.\n   *\n   * @category Passkey Management\n   */\n  async createPasskeyCredentials(params: PasskeyRequest): Promise<PasskeyCredentialData>{\n    try {\n      const passkeyParams = {\n        publicKey: {\n          challenge: base64ToBytes(params.challenge).buffer as ArrayBuffer,\n          rp: {\n            name: RP_NAME,\n          },\n          user: {\n            id: new TextEncoder().encode(params.userId),\n            name: `${params.appName}#${params.userId}`,\n            displayName: params.appName,\n          },\n          pubKeyCredParams: [\n            { type: \"public-key\", alg: -7 },   // ES256\n            { type: \"public-key\", alg: -257 }, // RS256\n          ],\n          authenticatorSelection: {\n            residentKey: \"required\",\n            requireResidentKey: true,\n            userVerification: \"required\",\n          },\n          timeout: 60000,\n          attestation: \"direct\",\n        },\n      } as CredentialCreationOptions;\n\n      const credential = (await navigator.credentials.create(passkeyParams)) as PublicKeyCredential;\n      if (!credential) {\n        throw new AuthorizationError(\n          \"CREDENTIAL_CREATION_FAILED\",\n          \"Could not create passkey credentials\"\n        );\n      }\n\n      const res = credential.response as AuthenticatorAttestationResponse;\n      if (!res.getPublicKey()) {\n        throw new AuthorizationError(\n          \"NO_PUBLIC_KEY\",\n          \"No public key found\"\n        );\n      }\n\n      const publicKey = this.bufferToBase64Url(res.getPublicKey()!);\n\n      // Return both the credential ID and public key for proper passkey flow\n      return {\n        id: credential.rawId,  // Raw ArrayBuffer for use in allowCredentials\n        publicKey: publicKey,  // Base64 encoded public key\n        credentialId: credential.id  // Base64url encoded ID string\n      };\n    } catch (error) {\n      throw new AuthorizationError(\n        `Passkey creation failed: ${error instanceof Error ? error.message : String(error)}`,\n        \"PASSKEY_CREATION_FAILED\"\n      );\n    }\n  }\n\n  /**\n   * Initiates the WebAuthn authentication process, prompting the user to\n   * authenticate using their previously registered passkey.\n   *\n   * @param params - Passkey authentication parameters including challenge\n   * @param credentialData - Optional specific credential to authenticate with\n   * @returns Promise resolving to assertion response with signature and authentication data\n   *\n   *\n   * @example\n   * ```typescript\n   * const assertion = await gridClient.getPasskeyCredentials({\n   *   env: 'production',\n   *   challenge: 'base64-encoded-challenge',\n   *   slotNumber: '123',\n   *   sessionKey: 'session-public-key-base58',\n   *   expirationInSeconds: '3600',\n   *   appName: 'My App',\n   *   userId: 'user-identifier',\n   *   redirectUrl: 'your-redirect-url'\n   * });\n   * console.log(assertion.response.signature);\n   * ```\n   * Note: You can use extractPasskeyAuthParams to extract the parameters from the URL.\n   *\n   * @category Passkey Management\n   */\n  async getPasskeyCredentials(params: PasskeyRequest, credentialData?: PasskeyCredentialData): Promise<PasskeyAssertionResponse> {\n    try {\n      const assertionParams = {\n        publicKey: {\n          challenge: base64ToBytes(params.challenge).buffer as ArrayBuffer,\n          allowCredentials: credentialData ?  [{\n            id: credentialData.id,  // This is the rawId ArrayBuffer from creation\n            type: 'public-key'\n          }]:[],\n          userVerification: \"required\",\n          timeout: 60000,\n        },\n      } as CredentialRequestOptions;\n\n      const assertion = (await navigator.credentials.get(assertionParams)) as PublicKeyCredential;\n\n      if (!assertion) {\n          throw new AuthorizationError(\n            \"ASSERTION_FAILED\",\n            \"Could not get passkey credentials\"\n          );\n      }\n\n      // Make sure we're converting everything to plain objects\n      const response = (assertion as PublicKeyCredential)\n        .response as AuthenticatorAssertionResponse;\n\n      const signature = this.bufferToBase64Url(response.signature);\n      const clientDataJSON = this.bufferToBase64Url(response.clientDataJSON);\n      const authenticatorData = this.bufferToBase64Url(response.authenticatorData);\n\n      if (credentialData) {\n        // Convert publicKey to base64 if it's not already\n        const publicKeyBase64 = typeof credentialData.publicKey === 'string'\n          ? credentialData.publicKey\n          : this.bufferToBase64Url(credentialData.publicKey);\n\n        const obj = {\n          response: {\n            signature,\n            clientDataJSON,\n            authenticatorData,\n            publicKey: publicKeyBase64,\n          },\n        };\n\n        return obj;\n      } else {\n        const obj = {\n          response: {\n            signature,\n            clientDataJSON,\n            authenticatorData,\n          },\n        };\n        return obj;\n      }\n    } catch (error) {\n      throw new AuthorizationError(\n        `Passkey assertion failed: ${error instanceof Error ? error.message : String(error)}`,\n        \"PASSKEY_ASSERTION_FAILED\"\n      );\n    }\n  }\n\n  /**\n   * Parses URL search parameters to extract the necessary information\n   * for passkey credential creation.\n   *\n   * @param query - URLSearchParams object containing passkey creation parameters\n   * @returns Parsed passkey request object ready for credential creation\n   *\n   * @example\n   * ```typescript\n   * const urlParams = new URLSearchParams(window.location.search);\n   * const passkeyParams = gridClient.extractPasskeyCreateParams(urlParams);\n   *\n   * const credentials = await gridClient.createPasskeyCredentials(passkeyParams);\n   * ```\n   *\n   * @category Passkey Management\n   */\n  extractPasskeyCreateParams(query: URLSearchParams): PasskeyRequest {\n    const params = {\n      env: query.get(\"env\"),\n      appName: query.get(\"app-name\"),\n      userId: query.get(\"user-id\"),\n      redirectUrl: query.get(\"redirect-url\"),\n      challenge: query.get(\"challenge\"),\n      slotNumber: query.get(\"slot-num\"),\n      sessionKey: query.get(\"session-key\"),\n      expirationInSeconds: query.get(\"expiration-in-seconds\"),\n    } as PasskeyRequest;\n\n    return params;\n  }\n\n  /**\n   * Parses URL search parameters to extract the necessary information\n   * for passkey authentication.\n   *\n   * @param query - URLSearchParams object containing passkey authentication parameters\n   * @returns Parsed passkey request object ready for authentication\n   *\n   * @example\n   * ```typescript\n   * const urlParams = new URLSearchParams(window.location.search);\n   * const authParams = gridClient.extractPasskeyAuthParams(urlParams);\n   *\n   * const assertion = await gridClient.getPasskeyCredentials(authParams);\n   * ```\n   *\n   * @category Passkey Management\n   */\n  extractPasskeyAuthParams(query: URLSearchParams): PasskeyRequest {\n    const params = {\n      env: query.get('env'),\n      redirectUrl: query.get('redirect-url'),\n      challenge: query.get('challenge'),\n      slotNumber: query.get('slot-num'),\n      sessionKey: query.get('session-key'),\n      expirationInSeconds: query.get('expiration-in-seconds'),\n    } as PasskeyRequest;\n\n    return params;\n  }\n\n  /**\n   * Initiates a new passkey authentication session, preparing the necessary\n   * challenge and session data for WebAuthn authentication flow.\n   *\n   * @param params - Passkey session creation parameters\n   * @param environment - Target environment ('sandbox' or 'production')\n   * @returns Promise resolving to passkey session creation response\n   *\n   *\n   * @example\n   * ```typescript\n   * await gridClient.createPasskeySession({\n   *   action: 'create',\n   *   sessionKey: 'session-public-key-base58',\n   *   env: 'production',\n   * }, 'production');\n   * ```\n   *\n   * @category Passkey Sessions\n   */\n  async createPasskeySession(\n    params: CreatePasskeySessionRequest,\n    environment: string\n  ): Promise<CreatePasskeySessionResponse> {\n    try {\n      const response = await this.apiClient.createPasskeySession(params, environment);\n\n      return response;\n    } catch (error: any) {\n      if (error instanceof AuthorizationError) {\n        throw error;\n      }\n      throw new AuthorizationError(\n        `Create passkey session failed: ${error.message}`,\n        \"PASSKEY_SESSION_CREATE_FAILED\"\n      );\n    }\n  }\n\n  /**\n   * Submits passkey authentication data to authorize an existing session,\n   * completing the WebAuthn authentication flow.\n   *\n   * @param params - Passkey session authorization parameters with authentication data\n   * @param environment - Target environment ('sandbox' or 'production')\n   * @returns Promise resolving to session authorization response\n   *\n   *\n   * @example\n   * ```typescript\n   * const authorization = await gridClient.authorizePasskeySession({\n   *   sessionKey: 'public-key-base58',\n   *   metaInfo: {\n   *     appName: 'My App',\n   *     redirectUrl: 'https://myapp.com/callback'\n   *   },\n   *   baseUrl: 'base-url'\n   * }, 'sandbox');\n   * ```\n   *\n   * @category Passkey Sessions\n   */\n  async authorizePasskeySession(\n    params: AuthorizePasskeySessionRequest,\n    environment: string\n  ): Promise<AuthorizePasskeySessionResponse> {\n    try {\n      const response = await this.apiClient.authorizePasskeySession(params, environment);\n\n      return response;\n    } catch (error: any) {\n      if (error instanceof AuthorizationError) {\n        throw error;\n      }\n      throw new AuthorizationError(\n        `Authorize passkey session failed: ${error.message}`,\n        \"PASSKEY_SESSION_AUTHORIZE_FAILED\"\n      );\n    }\n  }\n\n  /**\n   * Finalizes a passkey authentication session, generating the final\n   * session tokens and account access credentials.\n   *\n   * @param params - Passkey session submission parameters\n   * @param environment - Target environment ('sandbox' or 'production')\n   * @returns Promise resolving to session submission response with account details\n   *\n   *\n   * @example\n   * ```typescript\n   * const result = await gridClient.submitPasskeySession({\n   *   authenticatorResponse: <attestationObject from getPasskeySession>,\n   *   sessionKey: 'public-key-base58',\n   *   ceremonyType: 'auth',\n   *   slotNumber: 123\n   * }, 'sandbox');\n   * ```\n   *\n   * @category Passkey Sessions\n   */\n  async submitPasskeySession(\n    params: SubmitPasskeySessionRequest,\n    environment: string\n  ): Promise<SubmitPasskeySessionResponse> {\n    try {\n      const response = await this.apiClient.submitPasskeySession(params, environment);\n\n      // Response is already transformed to camelCase by API client\n      // Only encode sessionKey.key from byte array to base58\n      const sessionKey = bs58.encode(new Uint8Array(response.data.sessionKey.key));\n\n      return {\n        data: {\n          passkeyAccount: response.data.passkeyAccount,\n          smartAccount: response.data.smartAccount,\n          sessionKey: {\n            key: sessionKey,\n            expiration: response.data.sessionKey.expiration\n          },\n        },\n        lastResponse: response.lastResponse\n      };\n    } catch (error: any) {\n      if (error instanceof AuthorizationError) {\n        throw error;\n      }\n      throw new AuthorizationError(\n        `Submit passkey session failed: ${error.message}`,\n        \"PASSKEY_SESSION_SUBMIT_FAILED\"\n      );\n    }\n  }\n\n  /**\n   * Searches for an existing passkey account using credential information,\n   * allowing users to recover access to their accounts.\n   *\n   * @param params - Passkey account search parameters with credential data\n   * @param environment - Target environment ('sandbox' or 'production')\n   * @returns Promise resolving to found passkey account information\n   *\n   *\n   * @example\n   * ```typescript\n   * const account = await gridClient.findPasskeyAccount({\n   *   sessionKey: 'public-key-base58',\n   *   authenticatorResponse: <attestationObject from getPasskeySession>\n   * }, 'sandbox');\n   * ```\n   *\n   * @category Passkey Sessions\n   */\n  async findPasskeyAccount(\n    params: FindPasskeyAccountRequest,\n    environment: string\n  ): Promise<FindPasskeyAccountResponse> {\n    try {\n      const response = await this.apiClient.findPasskeyAccount(params, environment);\n\n      // Response is already transformed to camelCase by API client\n      // Convert the response format if it contains the expected backend structure\n      if (response.data.passkeyAccount && response.data.sessionKey) {\n        // Only encode sessionKey.key from byte array to base58\n        const sessionKeyBase58 = bs58.encode(new Uint8Array(response.data.sessionKey.key));\n        return {\n          data: {\n            passkeyAccount: response.data.passkeyAccount,\n            address: response.data.address,\n            sessionKey: {\n                key: sessionKeyBase58,\n                expiration: response.data.sessionKey.expiration\n              }\n            },\n            lastResponse: response.lastResponse\n          };\n      }\n\n      return response;\n    } catch (error: any) {\n      if (error instanceof AuthorizationError) {\n        throw error;\n      }\n      throw new AuthorizationError(\n        `Find passkey account failed: ${error.message}`,\n        \"PASSKEY_ACCOUNT_FIND_FAILED\"\n      );\n    }\n  }\n\n  /**\n   * Retrieves detailed information about a specific passkey account,\n   * including relying party ID, public key, and optional session key if not expired.\n   *\n   * @param passkeyAddress - The passkey account address (Solana public key) to retrieve\n   * @param environment - Target environment ('sandbox' or 'production')\n   * @returns Promise resolving to passkey account details with relying party ID, public key, and optional session key\n   *\n   *\n   * @example\n   * ```typescript\n   * const account = await gridClient.getPasskeyAccount(\n   *   'passkey-account-address',\n   *   'sandbox'\n   * );\n   * console.log(account.data.relyingPartyId);\n   * console.log(account.data.pubkey);\n   * if (account.data.sessionKey) {\n   *   console.log('Session key:', account.data.sessionKey.key);\n   *   console.log('Expires:', account.data.sessionKey.expiration);\n   * }\n   * ```\n   *\n   * @category Passkey Sessions\n   */\n  async getPasskeyAccount(\n    passkeyAddress: string,\n    environment: string\n  ): Promise<GetPasskeyAccountResponse> {\n    try {\n      if (!passkeyAddress) {\n        throw new AuthorizationError(\n          \"Passkey address is required\",\n          \"INVALID_REQUEST\"\n        );\n      }\n\n      const response = await this.apiClient.getPasskeyAccount(passkeyAddress, environment);\n\n      return response;\n    } catch (error: any) {\n      if (error instanceof AuthorizationError) {\n        throw error;\n      }\n      throw new AuthorizationError(\n        `Get passkey account failed: ${error.message}`,\n        \"PASSKEY_ACCOUNT_GET_FAILED\"\n      );\n    }\n  }\n\n  /**\n   * Creates both a passkey account (externally signed account) and smart account in one call.\n   * This combines the passkey creation ceremony with smart account initialization.\n   * Creates a 1/1 smart account with the passkey having full permissions.\n   *\n   * @param params - Passkey account creation parameters including session key and authenticator response\n   * @param environment - Target environment ('sandbox' or 'production')\n   * @returns Promise resolving to the created smart account details including passkey info\n   *\n   *\n   * @example\n   * ```typescript\n   * const sessionKeyObject = {\n   *   key: sessionKeyPubkey,\n   *   expiration: Date.now() + 900000\n   * };\n   *\n   * const account = await gridClient.createPasskeyAccount({\n   *   sessionKey: sessionKeyObject,\n   *   slotNumber: 123,\n   *   authenticatorResponse: webauthnResponse,\n   *   adminAddress: 'admin-public-key',\n   *   memo: 'My passkey account'\n   * }, 'sandbox');\n   * console.log('Smart account address:', account.data.address);\n   * console.log('Passkey account:', account.data.passkey.passkeyAccount);\n   * console.log('Session key:', account.data.passkey.sessionKey);\n   * ```\n   *\n   * @category Passkey Management\n   */\n  async createPasskeyAccount(\n    params: CreatePasskeyAccountRequest,\n    environment: string\n  ): Promise<CreatePasskeyAccountResponse> {\n    try {\n      if (!params.sessionKey || !params.slotNumber || !params.authenticatorResponse) {\n        throw new AuthorizationError(\n          \"Session key, slot number, and authenticator response are required\",\n          \"INVALID_REQUEST\"\n        );\n      }\n      const response = await this.apiClient.createPasskeyAccount(params, environment);\n\n      // Check for passkey session in authentication array (new API structure)\n      // API returns: authentication[].session.Passkey.session_key\n      const passkeyAuth = response.data.authentication?.find(\n        (auth: any) => auth.provider === 'passkey' \n      );\n\n      if (passkeyAuth?.session?.Passkey || passkeyAuth?.session?.passkey) {\n        // Support both capital P (Passkey) and lowercase p (passkey)\n        const passkeySession = passkeyAuth.session.Passkey || passkeyAuth.session.passkey;\n        // API returns snake_case keys (session_key), but support both formats\n        const rawSessionKey = passkeySession.session_key?.key || passkeySession.sessionKey?.key;\n\n        if (!rawSessionKey) {\n          throw new AuthorizationError(\n            \"Invalid response: missing session key in passkey session\",\n            \"INVALID_RESPONSE\"\n          );\n        }\n\n        // Flatten passkey session data to top-level for easier access\n        // Transform from: { provider, session: { Passkey: {...} } }\n        // To: { provider, sessionKey, passkeyAccount, pubkey, relyingPartyId, ... }\n        const updatedAuthentication = response.data.authentication.map((auth: any) => {\n          if (auth === passkeyAuth) {\n            return {\n              provider: auth.provider,\n              // Transform snake_case API response to camelCase for SDK\n              sessionKey: {\n                key: passkeySession.session_key?.key || passkeySession.sessionKey?.key,\n                expiration: passkeySession.session_key?.expiration || passkeySession.sessionKey?.expiration\n              },\n              passkeyAccount: passkeySession.passkey_account || passkeySession.passkeyAccount,\n              pubkey: passkeySession.pubkey,\n              relyingPartyId: passkeySession.relying_party_id || passkeySession.relyingPartyId,\n              // Keep original nested structure for reference\n              session: auth.session\n            };\n          }\n          return auth;\n        });\n\n        // Return response with flattened authentication structure\n        return {\n          data: {\n            ...response.data,\n            authentication: updatedAuthentication\n          },\n          lastResponse: response.lastResponse\n        };\n      }\n\n      // No passkey session found (shouldn't happen for create, but handle gracefully)\n      throw new AuthorizationError(\n        \"Invalid response: missing passkey session data\",\n        \"INVALID_RESPONSE\"\n      );\n    } catch (error: any) {\n      if (error instanceof AuthorizationError) {\n        throw error;\n      }\n      throw new AuthorizationError(\n        `Create passkey account failed: ${error.message}`,\n        \"PASSKEY_ACCOUNT_CREATE_FAILED\"\n      );\n    }\n  }\n\n  /**\n   * @hidden\n   * Convert ArrayBuffer to base64url encoding\n   *\n   * @param buffer - ArrayBuffer containing binary data to encode\n   * @returns Base64url encoded string\n   *\n   * @example\n   * ```typescript\n   * const binaryData = new Uint8Array([1, 2, 3, 4]).buffer;\n   * const encoded = gridClient.bufferToBase64Url(binaryData);\n   * console.log(encoded);\n   * ```\n   *\n   * @category Utilities\n   */\n  bufferToBase64Url(buffer: ArrayBuffer): string {\n    const base64 = btoa(String.fromCharCode(...new Uint8Array(buffer)));\n    return base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n  }\n}\n","import { AuthorizationError, SpendingLimitPeriod } from \"../types/common\";\nimport { ApiSpendingLimitPeriod } from \"../types/api\";\n\nconst gridToProgram: Record<SpendingLimitPeriod, string> = {\n    one_time: \"one_time\",\n    daily: \"day\",\n    weekly: \"week\",\n    monthly: \"month\",\n};\n\nexport function gridToProgramPeriod(period: SpendingLimitPeriod): ApiSpendingLimitPeriod {\n    const mapped = gridToProgram[period];\n    if (!mapped) throw new AuthorizationError(\"Invalid period\", \"INVALID_REQUEST\");\n    return mapped as ApiSpendingLimitPeriod;\n}","import { GridApiClient} from \"../api/grid-api-client\";\nimport {\n  SpendingLimitRequest,\n  UpdateSpendingLimitRequest,\n  UseSpendingLimitRequest,\n} from \"../types\";\nimport { CreateSpendingLimitResponse, GridError, SpendingLimitResponse, SpendingLimitsResponse, SpendingLimitTransactionResponse } from \"../types/common\";\nimport { gridToProgramPeriod } from \"../utils/period-mapper\";\n\n/**\n * @hidden\n * Service handling spending limit operations\n */\nexport class SpendingLimitService {\n  private apiClient: GridApiClient;\n\n  constructor(apiClient: GridApiClient) {\n    this.apiClient = apiClient;\n  }\n\n  /**\n   * Creates a new spending limit.\n   *\n   * @param smartAccountAddress - The account address to create spending limit for\n   * @param request - Spending limit configuration including amount, token, and period\n   * @returns Promise resolving to transaction response for spending limit creation\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const spendingLimitTx = await gridClient.createSpendingLimit(accountAddress, {\n   *     amount: 10000000,\n   *     mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',\n   *     period: 'daily',\n   *     spendingLimitSigners: ['limit-signer-address']\n   *   });\n   *   console.log('Spending limit created:', spendingLimitTx.spendingLimitAddress);\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Failed to create spending limit:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Spending Limits\n   */\n  async createSpendingLimit(\n    smartAccountAddress: string,\n    request: SpendingLimitRequest\n  ): Promise<CreateSpendingLimitResponse> {\n    // Transform period to API format and pass to API client\n    // The API client will handle camelCase to snake_case conversion\n    const requestPayload: SpendingLimitRequest = {\n      ...request,\n      period: gridToProgramPeriod(request.period) as any,\n    };\n\n    const response = await this.apiClient.createSpendingLimit(\n      smartAccountAddress,\n      requestPayload\n    );\n\n    return response;\n  }\n\n  /**\n   * Modifies the parameters of an existing spending limit, such as the amount,\n   * time period, or associated signers.\n   *\n   * @param accountAddress - The account address that owns the spending limit\n   * @param spendingLimitAddress - The address of the spending limit to update\n   * @param request - Update request with new spending limit parameters\n   * @returns Promise resolving to transaction response for the update\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const updateTx = await gridClient.updateSpendingLimit(\n   *     accountAddress,\n   *     spendingLimitAddress,\n   *     {\n   *       amount: \"5000000\",\n   *       spendingLimitSigners: ['signer-address']\n   *     }\n   *   );\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Update failed:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Spending Limits\n   */\n  async updateSpendingLimit(\n    accountAddress: string,\n    spendingLimitAddress: string,\n    request: UpdateSpendingLimitRequest\n  ): Promise<SpendingLimitTransactionResponse> {\n    const response = await this.apiClient.updateSpendingLimit(\n      accountAddress,\n      spendingLimitAddress,\n      request\n    );\n\n    return response;\n  }\n\n  /**\n   * Delete a spending limit\n   *\n   * Removes an existing spending limit from an account, allowing unrestricted\n   * spending for the associated token type.\n   *\n   * @param accountAddress - The account address that owns the spending limit\n   * @param spendingLimitAddress - The address of the spending limit to delete\n   * @returns Promise resolving to transaction response for the deletion\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const deleteTx = await gridClient.deleteSpendingLimit(\n   *     accountAddress,\n   *     spendingLimitAddress\n   *   );\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Deletion failed:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Spending Limits\n   */\n  async deleteSpendingLimit(\n    accountAddress: string,\n    spendingLimitAddress: string\n  ): Promise<SpendingLimitTransactionResponse> {\n    const response = await this.apiClient.deleteSpendingLimit(\n      accountAddress,\n      spendingLimitAddress\n    );\n    return response;\n  }\n\n  /**\n   * Use a spending limit for a transaction\n   *\n   * Utilizes an existing spending limit to authorize a transaction, automatically\n   * checking that the transaction amount is within the limit constraints.\n   *\n   * @param accountAddress - The account address that owns the spending limit\n   * @param spendingLimitAddress - The address of the spending limit to use\n   * @param request - Transaction request to authorize against the spending limit\n   * @returns Promise resolving to transaction response for the authorized transaction\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const limitTx = await gridClient.useSpendingLimit(\n   *     accountAddress,\n   *     spendingLimitAddress,\n   *     {\n   *       amount: 500000000,\n   *       signerAddress: \"signer-address\",\n   *       recipientAddress: \"recipient-address\"\n   *     }\n   *   );\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Spending limit authorization failed:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Spending Limits\n   */\n  async useSpendingLimit(\n    accountAddress: string,\n    spendingLimitAddress: string,\n    request: UseSpendingLimitRequest\n  ): Promise<SpendingLimitTransactionResponse> {\n    const response = await this.apiClient.useSpendingLimit(\n      accountAddress,\n      spendingLimitAddress,\n      request\n    );\n    return response;\n  }\n\n  /**\n   * Retrieves a spending limit by its address\n   *\n   * @param accountAddress - The account address that owns the spending limit\n   * @param spendingLimitAddress - The address of the spending limit to retrieve\n   * @returns Promise resolving to spending limit data\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const spendingLimit = await gridClient.getSpendingLimit(\n   *     accountAddress,\n   *     spendingLimitAddress\n   *   );\n   *   console.log('Limit amount:', spendingLimit.amount);\n   *   console.log('Remaining:', spendingLimit.remainingAmount);\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Failed to get spending limit:', error.message);\n   *   }\n   * }\n   * ```\n   */\n  async getSpendingLimit(\n    accountAddress: string,\n    spendingLimitAddress: string\n  ): Promise<SpendingLimitResponse> {\n    const response = await this.apiClient.getSpendingLimit(\n      accountAddress,\n      spendingLimitAddress\n    );\n    return response;\n  }\n\n\n  /**\n   * Retrieves all spending limits for an account\n   *\n   * @param accountAddress - The account address to get spending limits for\n   * @returns Promise resolving to array of spending limit data\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const limits = await gridClient.getSpendingLimits(accountAddress);\n   *   limits.forEach(limit => {\n   *     console.log(`Limit: ${limit.amount}, Remaining: ${limit.remainingAmount}`);\n   *   });\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Failed to get spending limits:', error.message);\n   *   }\n   * }\n   * ```\n   */\n  async getSpendingLimits(accountAddress: string): Promise<SpendingLimitsResponse> {\n    const response = await this.apiClient.getSpendingLimits(accountAddress);\n    return response;\n  }\n}\n","import { GridApiClient} from \"../api/grid-api-client\";\nimport {\n  CreatePaymentIntentRequest,\n  CreatePaymentIntentResponse,\n  RequestKycLinkRequest,\n  RequestVirtualAccountRequest,\n  GetVirtualAccountsQueryParams,\n  CreateStandingOrderRequest,\n  CreateStandingOrderResponse,\n  GetStandingOrdersQueryParams,\n  KycLinkResponse,\n} from \"../types\";\nimport { VirtualAccount, StandingOrder, KycStatusResponse, StandingOrderResponse, StandingOrdersResponse, VirtualAccountResponse, VirtualAccountsResponse } from \"../types/common\";\n\n/**\n * @hidden\n * Service handling banking operations (payment intents, KYC, virtual accounts, standing orders)\n */\nexport class BankingService {\n  private apiClient: GridApiClient;\n\n  constructor(apiClient: GridApiClient) {\n    this.apiClient = apiClient;\n  }\n\n  /**\n   * Initiates a payment intent that allows users to deposit fiat currency\n   * and receive cryptocurrency in their account. Handles the complete\n   * fiat-to-crypto conversion process.\n   *\n   * @param accountAddress - The account address to receive the converted crypto\n   * @param request - Payment intent request with amount, currency, and payment method\n   * @returns Promise resolving to payment intent response with transaction details\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const paymentIntent = await gridClient.createPaymentIntent(accountAddress, {\n   *     amount: \"100000\",\n   *     source: {\n   *       account: accountAddress,\n   *       currency: \"usdc\"\n   *     },\n   *     destination: {\n   *       address: \"3ciascNndLTBrDQXvs8nzZgWAiaL33tGM6fx3zzM7Fxt\",\n   *       currency: \"usdc\"\n   *     }\n   *   });\n   *   console.log(paymentIntent.paymentUrl);\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Payment intent failed:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Payment Processing\n   */\n  async createPaymentIntent(\n    accountAddress: string,\n    request: CreatePaymentIntentRequest\n  ): Promise<CreatePaymentIntentResponse> {\n    const response = await this.apiClient.createPaymentIntent(\n      accountAddress,\n      request\n    );\n\n    // Response is already transformed to camelCase by API client\n    const apiData = response.data;\n\n    const transactionPayload = {\n      kmsPayloads: apiData.kmsPayloads,\n      transactionSigners: apiData.transactionSigners,\n      transaction: apiData.transaction,\n    };\n\n    // Return response with excluded fields removed and transaction data wrapped\n    const {\n      kmsPayloads,\n      transactionSigners,\n      transaction,\n      ...cleanedResponse\n    } = apiData;\n\n    return {\n      data: {\n        ...cleanedResponse,\n        transactionPayload,\n      },\n      lastResponse: response.lastResponse\n    };\n  }\n\n  /**\n   * Generates a link for Know Your Customer (KYC) identity verification.\n   * Users complete the verification process through the provided link.\n   *\n   * @param accountAddress - The account address to associate with KYC\n   * @param request - KYC link request with verification requirements\n   * @returns Promise resolving to KYC link with verification URL\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const kycLink = await gridClient.requestKycLink(accountAddress, {\n   *     type: 'individual',\n   *     email: 'user@example.com',\n   *     fullName: 'John Doe',\n   *     endorsements: [],\n   *     redirectUri: 'your-redirect-uri'\n   *   });\n   *   console.log('KYC URL:', kycLink.link);\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('KYC link generation failed:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category KYC Verification\n   */\n  async requestKycLink(\n    accountAddress: string,\n    request: RequestKycLinkRequest\n  ): Promise<KycLinkResponse> {\n    const response = await this.apiClient.requestKycLink(\n      accountAddress,\n      request\n    );\n    return response;\n  }\n\n  /**\n   * Get KYC verification status\n   *\n   * Retrieves the current status of a KYC verification process, including\n   * completion status, verification level, and any required actions.\n   *\n   * @param accountAddress - The account address associated with KYC\n   * @param kycId - The KYC verification identifier\n   * @returns Promise resolving to KYC status data\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const kycStatus = await gridClient.getKycStatus(accountAddress, kycId);\n   *   console.log('Status:', kycStatus.status);\n   *   console.log('Level:', kycStatus.verificationLevel);\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Failed to get KYC status:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category KYC Verification\n   */\n  async getKycStatus(\n    accountAddress: string,\n    kycId: string\n  ): Promise<KycStatusResponse> {\n    const response = await this.apiClient.getKycStatus(accountAddress, kycId);\n    return response;\n  }\n\n  /**\n   * Creates a virtual bank account that allows users to receive fiat deposits\n   * which are automatically converted to cryptocurrency in their Grid account.\n   *\n   * @param accountAddress - The account address to associate with the virtual account\n   * @param request - Virtual account request with banking details and preferences\n   * @returns Promise resolving to virtual account with banking details\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const virtualAccount = await gridClient.requestVirtualAccount(accountAddress, {\n   *     currency: 'usd' as const\n   *   });\n   *   console.log('Account number:', virtualAccount.accountNumber);\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Virtual account creation failed:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Virtual Accounts\n   */\n  async requestVirtualAccount(\n    accountAddress: string,\n    request: RequestVirtualAccountRequest\n  ): Promise<VirtualAccountResponse> {\n    const response = await this.apiClient.requestVirtualAccount(\n      accountAddress,\n      request\n    );\n    return response;\n  }\n\n  /**\n   * Retrieves all virtual bank accounts associated with a Grid account,\n   * including their status, balances, and transaction history.\n   *\n   * @param accountAddress - The account address to get virtual accounts for\n   * @param queryParams - Optional query parameters for filtering and pagination\n   * @returns Promise resolving to array of virtual accounts\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const virtualAccounts = await gridClient.getVirtualAccounts(accountAddress);\n   *   virtualAccounts.forEach(account => {\n   *     console.log('Account:', account.id);\n   *   });\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Failed to get virtual accounts:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Virtual Accounts\n   */\n  async getVirtualAccounts(\n    accountAddress: string,\n    queryParams?: GetVirtualAccountsQueryParams\n  ): Promise<VirtualAccountsResponse> {\n    const response = await this.apiClient.getVirtualAccounts(\n      accountAddress,\n      queryParams\n    );\n    return response;\n  }\n\n  /**\n   * Create a standing order.\n   *\n   * @param accountAddress - The account address that will make the recurring payments\n   * @param request - Standing order request with payment details and schedule\n   * @returns Promise resolving to standing order creation response\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const standingOrder = await gridClient.createStandingOrder(accountAddress, {\n   *     amount: \"500000\",\n   *     source: {\n   *       account: \"source-address\",\n   *       currency: \"usdc\"\n   *     },\n   *     destination: {\n   *       address: \"destination-address\",\n   *       currency: \"usdc\"\n   *     },\n   *     frequency: \"weekly\",\n   *     startDate: \"2024-12-02T10:00:00Z\",\n   *     endDate: \"2025-12-31T23:59:59Z\"\n   *   });\n   *   console.log('Standing order created:', standingOrder.id);\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Standing order creation failed:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Standing Orders\n   */\n  async createStandingOrder(\n    accountAddress: string,\n    request: CreateStandingOrderRequest\n  ): Promise<CreateStandingOrderResponse> {\n    const response = await this.apiClient.createStandingOrder(\n      accountAddress,\n      request\n    );\n    return response;\n  }\n\n  /**\n   * Retrieves all standing orders associated with an account, including\n   * active, paused, and completed recurring payment schedules.\n   *\n   * @param accountAddress - The account address to get standing orders for\n   * @param queryParams - Optional query parameters for filtering and pagination\n   * @returns Promise resolving to array of standing orders\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const standingOrders = await gridClient.getStandingOrders(accountAddress);\n   *   standingOrders.forEach(order => {\n   *     console.log('Order:', order.id, 'Status:', order.status);\n   *   });\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Failed to get standing orders:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Standing Orders\n   */\n  async getStandingOrders(\n    accountAddress: string,\n    queryParams?: GetStandingOrdersQueryParams\n  ): Promise<StandingOrdersResponse> {\n    const response = await this.apiClient.getStandingOrders(\n      accountAddress,\n      queryParams\n    );\n    return response;\n  }\n\n  /**\n   * Retrieves detailed information about a specific standing order,\n   * including its current status, execution history, and next payment date.\n   *\n   * @param accountAddress - The account address that owns the standing order\n   * @param standingOrderId - The unique identifier of the standing order\n   * @returns Promise resolving to standing order details\n   *\n   * @example\n   * ```typescript\n   * try {\n   *   const order = await gridClient.getStandingOrder(accountAddress, orderId);\n   *   console.log('Next payment:', order.nextPaymentDate);\n   * } catch (error) {\n   *   if (error instanceof ApiError) {\n   *     console.error('Failed to get standing order:', error.message);\n   *   }\n   * }\n   * ```\n   *\n   * @category Standing Orders\n   */\n  async getStandingOrder(\n    accountAddress: string,\n    standingOrderId: string\n  ): Promise<StandingOrderResponse> {\n    const response = await this.apiClient.getStandingOrder(\n      accountAddress,\n      standingOrderId\n    );\n    return response;\n  }\n\n}","import bs58 from \"bs58\";\nimport { GridClientInterface } from \"../interfaces/sdk-interfaces\";\nimport { GridApiClient, GridApiConfig } from \"../api/grid-api-client\";\nimport {\n  AuthenticationManager,\n  AuthenticationRequest,\n} from \"../managers/authentication-manager\";\nimport {\n  SigningManager,\n  SignRequest,\n  TransactionPayload,\n  TransactionResult,\n  SignAndSendRequest,\n  TransactionResponse,\n} from \"../managers/signing-manager\";\nimport { AccountManager } from \"../managers/account-manager\";\nimport { AccountService } from \"../services/account-service\";\nimport { AuthService } from \"../services/auth-service\";\nimport { TransactionService } from \"../services/transaction-service\";\nimport { PasskeyService } from \"../services/passkey-service\";\nimport { SpendingLimitService } from \"../services/spending-limit-service\";\nimport { BankingService } from \"../services/banking-service\";\nimport { UtilityService } from \"../services/utility-service\";\nimport {\n  UniversalKeyPair,\n  InitAuthRequest,\n  InitAuthResponse,\n  CompleteAuthResponse,\n  CompleteAuthAndCreateAccountRequest,\n  SendTransactionRequest,\n  SpendingLimitRequest,\n  GetPasskeysResponse,\n  AddPasskeyRequest,\n  AddPasskeyQueryParams,\n  AddPasskeyResponse,\n  UpdateAccountRequest,\n  CreateAccountResponse,\n  GetAccountResponse,\n  GetAccountBalancesQueryParams,\n  GetTransfersOptions,\n  GetTransactionsResponse,\n  TransferResponse,\n  CreatePaymentIntentRequest,\n  CreatePaymentIntentResponse,\n  UpdateSpendingLimitRequest,\n  UseSpendingLimitRequest,\n  RequestKycLinkRequest,\n  PrepareArbitraryTransactionRequest,\n  PrepareArbitraryTransactionQueryParams,\n  // Trade Smart Transaction types\n  GetTradeQuoteRequest,\n  GetTradeQuoteResponse,\n  CreateTradeSmartTransactionRequest,\n  CreateTradeSmartTransactionResponse,\n  TradeSmartTransactionQuoteRequest,\n  TradeSmartTransactionQuoteResponse,    \n  PrepareTradeSmartTransactionRequest,\n  PrepareTradeSmartTransactionQueryParams,\n  PrepareTradeSmartTransactionResponse,\n  GetTradeSmartTransactionResponse,\n  RemovePasskeyQueryParams,\n  RemovePasskeyResponse,\n  RequestVirtualAccountRequest,\n  GetVirtualAccountsQueryParams,\n  CreateStandingOrderRequest,\n  CreateStandingOrderResponse,\n  GetStandingOrdersQueryParams,\n  StandingOrderResponse,\n  StandingOrdersResponse,\n  SessionSecrets,\n  CompleteAuthRequestWithOtp,\n  SignerProvider,\n  PasskeyRequest,\n  SessionKey,\n  CreatePasskeySessionRequest,\n  CreatePasskeySessionResponse,\n  AuthorizePasskeySessionRequest,\n  AuthorizePasskeySessionResponse,\n  SubmitPasskeySessionRequest,\n  SubmitPasskeySessionResponse,\n  FindPasskeyAccountRequest,\n  FindPasskeyAccountResponse,\n  GetPasskeySessionResponse,\n  GetPasskeyAccountResponse,\n  CreatePasskeyAccountRequest,\n  CreatePasskeyAccountResponse,\n  CompleteAuthAndCreateAccountResponse,\n  PasskeyCredentialData,\n  PasskeyAssertionResponse,\n  RefreshSessionRequest,\n  RefreshSessionResponse,\n  GridClientContext,\n  CreateAccountInput,\n  CreateAccountRequest,\n  AccountBalancesResponse,\n  KycStatusResponse,\n  KycLinkResponse,\n  VirtualAccountsResponse,\n  TransactionSubmissionResponse,\n  SpendingLimitTransactionResponse,\n  CreateSpendingLimitResponse,\n  SpendingLimitResponse,\n  SpendingLimitsResponse,\n  VirtualAccountResponse,\n  CreateProposalRequest,\n  CreateProposalResponse,\n  VoteProposalRequest,\n  VoteProposalResponse,\n  VoteAction,\n  ExecuteProposalRequest,\n  ExecuteProposalResponse,\n} from \"../types\";\nimport { VersionedTransaction } from \"@solana/web3.js\";\n\n/**\n * Grid SDK client for account management, authentication, and transactions\n *\n * @example\n * ```typescript\n * import { GridClient } from '@sqds/grid';\n *\n * const client = new GridClient({\n *   apiKey: 'your-api-key',\n *   environment: 'sandbox'\n * });\n *\n * const state = client.account.get();\n * client.account.on('change', (state) => console.log('Changed:', state));\n * ```\n */\nexport class GridClient implements GridClientInterface {\n  private apiClient: GridApiClient;\n  private authManager: AuthenticationManager;\n  private signingManager: SigningManager;\n  private _accountManager: AccountManager;\n  protected apiConfig: GridApiConfig;\n  private solanaRpcUrl?: string;\n\n  // Context management for user and session state\n  private context: GridClientContext;\n\n  // Service instances\n  private accountService: AccountService;\n  private authService: AuthService;\n  private transactionService: TransactionService;\n  private passkeyService: PasskeyService;\n  private spendingLimitService: SpendingLimitService;\n  private bankingService: BankingService;\n  private utilityService: UtilityService;\n\n  /**\n   * @hidden\n   */\n  constructor(apiConfig: GridApiConfig) {\n    this.apiConfig = apiConfig;\n    this.apiClient = new GridApiClient(apiConfig);\n    this.authManager = new AuthenticationManager(this.apiClient);\n    this.signingManager = new SigningManager();\n    this.solanaRpcUrl = apiConfig.solanaRpcUrl;\n\n    // Initialize empty context with signers array\n    this.context = {\n      client: {\n        environment: this.apiConfig.environment,\n        config: this.apiConfig,\n        solanaRpcUrl: this.solanaRpcUrl,\n      },\n      user: {\n        signers: [],\n      },\n    };\n\n    // Initialize account manager with context reference\n    this._accountManager = new AccountManager(this.context);\n\n    // Initialize services\n    this.accountService = new AccountService(this.apiClient, this.context);\n    this.authService = new AuthService(this.apiClient, this.authManager, this._accountManager, this.context);\n    this.transactionService = new TransactionService(this.apiClient, this.signingManager);\n    this.passkeyService = new PasskeyService(this.apiClient);\n    this.spendingLimitService = new SpendingLimitService(this.apiClient);\n    this.bankingService = new BankingService(this.apiClient);\n    this.utilityService = new UtilityService();\n  }\n\n  /**\n   * Account manager for reactive state management\n   *\n   * Provides access to account state and event subscriptions for reactive updates.\n   * Subscribe to the 'change' event to receive notifications when the account state changes.\n   *\n   * @example\n   * ```typescript\n   * client.account.on('change', (account) => {\n   *   console.log('Account updated:', account);\n   * });\n   *\n   * const current = client.account.get();\n   * console.log(current.accountAddress, current.isConnected);\n   *\n   * client.account.set('account-address', 'grid-user-id');\n   *\n   * client.account.disconnect();\n   * ```\n   *\n   * @category Account Management\n   */\n  get account(): AccountManager {\n    return this._accountManager;\n  }\n\n  /**\n   * Get client configuration\n   *\n   * @example\n   * ```typescript\n   * const config = client.getConfig();\n   * console.log(config.environment, config.baseUrl);\n   * ```\n   *\n   * @category Configuration\n   */\n  getConfig(): GridApiConfig {\n    return {\n      apiKey: this.apiConfig.apiKey,\n      environment: this.apiConfig.environment,\n      baseUrl: this.apiConfig.baseUrl,\n      appId: this.apiConfig.appId,\n      timeout: this.apiConfig.timeout,\n      retryAttempts: this.apiConfig.retryAttempts,\n      solanaRpcUrl: this.apiConfig.solanaRpcUrl,\n    };\n  }\n\n  /**\n   * Extract a Solana VersionedTransaction ready to be signed using solana web3.js\n   *\n   * @param transactionData - Grid transaction response containing the transaction\n   * @returns Deserialized VersionedTransaction ready for signing\n   *\n   * @example\n   * ```typescript\n   * const preparedTx = await gridClient.prepareArbitraryTransaction(accountAddress, prepareRequest);\n   * const signableTransaction = gridClient.extractSignableTransaction(preparedTx);\n   * ```\n   */\n  extractSignableTransaction(transactionData: TransactionPayload): VersionedTransaction {\n    return this.transactionService.extractSignableTransaction(transactionData);\n  }\n\n  /**\n   * Set an externally signed transaction into Grid transaction object so you can submit it via grid api.\n   *\n   * @param transactionData - Original Grid transaction data\n   * @param externallySignedTransaction - The signed VersionedTransaction\n   * @returns Updated Grid transaction response with signed transaction data\n   *\n   * @example\n   * ```typescript\n   * transaction.sign([externalSigner]);\n   *\n   * const signedTxData = gridClient.setExternallySignedTransaction(\n   *   originalTxData,\n   *   transaction\n   * );\n   * ```\n   */\n  setExternallySignedTransaction(transactionData: TransactionPayload, externallySignedTransaction: VersionedTransaction): TransactionPayload {\n    return this.transactionService.setExternallySignedTransaction(transactionData, externallySignedTransaction);\n  }\n  \n  /**\n   * Initialize authentication for an existing user.\n   * This is the first step in the authentication process.\n   *\n   * Note: For new users, you must call createAccount first to create an account before initializing authentication. This method is only for authenticating existing users.\n   *\n   * @param request - Authentication request containing email, keypair, or passkey information\n   * @returns Promise resolving to authentication initialization response with OTP details\n   *\n   * @example\n   * ```typescript\n   * const response = await gridClient.initAuth({\n   *   email: 'user@example.com'\n   * });\n   * ```\n   *\n   * @category Authentication\n   */\n  async initAuth(\n    request: InitAuthRequest | AuthenticationRequest\n  ): Promise<InitAuthResponse> {\n    return await this.authService.initAuth(request);\n  }\n\n  /**\n   * This is the second step in email-based authentication. Verifies the OTP\n   * code received via email and establishes an authenticated session.\n   *\n   * Note: For new users who need to create an account, use completeAuthAndCreateAccount instead, which completes authentication and creates the account in one step.\n   *\n   * @param request - Complete authentication request with OTP code and user context\n   * @returns Promise resolving to authentication completion response with session data\n   *\n   * @example\n   * ```typescript\n   * const sessionSecrets = await gridClient.generateSessionSecrets();\n   * const response = await gridClient.completeAuth({\n   *   otpCode: '123456',\n   *   user: <user object received from initAuth>,\n   *   sessionSecrets: sessionSecrets\n   * });\n   * ```\n   *\n   * @category Authentication\n   */\n  async completeAuth(\n    request: CompleteAuthRequestWithOtp\n  ): Promise<CompleteAuthResponse> {\n    return await this.authService.completeAuth(request);\n  }\n\n  /**\n   * Complete authentication and create account (streamlined onboarding)\n   *\n   * @param request - Auth completion and account creation request\n   * @returns Created account information\n   *\n   * @example\n   * ```typescript\n   * const sessionSecrets = await gridClient.generateSessionSecrets();\n   * const account = await gridClient.completeAuthAndCreateAccount({\n   *   otpCode: '123456',\n   *   user,\n   *   sessionSecrets\n   * });\n   * ```\n   *\n   * @category Authentication\n   */\n  async completeAuthAndCreateAccount(\n    request: CompleteAuthAndCreateAccountRequest\n  ): Promise<CompleteAuthAndCreateAccountResponse> {\n    return await this.authService.completeAuthAndCreateAccount(request);\n  }\n\n  /**\n   * Refresh MPC provider session to extend lifetime\n   *\n   * Note: Currently supports Privy only. Turnkey refresh not yet implemented.\n   *\n   * @param request - Session refresh request\n   * @returns Refreshed session data\n   *\n   * @example\n   * ```typescript\n   * const refreshed = await gridClient.refreshSession({\n   *   kmsPayload: { provider: 'privy', session: currentSession },\n   *   encryptionPublicKey: encryptionKey\n   * });\n   * ```\n   *\n   * @category Authentication\n   */\n  async refreshSession(\n    request: RefreshSessionRequest\n  ): Promise<RefreshSessionResponse> {\n    return await this.authService.refreshSession(request);\n  }\n\n  /**\n   * Generate session secrets for all supported providers\n   *\n   * @example\n   * ```typescript\n   * const sessionSecrets = await gridClient.generateSessionSecrets();\n   * ```\n   *\n   * @category Key Management\n   */\n  async generateSessionSecrets(): Promise<SessionSecrets> {\n    return await this.authService.generateSessionSecrets();\n  }\n\n  /**\n   * @hidden\n   * Generate a keypair for a specific provider\n   *\n   * Creates a new keypair for the specified authentication provider.\n   * If no provider is specified, defaults to Privy.\n   *\n   * @param provider - Optional provider type ('privy', 'turnkey', 'solana', 'passkey')\n   * @returns Promise resolving to a universal keypair with public and private keys\n   *\n   * @example\n   * ```typescript\n   * const keypair = await gridClient.generateKeyPair();\n   *\n   * const backupKeypair = await gridClient.generateKeyPair('turnkey');\n   *\n   * console.log(keypair.publicKey);\n   * ```\n   *\n   * @category Key Management\n   */\n  async generateKeyPair(provider?: SignerProvider): Promise<UniversalKeyPair> {\n    return await this.authService.generateKeyPair(provider);\n  }\n\n  /**\n   * Automatically selects the appropriate authentication provider based on the\n   * session context and available session secrets.\n   *\n   * @param request - Sign request containing transaction payload and session secrets\n   * @returns Promise resolving to transaction result with signatures and metadata\n   *\n   * @example\n   * ```typescript\n   * const authResult = await gridClient.completeAuth(payload);\n   * const preparedTx = await gridClient.prepareArbitraryTransaction(accountAddress, {\n   *   transaction: 'base64-encoded-transaction'\n   * });\n   *\n   * const signResult = await gridClient.sign({\n   *   sessionSecrets: sessionSecrets,\n   *   transactionPayload: preparedTx,\n   *   session: authResult.authentication\n   * });\n   * ```\n   *\n   * @category Transaction Signing\n   */\n  async sign(request: SignRequest): Promise<TransactionResult> {\n    return await this.transactionService.sign(request);\n  }\n\n  /**\n   * Sign and send a transaction. Automatically selects the appropriate authentication provider based on the\n   * session context and available session secrets\n   *\n   * @param request - Sign and send request containing transaction payload and session secrets\n   * @returns Promise resolving to transaction submission result with blockchain signature\n   *\n   * @example\n   * ```typescript\n   * const authResult = await gridClient.completeAuth(payload);\n   * const preparedTx = await gridClient.prepareArbitraryTransaction(accountAddress, {\n   *   transaction: 'base64-encoded-transaction'\n   * });\n   *\n   * const result = await gridClient.signAndSend({\n   *   sessionSecrets: sessionSecrets,\n   *   transactionPayload: preparedTx,\n   *   session: authResult.authentication,\n   *   address: accountAddress\n   * });\n   *\n   * ```\n   *\n   * @category Transaction Signing\n   */\n  async signAndSend(request: SignAndSendRequest): Promise<TransactionSubmissionResponse> {\n    return await this.transactionService.signAndSend(request);\n  }\n\n  /**\n   * Submits a previously signed transaction to the Solana blockchain through\n   * the Grid API.\n   *\n   * @param request - Send request containing the signed transaction and account address\n   * @returns Promise resolving to transaction submission result with signature\n   *\n   * @example\n   * ```typescript\n   * const signedTx = await gridClient.sign({ ... });\n   * const result = await gridClient.send({\n   *   signedTransactionPayload: signedTx,\n   *   address: 'account-address'\n   * });\n   * ```\n   *\n   * @category Transaction Signing\n   */\n  async send(request: SendTransactionRequest): Promise<TransactionSubmissionResponse> {\n    return await this.transactionService.send(request);\n  }\n\n  /**\n   * Creates either an email-based account (requires OTP verification)\n   * or a signer-based account (immediately active).\n   *\n   * @param input - Account creation input (simplified) or full request object with policies\n   * @returns Promise resolving to created account information\n   *\n   * Note: When passing AccountPolicies with signers, role defaults to 'primary' and provider defaults to 'external' if not specified.\n   *\n   * @example Email account\n   * ```typescript\n   * const emailAccount = await gridClient.createAccount({\n   *   email: 'user@example.com'\n   * });\n   * ```\n   *\n   * @example Signer account (simplified)\n   * ```typescript\n   * const signerAccount = await gridClient.createAccount({\n   *   signer: 'BKKjHs7kKsWFm8GKuFz3HzNKBjH4K4HhjhwxDHrRfKjj'\n   * });\n   * ```\n   *\n   * @example Configure account policies\n   * ```typescript\n   * const signerAccount = await gridClient.createAccount({\n   *   signers: [\n   *     {\n   *       address: 'BKKjHs7kKsWFm8GKuFz3HzNKBjH4K4HhjhwxDHrRfKjj',\n   *       permissions: ['CAN_INITIATE', 'CAN_VOTE']\n   *     }\n   *   ],\n   *   threshold: 1,\n   *   timeLock: null,\n   *   adminAddress: null\n   * });\n   * ```\n   *\n   * @category Authentication\n   */\n  async createAccount(\n    input: CreateAccountInput | CreateAccountRequest\n  ): Promise<CreateAccountResponse> {\n    return await this.authService.createAccount(input);\n  }\n\n  /**\n   * Retrieves comprehensive account details including account type, policies,\n   * signers, thresholds, and metadata.\n   *\n   * @param accountAddress - The account address to retrieve information for\n   * @returns Promise resolving to account details or error information\n   *\n   * @example\n   * ```typescript\n   * const account = await gridClient.getAccount('account-address');\n   * ```\n   *\n   * @category Account Management\n   */\n  async getAccount(accountAddress: string): Promise<GetAccountResponse> {\n    return await this.accountService.getAccount(accountAddress);\n  }\n\n  /**\n   * Update account settings and configuration such as policies, signers, thresholds, and metadata.\n   *\n   * @param accountAddress - The account address to update\n   * @param request - Update request containing the fields to modify\n   * @param admin - Whether to perform the update with admin privileges (optional)\n   * @returns Promise resolving to transaction response for the update operation\n   *\n   * @example\n   * ```typescript\n   * const updateTx = await gridClient.updateAccount(accountAddress, {\n   *   policies: {\n   *     threshold: 2\n   *   }\n   * });\n   *\n   * const adminUpdateTx = await gridClient.updateAccount(\n   *   accountAddress,\n   *   { policies: { threshold: 1 } },\n   *   true\n   * );\n   * ```\n   *\n   * @category Account Management\n   */\n  async updateAccount(\n    accountAddress: string,\n    request: UpdateAccountRequest,\n    admin?: boolean\n  ): Promise<TransactionResponse> {\n    return await this.accountService.updateAccount(accountAddress, request, admin);\n  }\n\n  /**\n   * Get account token balances\n   *\n   * Retrieves the current token balances for an account, including both\n   * native SOL and SPL token balances. Supports filtering and pagination.\n   *\n   * @param accountAddress - The account address to get balances for\n   * @param queryParams - Optional query parameters for filtering and pagination\n   * @returns Promise resolving to account balances response\n   *\n   * @example\n   * ```typescript\n   * const balances = await gridClient.getAccountBalances(accountAddress);\n   * ```\n   */\n  async getAccountBalances(\n    accountAddress: string,\n    queryParams?: GetAccountBalancesQueryParams\n  ): Promise<AccountBalancesResponse> {\n    return await this.accountService.getAccountBalances(accountAddress, queryParams);\n  }\n\n  /**\n   * Retrieves the transaction history for an account, including incoming and\n   * outgoing transfers. Supports filtering by date range, token type, and pagination.\n   *\n   * @param accountAddress - The account address to get transfers for\n   * @param options - Optional filtering and pagination options\n   * @returns Promise resolving to transfers response with transaction history\n   *\n   * @example\n   * ```typescript\n   * const transfers = await gridClient.getTransfers(accountAddress);\n   * ```\n   *\n   * @category Account Management\n   */\n  async getTransfers(\n    accountAddress: string,\n    options?: GetTransfersOptions\n  ): Promise<TransferResponse> {\n    return await this.accountService.getTransfers(accountAddress, options);\n  }\n\n  /**\n   * Retrieves the blockchain transaction history for an account\n   *\n   * Returns a list of Solana blockchain transactions associated with the account,\n   * including transaction signatures, statuses, and timestamps. This includes all\n   * on-chain activity for the account.\n   *\n   * @param accountAddress - The account address to get transactions for\n   * @returns Promise resolving to transaction history response\n   *\n   * @example\n   * ```typescript\n   * const response = await gridClient.getTransactions(accountAddress);\n   * if (response.data?.transactions) {\n   *   response.data.transactions.forEach(tx => {\n   *     console.log(tx.signature, tx.status);\n   *   });\n   * }\n   * ```\n   *\n   * @category Account Management\n   */\n  async getTransactions(accountAddress: string): Promise<GetTransactionsResponse> {\n    return await this.accountService.getTransactions(accountAddress);\n  }\n\n  /**\n   * Creates a new spending limit.\n   *\n   * @param smartAccountAddress - The account address to create spending limit for\n   * @param request - Spending limit configuration including amount, token, and period\n   * @returns Promise resolving to transaction response for spending limit creation\n   *\n   * @example\n   * ```typescript\n   * const spendingLimitTx = await gridClient.createSpendingLimit(accountAddress, {\n   *   amount: 10000000, \n   *   mint: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',\n   *   period: 'daily',\n   *   spendingLimitSigners: ['limit-signer-address']\n   * });\n   * ```\n   *\n   * @category Spending Limits\n   */\n  async createSpendingLimit(\n    smartAccountAddress: string,\n    request: SpendingLimitRequest\n  ): Promise<CreateSpendingLimitResponse> {\n    return await this.spendingLimitService.createSpendingLimit(smartAccountAddress, request);\n  }\n\n  /**\n   * Modifies the parameters of an existing spending limit, such as the amount,\n   * time period, or associated signers.\n   *\n   * @param accountAddress - The account address that owns the spending limit\n   * @param spendingLimitAddress - The address of the spending limit to update\n   * @param request - Update request with new spending limit parameters\n   * @returns Promise resolving to transaction response for the update\n   *\n   * @example\n   * ```typescript\n   * const updateTx = await gridClient.updateSpendingLimit(\n   *   amount: \"5000000\",\n   *   spendingLimitSigners: ['signer-address']\n   * );\n   * ```\n   *\n   * @category Spending Limits\n   */\n  async updateSpendingLimit(\n    accountAddress: string,\n    spendingLimitAddress: string,\n    request: UpdateSpendingLimitRequest\n  ): Promise<SpendingLimitTransactionResponse> {\n    return await this.spendingLimitService.updateSpendingLimit(accountAddress, spendingLimitAddress, request);\n  }\n\n  /**\n   * Delete a spending limit\n   *\n   * Removes an existing spending limit from an account, allowing unrestricted\n   * spending for the associated token type.\n   *\n   * @param accountAddress - The account address that owns the spending limit\n   * @param spendingLimitAddress - The address of the spending limit to delete\n   * @returns Promise resolving to transaction response for the deletion\n   *\n   * @example\n   * ```typescript\n   * const deleteTx = await gridClient.deleteSpendingLimit(\n   *   accountAddress,\n   *   spendingLimitAddress\n   * );\n   * ```\n   *\n   * @category Spending Limits\n   */\n  async deleteSpendingLimit(\n    accountAddress: string,\n    spendingLimitAddress: string\n  ): Promise<SpendingLimitTransactionResponse> {\n    return await this.spendingLimitService.deleteSpendingLimit(accountAddress, spendingLimitAddress);\n  }\n\n  /**\n   * Use a spending limit for a transaction\n   *\n   * Utilizes an existing spending limit to authorize a transaction, automatically\n   * checking that the transaction amount is within the limit constraints.\n   *\n   * @param accountAddress - The account address that owns the spending limit\n   * @param spendingLimitAddress - The address of the spending limit to use\n   * @param request - Transaction request to authorize against the spending limit\n   * @returns Promise resolving to transaction response for the authorized transaction\n   *\n   * @example\n   * ```typescript\n   * const limitTx = await gridClient.useSpendingLimit(\n   *   accountAddress,\n   *   spendingLimitAddress,\n   *   {\n   *     amount: 500000000,\n   *     signerAddress: \"signer-address\",\n   *     recipientAddress: \"recipient-address\"\n   *   }\n   * );\n   * ```\n   *\n   * @category Spending Limits\n   */\n  async useSpendingLimit(\n    accountAddress: string,\n    spendingLimitAddress: string,\n    request: UseSpendingLimitRequest\n  ): Promise<SpendingLimitTransactionResponse> {\n    return await this.spendingLimitService.useSpendingLimit(accountAddress, spendingLimitAddress, request);\n  }\n\n  /**\n   * Retrieves a spending limit by its address\n   *\n   * @param accountAddress - The account address that owns the spending limit\n   * @param spendingLimitAddress - The address of the spending limit to retrieve\n   * @returns Promise resolving to spending limit data\n   *\n   * @example\n   * ```typescript\n   * const spendingLimit = await gridClient.getSpendingLimit(\n   *   accountAddress,\n   *   spendingLimitAddress\n   * );\n   * console.log(spendingLimit.amount);\n   * console.log(spendingLimit.remainingAmount);\n   * ```\n   *\n   * @category Spending Limits\n   */\n  async getSpendingLimit(\n    accountAddress: string,\n    spendingLimitAddress: string\n  ): Promise<SpendingLimitResponse> {\n    return await this.spendingLimitService.getSpendingLimit(accountAddress, spendingLimitAddress);\n  }\n\n\n  /**\n   * Retrieves all spending limits for an account\n   *\n   * @param accountAddress - The account address to get spending limits for\n   * @returns Promise resolving to array of spending limit data\n   *\n   * @example\n   * ```typescript\n   * const limits = await gridClient.getSpendingLimits(accountAddress);\n   * limits.forEach(limit => {\n   *   console.log(`Limit: ${limit.amount}, Remaining: ${limit.remainingAmount}`);\n   * });\n   * ```\n   *\n   * @category Spending Limits\n   */\n  async getSpendingLimits(accountAddress: string): Promise<SpendingLimitsResponse> {\n    return await this.spendingLimitService.getSpendingLimits(accountAddress);\n  }\n\n  /**\n   * Retrieves all passkeys for an account\n   *\n   * @param accountAddress - The account address to get passkeys for\n   * @returns Promise resolving to passkeys response with credential details\n   *\n   * @example\n   * ```typescript\n   * const passkeys = await gridClient.getPasskeys(accountAddress);\n   * ```\n   *\n   * @category Passkey Management\n   */\n  async getPasskeys(accountAddress: string): Promise<GetPasskeysResponse> {\n    return await this.passkeyService.getPasskeys(accountAddress);\n  }\n\n  /**\n   * Registers a new passkey for an account.\n   * \n   * @param accountAddress - The account address to add the passkey to\n   * @param request - Passkey registration request with credential data\n   * @param queryParams - Optional query parameters for the registration\n   * @returns Promise resolving to passkey addition response\n   *\n   * @example\n   * ```typescript\n   * const passkeyResponse = await gridClient.addPasskey(accountAddress, {\n   *   passkey: {\n   *     address: \"2W6cUhpELHYhTi3Cn6SmHfVhJFKgqmUJLJ5V2DQNcaXE\",\n   *     role: \"secondary\",\n   *     permissions: [\"CAN_INITIATE\", \"CAN_VOTE\", \"CAN_EXECUTE\"]\n   *   }\n   * });\n   * ```\n   *\n   * @category Passkey Management\n   */\n  async addPasskey(\n    accountAddress: string,\n    request: AddPasskeyRequest,\n    queryParams?: AddPasskeyQueryParams\n  ): Promise<AddPasskeyResponse> {\n    return await this.passkeyService.addPasskey(accountAddress, request, queryParams);\n  }\n\n  /**\n   * Removes an existing passkey credential from an account, revoking its\n   * ability to authorize transactions.\n   *\n   * @param accountAddress - The account address that owns the passkey\n   * @param passkeyAddress - The address of the passkey to remove\n   * @param request - Passkey removal request with authorization details\n   * @param queryParams - Optional query parameters for the removal\n   * @returns Promise resolving to passkey removal response\n   *\n   * @example\n   * ```typescript\n   * const removeResponse = await gridClient.removePasskey(\n   *   accountAddress,\n   *   passkeyAddress\n   * );\n   * ```\n   *\n   * @category Passkey Management\n   */\n  async removePasskey(\n    accountAddress: string,\n    passkeyAddress: string,\n    transactionSigners?: string[],\n    queryParams?: RemovePasskeyQueryParams\n  ): Promise<RemovePasskeyResponse> {\n    return await this.passkeyService.removePasskey(accountAddress, passkeyAddress, transactionSigners, queryParams);\n  }\n\n  /**\n   * Initiates a payment intent that allows users to deposit fiat currency\n   * and receive cryptocurrency in their account. Handles the complete\n   * fiat-to-crypto conversion process.\n   *\n   * Note: Non-Enterprise customers must provide a `feeConfig` in the request.\n   * Enterprise customers may omit it as fees are handled by their plan.\n   *\n   * @param accountAddress - The account address to receive the converted crypto\n   * @param request - Payment intent request with amount, currency, and payment method\n   * @returns Promise resolving to payment intent response with transaction details\n   *\n   * @example\n   * ```typescript\n   * const paymentIntent = await gridClient.createPaymentIntent(accountAddress, {\n   *   amount: \"100000\",\n   *   source: {\n   *     account: accountAddress,\n   *     currency: \"usdc\"\n   *   },\n   *   destination: {\n   *     address: \"3ciascNndLTBrDQXvs8nzZgWAiaL33tGM6fx3zzM7Fxt\",\n   *     currency: \"usdc\"\n   *   },\n   *   feeConfig: {\n   *     currency: \"usdc\",\n   *     payerAddress: accountAddress\n   *   }\n   * });\n   * console.log(paymentIntent.data.paymentUrl);\n   * ```\n   *\n   * @category Payment Processing\n   */\n  async createPaymentIntent(\n    accountAddress: string,\n    request: CreatePaymentIntentRequest\n  ): Promise<CreatePaymentIntentResponse> {\n    return await this.bankingService.createPaymentIntent(accountAddress, request);\n  }\n\n  /**\n   * Generates a link for Know Your Customer (KYC) identity verification.\n   * Users complete the verification process through the provided link.\n   *\n   * @param accountAddress - The account address to associate with KYC\n   * @param request - KYC link request with verification requirements\n   * @returns Promise resolving to KYC link response with verification URL\n   *\n   * @example\n   * ```typescript\n   * const kycLink = await gridClient.requestKycLink(accountAddress, {\n   *   gridUserId: user.gridUserId,\n   *   type: 'individual',\n   *   email: 'user@example.com',\n   *   fullName: 'John Doe',\n   *   endorsements: [],\n   *   redirectUri: 'your-redirect-uri'\n   * });\n   * ```\n   *\n   * @category KYC Verification\n   */\n  async requestKycLink(\n    accountAddress: string,\n    request: RequestKycLinkRequest\n  ): Promise<KycLinkResponse> {\n    return await this.bankingService.requestKycLink(accountAddress, request);\n  }\n\n  /**\n   * Get KYC verification status\n   *\n   * Retrieves the current status of a KYC verification process, including\n   * completion status, verification level, and any required actions.\n   *\n   * @param accountAddress - The account address associated with KYC\n   * @param kycId - The KYC verification identifier\n   * @returns Promise resolving to KYC status response\n   *\n   * @example\n   * ```typescript\n   * const kycStatus = await gridClient.getKycStatus(accountAddress, kycId);\n   * if (kycStatus.success) {\n   *   console.log(kycStatus.data.status); // 'pending', 'approved', 'rejected'\n   *   console.log(kycStatus.data.verificationLevel); // Verification tier achieved\n   * }\n   * ```\n   *\n   * @category KYC Verification\n   */\n  async getKycStatus(\n    accountAddress: string,\n    kycId: string\n  ): Promise<KycStatusResponse> {\n    return await this.bankingService.getKycStatus(accountAddress, kycId);\n  }\n\n  /**\n   * Prepares any Solana transaction for signing by adding necessary account\n   * metadata, fee calculations, and smart account integration.\n   *\n   * @param accountAddress - The account address that will sign the transaction\n   * @param request - Transaction preparation request with the raw transaction\n   * @param queryParams - Optional query parameters for transaction preparation\n   * @returns Promise resolving to prepared transaction response ready for signing\n   *\n   * @example\n   * ```typescript\n   * const preparedTx = await gridClient.prepareArbitraryTransaction(accountAddress, {\n   *   transaction: 'base64-encoded-solana-transaction'\n   * });\n   *\n   * const signedTx = await gridClient.sign({\n   *   sessionSecrets: sessionSecrets,\n   *   transactionPayload: preparedTx\n   * });\n   * ```\n   *\n   * @category Transaction Processing\n   */\n  async prepareArbitraryTransaction(\n    accountAddress: string,\n    request: PrepareArbitraryTransactionRequest,\n    queryParams?: PrepareArbitraryTransactionQueryParams\n  ): Promise<TransactionResponse> {\n    return await this.transactionService.prepareArbitraryTransaction(accountAddress, request, queryParams);\n  }\n\n  // ============= Trade Smart Transaction Methods =============\n\n  /**\n   * Create a trade policy with spending limits and authorized signers.\n   *\n   * Note: Policies define allowed tokens, spending limits per period, and authorized signers for automated trading.\n   *\n   * @param accountAddress - Smart account address\n   * @param request - Policy configuration with signers, rules, and spending constraints\n   * @returns Policy address and transaction to sign\n   *\n   * @example\n   * ```typescript\n   * const response = await client.createTradeSmartTransaction(accountAddress, {\n   *   policies: {\n   *     signers: [{ address: 'XXXxx...', permissions: ['CAN_INITIATE', 'CAN_VOTE', 'CAN_EXECUTE'] }],\n   *     threshold: 1\n   *   },\n   *   rules: {\n   *     allowedInputs: [{\n   *       mint: 'So11111111111111111111111111111111111111112',\n   *       allowance: { amount: '1000000000', cadence: 'Daily' }\n   *     }],\n   *     allowedOutputs: ['EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'],\n   *     maxSlippageBps: 100,\n   *     feesBps: 10,\n   *     venue: 'jupiter'\n   *   }\n   * });\n   * ```\n   *\n   * @category Trade Smart Transactions\n   */\n  async createTradeSmartTransaction(\n    accountAddress: string,\n    request: CreateTradeSmartTransactionRequest\n  ): Promise<CreateTradeSmartTransactionResponse> {\n    return await this.apiClient.createTradeSmartTransaction(accountAddress, request);\n  }\n\n  /**\n   * Get a trade quote validated against policy constraints.\n   *\n   * Note: Quote checks spending limits and validates input/output tokens before returning price.\n   *\n   * @param accountAddress - Smart account address\n   * @param smartTransactionAddress - Policy address\n   * @param request - Quote parameters with venue, tokens, amount, and slippage\n   * @returns Validated quote from trading venue\n   *\n   * @example\n   * ```typescript\n   * const quote = await client.getTradeSmartTransactionQuote(\n   *   accountAddress,\n   *   smartTransactionAddress,\n   *   {\n   *     venue: 'jupiter',\n   *     fromMint: 'So11111111111111111111111111111111111111112',\n   *     toMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',\n   *     amount: 100000000,\n   *     slippageBps: 50\n   *   }\n   * );\n   * ```\n   *\n   * @category Trade Smart Transactions\n   */\n  async getTradeSmartTransactionQuote(\n    accountAddress: string,\n    smartTransactionAddress: string,\n    request: TradeSmartTransactionQuoteRequest\n  ): Promise<TradeSmartTransactionQuoteResponse> {\n    return await this.apiClient.getTradeSmartTransactionQuote(accountAddress, smartTransactionAddress, request);\n  }\n\n  /**\n   * Prepare a trade transaction with policy validation.\n   *\n   * Note: Validates against spending limits and allowed tokens before building transaction.\n   *\n   * @param accountAddress - Smart account address\n   * @param smartTransactionAddress - Policy address\n   * @param request - Trade details or pre-fetched quote\n   * @param queryParams - Optional debug mode for simulation logs\n   * @returns Prepared transaction with KMS payloads for signing\n   *\n   * @example\n   * ```typescript\n   * const tx = await client.prepareTradeSmartTransaction(\n   *   accountAddress,\n   *   smartTransactionAddress,\n   *   {\n   *     tradeArgs: {\n   *       type: 'arguments',\n   *       input: 'So11111111111111111111111111111111111111112',\n   *       output: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',\n   *       amount: 100000000,\n   *       slippageBps: 50,\n   *       feeBps: 10\n   *     }\n   *   }\n   * );\n   * ```\n   *\n   * @category Trade Smart Transactions\n   */\n  async prepareTradeSmartTransaction(\n    accountAddress: string,\n    smartTransactionAddress: string,\n    request: PrepareTradeSmartTransactionRequest,\n    queryParams?: PrepareTradeSmartTransactionQueryParams\n  ): Promise<PrepareTradeSmartTransactionResponse> {\n    return await this.apiClient.prepareTradeSmartTransaction(\n      accountAddress,\n      smartTransactionAddress,\n      request,\n      queryParams\n    );\n  }\n\n  // ============= Proposal Methods =============\n  /**\n   *  Create a proposal\n   * @param accountAddress - Account address\n   * @param request - Create proposal request\n   * @returns Promise resolving to create proposal response\n   *\n   * @example\n   * ```typescript\n   * const proposal = await client.createProposal(accountAddress, {\n   *   transaction: 'base64-encoded-solana-transaction',\n   *   signer: 'signer-pubkey',\n   *   rentPayer: 'rent-payer-pubkey'\n   * });\n   * ```\n   *\n   * @category Proposal\n   */\n  async createProposal(accountAddress: string, request: CreateProposalRequest): Promise<CreateProposalResponse> {\n    return await this.transactionService.createProposal(accountAddress, request);\n  }\n\n  /**\n   * Vote on a proposal\n   *\n   * Vote to approve, reject, or cancel a proposal on a smart account.\n   *\n   * @param accountAddress - Smart account address\n   * @param proposalAddress - Proposal address\n   * @param request - Vote proposal request containing signers and action\n   * @returns Promise resolving to vote proposal response with unsigned transaction\n   *\n   * @example\n   * ```typescript\n   * const voteResult = await client.voteProposal(\n   *   accountAddress,\n   *   proposalAddress,\n   *   {\n   *     signers: ['signer-pubkey-1', 'signer-pubkey-2'],\n   *     action: 'approve'\n   *   }\n   * );\n   * console.log('Transaction:', voteResult.data.transaction);\n   * console.log('Signers needed:', voteResult.data.transactionSigners);\n   * ```\n   *\n   * @category Proposal\n   */\n  async voteProposal(\n    accountAddress: string,\n    proposalAddress: string,\n    request: VoteProposalRequest\n  ): Promise<VoteProposalResponse> {\n    return await this.transactionService.voteProposal(accountAddress, proposalAddress, request);\n  }\n\n  /**\n   * Execute a proposal\n   *\n   * Execute an approved proposal on a smart account.\n   *\n   * Important:\n   * - Signer must have CAN_EXECUTE permission\n   * - Proposal must be in Approved state\n   * - Returns unsigned transaction with signatures\n   * - The transactionSignatures array can contain multiple signatures\n   *\n   * @param accountAddress - Smart account address\n   * @param proposalAddress - Proposal address\n   * @param request - Execute proposal request with signer\n   * @returns Promise resolving to execute proposal response with unsigned transaction\n   *\n   * @example\n   * ```typescript\n   * const executeResult = await client.executeProposal(\n   *   accountAddress,\n   *   proposalAddress,\n   *   { signer: 'executor-pubkey' }\n   * );\n   * console.log('Transaction:', executeResult.data.transaction);\n   * console.log('Signatures:', executeResult.data.transactionSignatures);\n   * ```\n   *\n   * @category Proposal\n   */\n  async executeProposal(\n    accountAddress: string,\n    proposalAddress: string,\n    request: ExecuteProposalRequest\n  ): Promise<ExecuteProposalResponse> {\n    return await this.transactionService.executeProposal(accountAddress, proposalAddress, request);\n  }\n\n  /**\n   * Retrieve policy details and current spending limit status.\n   *\n   * @param accountAddress - Smart account address\n   * @param smartTransactionAddress - Policy address\n   * @returns Policy configuration and tradable assets with remaining allowances\n   *\n   * @example\n   * ```typescript\n   * const result = await client.getTradeSmartTransaction(accountAddress, smartTransactionAddress);\n   * ```\n   *\n   * @category Trade Smart Transactions\n   */\n  async getTradeSmartTransaction(\n    accountAddress: string,\n    smartTransactionAddress: string\n  ): Promise<GetTradeSmartTransactionResponse> {\n    return await this.apiClient.getTradeSmartTransaction(accountAddress, smartTransactionAddress);\n  }\n\n  /**\n   * Creates a virtual bank account that allows users to receive fiat deposits\n   * which are automatically converted to cryptocurrency in their Grid account.\n   *\n   * @param accountAddress - The account address to associate with the virtual account\n   * @param request - Virtual account request with banking details and preferences\n   * @returns Promise resolving to virtual account response with banking details\n   *\n   * @example\n   * ```typescript\n   * const virtualAccount = await gridClient.requestVirtualAccount(accountAddress, {\n   *   gridUserId: 'grid-user-id',\n   *   currency: 'usd' as const\n   * });\n   * ```\n   *\n   * @category Virtual Accounts\n   */\n  async requestVirtualAccount(\n    accountAddress: string,\n    request: RequestVirtualAccountRequest\n  ): Promise<VirtualAccountResponse> {\n    return await this.bankingService.requestVirtualAccount(accountAddress, request);\n  }\n\n  /**\n   * Retrieves all virtual bank accounts associated with a Grid account,\n   * including their status, balances, and transaction history.\n   *\n   * @param accountAddress - The account address to get virtual accounts for\n   * @param queryParams - Optional query parameters for filtering and pagination\n   * @returns Promise resolving to virtual accounts response\n   * \n   * @example\n   * ```typescript\n   * const virtualAccounts = await gridClient.getVirtualAccounts(accountAddress);\n   * ```\n   *\n   * @category Virtual Accounts\n   */\n  async getVirtualAccounts(\n    accountAddress: string,\n    queryParams?: GetVirtualAccountsQueryParams\n  ): Promise<VirtualAccountsResponse> {\n    return await this.bankingService.getVirtualAccounts(accountAddress, queryParams);\n  }\n\n  /**\n   * Create a standing order.\n   *\n   * @param accountAddress - The account address that will make the recurring payments\n   * @param request - Standing order request with payment details and schedule\n   * @returns Promise resolving to standing order creation response\n   *\n   * @example\n   * ```typescript\n   * const standingOrder = await gridClient.createStandingOrder(accountAddress, {\n   *   amount: \"500000\",\n   *   gridUserId: \"grid-user-id\",\n   *   source: {\n   *     account: \"source-address\",\n   *     currency: \"usdc\"\n   *   },\n   *   destination: {\n   *     address: \"destination-address\",\n   *     currency: \"usdc\"\n   *   },\n   *   frequency: \"weekly\",\n   *   startDate: \"2024-12-02T10:00:00Z\",\n   *   endDate: \"2025-12-31T23:59:59Z\"\n   * });\n   * ```\n   *\n   * @category Standing Orders\n   */\n  async createStandingOrder(\n    accountAddress: string,\n    request: CreateStandingOrderRequest\n  ): Promise<CreateStandingOrderResponse> {\n    return await this.bankingService.createStandingOrder(accountAddress, request);\n  }\n\n  /**\n   * Retrieves all standing orders associated with an account, including\n   * active, paused, and completed recurring payment schedules.\n   *\n   * @param accountAddress - The account address to get standing orders for\n   * @param queryParams - Optional query parameters for filtering and pagination\n   * @returns Promise resolving to standing orders response\n   *\n   * @example\n   * ```typescript\n   * const standingOrders = await gridClient.getStandingOrders(accountAddress);\n   * ```\n   *\n   * @category Standing Orders\n   */\n  async getStandingOrders(\n    accountAddress: string,\n    queryParams?: GetStandingOrdersQueryParams\n  ): Promise<StandingOrdersResponse> {\n    return await this.bankingService.getStandingOrders(accountAddress, queryParams);\n  }\n\n  /**\n   * Retrieves detailed information about a specific standing order,\n   * including its current status, execution history, and next payment date.\n   *\n   * @param accountAddress - The account address that owns the standing order\n   * @param standingOrderId - The unique identifier of the standing order\n   * @returns Promise resolving to standing order details response\n   *\n   * @example\n   * ```typescript\n   * const order = await gridClient.getStandingOrder(accountAddress, orderId);\n   * ```\n   *\n   * @category Standing Orders\n   */\n  async getStandingOrder(\n    accountAddress: string,\n    standingOrderId: string\n  ): Promise<StandingOrderResponse> {\n    return await this.bankingService.getStandingOrder(accountAddress, standingOrderId);\n  }\n\n  /**\n   * @hidden\n   * Retrieves the current context including client configuration.\n   *\n   * Note: This method is for internal use. For accessing account state,\n   * use the account manager API instead: client.account.get()\n   *\n   * @returns Current Grid client context with client and user information\n   *\n   * @example\n   * ```typescript\n   * const context = gridClient.getContext();\n   * ```\n   *\n   * @category Context Management\n   */\n  getContext(): GridClientContext {\n    return this.context;\n  }\n\n  /**\n   * Initiates the WebAuthn credential creation process, prompting the user\n   * to register a new passkey using their device's authenticator (fingerprint,\n   * face recognition, or security key).\n   *\n   * @param params - Passkey creation parameters including challenge and user info\n   * @returns Promise resolving to credential data with public key and credential ID\n   *\n   * @example\n   * ```typescript\n   * const credentialData = await gridClient.createPasskeyCredentials({\n   *   env: 'production',\n   *   challenge: 'base64-encoded-challenge',\n   *   slotNumber: '123',\n   *   sessionKey: 'session-public-key-base58',\n   *   expirationInSeconds: '3600',\n   *   appName: 'My App',\n   *   userId: 'user-identifier',\n   *   redirectUrl: 'your-redirect-url'\n   * });\n   * ```\n   * Note: You can use extractPasskeyCreateParams to extract the parameters from the URL.\n   *\n   * @category Passkey Management\n   */\n  async createPasskeyCredentials(params: PasskeyRequest): Promise<PasskeyCredentialData>{\n    return await this.passkeyService.createPasskeyCredentials(params);\n  }\n\n  /**\n   * Initiates the WebAuthn authentication process, prompting the user to\n   * authenticate using their previously registered passkey.\n   *\n   * @param params - Passkey authentication parameters including challenge\n   * @param credentialData - Optional specific credential to authenticate with\n   * @returns Promise resolving to assertion response with signature and authentication data\n   *\n   * @example\n   * ```typescript\n   * const assertion = await gridClient.getPasskeyCredentials({\n   *   env: 'production',\n   *   challenge: 'base64-encoded-challenge',\n   *   slotNumber: '123',\n   *   sessionKey: 'session-public-key-base58',\n   *   expirationInSeconds: '3600',\n   *   appName: 'My App',\n   *   userId: 'user-identifier',\n   *   redirectUrl: 'your-redirect-url'\n   * });\n   * console.log(assertion.response.signature);\n   * ```\n   * Note: You can use extractPasskeyAuthParams to extract the parameters from the URL.\n   *\n   * @category Passkey Management\n   */\n  async getPasskeyCredentials(params: PasskeyRequest, credentialData?: PasskeyCredentialData): Promise<PasskeyAssertionResponse> {\n    return await this.passkeyService.getPasskeyCredentials(params, credentialData);\n  }\n\n  /**\n   * Parses URL search parameters to extract the necessary information\n   * for passkey credential creation.\n   *\n   * @param query - URLSearchParams object containing passkey creation parameters\n   * @returns Parsed passkey request object ready for credential creation\n   *\n   * @example\n   * ```typescript\n   * const urlParams = new URLSearchParams(window.location.search);\n   * const passkeyParams = gridClient.extractPasskeyCreateParams(urlParams);\n   *\n   * const credentials = await gridClient.createPasskeyCredentials(passkeyParams);\n   * ```\n   *\n   * @category Passkey Management\n   */\n  extractPasskeyCreateParams(query: URLSearchParams): PasskeyRequest {\n    return this.passkeyService.extractPasskeyCreateParams(query);\n  }\n\n  /**\n   * Parses URL search parameters to extract the necessary information\n   * for passkey authentication.\n   *\n   * @param query - URLSearchParams object containing passkey authentication parameters\n   * @returns Parsed passkey request object ready for authentication\n   *\n   * @example\n   * ```typescript\n   * const urlParams = new URLSearchParams(window.location.search);\n   * const authParams = gridClient.extractPasskeyAuthParams(urlParams);\n   *\n   * const assertion = await gridClient.getPasskeyCredentials(authParams);\n   * ```\n   *\n   * @category Passkey Management\n   */\n  extractPasskeyAuthParams(query: URLSearchParams): PasskeyRequest {\n    return this.passkeyService.extractPasskeyAuthParams(query);\n  }\n\n  /**\n   * @hidden\n   * Convert ArrayBuffer to base64url encoding\n   *\n   * @param buffer - ArrayBuffer containing binary data to encode\n   * @returns Base64url encoded string\n   *\n   * @example\n   * ```typescript\n   * const binaryData = new Uint8Array([1, 2, 3, 4]).buffer;\n   * const encoded = gridClient.bufferToBase64Url(binaryData);\n   * console.log(encoded);\n   * ```\n   *\n   * @category Utilities\n   */\n  bufferToBase64Url(buffer: ArrayBuffer): string {\n    return this.utilityService.bufferToBase64Url(buffer);\n  }\n\n  /**\n   * Helper function to create session key object from string and expiration\n   *\n   * @param sessionKeyString - Base58-encoded session key string\n   * @param expirationInSeconds - Expiration time as a string (seconds since epoch)\n   * @returns SessionKey object with decoded key bytes and parsed expiration\n   *\n   * @example\n   * ```typescript\n   * const sessionKey = gridClient.getSessionKeyObject(\n   *   'base58-encoded-key',\n   *   '900'\n   * );\n   * ```\n   *\n   * @category Utilities\n   */\n  getSessionKeyObject(sessionKeyString: string, expirationInSeconds: string): SessionKey {\n    return this.utilityService.getSessionKeyObject(sessionKeyString, expirationInSeconds);\n  }\n\n  /**\n   * Initiates a new passkey authentication session, preparing the necessary\n   * challenge and session data for WebAuthn authentication flow.\n   *\n   * @param params - Passkey session creation parameters\n   * @param environment - Target environment ('sandbox' or 'production')\n   * @returns Promise resolving to passkey session creation response\n   *\n   * @example\n   * ```typescript\n   * await gridClient.createPasskeySession({\n   *   action: 'create',\n   *   sessionKey: 'session-public-key-base58',\n   *   env: 'production',\n   * }, 'production');\n   * ```\n   *\n   * @category Passkey Sessions\n   */\n  async createPasskeySession(\n    params: CreatePasskeySessionRequest,\n    environment: string // TODO: check if we can remove this\n  ): Promise<CreatePasskeySessionResponse> {\n    return await this.passkeyService.createPasskeySession(params, environment);\n  }\n\n  /**\n   * Submits passkey authentication data to authorize an existing session,\n   * completing the WebAuthn authentication flow.\n   *\n   * @param params - Passkey session authorization parameters with authentication data\n   * @param environment - Target environment ('sandbox' or 'production')\n   * @returns Promise resolving to session authorization response\n   *\n   * @example\n   * ```typescript\n   * const authorization = await gridClient.authorizePasskeySession({\n   *   sessionKey: 'public-key-base58',\n   *   metaInfo: {\n   *     appName: 'My App',\n   *     redirectUrl: 'https://myapp.com/callback'\n   *   },\n   *   baseUrl: 'base-url'\n   * }, 'sandbox');\n   * ```\n   *\n   * @category Passkey Sessions\n   */\n  async authorizePasskeySession(\n    params: AuthorizePasskeySessionRequest,\n    environment: string\n  ): Promise<AuthorizePasskeySessionResponse> {\n    return await this.passkeyService.authorizePasskeySession(params, environment);\n  }\n\n  /**\n   * Finalizes a passkey authentication session, generating the final\n   * session tokens and account access credentials.\n   *\n   * @param params - Passkey session submission parameters\n   * @param environment - Target environment ('sandbox' or 'production')\n   * @returns Promise resolving to session submission response with account details\n   *\n   * @example\n   * ```typescript\n   * const result = await gridClient.submitPasskeySession({\n   *   authenticatorResponse: <attestationObject from getPasskeySession>,\n   *   sessionKey: 'public-key-base58',\n   *   ceremonyType: 'auth',\n   *   slotNumber: 123\n   * }, 'sandbox');\n   * ```\n   *\n   * @category Passkey Sessions\n   */\n  async submitPasskeySession(\n    params: SubmitPasskeySessionRequest,\n    environment: string\n  ): Promise<SubmitPasskeySessionResponse> {\n    return await this.passkeyService.submitPasskeySession(params, environment);\n  }\n\n  /**\n   * Searches for an existing passkey account using credential information,\n   * allowing users to recover access to their accounts.\n   *\n   * @param params - Passkey account search parameters with credential data\n   * @param environment - Target environment ('sandbox' or 'production')\n   * @returns Promise resolving to found passkey account information\n   *\n   * @example\n   * ```typescript\n   * const account = await gridClient.findPasskeyAccount({\n   *   sessionKey: 'public-key-base58',\n   *   authenticatorResponse: <attestationObject from getPasskeySession>\n   * }, 'sandbox');\n   * ```\n   *\n   * @category Passkey Sessions\n   */\n  async findPasskeyAccount(\n    params: FindPasskeyAccountRequest,\n    environment: string\n  ): Promise<FindPasskeyAccountResponse> {\n    return await this.passkeyService.findPasskeyAccount(params, environment);\n  }\n\n  /**\n   * Retrieves detailed information about a specific passkey account,\n   * including relying party ID, public key, and optional session key if not expired.\n   *\n   * @param passkeyAddress - The passkey account address (Solana public key) to retrieve\n   * @param environment - Target environment ('sandbox' or 'production')\n   * @returns Promise resolving to passkey account details with relying party ID, public key, and optional session key\n   *\n   * @example\n   * ```typescript\n   * const account = await gridClient.getPasskeyAccount(\n   *   'passkey-account-address',\n   *   'sandbox'\n   * );\n   * console.log(account.data.relyingPartyId);\n   * console.log(account.data.pubkey);\n   * if (account.data.sessionKey) {\n   *   console.log('Session key:', account.data.sessionKey.key);\n   *   console.log('Expires:', account.data.sessionKey.expiration);\n   * }\n   * ```\n   *\n   * @category Passkey Sessions\n   */\n  async getPasskeyAccount(\n    passkeyAddress: string,\n    environment: string\n  ): Promise<GetPasskeyAccountResponse> {\n    return await this.passkeyService.getPasskeyAccount(passkeyAddress, environment);\n  }\n\n  /**\n   * Creates both a passkey account (externally signed account) and smart account in one call.\n   * This combines the passkey creation ceremony with smart account initialization.\n   * Creates a 1/1 smart account with the passkey having full permissions.\n   *\n   * @param params - Passkey account creation parameters including session key and authenticator response\n   * @param environment - Target environment ('sandbox' or 'production')\n   * @returns Promise resolving to the created smart account details including passkey info\n   *\n   * @example\n   * ```typescript\n   * const sessionKeyObject = {\n   *   key: sessionKeyPubkey,\n   *   expiration: Date.now() + 900000\n   * };\n   *\n   * const account = await gridClient.createPasskeyAccount({\n   *   sessionKey: sessionKeyObject,\n   *   slotNumber: 123,\n   *   authenticatorResponse: webauthnResponse,\n   *   adminAddress: 'admin-public-key',\n   *   memo: 'My passkey account'\n   * }, 'sandbox');\n   * console.log('Smart account address:', account.data.address);\n   * console.log('Passkey account:', account.data.passkey.passkeyAccount);\n   * console.log('Session key:', account.data.passkey.sessionKey);\n   * ```\n   *\n   * @category Passkey Management\n   */\n  async createPasskeyAccount(\n    params: CreatePasskeyAccountRequest,\n    environment: string\n  ): Promise<CreatePasskeyAccountResponse> {\n    return await this.passkeyService.createPasskeyAccount(params, environment);\n  }\n\n  /**\n   * Get the current environment configuration\n   *\n   * Returns the environment the SDK is configured to use.\n   * This is useful for determining which network (devnet/mainnet) operations are targeting.\n   *\n   * @returns The current environment ('sandbox' for devnet, 'production' for mainnet)\n   *\n   * @example\n   * ```typescript\n   * const env = gridClient.getEnvironment();\n   * console.log(env); // 'sandbox' or 'production'\n   * ```\n   *\n   * @category Utilities\n   */\n  getEnvironment(): 'sandbox' | 'production' {\n    return this.apiConfig.environment;\n  }\n}\n"]}