diff --git a/README.md b/README.md index c96dd09..4becacf 100644 --- a/README.md +++ b/README.md @@ -51,8 +51,8 @@ const icpay = new Icpay({ }); // Server-side operations -const transactions = await icpay.getTransactionHistory(); -const accountBalances = await icpay.getAccountWalletBalances(); +const transactions = await icpay.protected.getTransactionHistory(); +const accountBalances = await icpay.protected.getAccountWalletBalances(); ``` ## Authentication Modes diff --git a/examples/balance-check-test.ts b/examples/balance-check-test.ts index 83e1c9d..1b075c8 100644 --- a/examples/balance-check-test.ts +++ b/examples/balance-check-test.ts @@ -70,7 +70,7 @@ async function testEnhancedBalanceFeatures() { // 5. Test getting account wallet balances (from API) console.log('\n5. Testing getAccountWalletBalances...'); try { - const accountBalances = await icpay.getAccountWalletBalances(); + const accountBalances = await icpay.protected.getAccountWalletBalances(); console.log('Account Wallet Balances:', { totalBalancesUSD: accountBalances.totalBalancesUSD, lastUpdated: accountBalances.lastUpdated, diff --git a/examples/basic-usage.ts b/examples/basic-usage.ts index 4328e69..69d50cf 100644 --- a/examples/basic-usage.ts +++ b/examples/basic-usage.ts @@ -87,7 +87,7 @@ async function example() { // 8. Check transaction status console.log('\nChecking transaction status...'); - const status = await icpay.getTransactionStatus(transaction.transactionId); + const status = await icpay.protected.getTransactionStatus(transaction.transactionId); console.log('Transaction Status:', status); // 9. Get account information diff --git a/examples/enhanced-usage.ts b/examples/enhanced-usage.ts index 8afbc93..d203805 100644 --- a/examples/enhanced-usage.ts +++ b/examples/enhanced-usage.ts @@ -137,7 +137,7 @@ async function privateExample() { // 9. Get account wallet balances (from API, private method) console.log('\n9. Fetching account wallet balances from API...'); - const accountWalletBalances = await icpay.getAccountWalletBalances(); + const accountWalletBalances = await icpay.protected.getAccountWalletBalances(); console.log('Account Wallet Balances:', { totalBalancesUSD: accountWalletBalances.totalBalancesUSD, lastUpdated: accountWalletBalances.lastUpdated, @@ -197,7 +197,7 @@ async function privateExample() { // 13. Get transaction status (private method) console.log('\n13. Checking transaction status...'); - const transactionStatus = await icpay.getTransactionStatus(transaction.transactionId); + const transactionStatus = await icpay.protected.getTransactionStatus(transaction.transactionId); console.log('Transaction Status:', { transactionId: transactionStatus.transactionId, status: transactionStatus.status, diff --git a/package.json b/package.json index dc218f0..dbf9f0c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@icpay/sdk", - "version": "1.3.51", + "version": "1.3.52", "description": "Official icpay SDK for Internet Computer payments", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/src/index.ts b/src/index.ts index 46628ef..5e37c9c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,19 +2,11 @@ import { IcpayConfig, CreateTransactionRequest, TransactionResponse, - TransactionStatus, - AccountInfo, - PublicAccountInfo, - VerifiedLedger, WalletConnectionResult, AllLedgerBalances, LedgerBalance, PriceCalculationRequest, PriceCalculationResult, - PaymentHistoryRequest, - PaymentHistoryResponse, - GetPaymentsByPrincipalRequest, - LedgerInfo, SendFundsUsdRequest, AccountPublic, LedgerPublic, @@ -28,8 +20,8 @@ import { HttpAgent, Actor } from '@dfinity/agent'; import { idlFactory as icpayIdl } from './declarations/icpay_canister_backend/icpay_canister_backend.did.js'; import { idlFactory as ledgerIdl } from './declarations/icrc-ledger/ledger.did.js'; import { Principal } from '@dfinity/principal'; -import { toAccountIdentifier, debugLog } from './utils'; -import { IcpayProtected } from './protected'; +import { debugLog } from './utils'; +import { createProtectedApi, ProtectedApi } from './protected'; export class Icpay { private config: IcpayConfig; @@ -43,7 +35,7 @@ export class Icpay { private accountInfoCache: any = null; private verifiedLedgersCache: { data: LedgerPublic[] | null; timestamp: number } = { data: null, timestamp: 0 }; private events: IcpayEventCenter; - public protected: IcpayProtected; + public protected: ProtectedApi; constructor(config: IcpayConfig) { this.config = { @@ -101,9 +93,8 @@ export class Icpay { debugLog(this.config.debug || false, 'privateApiClient created', this.privateApiClient); - // Initialize protected wrapper - this.protected = new IcpayProtected({ - publicApiClient: this.publicApiClient, + // Initialize protected API + this.protected = createProtectedApi({ privateApiClient: this.privateApiClient, emitStart: (name, args) => this.emitMethodStart(name, args), emitSuccess: (name, result) => this.emitMethodSuccess(name, result), @@ -219,13 +210,6 @@ export class Icpay { } } - /** - * Get detailed account information (private method - full data) - */ - async getDetailedAccountInfo(): Promise { - return this.protected.getDetailedAccountInfo(); - } - /** * Get verified ledgers (public method) */ @@ -300,17 +284,6 @@ export class Icpay { return result; } - /** - * Get transaction status by canister transaction ID (private method) - * - * This method returns transaction status from the ICPay API database. - * Note: Canister transactions may take up to 1 minute to sync to the API database. - * If a transaction is not found, a sync notification will be automatically triggered. - */ - async getTransactionStatus(canisterTransactionId: number): Promise { - return this.protected.getTransactionStatus(canisterTransactionId); - } - /** * Trigger transaction sync from canister (public method) * @@ -1224,20 +1197,6 @@ export class Icpay { } } - /** - * Get payment history for account (requires secret key) - */ - async getPaymentHistory(request: PaymentHistoryRequest = {}): Promise { - return this.protected.getPaymentHistory(request); - } - - /** - * Get payments by principal ID (for connected wallet) - checks both sender_principal_id and expected_sender_principal - */ - async getPaymentsByPrincipal(request: GetPaymentsByPrincipalRequest): Promise { - return this.protected.getPaymentsByPrincipal(request); - } - /** * Get detailed ledger information including price data (public method) */ @@ -1360,13 +1319,6 @@ export class Icpay { } } - /** - * Get account wallet balances (from API, not connected wallet) (private method) - */ - async getAccountWalletBalances(): Promise { - return this.protected.getAccountWalletBalances(); - } - /** * Utility function to format balance from smallest unit to human readable */ diff --git a/src/protected.ts b/src/protected.ts index 7506587..72ff293 100644 --- a/src/protected.ts +++ b/src/protected.ts @@ -18,345 +18,351 @@ import type { } from './types'; type EmitFn = (name: string, payload?: any) => void; +export type ProtectedApi = { + getPaymentById(id: string): Promise; + listPayments(): Promise; + getPaymentIntentById(id: string): Promise; + getInvoiceById(id: string): Promise; + getTransactionById(id: string): Promise; + getWalletById(id: string): Promise; + getVerifiedLedgersPrivate(): Promise; + getAllLedgersWithPricesPrivate(): Promise; + getLedgerInfoPrivate(idOrCanisterId: string): Promise; + getWebhookEventById(id: string): Promise; + getDetailedAccountInfo(): Promise; + getTransactionStatus(canisterTransactionId: number): Promise; + getPaymentHistory(request?: PaymentHistoryRequest): Promise; + getPaymentsByPrincipal(request: GetPaymentsByPrincipalRequest): Promise; + getAccountWalletBalances(): Promise; +}; -export class IcpayProtected { - private publicApiClient: AxiosInstance; - private privateApiClient: AxiosInstance | null; - private emitStart: EmitFn; - private emitSuccess: EmitFn; - private emitError: EmitFn; +export function createProtectedApi(params: { + privateApiClient: AxiosInstance | null; + emitStart: EmitFn; + emitSuccess: EmitFn; + emitError: EmitFn; +}): ProtectedApi { + const privateApiClient = params.privateApiClient; + const emitStart = params.emitStart; + const emitSuccess = params.emitSuccess; + const emitError = params.emitError; - constructor(params: { - publicApiClient: AxiosInstance; - privateApiClient: AxiosInstance | null; - emitStart: EmitFn; - emitSuccess: EmitFn; - emitError: EmitFn; - }) { - this.publicApiClient = params.publicApiClient; - this.privateApiClient = params.privateApiClient; - this.emitStart = params.emitStart; - this.emitSuccess = params.emitSuccess; - this.emitError = params.emitError; - } - - private requireSecretKey(methodName: string): void { - if (!this.privateApiClient) { + const requireSecretKey = (methodName: string) => { + if (!privateApiClient) { throw new IcpayError({ code: 'SECRET_KEY_REQUIRED', message: `${methodName} requires secret key authentication. Please provide secretKey in configuration.`, }); } - } + }; - async getPaymentById(id: string): Promise { - this.requireSecretKey('getPaymentById'); - this.emitStart('getPaymentById', { id }); - try { - const res = await this.privateApiClient!.get(`/sdk/payments/${id}`); - this.emitSuccess('getPaymentById', { id }); - return res.data as SdkPaymentAggregate; - } catch (error) { - this.emitError('getPaymentById', error); - throw error; - } - } + return { + async getPaymentById(id: string): Promise { + requireSecretKey('getPaymentById'); + emitStart('getPaymentById', { id }); + try { + const res = await privateApiClient!.get(`/sdk/payments/${id}`); + emitSuccess('getPaymentById', { id }); + return res.data as SdkPaymentAggregate; + } catch (error) { + emitError('getPaymentById', error); + throw error; + } + }, - async listPayments(): Promise { - this.requireSecretKey('listPayments'); - this.emitStart('listPayments'); - try { - const res = await this.privateApiClient!.get('/sdk/payments'); - this.emitSuccess('listPayments', { count: Array.isArray(res.data) ? res.data.length : undefined }); - return res.data as SdkPaymentAggregate[]; - } catch (error) { - this.emitError('listPayments', error); - throw error; - } - } + async listPayments(): Promise { + requireSecretKey('listPayments'); + emitStart('listPayments'); + try { + const res = await privateApiClient!.get('/sdk/payments'); + emitSuccess('listPayments', { count: Array.isArray(res.data) ? res.data.length : undefined }); + return res.data as SdkPaymentAggregate[]; + } catch (error) { + emitError('listPayments', error); + throw error; + } + }, - async getPaymentIntentById(id: string): Promise { - this.requireSecretKey('getPaymentIntentById'); - this.emitStart('getPaymentIntentById', { id }); - try { - const res = await this.privateApiClient!.get(`/sdk/payment-intents/${id}`); - this.emitSuccess('getPaymentIntentById', { id }); - return res.data as SdkPaymentIntent; - } catch (error) { - this.emitError('getPaymentIntentById', error); - throw error; - } - } + async getPaymentIntentById(id: string): Promise { + requireSecretKey('getPaymentIntentById'); + emitStart('getPaymentIntentById', { id }); + try { + const res = await privateApiClient!.get(`/sdk/payment-intents/${id}`); + emitSuccess('getPaymentIntentById', { id }); + return res.data as SdkPaymentIntent; + } catch (error) { + emitError('getPaymentIntentById', error); + throw error; + } + }, - async getInvoiceById(id: string): Promise { - this.requireSecretKey('getInvoiceById'); - this.emitStart('getInvoiceById', { id }); - try { - const res = await this.privateApiClient!.get(`/sdk/invoices/${id}`); - this.emitSuccess('getInvoiceById', { id }); - return res.data as SdkInvoice; - } catch (error) { - this.emitError('getInvoiceById', error); - throw error; - } - } + async getInvoiceById(id: string): Promise { + requireSecretKey('getInvoiceById'); + emitStart('getInvoiceById', { id }); + try { + const res = await privateApiClient!.get(`/sdk/invoices/${id}`); + emitSuccess('getInvoiceById', { id }); + return res.data as SdkInvoice; + } catch (error) { + emitError('getInvoiceById', error); + throw error; + } + }, - async getTransactionById(id: string): Promise { - this.requireSecretKey('getTransactionById'); - this.emitStart('getTransactionById', { id }); - try { - const res = await this.privateApiClient!.get(`/sdk/transactions/${id}`); - this.emitSuccess('getTransactionById', { id }); - return res.data as SdkTransaction; - } catch (error) { - this.emitError('getTransactionById', error); - throw error; - } - } + async getTransactionById(id: string): Promise { + requireSecretKey('getTransactionById'); + emitStart('getTransactionById', { id }); + try { + const res = await privateApiClient!.get(`/sdk/transactions/${id}`); + emitSuccess('getTransactionById', { id }); + return res.data as SdkTransaction; + } catch (error) { + emitError('getTransactionById', error); + throw error; + } + }, - async getWalletById(id: string): Promise { - this.requireSecretKey('getWalletById'); - this.emitStart('getWalletById', { id }); - try { - const res = await this.privateApiClient!.get(`/sdk/wallets/${id}`); - this.emitSuccess('getWalletById', { id }); - return res.data as SdkWallet; - } catch (error) { - this.emitError('getWalletById', error); - throw error; - } - } + async getWalletById(id: string): Promise { + requireSecretKey('getWalletById'); + emitStart('getWalletById', { id }); + try { + const res = await privateApiClient!.get(`/sdk/wallets/${id}`); + emitSuccess('getWalletById', { id }); + return res.data as SdkWallet; + } catch (error) { + emitError('getWalletById', error); + throw error; + } + }, - async getVerifiedLedgersPrivate(): Promise { - this.requireSecretKey('getVerifiedLedgersPrivate'); - this.emitStart('getVerifiedLedgersPrivate'); - try { - const res = await this.privateApiClient!.get('/sdk/ledgers/verified'); - this.emitSuccess('getVerifiedLedgersPrivate', { count: Array.isArray(res.data) ? res.data.length : undefined }); - return res.data as SdkLedger[]; - } catch (error) { - this.emitError('getVerifiedLedgersPrivate', error); - throw error; - } - } + async getVerifiedLedgersPrivate(): Promise { + requireSecretKey('getVerifiedLedgersPrivate'); + emitStart('getVerifiedLedgersPrivate'); + try { + const res = await privateApiClient!.get('/sdk/ledgers/verified'); + emitSuccess('getVerifiedLedgersPrivate', { count: Array.isArray(res.data) ? res.data.length : undefined }); + return res.data as SdkLedger[]; + } catch (error) { + emitError('getVerifiedLedgersPrivate', error); + throw error; + } + }, - async getAllLedgersWithPricesPrivate(): Promise { - this.requireSecretKey('getAllLedgersWithPricesPrivate'); - this.emitStart('getAllLedgersWithPricesPrivate'); - try { - const res = await this.privateApiClient!.get('/sdk/ledgers/all-with-prices'); - this.emitSuccess('getAllLedgersWithPricesPrivate', { count: Array.isArray(res.data) ? res.data.length : undefined }); - return res.data as SdkLedger[]; - } catch (error) { - this.emitError('getAllLedgersWithPricesPrivate', error); - throw error; - } - } + async getAllLedgersWithPricesPrivate(): Promise { + requireSecretKey('getAllLedgersWithPricesPrivate'); + emitStart('getAllLedgersWithPricesPrivate'); + try { + const res = await privateApiClient!.get('/sdk/ledgers/all-with-prices'); + emitSuccess('getAllLedgersWithPricesPrivate', { count: Array.isArray(res.data) ? res.data.length : undefined }); + return res.data as SdkLedger[]; + } catch (error) { + emitError('getAllLedgersWithPricesPrivate', error); + throw error; + } + }, - async getLedgerInfoPrivate(idOrCanisterId: string): Promise { - this.requireSecretKey('getLedgerInfoPrivate'); - this.emitStart('getLedgerInfoPrivate', { idOrCanisterId }); - try { - const res = await this.privateApiClient!.get(`/sdk/ledgers/${idOrCanisterId}`); - this.emitSuccess('getLedgerInfoPrivate', { idOrCanisterId }); - return res.data as SdkLedger; - } catch (error) { - this.emitError('getLedgerInfoPrivate', error); - throw error; - } - } + async getLedgerInfoPrivate(idOrCanisterId: string): Promise { + requireSecretKey('getLedgerInfoPrivate'); + emitStart('getLedgerInfoPrivate', { idOrCanisterId }); + try { + const res = await privateApiClient!.get(`/sdk/ledgers/${idOrCanisterId}`); + emitSuccess('getLedgerInfoPrivate', { idOrCanisterId }); + return res.data as SdkLedger; + } catch (error) { + emitError('getLedgerInfoPrivate', error); + throw error; + } + }, - async getWebhookEventById(id: string): Promise { - this.requireSecretKey('getWebhookEventById'); - this.emitStart('getWebhookEventById', { id }); - try { - const res = await this.privateApiClient!.get(`/sdk/webhook-events/${id}`); - this.emitSuccess('getWebhookEventById', { id }); - return res.data as SdkWebhookEvent; - } catch (error) { - this.emitError('getWebhookEventById', error); - throw error; - } - } + async getWebhookEventById(id: string): Promise { + requireSecretKey('getWebhookEventById'); + emitStart('getWebhookEventById', { id }); + try { + const res = await privateApiClient!.get(`/sdk/webhook-events/${id}`); + emitSuccess('getWebhookEventById', { id }); + return res.data as SdkWebhookEvent; + } catch (error) { + emitError('getWebhookEventById', error); + throw error; + } + }, - // ===== Moved secret methods from Icpay ===== + async getDetailedAccountInfo(): Promise { + requireSecretKey('getDetailedAccountInfo'); + emitStart('getDetailedAccountInfo'); + try { + const response = await privateApiClient!.get('/sdk/account'); + const account = response.data; + const result: AccountInfo = { + id: account.id, + name: account.name, + email: account.email, + isActive: account.isActive, + isLive: account.isLive, + accountCanisterId: account.accountCanisterId, + walletAddress: account.walletAddress, + createdAt: new Date(account.createdAt), + updatedAt: new Date(account.updatedAt), + } as any; + emitSuccess('getDetailedAccountInfo', result); + return result; + } catch (error) { + const err = new IcpayError({ + code: 'ACCOUNT_INFO_FETCH_FAILED', + message: 'Failed to fetch detailed account information', + details: error, + }); + emitError('getDetailedAccountInfo', err); + throw err; + } + }, - async getDetailedAccountInfo(): Promise { - this.requireSecretKey('getDetailedAccountInfo'); - this.emitStart('getDetailedAccountInfo'); - try { - const response = await this.privateApiClient!.get('/sdk/account'); - const account = response.data; - const result: AccountInfo = { - id: account.id, - name: account.name, - email: account.email, - isActive: account.isActive, - isLive: account.isLive, - accountCanisterId: account.accountCanisterId, - walletAddress: account.walletAddress, - createdAt: new Date(account.createdAt), - updatedAt: new Date(account.updatedAt), - } as any; - this.emitSuccess('getDetailedAccountInfo', result); - return result; - } catch (error) { - const err = new IcpayError({ - code: 'ACCOUNT_INFO_FETCH_FAILED', - message: 'Failed to fetch detailed account information', - details: error, - }); - this.emitError('getDetailedAccountInfo', err); - throw err; - } - } + async getTransactionStatus(canisterTransactionId: number): Promise { + requireSecretKey('getTransactionStatus'); + emitStart('getTransactionStatus', { canisterTransactionId }); + try { + const response = await privateApiClient!.get(`/sdk/transactions/${canisterTransactionId}/status`); + const result = response.data; + emitSuccess('getTransactionStatus', result); + return result; + } catch (error) { + const err = new IcpayError({ + code: 'TRANSACTION_STATUS_FETCH_FAILED', + message: 'Failed to fetch transaction status', + details: error, + }); + emitError('getTransactionStatus', err); + throw err; + } + }, - async getTransactionStatus(canisterTransactionId: number): Promise { - this.requireSecretKey('getTransactionStatus'); - this.emitStart('getTransactionStatus', { canisterTransactionId }); - try { - const response = await this.privateApiClient!.get(`/sdk/transactions/${canisterTransactionId}/status`); - const result = response.data; - this.emitSuccess('getTransactionStatus', result); - return result; - } catch (error) { - const err = new IcpayError({ - code: 'TRANSACTION_STATUS_FETCH_FAILED', - message: 'Failed to fetch transaction status', - details: error, - }); - this.emitError('getTransactionStatus', err); - throw err; - } - } + async getPaymentHistory(request: PaymentHistoryRequest = {}): Promise { + requireSecretKey('getPaymentHistory'); + emitStart('getPaymentHistory', { request }); + try { + const params = new URLSearchParams(); + if (request.accountId) params.append('accountId', request.accountId); + if (request.ledgerCanisterId) params.append('ledgerCanisterId', request.ledgerCanisterId); + if (request.fromTimestamp) params.append('fromTimestamp', request.fromTimestamp.toISOString()); + if (request.toTimestamp) params.append('toTimestamp', request.toTimestamp.toISOString()); + if (request.status) params.append('status', request.status); + if (request.limit) params.append('limit', request.limit.toString()); + if (request.offset) params.append('offset', request.offset.toString()); - async getPaymentHistory(request: PaymentHistoryRequest = {}): Promise { - this.requireSecretKey('getPaymentHistory'); - this.emitStart('getPaymentHistory', { request }); - try { - const params = new URLSearchParams(); - if (request.accountId) params.append('accountId', request.accountId); - if (request.ledgerCanisterId) params.append('ledgerCanisterId', request.ledgerCanisterId); - if (request.fromTimestamp) params.append('fromTimestamp', request.fromTimestamp.toISOString()); - if (request.toTimestamp) params.append('toTimestamp', request.toTimestamp.toISOString()); - if (request.status) params.append('status', request.status); - if (request.limit) params.append('limit', request.limit.toString()); - if (request.offset) params.append('offset', request.offset.toString()); + const response = await privateApiClient!.get(`/sdk/payments/history?${params.toString()}`); + const result: PaymentHistoryResponse = { + payments: response.data.payments.map((tx: any) => ({ + id: tx.id, + status: tx.status, + amount: tx.amount, + ledgerCanisterId: tx.ledgerCanisterId, + ledgerSymbol: tx.ledgerSymbol, + fromAddress: tx.fromAddress, + toAddress: tx.toAddress, + fee: tx.fee, + decimals: tx.decimals, + tokenPrice: tx.tokenPrice, + expectedSenderPrincipal: tx.expectedSenderPrincipal, + metadata: tx.metadata, + createdAt: new Date(tx.createdAt), + updatedAt: new Date(tx.updatedAt), + })), + total: response.data.total, + limit: response.data.limit, + offset: response.data.offset, + hasMore: response.data.hasMore, + } as any; + emitSuccess('getPaymentHistory', { total: result.total }); + return result; + } catch (error) { + const err = new IcpayError({ + code: 'PAYMENT_HISTORY_FETCH_FAILED', + message: 'Failed to fetch payment history', + details: error, + }); + emitError('getPaymentHistory', err); + throw err; + } + }, - const response = await this.privateApiClient!.get(`/sdk/payments/history?${params.toString()}`); - const result: PaymentHistoryResponse = { - payments: response.data.payments.map((tx: any) => ({ - id: tx.id, - status: tx.status, - amount: tx.amount, - ledgerCanisterId: tx.ledgerCanisterId, - ledgerSymbol: tx.ledgerSymbol, - fromAddress: tx.fromAddress, - toAddress: tx.toAddress, - fee: tx.fee, - decimals: tx.decimals, - tokenPrice: tx.tokenPrice, - expectedSenderPrincipal: tx.expectedSenderPrincipal, - metadata: tx.metadata, - createdAt: new Date(tx.createdAt), - updatedAt: new Date(tx.updatedAt), - })), - total: response.data.total, - limit: response.data.limit, - offset: response.data.offset, - hasMore: response.data.hasMore, - } as any; - this.emitSuccess('getPaymentHistory', { total: result.total }); - return result; - } catch (error) { - const err = new IcpayError({ - code: 'PAYMENT_HISTORY_FETCH_FAILED', - message: 'Failed to fetch payment history', - details: error, - }); - this.emitError('getPaymentHistory', err); - throw err; - } - } + async getPaymentsByPrincipal(request: GetPaymentsByPrincipalRequest): Promise { + requireSecretKey('getPaymentsByPrincipal'); + emitStart('getPaymentsByPrincipal', { request }); + try { + const params = new URLSearchParams(); + if (request.limit) params.append('limit', request.limit.toString()); + if (request.offset) params.append('offset', request.offset.toString()); + if (request.status) params.append('status', request.status); - async getPaymentsByPrincipal(request: GetPaymentsByPrincipalRequest): Promise { - this.requireSecretKey('getPaymentsByPrincipal'); - this.emitStart('getPaymentsByPrincipal', { request }); - try { - const params = new URLSearchParams(); - if (request.limit) params.append('limit', request.limit.toString()); - if (request.offset) params.append('offset', request.offset.toString()); - if (request.status) params.append('status', request.status); + const response = await privateApiClient!.get(`/sdk/payments/by-principal/${request.principalId}?${params.toString()}`); + const result: PaymentHistoryResponse = { + payments: response.data.payments.map((tx: any) => ({ + id: tx.id, + status: tx.status, + amount: tx.amount, + ledgerCanisterId: tx.ledgerCanisterId, + ledgerSymbol: tx.ledgerSymbol, + fromAddress: tx.fromAddress, + toAddress: tx.toAddress, + fee: tx.fee, + decimals: tx.decimals, + tokenPrice: tx.tokenPrice, + expectedSenderPrincipal: tx.expectedSenderPrincipal, + metadata: tx.metadata, + createdAt: new Date(tx.createdAt), + updatedAt: new Date(tx.updatedAt), + })), + total: response.data.total, + limit: response.data.limit, + offset: response.data.offset, + hasMore: response.data.hasMore, + } as any; + emitSuccess('getPaymentsByPrincipal', { total: result.total }); + return result; + } catch (error) { + const err = new IcpayError({ + code: 'PAYMENTS_BY_PRINCIPAL_FETCH_FAILED', + message: 'Failed to fetch payments by principal', + details: error, + }); + emitError('getPaymentsByPrincipal', err); + throw err; + } + }, - const response = await this.privateApiClient!.get(`/sdk/payments/by-principal/${request.principalId}?${params.toString()}`); - const result: PaymentHistoryResponse = { - payments: response.data.payments.map((tx: any) => ({ - id: tx.id, - status: tx.status, - amount: tx.amount, - ledgerCanisterId: tx.ledgerCanisterId, - ledgerSymbol: tx.ledgerSymbol, - fromAddress: tx.fromAddress, - toAddress: tx.toAddress, - fee: tx.fee, - decimals: tx.decimals, - tokenPrice: tx.tokenPrice, - expectedSenderPrincipal: tx.expectedSenderPrincipal, - metadata: tx.metadata, - createdAt: new Date(tx.createdAt), - updatedAt: new Date(tx.updatedAt), - })), - total: response.data.total, - limit: response.data.limit, - offset: response.data.offset, - hasMore: response.data.hasMore, - } as any; - this.emitSuccess('getPaymentsByPrincipal', { total: result.total }); - return result; - } catch (error) { - const err = new IcpayError({ - code: 'PAYMENTS_BY_PRINCIPAL_FETCH_FAILED', - message: 'Failed to fetch payments by principal', - details: error, - }); - this.emitError('getPaymentsByPrincipal', err); - throw err; - } - } - - async getAccountWalletBalances(): Promise { - this.requireSecretKey('getAccountWalletBalances'); - this.emitStart('getAccountWalletBalances'); - try { - const response = await this.privateApiClient!.get('/sdk/account/wallet-balances'); - const result: AllLedgerBalances = { - balances: response.data.balances.map((balance: any) => ({ - ledgerId: balance.ledgerId, - ledgerName: balance.ledgerName, - ledgerSymbol: balance.ledgerSymbol, - canisterId: balance.canisterId, - balance: balance.balance, - formattedBalance: balance.formattedBalance, - decimals: balance.decimals, - currentPrice: balance.currentPrice, - lastPriceUpdate: balance.lastPriceUpdate ? new Date(balance.lastPriceUpdate) : undefined, - lastUpdated: new Date(balance.lastUpdated), - } as LedgerBalance)), - totalBalancesUSD: response.data.totalBalancesUSD, - lastUpdated: new Date(response.data.lastUpdated), - }; - this.emitSuccess('getAccountWalletBalances', { count: result.balances.length, totalUSD: result.totalBalancesUSD }); - return result; - } catch (error) { - const err = new IcpayError({ - code: 'ACCOUNT_WALLET_BALANCES_FETCH_FAILED', - message: 'Failed to fetch account wallet balances', - details: error, - }); - this.emitError('getAccountWalletBalances', err); - throw err; - } - } + async getAccountWalletBalances(): Promise { + requireSecretKey('getAccountWalletBalances'); + emitStart('getAccountWalletBalances'); + try { + const response = await privateApiClient!.get('/sdk/account/wallet-balances'); + const result: AllLedgerBalances = { + balances: response.data.balances.map((balance: any) => ({ + ledgerId: balance.ledgerId, + ledgerName: balance.ledgerName, + ledgerSymbol: balance.ledgerSymbol, + canisterId: balance.canisterId, + balance: balance.balance, + formattedBalance: balance.formattedBalance, + decimals: balance.decimals, + currentPrice: balance.currentPrice, + lastPriceUpdate: balance.lastPriceUpdate ? new Date(balance.lastPriceUpdate) : undefined, + lastUpdated: new Date(balance.lastUpdated), + } as LedgerBalance)), + totalBalancesUSD: response.data.totalBalancesUSD, + lastUpdated: new Date(response.data.lastUpdated), + }; + emitSuccess('getAccountWalletBalances', { count: result.balances.length, totalUSD: result.totalBalancesUSD }); + return result; + } catch (error) { + const err = new IcpayError({ + code: 'ACCOUNT_WALLET_BALANCES_FETCH_FAILED', + message: 'Failed to fetch account wallet balances', + details: error, + }); + emitError('getAccountWalletBalances', err); + throw err; + } + }, + }; } -