@liberfi.io/ui-trade 0.1.2 → 0.1.4
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/README.md +194 -3
- package/dist/index.d.mts +319 -2
- package/dist/index.d.ts +319 -2
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +12 -9
package/dist/index.d.ts
CHANGED
|
@@ -2,6 +2,8 @@ import * as _liberfi_io_types from '@liberfi.io/types';
|
|
|
2
2
|
import { Chain, API, Token, Portfolio } from '@liberfi.io/types';
|
|
3
3
|
import { WalletAdapter } from '@liberfi.io/wallet-connector';
|
|
4
4
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
5
|
+
import { ReactNode } from 'react';
|
|
6
|
+
import { PredefinedToken } from '@liberfi.io/utils';
|
|
5
7
|
|
|
6
8
|
/**
|
|
7
9
|
* Input parameters for the `swap()` function returned by {@link useSwap}.
|
|
@@ -61,6 +63,33 @@ interface UseSwapRoutePollingOptions {
|
|
|
61
63
|
/** Called when a route fetch fails. */
|
|
62
64
|
onError?: (error: Error) => void;
|
|
63
65
|
}
|
|
66
|
+
/** Configuration values for a single trade preset (slippage, fees, MEV). */
|
|
67
|
+
interface TradePresetValues {
|
|
68
|
+
/** Slippage tolerance, 0-100 (percent). `null` = use default. */
|
|
69
|
+
slippage: number | null;
|
|
70
|
+
/** Priority fee in native token units. `null` = use default. */
|
|
71
|
+
priorityFee: number | null;
|
|
72
|
+
/** Tip fee in native token units. `null` = use default. */
|
|
73
|
+
tipFee: number | null;
|
|
74
|
+
/** Whether automatic fee estimation is enabled. */
|
|
75
|
+
autoFee: boolean;
|
|
76
|
+
/** Maximum fee cap when auto-fee is on (native token units). */
|
|
77
|
+
maxAutoFee: number | null;
|
|
78
|
+
/** Anti-MEV protection level. */
|
|
79
|
+
antiMev: "off" | "reduced" | "secure";
|
|
80
|
+
/** Custom RPC endpoint URL. `null` = use default. */
|
|
81
|
+
customRPC: string | null;
|
|
82
|
+
}
|
|
83
|
+
/** Default preset values matching Solana-typical settings. */
|
|
84
|
+
declare const DEFAULT_TRADE_PRESET: TradePresetValues;
|
|
85
|
+
/** Default preset values for EVM chains (gas fee in Gwei). */
|
|
86
|
+
declare const DEFAULT_EVM_TRADE_PRESET: TradePresetValues;
|
|
87
|
+
/** Default preset values for BSC (gas in Gwei + tip in BNB). */
|
|
88
|
+
declare const DEFAULT_BSC_TRADE_PRESET: TradePresetValues;
|
|
89
|
+
/** Default quick-buy amounts (native token units). */
|
|
90
|
+
declare const DEFAULT_BUY_AMOUNTS: number[];
|
|
91
|
+
/** Default quick-sell percentages. */
|
|
92
|
+
declare const DEFAULT_SELL_PERCENTAGES: number[];
|
|
64
93
|
/** Confirmation status of a tracked transaction. */
|
|
65
94
|
type TxConfirmationStatus = "idle" | "pending" | "confirmed" | "failed";
|
|
66
95
|
/** Options for the {@link useTxConfirmation} hook. */
|
|
@@ -317,6 +346,294 @@ declare function SwapUI({ fromToken, toToken, fromBalance, toBalance, amount, am
|
|
|
317
346
|
*/
|
|
318
347
|
declare function SwapPreviewModal({ isOpen, onOpenChange, fromToken, toToken, fromBalance, inputAmount, inputAmountInUsd, outputAmount, outputAmountInUsd, route, isRouting, routeError, onConfirm, isSwapping, }: SwapPreviewModalProps): react_jsx_runtime.JSX.Element;
|
|
319
348
|
|
|
349
|
+
/** Parameters for {@link useInstantTradeScript}. */
|
|
350
|
+
interface UseInstantTradeScriptParams {
|
|
351
|
+
/** Target chain */
|
|
352
|
+
chain: Chain;
|
|
353
|
+
/** Address of the token being traded (the non-native side) */
|
|
354
|
+
tokenAddress: string;
|
|
355
|
+
/** Called when a swap transaction is successfully submitted */
|
|
356
|
+
onSwapSubmitted?: (result: SwapResult) => void;
|
|
357
|
+
/** Called when a swap error occurs at any phase */
|
|
358
|
+
onSwapError?: (error: Error, phase: SwapPhase) => void;
|
|
359
|
+
}
|
|
360
|
+
/** Return value of {@link useInstantTradeScript}. */
|
|
361
|
+
interface UseInstantTradeScriptResult {
|
|
362
|
+
chain: Chain;
|
|
363
|
+
tokenAddress: string;
|
|
364
|
+
nativeToken: PredefinedToken | undefined;
|
|
365
|
+
tokenInfo: Token | null;
|
|
366
|
+
nativeBalance: Portfolio | null;
|
|
367
|
+
tokenBalance: Portfolio | null;
|
|
368
|
+
direction: "buy" | "sell";
|
|
369
|
+
setDirection: (d: "buy" | "sell") => void;
|
|
370
|
+
amount: number | undefined;
|
|
371
|
+
setAmount: (v: number | undefined) => void;
|
|
372
|
+
buyPreset: number;
|
|
373
|
+
setBuyPreset: (p: number) => void;
|
|
374
|
+
sellPreset: number;
|
|
375
|
+
setSellPreset: (p: number) => void;
|
|
376
|
+
currentPresetValues: TradePresetValues;
|
|
377
|
+
settings: InstantTradeSettings;
|
|
378
|
+
updateBuySettings: (s: BuySettings) => void;
|
|
379
|
+
updateSellSettings: (s: SellSettings) => void;
|
|
380
|
+
showSettings: boolean;
|
|
381
|
+
handlePresetClick: (preset: number) => void;
|
|
382
|
+
swap: () => Promise<void>;
|
|
383
|
+
isSwapping: boolean;
|
|
384
|
+
submitText: string;
|
|
385
|
+
isDisabled: boolean;
|
|
386
|
+
isLoading: boolean;
|
|
387
|
+
}
|
|
388
|
+
/** Props for {@link InstantTradeWidget}. */
|
|
389
|
+
interface InstantTradeWidgetProps {
|
|
390
|
+
/** Target chain */
|
|
391
|
+
chain: Chain;
|
|
392
|
+
/** Address of the token being traded */
|
|
393
|
+
tokenAddress: string;
|
|
394
|
+
/** Called when a swap transaction is submitted */
|
|
395
|
+
onSwapSubmitted?: (result: SwapResult) => void;
|
|
396
|
+
/** Called on swap error */
|
|
397
|
+
onSwapError?: (error: Error, phase: SwapPhase) => void;
|
|
398
|
+
/** Controlled settings (omit for localStorage fallback) */
|
|
399
|
+
settings?: InstantTradeSettings;
|
|
400
|
+
/** Called when settings change */
|
|
401
|
+
onSettingsChange?: (settings: InstantTradeSettings) => void;
|
|
402
|
+
/** Slot rendered next to trade-type tabs (e.g. wallet switcher) */
|
|
403
|
+
headerExtra?: ReactNode;
|
|
404
|
+
/** External style customization */
|
|
405
|
+
className?: string;
|
|
406
|
+
}
|
|
407
|
+
/** Props for {@link InstantTradeUI}. */
|
|
408
|
+
interface InstantTradeUIProps {
|
|
409
|
+
chain: Chain;
|
|
410
|
+
direction: "buy" | "sell";
|
|
411
|
+
onDirectionChange: (d: "buy" | "sell") => void;
|
|
412
|
+
amount: number | undefined;
|
|
413
|
+
onAmountChange: (v: number | undefined) => void;
|
|
414
|
+
customAmounts: (number | null)[];
|
|
415
|
+
customPercentages: (number | null)[];
|
|
416
|
+
onQuickAmountClick: (v: number) => void;
|
|
417
|
+
onQuickPercentageClick: (percent: number) => void;
|
|
418
|
+
onCustomAmountsEdit: (amounts: (number | null)[]) => void;
|
|
419
|
+
onCustomPercentagesEdit: (pcts: (number | null)[]) => void;
|
|
420
|
+
tokenSymbol?: string;
|
|
421
|
+
nativeSymbol?: string;
|
|
422
|
+
nativeDecimals?: number;
|
|
423
|
+
nativeBalance?: string;
|
|
424
|
+
tokenBalance?: string;
|
|
425
|
+
amountConversion?: string;
|
|
426
|
+
preset: number;
|
|
427
|
+
onPresetChange: (p: number) => void;
|
|
428
|
+
presetValues: TradePresetValues;
|
|
429
|
+
onPresetSettingsChange: (v: TradePresetValues) => void;
|
|
430
|
+
showSettings: boolean;
|
|
431
|
+
onPresetClick: (preset: number) => void;
|
|
432
|
+
submitText: string;
|
|
433
|
+
isDisabled: boolean;
|
|
434
|
+
isLoading: boolean;
|
|
435
|
+
onSubmit: () => void;
|
|
436
|
+
className?: string;
|
|
437
|
+
headerExtra?: ReactNode;
|
|
438
|
+
}
|
|
439
|
+
/** Value exposed by {@link InstantTradeContext}. */
|
|
440
|
+
interface InstantTradeContextValue {
|
|
441
|
+
chain: Chain;
|
|
442
|
+
tokenAddress: string;
|
|
443
|
+
nativeToken: PredefinedToken | undefined;
|
|
444
|
+
direction: "buy" | "sell";
|
|
445
|
+
setDirection: (d: "buy" | "sell") => void;
|
|
446
|
+
/** Quick-trade amount (native token units for buy, token units for sell). */
|
|
447
|
+
amount: number | undefined;
|
|
448
|
+
setAmount: (v: number | undefined) => void;
|
|
449
|
+
buyPreset: number;
|
|
450
|
+
setBuyPreset: (p: number) => void;
|
|
451
|
+
sellPreset: number;
|
|
452
|
+
setSellPreset: (p: number) => void;
|
|
453
|
+
settings: InstantTradeSettings;
|
|
454
|
+
updateBuySettings: (s: BuySettings) => void;
|
|
455
|
+
updateSellSettings: (s: SellSettings) => void;
|
|
456
|
+
currentPresetValues: TradePresetValues;
|
|
457
|
+
}
|
|
458
|
+
/** Props for {@link InstantTradeProvider}. */
|
|
459
|
+
interface InstantTradeProviderProps {
|
|
460
|
+
/** Target chain */
|
|
461
|
+
chain: Chain;
|
|
462
|
+
/** Address of the token being traded */
|
|
463
|
+
tokenAddress: string;
|
|
464
|
+
/** Controlled settings (omit for built-in localStorage persistence) */
|
|
465
|
+
settings?: InstantTradeSettings;
|
|
466
|
+
/** Called when settings change */
|
|
467
|
+
onSettingsChange?: (settings: InstantTradeSettings) => void;
|
|
468
|
+
children: ReactNode;
|
|
469
|
+
}
|
|
470
|
+
/** Props for {@link InstantTradeAmountInput}. */
|
|
471
|
+
interface InstantTradeAmountInputProps {
|
|
472
|
+
amount?: number;
|
|
473
|
+
onAmountChange: (amount?: number) => void;
|
|
474
|
+
preset?: number;
|
|
475
|
+
onPresetChange?: (preset: number) => void;
|
|
476
|
+
/** Called when an already-selected preset is clicked (e.g. open settings) */
|
|
477
|
+
onPresetClick?: (preset: number) => void;
|
|
478
|
+
variant?: "default" | "bordered";
|
|
479
|
+
radius?: "full" | "lg" | "md" | "sm";
|
|
480
|
+
size?: "sm" | "lg";
|
|
481
|
+
fullWidth?: boolean;
|
|
482
|
+
className?: string;
|
|
483
|
+
}
|
|
484
|
+
/** Props for {@link InstantTradeButton}. */
|
|
485
|
+
interface InstantTradeButtonProps {
|
|
486
|
+
className?: string;
|
|
487
|
+
children?: ReactNode;
|
|
488
|
+
}
|
|
489
|
+
/** Props for {@link PresetFormUI}. */
|
|
490
|
+
interface PresetFormUIProps {
|
|
491
|
+
value: TradePresetValues;
|
|
492
|
+
onChange: (value: TradePresetValues) => void;
|
|
493
|
+
/** Target chain — determines which fields are shown (e.g. anti-MEV for Solana only). */
|
|
494
|
+
chain: Chain;
|
|
495
|
+
nativeSymbol?: string;
|
|
496
|
+
nativeDecimals?: number;
|
|
497
|
+
className?: string;
|
|
498
|
+
}
|
|
499
|
+
/** Props for {@link PresetFormWidget}. */
|
|
500
|
+
interface PresetFormWidgetProps {
|
|
501
|
+
value: TradePresetValues;
|
|
502
|
+
onChange: (value: TradePresetValues) => void;
|
|
503
|
+
chain: Chain;
|
|
504
|
+
className?: string;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** Buy-side trade settings. */
|
|
508
|
+
interface BuySettings {
|
|
509
|
+
/** Four customizable quick-amount buttons (native token units) */
|
|
510
|
+
customAmounts: (number | null)[];
|
|
511
|
+
/** Three preset configurations */
|
|
512
|
+
presets: TradePresetValues[];
|
|
513
|
+
}
|
|
514
|
+
/** Sell-side trade settings. */
|
|
515
|
+
interface SellSettings {
|
|
516
|
+
/** Four customizable quick-percentage buttons (0-100) */
|
|
517
|
+
customPercentages: (number | null)[];
|
|
518
|
+
/** Three preset configurations */
|
|
519
|
+
presets: TradePresetValues[];
|
|
520
|
+
}
|
|
521
|
+
/** Combined buy + sell settings for instant trade. */
|
|
522
|
+
interface InstantTradeSettings {
|
|
523
|
+
buy: BuySettings;
|
|
524
|
+
sell: SellSettings;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
declare const DEFAULT_INSTANT_TRADE_SETTINGS: InstantTradeSettings;
|
|
528
|
+
/** Access the nearest {@link InstantTradeProvider}. Throws if none found. */
|
|
529
|
+
declare function useInstantTrade(): InstantTradeContextValue;
|
|
530
|
+
/**
|
|
531
|
+
* Provides instant-trade state to descendant components.
|
|
532
|
+
*
|
|
533
|
+
* Settings follow a controlled / uncontrolled pattern:
|
|
534
|
+
* - **Controlled**: pass `settings` + `onSettingsChange` props.
|
|
535
|
+
* - **Uncontrolled** (default): settings auto-persist to localStorage keyed by chain.
|
|
536
|
+
*/
|
|
537
|
+
declare function InstantTradeProvider({ chain, tokenAddress, settings: controlledSettings, onSettingsChange, children, }: InstantTradeProviderProps): react_jsx_runtime.JSX.Element;
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* Script hook that encapsulates all data and state for the instant trade form.
|
|
541
|
+
*
|
|
542
|
+
* Must be used inside an {@link InstantTradeProvider}.
|
|
543
|
+
* Pure TypeScript — no JSX, no UI imports.
|
|
544
|
+
*/
|
|
545
|
+
declare function useInstantTradeScript(params: UseInstantTradeScriptParams): UseInstantTradeScriptResult;
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* Full instant-trade widget — thin orchestration layer.
|
|
549
|
+
*
|
|
550
|
+
* Wraps `InstantTradeProvider`, calls `useInstantTradeScript` to get all data,
|
|
551
|
+
* and renders `InstantTradeUI` as the presentational layer.
|
|
552
|
+
*
|
|
553
|
+
* For custom UIs, use `useInstantTradeScript` directly inside an
|
|
554
|
+
* `InstantTradeProvider` with your own presentation.
|
|
555
|
+
*/
|
|
556
|
+
declare function InstantTradeWidget({ chain, tokenAddress, onSwapSubmitted, onSwapError, settings, onSettingsChange, headerExtra, className, }: InstantTradeWidgetProps): react_jsx_runtime.JSX.Element;
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* Preset form widget — thin orchestration layer.
|
|
560
|
+
*
|
|
561
|
+
* Manages local state initialized from `value`, resolves chain-specific
|
|
562
|
+
* native token info, and syncs changes upward via `onChange`.
|
|
563
|
+
*/
|
|
564
|
+
declare function PresetFormWidget({ value, onChange, chain, className, }: PresetFormWidgetProps): react_jsx_runtime.JSX.Element;
|
|
565
|
+
|
|
566
|
+
/**
|
|
567
|
+
* Pure presentational component for the instant trade form.
|
|
568
|
+
*
|
|
569
|
+
* Receives all data and callbacks via props — no API calls, no context access.
|
|
570
|
+
* Consumers can replace this component while reusing `useInstantTradeScript`.
|
|
571
|
+
*/
|
|
572
|
+
declare function InstantTradeUI({ chain, direction, onDirectionChange, amount, onAmountChange, customAmounts, customPercentages, onQuickAmountClick, onQuickPercentageClick, onCustomAmountsEdit, onCustomPercentagesEdit, tokenSymbol, nativeSymbol, nativeDecimals, nativeBalance, tokenBalance, amountConversion, preset, onPresetChange, presetValues, onPresetSettingsChange, showSettings, onPresetClick, submitText, isDisabled, isLoading, onSubmit, className, headerExtra, }: InstantTradeUIProps): react_jsx_runtime.JSX.Element;
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* Pure presentational preset-settings form.
|
|
576
|
+
*
|
|
577
|
+
* Renders inputs for slippage, priority fee, tip fee, auto fee,
|
|
578
|
+
* max auto fee, anti-MEV and custom RPC.
|
|
579
|
+
*
|
|
580
|
+
* The `chain` prop controls which fields are visible:
|
|
581
|
+
* - Solana: priority fee (SOL), tip fee (SOL), anti-MEV
|
|
582
|
+
* - Ethereum: gas fee (Gwei) only
|
|
583
|
+
* - BSC: gas fee (Gwei) + tip fee (BNB)
|
|
584
|
+
*/
|
|
585
|
+
declare function PresetFormUI({ value, onChange, chain, nativeSymbol, nativeDecimals, className, }: PresetFormUIProps): react_jsx_runtime.JSX.Element;
|
|
586
|
+
|
|
587
|
+
/**
|
|
588
|
+
* Compact amount input with preset selector buttons.
|
|
589
|
+
*
|
|
590
|
+
* Designed for inline/header usage (e.g. token detail page).
|
|
591
|
+
* Must be rendered inside an {@link InstantTradeProvider}.
|
|
592
|
+
*/
|
|
593
|
+
declare function InstantTradeAmountInput({ amount, onAmountChange, preset, onPresetChange, onPresetClick, variant, radius, size, fullWidth, className, }: InstantTradeAmountInputProps): react_jsx_runtime.JSX.Element;
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* Trade execution button that reads state from {@link InstantTradeProvider}.
|
|
597
|
+
*
|
|
598
|
+
* Resolves wallet, token addresses, converts amounts, applies preset
|
|
599
|
+
* settings, and calls `useSwap` from the SDK.
|
|
600
|
+
*/
|
|
601
|
+
declare function InstantTradeButton({ className, children, }: InstantTradeButtonProps): react_jsx_runtime.JSX.Element;
|
|
602
|
+
|
|
603
|
+
type AntiMevOption = "off" | "reduced" | "secure";
|
|
604
|
+
interface ChainPresetFeatures {
|
|
605
|
+
/** Label for the priority/gas fee field */
|
|
606
|
+
feeLabel: string;
|
|
607
|
+
/** Unit displayed for the fee input (e.g. "SOL", "Gwei") */
|
|
608
|
+
feeUnit: string;
|
|
609
|
+
/** Decimal places for the fee input */
|
|
610
|
+
feeDecimals: number;
|
|
611
|
+
/** Whether this chain supports a separate tip/bribe fee */
|
|
612
|
+
showTipFee: boolean;
|
|
613
|
+
/** Unit for tip fee (e.g. "SOL", "BNB"). Empty when hidden. */
|
|
614
|
+
tipFeeUnit: string;
|
|
615
|
+
/** Decimal places for the tip fee input */
|
|
616
|
+
tipFeeDecimals: number;
|
|
617
|
+
/**
|
|
618
|
+
* Available anti-MEV protection levels for this chain.
|
|
619
|
+
* - Solana: ["off", "reduced", "secure"]
|
|
620
|
+
* - ETH / BSC: ["off", "secure"]
|
|
621
|
+
*/
|
|
622
|
+
antiMevOptions: AntiMevOption[];
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* Returns the set of preset form features applicable to a given chain.
|
|
626
|
+
*
|
|
627
|
+
* - Solana: priority fee (SOL), tip fee (SOL/Jito), anti-MEV
|
|
628
|
+
* - Ethereum: gas fee (Gwei) only
|
|
629
|
+
* - BSC: gas fee (Gwei) + tip fee (BNB)
|
|
630
|
+
* - Other EVM: gas fee (Gwei), same as Ethereum by default
|
|
631
|
+
*/
|
|
632
|
+
declare function getChainPresetFeatures(chain: Chain, nativeSymbol?: string): ChainPresetFeatures;
|
|
633
|
+
declare function isSolanaChain(chain: Chain): boolean;
|
|
634
|
+
/** Returns chain-appropriate default preset values. */
|
|
635
|
+
declare function getDefaultPresetForChain(chain: Chain): TradePresetValues;
|
|
636
|
+
|
|
320
637
|
declare global {
|
|
321
638
|
interface Window {
|
|
322
639
|
__LIBERFI_VERSION__?: {
|
|
@@ -324,6 +641,6 @@ declare global {
|
|
|
324
641
|
};
|
|
325
642
|
}
|
|
326
643
|
}
|
|
327
|
-
declare const _default: "0.1.
|
|
644
|
+
declare const _default: "0.1.4";
|
|
328
645
|
|
|
329
|
-
export { type SwapInput, type SwapPhase, SwapPreviewModal, type SwapPreviewModalProps, type SwapResult, SwapUI, type SwapUIProps, SwapWidget, type SwapWidgetProps, type TxConfirmationStatus, type UseSwapOptions, type UseSwapRoutePollingOptions, type UseSwapScriptParams, type UseSwapScriptResult, type UseTxConfirmationOptions, useSwap, useSwapRoutePolling, useSwapScript, useTxConfirmation, _default as version };
|
|
646
|
+
export { type AntiMevOption, type BuySettings, type ChainPresetFeatures, DEFAULT_BSC_TRADE_PRESET, DEFAULT_BUY_AMOUNTS, DEFAULT_EVM_TRADE_PRESET, DEFAULT_INSTANT_TRADE_SETTINGS, DEFAULT_SELL_PERCENTAGES, DEFAULT_TRADE_PRESET, InstantTradeAmountInput, type InstantTradeAmountInputProps, InstantTradeButton, type InstantTradeButtonProps, type InstantTradeContextValue, InstantTradeProvider, type InstantTradeProviderProps, type InstantTradeSettings, InstantTradeUI, type InstantTradeUIProps, InstantTradeWidget, type InstantTradeWidgetProps, PresetFormUI, type PresetFormUIProps, PresetFormWidget, type PresetFormWidgetProps, type SellSettings, type SwapInput, type SwapPhase, SwapPreviewModal, type SwapPreviewModalProps, type SwapResult, SwapUI, type SwapUIProps, SwapWidget, type SwapWidgetProps, type TradePresetValues, type TxConfirmationStatus, type UseInstantTradeScriptParams, type UseInstantTradeScriptResult, type UseSwapOptions, type UseSwapRoutePollingOptions, type UseSwapScriptParams, type UseSwapScriptResult, type UseTxConfirmationOptions, getChainPresetFeatures, getDefaultPresetForChain, isSolanaChain, useInstantTrade, useInstantTradeScript, useSwap, useSwapRoutePolling, useSwapScript, useTxConfirmation, _default as version };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var react$1=require('react'),react=require('@liberfi.io/react'),types=require('@liberfi.io/types'),walletConnector=require('@liberfi.io/wallet-connector'),ui=require('@liberfi.io/ui'),jsxRuntime=require('react/jsx-runtime');function Fe(e){let t=atob(e),u=new Uint8Array(t.length);for(let i=0;i<t.length;i++)u[i]=t.charCodeAt(i);return u}function Me(e){let t="";for(let u=0;u<e.length;u++)t+=String.fromCharCode(e[u]);return btoa(t)}function ie(e){let{client:t}=react.useDexClient(),[u,i]=react$1.useState(false),a=react$1.useRef(e);a.current=e;let n=react$1.useCallback(async d=>{let{wallet:m,chain:p,...r}=d;i(true);try{let l;try{l=await t.swapRoute({chain:p,userAddress:m.address,input:r.input,output:r.output,mode:r.mode??types.API.SwapMode.EXACT_IN,amount:r.amount,slippage:r.slippage,priorityFee:r.priorityFee,tipFee:r.tipFee,isAntiMev:r.isAntiMev,permit:r.permit,deadline:r.deadline});}catch(s){let S=s instanceof Error?s:new Error(String(s));throw a.current?.onError?.(S,"route"),S}let h;try{let s=Fe(l.serializedTx);h=await m.signTransaction(s);}catch(s){let S=s instanceof Error?s:new Error(String(s));throw a.current?.onError?.(S,"sign"),S}let f;try{let s=Me(h);f=await t.sendTx({chain:p,serializedTx:s});}catch(s){let S=s instanceof Error?s:new Error(String(s));throw a.current?.onError?.(S,"send"),S}let w={txHash:f.txHash,extra:f.extra};return a.current?.onSubmitted?.(w),w}finally{i(false);}},[t]);return react$1.useMemo(()=>({swap:n,isSwapping:u}),[n,u])}var Le=12e3;function ae(e,t){let u=t?.interval??Le,i=t?.paused??false,a=react$1.useRef(t);a.current=t;let d=!!e.chain&&!!e.userAddress&&!!e.input&&!!e.output&&!!e.amount&&!i,m=react.useSwapRouteQuery(e,{enabled:d,refetchInterval:d?u:false,retry:false});return react$1.useEffect(()=>{m.error&&a.current?.onError?.(m.error);},[m.error]),react$1.useMemo(()=>({route:m.data,isRouting:m.isFetching,error:m.error}),[m.data,m.isFetching,m.error])}var je=6e4;function ue(e){let{client:t}=react.useDexClient(),[u,i]=react$1.useState(()=>new Map),a=react$1.useRef(e);a.current=e;let n=react$1.useCallback((r,l)=>{i(h=>{let f=h.get(r);if(!f||f.status===l)return h;let w=new Map(h);return w.set(r,{...f,status:l}),w});},[]),d=react$1.useCallback((r,l)=>{i(f=>{if(f.has(l))return f;let w=new Map(f);return w.set(l,{chain:r,txHash:l,status:"pending"}),w});let h=a.current?.timeout??je;t.checkTxSuccess(r,l,h).then(f=>{if(f)n(l,"confirmed"),a.current?.onConfirmed?.(l);else {let w=new Error("Transaction failed on-chain");n(l,"failed"),a.current?.onFailed?.(l,w);}}).catch(f=>{let w=f instanceof Error?f:new Error(String(f));n(l,"failed"),a.current?.onFailed?.(l,w);});},[t,n]),m=react$1.useCallback(r=>{i(l=>{if(!l.has(r))return l;let h=new Map(l);return h.delete(r),h});},[]),p=react$1.useCallback(()=>{i(r=>r.size===0?r:new Map);},[]);return react$1.useMemo(()=>({track:d,clear:m,clearAll:p,transactions:u}),[d,m,p,u])}var Qe=new Set([types.Chain.SOLANA,types.Chain.SOLANA_TESTNET,types.Chain.SOLANA_DEVNET]);function Ke(e){return Qe.has(e)?types.ChainNamespace.SOLANA:types.ChainNamespace.EVM}var Xe=1e4,qe=15e3;function Ge(e,t){if(e.length===0)return;let i=e[e.length-1].outputAmount;if(!i||i==="0")return "0";let a=i.padStart(t+1,"0"),n=a.slice(0,a.length-t)||"0",m=a.slice(a.length-t).replace(/0+$/,"");return m?`${n}.${m}`:n}function j(e){let{chain:t}=e,u=walletConnector.useWallets(),i=Ke(t),a=react$1.useMemo(()=>u.find(o=>o.chainNamespace===i&&o.isConnected),[u,i]),n=a?.address??"",[d,m]=react$1.useState(e.from??""),[p,r]=react$1.useState(e.to??""),l=react$1.useRef(e.from),h=react$1.useRef(e.to);react$1.useEffect(()=>{e.from!==l.current&&(l.current=e.from,e.from&&m(e.from));},[e.from]),react$1.useEffect(()=>{e.to!==h.current&&(h.current=e.to,e.to&&r(e.to));},[e.to]);let f=react$1.useMemo(()=>[d,p].filter(Boolean),[d,p]),w=react.useTokensQuery({chain:t,addresses:f},{enabled:f.length>0,refetchInterval:Xe}),s=react$1.useMemo(()=>w.data?.find(o=>o.address===d)??null,[w.data,d]),S=react$1.useMemo(()=>w.data?.find(o=>o.address===p)??null,[w.data,p]),C=react.useWalletPortfoliosByTokensQuery({chain:t,address:n,tokenAddresses:f},{enabled:!!n&&f.length>0,refetchInterval:qe}),b=react$1.useMemo(()=>C.data?.find(o=>o.address===d)??null,[C.data,d]),g=react$1.useMemo(()=>C.data?.find(o=>o.address===p)??null,[C.data,p]),[A,T]=react$1.useState(void 0),P=react$1.useMemo(()=>{if(!A||s?.decimals==null)return;let o=A.split("."),I=o[0]??"0",ye=(o[1]??"").slice(0,s.decimals).padEnd(s.decimals,"0");return (I+ye).replace(/^0+/,"")||"0"},[A,s?.decimals]),X=react$1.useMemo(()=>{if(!A||!s?.marketData?.priceInUsd)return;let o=Number(s.marketData.priceInUsd),I=Number(A)*o;return Number.isFinite(I)?I.toString():void 0},[A,s?.marketData?.priceInUsd]),q=react$1.useCallback(()=>{if(!b)return;let o=Number(b.amount);if(!Number.isFinite(o)||o<=0)return;let I=o/2,oe=s?.decimals??9;T(I.toLocaleString("en-US",{useGrouping:false,maximumFractionDigits:oe}));},[b,s?.decimals]),G=react$1.useCallback(()=>{if(!b)return;let o=Number(b.amount);if(!Number.isFinite(o)||o<=0)return;let I=s?.decimals??9;T(o.toLocaleString("en-US",{useGrouping:false,maximumFractionDigits:I}));},[b,s?.decimals]),be=react$1.useMemo(()=>({chain:t,userAddress:n||void 0,input:d||void 0,output:p||void 0,mode:types.API.SwapMode.EXACT_IN,amount:P}),[t,n,d,p,P]),Z=react$1.useRef(false),{route:U,isRouting:H,error:J}=ae(be,{paused:Z.current}),F=react$1.useMemo(()=>U&&S?Ge(U.plans,S.decimals):void 0,[U,S]),Y=react$1.useMemo(()=>{if(!F||!S?.marketData?.priceInUsd)return;let o=Number(S.marketData.priceInUsd),I=Number(F)*o;return Number.isFinite(I)?I.toString():void 0},[F,S?.marketData?.priceInUsd]),{swap:ee,isSwapping:k}=ie();Z.current=k;let L=react$1.useRef(e.onComplete);L.current=e.onComplete;let{track:te,transactions:D}=ue({onConfirmed:o=>{L.current?.({success:true,txHash:o});},onFailed:o=>{L.current?.({success:false,txHash:o});}}),ne=react$1.useMemo(()=>{if(D.size===0)return "idle";let o=Array.from(D.values());return o[o.length-1].status},[D]),re=react$1.useCallback(async()=>{if(!(!a||!U||!d||!p||!P))try{let o=await ee({chain:t,wallet:a,input:d,output:p,amount:P,mode:types.API.SwapMode.EXACT_IN});te(t,o.txHash);}catch{}},[a,U,t,d,p,P,ee,te]),se=w.isPending||C.isPending;return react$1.useMemo(()=>({fromTokenAddress:d,toTokenAddress:p,setFromTokenAddress:m,setToTokenAddress:r,fromToken:s,toToken:S,fromBalance:b,toBalance:g,amount:A,setAmount:T,setHalfAmount:q,setMaxAmount:G,amountInDecimals:P,amountInUsd:X,outputAmount:F,outputAmountInUsd:Y,route:U,isRouting:H,routeError:J,swap:re,isSwapping:k,txStatus:ne,isLoading:se}),[d,p,s,S,b,g,A,q,G,P,X,F,Y,U,H,J,re,k,ne,se])}function V({isOpen:e,onOpenChange:t,fromToken:u,toToken:i,fromBalance:a,inputAmount:n,inputAmountInUsd:d,outputAmount:m,outputAmountInUsd:p,route:r,isRouting:l,routeError:h,onConfirm:f,isSwapping:w}){let[s,S]=react$1.useState(false),C=react$1.useCallback(()=>S(g=>!g),[]),b=react$1.useMemo(()=>r?r.plans.map((g,A)=>({key:`plan-${A}`,name:g.name,input:g.input,inputAmount:g.inputAmount,output:g.output,outputAmount:g.outputAmount,feeQuote:g.feeQuote,feeAmount:g.feeAmount})):[],[r]);return jsxRuntime.jsx(ui.Modal,{isOpen:e,onOpenChange:t,hideCloseButton:true,scrollBehavior:"inside",backdrop:"blur",children:jsxRuntime.jsxs(ui.ModalContent,{className:"bg-content2 rounded-lg",children:[jsxRuntime.jsx(ui.ModalHeader,{children:"Preview"}),jsxRuntime.jsx(ui.ModalBody,{children:jsxRuntime.jsxs("div",{className:"flex w-full max-h-[70vh] flex-1 flex-col overflow-y-auto py-2",children:[jsxRuntime.jsxs("div",{className:"mb-5",children:[jsxRuntime.jsx("div",{className:"text-neutral flex items-center justify-between text-xs font-medium",children:"From"}),jsxRuntime.jsxs("div",{className:"bg-content3 mt-3 flex w-full items-center gap-3 rounded-lg px-4 py-3",children:[jsxRuntime.jsxs("div",{className:"flex flex-1 items-center gap-3",children:[u?.image&&jsxRuntime.jsx(ui.Avatar,{size:"sm",src:u.image,name:u.symbol,className:"h-6 w-6"}),jsxRuntime.jsxs("div",{className:"flex flex-col items-start justify-center gap-0.5",children:[jsxRuntime.jsx("div",{className:"text-foreground text-xs",children:u?.symbol??"\u2014"}),a&&jsxRuntime.jsxs("div",{className:"text-neutral flex items-center gap-1 text-[10px]",children:[jsxRuntime.jsx(at,{}),jsxRuntime.jsxs("span",{children:[$(a.amount)," ",u?.symbol]})]})]})]}),jsxRuntime.jsxs("div",{className:"flex-0 flex flex-col items-end justify-center gap-0.5",children:[jsxRuntime.jsx("div",{className:"text-foreground text-xs",children:$(n)}),jsxRuntime.jsxs("div",{className:"text-neutral text-[10px]",children:["$",fe(d)]})]})]})]}),jsxRuntime.jsxs("div",{className:"mb-5",children:[jsxRuntime.jsx("div",{className:"text-neutral flex items-center justify-between text-xs font-medium",children:"Estimated Receive"}),jsxRuntime.jsxs("div",{className:"bg-content3 mt-3 flex w-full items-center gap-3 rounded-lg px-4 py-3",children:[jsxRuntime.jsxs("div",{className:"flex flex-1 items-center gap-3",children:[i?.image&&jsxRuntime.jsx(ui.Avatar,{size:"sm",src:i.image,name:i.symbol,className:"h-6 w-6"}),jsxRuntime.jsxs("div",{className:"flex flex-col items-start justify-center gap-0.5",children:[jsxRuntime.jsx("div",{className:"text-foreground text-xs",children:i?.symbol??"\u2014"}),jsxRuntime.jsx("div",{className:"text-neutral text-[10px]",children:E(i?.address)})]})]}),jsxRuntime.jsxs("div",{className:"flex-0 flex flex-col items-end justify-center gap-0.5",children:[jsxRuntime.jsx("div",{className:"text-foreground text-xs",children:$(m)}),jsxRuntime.jsxs("div",{className:"text-neutral text-[10px]",children:["$",fe(p)]})]})]})]}),s&&b.length>0&&jsxRuntime.jsxs("div",{className:"my-3",children:[jsxRuntime.jsx("div",{className:"text-neutral flex items-center justify-between text-xs font-medium",children:"Route Details"}),jsxRuntime.jsx("div",{className:"mt-3 flex flex-col gap-3",children:b.map(g=>jsxRuntime.jsxs("div",{className:"bg-content3 flex w-full flex-col items-center gap-2 rounded-lg px-4 py-3",children:[jsxRuntime.jsxs("div",{className:"flex w-full items-center justify-between",children:[jsxRuntime.jsx("div",{className:"text-neutral text-xs",children:"DEX"}),jsxRuntime.jsx("div",{className:"text-foreground text-xs",children:g.name})]}),jsxRuntime.jsxs("div",{className:"flex w-full items-center justify-between",children:[jsxRuntime.jsx("div",{className:"text-neutral text-xs",children:"Swap"}),jsxRuntime.jsxs("div",{className:"text-foreground flex items-center gap-2 text-xs",children:[jsxRuntime.jsxs("span",{children:[z(g.inputAmount)," ",E(g.input)]}),jsxRuntime.jsx(ui.TradeIcon,{width:12,height:12,className:"text-foreground"}),jsxRuntime.jsxs("span",{children:[z(g.outputAmount)," ",E(g.output)]})]})]}),g.feeAmount&&jsxRuntime.jsxs("div",{className:"flex w-full items-center justify-between",children:[jsxRuntime.jsx("div",{className:"text-neutral text-xs",children:"Fee"}),jsxRuntime.jsxs("div",{className:"text-foreground text-xs",children:[z(g.feeAmount)," ",E(g.feeQuote)]})]})]},g.key))})]}),b.length>0&&jsxRuntime.jsx("div",{className:"flex justify-center",children:jsxRuntime.jsx(ui.Button,{size:"sm",className:"text-neutral flex bg-transparent text-xs",endContent:s?jsxRuntime.jsx(ui.ChevronUpIcon,{width:12,height:12}):jsxRuntime.jsx(ui.ChevronDownIcon,{width:12,height:12}),disableRipple:true,onPress:C,children:s?"Show Less":"Show More"})})]})}),jsxRuntime.jsx(ui.ModalFooter,{children:jsxRuntime.jsx(ui.Button,{fullWidth:true,color:"primary",className:"flex rounded-lg",disableRipple:true,isDisabled:!r||!!h,isLoading:!r&&l||w,onPress:f,children:"Confirm"})})]})})}function at(){return jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:12,height:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:"text-neutral",children:[jsxRuntime.jsx("path",{d:"M21 12V7H5a2 2 0 0 1 0-4h14v4"}),jsxRuntime.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h16v-5"}),jsxRuntime.jsx("path",{d:"M18 12a2 2 0 0 0 0 4h4v-4Z"})]})}function fe(e){if(!e)return "0.00";let t=Number(e);return Number.isFinite(t)?t.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):"0.00"}function $(e){if(!e)return "0";let t=Number(e);return Number.isFinite(t)?t>=1e6?(t/1e6).toLocaleString("en-US",{maximumFractionDigits:2})+"M":t>=1e3?(t/1e3).toLocaleString("en-US",{maximumFractionDigits:2})+"K":t.toLocaleString("en-US",{maximumFractionDigits:6}):"0"}function z(e){if(!e||e==="0")return "0";let t=Number(e);return Number.isFinite(t)?t>=1e12?(t/1e12).toFixed(2)+"T":t>=1e9?(t/1e9).toFixed(2)+"B":t>=1e6?(t/1e6).toFixed(2)+"M":t>=1e3?(t/1e3).toFixed(2)+"K":e:e}function E(e){return e?e.length<=10?e:`${e.slice(0,4)}...${e.slice(-4)}`:"\u2014"}function K({fromToken:e,toToken:t,fromBalance:u,toBalance:i,amount:a,amountInUsd:n,onAmountChange:d,onHalfAmount:m,onMaxAmount:p,outputAmount:r,outputAmountInUsd:l,onFromTokenSelect:h,onToTokenSelect:f,route:w,isRouting:s,routeError:S,onPreview:C,isSwapping:b,className:g}){return jsxRuntime.jsxs("div",{className:ui.cn("px-4 pb-4 lg:pb-8",g),children:[jsxRuntime.jsxs("div",{className:"space-y-3",children:[jsxRuntime.jsx("p",{className:"text-neutral text-sm font-medium",children:"From"}),jsxRuntime.jsxs("div",{className:"bg-content1 flex flex-col rounded-lg px-3.5 pb-2.5 pt-2",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx("div",{className:"flex-1",children:jsxRuntime.jsx(ui.Input,{type:"number",value:a??"",onChange:A=>d(A.target.value||void 0),placeholder:"0",classNames:{inputWrapper:ui.cn("h-10 p-0 bg-transparent","data-[hover=true]:bg-transparent group-data-[focus=true]:bg-transparent","group-data-[focus-visible=true]:ring-offset-transparent group-data-[focus-visible=true]:ring-transparent"),input:ui.cn("w-full h-full caret-primary text-3xl font-medium","placeholder:text-placeholder placeholder:text-3xl placeholder:font-medium","scrollbar-hide overflow-hidden text-ellipsis whitespace-nowrap")}})}),jsxRuntime.jsx("div",{className:"flex-0 flex h-full items-center justify-center",children:jsxRuntime.jsx(ui.Button,{className:ui.cn("flex min-w-0 h-8 min-h-8 pl-3 pr-2 bg-content3 rounded-full",e?"text-foreground":"text-neutral"),disableRipple:true,startContent:e?.image?jsxRuntime.jsx(ui.Avatar,{size:"sm",src:e.image,name:e.symbol,className:"h-6 w-6"}):null,endContent:jsxRuntime.jsx(ui.ChevronDownIcon,{width:16,height:16,className:"text-neutral"}),onPress:()=>h(""),children:e?e.symbol:"Select token"})})]}),jsxRuntime.jsxs("div",{className:"mt-3 flex items-center justify-between gap-4",children:[jsxRuntime.jsxs("div",{className:"text-neutral flex-1 text-xs",children:["\u2248 $",Se(n)]}),u&&jsxRuntime.jsxs("div",{className:"flex-0 flex items-center gap-2 pr-3 text-xs",children:[jsxRuntime.jsx(ve,{}),jsxRuntime.jsxs("span",{className:"text-neutral",children:[he(u.amount)," ",u.symbol]}),m&&jsxRuntime.jsx("span",{className:"text-primary cursor-pointer",onClick:m,children:"Half"}),p&&jsxRuntime.jsx("span",{className:"text-primary cursor-pointer",onClick:p,children:"Max"})]})]}),S&&jsxRuntime.jsx("p",{className:"mt-1 break-words text-xs text-danger-500",children:S.message})]})]}),jsxRuntime.jsxs("div",{className:"mt-4 space-y-3",children:[jsxRuntime.jsx("p",{className:"text-neutral text-sm font-medium",children:"To"}),jsxRuntime.jsxs("div",{className:"bg-content1 flex flex-col rounded-lg px-3.5 pb-2.5 pt-2",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx("div",{className:"flex-1",children:jsxRuntime.jsx(ui.Input,{type:"number",value:r??"",disabled:true,placeholder:"0",classNames:{inputWrapper:ui.cn("h-10 p-0 bg-transparent","data-[hover=true]:bg-transparent group-data-[focus=true]:bg-transparent","group-data-[focus-visible=true]:ring-offset-transparent group-data-[focus-visible=true]:ring-transparent"),input:ui.cn("w-full h-full caret-primary text-3xl font-medium","placeholder:text-placeholder placeholder:text-3xl placeholder:font-medium","scrollbar-hide overflow-hidden text-ellipsis whitespace-nowrap")}})}),jsxRuntime.jsx("div",{className:"flex-0 flex h-full items-center justify-center",children:jsxRuntime.jsx(ui.Button,{className:ui.cn("flex min-w-0 h-8 min-h-8 pl-3 pr-2 bg-content3 rounded-full",t?"text-foreground":"text-neutral"),disableRipple:true,startContent:t?.image?jsxRuntime.jsx(ui.Avatar,{size:"sm",src:t.image,name:t.symbol,className:"h-6 w-6"}):null,endContent:jsxRuntime.jsx(ui.ChevronDownIcon,{width:16,height:16,className:"text-neutral"}),onPress:()=>f(""),children:t?t.symbol:"Select token"})})]}),jsxRuntime.jsxs("div",{className:"mt-3 flex items-center justify-between gap-4",children:[jsxRuntime.jsxs("div",{className:"text-neutral flex-1 text-xs",children:["\u2248 $",Se(l)]}),i&&jsxRuntime.jsxs("div",{className:"flex-0 flex items-center gap-2 pr-3 text-xs",children:[jsxRuntime.jsx(ve,{}),jsxRuntime.jsxs("span",{className:"text-neutral",children:[he(i.amount)," ",i.symbol]})]})]})]})]}),jsxRuntime.jsx(ui.Button,{fullWidth:true,color:"primary",className:"mt-8 flex rounded-lg",disableRipple:true,isDisabled:!w,isLoading:!w&&s,onPress:C,children:b?"Swapping...":s?"Finding route...":"Swap"})]})}function ve(){return jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:12,height:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:"text-neutral",children:[jsxRuntime.jsx("path",{d:"M21 12V7H5a2 2 0 0 1 0-4h14v4"}),jsxRuntime.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h16v-5"}),jsxRuntime.jsx("path",{d:"M18 12a2 2 0 0 0 0 4h4v-4Z"})]})}function Se(e){if(!e)return "0.00";let t=Number(e);return Number.isFinite(t)?t.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):"0.00"}function he(e){if(!e)return "0";let t=Number(e);return Number.isFinite(t)?t>=1e6?(t/1e6).toLocaleString("en-US",{maximumFractionDigits:2})+"M":t>=1e3?(t/1e3).toLocaleString("en-US",{maximumFractionDigits:2})+"K":t.toLocaleString("en-US",{maximumFractionDigits:6}):"0"}function ct({chain:e,from:t,to:u,onComplete:i,className:a}){let n=j({chain:e,from:t,to:u,onComplete:i}),{isOpen:d,onOpen:m,onOpenChange:p,onClose:r}=ui.useDisclosure(),l=react$1.useCallback(async()=>{await n.swap(),r();},[n,r]);return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(K,{fromToken:n.fromToken,toToken:n.toToken,fromBalance:n.fromBalance,toBalance:n.toBalance,amount:n.amount,amountInUsd:n.amountInUsd,onAmountChange:n.setAmount,onHalfAmount:n.setHalfAmount,onMaxAmount:n.setMaxAmount,outputAmount:n.outputAmount,outputAmountInUsd:n.outputAmountInUsd,onFromTokenSelect:n.setFromTokenAddress,onToTokenSelect:n.setToTokenAddress,route:n.route,isRouting:n.isRouting,routeError:n.routeError,onPreview:m,isSwapping:n.isSwapping,className:a}),jsxRuntime.jsx(V,{isOpen:d,onOpenChange:p,fromToken:n.fromToken,toToken:n.toToken,fromBalance:n.fromBalance,inputAmount:n.amount,inputAmountInUsd:n.amountInUsd,outputAmount:n.outputAmount,outputAmountInUsd:n.outputAmountInUsd,route:n.route,isRouting:n.isRouting,routeError:n.routeError,onConfirm:l,isSwapping:n.isSwapping})]})}typeof window<"u"&&(window.__LIBERFI_VERSION__=window.__LIBERFI_VERSION__||{},window.__LIBERFI_VERSION__["@liberfi.io/ui-trade"]="0.1.2");var pt="0.1.2";
|
|
2
|
-
exports.SwapPreviewModal=
|
|
1
|
+
'use strict';var react=require('react'),react$1=require('@liberfi.io/react'),types=require('@liberfi.io/types'),walletConnector=require('@liberfi.io/wallet-connector'),ui=require('@liberfi.io/ui'),jsxRuntime=require('react/jsx-runtime'),utils=require('@liberfi.io/utils'),ae=require('bignumber.js'),hooks=require('@liberfi.io/hooks');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ae__default=/*#__PURE__*/_interopDefault(ae);function kt(e){let t=atob(e),r=new Uint8Array(t.length);for(let a=0;a<t.length;a++)r[a]=t.charCodeAt(a);return r}function Mt(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function re(e){let{client:t}=react$1.useDexClient(),[r,a]=react.useState(false),l=react.useRef(e);l.current=e;let s=react.useCallback(async n=>{let{wallet:o,chain:u,...c}=n;a(true);try{let d;try{d=await t.swapRoute({chain:u,userAddress:o.address,input:c.input,output:c.output,mode:c.mode??types.API.SwapMode.EXACT_IN,amount:c.amount,slippage:c.slippage,priorityFee:c.priorityFee,tipFee:c.tipFee,isAntiMev:c.isAntiMev,permit:c.permit,deadline:c.deadline});}catch(i){let g=i instanceof Error?i:new Error(String(i));throw l.current?.onError?.(g,"route"),g}let m;try{let i=kt(d.serializedTx);m=await o.signTransaction(i);}catch(i){let g=i instanceof Error?i:new Error(String(i));throw l.current?.onError?.(g,"sign"),g}let f;try{let i=Mt(m);f=await t.sendTx({chain:u,serializedTx:i});}catch(i){let g=i instanceof Error?i:new Error(String(i));throw l.current?.onError?.(g,"send"),g}let h={txHash:f.txHash,extra:f.extra};return l.current?.onSubmitted?.(h),h}finally{a(false);}},[t]);return react.useMemo(()=>({swap:s,isSwapping:r}),[s,r])}var _t=12e3;function Ke(e,t){let r=t?.interval??_t,a=t?.paused??false,l=react.useRef(t);l.current=t;let n=!!e.chain&&!!e.userAddress&&!!e.input&&!!e.output&&!!e.amount&&!a,o=react$1.useSwapRouteQuery(e,{enabled:n,refetchInterval:n?r:false,retry:false});return react.useEffect(()=>{o.error&&l.current?.onError?.(o.error);},[o.error]),react.useMemo(()=>({route:o.data,isRouting:o.isFetching,error:o.error}),[o.data,o.isFetching,o.error])}var zt=6e4;function Ge(e){let{client:t}=react$1.useDexClient(),[r,a]=react.useState(()=>new Map),l=react.useRef(e);l.current=e;let s=react.useCallback((c,d)=>{a(m=>{let f=m.get(c);if(!f||f.status===d)return m;let h=new Map(m);return h.set(c,{...f,status:d}),h});},[]),n=react.useCallback((c,d)=>{a(f=>{if(f.has(d))return f;let h=new Map(f);return h.set(d,{chain:c,txHash:d,status:"pending"}),h});let m=l.current?.timeout??zt;t.checkTxSuccess(c,d,m).then(f=>{if(f)s(d,"confirmed"),l.current?.onConfirmed?.(d);else {let h=new Error("Transaction failed on-chain");s(d,"failed"),l.current?.onFailed?.(d,h);}}).catch(f=>{let h=f instanceof Error?f:new Error(String(f));s(d,"failed"),l.current?.onFailed?.(d,h);});},[t,s]),o=react.useCallback(c=>{a(d=>{if(!d.has(c))return d;let m=new Map(d);return m.delete(c),m});},[]),u=react.useCallback(()=>{a(c=>c.size===0?c:new Map);},[]);return react.useMemo(()=>({track:n,clear:o,clearAll:u,transactions:r}),[n,o,u,r])}var Ht=new Set([types.Chain.SOLANA,types.Chain.SOLANA_TESTNET,types.Chain.SOLANA_DEVNET]);function Kt(e){return Ht.has(e)?types.ChainNamespace.SOLANA:types.ChainNamespace.EVM}var Gt=1e4,Xt=15e3;function Zt(e,t){if(e.length===0)return;let a=e[e.length-1].outputAmount;if(!a||a==="0")return "0";let l=a.padStart(t+1,"0"),s=l.slice(0,l.length-t)||"0",o=l.slice(l.length-t).replace(/0+$/,"");return o?`${s}.${o}`:s}function Fe(e){let{chain:t}=e,r=walletConnector.useWallets(),a=Kt(t),l=react.useMemo(()=>r.find(w=>w.chainNamespace===a&&w.isConnected),[r,a]),s=l?.address??"",[n,o]=react.useState(e.from??""),[u,c]=react.useState(e.to??""),d=react.useRef(e.from),m=react.useRef(e.to);react.useEffect(()=>{e.from!==d.current&&(d.current=e.from,e.from&&o(e.from));},[e.from]),react.useEffect(()=>{e.to!==m.current&&(m.current=e.to,e.to&&c(e.to));},[e.to]);let f=react.useMemo(()=>[n,u].filter(Boolean),[n,u]),h=react$1.useTokensQuery({chain:t,addresses:f},{enabled:f.length>0,refetchInterval:Gt}),i=react.useMemo(()=>h.data?.find(w=>w.address===n)??null,[h.data,n]),g=react.useMemo(()=>h.data?.find(w=>w.address===u)??null,[h.data,u]),v=react$1.useWalletPortfoliosByTokensQuery({chain:t,address:s,tokenAddresses:f},{enabled:!!s&&f.length>0,refetchInterval:Xt}),b=react.useMemo(()=>v.data?.find(w=>w.address===n)??null,[v.data,n]),x=react.useMemo(()=>v.data?.find(w=>w.address===u)??null,[v.data,u]),[T,M]=react.useState(void 0),I=react.useMemo(()=>{if(!T||i?.decimals==null)return;let w=T.split("."),D=w[0]??"0",Pt=(w[1]??"").slice(0,i.decimals).padEnd(i.decimals,"0");return (D+Pt).replace(/^0+/,"")||"0"},[T,i?.decimals]),R=react.useMemo(()=>{if(!T||!i?.marketData?.priceInUsd)return;let w=Number(i.marketData.priceInUsd),D=Number(T)*w;return Number.isFinite(D)?D.toString():void 0},[T,i?.marketData?.priceInUsd]),k=react.useCallback(()=>{if(!b)return;let w=Number(b.amount);if(!Number.isFinite(w)||w<=0)return;let D=w/2,He=i?.decimals??9;M(D.toLocaleString("en-US",{useGrouping:false,maximumFractionDigits:He}));},[b,i?.decimals]),U=react.useCallback(()=>{if(!b)return;let w=Number(b.amount);if(!Number.isFinite(w)||w<=0)return;let D=i?.decimals??9;M(w.toLocaleString("en-US",{useGrouping:false,maximumFractionDigits:D}));},[b,i?.decimals]),A=react.useMemo(()=>({chain:t,userAddress:s||void 0,input:n||void 0,output:u||void 0,mode:types.API.SwapMode.EXACT_IN,amount:I}),[t,s,n,u,I]),z=react.useRef(false),{route:L,isRouting:q,error:J}=Ke(A,{paused:z.current}),H=react.useMemo(()=>L&&g?Zt(L.plans,g.decimals):void 0,[L,g]),y=react.useMemo(()=>{if(!H||!g?.marketData?.priceInUsd)return;let w=Number(g.marketData.priceInUsd),D=Number(H)*w;return Number.isFinite(D)?D.toString():void 0},[H,g?.marketData?.priceInUsd]),{swap:B,isSwapping:O}=re();z.current=O;let K=react.useRef(e.onComplete);K.current=e.onComplete;let{track:le,transactions:G}=Ge({onConfirmed:w=>{K.current?.({success:true,txHash:w});},onFailed:w=>{K.current?.({success:false,txHash:w});}}),X=react.useMemo(()=>{if(G.size===0)return "idle";let w=Array.from(G.values());return w[w.length-1].status},[G]),Y=react.useCallback(async()=>{if(!(!l||!L||!n||!u||!I))try{let w=await B({chain:t,wallet:l,input:n,output:u,amount:I,mode:types.API.SwapMode.EXACT_IN});le(t,w.txHash);}catch{}},[l,L,t,n,u,I,B,le]),se=h.isPending||v.isPending;return react.useMemo(()=>({fromTokenAddress:n,toTokenAddress:u,setFromTokenAddress:o,setToTokenAddress:c,fromToken:i,toToken:g,fromBalance:b,toBalance:x,amount:T,setAmount:M,setHalfAmount:k,setMaxAmount:U,amountInDecimals:I,amountInUsd:R,outputAmount:H,outputAmountInUsd:y,route:L,isRouting:q,routeError:J,swap:Y,isSwapping:O,txStatus:X,isLoading:se}),[n,u,i,g,b,x,T,k,U,I,R,H,y,L,q,J,Y,O,X,se])}function Me({isOpen:e,onOpenChange:t,fromToken:r,toToken:a,fromBalance:l,inputAmount:s,inputAmountInUsd:n,outputAmount:o,outputAmountInUsd:u,route:c,isRouting:d,routeError:m,onConfirm:f,isSwapping:h}){let[i,g]=react.useState(false),v=react.useCallback(()=>g(x=>!x),[]),b=react.useMemo(()=>c?c.plans.map((x,T)=>({key:`plan-${T}`,name:x.name,input:x.input,inputAmount:x.inputAmount,output:x.output,outputAmount:x.outputAmount,feeQuote:x.feeQuote,feeAmount:x.feeAmount})):[],[c]);return jsxRuntime.jsx(ui.Modal,{isOpen:e,onOpenChange:t,hideCloseButton:true,scrollBehavior:"inside",backdrop:"blur",children:jsxRuntime.jsxs(ui.ModalContent,{className:"bg-content2 rounded-lg",children:[jsxRuntime.jsx(ui.ModalHeader,{children:"Preview"}),jsxRuntime.jsx(ui.ModalBody,{children:jsxRuntime.jsxs("div",{className:"flex w-full max-h-[70vh] flex-1 flex-col overflow-y-auto py-2",children:[jsxRuntime.jsxs("div",{className:"mb-5",children:[jsxRuntime.jsx("div",{className:"text-neutral flex items-center justify-between text-xs font-medium",children:"From"}),jsxRuntime.jsxs("div",{className:"bg-content3 mt-3 flex w-full items-center gap-3 rounded-lg px-4 py-3",children:[jsxRuntime.jsxs("div",{className:"flex flex-1 items-center gap-3",children:[r?.image&&jsxRuntime.jsx(ui.Avatar,{size:"sm",src:r.image,name:r.symbol,className:"h-6 w-6"}),jsxRuntime.jsxs("div",{className:"flex flex-col items-start justify-center gap-0.5",children:[jsxRuntime.jsx("div",{className:"text-foreground text-xs",children:r?.symbol??"\u2014"}),l&&jsxRuntime.jsxs("div",{className:"text-neutral flex items-center gap-1 text-[10px]",children:[jsxRuntime.jsx(un,{}),jsxRuntime.jsxs("span",{children:[Ee(l.amount)," ",r?.symbol]})]})]})]}),jsxRuntime.jsxs("div",{className:"flex-0 flex flex-col items-end justify-center gap-0.5",children:[jsxRuntime.jsx("div",{className:"text-foreground text-xs",children:Ee(s)}),jsxRuntime.jsxs("div",{className:"text-neutral text-[10px]",children:["$",et(n)]})]})]})]}),jsxRuntime.jsxs("div",{className:"mb-5",children:[jsxRuntime.jsx("div",{className:"text-neutral flex items-center justify-between text-xs font-medium",children:"Estimated Receive"}),jsxRuntime.jsxs("div",{className:"bg-content3 mt-3 flex w-full items-center gap-3 rounded-lg px-4 py-3",children:[jsxRuntime.jsxs("div",{className:"flex flex-1 items-center gap-3",children:[a?.image&&jsxRuntime.jsx(ui.Avatar,{size:"sm",src:a.image,name:a.symbol,className:"h-6 w-6"}),jsxRuntime.jsxs("div",{className:"flex flex-col items-start justify-center gap-0.5",children:[jsxRuntime.jsx("div",{className:"text-foreground text-xs",children:a?.symbol??"\u2014"}),jsxRuntime.jsx("div",{className:"text-neutral text-[10px]",children:he(a?.address)})]})]}),jsxRuntime.jsxs("div",{className:"flex-0 flex flex-col items-end justify-center gap-0.5",children:[jsxRuntime.jsx("div",{className:"text-foreground text-xs",children:Ee(o)}),jsxRuntime.jsxs("div",{className:"text-neutral text-[10px]",children:["$",et(u)]})]})]})]}),i&&b.length>0&&jsxRuntime.jsxs("div",{className:"my-3",children:[jsxRuntime.jsx("div",{className:"text-neutral flex items-center justify-between text-xs font-medium",children:"Route Details"}),jsxRuntime.jsx("div",{className:"mt-3 flex flex-col gap-3",children:b.map(x=>jsxRuntime.jsxs("div",{className:"bg-content3 flex w-full flex-col items-center gap-2 rounded-lg px-4 py-3",children:[jsxRuntime.jsxs("div",{className:"flex w-full items-center justify-between",children:[jsxRuntime.jsx("div",{className:"text-neutral text-xs",children:"DEX"}),jsxRuntime.jsx("div",{className:"text-foreground text-xs",children:x.name})]}),jsxRuntime.jsxs("div",{className:"flex w-full items-center justify-between",children:[jsxRuntime.jsx("div",{className:"text-neutral text-xs",children:"Swap"}),jsxRuntime.jsxs("div",{className:"text-foreground flex items-center gap-2 text-xs",children:[jsxRuntime.jsxs("span",{children:[ke(x.inputAmount)," ",he(x.input)]}),jsxRuntime.jsx(ui.TradeIcon,{width:12,height:12,className:"text-foreground"}),jsxRuntime.jsxs("span",{children:[ke(x.outputAmount)," ",he(x.output)]})]})]}),x.feeAmount&&jsxRuntime.jsxs("div",{className:"flex w-full items-center justify-between",children:[jsxRuntime.jsx("div",{className:"text-neutral text-xs",children:"Fee"}),jsxRuntime.jsxs("div",{className:"text-foreground text-xs",children:[ke(x.feeAmount)," ",he(x.feeQuote)]})]})]},x.key))})]}),b.length>0&&jsxRuntime.jsx("div",{className:"flex justify-center",children:jsxRuntime.jsx(ui.Button,{size:"sm",className:"text-neutral flex bg-transparent text-xs",endContent:i?jsxRuntime.jsx(ui.ChevronUpIcon,{width:12,height:12}):jsxRuntime.jsx(ui.ChevronDownIcon,{width:12,height:12}),disableRipple:true,onPress:v,children:i?"Show Less":"Show More"})})]})}),jsxRuntime.jsx(ui.ModalFooter,{children:jsxRuntime.jsx(ui.Button,{fullWidth:true,color:"primary",className:"flex rounded-lg",disableRipple:true,isDisabled:!c||!!m,isLoading:!c&&d||h,onPress:f,children:"Confirm"})})]})})}function un(){return jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:12,height:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:"text-neutral",children:[jsxRuntime.jsx("path",{d:"M21 12V7H5a2 2 0 0 1 0-4h14v4"}),jsxRuntime.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h16v-5"}),jsxRuntime.jsx("path",{d:"M18 12a2 2 0 0 0 0 4h4v-4Z"})]})}function et(e){if(!e)return "0.00";let t=Number(e);return Number.isFinite(t)?t.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):"0.00"}function Ee(e){if(!e)return "0";let t=Number(e);return Number.isFinite(t)?t>=1e6?(t/1e6).toLocaleString("en-US",{maximumFractionDigits:2})+"M":t>=1e3?(t/1e3).toLocaleString("en-US",{maximumFractionDigits:2})+"K":t.toLocaleString("en-US",{maximumFractionDigits:6}):"0"}function ke(e){if(!e||e==="0")return "0";let t=Number(e);return Number.isFinite(t)?t>=1e12?(t/1e12).toFixed(2)+"T":t>=1e9?(t/1e9).toFixed(2)+"B":t>=1e6?(t/1e6).toFixed(2)+"M":t>=1e3?(t/1e3).toFixed(2)+"K":e:e}function he(e){return e?e.length<=10?e:`${e.slice(0,4)}...${e.slice(-4)}`:"\u2014"}function Ue({fromToken:e,toToken:t,fromBalance:r,toBalance:a,amount:l,amountInUsd:s,onAmountChange:n,onHalfAmount:o,onMaxAmount:u,outputAmount:c,outputAmountInUsd:d,onFromTokenSelect:m,onToTokenSelect:f,route:h,isRouting:i,routeError:g,onPreview:v,isSwapping:b,className:x}){return jsxRuntime.jsxs("div",{className:ui.cn("px-4 pb-4 lg:pb-8",x),children:[jsxRuntime.jsxs("div",{className:"space-y-3",children:[jsxRuntime.jsx("p",{className:"text-neutral text-sm font-medium",children:"From"}),jsxRuntime.jsxs("div",{className:"bg-content1 flex flex-col rounded-lg px-3.5 pb-2.5 pt-2",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx("div",{className:"flex-1",children:jsxRuntime.jsx(ui.Input,{type:"number",value:l??"",onChange:T=>n(T.target.value||void 0),placeholder:"0",classNames:{inputWrapper:ui.cn("h-10 p-0 bg-transparent","data-[hover=true]:bg-transparent group-data-[focus=true]:bg-transparent","group-data-[focus-visible=true]:ring-offset-transparent group-data-[focus-visible=true]:ring-transparent"),input:ui.cn("w-full h-full caret-primary text-3xl font-medium","placeholder:text-placeholder placeholder:text-3xl placeholder:font-medium","scrollbar-hide overflow-hidden text-ellipsis whitespace-nowrap")}})}),jsxRuntime.jsx("div",{className:"flex-0 flex h-full items-center justify-center",children:jsxRuntime.jsx(ui.Button,{className:ui.cn("flex min-w-0 h-8 min-h-8 pl-3 pr-2 bg-content3 rounded-full",e?"text-foreground":"text-neutral"),disableRipple:true,startContent:e?.image?jsxRuntime.jsx(ui.Avatar,{size:"sm",src:e.image,name:e.symbol,className:"h-6 w-6"}):null,endContent:jsxRuntime.jsx(ui.ChevronDownIcon,{width:16,height:16,className:"text-neutral"}),onPress:()=>m(""),children:e?e.symbol:"Select token"})})]}),jsxRuntime.jsxs("div",{className:"mt-3 flex items-center justify-between gap-4",children:[jsxRuntime.jsxs("div",{className:"text-neutral flex-1 text-xs",children:["\u2248 $",at(s)]}),r&&jsxRuntime.jsxs("div",{className:"flex-0 flex items-center gap-2 pr-3 text-xs",children:[jsxRuntime.jsx(rt,{}),jsxRuntime.jsxs("span",{className:"text-neutral",children:[it(r.amount)," ",r.symbol]}),o&&jsxRuntime.jsx("span",{className:"text-primary cursor-pointer",onClick:o,children:"Half"}),u&&jsxRuntime.jsx("span",{className:"text-primary cursor-pointer",onClick:u,children:"Max"})]})]}),g&&jsxRuntime.jsx("p",{className:"mt-1 break-words text-xs text-danger-500",children:g.message})]})]}),jsxRuntime.jsxs("div",{className:"mt-4 space-y-3",children:[jsxRuntime.jsx("p",{className:"text-neutral text-sm font-medium",children:"To"}),jsxRuntime.jsxs("div",{className:"bg-content1 flex flex-col rounded-lg px-3.5 pb-2.5 pt-2",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx("div",{className:"flex-1",children:jsxRuntime.jsx(ui.Input,{type:"number",value:c??"",disabled:true,placeholder:"0",classNames:{inputWrapper:ui.cn("h-10 p-0 bg-transparent","data-[hover=true]:bg-transparent group-data-[focus=true]:bg-transparent","group-data-[focus-visible=true]:ring-offset-transparent group-data-[focus-visible=true]:ring-transparent"),input:ui.cn("w-full h-full caret-primary text-3xl font-medium","placeholder:text-placeholder placeholder:text-3xl placeholder:font-medium","scrollbar-hide overflow-hidden text-ellipsis whitespace-nowrap")}})}),jsxRuntime.jsx("div",{className:"flex-0 flex h-full items-center justify-center",children:jsxRuntime.jsx(ui.Button,{className:ui.cn("flex min-w-0 h-8 min-h-8 pl-3 pr-2 bg-content3 rounded-full",t?"text-foreground":"text-neutral"),disableRipple:true,startContent:t?.image?jsxRuntime.jsx(ui.Avatar,{size:"sm",src:t.image,name:t.symbol,className:"h-6 w-6"}):null,endContent:jsxRuntime.jsx(ui.ChevronDownIcon,{width:16,height:16,className:"text-neutral"}),onPress:()=>f(""),children:t?t.symbol:"Select token"})})]}),jsxRuntime.jsxs("div",{className:"mt-3 flex items-center justify-between gap-4",children:[jsxRuntime.jsxs("div",{className:"text-neutral flex-1 text-xs",children:["\u2248 $",at(d)]}),a&&jsxRuntime.jsxs("div",{className:"flex-0 flex items-center gap-2 pr-3 text-xs",children:[jsxRuntime.jsx(rt,{}),jsxRuntime.jsxs("span",{className:"text-neutral",children:[it(a.amount)," ",a.symbol]})]})]})]})]}),jsxRuntime.jsx(ui.Button,{fullWidth:true,color:"primary",className:"mt-8 flex rounded-lg",disableRipple:true,isDisabled:!h,isLoading:!h&&i,onPress:v,children:b?"Swapping...":i?"Finding route...":"Swap"})]})}function rt(){return jsxRuntime.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:12,height:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:"text-neutral",children:[jsxRuntime.jsx("path",{d:"M21 12V7H5a2 2 0 0 1 0-4h14v4"}),jsxRuntime.jsx("path",{d:"M3 5v14a2 2 0 0 0 2 2h16v-5"}),jsxRuntime.jsx("path",{d:"M18 12a2 2 0 0 0 0 4h4v-4Z"})]})}function at(e){if(!e)return "0.00";let t=Number(e);return Number.isFinite(t)?t.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}):"0.00"}function it(e){if(!e)return "0";let t=Number(e);return Number.isFinite(t)?t>=1e6?(t/1e6).toLocaleString("en-US",{maximumFractionDigits:2})+"M":t>=1e3?(t/1e3).toLocaleString("en-US",{maximumFractionDigits:2})+"K":t.toLocaleString("en-US",{maximumFractionDigits:6}):"0"}function mn({chain:e,from:t,to:r,onComplete:a,className:l}){let s=Fe({chain:e,from:t,to:r,onComplete:a}),{isOpen:n,onOpen:o,onOpenChange:u,onClose:c}=ui.useDisclosure(),d=react.useCallback(async()=>{await s.swap(),c();},[s,c]);return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(Ue,{fromToken:s.fromToken,toToken:s.toToken,fromBalance:s.fromBalance,toBalance:s.toBalance,amount:s.amount,amountInUsd:s.amountInUsd,onAmountChange:s.setAmount,onHalfAmount:s.setHalfAmount,onMaxAmount:s.setMaxAmount,outputAmount:s.outputAmount,outputAmountInUsd:s.outputAmountInUsd,onFromTokenSelect:s.setFromTokenAddress,onToTokenSelect:s.setToTokenAddress,route:s.route,isRouting:s.isRouting,routeError:s.routeError,onPreview:o,isSwapping:s.isSwapping,className:l}),jsxRuntime.jsx(Me,{isOpen:n,onOpenChange:u,fromToken:s.fromToken,toToken:s.toToken,fromBalance:s.fromBalance,inputAmount:s.amount,inputAmountInUsd:s.amountInUsd,outputAmount:s.outputAmount,outputAmountInUsd:s.outputAmountInUsd,route:s.route,isRouting:s.isRouting,routeError:s.routeError,onConfirm:d,isSwapping:s.isSwapping})]})}var lt={slippage:20,priorityFee:.001,tipFee:.001,autoFee:false,maxAutoFee:.1,antiMev:"off",customRPC:null},ut={slippage:1,priorityFee:5,tipFee:null,autoFee:false,maxAutoFee:null,antiMev:"off",customRPC:null},dt={slippage:1,priorityFee:5,tipFee:.001,autoFee:false,maxAutoFee:null,antiMev:"off",customRPC:null},kr=[.01,.1,1,10],Mr=[10,25,50,100];var Be=new Set([types.Chain.SOLANA,types.Chain.SOLANA_TESTNET,types.Chain.SOLANA_DEVNET]),ct=new Set([types.Chain.BINANCE,types.Chain.BINANCE_TESTNET]);function te(e,t="ETH"){return Be.has(e)?{feeLabel:"Priority Fee",feeUnit:"SOL",feeDecimals:9,showTipFee:true,tipFeeUnit:"SOL",tipFeeDecimals:9,antiMevOptions:["off","reduced","secure"]}:ct.has(e)?{feeLabel:"Gas Fee",feeUnit:"Gwei",feeDecimals:2,showTipFee:true,tipFeeUnit:"BNB",tipFeeDecimals:9,antiMevOptions:["off","secure"]}:{feeLabel:"Gas Fee",feeUnit:"Gwei",feeDecimals:2,showTipFee:false,tipFeeUnit:t,tipFeeDecimals:9,antiMevOptions:["off","secure"]}}function gn(e){return Be.has(e)}function $(e){return Be.has(e)?lt:ct.has(e)?dt:ut}function mt(e){let t=$(e);return {buy:{customAmounts:[.01,.1,1,10],presets:[{...t},{...t},{...t}]},sell:{customPercentages:[10,25,50,100],presets:[{...t},{...t},{...t}]}}}var vn=mt("900900900");function pt(e){return `liberfi.instant-trade.settings.${e}`}function Sn(e,t){try{let r=localStorage.getItem(pt(String(e)));if(r)return JSON.parse(r)}catch{}return t}function wn(e,t){try{localStorage.setItem(pt(e),JSON.stringify(t));}catch{}}var ft=react.createContext(null);function ne(){let e=react.useContext(ft);if(!e)throw new Error("useInstantTrade must be used within an InstantTradeProvider");return e}function _e({chain:e,tokenAddress:t,settings:r,onSettingsChange:a,children:l}){let s=react.useMemo(()=>utils.getNativeToken(e),[e]),n=r!==void 0,o=react.useMemo(()=>mt(e),[e]),[u,c]=react.useState(()=>n?o:Sn(e,o)),d=n?r:u,m=react.useCallback(A=>{n?a?.(A):(c(A),wn(String(e),A));},[n,a,e]),f=react.useCallback(A=>m({...d,buy:A}),[d,m]),h=react.useCallback(A=>m({...d,sell:A}),[d,m]),[i,g]=react.useState("buy"),[v,b]=react.useState(),[x,T]=react.useState(0),[M,I]=react.useState(0),R=react.useMemo(()=>$(e),[e]),k=react.useMemo(()=>{let A=i==="buy"?x:M;return (i==="buy"?d.buy.presets:d.sell.presets)[A]??R},[i,x,M,d,R]),U=react.useMemo(()=>({chain:e,tokenAddress:t,nativeToken:s,direction:i,setDirection:g,amount:v,setAmount:b,buyPreset:x,setBuyPreset:T,sellPreset:M,setSellPreset:I,settings:d,updateBuySettings:f,updateSellSettings:h,currentPresetValues:k}),[e,t,s,i,v,x,M,d,f,h,k]);return jsxRuntime.jsx(ft.Provider,{value:U,children:l})}var En=new Set([types.Chain.SOLANA,types.Chain.SOLANA_TESTNET,types.Chain.SOLANA_DEVNET]);function kn(e){return En.has(e)?types.ChainNamespace.SOLANA:types.ChainNamespace.EVM}var Mn=15e3,Rn=1e4;function Ve(e){let{chain:t,tokenAddress:r,onSwapSubmitted:a,onSwapError:l}=e,s=ne(),n=react.useMemo(()=>utils.getNativeToken(t),[t]),o=react.useMemo(()=>utils.getWrappedToken(t),[t]),u=walletConnector.useWallets(),c=kn(t),d=react.useMemo(()=>u.find(y=>y.chainNamespace===c&&y.isConnected),[u,c]),m=d?.address??"",f=react.useMemo(()=>{let y=[r];return n&&y.push(n.address),o&&y.push(o.address),y.filter(Boolean)},[r,n,o]),h=react$1.useTokensQuery({chain:t,addresses:f},{enabled:f.length>0,refetchInterval:Rn}),i=react.useMemo(()=>h.data?.find(y=>y.address===r)??null,[h.data,r]),g=react$1.useWalletPortfoliosByTokensQuery({chain:t,address:m,tokenAddresses:f},{enabled:!!m&&f.length>0,refetchInterval:Mn}),v=n?.address??o?.address??"",b=react.useMemo(()=>g.data?.find(y=>y.address===v)??null,[g.data,v]),x=react.useMemo(()=>g.data?.find(y=>y.address===r)??null,[g.data,r]),[T,M]=react.useState(false),I=react.useRef(null),R=react.useCallback(y=>{let B=I.current;I.current=y,M(O=>B===null||B!==y?true:!O);},[]),k=react.useRef(a);k.current=a;let U=react.useRef(l);U.current=l;let{swap:A,isSwapping:z}=re({onSubmitted:y=>k.current?.(y),onError:(y,B)=>U.current?.(y,B)}),L=react.useCallback(async()=>{if(!s.amount||!d||!r)return;let y=n?.decimals??9,B=o?.address??n?.address??"",O=s.direction==="buy",K=O?B:r,le=O?r:B,G=O?y:i?.decimals??9,X=new ae__default.default(s.amount).shiftedBy(G).decimalPlaces(0).toString(),Y=s.currentPresetValues,se=$(t),w=new ae__default.default(Y.priorityFee??se.priorityFee??0).shiftedBy(y).decimalPlaces(0).toString(),D=new ae__default.default(Y.tipFee??se.tipFee??0).shiftedBy(y).decimalPlaces(0).toString();try{await A({chain:t,wallet:d,input:K,output:le,amount:X,slippage:Y.slippage??se.slippage??1,priorityFee:w,tipFee:D,isAntiMev:Y.antiMev!=="off"}),s.setAmount(void 0);}catch{}},[s,d,r,n,o,i,t,A]),q=react.useMemo(()=>{let y=s.direction==="buy"?"Buy":"Sell";if(!s.amount)return y;if(s.direction==="buy"){let O=b?.amount;if(O&&new ae__default.default(O).lt(s.amount))return `${y} (Insufficient balance)`;let K=n?.symbol??"";i?.marketData?.priceInUsd?Number(i.marketData.priceInUsd):null;let G=h.data?.find(X=>X.address===v)?.marketData?.priceInUsd;if(G){let X=utils.formatAmountUSD(new ae__default.default(s.amount).times(Number(G)));return `${y} ${s.amount} ${K} (${X})`}return `${y} ${s.amount} ${K}`}let B=x?.amount;return B&&new ae__default.default(B).lt(s.amount)?`${y} (Insufficient balance)`:y},[s.direction,s.amount,b,x,n,i,h.data,v]),J=!s.amount||!d||!r,H=h.isPending||g.isPending;return react.useMemo(()=>({chain:t,tokenAddress:r,nativeToken:n,tokenInfo:i,nativeBalance:b,tokenBalance:x,direction:s.direction,setDirection:s.setDirection,amount:s.amount,setAmount:s.setAmount,buyPreset:s.buyPreset,setBuyPreset:s.setBuyPreset,sellPreset:s.sellPreset,setSellPreset:s.setSellPreset,currentPresetValues:s.currentPresetValues,settings:s.settings,updateBuySettings:s.updateBuySettings,updateSellSettings:s.updateSellSettings,showSettings:T,handlePresetClick:R,swap:L,isSwapping:z,submitText:q,isDisabled:J,isLoading:H}),[t,r,n,i,b,x,s,T,R,L,z,q,J,H])}function me({value:e,onChange:t,chain:r,nativeSymbol:a="SOL",nativeDecimals:l=9,className:s}){let n=react.useCallback(u=>t({...e,...u}),[e,t]),o=react.useMemo(()=>te(r,a),[r,a]);return jsxRuntime.jsxs("div",{className:ui.cn("space-y-1.5",s),children:[jsxRuntime.jsx(Vn,{value:e.slippage,onChange:u=>n({slippage:u})}),jsxRuntime.jsx(Wn,{value:e.priorityFee,onChange:u=>n({priorityFee:u}),label:o.feeLabel,symbol:o.feeUnit,decimals:o.feeDecimals}),o.showTipFee&&jsxRuntime.jsx(zn,{value:e.tipFee,onChange:u=>n({tipFee:u}),symbol:o.tipFeeUnit,decimals:o.tipFeeDecimals}),jsxRuntime.jsx($n,{value:e.autoFee,onChange:u=>n({autoFee:u})}),e.autoFee&&jsxRuntime.jsx(Qn,{value:e.maxAutoFee,onChange:u=>n({maxAutoFee:u}),symbol:a}),jsxRuntime.jsx(Hn,{value:e.antiMev,onChange:u=>n({antiMev:u}),options:o.antiMevOptions}),jsxRuntime.jsx(Kn,{value:e.customRPC,onChange:u=>n({customRPC:u})})]})}var pe={inputWrapper:"bg-content2 data-[hover=true]:bg-content3 group-data-[focus=true]:bg-content3 h-8 min-h-0 py-0",input:"text-xs"};function ye(e){return react.useCallback(t=>{typeof t=="number"&&e(isNaN(t)?null:t);},[e])}function Vn({value:e,onChange:t}){let r=ye(t);return jsxRuntime.jsxs("div",{className:"w-full grid grid-cols-2 gap-2 items-center",children:[jsxRuntime.jsx("div",{className:"text-xs text-neutral",children:"Slippage"}),jsxRuntime.jsx(ui.NumberInput,{fullWidth:true,value:e===null?void 0:e,onChange:r,hideStepper:true,minValue:0,maxValue:100,step:1,endContent:jsxRuntime.jsx("span",{className:"text-xs text-neutral",children:"%"}),classNames:pe,"aria-label":"Slippage"})]})}function Wn({value:e,onChange:t,label:r="Priority Fee",symbol:a,decimals:l}){let s=ye(t);return jsxRuntime.jsxs("div",{className:"w-full grid grid-cols-2 gap-2 items-center",children:[jsxRuntime.jsxs("div",{className:"text-xs text-neutral flex items-center gap-1",children:[r,jsxRuntime.jsx(ui.Tooltip,{content:"Extra fee paid to validators to prioritize your transaction.",classNames:{content:"text-xs text-neutral py-2 px-4 max-w-xs"},children:jsxRuntime.jsx(ui.Button,{isIconOnly:true,className:"bg-transparent min-w-0 w-4 min-h-0 h-4 p-0",size:"sm",disableRipple:true,children:jsxRuntime.jsx(ui.InfoIcon,{width:13,height:13,className:"text-neutral"})})})]}),jsxRuntime.jsx(ui.NumberInput,{fullWidth:true,value:e===null?void 0:e,onChange:s,hideStepper:true,minValue:0,formatOptions:{maximumFractionDigits:l},endContent:jsxRuntime.jsx("span",{className:"text-xs text-neutral",children:a}),classNames:pe,"aria-label":"Priority Fee"})]})}function zn({value:e,onChange:t,symbol:r,decimals:a}){let l=ye(t);return jsxRuntime.jsxs("div",{className:"w-full grid grid-cols-2 gap-2 items-center",children:[jsxRuntime.jsxs("div",{className:"text-xs text-neutral flex items-center gap-1",children:["Tip Fee",jsxRuntime.jsx(ui.Tooltip,{content:"Additional tip sent alongside the transaction (e.g. Jito tip).",classNames:{content:"text-xs text-neutral py-2 px-4 max-w-xs"},children:jsxRuntime.jsx(ui.Button,{isIconOnly:true,className:"bg-transparent min-w-0 w-4 min-h-0 h-4 p-0",size:"sm",disableRipple:true,children:jsxRuntime.jsx(ui.InfoIcon,{width:13,height:13,className:"text-neutral"})})})]}),jsxRuntime.jsx(ui.NumberInput,{fullWidth:true,value:e===null?void 0:e,onChange:l,hideStepper:true,minValue:0,formatOptions:{maximumFractionDigits:a},endContent:jsxRuntime.jsx("span",{className:"text-xs text-neutral",children:r}),classNames:pe,"aria-label":"Tip Fee"})]})}function $n({value:e,onChange:t}){return jsxRuntime.jsxs("div",{className:"w-full grid grid-cols-2 gap-2 items-center",children:[jsxRuntime.jsxs("div",{className:"text-xs text-neutral flex items-center gap-1",children:["Auto Fee",jsxRuntime.jsx(ui.Tooltip,{content:"Automatically estimate optimal fee based on network conditions.",classNames:{content:"text-xs text-neutral py-2 px-4 max-w-xs"},children:jsxRuntime.jsx(ui.Button,{isIconOnly:true,className:"bg-transparent min-w-0 w-4 min-h-0 h-4 p-0",size:"sm",disableRipple:true,children:jsxRuntime.jsx(ui.InfoIcon,{width:13,height:13,className:"text-neutral"})})})]}),jsxRuntime.jsx("div",{className:"flex justify-end",children:jsxRuntime.jsx(ui.Switch,{isSelected:e,onValueChange:t,color:"primary",size:"sm","aria-label":"Auto Fee"})})]})}function Qn({value:e,onChange:t,symbol:r}){let a=ye(t);return jsxRuntime.jsxs("div",{className:"w-full grid grid-cols-2 gap-2 items-center",children:[jsxRuntime.jsx("div",{className:"text-xs text-neutral",children:"Max Auto Fee"}),jsxRuntime.jsx(ui.NumberInput,{fullWidth:true,value:e===null?void 0:e,onChange:a,hideStepper:true,minValue:0,endContent:jsxRuntime.jsx("span",{className:"text-xs text-neutral",children:r}),classNames:pe,"aria-label":"Max Auto Fee"})]})}var jn={off:"Off",reduced:"Reduced",secure:"Secure"};function Hn({value:e,onChange:t,options:r}){return jsxRuntime.jsxs("div",{className:"w-full grid grid-cols-2 gap-2 items-center",children:[jsxRuntime.jsxs("div",{className:"text-xs text-neutral flex items-center gap-1",children:["Anti-MEV",jsxRuntime.jsx(ui.Tooltip,{content:"MEV protection shields your transaction from sandwich attacks.",classNames:{content:"text-xs text-neutral py-2 px-4 max-w-xs"},children:jsxRuntime.jsx(ui.Button,{isIconOnly:true,className:"bg-transparent min-w-0 w-4 min-h-0 h-4 p-0",size:"sm",disableRipple:true,children:jsxRuntime.jsx(ui.InfoIcon,{width:13,height:13,className:"text-neutral"})})})]}),jsxRuntime.jsx("div",{className:"flex justify-end",children:jsxRuntime.jsx(ui.Tabs,{variant:"bordered",color:"primary",size:"sm",disableAnimation:true,radius:"lg",classNames:{tabList:"border-border border-1 gap-0",tab:"min-h-0 h-5 px-2"},selectedKey:e,onSelectionChange:t,"aria-label":"Anti-MEV",children:r.map(a=>jsxRuntime.jsx(ui.Tab,{title:jn[a]??a},a))})})]})}function Kn({value:e,onChange:t}){return jsxRuntime.jsxs("div",{className:"w-full flex gap-4 items-center",children:[jsxRuntime.jsx("div",{className:"flex-none text-xs text-neutral",children:"Custom RPC"}),jsxRuntime.jsx("div",{className:"flex-auto",children:jsxRuntime.jsx(ui.Input,{fullWidth:true,value:e??"",onValueChange:r=>t(r||null),classNames:pe,placeholder:"https://...","aria-label":"Custom RPC"})})]})}function $e({chain:e,direction:t,onDirectionChange:r,amount:a,onAmountChange:l,customAmounts:s,customPercentages:n,onQuickAmountClick:o,onQuickPercentageClick:u,onCustomAmountsEdit:c,onCustomPercentagesEdit:d,tokenSymbol:m,nativeSymbol:f,nativeDecimals:h,nativeBalance:i,tokenBalance:g,amountConversion:v,preset:b,onPresetChange:x,presetValues:T,onPresetSettingsChange:M,showSettings:I,onPresetClick:R,submitText:k,isDisabled:U,isLoading:A,onSubmit:z,className:L,headerExtra:q}){return jsxRuntime.jsxs("div",{className:ui.cn("flex-none sm:px-3 py-3 bg-content1 rounded-lg",L),children:[jsxRuntime.jsxs(ui.Tabs,{fullWidth:true,size:"sm",selectedKey:t,onSelectionChange:r,classNames:{tabList:"bg-content2",tab:"data-[selected=true]:bg-content3 h-6"},disableAnimation:true,children:[jsxRuntime.jsx(ui.Tab,{title:"Buy"},"buy"),jsxRuntime.jsx(ui.Tab,{title:"Sell"},"sell")]}),jsxRuntime.jsxs("div",{className:"mt-2.5 h-8 flex items-center justify-between",children:[jsxRuntime.jsx(ui.Tabs,{size:"sm",variant:"underlined",classNames:{tabList:"gap-0",tab:"px-1.5"},selectedKey:"market",disableAnimation:true,children:jsxRuntime.jsx(ui.Tab,{title:"Market"},"market")}),q]}),jsxRuntime.jsx("div",{className:"mt-2.5",children:t==="buy"?jsxRuntime.jsx(rs,{amount:a,onAmountChange:l,customAmounts:s,onQuickAmountClick:o,onCustomAmountsEdit:c,nativeSymbol:f,nativeDecimals:h}):jsxRuntime.jsx(as,{amount:a,onAmountChange:l,customPercentages:n,onQuickPercentageClick:u,onCustomPercentagesEdit:d,tokenSymbol:m})}),jsxRuntime.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[jsxRuntime.jsxs("div",{className:"text-xs text-neutral space-x-1",children:[jsxRuntime.jsx("span",{children:"Balance:"}),jsxRuntime.jsx("span",{children:t==="buy"?i?`${i} ${f??""}`:"--":g?`${g} ${m??""}`:"--"})]}),v&&jsxRuntime.jsx("div",{className:"text-xs text-neutral",children:v})]}),jsxRuntime.jsx("div",{className:"mt-4",children:jsxRuntime.jsx(is,{values:T,chain:e})}),jsxRuntime.jsx("div",{className:"mt-2",children:jsxRuntime.jsxs(ui.Tabs,{variant:"bordered",size:"sm",fullWidth:true,classNames:{tabList:"border-content3 border-1 gap-0 p-0.5",tab:"min-h-0 h-6 px-2 py-1 text-xs data-[selected=true]:bg-content3",tabContent:"text-neutral"},selectedKey:`${b}`,onSelectionChange:J=>x(Number(J)),disableAnimation:true,"aria-label":"Presets",children:[jsxRuntime.jsx(ui.Tab,{title:"Preset 1",onClick:()=>R(0)},0),jsxRuntime.jsx(ui.Tab,{title:"Preset 2",onClick:()=>R(1)},1),jsxRuntime.jsx(ui.Tab,{title:"Preset 3",onClick:()=>R(2)},2)]})}),I&&jsxRuntime.jsx("div",{className:"mt-2.5",children:jsxRuntime.jsx(me,{value:T,onChange:M,chain:e,nativeSymbol:f,nativeDecimals:h})}),jsxRuntime.jsx(ui.Button,{fullWidth:true,size:"sm",color:t==="buy"?"primary":"secondary",className:"mt-2 rounded-lg",disableRipple:true,isDisabled:U,isLoading:A,onPress:z,children:k})]})}function rs({amount:e,onAmountChange:t,customAmounts:r,onQuickAmountClick:a,onCustomAmountsEdit:l,nativeSymbol:s,nativeDecimals:n}){let o=react.useCallback(u=>{typeof u=="number"&&t(isNaN(u)?void 0:u);},[t]);return jsxRuntime.jsxs("div",{className:"space-y-0.5",children:[jsxRuntime.jsx(ui.NumberInput,{min:0,value:e,onChange:o,fullWidth:true,hideStepper:true,startContent:jsxRuntime.jsx("span",{className:"flex-none text-xs text-neutral",children:"Amount"}),endContent:jsxRuntime.jsx("span",{className:"flex-none text-xs text-neutral",children:s??""}),formatOptions:{maximumFractionDigits:n??9},classNames:{inputWrapper:ui.cn("h-8 min-h-0 py-0 rounded-lg rounded-b-none shadow-none","bg-content2 data-[hover=true]:bg-content3 group-data-[focus=true]:bg-content3"),input:"text-xs"}}),jsxRuntime.jsx(St,{values:r,onSelect:a,onEdit:l})]})}function as({amount:e,onAmountChange:t,customPercentages:r,onQuickPercentageClick:a,onCustomPercentagesEdit:l,tokenSymbol:s}){let n=react.useCallback(o=>{typeof o=="number"&&t(isNaN(o)?void 0:o);},[t]);return jsxRuntime.jsxs("div",{className:"space-y-0.5",children:[jsxRuntime.jsx(ui.NumberInput,{min:0,value:e,onChange:n,fullWidth:true,hideStepper:true,startContent:jsxRuntime.jsx("span",{className:"flex-none text-xs text-neutral",children:"Amount"}),endContent:jsxRuntime.jsx("span",{className:"flex-none text-xs text-neutral",children:s??""}),classNames:{inputWrapper:ui.cn("h-8 min-h-0 py-0 rounded-lg rounded-b-none shadow-none","bg-content2 data-[hover=true]:bg-content3 group-data-[focus=true]:bg-content3"),input:"text-xs"}}),jsxRuntime.jsx(St,{values:r,onSelect:a,onEdit:l,suffix:"%"})]})}function St({values:e,onSelect:t,onEdit:r,suffix:a}){let[l,s]=react.useState(false),[n,o]=react.useState([]),u=react.useCallback(()=>{o([...e]),s(true);},[e]),c=react.useCallback(()=>{s(false),r(n);},[r,n]);return jsxRuntime.jsxs("div",{className:"flex gap-0.5",children:[jsxRuntime.jsx("div",{className:"flex-auto grid grid-cols-4 gap-0.5",children:Array.from({length:4}).map((d,m)=>jsxRuntime.jsx("div",{className:ui.cn("h-6 bg-content2 flex items-center justify-center",m===0&&"rounded-bl-lg"),children:l?jsxRuntime.jsx(ui.NumberInput,{fullWidth:true,value:n[m]===null||n[m]===void 0?void 0:n[m],onChange:f=>{if(typeof f=="number"){let h=isNaN(f)?null:f;o(i=>{let g=[...i];return g[m]=h,g});}},min:0,hideStepper:true,classNames:{inputWrapper:ui.cn("p-0 h-6 min-h-0 rounded-none flex shadow-none","bg-content2 data-[hover=true]:bg-content3 group-data-[focus=true]:bg-content3",m===0&&"rounded-bl-lg"),innerWrapper:"pb-0",input:"text-xs text-center"}}):jsxRuntime.jsx(ui.Button,{className:"min-w-0 w-full min-h-0 h-full p-0 bg-transparent text-xs",size:"sm",disableRipple:true,onPress:()=>e[m]!=null&&t(e[m]),endContent:a?jsxRuntime.jsx("span",{className:"text-xs text-neutral",children:a}):null,children:e[m]??""})},m))}),jsxRuntime.jsx("div",{className:"flex-none bg-content2 rounded-br-lg overflow-hidden",children:l?jsxRuntime.jsx(ui.Button,{size:"sm",isIconOnly:true,className:"bg-transparent h-6 min-h-6 p-0",disableRipple:true,onPress:c,children:jsxRuntime.jsx(ui.CheckIcon,{width:12,height:12})}):jsxRuntime.jsx(ui.Button,{size:"sm",isIconOnly:true,className:"bg-transparent h-6 min-h-6 p-0",disableRipple:true,onPress:u,children:jsxRuntime.jsx(ui.EditIcon,{width:12,height:12})})})]})}function is({values:e,chain:t}){let r=react.useMemo(()=>te(t),[t]);return jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx(ui.Tooltip,{content:"Slippage",classNames:{content:"text-xs text-neutral py-2 px-4 max-w-xs"},children:jsxRuntime.jsx(ui.Button,{size:"sm",className:"bg-transparent p-0 h-5 min-h-0 w-auto min-w-0 gap-0.5 text-xs text-neutral",disableRipple:true,startContent:jsxRuntime.jsx(ui.SlippageIcon,{width:14,height:14}),children:utils.formatPercent((e.slippage??0)/100)})}),jsxRuntime.jsx(ui.Tooltip,{content:r.feeLabel,classNames:{content:"text-xs text-neutral py-2 px-4 max-w-xs"},children:jsxRuntime.jsx(ui.Button,{size:"sm",className:"bg-transparent p-0 h-5 min-h-0 w-auto min-w-0 gap-0.5 text-xs text-neutral",disableRipple:true,startContent:jsxRuntime.jsx(ui.ZapFastIcon,{width:14,height:14}),children:utils.formatPrice(e.priorityFee??0)})}),r.showTipFee&&jsxRuntime.jsx(ui.Tooltip,{content:"Tip Fee",classNames:{content:"text-xs text-neutral py-2 px-4 max-w-xs"},children:jsxRuntime.jsx(ui.Button,{size:"sm",className:"bg-transparent p-0 h-5 min-h-0 w-auto min-w-0 gap-0.5 text-xs text-neutral",disableRipple:true,startContent:jsxRuntime.jsx(ui.CoinsIcon,{width:14,height:14}),children:utils.formatPrice(e.tipFee??0)})}),jsxRuntime.jsx(ui.Tooltip,{content:"Anti-MEV",classNames:{content:"text-xs text-neutral py-2 px-4 max-w-xs"},children:jsxRuntime.jsxs(ui.Button,{size:"sm",className:"bg-transparent p-0 h-5 min-h-0 w-auto min-w-0 gap-0.5 text-xs text-neutral",disableRipple:true,startContent:jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[(!e.antiMev||e.antiMev==="off")&&jsxRuntime.jsx(ui.ShieldOffIcon,{width:14,height:14,className:"text-neutral"}),e.antiMev==="reduced"&&jsxRuntime.jsx(ui.ShieldIcon,{width:14,height:14,className:"text-neutral"}),e.antiMev==="secure"&&jsxRuntime.jsx(ui.ShieldPlusIcon,{width:14,height:14,className:"text-neutral"})]}),children:[(!e.antiMev||e.antiMev==="off")&&"Off",e.antiMev==="reduced"&&"Reduced",e.antiMev==="secure"&&"Secure"]})})]})}function us({chain:e,tokenAddress:t,onSwapSubmitted:r,onSwapError:a,settings:l,onSettingsChange:s,headerExtra:n,className:o}){return jsxRuntime.jsx(_e,{chain:e,tokenAddress:t,settings:l,onSettingsChange:s,children:jsxRuntime.jsx(ds,{chain:e,tokenAddress:t,onSwapSubmitted:r,onSwapError:a,headerExtra:n,className:o})})}function ds({chain:e,tokenAddress:t,onSwapSubmitted:r,onSwapError:a,headerExtra:l,className:s}){let n=Ve({chain:e,tokenAddress:t,onSwapSubmitted:r,onSwapError:a}),o=react.useCallback(i=>n.setAmount(i),[n]),u=react.useCallback(i=>{let g=n.tokenBalance?.amount;if(!g)return;let v=new ae__default.default(g).times(i).div(100).toNumber();n.setAmount(v);},[n]),c=react.useCallback(i=>{n.updateBuySettings({...n.settings.buy,customAmounts:i});},[n]),d=react.useCallback(i=>{n.updateSellSettings({...n.settings.sell,customPercentages:i});},[n]),m=react.useCallback(i=>{let g=n.direction==="buy",v=g?n.buyPreset:n.sellPreset;if(g){let b=n.settings.buy,x=[...b.presets];x[v]=i,n.updateBuySettings({...b,presets:x});}else {let b=n.settings.sell,x=[...b.presets];x[v]=i,n.updateSellSettings({...b,presets:x});}},[n]),f=react.useCallback(i=>{n.direction==="buy"?n.setBuyPreset(i):n.setSellPreset(i);},[n]),h=n.direction==="buy"?n.buyPreset:n.sellPreset;return jsxRuntime.jsx($e,{chain:e,direction:n.direction,onDirectionChange:n.setDirection,amount:n.amount,onAmountChange:n.setAmount,customAmounts:n.settings.buy.customAmounts,customPercentages:n.settings.sell.customPercentages,onQuickAmountClick:o,onQuickPercentageClick:u,onCustomAmountsEdit:c,onCustomPercentagesEdit:d,tokenSymbol:n.tokenInfo?.symbol,nativeSymbol:n.nativeToken?.symbol,nativeDecimals:n.nativeToken?.decimals,nativeBalance:n.nativeBalance?.amount,tokenBalance:n.tokenBalance?.amount,amountConversion:void 0,preset:h,onPresetChange:f,presetValues:n.currentPresetValues,onPresetSettingsChange:m,showSettings:n.showSettings,onPresetClick:n.handlePresetClick,submitText:n.submitText,isDisabled:n.isDisabled,isLoading:n.isSwapping,onSubmit:n.swap,className:s,headerExtra:l})}function hs({value:e,onChange:t,chain:r,className:a}){let l=react.useMemo(()=>utils.getNativeToken(r),[r]),s=hooks.useCallbackRef(t),[n,o]=react.useState(e);react.useEffect(()=>{o(e);},[e]);let u=react.useCallback(c=>{o(c),s(c);},[s]);return jsxRuntime.jsx(me,{value:n,onChange:u,chain:r,nativeSymbol:l?.symbol,nativeDecimals:l?.decimals,className:a})}function ks({amount:e,onAmountChange:t,preset:r=0,onPresetChange:a,onPresetClick:l,variant:s="default",radius:n="full",size:o="sm",fullWidth:u=false,className:c}){let{chain:d,nativeToken:m,settings:f}=ne(),h=react.useMemo(()=>$(d),[d]),i=react.useCallback(v=>{typeof v=="number"&&t(isNaN(v)?void 0:v);},[t]),g=react.useCallback(v=>{r===v?l?.(v):a?.(v);},[r,a,l]);return jsxRuntime.jsxs("div",{className:ui.cn("flex items-center gap-1.5 overflow-hidden px-3",n==="full"&&"rounded-full",n==="lg"&&"rounded-lg",n==="md"&&"rounded-md",n==="sm"&&"rounded-sm",s==="bordered"&&"border-1 border-border",s==="default"&&"bg-content2",c),children:[jsxRuntime.jsx("div",{className:ui.cn(u?"w-full":"w-20"),children:jsxRuntime.jsx(ui.NumberInput,{fullWidth:true,value:e,onChange:i,hideStepper:true,minValue:0,formatOptions:{maximumFractionDigits:m?.decimals??9},startContent:jsxRuntime.jsx(ui.LightningIcon,{width:12,height:12,className:"text-neutral flex-none"}),endContent:m?jsxRuntime.jsx(ui.Avatar,{className:"w-4 h-4 bg-transparent flex-none",name:m.symbol}):null,classNames:{inputWrapper:ui.cn("bg-transparent data-[hover=true]:bg-transparent group-data-[focus=true]:bg-transparent","w-full min-w-0 min-h-0 p-0 rounded-none",o==="sm"&&"h-6",o==="lg"&&"h-8"),input:"text-sm"},placeholder:"0.0","aria-label":"Instant trade amount"})}),jsxRuntime.jsx("div",{className:"w-px bg-border h-4"}),jsxRuntime.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:3}).map((v,b)=>jsxRuntime.jsx(ui.Tooltip,{content:jsxRuntime.jsx(Ms,{values:f.buy.presets[b]??h,chain:d}),placement:"bottom",children:jsxRuntime.jsx(ui.Button,{className:ui.cn("w-auto min-w-0 h-auto min-h-0 px-1 py-0.5 text-xs bg-transparent rounded",{"text-primary hover:bg-primary/20":b===r,"text-neutral hover:bg-content3":b!==r}),disableRipple:true,onPress:()=>g(b),children:`P${b+1}`})},b))})]})}function Ms({values:e,chain:t}){let r=react.useMemo(()=>te(t),[t]);return jsxRuntime.jsxs("div",{className:"px-1 py-0.5 flex flex-col gap-1.5 text-xs text-neutral",children:[jsxRuntime.jsxs("div",{className:"w-full flex items-center justify-between gap-3",children:[jsxRuntime.jsx(ui.SlippageIcon,{width:14,height:14}),jsxRuntime.jsx("span",{children:utils.formatPercent((e.slippage??0)/100)})]}),jsxRuntime.jsxs("div",{className:"w-full flex items-center justify-between gap-3",children:[jsxRuntime.jsx(ui.ZapFastIcon,{width:14,height:14}),jsxRuntime.jsxs("span",{children:[utils.formatPrice(e.priorityFee??0)," ",r.feeUnit]})]}),r.showTipFee&&jsxRuntime.jsxs("div",{className:"w-full flex items-center justify-between gap-3",children:[jsxRuntime.jsx(ui.CoinsIcon,{width:14,height:14}),jsxRuntime.jsxs("span",{children:[utils.formatPrice(e.tipFee??0)," ",r.tipFeeUnit]})]}),jsxRuntime.jsxs("div",{className:"w-full flex items-center justify-between gap-3",children:[(!e.antiMev||e.antiMev==="off")&&jsxRuntime.jsx(ui.ShieldOffIcon,{width:14,height:14}),e.antiMev==="reduced"&&jsxRuntime.jsx(ui.ShieldIcon,{width:14,height:14}),e.antiMev==="secure"&&jsxRuntime.jsx(ui.ShieldPlusIcon,{width:14,height:14}),jsxRuntime.jsxs("span",{children:[(!e.antiMev||e.antiMev==="off")&&"Off",e.antiMev==="reduced"&&"Reduced",e.antiMev==="secure"&&"Secure"]})]})]})}function Os({className:e,children:t}){let{chain:r,tokenAddress:a,nativeToken:l,direction:s,amount:n,setAmount:o,currentPresetValues:u}=ne(),d=walletConnector.useWallets()[0]??null,m=react.useMemo(()=>utils.getWrappedToken(r),[r]),{swap:f,isSwapping:h}=re(),i=!n||!d||!a,g=react.useCallback(async()=>{if(!n||!d||!a)return;let v=l??utils.getNativeToken(r),b=v?.decimals??9,x=m?.address??v?.address??"",T=s==="buy",M=T?x:a,I=T?a:x,R=new ae__default.default(n).shiftedBy(b).decimalPlaces(0).toString(),k=u,U=$(r),A=new ae__default.default(k.priorityFee??U.priorityFee??0).shiftedBy(b).decimalPlaces(0).toString(),z=new ae__default.default(k.tipFee??U.tipFee??0).shiftedBy(b).decimalPlaces(0).toString();try{await f({chain:r,wallet:d,input:M,output:I,amount:R,slippage:k.slippage??U.slippage??1,priorityFee:A,tipFee:z,isAntiMev:k.antiMev!=="off"}),o(void 0);}catch{}},[n,d,a,l,m,r,s,u,f,o]);return jsxRuntime.jsx(ui.Button,{fullWidth:true,size:"sm",color:s==="buy"?"primary":"secondary",className:e,disableRipple:true,isDisabled:i,isLoading:h,onPress:g,children:t??(s==="buy"?"Buy":"Sell")})}typeof window<"u"&&(window.__LIBERFI_VERSION__=window.__LIBERFI_VERSION__||{},window.__LIBERFI_VERSION__["@liberfi.io/ui-trade"]="0.1.4");var Ws="0.1.4";
|
|
2
|
+
exports.DEFAULT_BSC_TRADE_PRESET=dt;exports.DEFAULT_BUY_AMOUNTS=kr;exports.DEFAULT_EVM_TRADE_PRESET=ut;exports.DEFAULT_INSTANT_TRADE_SETTINGS=vn;exports.DEFAULT_SELL_PERCENTAGES=Mr;exports.DEFAULT_TRADE_PRESET=lt;exports.InstantTradeAmountInput=ks;exports.InstantTradeButton=Os;exports.InstantTradeProvider=_e;exports.InstantTradeUI=$e;exports.InstantTradeWidget=us;exports.PresetFormUI=me;exports.PresetFormWidget=hs;exports.SwapPreviewModal=Me;exports.SwapUI=Ue;exports.SwapWidget=mn;exports.getChainPresetFeatures=te;exports.getDefaultPresetForChain=$;exports.isSolanaChain=gn;exports.useInstantTrade=ne;exports.useInstantTradeScript=Ve;exports.useSwap=re;exports.useSwapRoutePolling=Ke;exports.useSwapScript=Fe;exports.useTxConfirmation=Ge;exports.version=Ws;//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|