@settlr/sdk 0.4.4 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -875,4 +875,382 @@ declare function createWebhookHandler(options: {
875
875
  onError?: (error: Error) => void;
876
876
  }): (req: any, res: any) => Promise<void>;
877
877
 
878
- export { BuyButton, type BuyButtonProps, CheckoutWidget, type CheckoutWidgetProps, type CreatePaymentOptions, type CreateSubscriptionOptions, type MerchantConfig, type Payment, PaymentModal, type PaymentModalProps, type PaymentResult, type PaymentStatus, SETTLR_CHECKOUT_URL, SUPPORTED_NETWORKS, SUPPORTED_TOKENS, Settlr, type SettlrConfig, SettlrProvider, type Subscription, type SubscriptionInterval, type SubscriptionPlan, type SubscriptionStatus, type SupportedToken, type TransactionOptions, USDC_MINT_DEVNET, USDC_MINT_MAINNET, USDT_MINT_DEVNET, USDT_MINT_MAINNET, type WebhookEventType, type WebhookHandler, type WebhookHandlers, type WebhookPayload, createWebhookHandler, formatUSDC, getTokenDecimals, getTokenMint, parseUSDC, parseWebhookPayload, shortenAddress, usePaymentLink, usePaymentModal, useSettlr, verifyWebhookSignature };
878
+ /**
879
+ * Inco Lightning Privacy Module
880
+ *
881
+ * Helpers for issuing private receipts with FHE-encrypted payment amounts.
882
+ * Only authorized parties (merchant + customer) can decrypt via Inco covalidators.
883
+ */
884
+
885
+ /**
886
+ * Inco Lightning Program ID (devnet)
887
+ */
888
+ declare const INCO_LIGHTNING_PROGRAM_ID: PublicKey;
889
+ /**
890
+ * Settlr Program ID
891
+ */
892
+ declare const SETTLR_PROGRAM_ID: PublicKey;
893
+ /**
894
+ * Derive the allowance PDA for a given handle and allowed address
895
+ * This PDA stores the decryption permission for a specific address
896
+ *
897
+ * @param handle - The u128 handle to the encrypted value (as bigint)
898
+ * @param allowedAddress - The address being granted decryption access
899
+ * @returns The allowance PDA and bump
900
+ */
901
+ declare function findAllowancePda(handle: bigint, allowedAddress: PublicKey): [PublicKey, number];
902
+ /**
903
+ * Derive the private receipt PDA for a given payment ID
904
+ *
905
+ * @param paymentId - The payment ID string
906
+ * @returns The private receipt PDA and bump
907
+ */
908
+ declare function findPrivateReceiptPda(paymentId: string): [PublicKey, number];
909
+ /**
910
+ * Encrypt an amount for Inco Lightning
911
+ *
912
+ * In production, this would use the Inco encryption API to create
913
+ * a proper FHE ciphertext. For now, this is a placeholder that
914
+ * would be replaced with the actual Inco client library.
915
+ *
916
+ * @param amount - The amount in USDC lamports (6 decimals)
917
+ * @returns Encrypted ciphertext as Uint8Array
918
+ */
919
+ declare function encryptAmount(amount: bigint): Promise<Uint8Array>;
920
+ /**
921
+ * Configuration for issuing a private receipt
922
+ */
923
+ interface PrivateReceiptConfig {
924
+ /** Payment ID (must be unique) */
925
+ paymentId: string;
926
+ /** Amount in USDC (will be converted to lamports) */
927
+ amount: number;
928
+ /** Customer wallet address (payer and signer) */
929
+ customer: PublicKey;
930
+ /** Merchant wallet address (receives decryption access) */
931
+ merchant: PublicKey;
932
+ /** Pre-computed encrypted amount ciphertext (optional, will encrypt if not provided) */
933
+ encryptedAmount?: Uint8Array;
934
+ }
935
+ /**
936
+ * Build accounts needed for issuing a private receipt
937
+ *
938
+ * Note: This returns the accounts structure but the actual transaction
939
+ * must be built using the Anchor program client with `remainingAccounts`
940
+ * for the allowance PDAs.
941
+ *
942
+ * @param config - Private receipt configuration
943
+ * @returns Object with all required account addresses
944
+ */
945
+ declare function buildPrivateReceiptAccounts(config: PrivateReceiptConfig): Promise<{
946
+ customer: PublicKey;
947
+ merchant: PublicKey;
948
+ privateReceipt: PublicKey;
949
+ incoLightningProgram: PublicKey;
950
+ systemProgram: PublicKey;
951
+ bump: number;
952
+ }>;
953
+ /**
954
+ * Simulate a transaction to get the resulting encrypted handle
955
+ *
956
+ * This is needed because we need the handle to derive allowance PDAs,
957
+ * but the handle is only known after the encryption CPI call.
958
+ *
959
+ * Pattern:
960
+ * 1. Build tx without allowance accounts
961
+ * 2. Simulate to get the handle from account state
962
+ * 3. Derive allowance PDAs from handle
963
+ * 4. Execute real tx with allowance accounts in remainingAccounts
964
+ *
965
+ * @param connection - Solana connection
966
+ * @param transaction - Built transaction without allowance accounts
967
+ * @param privateReceiptPda - The PDA where encrypted handle will be stored
968
+ * @returns The encrypted handle as bigint, or null if simulation failed
969
+ */
970
+ declare function simulateAndGetHandle(connection: any, // Connection type
971
+ transaction: any, // Transaction type
972
+ privateReceiptPda: PublicKey): Promise<bigint | null>;
973
+ /**
974
+ * Build remaining accounts array for allowance PDAs
975
+ *
976
+ * These must be passed to the instruction after deriving from the handle.
977
+ * Since we don't know the handle until after simulation, this is called
978
+ * after simulateAndGetHandle.
979
+ *
980
+ * @param handle - The encrypted handle from simulation
981
+ * @param customer - Customer address (granted access)
982
+ * @param merchant - Merchant address (granted access)
983
+ * @returns Array of remaining accounts for the instruction
984
+ */
985
+ declare function buildAllowanceRemainingAccounts(handle: bigint, customer: PublicKey, merchant: PublicKey): Array<{
986
+ pubkey: PublicKey;
987
+ isSigner: boolean;
988
+ isWritable: boolean;
989
+ }>;
990
+ /**
991
+ * Full flow example for issuing a private receipt
992
+ *
993
+ * @example
994
+ * ```typescript
995
+ * import { issuePrivateReceiptFlow } from '@settlr/sdk/privacy';
996
+ *
997
+ * const result = await issuePrivateReceiptFlow({
998
+ * connection,
999
+ * program, // Anchor program instance
1000
+ * paymentId: 'payment_123',
1001
+ * amount: 99.99,
1002
+ * customer: customerWallet.publicKey,
1003
+ * merchant: merchantPubkey,
1004
+ * signTransaction: customerWallet.signTransaction,
1005
+ * });
1006
+ *
1007
+ * console.log('Private receipt:', result.signature);
1008
+ * console.log('Handle:', result.handle.toString());
1009
+ * ```
1010
+ */
1011
+ interface IssuePrivateReceiptResult {
1012
+ /** Transaction signature */
1013
+ signature: string;
1014
+ /** Encrypted amount handle (u128 as bigint) */
1015
+ handle: bigint;
1016
+ /** Private receipt PDA address */
1017
+ privateReceiptPda: PublicKey;
1018
+ }
1019
+ /**
1020
+ * Privacy-preserving receipt features
1021
+ *
1022
+ * Key benefits:
1023
+ * - Payment amounts hidden on-chain (only u128 handle visible)
1024
+ * - Merchant can still decrypt for accounting/tax compliance
1025
+ * - Customer can verify their payment privately
1026
+ * - Competitors can't see your revenue on-chain
1027
+ */
1028
+ declare const PrivacyFeatures: {
1029
+ /** Amount is FHE-encrypted, only handle stored on-chain */
1030
+ readonly ENCRYPTED_AMOUNTS: true;
1031
+ /** Selective disclosure - only merchant + customer can decrypt */
1032
+ readonly ACCESS_CONTROL: true;
1033
+ /** CSV export still works (decrypts server-side for authorized merchant) */
1034
+ readonly ACCOUNTING_COMPATIBLE: true;
1035
+ /** Inco covalidators ensure trustless decryption */
1036
+ readonly TRUSTLESS_DECRYPTION: true;
1037
+ };
1038
+
1039
+ /**
1040
+ * One-Click Payments Module
1041
+ *
1042
+ * Enables frictionless repeat payments for returning customers.
1043
+ * Customer approves a spending limit once, merchant can charge without interaction.
1044
+ */
1045
+ interface SpendingApproval {
1046
+ id: string;
1047
+ customerWallet: string;
1048
+ customerEmail?: string;
1049
+ merchantWallet: string;
1050
+ spendingLimit: number;
1051
+ amountSpent: number;
1052
+ remainingLimit: number;
1053
+ expiresAt: Date;
1054
+ status: 'active' | 'expired' | 'revoked';
1055
+ createdAt: Date;
1056
+ }
1057
+ interface ApproveOneClickOptions {
1058
+ /** Customer's wallet address */
1059
+ customerWallet: string;
1060
+ /** Customer's email (optional, for notifications) */
1061
+ customerEmail?: string;
1062
+ /** Merchant's wallet address */
1063
+ merchantWallet: string;
1064
+ /** Maximum USDC amount the merchant can charge */
1065
+ spendingLimit: number;
1066
+ /** Days until approval expires (default: 30) */
1067
+ expiresInDays?: number;
1068
+ }
1069
+ interface ChargeOneClickOptions {
1070
+ /** Customer's wallet address */
1071
+ customerWallet: string;
1072
+ /** Merchant's wallet address */
1073
+ merchantWallet: string;
1074
+ /** Amount to charge in USDC */
1075
+ amount: number;
1076
+ /** Optional memo for the transaction */
1077
+ memo?: string;
1078
+ }
1079
+ interface OneClickResult {
1080
+ success: boolean;
1081
+ error?: string;
1082
+ txSignature?: string;
1083
+ remainingLimit?: number;
1084
+ }
1085
+ /**
1086
+ * One-Click Payment Client
1087
+ *
1088
+ * @example
1089
+ * ```typescript
1090
+ * import { OneClickClient } from '@settlr/sdk';
1091
+ *
1092
+ * const oneClick = new OneClickClient('https://settlr.dev');
1093
+ *
1094
+ * // Customer approves merchant
1095
+ * await oneClick.approve({
1096
+ * customerWallet: 'Ac52MM...',
1097
+ * merchantWallet: 'DjLFeM...',
1098
+ * spendingLimit: 100, // $100 max
1099
+ * });
1100
+ *
1101
+ * // Merchant charges customer later (no interaction needed)
1102
+ * const result = await oneClick.charge({
1103
+ * customerWallet: 'Ac52MM...',
1104
+ * merchantWallet: 'DjLFeM...',
1105
+ * amount: 25,
1106
+ * });
1107
+ * ```
1108
+ */
1109
+ declare class OneClickClient {
1110
+ private baseUrl;
1111
+ constructor(baseUrl?: string);
1112
+ /**
1113
+ * Customer approves a spending limit for a merchant
1114
+ */
1115
+ approve(options: ApproveOneClickOptions): Promise<{
1116
+ success: boolean;
1117
+ approval?: SpendingApproval;
1118
+ }>;
1119
+ /**
1120
+ * Check if customer has active approval for merchant
1121
+ */
1122
+ check(customerWallet: string, merchantWallet: string): Promise<{
1123
+ hasApproval: boolean;
1124
+ remainingLimit?: number;
1125
+ approval?: SpendingApproval;
1126
+ }>;
1127
+ /**
1128
+ * Merchant charges customer using their one-click approval
1129
+ * No customer interaction required if approval exists with sufficient limit
1130
+ */
1131
+ charge(options: ChargeOneClickOptions): Promise<OneClickResult>;
1132
+ /**
1133
+ * Customer revokes merchant's one-click access
1134
+ */
1135
+ revoke(customerWallet: string, merchantWallet: string): Promise<{
1136
+ success: boolean;
1137
+ }>;
1138
+ }
1139
+ /**
1140
+ * Create a one-click payment client
1141
+ *
1142
+ * @param baseUrl - Settlr API base URL (default: https://settlr.dev)
1143
+ */
1144
+ declare function createOneClickClient(baseUrl?: string): OneClickClient;
1145
+
1146
+ /**
1147
+ * Mobile Game Integration Utilities
1148
+ *
1149
+ * Simple helpers for integrating Settlr payments in mobile games.
1150
+ * Works with Unity, Unreal, native iOS/Android, React Native, etc.
1151
+ *
1152
+ * The simplest integration is URL-based - just open the checkout URL
1153
+ * and listen for the callback.
1154
+ */
1155
+ interface MobileCheckoutOptions {
1156
+ /** Amount in USDC */
1157
+ amount: number;
1158
+ /** Merchant wallet address */
1159
+ merchantWallet: string;
1160
+ /** Optional: Merchant display name */
1161
+ merchantName?: string;
1162
+ /** Optional: Payment description */
1163
+ memo?: string;
1164
+ /** URL to redirect after success */
1165
+ successUrl?: string;
1166
+ /** URL to redirect on cancel */
1167
+ cancelUrl?: string;
1168
+ /** Optional: Your order/transaction ID */
1169
+ orderId?: string;
1170
+ /** Optional: Customer ID for one-click */
1171
+ customerId?: string;
1172
+ }
1173
+ interface MobileCheckoutResult {
1174
+ success: boolean;
1175
+ signature?: string;
1176
+ orderId?: string;
1177
+ error?: string;
1178
+ }
1179
+ /**
1180
+ * Generate a checkout URL for mobile games
1181
+ *
1182
+ * Usage in Unity (C#):
1183
+ * ```csharp
1184
+ * string url = $"https://settlr.dev/checkout?amount={amount}&merchant={wallet}";
1185
+ * Application.OpenURL(url);
1186
+ * ```
1187
+ *
1188
+ * Usage in Swift:
1189
+ * ```swift
1190
+ * let url = "https://settlr.dev/checkout?amount=\(amount)&merchant=\(wallet)"
1191
+ * UIApplication.shared.open(URL(string: url)!)
1192
+ * ```
1193
+ */
1194
+ declare function generateCheckoutUrl(options: MobileCheckoutOptions, baseUrl?: string): string;
1195
+ /**
1196
+ * Generate a deep link for mobile app integration
1197
+ *
1198
+ * For apps that register a custom URL scheme (e.g., mygame://)
1199
+ * the success/cancel URLs can redirect back to the app.
1200
+ *
1201
+ * Example:
1202
+ * - successUrl: "mygame://payment-success?order=123"
1203
+ * - cancelUrl: "mygame://payment-cancel?order=123"
1204
+ */
1205
+ declare function generateDeepLinkCheckout(options: MobileCheckoutOptions, appScheme: string, baseUrl?: string): string;
1206
+ /**
1207
+ * Parse the callback URL when user returns to app
1208
+ *
1209
+ * Usage in Swift:
1210
+ * ```swift
1211
+ * func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
1212
+ * if url.scheme == "mygame" && url.host == "payment-success" {
1213
+ * let signature = URLComponents(url: url, resolvingAgainstBaseURL: true)?
1214
+ * .queryItems?.first(where: { $0.name == "signature" })?.value
1215
+ * // Handle success
1216
+ * }
1217
+ * }
1218
+ * ```
1219
+ */
1220
+ declare function parseCallbackUrl(url: string): MobileCheckoutResult;
1221
+ /**
1222
+ * REST API endpoint info for server-side integration
1223
+ *
1224
+ * Mobile games can use these APIs directly without the SDK:
1225
+ *
1226
+ * 1. Create checkout session:
1227
+ * POST /api/checkout/create
1228
+ * { amount, merchantWallet, memo }
1229
+ * → { sessionId, checkoutUrl }
1230
+ *
1231
+ * 2. Check payment status:
1232
+ * GET /api/checkout/status?session={sessionId}
1233
+ * → { status: 'pending' | 'completed' | 'expired', signature? }
1234
+ *
1235
+ * 3. One-click payment (for returning players):
1236
+ * POST /api/one-click
1237
+ * { action: 'charge', customerWallet, merchantWallet, amount }
1238
+ * → { success, signature }
1239
+ */
1240
+ declare const REST_API: {
1241
+ createSession: string;
1242
+ checkStatus: string;
1243
+ oneClick: string;
1244
+ webhook: string;
1245
+ };
1246
+ /**
1247
+ * Example Unity C# integration code
1248
+ * (For documentation purposes)
1249
+ */
1250
+ declare const UNITY_EXAMPLE = "\n// SettlrPayment.cs - Drop into your Unity project\n\nusing UnityEngine;\nusing UnityEngine.Networking;\nusing System.Collections;\n\npublic class SettlrPayment : MonoBehaviour\n{\n public string merchantWallet = \"YOUR_WALLET_ADDRESS\";\n public string settlrUrl = \"https://settlr.dev\";\n \n // Call this to start a payment\n public void StartPayment(float amount, string orderId, System.Action<bool, string> callback)\n {\n string url = $\"{settlrUrl}/checkout?amount={amount}&merchant={merchantWallet}&order_id={orderId}\";\n \n // Add deep link callback (register mygame:// scheme in your app)\n url += $\"&success_url=mygame://payment-success?order={orderId}\";\n url += $\"&cancel_url=mygame://payment-cancel?order={orderId}\";\n \n Application.OpenURL(url);\n \n // Start polling for completion\n StartCoroutine(PollPaymentStatus(orderId, callback));\n }\n \n IEnumerator PollPaymentStatus(string orderId, System.Action<bool, string> callback)\n {\n string statusUrl = $\"{settlrUrl}/api/checkout/status?order_id={orderId}\";\n \n for (int i = 0; i < 60; i++) // Poll for 5 minutes\n {\n using (UnityWebRequest request = UnityWebRequest.Get(statusUrl))\n {\n yield return request.SendWebRequest();\n \n if (request.result == UnityWebRequest.Result.Success)\n {\n var response = JsonUtility.FromJson<PaymentStatusResponse>(request.downloadHandler.text);\n \n if (response.status == \"completed\")\n {\n callback(true, response.signature);\n yield break;\n }\n else if (response.status == \"expired\" || response.status == \"cancelled\")\n {\n callback(false, null);\n yield break;\n }\n }\n }\n \n yield return new WaitForSeconds(5f); // Check every 5 seconds\n }\n \n callback(false, \"Timeout\");\n }\n \n [System.Serializable]\n class PaymentStatusResponse\n {\n public string status;\n public string signature;\n }\n}\n";
1251
+ /**
1252
+ * Example React Native integration
1253
+ */
1254
+ declare const REACT_NATIVE_EXAMPLE = "\n// SettlrPayment.tsx - React Native component\n\nimport { Linking, Alert } from 'react-native';\nimport { useEffect } from 'react';\n\nconst SETTLR_URL = 'https://settlr.dev';\nconst APP_SCHEME = 'mygame';\n\nexport function useSettlrPayment(onSuccess: (sig: string) => void) {\n useEffect(() => {\n const handleDeepLink = ({ url }: { url: string }) => {\n if (url.includes('payment-success')) {\n const sig = new URL(url).searchParams.get('signature');\n if (sig) onSuccess(sig);\n }\n };\n \n Linking.addEventListener('url', handleDeepLink);\n return () => Linking.removeAllListeners('url');\n }, [onSuccess]);\n \n const startPayment = async (amount: number, merchantWallet: string) => {\n const orderId = `order_${Date.now()}`;\n const url = `${SETTLR_URL}/checkout?amount=${amount}&merchant=${merchantWallet}` +\n `&success_url=${APP_SCHEME}://payment-success?order=${orderId}` +\n `&cancel_url=${APP_SCHEME}://payment-cancel?order=${orderId}`;\n \n await Linking.openURL(url);\n };\n \n return { startPayment };\n}\n";
1255
+
1256
+ export { type ApproveOneClickOptions, BuyButton, type BuyButtonProps, type ChargeOneClickOptions, CheckoutWidget, type CheckoutWidgetProps, type CreatePaymentOptions, type CreateSubscriptionOptions, INCO_LIGHTNING_PROGRAM_ID, type IssuePrivateReceiptResult, type MerchantConfig, type MobileCheckoutOptions, type MobileCheckoutResult, OneClickClient, type OneClickResult, type Payment, PaymentModal, type PaymentModalProps, type PaymentResult, type PaymentStatus, PrivacyFeatures, type PrivateReceiptConfig, REACT_NATIVE_EXAMPLE, REST_API, SETTLR_CHECKOUT_URL, SETTLR_PROGRAM_ID, SUPPORTED_NETWORKS, SUPPORTED_TOKENS, Settlr, type SettlrConfig, SettlrProvider, type SpendingApproval, type Subscription, type SubscriptionInterval, type SubscriptionPlan, type SubscriptionStatus, type SupportedToken, type TransactionOptions, UNITY_EXAMPLE, USDC_MINT_DEVNET, USDC_MINT_MAINNET, USDT_MINT_DEVNET, USDT_MINT_MAINNET, type WebhookEventType, type WebhookHandler, type WebhookHandlers, type WebhookPayload, buildAllowanceRemainingAccounts, buildPrivateReceiptAccounts, createOneClickClient, createWebhookHandler, encryptAmount, findAllowancePda, findPrivateReceiptPda, formatUSDC, generateCheckoutUrl, generateDeepLinkCheckout, getTokenDecimals, getTokenMint, parseCallbackUrl, parseUSDC, parseWebhookPayload, shortenAddress, simulateAndGetHandle, usePaymentLink, usePaymentModal, useSettlr, verifyWebhookSignature };