@silentswap/react 0.0.41

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.
Files changed (86) hide show
  1. package/README.md +48 -0
  2. package/dist/contexts/AssetsContext.d.ts +24 -0
  3. package/dist/contexts/AssetsContext.js +83 -0
  4. package/dist/contexts/BalancesContext.d.ts +28 -0
  5. package/dist/contexts/BalancesContext.js +533 -0
  6. package/dist/contexts/OrdersContext.d.ts +53 -0
  7. package/dist/contexts/OrdersContext.js +240 -0
  8. package/dist/contexts/PricesContext.d.ts +12 -0
  9. package/dist/contexts/PricesContext.js +109 -0
  10. package/dist/contexts/SilentSwapContext.d.ts +58 -0
  11. package/dist/contexts/SilentSwapContext.js +205 -0
  12. package/dist/hooks/silent/orderTrackingWebSocketManager.d.ts +48 -0
  13. package/dist/hooks/silent/orderTrackingWebSocketManager.js +284 -0
  14. package/dist/hooks/silent/solana-transaction.d.ts +60 -0
  15. package/dist/hooks/silent/solana-transaction.js +236 -0
  16. package/dist/hooks/silent/useAuth.d.ts +90 -0
  17. package/dist/hooks/silent/useAuth.js +269 -0
  18. package/dist/hooks/silent/useBridgeExecution.d.ts +39 -0
  19. package/dist/hooks/silent/useBridgeExecution.js +877 -0
  20. package/dist/hooks/silent/useOrderSigning.d.ts +34 -0
  21. package/dist/hooks/silent/useOrderSigning.js +133 -0
  22. package/dist/hooks/silent/useOrderTracking.d.ts +174 -0
  23. package/dist/hooks/silent/useOrderTracking.js +524 -0
  24. package/dist/hooks/silent/useQuoteCalculation.d.ts +50 -0
  25. package/dist/hooks/silent/useQuoteCalculation.js +331 -0
  26. package/dist/hooks/silent/useQuoteFetching.d.ts +18 -0
  27. package/dist/hooks/silent/useQuoteFetching.js +54 -0
  28. package/dist/hooks/silent/useRefund.d.ts +26 -0
  29. package/dist/hooks/silent/useRefund.js +134 -0
  30. package/dist/hooks/silent/useSilentClient.d.ts +16 -0
  31. package/dist/hooks/silent/useSilentClient.js +32 -0
  32. package/dist/hooks/silent/useSilentOrders.d.ts +174 -0
  33. package/dist/hooks/silent/useSilentOrders.js +73 -0
  34. package/dist/hooks/silent/useSilentQuote.d.ts +88 -0
  35. package/dist/hooks/silent/useSilentQuote.js +381 -0
  36. package/dist/hooks/silent/useWallet.d.ts +76 -0
  37. package/dist/hooks/silent/useWallet.js +203 -0
  38. package/dist/hooks/useAssetPrice.d.ts +8 -0
  39. package/dist/hooks/useAssetPrice.js +47 -0
  40. package/dist/hooks/useContacts.d.ts +52 -0
  41. package/dist/hooks/useContacts.js +259 -0
  42. package/dist/hooks/useEgressEstimates.d.ts +32 -0
  43. package/dist/hooks/useEgressEstimates.js +230 -0
  44. package/dist/hooks/useHiddenSwapFees.d.ts +22 -0
  45. package/dist/hooks/useHiddenSwapFees.js +81 -0
  46. package/dist/hooks/useOrderEstimates.d.ts +37 -0
  47. package/dist/hooks/useOrderEstimates.js +393 -0
  48. package/dist/hooks/useOutputAssetInfo.d.ts +12 -0
  49. package/dist/hooks/useOutputAssetInfo.js +38 -0
  50. package/dist/hooks/usePrices.d.ts +60 -0
  51. package/dist/hooks/usePrices.js +188 -0
  52. package/dist/hooks/useQuote.d.ts +73 -0
  53. package/dist/hooks/useQuote.js +507 -0
  54. package/dist/hooks/useResetSwapForm.d.ts +16 -0
  55. package/dist/hooks/useResetSwapForm.js +68 -0
  56. package/dist/hooks/useSlippageUsd.d.ts +11 -0
  57. package/dist/hooks/useSlippageUsd.js +19 -0
  58. package/dist/hooks/useSolanaAdapter.d.ts +15 -0
  59. package/dist/hooks/useSolanaAdapter.js +55 -0
  60. package/dist/hooks/useStatus.d.ts +25 -0
  61. package/dist/hooks/useStatus.js +60 -0
  62. package/dist/hooks/useSwap.d.ts +67 -0
  63. package/dist/hooks/useSwap.js +285 -0
  64. package/dist/hooks/useTransaction.d.ts +119 -0
  65. package/dist/hooks/useTransaction.js +353 -0
  66. package/dist/hooks/useTransactionAddress.d.ts +11 -0
  67. package/dist/hooks/useTransactionAddress.js +26 -0
  68. package/dist/hooks/useUsdValue.d.ts +7 -0
  69. package/dist/hooks/useUsdValue.js +19 -0
  70. package/dist/index.d.ts +54 -0
  71. package/dist/index.js +41 -0
  72. package/dist/stories/SilentSwapOverview.stories.d.ts +10 -0
  73. package/dist/stories/SilentSwapOverview.stories.js +364 -0
  74. package/dist/stories/useAuth.stories.d.ts +6 -0
  75. package/dist/stories/useAuth.stories.js +55 -0
  76. package/dist/stories/useSilentClient.stories.d.ts +9 -0
  77. package/dist/stories/useSilentClient.stories.js +39 -0
  78. package/dist/stories/useSilentOrders.stories.d.ts +1 -0
  79. package/dist/stories/useSilentOrders.stories.js +1 -0
  80. package/dist/stories/useSilentQuote.stories.d.ts +6 -0
  81. package/dist/stories/useSilentQuote.stories.js +267 -0
  82. package/dist/stories/useTransaction.stories.d.ts +6 -0
  83. package/dist/stories/useTransaction.stories.js +121 -0
  84. package/dist/utils/formatters.d.ts +33 -0
  85. package/dist/utils/formatters.js +82 -0
  86. package/package.json +67 -0
