@silentswap/react 0.0.87 → 0.0.89

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.
@@ -1,12 +1,43 @@
1
1
  import React from 'react';
2
2
  import { type Connector } from 'wagmi';
3
3
  import { type WalletClient } from 'viem';
4
+ import type { PlatformHealthStatus } from '../hooks/usePlatformHealth.js';
4
5
  import { ENVIRONMENT, type SilentSwapClient, type SilentSwapClientConfig, type AuthResponse, type QuoteResponse, type CalculationDirection } from '@silentswap/sdk';
5
6
  import { type ExecuteSwapParams, type SwapResult } from '../hooks/silent/useSilentQuote.js';
6
7
  import { type OutputStatus } from '../hooks/silent/useOrderTracking.js';
7
8
  import { type SolanaWalletConnector, type SolanaConnection } from '../hooks/silent/solana-transaction.js';
8
9
  import { type BitcoinWalletConnector, type BitcoinConnection } from '../hooks/silent/bitcoin-transaction.js';
9
10
  import { type SilentSwapWallet } from '../hooks/silent/useWallet.js';
11
+ export interface SilentSwapStatusData {
12
+ platformHealth: PlatformHealthStatus | undefined;
13
+ serviceFeeRate: number;
14
+ overheadUsd: number;
15
+ minimumDepositUusdc: string | undefined;
16
+ maximumDepositUusdc: string | undefined;
17
+ outputLimit: number | undefined;
18
+ identity: string | undefined;
19
+ volume: number | undefined;
20
+ liquidity: number | undefined;
21
+ storage: Record<string, string> | undefined;
22
+ isLoading: boolean;
23
+ }
24
+ export interface SilentSwapFees {
25
+ serviceFeeUsd: number;
26
+ bridgeFeeIngressUsd: number;
27
+ bridgeFeeEgressUsd: number;
28
+ slippageUsd: number;
29
+ }
30
+ export interface SilentSwapOrderTracking {
31
+ progresses: (number | undefined)[];
32
+ statusTexts: string[];
33
+ isComplete: boolean;
34
+ error: Error | null;
35
+ outputs: OutputStatus[];
36
+ }
37
+ export interface SilentSwapEstimates {
38
+ isLoading: boolean;
39
+ fetchEstimates: (direction?: CalculationDirection) => Promise<void>;
40
+ }
10
41
  export interface SilentSwapContextType {
11
42
  client: SilentSwapClient;
12
43
  environment: ENVIRONMENT;
@@ -26,19 +57,10 @@ export interface SilentSwapContextType {
26
57
  clearQuote: () => void;
27
58
  depositAmountUsdc: number;
28
59
  loadingAmounts: boolean;
29
- orderProgresses: (number | undefined)[];
30
- orderStatusTexts: string[];
31
- orderComplete: boolean;
32
- orderTrackingError: Error | null;
33
- orderOutputs: OutputStatus[];
34
- serviceFeeUsd: number;
35
- bridgeFeeIngressUsd: number;
36
- bridgeFeeEgressUsd: number;
37
- slippageUsd: number;
38
- serviceFeeRate: number;
39
- overheadUsd: number;
40
- egressEstimatesLoading: boolean;
41
- fetchEstimates: (direction?: CalculationDirection) => Promise<void>;
60
+ status: SilentSwapStatusData;
61
+ fees: SilentSwapFees;
62
+ order: SilentSwapOrderTracking;
63
+ estimates: SilentSwapEstimates;
42
64
  handleNewSwap: () => void;
43
65
  solanaRpcUrl?: string;
44
66
  }
@@ -40,19 +40,36 @@ const DEFAULT_CONTEXT = {
40
40
  clearQuote: () => { },
41
41
  depositAmountUsdc: 0,
42
42
  loadingAmounts: false,
43
- orderProgresses: [],
44
- orderStatusTexts: [],
45
- orderComplete: false,
46
- orderTrackingError: null,
47
- orderOutputs: [],
48
- serviceFeeUsd: 0,
49
- bridgeFeeIngressUsd: 0,
50
- bridgeFeeEgressUsd: 0,
51
- slippageUsd: 0,
52
- serviceFeeRate: 0,
53
- overheadUsd: 0,
54
- egressEstimatesLoading: false,
55
- fetchEstimates: async (_direction) => { },
43
+ status: {
44
+ platformHealth: undefined,
45
+ serviceFeeRate: 0,
46
+ overheadUsd: 0,
47
+ minimumDepositUusdc: undefined,
48
+ maximumDepositUusdc: undefined,
49
+ outputLimit: undefined,
50
+ identity: undefined,
51
+ volume: undefined,
52
+ liquidity: undefined,
53
+ storage: undefined,
54
+ isLoading: true,
55
+ },
56
+ fees: {
57
+ serviceFeeUsd: 0,
58
+ bridgeFeeIngressUsd: 0,
59
+ bridgeFeeEgressUsd: 0,
60
+ slippageUsd: 0,
61
+ },
62
+ order: {
63
+ progresses: [],
64
+ statusTexts: [],
65
+ isComplete: false,
66
+ error: null,
67
+ outputs: [],
68
+ },
69
+ estimates: {
70
+ isLoading: false,
71
+ fetchEstimates: async (_direction) => { },
72
+ },
56
73
  handleNewSwap: () => { },
57
74
  };
58
75
  const SilentSwapContext = createContext(DEFAULT_CONTEXT);
@@ -93,7 +110,7 @@ function SilentSwapInnerProvider({ children, client, evmAddress, solAddress, bit
93
110
  const transactionAddress = useTransactionAddress(tokenIn, evmAddress, solAddress, bitcoinAddress);
94
111
  const effectiveQuoteAddress = transactionAddress;
95
112
  const { getPrice } = usePrices();
96
- const { serviceFeeRate, overheadUsd } = useStatus();
113
+ const { serviceFeeRate, overheadUsd, platformHealth: statusPlatformHealth, minimumDepositUusdc, maximumDepositUusdc, outputLimit, identity, volume, liquidity, storage, isLoading: statusLoading, } = useStatus({ baseUrl: config.baseUrl ?? '', environment: config.environment, proId });
97
114
  const { fetchEstimates, isLoading: egressEstimatesLoading, egressQuotes: egressQuotesFromEstimates, ingressQuote: ingressQuoteFromEstimates, depositAmountUsd: depositAmountUsdFromEstimates, bridgeProviderFromQuote, usdcPrice: usdcPriceFromEstimates, } = useEgressEstimates({
98
115
  evmAddress,
99
116
  solAddress,
@@ -206,19 +223,36 @@ function SilentSwapInnerProvider({ children, client, evmAddress, solAddress, bit
206
223
  clearQuote,
207
224
  depositAmountUsdc,
208
225
  loadingAmounts,
209
- orderProgresses,
210
- orderStatusTexts,
211
- orderComplete,
212
- orderTrackingError,
213
- orderOutputs,
214
- serviceFeeUsd: effectiveServiceFeeUsd,
215
- bridgeFeeIngressUsd: effectiveBridgeFeeIngressUsd,
216
- bridgeFeeEgressUsd: effectiveBridgeFeeEgressUsd,
217
- slippageUsd,
218
- serviceFeeRate,
219
- overheadUsd,
220
- egressEstimatesLoading,
221
- fetchEstimates,
226
+ status: {
227
+ platformHealth: statusPlatformHealth,
228
+ serviceFeeRate,
229
+ overheadUsd,
230
+ minimumDepositUusdc,
231
+ maximumDepositUusdc,
232
+ outputLimit,
233
+ identity,
234
+ volume,
235
+ liquidity,
236
+ storage,
237
+ isLoading: statusLoading,
238
+ },
239
+ fees: {
240
+ serviceFeeUsd: effectiveServiceFeeUsd,
241
+ bridgeFeeIngressUsd: effectiveBridgeFeeIngressUsd,
242
+ bridgeFeeEgressUsd: effectiveBridgeFeeEgressUsd,
243
+ slippageUsd,
244
+ },
245
+ order: {
246
+ progresses: orderProgresses,
247
+ statusTexts: orderStatusTexts,
248
+ isComplete: orderComplete,
249
+ error: orderTrackingError,
250
+ outputs: orderOutputs,
251
+ },
252
+ estimates: {
253
+ isLoading: egressEstimatesLoading,
254
+ fetchEstimates,
255
+ },
222
256
  handleNewSwap,
223
257
  solanaRpcUrl,
224
258
  }, children: children });
@@ -28,8 +28,8 @@ export type PlatformHealthContextType = {
28
28
  export type PlatformHealthProviderProps = {
29
29
  children: React.ReactNode;
30
30
  /**
31
- * Pro user ID for volume tracking (from ?pro= URL or localStorage silentswap:pro).
32
- * When set, status is fetched with ?pro= and identity/volume/liquidity are returned.
31
+ * @deprecated proId is now read from the parent SilentSwapContext (passed via SilentSwapProvider).
32
+ * This prop is ignored.
33
33
  */
34
34
  proId?: string;
35
35
  /**
@@ -44,10 +44,11 @@ export type PlatformHealthProviderProps = {
44
44
  onTrackingDisabledChange?: (disabled: boolean) => void;
45
45
  };
46
46
  /**
47
- * Provider that monitors platform health from status API and provides validation functions
48
- * for deposit amounts, output limits, and service fee rates
47
+ * Provider that monitors platform health from SilentSwapContext (which calls useStatus
48
+ * once with proId) and provides validation functions for deposit amounts, output limits,
49
+ * and service fee rates.
49
50
  */
50
- export declare function PlatformHealthProvider({ children, proId, onFormDisabledChange, onTrackingDisabledChange, }: PlatformHealthProviderProps): import("react/jsx-runtime").JSX.Element;
51
+ export declare function PlatformHealthProvider({ children, onFormDisabledChange, onTrackingDisabledChange, }: PlatformHealthProviderProps): import("react/jsx-runtime").JSX.Element;
51
52
  /**
52
53
  * Hook to access platform health context
53
54
  */
@@ -1,16 +1,19 @@
1
1
  'use client';
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import React, { createContext, useContext, useEffect, useMemo, useCallback } from 'react';
4
- import { useStatus } from '../hooks/useStatus.js';
4
+ import { useSilentSwap } from '../contexts/SilentSwapContext.js';
5
5
  import { BigNumber } from 'bignumber.js';
6
6
  const MAX_DEPOSIT_USD = 25000;
7
7
  const PlatformHealthContext = createContext(undefined);
8
8
  /**
9
- * Provider that monitors platform health from status API and provides validation functions
10
- * for deposit amounts, output limits, and service fee rates
9
+ * Provider that monitors platform health from SilentSwapContext (which calls useStatus
10
+ * once with proId) and provides validation functions for deposit amounts, output limits,
11
+ * and service fee rates.
11
12
  */
12
- export function PlatformHealthProvider({ children, proId, onFormDisabledChange, onTrackingDisabledChange, }) {
13
- const { platformHealth: statusPlatformHealth, maximumDepositUusdc, minimumDepositUusdc, outputLimit, serviceFeeRate, overheadUsd, identity, volume, liquidity, storage, } = useStatus(proId != null ? { proId } : undefined);
13
+ export function PlatformHealthProvider({ children, onFormDisabledChange, onTrackingDisabledChange, }) {
14
+ // Consume status data from parent SilentSwapContext instead of calling useStatus again
15
+ const { status } = useSilentSwap();
16
+ const { platformHealth: statusPlatformHealth, maximumDepositUusdc, minimumDepositUusdc, outputLimit, serviceFeeRate, overheadUsd, identity, volume, liquidity, storage, } = status;
14
17
  // Normalize platform health status
15
18
  const platformHealth = useMemo(() => {
16
19
  if (!statusPlatformHealth)
@@ -88,14 +91,12 @@ export function PlatformHealthProvider({ children, proId, onFormDisabledChange,
88
91
  }
89
92
  }, [maximumDepositUusdc]);
90
93
  const getServiceFeeRate = useCallback(() => {
91
- if (!serviceFeeRate)
94
+ if (serviceFeeRate == null)
92
95
  return 0.01;
93
- try {
94
- return +serviceFeeRate || 0.01;
95
- }
96
- catch {
96
+ const rate = +serviceFeeRate;
97
+ if (isNaN(rate))
97
98
  return 0.01;
98
- }
99
+ return rate;
99
100
  }, [serviceFeeRate]);
100
101
  // Validate deposit amount against min/max limits
101
102
  const validateDepositAmount = useCallback((usdAmount) => {
@@ -12,14 +12,20 @@ export interface StatusResponse {
12
12
  storage?: Record<string, string>;
13
13
  }
14
14
  export interface UseStatusOptions {
15
+ /** Base URL for the status endpoint (e.g. https://api.silentswap.io) */
16
+ baseUrl: string;
17
+ /** Environment name, used to re-fetch when environment changes */
18
+ environment: string;
15
19
  /** Pro user ID for volume tracking (from ?pro= URL or localStorage) */
16
20
  proId?: string;
17
21
  }
18
22
  /**
19
- * Hook to fetch the current platform status, fee rates, and limits
20
- * When proId is provided, fetches with ?pro= for pro user volume tracking and returns identity/volume/liquidity.
23
+ * Hook to fetch the current platform status, fee rates, and limits.
24
+ * Requires baseUrl and environment to be passed directly (since this hook
25
+ * is called inside SilentSwapInnerProvider before the context is available).
26
+ * When proId is provided, fetches with ?pro= for pro user volume tracking.
21
27
  */
22
- export declare function useStatus(options?: UseStatusOptions): {
28
+ export declare function useStatus(options: UseStatusOptions): {
23
29
  status: StatusResponse;
24
30
  isLoading: boolean;
25
31
  error: Error | null;
@@ -1,72 +1,62 @@
1
1
  import { useState, useEffect } from 'react';
2
- import { useSilentSwap } from '../contexts/SilentSwapContext.js';
2
+ // Module-level cache: survives component unmount/remount and Strict Mode cycles.
3
+ // Keyed by fetch params so a new fetch only happens when params actually change.
4
+ let statusCache = null;
3
5
  /**
4
- * Hook to fetch the current platform status, fee rates, and limits
5
- * When proId is provided, fetches with ?pro= for pro user volume tracking and returns identity/volume/liquidity.
6
+ * Hook to fetch the current platform status, fee rates, and limits.
7
+ * Requires baseUrl and environment to be passed directly (since this hook
8
+ * is called inside SilentSwapInnerProvider before the context is available).
9
+ * When proId is provided, fetches with ?pro= for pro user volume tracking.
6
10
  */
7
11
  export function useStatus(options) {
8
- const { config, client } = useSilentSwap();
9
- const baseUrl = config.baseUrl;
10
- const proId = options?.proId;
11
- const [status, setStatus] = useState({});
12
- const [isLoading, setIsLoading] = useState(true);
12
+ const { baseUrl, environment, proId } = options;
13
+ const fetchKey = `${baseUrl}|${environment}|${proId ?? ''}`;
14
+ const [status, setStatus] = useState(() => statusCache?.key === fetchKey && statusCache.data ? statusCache.data : {});
15
+ const [isLoading, setIsLoading] = useState(() => !(statusCache?.key === fetchKey && statusCache.data && Object.keys(statusCache.data).length > 0));
13
16
  const [error, setError] = useState(null);
14
17
  useEffect(() => {
15
- // Skip if baseUrl is not yet available (shouldn't happen, but safety check)
16
- if (!baseUrl) {
17
- console.warn('[useStatus] baseUrl is not available yet');
18
+ if (!baseUrl)
18
19
  return;
19
- }
20
- // Skip if we're using the default/placeholder context
21
- // The DEFAULT_CONTEXT has client: {} as SilentSwapClient (empty object placeholder)
22
- // Real SilentSwapClient instances are class instances, not plain objects
23
- // Check if client is the placeholder by verifying it's a plain empty object
24
- const isPlaceholderClient = client &&
25
- typeof client === 'object' &&
26
- Object.getPrototypeOf(client) === Object.prototype &&
27
- Object.keys(client).length === 0;
28
- if (isPlaceholderClient) {
29
- console.warn('[useStatus] Context not yet initialized (placeholder client detected), skipping fetch until real context is available');
30
- setIsLoading(false);
31
- return;
32
- }
33
- let isMounted = true;
34
- const fetchStatus = async () => {
35
- try {
36
- setIsLoading(true);
37
- const search = proId ? `?${new URLSearchParams({ pro: proId }).toString()}` : '';
38
- const statusUrl = `${baseUrl}/status${search}`;
39
- console.log('[useStatus] Fetching status from:', statusUrl, 'environment:', config.environment);
40
- const response = await fetch(statusUrl);
41
- if (!response.ok) {
42
- throw new Error(`Failed to fetch status: ${response.statusText}`);
43
- }
44
- const data = await response.json();
45
- if (isMounted) {
46
- console.log('[useStatus] Status fetched successfully from:', statusUrl);
20
+ // Already fetched or in-flight for this exact param set — skip
21
+ if (statusCache?.key === fetchKey) {
22
+ if (statusCache.promise) {
23
+ // In-flight from another mount wait for it and apply
24
+ statusCache.promise.then((data) => {
47
25
  setStatus(data);
48
- setError(null);
49
- }
50
- }
51
- catch (err) {
52
- if (isMounted) {
53
- console.error('[useStatus] Failed to fetch status from:', baseUrl, err);
54
- setError(err instanceof Error ? err : new Error('Failed to fetch status'));
55
- // Use defaults on error
56
- setStatus({});
57
- }
58
- }
59
- finally {
60
- if (isMounted) {
61
26
  setIsLoading(false);
62
- }
27
+ });
63
28
  }
64
- };
65
- fetchStatus();
66
- return () => {
67
- isMounted = false;
68
- };
69
- }, [baseUrl, config.environment, proId]);
29
+ return;
30
+ }
31
+ const search = proId ? `?${new URLSearchParams({ pro: proId }).toString()}` : '';
32
+ const statusUrl = `${baseUrl}/status${search}`;
33
+ console.log('[useStatus] Fetching status from:', statusUrl, 'environment:', environment);
34
+ const promise = fetch(statusUrl)
35
+ .then((response) => {
36
+ if (!response.ok)
37
+ throw new Error(`Failed to fetch status: ${response.statusText}`);
38
+ return response.json();
39
+ })
40
+ .then((data) => {
41
+ console.log('[useStatus] Status fetched successfully from:', statusUrl);
42
+ statusCache = { key: fetchKey, data };
43
+ setStatus(data);
44
+ setError(null);
45
+ return data;
46
+ })
47
+ .catch((err) => {
48
+ console.error('[useStatus] Failed to fetch status from:', baseUrl, err);
49
+ setError(err instanceof Error ? err : new Error('Failed to fetch status'));
50
+ setStatus({});
51
+ statusCache = null; // Allow retry
52
+ return {};
53
+ })
54
+ .finally(() => {
55
+ setIsLoading(false);
56
+ });
57
+ // Claim the slot immediately so no other mount starts a duplicate
58
+ statusCache = { key: fetchKey, data: {}, promise };
59
+ }, [baseUrl, environment, proId, fetchKey]);
70
60
  // Convert overheadUsd from string to number
71
61
  const overheadUsd = status.overheadUsd ? parseFloat(status.overheadUsd) : 0;
72
62
  // serviceFeeRate is a Decimal (0.01 = 1%), convert to number
package/dist/index.d.ts CHANGED
@@ -10,7 +10,7 @@ export type { BalancesContextType, UserBalance } from './contexts/BalancesContex
10
10
  export { OrdersProvider, useOrdersContext, useWalletFacilitatorGroups } from './contexts/OrdersContext.js';
11
11
  export type { OrdersContextOrderMetadata, OrdersContextOrder, OrderDestination, FacilitatorGroup, OrdersContextType } from './contexts/OrdersContext.js';
12
12
  export { SilentSwapProvider, useSilentSwap } from './contexts/SilentSwapContext.js';
13
- export type { SilentSwapContextType } from './contexts/SilentSwapContext.js';
13
+ export type { SilentSwapContextType, SilentSwapStatusData, SilentSwapFees, SilentSwapOrderTracking, SilentSwapEstimates, } from './contexts/SilentSwapContext.js';
14
14
  export { useSilentOrders } from './hooks/silent/useSilentOrders.js';
15
15
  export { useAuth } from './hooks/silent/useAuth.js';
16
16
  export { useWallet } from './hooks/silent/useWallet.js';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@silentswap/react",
3
3
  "type": "module",
4
- "version": "0.0.87",
4
+ "version": "0.0.89",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
@@ -24,8 +24,8 @@
24
24
  "dependencies": {
25
25
  "@bigmi/core": "^0.6.5",
26
26
  "@ensdomains/ensjs": "^4.2.0",
27
- "@silentswap/sdk": "0.0.87",
28
- "@silentswap/ui-kit": "0.0.87",
27
+ "@silentswap/sdk": "0.0.89",
28
+ "@silentswap/ui-kit": "0.0.89",
29
29
  "@solana/codecs-strings": "^5.1.0",
30
30
  "@solana/kit": "^5.1.0",
31
31
  "@solana/rpc": "^5.1.0",