{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// src/index.ts\n\nimport axios, { AxiosError, AxiosResponse } from \"axios\";\nimport * as crypto from \"crypto\";\nimport {\n  CreateSubAccountData,\n  CreateSubAccountResponse,\n} from \"./types/subAccount\";\nimport { CurrencyConversionPayload, CurrencyConversionResult } from \"./types\";\n\n/**\n * Configuration interface for initializing the Pay100 SDK\n * @property publicKey - API public key required for all API calls\n * @property secretKey - Secret key used for server-side authentication and request signing\n * @property baseUrl - Optional API base URL, defaults to production endpoint\n */\ninterface IPay100Config {\n  publicKey: string;\n  secretKey?: string;\n  baseUrl?: string;\n}\n\n/**\n * Interface representing transaction data returned from payment verification\n * Flexible structure to accommodate various transaction types and properties\n */\ninterface ITransactionData {\n  [key: string]: unknown;\n}\n\n/**\n * Interface for raw API responses before processing\n * Provides a flexible structure while capturing common response elements\n */\ninterface IRawApiResponse {\n  status?: string;\n  message?: string;\n  data?: unknown;\n  [key: string]: unknown;\n}\n\n/**\n * Standardized response interface for transaction verification\n * @property status - Result status ('success' or 'error')\n * @property data - Transaction details when successful, empty object on failure\n * @property message - Optional response message, typically present on errors\n */\ninterface IVerifyResponse {\n  status: \"success\" | \"error\";\n  data: ITransactionData | Record<string, never>;\n  message?: string;\n}\n\n// Default API endpoint if not otherwise specified\nconst BASE_URL = process.env.BASE_URL || \"https://api.100pay.co\";\n\n/**\n * Custom error class for payment verification failures\n * Provides consistent error structure for better error handling\n */\nexport class PaymentVerificationError extends Error {\n  status: string;\n  data: Record<string, never>;\n\n  constructor(message: string) {\n    super(message);\n    this.name = \"PaymentVerificationError\";\n    this.status = \"error\";\n    this.data = {};\n  }\n}\n\n/**\n * Main SDK class for interacting with the 100Pay payment platform\n * Provides methods for transaction verification, subaccount management,\n * and currency conversion\n */\nexport class Pay100 {\n  private publicKey: string;\n  private secretKey?: string;\n  private baseUrl: string;\n\n  /**\n   * Initialize the Pay100 SDK\n   * @param config - Configuration object containing API keys and optional base URL\n   */\n  constructor({ publicKey, secretKey, baseUrl = BASE_URL }: IPay100Config) {\n    this.publicKey = publicKey;\n    this.secretKey = secretKey;\n    this.baseUrl = baseUrl;\n  }\n\n  /**\n   * Creates a cryptographic signature for secure server-to-server communication\n   *\n   * @param payload - Request payload that needs to be signed\n   * @returns Object containing current timestamp and HMAC SHA-256 signature\n   * @throws Error if secret key is missing or invalid\n   */\n  private createSignature(payload: Record<string, unknown>): {\n    timestamp: string;\n    signature: string;\n  } {\n    const timestamp = Date.now().toString();\n\n    // Extract the token part from the secret key if it's in the format\n    // STATUS;TYPE;TOKEN (e.g., \"LIVE;SK;eyJhbGciOiJIUzI1...\")\n    let signingSecret = this?.secretKey;\n\n    if (this?.secretKey?.includes(\";\")) {\n      const secretKeyParts = this.secretKey.split(\";\");\n      if (secretKeyParts.length === 3) {\n        // Use just the token part as the signing secret\n        signingSecret = secretKeyParts[2];\n      }\n    }\n\n    if (!signingSecret) {\n      throw new Error(\"Secret key is required for signing\");\n    }\n\n    // Create signature using HMAC SHA-256\n    const signature = crypto\n      .createHmac(\"sha256\", signingSecret)\n      .update(timestamp + JSON.stringify(payload))\n      .digest(\"hex\");\n\n    return { timestamp, signature };\n  }\n\n  /**\n   * Constructs HTTP headers for API requests with optional authentication\n   *\n   * @param payload - Request payload used to generate security signature\n   * @returns Object containing all necessary HTTP headers\n   */\n  private getHeaders(\n    payload: Record<string, unknown> = {}\n  ): Record<string, string> {\n    // Generate authentication headers if secret key is available (server-side mode)\n    if (this.secretKey) {\n      const { timestamp, signature } = this.createSignature(payload);\n      return {\n        \"api-key\": this.publicKey,\n        \"x-secret-key\": this.secretKey,\n        \"x-timestamp\": timestamp,\n        \"x-signature\": signature,\n        \"Content-Type\": \"application/json\",\n      };\n    }\n\n    // Basic headers for public API usage (client-side mode)\n    return {\n      \"api-key\": this.publicKey,\n      \"Content-Type\": \"application/json\",\n    };\n  }\n\n  /**\n   * Verifies the status and details of a payment transaction\n   *\n   * @param transactionId - Unique identifier of the transaction to verify\n   * @returns Promise resolving to verification result with transaction data\n   * @throws PaymentVerificationError on network issues or invalid responses\n   */\n  verify = async (transactionId: string): Promise<IVerifyResponse> => {\n    try {\n      const payload = { transactionId };\n\n      const response: AxiosResponse<IRawApiResponse> = await axios({\n        method: \"POST\",\n        url: `${this.baseUrl}/api/v1/pay/crypto/payment/${transactionId}`,\n        headers: this.getHeaders(payload),\n        data: payload,\n      });\n\n      // Handle empty response\n      if (!response.data) {\n        return {\n          status: \"error\",\n          data: {},\n          message:\n            \"Something went wrong, be sure you supplied a valid payment id.\",\n        };\n      }\n\n      // Handle string responses which indicate errors\n      if (typeof response.data === \"string\") {\n        if (response.data === \"Access Denied, Invalid KEY supplied\") {\n          return {\n            status: \"error\",\n            data: {},\n            message: \"Access Denied, Invalid KEY supplied\",\n          };\n        }\n\n        if (response.data === \"invalid payment id supplied\") {\n          return {\n            status: \"error\",\n            data: {},\n          };\n        }\n      }\n\n      // Validate and transform response data to ensure type safety\n      const responseData = response.data;\n\n      // Ensure the response data is an object that can be safely cast to ITransactionData\n      const transactionData: ITransactionData =\n        responseData && typeof responseData === \"object\"\n          ? (responseData as ITransactionData)\n          : {};\n\n      // Return successful response with properly typed data\n      return {\n        status: \"success\",\n        data: transactionData,\n      };\n    } catch (error) {\n      // Handle Axios errors with detailed message\n      if (axios.isAxiosError(error)) {\n        const axiosError = error as AxiosError;\n        throw new PaymentVerificationError(\n          axiosError.message ||\n            \"Something went wrong, be sure you supplied a valid payment id.\"\n        );\n      }\n\n      // Handle other errors with appropriate message\n      throw new PaymentVerificationError(\n        error instanceof Error ? error.message : \"An unknown error occurred\"\n      );\n    }\n  };\n\n  /**\n   * Namespace for subaccount management operations\n   * Provides methods to create and manage subaccounts\n   */\n  subaccounts = {\n    /**\n     * Creates a new subaccount within the platform\n     *\n     * @param data - Subaccount configuration including owner details and supported currencies\n     * @returns Promise resolving to the created subaccount details\n     * @throws Error if the request fails or returns invalid data\n     */\n    create: async (\n      data: CreateSubAccountData\n    ): Promise<CreateSubAccountResponse> => {\n      return this.request<CreateSubAccountResponse>(\n        \"POST\",\n        \"/api/v1/assets/subaccount/create\",\n        data\n      );\n    },\n  };\n\n  /**\n   * Namespace for currency conversion operations\n   * Provides methods to calculate exchange rates and fees\n   */\n  conversion = {\n    /**\n     * Calculates a preview of currency conversion with rates and fees\n     *\n     * @param data - Conversion details including amount, source and target currencies\n     * @returns Promise resolving to detailed conversion calculation\n     * @throws Error if the request fails or returns invalid data\n     */\n    preview: async (\n      data: CurrencyConversionPayload\n    ): Promise<CurrencyConversionResult> => {\n      return this.request<CurrencyConversionResult>(\n        \"POST\",\n        \"/api/v1/user/preview-convert-asset\",\n        {\n          amount: data.amount,\n          to_symbol: data.toSymbol,\n          from_symbol: data.fromSymbol,\n          appId: data.appId,\n        }\n      );\n    },\n  };\n\n  /**\n   * Generic method to make authenticated API requests to any endpoint\n   *\n   * @param method - HTTP method to use (GET, POST, PUT, DELETE)\n   * @param endpoint - API endpoint path (will be appended to base URL)\n   * @param data - Request payload or query parameters\n   * @returns Promise resolving to the typed API response\n   * @throws Error with detailed message on request failure\n   */\n  async request<T>(\n    method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\",\n    endpoint: string,\n    data: Record<string, unknown> = {}\n  ): Promise<T> {\n    try {\n      const url = `${this.baseUrl}${endpoint}`;\n      const headers = this.getHeaders(data);\n\n      const response = await axios({\n        method,\n        url,\n        headers,\n        data: method !== \"GET\" ? data : undefined,\n        params: method === \"GET\" ? data : undefined,\n      });\n\n      return response.data as T;\n    } catch (error) {\n      if (axios.isAxiosError(error)) {\n        const axiosError = error as AxiosError;\n        const errorMessage =\n          axiosError.response?.data &&\n          typeof axiosError.response.data === \"object\" &&\n          \"message\" in axiosError.response.data\n            ? String(axiosError.response.data.message)\n            : axiosError.message;\n\n        throw new Error(`API Request Failed: ${errorMessage}`);\n      }\n\n      throw error;\n    }\n  }\n}\n\nexport * from \"./types\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;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