@@ -0,0 +1,174 @@
1
+ import type { SilentSwapClient, AuthRequest, AuthResponse, NonceResponse, OrderRequest, OrderResponse, QuoteRequest, QuoteResponse } from '@silentswap/sdk';
2
+ export interface useSilentOrdersOptions {
3
+ client: SilentSwapClient;
4
+ }
5
+ export interface useSilentOrdersReturn {
6
+ isLoading: boolean;
7
+ error: Error | null;
8
+ getNonce: (address: `0x${string}`) => Promise<NonceResponse | null>;
9
+ /**
10
+ * Authenticates a user with SIWE (Sign-In with Ethereum)
11
+ *
12
+ * @param auth - Authentication request containing SIWE message and signature
13
+ * @returns Promise resolving to authentication response or null on error
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * const { authenticate } = useSilentOrders({ client });
18
+ *
19
+ * // First get a nonce for the user
20
+ * const nonceResponse = await getNonce('0x1234567890123456789012345678901234567890');
21
+ *
22
+ * // Create SIWE message (using useAuth hook)
23
+ * const siweMessage = createSignInMessage(
24
+ * '0x1234567890123456789012345678901234567890',
25
+ * nonceResponse.nonce,
26
+ * 'example.com'
27
+ * );
28
+ *
29
+ * // Sign the message with wallet
30
+ * const signature = await wallet.signMessage(siweMessage);
31
+ *
32
+ * // Authenticate
33
+ * const authResponse = await authenticate({
34
+ * siwe: {
35
+ * message: siweMessage,
36
+ * signature: signature as `0x${string}`
37
+ * }
38
+ * });
39
+ *
40
+ * if (authResponse) {
41
+ * console.log('Authenticated address:', authResponse.address);
42
+ * console.log('Secret token:', authResponse.secretToken);
43
+ * }
44
+ * ```
45
+ */
46
+ authenticate: (auth: AuthRequest) => Promise<AuthResponse | null>;
47
+ /**
48
+ * Gets a quote for a SilentSwap order
49
+ *
50
+ * @param quote - Quote request containing signer, viewer, and outputs
51
+ * @returns Promise resolving to quote response or null on error
52
+ *
53
+ * @example
54
+ * ```typescript
55
+ * const { getQuote } = useSilentOrders({ client });
56
+ * import {
57
+ * createHdFacilitatorGroupFromEntropy,
58
+ * FacilitatorKeyType,
59
+ * caip19FungibleEvmToken,
60
+ * PublicKeyArgGroups,
61
+ * DeliveryMethod,
62
+ * } from '@silentswap/sdk';
63
+ *
64
+ * // Generate entropy (in a real app, this would come from a secure source)
65
+ * const entropy = new Uint8Array(32);
66
+ * const random = crypto.getRandomValues(entropy);
67
+ *
68
+ * // Create HD facilitator group from entropy
69
+ * const group = await createHdFacilitatorGroupFromEntropy(random, 0);
70
+ *
71
+ * // Derive viewer account
72
+ * const viewer = await group.viewer();
73
+ *
74
+ * // Export its public key
75
+ * const { publicKeyBytes: pk65_viewer } = viewer.exportPublicKey('*', FacilitatorKeyType.SECP256K1);
76
+ *
77
+ * // Export public keys for the facilitator group
78
+ * const groupPublicKeys = await group.exportPublicKeys(1, [
79
+ * ...PublicKeyArgGroups.GENERIC,
80
+ * ]);
81
+ *
82
+ * // Define outputs
83
+ * const outputs = [{
84
+ * method: DeliveryMethod.SNIP,
85
+ * asset: caip19FungibleEvmToken(1, '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48'),
86
+ * facilitatorPublicKeys: groupPublicKeys[0],
87
+ * recipient: '0x461ddCA267968eB7A8191c0cDb1684a45b9250c9' as `0x${string}`,
88
+ * value: '10000000' as `${bigint}`,
89
+ * }];
90
+ *
91
+ * // Request a quote
92
+ * const quoteResponse = await getQuote({
93
+ * signer: '0x461ddCA267968eB7A8191c0cDb1684a45b9250c9' as `0x${string}`,
94
+ * viewer: pk65_viewer,
95
+ * outputs: outputs,
96
+ * });
97
+ *
98
+ * if (quoteResponse) {
99
+ * console.log('Quote ID:', quoteResponse.quoteId);
100
+ * // Store group for later use in order creation
101
+ * }
102
+ * ```
103
+ */
104
+ getQuote: (quote: QuoteRequest) => Promise<QuoteResponse | null>;
105
+ /**
106
+ * Creates a SilentSwap order by submitting a signed quote with all required authorizations
107
+ *
108
+ * @param order - Order request containing quote, signatures, and authorizations
109
+ * @returns Promise resolving to order response with deposit transaction or null on error
110
+ *
111
+ * @example
112
+ * ```typescript
113
+ * const { createOrder, getQuote } = useSilentOrders({ client });
114
+ * const { createEip712DocForOrder } = useAuth();
115
+ * import { createViemSigner } from '@silentswap/sdk';
116
+ * import type { AuthorizationInstruction } from '@silentswap/sdk';
117
+ *
118
+ * // Assume we have a quoteResponse and group from getQuote
119
+ * const quoteResponse = await getQuote({ /* ... *\/ });
120
+ * if (!quoteResponse) throw new Error('Failed to get quote');
121
+ *
122
+ * // Create signer (using viem/wagmi)
123
+ * const signer = createViemSigner(
124
+ * { address: connectedAddress, type: 'json-rpc' },
125
+ * walletClient
126
+ * );
127
+ *
128
+ * // Sign authorizations
129
+ * const signedAuths = await Promise.all(
130
+ * quoteResponse.authorizations.map(async (g_auth: AuthorizationInstruction) => ({
131
+ * ...g_auth,
132
+ * signature: await (async () => {
133
+ * if ('eip3009_deposit' === g_auth.type) {
134
+ * return await signer.signEip712TypedData(g_auth.eip712);
135
+ * }
136
+ * throw Error(`Authorization instruction type not implemented: ${g_auth.type}`);
137
+ * })(),
138
+ * }))
139
+ * );
140
+ *
141
+ * // Sign the order's EIP-712
142
+ * const orderDoc = createEip712DocForOrder(quoteResponse);
143
+ * const signedQuote = await signer.signEip712TypedData(orderDoc);
144
+ *
145
+ * // Approve proxy authorizations using the facilitator group
146
+ * const facilitatorReplies = await group.approveProxyAuthorizations(quoteResponse.facilitators, {
147
+ * proxyPublicKey: client.proxyPublicKey,
148
+ * });
149
+ *
150
+ * // Create the order
151
+ * const orderResponse = await createOrder({
152
+ * quote: quoteResponse.quote,
153
+ * quoteId: quoteResponse.quoteId,
154
+ * authorizations: signedAuths,
155
+ * eip712Domain: orderDoc.domain,
156
+ * signature: signedQuote,
157
+ * facilitators: facilitatorReplies,
158
+ * });
159
+ *
160
+ * if (orderResponse) {
161
+ * console.log('Placed order', orderResponse.response.orderId);
162
+ * // Use orderResponse.transaction to execute the deposit
163
+ * }
164
+ * ```
165
+ */
166
+ createOrder: (order: OrderRequest) => Promise<OrderResponse | null>;
167
+ }
168
+ /**
169
+ * React hook for managing SilentSwap orders and related operations
170
+ *
171
+ * @param options - Options containing the SilentSwap client
172
+ * @returns Object with order management methods and state
173
+ */
174
+ export declare function useSilentOrders({ client }: useSilentOrdersOptions): useSilentOrdersReturn;
@@ -0,0 +1,73 @@
1
+ import { useCallback, useState } from 'react';
2
+ /**
3
+ * React hook for managing SilentSwap orders and related operations
4
+ *
5
+ * @param options - Options containing the SilentSwap client
6
+ * @returns Object with order management methods and state
7
+ */
8
+ export function useSilentOrders({ client }) {
9
+ const [isLoading, setIsLoading] = useState(false);
10
+ const [error, setError] = useState(null);
11
+ const handleAsyncOperation = useCallback(async (operation, errorMessage) => {
12
+ setIsLoading(true);
13
+ setError(null);
14
+ try {
15
+ const result = await operation();
16
+ return result ?? null;
17
+ }
18
+ catch (err) {
19
+ const error = err instanceof Error ? err : new Error(errorMessage);
20
+ setError(error);
21
+ return null;
22
+ }
23
+ finally {
24
+ setIsLoading(false);
25
+ }
26
+ }, []);
27
+ const getNonce = useCallback(async (address) => {
28
+ return handleAsyncOperation(async () => {
29
+ const [error, response] = await client.nonce(address);
30
+ if (error) {
31
+ throw new Error(`Failed to get nonce: ${error.error}`);
32
+ }
33
+ return response;
34
+ }, 'Failed to fetch nonce');
35
+ }, [client, handleAsyncOperation]);
36
+ const authenticate = useCallback(async (auth) => {
37
+ return handleAsyncOperation(async () => {
38
+ const [error, response] = await client.authenticate(auth);
39
+ if (error) {
40
+ throw new Error(`Authentication failed: ${error.error}`);
41
+ }
42
+ return response;
43
+ }, 'Authentication failed');
44
+ }, [client, handleAsyncOperation]);
45
+ const getQuote = useCallback(async (quote) => {
46
+ return handleAsyncOperation(async () => {
47
+ const [error, response] = await client.quote(quote);
48
+ if (error) {
49
+ throw new Error(`Failed to get quote: ${error.error}`);
50
+ }
51
+ return response;
52
+ }, 'Failed to fetch quote');
53
+ }, [client, handleAsyncOperation]);
54
+ const createOrder = useCallback(async (order) => {
55
+ return handleAsyncOperation(async () => {
56
+ const [error, response] = await client.order(order);
57
+ if (error) {
58
+ throw new Error(`Failed to create order: ${error.error}`);
59
+ }
60
+ return response;
61
+ }, 'Failed to create order');
62
+ }, [client, handleAsyncOperation]);
63
+ return {
64
+ // State
65
+ isLoading,
66
+ error,
67
+ // Methods
68
+ getNonce,
69
+ authenticate,
70
+ getQuote,
71
+ createOrder,
72
+ };
73
+ }
@@ -0,0 +1,88 @@
1
+ import type { SilentSwapClient, QuoteResponse, AssetInfo } from '@silentswap/sdk';
2
+ import type { WalletClient } from 'viem';
3
+ import type { Connector } from 'wagmi';
4
+ import type { SolanaWalletConnector, SolanaConnection } from './solana-transaction.js';
5
+ import { type SwapTransaction } from '../useTransaction.js';
6
+ import type { SilentSwapWallet } from './useWallet.js';
7
+ export type { SwapTransaction };
8
+ export interface Destination {
9
+ asset: string;
10
+ contact: string;
11
+ amount: string;
12
+ priceUsd?: number;
13
+ }
14
+ /**
15
+ * Result of executing a swap
16
+ */
17
+ export interface SwapResult {
18
+ orderId: string;
19
+ viewingAuth: string;
20
+ depositTransaction: SwapTransaction;
21
+ bridgeTransaction?: SwapTransaction;
22
+ }
23
+ /**
24
+ * Options for useSilentQuote hook
25
+ */
26
+ export interface useSilentQuoteOptions {
27
+ /** EVM address */
28
+ evmAddress: `0x${string}` | string;
29
+ /** Solana address */
30
+ solAddress: string;
31
+ /** SilentSwap client instance */
32
+ client: SilentSwapClient;
33
+ /** User's address (EVM hex address or Solana base58 address) */
34
+ address: `0x${string}` | string;
35
+ /** Wallet client for signing operations */
36
+ walletClient?: WalletClient;
37
+ /** Wagmi connector */
38
+ connector?: Connector;
39
+ /** SilentSwap wallet instance */
40
+ wallet: SilentSwapWallet | null;
41
+ /** Whether wallet is currently being generated (to prevent swap execution before wallet is ready) */
42
+ walletLoading?: boolean;
43
+ /** Facilitator group for the swap, or a function that resolves it */
44
+ /** Status update callback */
45
+ onStatus?: (status: string) => void;
46
+ /** Solana wallet connector (required for Solana swaps) */
47
+ solanaConnector?: SolanaWalletConnector;
48
+ /** Solana RPC connection (required for Solana swaps) */
49
+ solanaConnection?: SolanaConnection;
50
+ /** Solana RPC URL (optional, will create connection if not provided) */
51
+ solanaRpcUrl?: string;
52
+ /** Get price function */
53
+ getPrice: (asset: AssetInfo) => Promise<number>;
54
+ setDestinations: (updater: Destination[] | ((prev: Destination[]) => Destination[])) => void;
55
+ }
56
+ /**
57
+ * Return type for useSilentQuote hook
58
+ */
59
+ export interface useSilentQuoteReturn {
60
+ isLoading: boolean;
61
+ isSwapping: boolean;
62
+ currentStep: string;
63
+ quote: QuoteResponse | null;
64
+ error: Error | null;
65
+ orderId: string | null;
66
+ viewingAuth: string | null;
67
+ executeSwap: (params: ExecuteSwapParams) => Promise<SwapResult | null>;
68
+ clearQuote: () => void;
69
+ loadingAmounts: boolean;
70
+ depositAmountUsdc: number;
71
+ }
72
+ /**
73
+ * Parameters for executing a swap
74
+ * Simplified interface - quote fetching and calculations are handled internally
75
+ */
76
+ export interface ExecuteSwapParams {
77
+ /** Source asset CAIP-19 identifier */
78
+ sourceAsset: string;
79
+ /** Source amount (in human-readable units, e.g., "1.5") */
80
+ sourceAmount: string;
81
+ /** Destinations array */
82
+ destinations: Destination[];
83
+ /** Splits array for destination amounts */
84
+ splits: number[];
85
+ /** Contact ID of the sender (e.g., "caip10:eip155:*:0x...") */
86
+ senderContactId: string;
87
+ }
88
+ export declare function useSilentQuote({ client, address, evmAddress, solAddress, walletClient, connector, wallet, walletLoading, onStatus, solanaConnector, solanaConnection, solanaRpcUrl, getPrice, setDestinations, }: useSilentQuoteOptions): useSilentQuoteReturn;