/** * Soledgic SDK Type Definitions * All request/response interfaces and type aliases */ interface SoledgicConfig { apiKey: string; /** API base URL. Defaults to Soledgic's public v1 API endpoint. */ baseUrl?: string; /** Request timeout in milliseconds. Default: 30000 (30s). */ timeout?: number; /** API version header to send with requests. Default: 2026-03-01. */ apiVersion?: string; } type WebhookPayloadInput = string | ArrayBuffer | ArrayBufferView | Record; interface VerifyWebhookSignatureOptions { toleranceSeconds?: number; now?: number | Date; } interface ParsedWebhookEvent> { id: string | null; type: string; createdAt: string | null; livemode: boolean | null; data: T | null; raw: Record; } interface WebhookEndpoint { id: string; url: string; description: string | null; events: string[]; isActive: boolean; createdAt: string; secretRotatedAt: string | null; } interface WebhookEndpointSecretResult extends WebhookEndpoint { secret: string | null; } interface WebhookDelivery { id: string; endpointId: string | null; endpointUrl: string | null; eventType: string; status: string; attempts: number; maxAttempts: number | null; responseStatus: number | null; responseBody: string | null; responseTimeMs: number | null; createdAt: string; deliveredAt: string | null; nextRetryAt: string | null; payload: Record | null; } interface WebhookDeliveriesRequest { endpointId?: string; eventType?: string; status?: string; checkoutId?: string; orderId?: string; paymentId?: string; limit?: number; } interface WebhookDeliveriesResponse { success: boolean; data: WebhookDelivery[]; } type SandboxWebhookEventType = 'sandbox.test' | 'checkout.completed' | 'checkout.failed' | 'membership.activated' | 'membership.cancelled' | 'membership.past_due' | 'membership.expired' | 'dispute.created' | 'dispute.funds_withdrawn' | 'chargeback.created' | 'chargeback.funds_withdrawn' | 'hold.created' | 'hold.released' | 'hold.failed' | 'refund_request.created' | 'refund_request.completed' | 'refund_request.rejected' | 'refund_request.cancelled' | 'payout_request.created' | 'payout_request.approved' | 'payout_request.rejected' | 'payout_request.cancelled' | 'payout_request.failed' | 'payout_request.completed' | 'refund.created' | 'sale.refunded' | 'payout.created' | 'payout.processing' | 'payout.executed' | 'payout.failed'; type SandboxScenarioType = 'checkout.failed' | 'refund.created' | 'sale.refunded' | 'payout.failed' | 'dispute.created' | 'dispute.funds_withdrawn' | 'chargeback.created' | 'chargeback.funds_withdrawn' | 'hold.created' | 'hold.released' | 'hold.failed'; interface SandboxScenarioRequest { idempotencyKey: string; scenario: SandboxScenarioType; source?: string; runId?: string; checkoutId?: string; orderId?: string; externalOrderId?: string; paymentId?: string; participantId?: string; creatorId?: string; customerId?: string; externalUserId?: string; amountCents?: number; currency?: string; reason?: string; occurredAt?: string | Date; metadata?: Record; } interface RecordIncomeRequest { referenceId: string; amount: number; description?: string; category?: string; customerId?: string; customerName?: string; receivedTo?: string; invoiceId?: string; transactionDate?: string; metadata?: Record; } interface RecordExpenseRequest { referenceId: string; amount: number; description?: string; category?: string; vendorId?: string; vendorName?: string; paidFrom?: 'cash' | 'credit_card' | string; receiptUrl?: string; taxDeductible?: boolean; transactionDate?: string; metadata?: Record; authorizingInstrumentId?: string; riskEvaluationId?: string; authorizationDecisionId?: string; } interface RecordBillRequest { amount: number; description: string; vendorName: string; vendorId?: string; referenceId?: string; dueDate?: string; expenseCategory?: string; paid?: boolean; metadata?: Record; authorizingInstrumentId?: string; riskEvaluationId?: string; authorizationDecisionId?: string; } interface ExtractedTerms { amount: number; currency: string; cadence?: 'one_time' | 'monthly' | 'quarterly' | 'annual' | 'weekly' | 'bi_weekly'; counterpartyName: string; } interface RegisterInstrumentRequest { externalRef: string; extractedTerms: ExtractedTerms; } interface RegisterInstrumentResponse { success: boolean; instrumentId: string; fingerprint: string; externalRef: string; } interface AuthorizationResult { verified: boolean; instrumentId: string; externalRef: string; mismatches?: string[]; } interface ProjectIntentRequest { authorizingInstrumentId: string; untilDate: string; horizonCount?: number; } interface ProjectIntentResponse { success: boolean; instrumentId: string; externalRef: string; cadence: string; projectionsCreated: number; projectionsRequested: number; duplicatesSkipped: number; dateRange: { from: string; to: string; }; projectedDates: string[]; } interface ProjectionMatch { matched: boolean; projectionId: string; expectedDate: string; instrumentId: string; } interface ObligationItem { expectedDate: string; amount: number; currency: string; counterparty: string | null; } interface Obligations { pendingTotal: number; pendingCount: number; items: ObligationItem[]; } interface BreachRisk { atRisk: boolean; shortfall: number; coverageRatio: number; } type AlertType = 'breach_risk' | 'projection_created' | 'instrument_invalidated'; type AlertChannel = 'slack' | 'email' | 'webhook'; interface AlertThresholds { coverageRatioBelow?: number; shortfallAbove?: number; } interface SlackAlertConfig { webhookUrl: string; channel?: string; } interface EmailAlertConfig { recipients: string[]; } interface AlertConfiguration { id: string; alertType: AlertType; channel: AlertChannel; config: SlackAlertConfig | EmailAlertConfig | Record; thresholds: AlertThresholds; isActive: boolean; lastTriggeredAt?: string; triggerCount: number; createdAt: string; } interface CreateAlertRequest { alertType: AlertType; channel: AlertChannel; config: SlackAlertConfig | EmailAlertConfig; thresholds?: AlertThresholds; isActive?: boolean; } interface UpdateAlertRequest { configId: string; config?: Partial; thresholds?: AlertThresholds; isActive?: boolean; } interface AlertTestResult { success: boolean; message: string; channel?: string; error?: string; } type PolicyType = 'require_instrument' | 'budget_cap' | 'projection_guard'; type PolicySeverity = 'hard' | 'soft'; type AuthorizationDecisionType = 'allowed' | 'warn' | 'blocked'; interface PolicyViolation { policyId: string; policyType: PolicyType; severity: PolicySeverity; reason: string; } interface PreflightAuthorizationRequest { idempotencyKey: string; amount: number; currency?: string; counterpartyName?: string; authorizingInstrumentId?: string; expectedDate?: string; category?: string; } interface PreflightAuthorizationResponse { success: boolean; cached: boolean; decision: { id: string; decision: AuthorizationDecisionType; violatedPolicies: PolicyViolation[]; expiresAt: string; createdAt: string; }; message?: string; } interface AuthorizationPolicy { id: string; policyType: PolicyType; config: Record; severity: PolicySeverity; priority: number; isActive: boolean; createdAt: string; } interface CreatePolicyRequest { policyType: PolicyType; config: Record; severity?: PolicySeverity; priority?: number; } interface PreflightResult { decisionId: string; decision: AuthorizationDecisionType; warning?: string; } interface RecordRefundResponse { success: boolean; transactionId: string | null; referenceId: string | null; saleReference: string | null; refundedAmountCents: number | null; currency: string | null; status: string | null; breakdown: { fromCreatorCents: number; fromPlatformCents: number; } | null; isFullRefund: boolean | null; repairPending?: boolean | null; warning?: string | null; warningCode?: string | null; } interface ListRefundsRequest { saleReference?: string; limit?: number; } interface RefundSummary { id: string; transactionId: string | null; referenceId: string | null; saleReference: string | null; refundedAmountCents: number; currency: string; status: string; reason: string | null; refundFrom: string | null; externalRefundId: string | null; createdAt: string | null; breakdown: { fromCreatorCents: number; fromPlatformCents: number; } | null; repairPending?: boolean | null; lastError?: string | null; } interface ListRefundsResponse { success: boolean; refunds: RefundSummary[]; count: number; } interface ReverseTransactionRequest { transactionId: string; reason: string; partialAmount?: number; idempotencyKey?: string; metadata?: Record; } interface CreatePeriodRequest { startDate: string; endDate: string; name?: string; } interface ReconcileMatchRequest { transactionId: string; bankTransactionId: string; } interface CreateSnapshotRequest { periodId?: string; asOfDate?: string; } interface BackdatePolicyRequest { policyType: 'none' | 'soft' | 'hard'; gracePeriodDays?: number; maxBackdateDays?: number; requireApproval?: boolean; allowCurrentMonth?: boolean; allowPriorMonth?: boolean; blockPriorQuarter?: boolean; } interface ParticipantPayoutPreferences { schedule?: 'manual' | 'weekly' | 'biweekly' | 'monthly'; minimumAmount?: number; } interface CreateParticipantRequest { participantId: string; displayName?: string; email?: string; defaultSplitPercent?: number; payoutPreferences?: ParticipantPayoutPreferences; metadata?: Record; } /** * @deprecated Public ledger creation is retired. Use authenticated onboarding. */ interface CreateLedgerRequest { businessName: string; ownerEmail: string; ledgerMode?: 'standard' | 'platform'; settings?: { defaultTaxRate?: number; defaultSplitPercent?: number; platformFeePercent?: number; minPayoutAmount?: number; payoutSchedule?: 'manual' | 'weekly' | 'monthly'; taxWithholdingPercent?: number; currency?: string; fiscalYearStart?: string; receiptThreshold?: number; }; } interface ExportReportRequest { reportType: 'transaction_detail' | 'creator_earnings' | 'platform_revenue' | 'payout_summary' | 'reconciliation' | 'audit_log'; format: 'csv' | 'json'; startDate?: string; endDate?: string; creatorId?: string; } interface RecordAdjustmentRequest { adjustmentType: 'correction' | 'reclassification' | 'accrual' | 'deferral' | 'depreciation' | 'write_off' | 'year_end' | 'opening_balance' | 'other'; entries: Array<{ accountType: string; entityId?: string; entryType: 'debit' | 'credit'; amount: number; }>; reason: string; adjustmentDate?: string; originalTransactionId?: string; supportingDocumentation?: string; preparedBy: string; } interface RecordOpeningBalanceRequest { asOfDate: string; source: 'manual' | 'imported' | 'migrated' | 'year_start'; sourceDescription?: string; balances: Array<{ accountType: string; entityId?: string; balance: number; }>; } interface RecordTransferRequest { fromAccountType: string; toAccountType: string; amount: number; transferType: 'tax_reserve' | 'payout_reserve' | 'owner_draw' | 'owner_contribution' | 'operating' | 'savings' | 'investment' | 'other'; description?: string; referenceId: string; } interface RiskEvaluationRequest { idempotencyKey: string; amount: number; currency?: string; counterpartyName?: string; authorizingInstrumentId?: string; expectedDate?: string; category?: string; } interface UploadReceiptRequest { fileUrl: string; fileName?: string; fileSize?: number; mimeType?: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'application/pdf'; merchantName?: string; transactionDate?: string; totalAmount?: number; transactionId?: string; } interface GenerateReceiptRequest { checkoutId?: string; checkoutSessionId?: string; transactionId?: string; saleTransactionId?: string; orderId?: string; externalOrderId?: string; metadata?: Record; } interface ReceiptResource { id: string; receiptId: string; status: string; hostedUrl: string | null; fileUrl: string | null; checkoutSessionId: string | null; saleTransactionId: string | null; orderId: string | null; externalOrderId: string | null; totalAmount: number | null; currency: string | null; createdAt: string | null; metadata: Record; } interface GenerateReceiptResponse { success: boolean; idempotent?: boolean; receipt: ReceiptResource | null; receiptId: string | null; hostedUrl: string | null; } interface GetReceiptResponse { success: boolean; receipt: ReceiptResource | null; } interface ReceivePaymentRequest { amount: number; invoiceTransactionId?: string; customerName?: string; customerId?: string; referenceId?: string; paymentMethod?: string; paymentDate?: string; metadata?: Record; } interface ParticipantWalletMutationRequest { participantId: string; amount: number; referenceId: string; description?: string; metadata?: Record; } interface ParticipantTransferRequest { fromParticipantId: string; toParticipantId: string; amount: number; referenceId: string; description?: string; metadata?: Record; } interface HoldQueryOptions { participantId?: string; ventureId?: string; readyOnly?: boolean; limit?: number; } interface ReleaseHoldRequest { holdId: string; /** * @deprecated Hold release never executes a payout. This option is accepted * for source compatibility and ignored; use `payouts.create` for ACH. */ executeTransfer?: boolean; } type StandardCheckoutPayment = ({ paymentMethodId: string; idempotencyKey: string; successUrl?: string; cancelUrl?: string; } | { paymentMethodId?: undefined; successUrl: string; cancelUrl?: string; idempotencyKey?: string; }); type WalletFundedHostedCheckoutMode = { /** The authenticated consumer whose wallet is funded and debited atomically. */ buyerUserId: string; purchaseMode: 'direct_funded_wallet'; paymentMethodId?: undefined; successUrl: string; cancelUrl?: string; idempotencyKey?: string; }; type CreateCheckoutSessionRequest = { participantId: string; amount: number; currency?: 'USD'; productId?: string; productName?: string; /** Customer email for hosted display/receipts. Sandbox buyer sessions can use this alone to derive a stable test wallet. */ customerEmail?: string; customerId?: string; /** Request a releasable marketplace hold; completed checkout webhooks include hold_id/payment_hold_id. */ holdFunds?: boolean; sandboxCheckoutProvider?: 'soledgic' | 'stripe'; metadata?: Record; } & (WalletFundedHostedCheckoutMode | ({ purchaseMode?: undefined; buyerUserId?: string; } & StandardCheckoutPayment)); type MembershipBillingInterval = 'weekly' | 'monthly' | 'quarterly' | 'annual'; interface MembershipTier { id: string; tierKey: string; name: string; description: string | null; participantId: string; productId: string | null; amountCents: number; currency: string; billingInterval: MembershipBillingInterval; trialDays: number; active: boolean; benefits: unknown[]; metadata: Record; createdAt: string | null; updatedAt: string | null; } interface CreateMembershipTierRequest { tierKey: string; name: string; participantId: string; amountCents: number; currency?: 'USD'; billingInterval?: MembershipBillingInterval; description?: string; productId?: string; trialDays?: number; active?: boolean; benefits?: unknown[]; metadata?: Record; } interface Membership { id: string; tierId: string | null; customerId: string; customerEmail: string | null; buyerUserId: string | null; status: string; currentPeriodStart: string | null; currentPeriodEnd: string | null; cancelAtPeriodEnd: boolean; latestCheckoutSessionId: string | null; latestTransactionId: string | null; metadata: Record; createdAt: string | null; updatedAt: string | null; } type CreateMembershipRequest = { tierId?: string; tierKey?: string; customerId: string; customerEmail?: string; buyerUserId?: string; metadata?: Record; sandboxCheckoutProvider?: 'soledgic' | 'stripe'; } & ({ paymentMethodId: string; idempotencyKey: string; successUrl?: string; cancelUrl?: string; } | { paymentMethodId?: undefined; successUrl: string; cancelUrl?: string; idempotencyKey?: string; }); interface MembershipResponse { success: boolean; membership: Membership | Record; billingCycle?: Record | null; checkoutSession?: CheckoutSessionResourceResponse['checkoutSession'] | Record | null; } interface MembershipEntitlementsResponse { success: boolean; entitlements: Array<{ membershipId: string; tierId: string; tierKey: string; customerId: string; active: boolean; currentPeriodEnd: string | null; benefits: unknown[]; }>; } type WalletSessionPermission = 'view_balance' | 'list_activity' | 'top_up' | 'request_refund'; type WalletSessionOwnerType = 'user' | 'consumer' | 'participant' | 'creator' | (string & {}); interface CreateWalletSessionRequest { /** Existing wallet id in the API key's ledger. Soledgic binds the session to that ledger's organization. */ walletId?: string; /** Your app's stable customer/user id, or the participant id for creator earnings sessions. */ ownerId?: string; /** Alias for ownerId. */ externalUserId?: string; /** * Use user/consumer for buyer wallet sessions and participant/creator for creator earnings sessions. * Creator sessions resolve participant_identity_links and require an existing creator_balance account. */ ownerType?: WalletSessionOwnerType; customerEmail?: string; permissions?: WalletSessionPermission[]; successUrl?: string; cancelUrl?: string; expiresInMinutes?: number; idempotencyKey?: string; metadata?: Record; } interface CreatePayoutRequest { participantId: string; walletId?: string; amount: number; referenceId: string; referenceType?: string; description?: string; payoutMethod?: string; fees?: number; feesPaidBy?: 'platform' | 'creator'; metadata?: Record; } interface CreateRefundRequest { saleReference: string; reason: string; amount?: number; refundFrom?: 'both' | 'platform_only' | 'creator_only'; externalRefundId?: string; idempotencyKey?: string; metadata?: Record; } type RefundRequestStatus = 'pending' | 'processing' | 'completed' | 'rejected' | 'cancelled' | 'failed'; type RefundFrom = 'both' | 'platform_only' | 'creator_only'; interface RefundRequestResource { id: string; saleReference: string | null; saleTransactionId: string | null; customerId: string | null; customerEmail: string | null; amount: number; amountCents: number; currency: string | null; reason: string | null; refundFrom: RefundFrom | string | null; status: RefundRequestStatus | string; refundTransactionId: string | null; rejectionReason: string | null; failureReason: string | null; createdAt: string | null; updatedAt: string | null; reviewedAt: string | null; completedAt: string | null; cancelledAt: string | null; metadata: Record; } interface CreateRefundRequestParams { saleReference: string; originalSaleReference?: string; amount?: number; reason: string; refundFrom?: RefundFrom; customerId?: string; customerEmail?: string; requesterUserId?: string; idempotencyKey?: string; metadata?: Record; } interface ListRefundRequestsParams { status?: RefundRequestStatus | string; saleReference?: string; customerId?: string; limit?: number; } interface ReviewRefundRequestParams { refundRequestId: string; reason?: string; reviewedByUserId?: string; reviewedByActor?: string; metadata?: Record; } interface RefundRequestResourceResponse { success: boolean; idempotent?: boolean; refundRequest: RefundRequestResource | null; refund?: RefundResourceResponse['refund'] | null; error?: string; errorCode?: string; } interface ListRefundRequestsResponse { success: boolean; refundRequests: RefundRequestResource[]; count: number; } interface SandboxCheckoutCompleteRequest { checkoutSessionId: string; idempotencyKey: string; paymentId?: string; metadata?: Record; } interface SandboxCheckoutFailRequest { checkoutSessionId: string; idempotencyKey: string; reason?: string; metadata?: Record; } interface SandboxWebhookTestRequest { idempotencyKey: string; eventType?: SandboxWebhookEventType; payload?: Record; } interface SandboxEventsRequest { eventType?: SandboxWebhookEventType | string; limit?: number; checkoutId?: string; orderId?: string; paymentId?: string; } interface SandboxCheckoutActionResponse { success: boolean; idempotent?: boolean; alreadyExists?: boolean; status?: string | null; checkoutSession: { id: string; status: string | null; mode: string | null; paymentId: string | null; referenceId: string | null; amount: number | null; currency: string | null; creatorId: string | null; productId: string | null; productName: string | null; completedAt: string | null; saleTransactionId?: string | null; webhookDeliveriesQueued?: number | null; webhookDeliveriesDelivered?: number | null; } | null; webhookDeliveries?: WebhookDelivery[]; webhookDeliveryOutcomes?: Array<{ id: string; outcome: 'delivered' | 'failed' | 'blocked'; }>; error?: string; errorCode?: string; } interface SandboxWebhookTestResponse { success: boolean; eventType: string; webhookDeliveriesQueued: number; webhookDeliveriesDelivered?: number; webhookDeliveries: WebhookDelivery[]; webhookDeliveryOutcomes?: Array<{ id: string; outcome: 'delivered' | 'failed' | 'blocked'; }>; } interface SandboxEventsResponse { success: boolean; count: number; events: WebhookDelivery[]; } interface WebhookReplayResponse { success: boolean; message?: string; data: WebhookDelivery | null; outcomes?: Array<{ id: string; outcome: 'delivered' | 'failed' | 'blocked'; }>; } interface SandboxCleanupRequest { /** Defaults to true unless confirm is true. Set false with confirm to execute cleanup. */ dryRun?: boolean; /** run deletes rows matching source/runId; sandbox_ledger resets runtime data and preserves webhook endpoints. */ scope?: 'run' | 'sandbox_ledger'; source?: string; runId?: string; /** Pass true to send the required cleanup confirmation token for the selected scope. */ confirm?: boolean; } interface SandboxCleanupResponse { success: boolean; mode: 'sandbox'; dryRun: boolean; scope: 'run' | 'sandbox_ledger'; ledgerId: string; source: string | null; runId: string | null; counts: Record; errors?: Record; estimatedDeleted?: number; cleaned?: boolean; deleted?: Record; cleanup?: Record; preserved?: Record; message?: string; error?: string; errorCode?: string; } interface UpsertUserWalletRequest { /** Your app's stable user/customer id. The wallet is bound to the API key's organization server-side. */ externalUserId: string; /** Optional label for the wallet owner type. Defaults to "user". */ ownerType?: string; name?: string; metadata?: Record; } interface UpsertCreatorRequest { /** Your app's stable creator/seller id. */ externalCreatorId: string; displayName?: string; /** Creates a pending identity invite. Exact upsert retries preserve the delivered invite; no consumer wallet is created. */ email?: string; defaultSplitPercent?: number; payoutPreferences?: ParticipantPayoutPreferences; metadata?: Record; } interface CreateCreatorWalletRequest { /** Your app's stable creator/seller id, mapped to a Soledgic participant. */ creatorId: string; name?: string; metadata?: Record; } type UniversalCheckoutBaseRequest = { /** Your app's stable creator/seller id, mapped to participant_id. */ creatorId: string; amount: number; currency?: string; /** Your app's stable product/session id, mapped to product_id. */ externalProductId?: string; productName?: string; /** Your app's stable buyer/user id, mapped to customer_id. */ externalUserId?: string; customerEmail?: string; /** Your app's stable order/purchase id. Used as idempotency_key when no explicit idempotencyKey is provided. */ externalOrderId?: string; /** Request a releasable marketplace hold; completed checkout webhooks include hold_id/payment_hold_id. */ holdFunds?: boolean; sandboxCheckoutProvider?: 'soledgic' | 'stripe'; metadata?: Record; }; type UniversalCheckoutRequest = UniversalCheckoutBaseRequest & (WalletFundedHostedCheckoutMode | ({ purchaseMode?: undefined; buyerUserId?: string; } & StandardCheckoutPayment)); /** * A buyer-funded hosted checkout. Soledgic collects funds through the configured * hosted processor, credits the buyer wallet, and applies the purchase atomically. * This request never enters creator/merchant onboarding. */ type CreateWalletFundedCheckoutRequest = UniversalCheckoutBaseRequest & { /** Non-empty authenticated consumer id used for wallet accounting. */ buyerUserId: string; /** Required redirect after the hosted processor confirms payment. */ successUrl: string; cancelUrl?: string; /** Explicit idempotency key. Falls back to externalOrderId when omitted. */ idempotencyKey?: string; currency?: 'USD'; }; interface InvoiceLineItem { description: string; quantity: number; unitPrice: number; amount?: number; } interface CreateInvoiceRequest { customerName: string; customerEmail?: string; customerId?: string; customerAddress?: { line1?: string; line2?: string; city?: string; state?: string; postalCode?: string; country?: string; }; lineItems: InvoiceLineItem[]; taxAmount?: number; discountAmount?: number; dueDate?: string; notes?: string; terms?: string; referenceId?: string; metadata?: Record; } interface RecordInvoicePaymentRequest { amount: number; paymentMethod?: string; paymentDate?: string; referenceId?: string; notes?: string; } interface PayBillRequest { billTransactionId?: string; amount: number; vendorName?: string; referenceId?: string; paymentMethod?: string; paymentDate?: string; metadata?: Record; } interface CreateBudgetRequest { name: string; categoryCode?: string; budgetAmount: number; budgetPeriod: 'weekly' | 'monthly' | 'quarterly' | 'annual'; alertAtPercentage?: number; } interface CreateRecurringRequest { name: string; merchantName: string; categoryCode: string; amount: number; recurrenceInterval: 'weekly' | 'monthly' | 'quarterly' | 'annual'; recurrenceDay?: number; startDate: string; endDate?: string; businessPurpose: string; isVariableAmount?: boolean; } interface CreateContractorRequest { name: string; email?: string; companyName?: string; } interface RecordContractorPaymentRequest { contractorId: string; amount: number; paymentDate: string; paymentMethod?: string; paymentReference?: string; description?: string; } interface CreateBankAccountRequest { bankName: string; accountName: string; accountType: 'checking' | 'savings' | 'credit_card' | 'other'; accountLastFour?: string; } interface SubmitTaxInfoRequestBase { participantId: string; legalName: string; taxIdType: 'ssn' | 'ein' | 'itin'; taxIdLast4: string; businessType: 'individual' | 'sole_proprietor' | 'llc' | 'corporation' | 'partnership'; address?: { line1?: string; line2?: string; city?: string; state?: string; postalCode?: string; country?: string; }; certify: boolean; } type SubmitTaxInfoRequest = SubmitTaxInfoRequestBase & ({ /** Full 9-digit TIN, stored only through Soledgic Vault's atomic tax RPC. */ taxIdFull: string; /** Required with taxIdFull so an ambiguous retry cannot create another Vault secret or certification. */ idempotencyKey: string; } | { taxIdFull?: undefined; /** Optional for a last-four-only certification. */ idempotencyKey?: string; }); type KycStatus = 'pending' | 'under_review' | 'approved' | 'rejected' | 'suspended'; type KycTaxIdType = 'ssn' | 'ein' | 'itin'; type KycBusinessType = 'individual' | 'sole_proprietor' | 'llc' | 'corporation' | 'partnership' | 'nonprofit'; type CreatorKycBusinessType = Exclude; type KycDocumentType = 'government_id' | 'proof_of_address' | 'w9' | 'ein_letter' | 'articles_of_incorporation' | 'beneficial_owner_id' | 'processor_verification' | 'other'; interface KycAddress { line1?: string; line2?: string; city?: string; state?: string; postalCode?: string; country?: string; } interface KycDocumentEvidence { documentType: KycDocumentType; fileName?: string; /** HTTPS source copied into private compliance storage. Creator KYC requires idempotencyKey when this is set. */ fileUrl?: string; providerDocumentId?: string; processorVerificationId?: string; mimeType?: string; fileSizeBytes?: number; metadata?: Record; } interface BusinessKybPrimaryContact { name: string; email: string; phone?: string; } interface BusinessKybBeneficialOwner { name?: string; email?: string; title?: string; ownershipPercent?: number; dateOfBirth?: string; address?: KycAddress; governmentIdLast4?: string; } interface SubmitBusinessKybRequest { businessType: KycBusinessType; legalName: string; taxIdType?: KycTaxIdType; taxIdLast4?: string; /** Optional full TIN. Stored only through the atomic Vault/KYB transaction and never returned. */ taxIdFull?: string; primaryContact: BusinessKybPrimaryContact; businessAddress: KycAddress; beneficialOwners?: BusinessKybBeneficialOwner[]; documentEvidence: KycDocumentEvidence[]; /** Stable key for retrying this exact KYB draft or review submission. */ idempotencyKey: string; /** Defaults to true. When false, Soledgic stores a pending draft instead of marking KYB under review. */ submitForReview?: boolean; metadata?: Record; } interface SubmitCreatorKycRequest { participantId: string; legalName: string; displayName?: string; email: string; dateOfBirth: string; taxIdType?: KycTaxIdType; taxIdLast4?: string; businessType?: CreatorKycBusinessType; address: KycAddress; documentEvidence: KycDocumentEvidence[]; /** Stable retry key. Required at runtime when any document evidence uses fileUrl. */ idempotencyKey?: string; /** Defaults to true. When false, Soledgic stores a pending draft instead of marking KYC under review. */ submitForReview?: boolean; metadata?: Record; } interface CreateCreatorVerificationSessionRequest { participantId: string; /** Optional post-verification destination on an HTTPS origin registered to your organization. */ returnUrl?: string; /** Session lifetime from 5 to 60 minutes. Defaults to 30. */ expiresInMinutes?: number; /** Stable key for safely retrying the same session creation request. */ idempotencyKey?: string; metadata?: Record; } type CreatorVerificationSessionStatus = 'pending' | 'consumed' | 'completed' | 'expired' | 'revoked'; interface CreateCreatorVerificationSessionResponse { success: boolean; already_exists?: boolean; creator_verification_session: { id: string; object: 'creator_verification_session'; participant_id: string; status: CreatorVerificationSessionStatus; /** Hosted URL. The one-time client secret is carried in the URL fragment, not the request path. */ url: string; /** One-time secret returned only by this API. Never log or persist it. */ client_secret: string; return_url: string | null; expires_at: string; created_at: string; metadata: Record; }; } interface KycSubmissionSummary { id: string; status: KycStatus; submitted_at: string; reviewed_at?: string | null; rejection_reason?: string | null; } interface BusinessKybResponse { success: boolean; business_kyb: { organization_id: string; status: KycStatus; missing_fields?: string[]; latest_submission?: KycSubmissionSummary | null; [key: string]: unknown; }; } interface CreatorKycResponse { success: boolean; creator_kyc: { participant_id: string; connected_account_id?: string | null; status: KycStatus; tax_certified?: boolean; missing_fields?: string[]; latest_submission?: KycSubmissionSummary | null; [key: string]: unknown; }; } interface ImportBankStatementLine { transactionDate: string; postDate?: string; description: string; amount: number; referenceNumber?: string; checkNumber?: string; merchantName?: string; categoryHint?: string; } interface ImportBankStatementRequest { bankAccountId: string; lines: ImportBankStatementLine[]; autoMatch?: boolean; } interface CheckoutBreakdown { grossAmountCents: number; subtotalAmountCents: number | null; salesTaxAmountCents: number | null; salesTaxState: string | null; creatorAmountCents: number; platformAmountCents: number; soledgicFeeCents: number | null; creatorPercent: number; } interface ReverseResponse { success: boolean; voidType: string; message: string; transactionId: string; reversalId: string | null; reversedAmount: number | null; isPartial: boolean | null; voidedAt: string | null; reversedAt: string | null; warning: string | null; } interface Period { id: string; name: string; startDate: string; endDate: string; status: 'open' | 'closed' | 'locked' | 'archived'; lockedAt?: string; balanceCheck?: { isBalanced: boolean; totalDebits: number; totalCredits: number; }; } interface ReconciliationSnapshot { id: string; periodStart: string; periodEnd: string; integrityHash: string; integrityValid: boolean; summary: { totalMatched: number; totalUnmatched: number; matchedAmount: number; unmatchedAmount: number; }; } interface FrozenStatement { type: 'profit_loss' | 'balance_sheet' | 'trial_balance'; periodId: string; generatedAt: string; integrityHash: string; integrityValid: boolean; readOnly: true; data: any; } interface ParticipantSummary { id: string; linkedUserId: string | null; name: string | null; tier: string | null; ledgerBalanceCents: number; heldAmountCents: number; availableBalanceCents: number; } interface ParticipantDetail { id: string; linkedUserId: string | null; name: string | null; tier: string | null; customSplitPercent: number | null; ledgerBalanceCents: number; heldAmountCents: number; availableBalanceCents: number; holds: Array<{ amountCents: number; reason: string | null; releaseDate: string | null; status: string; }>; } interface CreateParticipantResponse { success: boolean; participant: { id: string; accountId: string; created: boolean; linkedUserId: string | null; identityLinkId: string | null; identityLinkStatus: 'active' | 'pending' | null; displayName: string | null; email: string | null; defaultSplitPercent: number; payoutPreferences: Record; createdAt: string; }; } interface ParticipantPayoutEligibilityResponse { success: boolean; eligibility: { participantId: string; eligible: boolean; availableBalanceCents: number; issues: string[]; requirements: Record; }; } /** * @deprecated Public ledger creation is retired. The SDK method now throws a * 410 ENDPOINT_RETIRED error instead of calling /v1/create-ledger. */ interface CreateLedgerResponse { success: boolean; ledger: { id: string; businessName: string; ledgerMode: string; apiKey: string; status: string; createdAt: string; }; warning: string; } interface ExportReportJsonResponse { success: boolean; reportType: string; generatedAt: string; rowCount: number; data: any[]; } interface ExportReportCsvResponse { csv: string; filename: string; } interface RiskEvaluationResponse { success: boolean; cached: boolean; evaluation: { id: string; signal: 'within_policy' | 'elevated_risk' | 'high_risk'; riskFactors: Array<{ policyId: string; policyType: string; severity: 'hard' | 'soft'; indicator: string; }>; validUntil: string; createdAt: string; acknowledgedAt: string | null; }; } interface FraudPolicyResource { id: string; type: PolicyType; severity: PolicySeverity; priority: number; isActive: boolean; config: Record; createdAt: string | null; updatedAt: string | null; } interface FraudPolicyListResponse { success: boolean; policies: FraudPolicyResource[]; } interface FraudPolicyResponse { success: boolean; policy: FraudPolicyResource; } interface FraudPolicyDeleteResponse { success: boolean; deleted: boolean; policyId: string; } interface ReconciliationMatchResponse { success: boolean; match: { id: string; transactionId: string; bankTransactionId: string; status: string; matchedAt: string; }; } interface ReconciliationUnmatchResponse { success: boolean; deleted: boolean; transactionId: string; } interface UnmatchedTransactionsResponse { success: boolean; unmatchedCount: number; transactions: Array<{ id: string; referenceId: string | null; description: string | null; amount: number; currency: string; createdAt: string; status: string; metadata: Record; }>; } interface AutoMatchReconciliationResponse { success: boolean; result: { matched: boolean; matchType: string | null; matchedTransactionId: string | null; bankAggregatorTransactionId: string; }; } interface TaxDocumentsResponse { success: boolean; taxYear: number; summary: { totalDocuments: number; totalAmount: number; byStatus: { calculated: number; exported: number; filed: number; }; }; documents: any[]; } interface TaxDocumentResponse { success: boolean; document: any; } interface TaxDocumentGenerationResponse { success: boolean; generation: { taxYear: number; created: number; skipped: number; totalAmount: number; }; } interface TaxCalculationResponse { success: boolean; calculation: { participantId: string; taxYear: number; grossPayments: number; transactionCount: number; requires1099: boolean; monthlyTotals: Record; threshold: number; linkedUserId: string | null; sharedTaxProfile: { status: string; } | null; }; } interface TaxSummaryResponse { success: boolean; taxYear: number; note: string; summaries: Array<{ participantId: string; linkedUserId: string | null; grossEarnings: number; refundsIssued: number; netEarnings: number; totalPaidOut: number; requires1099: boolean; sharedTaxProfile: { status: string; } | null; }>; totals: { totalGross: number; totalRefunds: number; totalNet: number; totalPaid: number; participantsRequiring1099: number; }; } interface ComplianceOverviewResponse { success: boolean; overview: { windowDays: number; accessWindowHours: number; totalEvents: number; uniqueIps: number; uniqueActors: number; highRiskEvents: number; criticalRiskEvents: number; failedAuthEvents: number; payoutsFailed: number; refundsRecorded: number; disputeEvents: number; }; note: string; } interface ComplianceAccessPatternsResponse { success: boolean; windowHours: number; count: number; patterns: Array<{ ipAddress: string; hour: string; requestCount: number; uniqueActions: number; actions: string[]; maxRiskScore: number; failedAuths: number; }>; } interface ComplianceFinancialActivityResponse { success: boolean; windowDays: number; activity: Array<{ date: string; payoutsInitiated: number; payoutsCompleted: number; payoutsFailed: number; salesRecorded: number; refundsRecorded: number; disputeEvents: number; }>; } interface ComplianceSecuritySummaryResponse { success: boolean; windowDays: number; summary: Array<{ date: string; action: string; eventCount: number; uniqueIps: number; uniqueActors: number; avgRiskScore: number; maxRiskScore: number; highRiskCount: number; criticalRiskCount: number; }>; } interface UploadReceiptResponse { success: boolean; receiptId: string; status: 'uploaded' | 'matched' | 'orphan'; linkedTransactionId: string | null; } interface ReceivePaymentResponse { success: boolean; transactionId: string; amount: number; } interface WalletObject { id: string; object: 'wallet'; walletType: 'consumer_credit' | 'creator_earnings'; scopeType: 'customer' | 'participant'; ownerId: string | null; ownerType: string | null; participantId: string | null; accountType: string; name: string | null; currency: string; status: string; balance: number; heldAmount: number; availableBalance: number; redeemable: boolean; transferable: boolean; topupSupported: boolean; payoutSupported: boolean; createdAt: string | null; metadata: Record; } interface ListWalletsRequest { ownerId?: string; ownerType?: string; walletType?: WalletObject['walletType']; limit?: number; offset?: number; } interface ListWalletsResponse { success: boolean; wallets: WalletObject[]; total: number; limit: number; offset: number; } interface CreateWalletRequest { /** Your app's stable customer/user id. The wallet is scoped to the API key's ledger organization. */ ownerId?: string; /** Participant id for creator earnings wallets. */ participantId?: string; ownerType?: string; walletType: WalletObject['walletType']; name?: string; metadata?: Record; } interface CreateWalletResponse { success: boolean; created: boolean; wallet: WalletObject; } interface GetWalletResponse { success: boolean; wallet: WalletObject; } interface WalletEntriesResponse { success: boolean; wallet: WalletObject | null; entries: WalletHistoryEntry[]; total: number; limit: number; offset: number; } interface WalletTopupRequest { walletId: string; amount: number; referenceId: string; description?: string; metadata?: Record; } interface WalletTopupResponse { success: boolean; walletId: string | null; ownerId: string | null; transactionId: string | null; balance: number | null; } interface SharedWalletSpendRequest { /** The buyer's Soledgic OIDC subject (the `sub` from the ID token). */ consumerSub: string; /** Gross amount in cents. */ amount: number; /** Idempotency key. */ referenceId: string; /** Creator receiving the split. */ creatorId: string; /** Creator share of the subtotal (0-100). Defaults to 80. */ creatorPercent?: number; /** Sales tax in cents (part of gross). Defaults to 0. */ salesTax?: number; productId?: string; productName?: string; metadata?: Record; } interface SharedWalletSpendResponse { success: boolean; consumerTransactionId: string | null; platformTransactionId: string | null; referenceId: string | null; amountCents: number | null; creatorId: string | null; walletBalanceCents: number | null; creatorBalanceCents: number | null; } /** * Place an ESCROW hold against a buyer's shared Soledgic balance. Use this for * delivery/escrow purchases — funds leave the buyer's balance and are parked in * the platform's escrow account; the creator is paid only on release. (Use * `sharedSpend` for immediate-settlement purchases.) */ interface SharedWalletHoldRequest { /** The buyer's Soledgic OIDC subject (the `sub` from the ID token). */ consumerSub: string; /** Gross amount in cents. */ amount: number; /** Idempotency key — typically the order/escrow reference. */ referenceId: string; /** Creator receiving the split when the hold is released. */ creatorId: string; /** Creator share of the subtotal (0-100). Defaults to 80. */ creatorPercent?: number; /** Sales tax in cents (part of gross). Defaults to 0. */ salesTax?: number; productId?: string; productName?: string; metadata?: Record; } interface SharedWalletHoldResponse { success: boolean; holdId: string | null; consumerTransactionId: string | null; platformTransactionId: string | null; referenceId: string | null; amountCents: number | null; creatorId: string | null; status: string | null; walletBalanceCents: number | null; } /** Release or refund a previously placed shared-wallet escrow hold. */ interface SharedWalletHoldActionRequest { /** The hold reference (the `referenceId` used when placing the hold). */ referenceId: string; /** Refund only: an optional reason recorded on the reversal. */ reason?: string; metadata?: Record; } interface SharedWalletReleaseResponse { success: boolean; releaseTransactionId: string | null; referenceId: string | null; status: string | null; creatorBalanceCents: number | null; } interface SharedWalletRefundResponse { success: boolean; consumerTransactionId: string | null; platformTransactionId: string | null; referenceId: string | null; status: string | null; walletBalanceCents: number | null; } /** * Reverse a completed shared-wallet SPEND (the refund path for immediate-settled * purchases). The buyer is made whole; the creator's share is clawed back and * their balance may go negative (a debt recovered from future earnings). */ interface SharedWalletSpendReverseRequest { /** The platform sale transaction id returned when the spend was made. */ saleTransactionId: string; reason?: string; metadata?: Record; } interface SharedWalletSpendReverseResponse { success: boolean; consumerReversalTransactionId: string | null; platformReversalTransactionId: string | null; saleTransactionId: string | null; status: string | null; walletBalanceCents: number | null; /** Negative => the creator now carries a debt recovered from future earnings. */ creatorBalanceCents: number | null; } interface SharedWalletAuthorizationRevokeRequest { /** The buyer's Soledgic OIDC subject (from their ID token). */ consumerSub: string; } interface SharedWalletAuthorizationRevokeResponse { success: boolean; /** True if an active authorization was revoked; false if there was nothing active. */ revoked: boolean; consumerSub: string | null; } interface WalletWithdrawRequest { walletId: string; /** Amount in cents */ amount: number; referenceId: string; description?: string; metadata?: Record; } interface WalletWithdrawalResponse { success: boolean; walletId: string | null; ownerId: string | null; transactionId: string | null; balance: number | null; } interface WalletHistoryEntry { entryId: string; entryType: 'debit' | 'credit'; amount: number; transactionId: string; referenceId: string; transactionType: string; description: string | null; status: string; metadata: Record | null; createdAt: string; } interface ParticipantTransferResponse { success: boolean; transfer: { transactionId: string; fromParticipantId: string; toParticipantId: string; fromBalance: number; toBalance: number; }; } interface HeldFund { id: string; participantId: string | null; participantName: string | null; amount: number; currency: string; heldSince: string; daysHeld: number; holdReason: string | null; holdReasonCode: string; holdReasonDescription: string; holdUntil: string | null; readyForRelease: boolean; releaseStatus: string; transactionReference: string | null; productName: string | null; ventureId: string | null; connectedAccountReady: boolean; } interface HeldFundsResponse { success: boolean; holds: HeldFund[]; count: number; } interface HeldFundsSummaryResponse { success: boolean; summary: Record; } interface ReleaseHoldResponse { success: boolean; release: { id: string; holdId: string; status: string | null; availabilityReleased: boolean; /** @deprecated Always false for the current hold-release API. */ executed: boolean; /** @deprecated Always null; use the payout response for transfer ids. */ transferId: string | null; /** @deprecated Always null; use the payout response for transfer status. */ transferStatus: string | null; amount: number | null; currency: string | null; }; } interface CheckoutSessionResourceResponse { success: boolean; checkoutSession: { id: string; mode: 'session' | 'direct' | string; provider: string | null; checkoutUrl: string | null; paymentId: string | null; paymentIntentId: string | null; status: string | null; requiresAction: boolean; amount: number; currency: string; expiresAt: string | null; sandbox: boolean; fundingTransactionId: string | null; saleTransactionId: string | null; saleReference: string | null; holdId: string | null; paymentHoldId: string | null; breakdown: CheckoutBreakdown | null; }; } interface WalletSessionObject { id: string; object: 'wallet_session'; walletId: string; externalUserId: string | null; customerEmail: string | null; permissions: WalletSessionPermission[]; status: string; walletUrl: string; successUrl: string | null; cancelUrl: string | null; expiresAt: string; createdAt: string | null; metadata: Record; } interface CreateWalletSessionResponse { success: boolean; alreadyExists?: boolean; walletSession: WalletSessionObject; } interface PayoutResourceResponse { success: boolean; payout: { id: string; transactionId: string; grossAmountCents: number | null; feesCents: number | null; netAmountCents: number | null; previousBalanceCents: number | null; newBalanceCents: number | null; status?: string | null; simulated?: boolean; livemode?: boolean; payoutRail?: 'bank_ach' | 'sandbox' | string | null; bankTransferId?: string | null; bankTransferStatus?: string | null; /** @deprecated Use bankTransferId. */ processorTransferId?: string | null; /** @deprecated Use bankTransferStatus. */ processorTransferStatus?: string | null; webhookDeliveriesQueued?: number | null; webhookDeliveriesDelivered?: number | null; webhookDeliveryOutcomes?: Array<{ id: string; outcome: 'delivered' | 'failed' | 'blocked'; }>; }; } interface RefundResourceResponse { success: boolean; refund: { id: string; transactionId: string | null; referenceId: string | null; saleReference: string | null; refundedAmountCents: number | null; currency: string | null; status: string | null; breakdown: { fromCreatorCents: number; fromPlatformCents: number; } | null; isFullRefund: boolean | null; repairPending?: boolean | null; }; warning?: string | null; warningCode?: string | null; } /** * Soledgic SDK Error Classes * Typed errors with HTTP status mapping */ declare class SoledgicError extends Error { status: number; details?: unknown | undefined; code?: string | undefined; constructor(message: string, status: number, details?: unknown | undefined, code?: string | undefined); } declare class ValidationError extends SoledgicError { constructor(message: string, details?: unknown, code?: string); } declare class AuthenticationError extends SoledgicError { constructor(message?: string, details?: unknown, code?: string); } declare class NotFoundError extends SoledgicError { constructor(message: string, details?: unknown, code?: string); } declare class ConflictError extends SoledgicError { constructor(message: string, details?: unknown, code?: string); } /** * Soledgic SDK Webhook Utilities * Signature verification and event parsing */ declare function isArrayBufferView(value: unknown): value is ArrayBufferView; declare function webhookPayloadToString(payload: WebhookPayloadInput): string; declare function timingSafeEqual(a: string, b: string): boolean; declare function hmacHex(secret: string, payload: string): Promise; declare function parseWebhookSignatureHeader(signatureHeader: string): { timestamp: number | null; v1Signatures: string[]; }; declare function verifyWebhookSignature(payload: WebhookPayloadInput, signatureHeader: string, secret: string, options?: VerifyWebhookSignatureOptions): Promise; declare function parseWebhookEvent>(payload: WebhookPayloadInput): ParsedWebhookEvent; declare const SOLEDGIC_SANDBOX_WEBHOOK_EVENTS: readonly ["sandbox.test", "checkout.completed", "checkout.failed", "membership.activated", "membership.cancelled", "membership.past_due", "membership.expired", "dispute.created", "dispute.funds_withdrawn", "chargeback.created", "chargeback.funds_withdrawn", "hold.created", "hold.released", "hold.failed", "refund_request.created", "refund_request.completed", "refund_request.rejected", "refund_request.cancelled", "payout_request.created", "payout_request.approved", "payout_request.rejected", "payout_request.cancelled", "payout_request.failed", "payout_request.completed", "refund.created", "sale.refunded", "payout.created", "payout.processing", "payout.executed", "payout.failed"]; declare const SOLEDGIC_SANDBOX_TEST_CARDS: readonly [{ readonly brand: "visa"; readonly cardId: "sandbox_visa_success"; readonly cvc: "123"; readonly expMonth: "12"; readonly expYear: "34"; readonly last4: "4242"; readonly number: "4242 4242 4242 4242"; readonly outcome: "succeeded"; readonly postalCode: "10001"; }, { readonly brand: "mastercard"; readonly cardId: "sandbox_mastercard_success"; readonly cvc: "123"; readonly expMonth: "12"; readonly expYear: "34"; readonly last4: "4444"; readonly number: "5555 5555 5555 4444"; readonly outcome: "succeeded"; readonly postalCode: "10001"; }, { readonly brand: "visa"; readonly cardId: "sandbox_visa_declined"; readonly cvc: "123"; readonly expMonth: "12"; readonly expYear: "34"; readonly last4: "0002"; readonly number: "4000 0000 0000 0002"; readonly outcome: "declined"; readonly postalCode: "10001"; }]; interface SandboxRunMetadataInput { source: string; runId: string; externalOrderId?: string; externalUserId?: string; extra?: Record; } interface SandboxCheckoutCompletedAssertion { checkoutSessionId: string; paymentId: string; externalOrderId: string | null; externalUserId: string | null; currency: string; sandboxIdempotencyKey: string; source: string | null; runId: string | null; } interface BuildTestWebhookInput { eventType?: SandboxWebhookEventType; data?: Record; metadata?: Record; secret: string; deliveryId?: string; timestamp?: number | Date; attempt?: number; } interface BuiltTestWebhook { payload: Record; rawBody: string; headers: Record; } type SandboxScenarioPayloadInput = Omit; declare function buildSandboxRunMetadata(input: SandboxRunMetadataInput): Record; declare function buildSandboxScenarioPayload(input: SandboxScenarioPayloadInput): Record; declare function assertSandboxWebhookMode(payload: WebhookPayloadInput, expectedEventType?: SandboxWebhookEventType | string): ParsedWebhookEvent>; declare function assertSandboxCheckoutCompleted(payload: WebhookPayloadInput): SandboxCheckoutCompletedAssertion; declare function buildTestWebhook(input: BuildTestWebhookInput): Promise; /** * Soledgic SDK Internal Helpers * Response mapping utilities */ declare function mapWebhookEndpoint(endpoint: any): WebhookEndpoint; declare function resolveWebhookEndpointUrl(webhookEndpoints: unknown, endpointUrl: unknown): string | null; declare function mapWebhookDelivery(delivery: any): WebhookDelivery; declare const DEFAULT_API_VERSION = "2026-03-01"; declare const DEFAULT_BASE_URL = "https://api.soledgic.com/v1"; declare const SOLEDGIC_SDK_VERSION = "0.8.0"; declare function normalizeBaseUrl(input?: string): string; declare class Soledgic { private _getKey; private baseUrl; private timeoutMs; private apiVersion; constructor(config: SoledgicConfig); /** Clear the API key from memory. After calling destroy(), all requests will throw. */ destroy(): void; /** * Manage webhook endpoints and verify incoming webhook signatures. * * Soledgic signs every webhook with HMAC-SHA256. Always verify the signature * before processing an event. Use `parseEvent` to get a typed event object. * * @example * // In your webhook handler (e.g. Next.js API route): * const rawBody = await request.text(); * const isValid = client.webhooks.verifySignature( * rawBody, * request.headers.get('x-soledgic-signature')!, * process.env.SOLEDGIC_WEBHOOK_SECRET!, * ); * if (!isValid) return new Response('Unauthorized', { status: 401 }); * * const event = client.webhooks.parseEvent(rawBody); * if (event.type === 'checkout.completed') { ... } */ readonly webhooks: { /** * Verify the HMAC-SHA256 signature on an incoming webhook payload. * Returns `true` if the signature is valid, `false` otherwise. * Always verify before processing — replay attacks are real. */ verifySignature: (payload: WebhookPayloadInput, signatureHeader: string, secret: string, options?: VerifyWebhookSignatureOptions) => Promise; /** * Parse a raw webhook payload into a typed event object. * Call after `verifySignature` confirms the payload is authentic. */ parseEvent: >(payload: WebhookPayloadInput) => ParsedWebhookEvent; /** List all registered webhook endpoints for this API key. */ listEndpoints: () => Promise<{ success: any; data: any; }>; /** * Register a URL to receive webhook events. * Omit `events` to subscribe to all event types. * * @example * await client.webhooks.createEndpoint({ * url: process.env.SOLEDGIC_WEBHOOK_URL!, * events: ['checkout.completed', 'payout.executed', 'refund_request.created'], * }); */ createEndpoint: (config: { url: string; description?: string; events?: string[]; }) => Promise<{ success: any; data: { secret: any; id: string; url: string; description: string | null; events: string[]; isActive: boolean; createdAt: string; secretRotatedAt: string | null; }; message: any; }>; /** Update a webhook endpoint's URL, event subscriptions, or active status. */ updateEndpoint: (endpointId: string, updates: { url?: string; description?: string; events?: string[]; isActive?: boolean; }) => Promise<{ success: any; data: WebhookEndpoint; }>; /** Remove a webhook endpoint. Delivery to this URL stops immediately. */ deleteEndpoint: (endpointId: string) => Promise<{ success: any; message: any; }>; /** Send a synthetic test event to a webhook endpoint to confirm delivery is working. */ testEndpoint: (endpointId: string) => Promise<{ success: any; error: any; data: { delivered: boolean; status: any; responseTimeMs: any; }; }>; /** List recent webhook delivery attempts, including status codes and response bodies. */ listDeliveries: (requestOrEndpointId?: WebhookDeliveriesRequest | string, limit?: number) => Promise; /** Re-send a previously delivered event. Useful for replaying events your handler missed. */ replayDelivery: (deliveryId: string) => Promise; /** Retry a failed delivery attempt. */ retryDelivery: (deliveryId: string) => Promise<{ success: any; message: any; }>; /** * Rotate the HMAC signing secret for a webhook endpoint. * Update your handler's `SOLEDGIC_WEBHOOK_SECRET` env var after rotating. */ rotateSecret: (endpointId: string) => Promise<{ success: any; data: { secret: any; }; message: any; }>; }; /** * Platform health and API status. */ readonly platform: { /** Check that the Soledgic API is reachable and returning healthy responses. */ getStatus: () => Promise; }; /** * Consumer/buyer wallet management. * * `consumer_credit` wallets hold buyer stored balances for wallet-funded checkout. * Use `users.upsertWallet` on signup or first login — it is safe to call multiple times. * * @useCase Consumer Stored Balance Wallet * @intent Provision wallet-funded checkout balances for buyers * * @example * const { wallet } = await client.users.upsertWallet({ * externalUserId: 'user_123', * name: 'Jane Doe', * }); * // wallet.id is the Soledgic wallet ID — store it or derive it from externalUserId */ readonly users: { /** * Create or retrieve a `consumer_credit` wallet for a buyer. * Idempotent on `externalUserId` — safe to call on every signup or login. */ upsertWallet: (req: UpsertUserWalletRequest) => Promise; }; /** * Onboard and manage creators — sellers, instructors, or any participant who earns money. * * Creators are the central concept in Soledgic's revenue model. Each creator has * a participant profile, a `creator_earnings` wallet, and a default revenue split * percent. Call `creators.upsert` when a user becomes a seller on your platform. * * @useCase Marketplace Seller Onboarding * @intent Register a creator with a default revenue split applied to all future checkouts * * @example * // Onboard a creator with an 85% revenue share * await client.creators.upsert({ * externalCreatorId: 'creator_maya', * displayName: 'Maya Chen', * email: process.env.CREATOR_EMAIL, * defaultSplitPercent: 85, * }); * * // Check if they can receive a payout yet * const eligibility = await client.creators.getPayoutEligibility('creator_maya'); */ readonly creators: { /** * Create or update a creator profile. Idempotent on `externalCreatorId` — safe to * call on every login. Sets the default revenue split applied to all future checkouts. * `defaultSplitPercent` is the creator's share (e.g. 90 means creator keeps 90%, platform keeps 10%). */ upsert: (req: UpsertCreatorRequest) => Promise; /** Fetch a creator's profile, KYC status, and current configuration. */ get: (creatorId: string) => Promise<{ success: boolean; participant: ParticipantDetail; }>; /** * Check whether a creator is currently eligible to receive a payout. * Returns eligibility status, reasons for ineligibility (missing KYC, no bank account, etc.), * and available balance. Call this before `payouts.request` to surface clear errors to creators. */ getPayoutEligibility: (creatorId: string) => Promise; /** * Explicitly create a `creator_earnings` wallet for a creator. * This is normally created automatically on the first checkout completion — * call this only if you need the wallet to exist before any sale has occurred. */ createWallet: (req: CreateCreatorWalletRequest) => Promise; }; /** * Create hosted checkout sessions. Alias for `purchases`. * Prefer `purchases.create` for new integrations — same underlying method. */ readonly orders: { /** * Create a hosted checkout session tied to a creator. * On payment completion, the ledger is updated atomically: * creator wallet credited, platform fee collected, webhooks fired. * * @example * const session = await client.orders.createCheckout({ * creatorId: 'creator_maya', * amount: 4900, // $49.00 in cents * productName: 'Design system kit', * successUrl: process.env.CHECKOUT_SUCCESS_URL!, * cancelUrl: process.env.CHECKOUT_CANCEL_URL!, * }); * // Redirect buyer to session.checkoutSession.checkoutUrl */ createCheckout: (req: UniversalCheckoutRequest) => Promise; /** * Create a hosted checkout that funds and spends the authenticated buyer's * wallet atomically. Alias for `purchases.createWalletFundedCheckout`. */ createWalletFundedCheckout: (req: CreateWalletFundedCheckoutRequest) => Promise; }; /** * Create hosted checkout sessions for marketplace purchases. * * This is the primary way to collect payment for a creator's product. * The checkout session links buyer → product → creator. When payment completes, * Soledgic applies the revenue split atomically and fires `checkout.completed`. * * @useCase Marketplace Purchase * @intent Atomic Revenue Split — creator and platform shares applied at payment completion, no reconciliation step * * @example * const session = await client.purchases.create({ * creatorId: 'creator_maya', * amount: 4900, // $49.00 in cents * productName: 'Design system kit', * externalOrderId: 'order_abc123', // your stable order ID (idempotency key) * successUrl: process.env.CHECKOUT_SUCCESS_URL!, * }); * redirect(session.checkoutSession.checkoutUrl); */ readonly purchases: { /** * Create a hosted checkout session. Revenue split between creator and platform * is applied atomically when the buyer completes payment. * Use `externalOrderId` as your idempotency key — safe to retry. */ create: (req: UniversalCheckoutRequest) => Promise; /** * Create a buyer-funded hosted checkout without entering merchant onboarding. * The buyer id and success URL are required; the SDK sets the canonical * `direct_funded_wallet` purchase mode automatically. */ createWalletFundedCheckout: (req: CreateWalletFundedCheckoutRequest) => Promise; }; /** * Membership tiers and subscriber lifecycle for creator communities. * * Memberships use checkout sessions for payment, then activate entitlements only * after the checkout sale is recorded in the ledger. */ readonly memberships: { createTier: (req: CreateMembershipTierRequest) => Promise<{ success: boolean; tier: MembershipTier; }>; listTiers: () => Promise<{ success: boolean; tiers: MembershipTier[]; }>; create: (req: CreateMembershipRequest) => Promise; list: (customerId?: string) => Promise<{ success: boolean; memberships: any[]; }>; get: (membershipId: string) => Promise<{ success: boolean; membership: any; }>; renew: (membershipId: string, req: Omit) => Promise; cancel: (membershipId: string, options?: { cancelAtPeriodEnd?: boolean; reason?: string; }) => Promise<{ success: boolean; membership: any; }>; resume: (membershipId: string) => Promise<{ success: boolean; membership: any; }>; entitlements: (customerId: string, tierKey?: string) => Promise; }; /** * Simulate payment events in test mode without touching real money. * * All sandbox methods require a test API key (`slk_test_...`). * Use `sandbox.completeCheckout` to simulate a successful payment in your * integration tests or local development — it triggers the full ledger update * and webhook delivery exactly as a real payment would. * * @example * const session = await client.purchases.create({ ... }); * await client.sandbox.completeCheckout({ * checkoutSessionId: session.checkoutSession.id, * idempotencyKey: 'test_complete_001', * }); * // creator wallet is now credited, checkout.completed webhook fired */ readonly sandbox: { /** * Simulate a successful buyer payment for a checkout session. * Triggers the full downstream flow: ledger update, wallet credit, split applied, * and `checkout.completed` webhook delivered. Use in integration tests. */ completeCheckout: (req: SandboxCheckoutCompleteRequest) => Promise; /** Simulate a failed payment attempt. Fires `checkout.failed` webhook. */ failCheckout: (req: SandboxCheckoutFailRequest) => Promise; /** Deliver a synthetic test webhook event to a registered endpoint. */ sendTestWebhook: (req: SandboxWebhookTestRequest) => Promise; /** * Run a named sandbox scenario — a multi-step payment flow (e.g. full checkout → payout cycle). * Useful for testing end-to-end flows without writing individual step calls. */ sendScenario: (req: SandboxScenarioRequest) => Promise; /** List recent sandbox events for debugging test runs. */ listEvents: (req?: SandboxEventsRequest) => Promise; /** Remove sandbox test data. Call between test runs to start from a clean state. */ cleanup: (req?: SandboxCleanupRequest) => Promise; }; /** * Query and manage wallet balances for any platform participant. * * Wallets are the core balance primitive in Soledgic. Each participant can have * multiple wallets by type: `creator_earnings` holds payout-eligible creator revenue; * `consumer_credit` holds buyer stored balance. * * @useCase Check Creator Earnings Balance * @intent Read real-time ledger balance before requesting a payout or displaying creator dashboard data * * @example * // Get all creator earnings wallets for a creator * const { wallets } = await client.wallets.list({ * ownerId: 'creator_maya', * walletType: 'creator_earnings', * }); * console.log(wallets[0].balance); // current balance in cents * * // Show a buyer their transaction history * const activity = await client.wallets.listActivity(wallets[0].id, { limit: 20 }); */ readonly wallets: { /** * List wallets with optional filtering by owner, type, or participant. * Use `walletType: 'creator_earnings'` to get creator balance wallets, * or `walletType: 'consumer_credit'` for buyer stored-balance wallets. */ list: (filters?: ListWalletsRequest) => Promise; /** Create a new wallet for a participant. Prefer `creators.createWallet` or `users.upsertWallet` for standard wallet types. */ create: (req: CreateWalletRequest) => Promise; /** Fetch a single wallet by its Soledgic wallet ID, including current balance. */ get: (walletId: string) => Promise; /** * Paginated list of ledger entries (transactions) for a wallet. * Use to build activity feeds, balance history views, or export transaction data. */ listActivity: (walletId: string, options?: { limit?: number; offset?: number; }) => Promise; /** Add funds to a wallet directly (platform-initiated balance adjustment, not a buyer payment). */ topUp: (req: WalletTopupRequest) => Promise; /** Debit funds from a wallet (platform-initiated). */ withdraw: (req: WalletWithdrawRequest) => Promise; /** * Move funds between two participant wallets on the same platform. * Both wallets must belong to your platform's ledger. */ transfer: (req: ParticipantTransferRequest) => Promise; /** * Create a hosted payment page that lets a buyer fund their own wallet. * Useful for pre-loading a buyer wallet before a purchase. */ createHostedSession: (req: CreateWalletSessionRequest) => Promise; /** * Charge a buyer's shared Soledgic balance for a purchase on your platform * (cross-platform / closed-loop wallet). The buyer is identified by their * Soledgic OIDC subject (`consumerSub`) and must have authorized your platform * to spend from their balance (granted at "Sign in with Soledgic"). The split * posts on your ledger; funds are debited from the buyer's shared balance. * * @useCase Spend a buyer's portable Soledgic balance */ sharedSpend: (req: SharedWalletSpendRequest) => Promise; /** * Refund a completed shared-wallet spend (immediate-settled purchase). The * buyer is made whole; the creator's share is clawed back (their balance may * go negative, recovered from future earnings). * * @useCase Refund a buyer paid from their portable Soledgic balance */ reverseSharedSpend: (req: SharedWalletSpendReverseRequest) => Promise; /** * Platform "disconnect": revoke THIS platform's standing authorization to spend * a consumer's shared Soledgic balance. Scoped to the calling platform — it can * only ever revoke access to itself. Idempotent (`revoked:false` if nothing was active). * * @useCase Stop being able to charge a buyer's portable balance when they unlink */ revokeSharedSpendAuthorization: (req: SharedWalletAuthorizationRevokeRequest) => Promise; /** * Place an ESCROW hold against a buyer's shared Soledgic balance for a * delivery/escrow purchase. Funds leave the buyer's balance into escrow; the * creator is paid only when you call `releaseSharedHold`. Refund a still-held * hold with `refundSharedHold`. Use `sharedSpend` for immediate settlement. * * @useCase Escrow a buyer's portable Soledgic balance for an order */ sharedHold: (req: SharedWalletHoldRequest) => Promise; /** Release a previously placed shared-wallet escrow hold to the creator. */ releaseSharedHold: (req: SharedWalletHoldActionRequest) => Promise; /** Refund a still-held shared-wallet escrow hold back to the buyer's balance. */ refundSharedHold: (req: SharedWalletHoldActionRequest) => Promise; }; /** * Create hosted wallet funding sessions (buyer-facing top-up pages). * Alias for `wallets.createHostedSession`. */ readonly walletSessions: { /** Create a hosted payment page for a buyer to fund their own wallet. */ create: (req: CreateWalletSessionRequest) => Promise; }; /** * Request and check eligibility for creator ACH payouts. * * Payouts move funds from a creator's `creator_earnings` wallet to their * linked bank account via ACH. Check eligibility first — it surfaces KYC/KYB * status, missing bank account details, and minimum balance requirements. * * @useCase Creator Payout Disbursement * @intent Disburse earned marketplace revenue to a creator's bank account via ACH * * @example * const eligibility = await client.payouts.getEligibility('creator_maya'); * if (eligibility.eligible) { * await client.payouts.request({ * participantId: 'creator_maya', * amount: eligibility.availableBalanceCents, * referenceId: `payout_${Date.now()}`, * }); * } */ readonly payouts: { /** * Queue an ACH payout from a creator's earnings wallet to their bank account. * Throws if the creator is not KYC/KYB approved or has no linked bank account. * Use `referenceId` as your idempotency key — safe to retry with the same value. * * @example * await client.payouts.request({ * participantId: 'creator_maya', * amount: 4750, // $47.50 in cents * referenceId: 'payout_2026_05_01', * }); */ request: (req: CreatePayoutRequest) => Promise; /** * Check whether a creator can receive a payout right now. * Returns eligibility status and reasons for any ineligibility * (e.g. KYC pending, no bank account, balance below minimum). */ getEligibility: (creatorId: string) => Promise; }; /** * KYC/KYB verification for your platform and for individual creators. * * Your platform must complete KYB (business verification) before live-mode payouts * are enabled. Each creator must complete KYC before they can receive payouts. * Check status with `kyc.getBusiness` / `kyc.getCreator` before gating features. */ readonly kyc: { /** Fetch your platform's current KYB (business verification) status and required fields. */ getBusiness: () => Promise; /** * Submit or update your platform's KYB information. * Required before live-mode payouts are enabled on your account. */ submitBusiness: (req: SubmitBusinessKybRequest) => Promise; /** Fetch a creator's KYC verification status. */ getCreator: (participantId: string) => Promise; /** * Submit KYC information for a creator. * Required before the creator can receive payouts. Gate your payout UI * on `kyc.getCreator` status rather than asking again on every visit. */ submitCreator: (req: SubmitCreatorKycRequest) => Promise; /** * Create a short-lived hosted verification capability for a creator. * Send the returned URL to the creator; never expose your API key or log * the one-time client secret embedded in the URL fragment. */ createCreatorVerificationSession: (req: CreateCreatorVerificationSessionRequest) => Promise; }; /** * Issue refunds on completed sales. * * Refunds reverse a transaction and roll back the corresponding ledger entries. * Use `refundFrom` to control whether the platform, the creator, or both absorb * the refund amount. For buyer-initiated refund flows with an approval step, * use `refundRequests` instead. */ readonly refunds: { /** * Issue a refund on a completed sale transaction. * `refundFrom: 'both'` splits the refund proportionally between platform and creator. * `refundFrom: 'platform_only'` absorbs the full refund from the platform fee. * `refundFrom: 'creator_only'` debits the creator's wallet entirely. * * @example * await client.refunds.request({ * saleReference: 'order_abc123', * reason: 'Product not as described', * refundFrom: 'both', * }); */ request: (req: CreateRefundRequest) => Promise; /** List refunds with optional filtering by date, status, or participant. */ list: (req?: ListRefundsRequest) => Promise; }; /** * Manage buyer-initiated refund requests with a review/approval workflow. * * Unlike `refunds.request` (which issues a refund immediately), refund requests * create a pending item your team reviews before issuing. Use this pattern when * you want human review, dispute windows, or platform policy enforcement. * * @example * // Buyer submits a refund request from your UI * const { refundRequest } = await client.refundRequests.create({ * saleReference: 'order_abc123', * customerId: 'user_456', * reason: 'Item not received', * idempotencyKey: 'rr_order_abc123', * }); * * // Your support team approves it * await client.refundRequests.approve({ refundRequestId: refundRequest.id }); */ readonly refundRequests: { /** * Create a pending refund request on behalf of a buyer. * Fires `refund_request.created` webhook. Does not issue the refund immediately. */ create: (req: CreateRefundRequestParams) => Promise; /** List refund requests with optional status or date filtering. */ list: (req?: ListRefundRequestsParams) => Promise; /** Approve a refund request and issue the refund. Fires `refund_request.completed` webhook. */ approve: (req: ReviewRefundRequestParams) => Promise; /** Reject a refund request. Fires `refund_request.rejected` webhook. */ reject: (req: ReviewRefundRequestParams) => Promise; /** Cancel a refund request before it is reviewed. Fires `refund_request.cancelled` webhook. */ cancel: (req: ReviewRefundRequestParams) => Promise; }; /** * Manage escrow-style fund holds. * * Holds lock funds in a wallet pending a condition — delivery confirmation, * dispute window expiry, or manual release. This is the primitive for * escrow-style marketplace flows: funds are committed but not yet payable. * * @example * // Release a hold after delivery is confirmed * await client.holds.release({ * holdId: 'hold_xyz', * referenceId: 'delivery_confirmed_order_abc', * }); */ readonly holds: { /** List active holds on the platform, optionally filtered by wallet or participant. */ list: (options?: HoldQueryOptions) => Promise; /** * Release a hold, making the held funds available. This never sends money * to a bank; create a payout separately after the release. */ release: (req: ReleaseHoldRequest) => Promise; }; /** * Reverse completed transactions to correct ledger errors. * * Reversals undo a transaction and roll back all associated ledger entries. * Use for error correction (e.g. duplicate charge, wrong amount) — not for * normal refunds. For buyer refunds, use `refunds.request` or `refundRequests`. */ readonly reversals: { /** * Reverse a transaction and roll back its ledger entries atomically. * This is a hard correction — prefer `refunds` for buyer-facing refund flows. */ create: (req: ReverseTransactionRequest) => Promise; }; /** * Generate and retrieve immutable payment receipts. * * Receipts are Soledgic-hosted, buyer-facing documents for completed payments. * Generate one after `checkout.completed` and share the URL with the buyer. * * @example * // In your checkout.completed webhook handler: * const { receipt } = await client.receipts.generate({ * checkoutId: event.data.checkoutSessionId, * externalOrderId: event.data.externalOrderId, * }); * // Send receipt.url to the buyer's email */ readonly receipts: { /** * Generate a Soledgic-hosted receipt for a completed checkout. * Returns a URL suitable for sharing with the buyer or embedding in confirmation emails. */ generate: (req: GenerateReceiptRequest) => Promise; /** Fetch a previously generated receipt by its Soledgic receipt ID. */ get: (receiptId: string) => Promise; /** Upload an external receipt document and associate it with a transaction. */ upload: (req: UploadReceiptRequest) => Promise; }; /** * Query transaction history across wallets. * * Use `activity.listWallet` to power creator earnings dashboards, buyer * transaction history screens, or data exports for reconciliation. * * @example * // Show a creator their last 50 earnings entries * const { entries } = await client.activity.listWallet(walletId, { limit: 50 }); */ readonly activity: { /** * Paginated list of ledger entries for a specific wallet. * Each entry includes amount, direction (credit/debit), type, and timestamp. * Use to build activity feeds, export transaction history, or power balance charts. */ listWallet: (walletId: string, options?: { limit?: number; offset?: number; }) => Promise; /** List refund transactions with optional date or status filtering. */ listRefunds: (req?: ListRefundsRequest) => Promise; }; private throwTypedError; private requestHeaders; private request; private requestGet; private requestRaw; private createUniversalCheckout; private createWalletFundedHostedCheckout; private requestGetRaw; private requestDelete; recordIncome(req: RecordIncomeRequest): Promise; recordExpense(req: RecordExpenseRequest): Promise; recordBill(req: RecordBillRequest): Promise; registerInstrument(req: RegisterInstrumentRequest): Promise; projectIntent(req: ProjectIntentRequest): Promise; reverseTransaction(req: ReverseTransactionRequest): Promise; listPeriods(): Promise<{ success: boolean; periods: Period[]; }>; createPeriod(req: CreatePeriodRequest): Promise<{ success: boolean; period: Period; }>; closePeriod(year: number, month?: number, quarter?: number): Promise; matchTransaction(req: ReconcileMatchRequest): Promise; unmatchTransaction(transactionId: string): Promise; listUnmatchedTransactions(): Promise; createReconciliationSnapshot(req: CreateSnapshotRequest): Promise<{ success: boolean; snapshot_id: string; integrity_hash: string; }>; getReconciliationSnapshot(periodId: string): Promise<{ success: boolean; snapshot: ReconciliationSnapshot; }>; autoMatchBankTransaction(bankAggregatorTransactionId: string): Promise; generateFrozenStatements(periodId: string): Promise<{ success: boolean; message?: string; period_id?: string; statements?: { trial_balance: { hash: string; balanced: boolean; }; profit_loss: { hash: string; net_income: number; }; balance_sheet: { hash: string; balanced: boolean; }; }; }>; getFrozenStatement(periodId: string, statementType: 'profit_loss' | 'balance_sheet' | 'trial_balance'): Promise<{ success: boolean; statement: FrozenStatement; }>; listFrozenStatements(periodId?: string): Promise; verifyFrozenStatements(periodId: string): Promise<{ success: boolean; all_valid: boolean; verification_results: any[]; }>; listTiers(): Promise<{ success: boolean; data: Array>; }>; getEffectiveSplit(creatorId: string): Promise<{ success: boolean; data: { creator_id: string; creator_percent: number; platform_percent: number; source: string; }; }>; setCreatorSplit(creatorId: string, splitPercent: number): Promise<{ success: boolean; data?: { creator_id: string; creator_percent: number; platform_percent: number; }; }>; clearCreatorSplit(creatorId: string): Promise<{ success: boolean; }>; autoPromoteCreators(): Promise; getSummary(): Promise<{ success: any; data: any; }>; getProfitLoss(startDate: string, endDate: string): Promise; getTrialBalance(asOf?: string): Promise; get1099Summary(year: number): Promise; getCreatorEarnings(startDate: string, endDate: string): Promise; getHistoricalEarnings(options?: { startDate?: string; endDate?: string; creatorId?: string; granularity?: 'monthly' | 'quarterly' | 'daily' | 'total'; }): Promise; getTransactions(startDate?: string, endDate?: string, creatorId?: string): Promise; generatePDF(reportType: 'creator_statement' | 'profit_loss' | 'trial_balance' | '1099', options?: { creatorId?: string; startDate?: string; endDate?: string; taxYear?: number; periodId?: string; }): Promise<{ success: boolean; filename: string; data: string; frozen?: boolean; }>; getCreatorStatement(creatorId: string, startDate: string, endDate: string): Promise<{ success: boolean; filename: string; data: string; frozen?: boolean; }>; getProfitLossPDF(startDate: string, endDate: string, periodId?: string): Promise<{ success: boolean; filename: string; data: string; frozen?: boolean; }>; getTrialBalancePDF(): Promise<{ success: boolean; filename: string; data: string; frozen?: boolean; }>; get1099PDF(taxYear: number): Promise<{ success: boolean; filename: string; data: string; frozen?: boolean; }>; configureEmail(config: { enabled: boolean; sendDay?: number; fromName?: string; fromEmail?: string; subjectTemplate?: string; bodyTemplate?: string; ccAdmin?: boolean; adminEmail?: string; }): Promise; sendMonthlyStatements(year?: number, month?: number): Promise; sendCreatorStatement(creatorId: string, year?: number, month?: number): Promise; previewStatementEmail(creatorId: string, year?: number, month?: number): Promise; getEmailHistory(): Promise; listWebhookEndpoints(): Promise<{ success: any; data: any; }>; createWebhookEndpoint(config: { url: string; description?: string; events?: string[]; }): Promise<{ success: any; data: { secret: any; id: string; url: string; description: string | null; events: string[]; isActive: boolean; createdAt: string; secretRotatedAt: string | null; }; message: any; }>; updateWebhookEndpoint(endpointId: string, updates: { url?: string; description?: string; events?: string[]; isActive?: boolean; }): Promise<{ success: any; data: WebhookEndpoint; }>; deleteWebhookEndpoint(endpointId: string): Promise<{ success: any; message: any; }>; testWebhookEndpoint(endpointId: string): Promise<{ success: any; error: any; data: { delivered: boolean; status: any; responseTimeMs: any; }; }>; getWebhookDeliveries(requestOrEndpointId?: WebhookDeliveriesRequest | string, limit?: number): Promise; retryWebhookDelivery(deliveryId: string): Promise<{ success: any; message: any; }>; replayWebhookDelivery(deliveryId: string): Promise; rotateWebhookSecret(endpointId: string): Promise<{ success: any; data: { secret: any; }; message: any; }>; listAlerts(): Promise<{ success: boolean; data: AlertConfiguration[]; }>; createAlert(req: CreateAlertRequest): Promise<{ success: boolean; data: AlertConfiguration; }>; updateAlert(req: UpdateAlertRequest): Promise<{ success: boolean; data: AlertConfiguration; }>; deleteAlert(configId: string): Promise<{ success: boolean; message: string; }>; testAlert(configId: string): Promise; preflightAuthorization(req: PreflightAuthorizationRequest): Promise; preflightAndRecordExpense(preflight: PreflightAuthorizationRequest, expense: Omit): Promise<{ preflight: PreflightAuthorizationResponse; transaction?: any; }>; preflightAndRecordBill(preflight: PreflightAuthorizationRequest, bill: Omit): Promise<{ preflight: PreflightAuthorizationResponse; transaction?: any; }>; getImportTemplates(): Promise<{ success: boolean; data: { builtin: Array>; custom: Array>; accounts: Array>; }; }>; parseImportFile(fileBase64: string, format?: 'csv' | 'ofx' | 'qfx' | 'auto'): Promise; importTransactions(transactions: Array<{ date: string; description: string; amount: number; reference?: string; }>): Promise<{ success: boolean; data: { session_id?: string; imported: number; skipped: number; matched?: number; unmatched?: number; errors?: string[]; balance?: { opening: number; closing_expected: number; closing_computed: number; discrepancy: number; verified: boolean; } | null; }; }>; saveImportTemplate(template: { name: string; bank_name: string; format: string; mapping: Record; skip_rows?: number; delimiter?: string; }): Promise; getEscrowSummary(): Promise<{ success: any; summary: any; }>; getHeldFunds(options?: { ventureId?: string; creatorId?: string; readyOnly?: boolean; limit?: number; }): Promise; releaseFunds(entryId: string, _executeTransfer?: boolean): Promise<{ success: any; release_id: any; entry_id: any; status: any; availability_released: boolean; executed: boolean; transfer_id: any; transfer_status: any; amount: any; currency: any; }>; checkPayoutEligibility(participantId: string): Promise<{ success: any; participant_id: any; eligible: boolean; available_balance_cents: any; issues: any; requirements: any; }>; runHealthCheck(): Promise; getHealthStatus(): Promise; getHealthHistory(): Promise; getAPAging(asOfDate?: string): Promise; getARAging(asOfDate?: string): Promise; getBalanceSheet(asOfDate?: string): Promise; getDetailedTrialBalance(options?: { asOf?: string; snapshot?: boolean; }): Promise; getDetailedProfitLoss(options?: { year?: number; month?: number; quarter?: number; startDate?: string; endDate?: string; breakdown?: 'monthly'; }): Promise; getRunway(): Promise; createParticipant(req: CreateParticipantRequest): Promise; listParticipants(): Promise<{ success: boolean; participants: ParticipantSummary[]; }>; getParticipant(participantId: string): Promise<{ success: boolean; participant: ParticipantDetail; }>; getParticipantPayoutEligibility(participantId: string): Promise; /** * @deprecated Public ledger creation is retired. Use authenticated dashboard * onboarding or Soledgic support-assisted organization provisioning. */ createLedger(req: CreateLedgerRequest): Promise; recordAdjustment(req: RecordAdjustmentRequest): Promise; recordOpeningBalance(req: RecordOpeningBalanceRequest): Promise; recordTransfer(req: RecordTransferRequest): Promise; evaluateFraud(req: RiskEvaluationRequest): Promise; createFraudPolicy(req: CreatePolicyRequest): Promise; listFraudPolicies(): Promise; deleteFraudPolicy(policyId: string): Promise; calculateTaxForParticipant(participantId: string, taxYear?: number): Promise; generateAllTaxDocuments(taxYear?: number): Promise; listTaxDocuments(taxYear?: number): Promise; getTaxDocument(documentId: string): Promise; exportTaxDocuments(taxYear?: number, format?: 'json'): Promise<{ success: boolean; tax_year?: number; documents?: Array>; }>; exportTaxDocuments(taxYear: number | undefined, format: 'csv'): Promise<{ csv: string; filename: string; }>; markTaxDocumentFiled(documentId: string): Promise; generateTaxSummary(taxYear: number, creatorId?: string): Promise; markTaxDocumentsFiledBulk(taxYear: number): Promise; correctTaxDocument(documentId: string, params: { reason: string; grossAmount?: number; federalWithholding?: number; stateWithholding?: number; }): Promise; deliverTaxDocumentCopyB(taxYear: number): Promise; generateTaxDocumentPdf(documentId: string, copyType?: string): Promise; generateTaxDocumentPdfBatch(taxYear: number, copyType?: string): Promise; getComplianceOverview(options?: { days?: number; hours?: number; }): Promise; listComplianceAccessPatterns(options?: { hours?: number; limit?: number; }): Promise; listComplianceFinancialActivity(options?: { days?: number; }): Promise; listComplianceSecuritySummary(options?: { days?: number; }): Promise; exportReport(req: ExportReportRequest & { format: 'json'; }): Promise; exportReport(req: ExportReportRequest & { format: 'csv'; }): Promise; exportReport(req: ExportReportRequest): Promise; private mapReceiptResource; generateReceipt(req: GenerateReceiptRequest): Promise; getReceipt(receiptId: string): Promise; uploadReceipt(req: UploadReceiptRequest): Promise; receivePayment(req: ReceivePaymentRequest): Promise; private mapWalletObject; listWallets(filters?: ListWalletsRequest): Promise; createWallet(req: CreateWalletRequest): Promise; getWallet(walletId: string): Promise; getWalletEntries(walletId: string, options?: { limit?: number; offset?: number; }): Promise; topUpWallet(req: WalletTopupRequest): Promise; spendSharedWallet(req: SharedWalletSpendRequest): Promise; reverseSharedWalletSpend(req: SharedWalletSpendReverseRequest): Promise; revokeSharedSpendAuthorization(req: SharedWalletAuthorizationRevokeRequest): Promise; holdSharedWallet(req: SharedWalletHoldRequest): Promise; releaseSharedWalletHold(req: SharedWalletHoldActionRequest): Promise; refundSharedWalletHold(req: SharedWalletHoldActionRequest): Promise; withdrawFromWallet(req: WalletWithdrawRequest): Promise; createTransfer(req: ParticipantTransferRequest): Promise; listHolds(options?: HoldQueryOptions): Promise; getHoldSummary(): Promise; releaseHold(req: ReleaseHoldRequest): Promise; createCheckoutSession(req: CreateCheckoutSessionRequest): Promise; createMembershipTier(req: CreateMembershipTierRequest): Promise<{ success: boolean; tier: MembershipTier; }>; listMembershipTiers(): Promise<{ success: boolean; tiers: MembershipTier[]; }>; createMembership(req: CreateMembershipRequest): Promise; listMemberships(customerId?: string): Promise<{ success: boolean; memberships: any[]; }>; getMembership(membershipId: string): Promise<{ success: boolean; membership: any; }>; renewMembership(membershipId: string, req: Omit): Promise; cancelMembership(membershipId: string, options?: { cancelAtPeriodEnd?: boolean; reason?: string; }): Promise<{ success: boolean; membership: any; }>; resumeMembership(membershipId: string): Promise<{ success: boolean; membership: any; }>; getMembershipEntitlements(customerId: string, tierKey?: string): Promise; private mapMembershipTier; private mapMembershipResponse; createWalletSession(req: CreateWalletSessionRequest): Promise; private mapSandboxCheckoutActionResponse; completeSandboxCheckout(req: SandboxCheckoutCompleteRequest): Promise; failSandboxCheckout(req: SandboxCheckoutFailRequest): Promise; sendSandboxWebhookTest(req: SandboxWebhookTestRequest): Promise; sendSandboxScenario(req: SandboxScenarioRequest): Promise; listSandboxEvents(req?: SandboxEventsRequest): Promise; cleanupSandbox(req?: SandboxCleanupRequest): Promise; createPayout(req: CreatePayoutRequest): Promise; private mapRefundRequestResource; private mapRefundRequestResponse; createRefund(req: CreateRefundRequest): Promise; listRefunds(req?: ListRefundsRequest): Promise; createRefundRequest(req: CreateRefundRequestParams): Promise; listRefundRequests(req?: ListRefundRequestsParams): Promise; approveRefundRequest(req: ReviewRefundRequestParams): Promise; rejectRefundRequest(req: ReviewRefundRequestParams): Promise; cancelRefundRequest(req: ReviewRefundRequestParams): Promise; createInvoice(req: CreateInvoiceRequest): Promise; listInvoices(options?: { status?: string; customerId?: string; limit?: number; offset?: number; }): Promise; getInvoice(invoiceId: string): Promise; sendInvoice(invoiceId: string): Promise; recordInvoicePayment(invoiceId: string, req: RecordInvoicePaymentRequest): Promise; voidInvoice(invoiceId: string, reason?: string): Promise; payBill(req: PayBillRequest): Promise; createBudget(req: CreateBudgetRequest): Promise; listBudgets(): Promise; createRecurring(req: CreateRecurringRequest): Promise; listRecurring(): Promise; getDueRecurring(days?: number): Promise; createContractor(req: CreateContractorRequest): Promise; listContractors(): Promise; recordContractorPayment(req: RecordContractorPaymentRequest): Promise; createBankAccount(req: CreateBankAccountRequest): Promise; listBankAccounts(): Promise; listLedgers(): Promise; deleteCreator(creatorId: string): Promise; submitTaxInfo(req: SubmitTaxInfoRequest): Promise; getBusinessKyb(): Promise; submitBusinessKyb(req: SubmitBusinessKybRequest): Promise; getCreatorKyc(participantId: string): Promise; submitCreatorKyc(req: SubmitCreatorKycRequest): Promise; createCreatorVerificationSession(req: CreateCreatorVerificationSessionRequest): Promise; importBankStatement(req: ImportBankStatementRequest): Promise; } export { type AlertChannel, type AlertConfiguration, type AlertTestResult, type AlertThresholds, type AlertType, AuthenticationError, type AuthorizationDecisionType, type AuthorizationPolicy, type AuthorizationResult, type AutoMatchReconciliationResponse, type BackdatePolicyRequest, type BreachRisk, type BuildTestWebhookInput, type BuiltTestWebhook, type BusinessKybBeneficialOwner, type BusinessKybPrimaryContact, type BusinessKybResponse, type CheckoutBreakdown, type CheckoutSessionResourceResponse, type ComplianceAccessPatternsResponse, type ComplianceFinancialActivityResponse, type ComplianceOverviewResponse, type ComplianceSecuritySummaryResponse, ConflictError, type CreateAlertRequest, type CreateBankAccountRequest, type CreateBudgetRequest, type CreateCheckoutSessionRequest, type CreateContractorRequest, type CreateCreatorVerificationSessionRequest, type CreateCreatorVerificationSessionResponse, type CreateCreatorWalletRequest, type CreateInvoiceRequest, type CreateLedgerRequest, type CreateLedgerResponse, type CreateMembershipRequest, type CreateMembershipTierRequest, type CreateParticipantRequest, type CreateParticipantResponse, type CreatePayoutRequest, type CreatePeriodRequest, type CreatePolicyRequest, type CreateRecurringRequest, type CreateRefundRequest, type CreateRefundRequestParams, type CreateSnapshotRequest, type CreateWalletFundedCheckoutRequest, type CreateWalletRequest, type CreateWalletResponse, type CreateWalletSessionRequest, type CreateWalletSessionResponse, type CreatorKycBusinessType, type CreatorKycResponse, type CreatorVerificationSessionStatus, DEFAULT_API_VERSION, DEFAULT_BASE_URL, type EmailAlertConfig, type ExportReportCsvResponse, type ExportReportJsonResponse, type ExportReportRequest, type ExtractedTerms, type FraudPolicyDeleteResponse, type FraudPolicyListResponse, type FraudPolicyResource, type FraudPolicyResponse, type FrozenStatement, type GenerateReceiptRequest, type GenerateReceiptResponse, type GetReceiptResponse, type GetWalletResponse, type HeldFund, type HeldFundsResponse, type HeldFundsSummaryResponse, type HoldQueryOptions, type ImportBankStatementLine, type ImportBankStatementRequest, type InvoiceLineItem, type KycAddress, type KycBusinessType, type KycDocumentEvidence, type KycDocumentType, type KycStatus, type KycSubmissionSummary, type KycTaxIdType, type ListRefundRequestsParams, type ListRefundRequestsResponse, type ListRefundsRequest, type ListRefundsResponse, type ListWalletsRequest, type ListWalletsResponse, type Membership, type MembershipBillingInterval, type MembershipEntitlementsResponse, type MembershipResponse, type MembershipTier, NotFoundError, type ObligationItem, type Obligations, type ParsedWebhookEvent, type ParticipantDetail, type ParticipantPayoutEligibilityResponse, type ParticipantPayoutPreferences, type ParticipantSummary, type ParticipantTransferRequest, type ParticipantTransferResponse, type ParticipantWalletMutationRequest, type PayBillRequest, type PayoutResourceResponse, type Period, type PolicySeverity, type PolicyType, type PolicyViolation, type PreflightAuthorizationRequest, type PreflightAuthorizationResponse, type PreflightResult, type ProjectIntentRequest, type ProjectIntentResponse, type ProjectionMatch, type ReceiptResource, type ReceivePaymentRequest, type ReceivePaymentResponse, type ReconcileMatchRequest, type ReconciliationMatchResponse, type ReconciliationSnapshot, type ReconciliationUnmatchResponse, type RecordAdjustmentRequest, type RecordBillRequest, type RecordContractorPaymentRequest, type RecordExpenseRequest, type RecordIncomeRequest, type RecordInvoicePaymentRequest, type RecordOpeningBalanceRequest, type RecordRefundResponse, type RecordTransferRequest, type RefundFrom, type RefundRequestResource, type RefundRequestResourceResponse, type RefundRequestStatus, type RefundResourceResponse, type RefundSummary, type RegisterInstrumentRequest, type RegisterInstrumentResponse, type ReleaseHoldRequest, type ReleaseHoldResponse, type ReverseResponse, type ReverseTransactionRequest, type ReviewRefundRequestParams, type RiskEvaluationRequest, type RiskEvaluationResponse, SOLEDGIC_SANDBOX_TEST_CARDS, SOLEDGIC_SANDBOX_WEBHOOK_EVENTS, SOLEDGIC_SDK_VERSION, type SandboxCheckoutActionResponse, type SandboxCheckoutCompleteRequest, type SandboxCheckoutCompletedAssertion, type SandboxCheckoutFailRequest, type SandboxCleanupRequest, type SandboxCleanupResponse, type SandboxEventsRequest, type SandboxEventsResponse, type SandboxRunMetadataInput, type SandboxScenarioPayloadInput, type SandboxScenarioRequest, type SandboxScenarioType, type SandboxWebhookEventType, type SandboxWebhookTestRequest, type SandboxWebhookTestResponse, type SharedWalletAuthorizationRevokeRequest, type SharedWalletAuthorizationRevokeResponse, type SharedWalletHoldActionRequest, type SharedWalletHoldRequest, type SharedWalletHoldResponse, type SharedWalletRefundResponse, type SharedWalletReleaseResponse, type SharedWalletSpendRequest, type SharedWalletSpendResponse, type SharedWalletSpendReverseRequest, type SharedWalletSpendReverseResponse, type SlackAlertConfig, Soledgic, type SoledgicConfig, SoledgicError, type SubmitBusinessKybRequest, type SubmitCreatorKycRequest, type SubmitTaxInfoRequest, type TaxCalculationResponse, type TaxDocumentGenerationResponse, type TaxDocumentResponse, type TaxDocumentsResponse, type TaxSummaryResponse, type UniversalCheckoutRequest, type UnmatchedTransactionsResponse, type UpdateAlertRequest, type UploadReceiptRequest, type UploadReceiptResponse, type UpsertCreatorRequest, type UpsertUserWalletRequest, ValidationError, type VerifyWebhookSignatureOptions, type WalletEntriesResponse, type WalletHistoryEntry, type WalletObject, type WalletSessionObject, type WalletSessionOwnerType, type WalletSessionPermission, type WalletTopupRequest, type WalletTopupResponse, type WalletWithdrawRequest, type WalletWithdrawalResponse, type WebhookDeliveriesRequest, type WebhookDeliveriesResponse, type WebhookDelivery, type WebhookEndpoint, type WebhookEndpointSecretResult, type WebhookPayloadInput, type WebhookReplayResponse, assertSandboxCheckoutCompleted, assertSandboxWebhookMode, buildSandboxRunMetadata, buildSandboxScenarioPayload, buildTestWebhook, Soledgic as default, hmacHex, isArrayBufferView, mapWebhookDelivery, mapWebhookEndpoint, normalizeBaseUrl, parseWebhookEvent, parseWebhookSignatureHeader, resolveWebhookEndpointUrl, timingSafeEqual, verifyWebhookSignature, webhookPayloadToString };