@dcentralab/d402-client 0.3.5 → 0.3.8

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
@@ -1,5 +1,6 @@
1
1
  import { Account } from 'viem/accounts';
2
- import { PublicClient, WalletClient, Hash, Address } from 'viem';
2
+ import { WalletClient, PublicClient, Hash, Address } from 'viem';
3
+ import { Chain } from 'viem/chains';
3
4
 
4
5
  /**
5
6
  * Type definitions for D402 payment protocol
@@ -198,6 +199,11 @@ interface D402ClientConfig {
198
199
  * Typically from wagmi: `walletClient.account`
199
200
  */
200
201
  operatorAccount: Account;
202
+ /**
203
+ * Wallet client for signing (required for wagmi/browser use).
204
+ * This is needed because wagmi accounts don't have signTypedData directly.
205
+ */
206
+ walletClient?: WalletClient;
201
207
  /**
202
208
  * IATPWallet contract address.
203
209
  * Get from `createIATPWallet()` or `getWalletsByOwner()`.
@@ -267,6 +273,7 @@ interface D402ClientConfig {
267
273
  */
268
274
  declare class D402Client {
269
275
  private readonly operatorAccount;
276
+ private readonly walletClient?;
270
277
  private readonly iatpWalletAddress;
271
278
  private readonly maxValue?;
272
279
  private readonly paymentRequirementsSelector;
@@ -383,6 +390,45 @@ declare class D402Client {
383
390
  * ```
384
391
  */
385
392
  fetch(url: string, init?: RequestInit): Promise<Response>;
393
+ /**
394
+ * Call an MCP tool with automatic session initialization and payment handling.
395
+ *
396
+ * This is the simplest way to call an MCP tool. It handles:
397
+ * - MCP session initialization
398
+ * - JSON-RPC payload construction
399
+ * - HTTP 402 payment flow
400
+ * - SSE/JSON response parsing
401
+ *
402
+ * @param endpoint - MCP server endpoint URL
403
+ * @param toolName - Name of the tool to call
404
+ * @param input - Tool arguments
405
+ * @param options - Optional configuration
406
+ * @returns The tool's result data
407
+ *
408
+ * @example
409
+ * ```ts
410
+ * const client = new D402Client({
411
+ * operatorAccount: walletClient.account,
412
+ * walletClient,
413
+ * iatpWalletAddress,
414
+ * })
415
+ *
416
+ * // Simple one-liner!
417
+ * const result = await client.mcpCall(
418
+ * 'https://my-mcp.example.com/mcp',
419
+ * 'google_search',
420
+ * { q: 'test search' }
421
+ * )
422
+ *
423
+ * console.log(result) // { searchResults: [...] }
424
+ * ```
425
+ */
426
+ mcpCall(endpoint: string, toolName: string, input: Record<string, unknown>, options?: {
427
+ /** Skip session initialization (for stateless servers) */
428
+ skipInit?: boolean;
429
+ /** Custom JSON-RPC request ID */
430
+ requestId?: string | number;
431
+ }): Promise<unknown>;
386
432
  }
387
433
 
388
434
  /**
@@ -399,6 +445,7 @@ declare class D402Client {
399
445
  *
400
446
  * @param params - Signing parameters
401
447
  * @param params.operatorAccount - User's account for signing (from wagmi walletClient)
448
+ * @param params.walletClient - Optional wallet client for signing (wagmi). If provided, uses walletClient.signTypedData
402
449
  * @param params.paymentRequirement - Payment requirements from 402 response
403
450
  * @param params.iatpWalletAddress - IATPWallet contract address (optional)
404
451
  * @param params.requestPath - API request path (optional, uses payment_requirements.resource if not provided)
@@ -412,6 +459,7 @@ declare class D402Client {
412
459
  * // User signs payment (MetaMask popup appears)
413
460
  * const signedPayment = await signD402Payment({
414
461
  * operatorAccount: walletClient.account, // User's wallet
462
+ * walletClient: walletClient, // For signing with wagmi
415
463
  * paymentRequirement: requirement,
416
464
  * iatpWalletAddress: '0xUserIATPWallet...'
417
465
  * })
@@ -422,6 +470,7 @@ declare class D402Client {
422
470
  */
423
471
  declare function signD402Payment(params: {
424
472
  operatorAccount: Account;
473
+ walletClient?: WalletClient;
425
474
  paymentRequirement: PaymentRequirement;
426
475
  iatpWalletAddress: `0x${string}`;
427
476
  requestPath?: string;
@@ -542,6 +591,23 @@ declare function decodePaymentResponse(header: string): {
542
591
  message?: string;
543
592
  };
544
593
 
594
+ /**
595
+ * Core type definitions shared across the package
596
+ */
597
+ /**
598
+ * Supported blockchain networks (where IATP contracts are deployed)
599
+ */
600
+ type SupportedNetwork = 'sepolia' | 'arbitrum';
601
+ /**
602
+ * EIP-712 domain for signature verification
603
+ */
604
+ interface EIP712Domain {
605
+ name: string;
606
+ version: string;
607
+ chainId: number;
608
+ verifyingContract: `0x${string}`;
609
+ }
610
+
545
611
  /**
546
612
  * Type definitions for wallet module
547
613
  */
@@ -592,7 +658,7 @@ interface WithdrawalRequest {
592
658
  *
593
659
  * @param params - Creation parameters
594
660
  * @param params.ownerAccount - Owner's account (will own the wallet)
595
- * @param params.network - Network to deploy on (default: "sepolia")
661
+ * @param params.network - Network to deploy on: "sepolia" | "arbitrum" (default: "sepolia")
596
662
  * @param params.rpcUrl - Custom RPC URL (optional)
597
663
  * @returns Wallet creation result with addresses and keys
598
664
  *
@@ -613,7 +679,8 @@ interface WithdrawalRequest {
613
679
  */
614
680
  declare function createIATPWallet(params: {
615
681
  ownerAccount: Account;
616
- network?: 'sepolia';
682
+ walletClient?: WalletClient;
683
+ network?: SupportedNetwork;
617
684
  rpcUrl?: string;
618
685
  }): Promise<WalletCreationResult>;
619
686
 
@@ -631,7 +698,7 @@ declare function createIATPWallet(params: {
631
698
  * @param params.publicClient - Viem PublicClient (from wagmi usePublicClient)
632
699
  * @param params.walletAddress - IATPWallet contract address
633
700
  * @param params.tokenAddress - Token contract address (e.g., USDC)
634
- * @param params.network - Network to query (default: "sepolia")
701
+ * @param params.network - Network to query: "sepolia" | "arbitrum" (default: "sepolia")
635
702
  * @returns Available balance in token's base units (wei)
636
703
  *
637
704
  * @example
@@ -654,7 +721,7 @@ declare function getAvailableBalance(params: {
654
721
  publicClient: PublicClient;
655
722
  walletAddress: Address;
656
723
  tokenAddress: Address;
657
- network?: 'sepolia';
724
+ network?: SupportedNetwork;
658
725
  }): Promise<bigint>;
659
726
  /**
660
727
  * Get all IATPWallet addresses owned by a user.
@@ -666,7 +733,7 @@ declare function getAvailableBalance(params: {
666
733
  *
667
734
  * @param params - Query parameters
668
735
  * @param params.ownerAddress - User's wallet address (from MetaMask)
669
- * @param params.network - Network to query (default: "sepolia")
736
+ * @param params.network - Network to query: "sepolia" | "arbitrum" (default: "sepolia")
670
737
  * @param params.rpcUrl - Custom RPC URL (optional)
671
738
  * @returns Array of IATPWallet contract addresses (empty if user has no wallets)
672
739
  *
@@ -692,7 +759,7 @@ declare function getAvailableBalance(params: {
692
759
  */
693
760
  declare function getWalletsByOwner(params: {
694
761
  ownerAddress: Address;
695
- network?: 'sepolia';
762
+ network?: SupportedNetwork;
696
763
  rpcUrl?: string;
697
764
  }): Promise<Address[]>;
698
765
 
@@ -710,7 +777,7 @@ declare function getWalletsByOwner(params: {
710
777
  * @param params.publicClient - Viem PublicClient
711
778
  * @param params.walletAddress - IATPWallet contract address
712
779
  * @param params.tokenAddress - Token contract address
713
- * @param params.network - Network to query (default: "sepolia")
780
+ * @param params.network - Network: "sepolia" | "arbitrum" (default: "sepolia")
714
781
  * @returns Withdrawal request details or null if no request exists
715
782
  *
716
783
  * @example
@@ -739,7 +806,7 @@ declare function getWithdrawalRequest(params: {
739
806
  publicClient: PublicClient;
740
807
  walletAddress: Address;
741
808
  tokenAddress: Address;
742
- network?: 'sepolia';
809
+ network?: SupportedNetwork;
743
810
  }): Promise<{
744
811
  request: WithdrawalRequest;
745
812
  unlockTime: bigint;
@@ -757,7 +824,7 @@ declare function getWithdrawalRequest(params: {
757
824
  * @param params.tokenAddress - Token contract address
758
825
  * @param params.amount - Amount in token's base units (wei)
759
826
  * @param params.account - Account to sign transaction (operator)
760
- * @param params.network - Network (default: "sepolia")
827
+ * @param params.network - Network: "sepolia" | "arbitrum" (default: "sepolia")
761
828
  * @returns Transaction hash
762
829
  *
763
830
  * @example
@@ -782,7 +849,7 @@ declare function requestWithdrawal(params: {
782
849
  tokenAddress: Address;
783
850
  amount: bigint;
784
851
  account: Account;
785
- network?: 'sepolia';
852
+ network?: SupportedNetwork;
786
853
  }): Promise<Hash>;
787
854
  /**
788
855
  * Execute a withdrawal from an IATPWallet (after unlock period).
@@ -796,7 +863,7 @@ declare function requestWithdrawal(params: {
796
863
  * @param params.walletAddress - IATPWallet contract address
797
864
  * @param params.tokenAddress - Token contract address
798
865
  * @param params.account - Account to sign transaction (operator)
799
- * @param params.network - Network (default: "sepolia")
866
+ * @param params.network - Network: "sepolia" | "arbitrum" (default: "sepolia")
800
867
  * @returns Transaction hash
801
868
  *
802
869
  * @example
@@ -818,9 +885,112 @@ declare function executeWithdrawal(params: {
818
885
  walletAddress: Address;
819
886
  tokenAddress: Address;
820
887
  account: Account;
821
- network?: 'sepolia';
888
+ network?: SupportedNetwork;
822
889
  }): Promise<Hash>;
823
890
 
891
+ /**
892
+ * MCP Session Management
893
+ *
894
+ * Handles MCP protocol session initialization.
895
+ */
896
+ /**
897
+ * Initialize an MCP session with the server.
898
+ *
899
+ * Sends the `initialize` JSON-RPC method to establish a session.
900
+ * Some servers return a session ID in headers, others are stateless.
901
+ *
902
+ * @param endpoint - MCP server endpoint URL
903
+ * @returns Session ID if provided by server, null otherwise
904
+ */
905
+ declare function initMcpSession(endpoint: string): Promise<string | null>;
906
+
907
+ /**
908
+ * MCP Payload Builder
909
+ *
910
+ * Constructs JSON-RPC payloads for MCP tool calls.
911
+ */
912
+ interface JsonRpcPayload {
913
+ jsonrpc: '2.0';
914
+ id: string | number;
915
+ method: string;
916
+ params: {
917
+ name: string;
918
+ arguments: Record<string, unknown>;
919
+ };
920
+ }
921
+ /**
922
+ * Build a JSON-RPC payload for an MCP tool call.
923
+ *
924
+ * @param toolName - Name of the MCP tool to call
925
+ * @param args - Tool arguments
926
+ * @param requestId - Optional custom request ID (default: 1)
927
+ * @returns Complete JSON-RPC payload ready to send
928
+ *
929
+ * @example
930
+ * ```ts
931
+ * const payload = buildToolCallPayload('google_search', { q: 'test' })
932
+ * // { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'google_search', arguments: { q: 'test' } } }
933
+ * ```
934
+ */
935
+ declare function buildToolCallPayload(toolName: string, args: Record<string, unknown>, requestId?: string | number): JsonRpcPayload;
936
+ /**
937
+ * Build headers for an MCP request.
938
+ *
939
+ * @param sessionId - Optional MCP session ID
940
+ * @returns Headers object for fetch
941
+ */
942
+ declare function buildMcpHeaders(sessionId?: string | null): Record<string, string>;
943
+
944
+ /**
945
+ * MCP Response Parser
946
+ *
947
+ * Handles parsing of MCP responses in both JSON and SSE formats.
948
+ */
949
+ interface McpToolResult {
950
+ /** Whether the tool call was successful */
951
+ isError: boolean;
952
+ /** The tool's output content */
953
+ content: Array<{
954
+ type: string;
955
+ text?: string;
956
+ [key: string]: unknown;
957
+ }>;
958
+ /** Structured content if available */
959
+ structuredContent?: unknown;
960
+ }
961
+ interface ParsedMcpResponse {
962
+ /** JSON-RPC response ID */
963
+ id: string | number;
964
+ /** The tool result */
965
+ result: McpToolResult | unknown;
966
+ /** Error if the call failed */
967
+ error?: {
968
+ code: number;
969
+ message: string;
970
+ data?: unknown;
971
+ };
972
+ }
973
+ /**
974
+ * Parse an MCP response, handling both SSE and JSON formats.
975
+ *
976
+ * MCP servers may return responses as:
977
+ * - `application/json`: Standard JSON response
978
+ * - `text/event-stream`: Server-Sent Events with `data: {...}` format
979
+ *
980
+ * @param response - Fetch Response object
981
+ * @returns Parsed response data
982
+ */
983
+ declare function parseMcpResponse(response: Response): Promise<ParsedMcpResponse>;
984
+ /**
985
+ * Extract the tool result from an MCP response.
986
+ *
987
+ * Handles the nested structure and returns just the useful data.
988
+ *
989
+ * @param response - Parsed MCP response
990
+ * @returns The tool's result data
991
+ */
992
+ declare function extractToolResult(response: ParsedMcpResponse): unknown;
993
+
824
994
  /**
825
995
  * IATPSettlementLayer query functions
826
996
  */
@@ -835,7 +1005,7 @@ declare function executeWithdrawal(params: {
835
1005
  * @param params.publicClient - Viem PublicClient (from wagmi usePublicClient)
836
1006
  * @param params.providerAddress - Provider (utility agent) IATPWallet address
837
1007
  * @param params.tokenAddress - Token contract address
838
- * @param params.network - Network (default: "sepolia")
1008
+ * @param params.network - Network: "sepolia" | "arbitrum" (default: "sepolia")
839
1009
  * @returns Locked balance in base units (wei)
840
1010
  *
841
1011
  * @example
@@ -856,7 +1026,7 @@ declare function getLockedBalanceForProvider(params: {
856
1026
  publicClient: PublicClient;
857
1027
  providerAddress: Address;
858
1028
  tokenAddress: Address;
859
- network?: 'sepolia';
1029
+ network?: SupportedNetwork;
860
1030
  }): Promise<bigint>;
861
1031
  /**
862
1032
  * Get unlocked balance for a provider across released epochs.
@@ -868,7 +1038,7 @@ declare function getLockedBalanceForProvider(params: {
868
1038
  * @param params.publicClient - Viem PublicClient (from wagmi usePublicClient)
869
1039
  * @param params.providerAddress - Provider (utility agent) IATPWallet address
870
1040
  * @param params.tokenAddress - Token contract address
871
- * @param params.network - Network (default: "sepolia")
1041
+ * @param params.network - Network: "sepolia" | "arbitrum" (default: "sepolia")
872
1042
  * @returns Unlocked balance in base units (wei)
873
1043
  *
874
1044
  * @example
@@ -889,7 +1059,7 @@ declare function getUnlockedBalanceForProvider(params: {
889
1059
  publicClient: PublicClient;
890
1060
  providerAddress: Address;
891
1061
  tokenAddress: Address;
892
- network?: 'sepolia';
1062
+ network?: SupportedNetwork;
893
1063
  }): Promise<bigint>;
894
1064
 
895
1065
  /**
@@ -909,7 +1079,7 @@ declare function getUnlockedBalanceForProvider(params: {
909
1079
  * @param params.walletClient - Viem WalletClient (from wagmi useWalletClient)
910
1080
  * @param params.publicClient - Viem PublicClient (from wagmi usePublicClient)
911
1081
  * @param params.tokenAddress - Token contract address to withdraw
912
- * @param params.network - Network (default: "sepolia")
1082
+ * @param params.network - Network: "sepolia" | "arbitrum" (default: "sepolia")
913
1083
  * @returns Transaction hash
914
1084
  *
915
1085
  * @example
@@ -930,26 +1100,9 @@ declare function withdrawAllAvailableEpochs(params: {
930
1100
  walletClient: WalletClient;
931
1101
  publicClient: PublicClient;
932
1102
  tokenAddress: Address;
933
- network?: 'sepolia';
1103
+ network?: SupportedNetwork;
934
1104
  }): Promise<Hash>;
935
1105
 
936
- /**
937
- * Core type definitions shared across the package
938
- */
939
- /**
940
- * Supported blockchain networks (where IATP contracts are deployed)
941
- */
942
- type SupportedNetwork = 'sepolia';
943
- /**
944
- * EIP-712 domain for signature verification
945
- */
946
- interface EIP712Domain {
947
- name: string;
948
- version: string;
949
- chainId: number;
950
- verifyingContract: `0x${string}`;
951
- }
952
-
953
1106
  /**
954
1107
  * Contract configuration and utilities.
955
1108
  *
@@ -970,8 +1123,7 @@ declare enum ContractName {
970
1123
  * Get contract address for a given network.
971
1124
  *
972
1125
  * @param contractName - Name of the contract (use ContractName enum)
973
- * @param network - Network name (default: "sepolia")
974
- * @param useProxy - Use proxy address if true, implementation if false (default: true)
1126
+ * @param network - Network: "sepolia" | "arbitrum" (default: "sepolia")
975
1127
  * @returns Contract address as hex string, or null if not found
976
1128
  *
977
1129
  * @example
@@ -980,12 +1132,12 @@ declare enum ContractName {
980
1132
  * console.log(factoryAddr) // "0x15D83638E339a0f29283f6B93dC1bb90b8339078"
981
1133
  * ```
982
1134
  */
983
- declare function getContractAddress(contractName: string | ContractName, network?: SupportedNetwork, useProxy?: boolean): string | null;
1135
+ declare function getContractAddress(contractName: string | ContractName, network?: SupportedNetwork): string | null;
984
1136
  /**
985
1137
  * Get contract ABI for a given network.
986
1138
  *
987
1139
  * @param contractName - Name of the contract (use ContractName enum)
988
- * @param network - Network name (default: "sepolia")
1140
+ * @param network - Network: "sepolia" | "arbitrum" (default: "sepolia")
989
1141
  * @returns Contract ABI as array of objects, or null if not found
990
1142
  *
991
1143
  * @example
@@ -999,7 +1151,7 @@ declare function getContractAbi(contractName: string | ContractName, network?: S
999
1151
  * Get contract configuration (address and ABI) for a network.
1000
1152
  *
1001
1153
  * @param contractName - Name of the contract
1002
- * @param network - Network name (default: "sepolia")
1154
+ * @param network - Network: "sepolia" | "arbitrum" (default: "sepolia")
1003
1155
  * @returns Object with address and abi, or null if not found
1004
1156
  *
1005
1157
  * @example
@@ -1020,6 +1172,19 @@ declare function getContractConfig(contractName: string | ContractName, network?
1020
1172
  * Utility functions for D402 payment processing
1021
1173
  */
1022
1174
 
1175
+ /**
1176
+ * Get viem Chain object for a supported network
1177
+ *
1178
+ * @param network - Network name
1179
+ * @returns viem Chain object
1180
+ *
1181
+ * @example
1182
+ * ```ts
1183
+ * const chain = getChain('arbitrum')
1184
+ * console.log(chain.id) // 42161
1185
+ * ```
1186
+ */
1187
+ declare function getChain(network: SupportedNetwork): Chain;
1023
1188
  /**
1024
1189
  * Parse a money string or number into atomic units (wei)
1025
1190
  *
@@ -1071,7 +1236,6 @@ declare function getUsdcAddress(network: SupportedNetwork): `0x${string}`;
1071
1236
  * ```ts
1072
1237
  * getChainId('sepolia') // Returns 11155111
1073
1238
  * getChainId('11155111') // Returns 11155111 (passthrough)
1074
- * getChainId('base') // Returns 8453 (for parsing 402 responses)
1075
1239
  * ```
1076
1240
  */
1077
1241
  declare function getChainId(network: string): number;
@@ -1172,4 +1336,4 @@ declare class UnsupportedNetworkError extends PaymentError {
1172
1336
  constructor(network: string);
1173
1337
  }
1174
1338
 
1175
- export { ContractName, D402Client, type D402ClientConfig, type D402Response, type EIP712Domain, Invalid402ResponseError, MissingRequestConfigError, PaymentAlreadyAttemptedError, PaymentAmountExceededError, type PaymentAuthorization, PaymentError, type PaymentRequirement, type PaymentSelector, type PaymentSelectorOptions, PaymentVerificationError, type SignedPayment, type SupportedNetwork, UnsupportedNetworkError, UnsupportedSchemeError, type WalletCreationResult, type WithdrawalRequest, createIATPWallet, createPaymentSelector, decodePayment, decodePaymentResponse, encodePayment, executeWithdrawal, findMatchingPaymentRequirement, formatMoney, generateNonce, getAvailableBalance, getChainId, getContractAbi, getContractAddress, getContractConfig, getCurrentTimestamp, getLockedBalanceForProvider, getUnlockedBalanceForProvider, getUsdcAddress, getWalletsByOwner, getWithdrawalRequest, isValidAddress, normalizeAddress, parseAllPaymentRequirements, parseMoney, parsePaymentRequirement, requestWithdrawal, selectPaymentRequirement, signD402Payment, sortPaymentRequirements, usdToUsdc, withdrawAllAvailableEpochs };
1339
+ export { ContractName, D402Client, type D402ClientConfig, type D402Response, type EIP712Domain, Invalid402ResponseError, type JsonRpcPayload, type McpToolResult, MissingRequestConfigError, type ParsedMcpResponse, PaymentAlreadyAttemptedError, PaymentAmountExceededError, type PaymentAuthorization, PaymentError, type PaymentRequirement, type PaymentSelector, type PaymentSelectorOptions, PaymentVerificationError, type SignedPayment, type SupportedNetwork, UnsupportedNetworkError, UnsupportedSchemeError, type WalletCreationResult, type WithdrawalRequest, buildMcpHeaders, buildToolCallPayload, createIATPWallet, createPaymentSelector, decodePayment, decodePaymentResponse, encodePayment, executeWithdrawal, extractToolResult, findMatchingPaymentRequirement, formatMoney, generateNonce, getAvailableBalance, getChain, getChainId, getContractAbi, getContractAddress, getContractConfig, getCurrentTimestamp, getLockedBalanceForProvider, getUnlockedBalanceForProvider, getUsdcAddress, getWalletsByOwner, getWithdrawalRequest, initMcpSession, isValidAddress, normalizeAddress, parseAllPaymentRequirements, parseMcpResponse, parseMoney, parsePaymentRequirement, requestWithdrawal, selectPaymentRequirement, signD402Payment, sortPaymentRequirements, usdToUsdc, withdrawAllAvailableEpochs };