mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 16:33:36 +00:00
breakout payment operations, remove slider and update coco
This commit is contained in:
1 parent
3df413fa84
commit
0b8d104808
10 files changed
+1174
-1064
No files matched your search
Generated
+272
-117
File diff suppressed because it is too large.
Load diff
+6
-6
@@ -4,10 +4,10 @@
|
|||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "npm i --legacy-peer-deps --silent && vite",
|
"dev": "npm i --silent && vite",
|
||||||
"build": "npm i --legacy-peer-deps --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
|
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
|
||||||
"test": "npm i --legacy-peer-deps --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'",
|
"test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'",
|
||||||
"deploy": "npm i --legacy-peer-deps --silent && npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
|
"deploy": "npm i --silent && npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@bitcoinerlab/secp256k1": "^1.2.0",
|
"@bitcoinerlab/secp256k1": "^1.2.0",
|
||||||
@@ -54,8 +54,8 @@
|
|||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"cmdk": "^1.0.0",
|
"cmdk": "^1.0.0",
|
||||||
"coco-cashu-core": "1.0.0-rc10",
|
"coco-cashu-core": "1.0.0-rc.17",
|
||||||
"coco-cashu-indexeddb": "0.8.0",
|
"coco-cashu-indexeddb": "1.0.0-rc.17",
|
||||||
"date-fns": "^3.6.0",
|
"date-fns": "^3.6.0",
|
||||||
"ecpair": "^3.0.0",
|
"ecpair": "^3.0.0",
|
||||||
"embla-carousel-react": "^8.3.0",
|
"embla-carousel-react": "^8.3.0",
|
||||||
|
|||||||
@@ -8,7 +8,10 @@ import { useToast } from '@/hooks/useToast';
|
|||||||
import { useQRCode, type QRScanResult } from '@/hooks/useQRCode';
|
import { useQRCode, type QRScanResult } from '@/hooks/useQRCode';
|
||||||
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
|
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
|
||||||
import { useMintManager } from '@/hooks/cashu/useMintManager';
|
import { useMintManager } from '@/hooks/cashu/useMintManager';
|
||||||
import { useWalletTransactions } from '@/hooks/cashu/useWalletTransactions';
|
import { useTokenOperations } from '@/hooks/cashu/useTokenOperations';
|
||||||
|
import { useLightningOperations } from '@/hooks/cashu/useLightningOperations';
|
||||||
|
import { useReverseSwapOperations } from '@/hooks/cashu/useReverseSwapOperations';
|
||||||
|
import { useSeedPhraseRestore } from '@/hooks/cashu/useSeedPhraseRestore';
|
||||||
import { useHistoryManager } from '@/hooks/cashu/useHistoryManager';
|
import { useHistoryManager } from '@/hooks/cashu/useHistoryManager';
|
||||||
import { useBitcoinBalance, useBitcoinTransactionHistory, useBitcoinOperations } from '@/hooks/useBitcoinBalance';
|
import { useBitcoinBalance, useBitcoinTransactionHistory, useBitcoinOperations } from '@/hooks/useBitcoinBalance';
|
||||||
import { useNsecAccess } from '@/hooks/useNsecAccess';
|
import { useNsecAccess } from '@/hooks/useNsecAccess';
|
||||||
@@ -118,13 +121,42 @@ export function CashuWallet() {
|
|||||||
setActiveMintUrl(url);
|
setActiveMintUrl(url);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Transaction operation hooks
|
||||||
|
const tokenOps = useTokenOperations({
|
||||||
|
coco,
|
||||||
|
activeMintUrl,
|
||||||
|
generateQRCode,
|
||||||
|
getEncodedToken,
|
||||||
|
});
|
||||||
|
|
||||||
|
const lightningOps = useLightningOperations({
|
||||||
|
coco,
|
||||||
|
activeMintUrl,
|
||||||
|
generateQRCode,
|
||||||
|
getLightningInvoice,
|
||||||
|
});
|
||||||
|
|
||||||
|
const reverseSwapOps = useReverseSwapOperations({
|
||||||
|
coco,
|
||||||
|
activeMintUrl,
|
||||||
|
});
|
||||||
|
|
||||||
|
const restore = useSeedPhraseRestore({ coco });
|
||||||
|
|
||||||
|
// Extract all needed values
|
||||||
const {
|
const {
|
||||||
tokenInput,
|
tokenInput,
|
||||||
setTokenInput,
|
setTokenInput,
|
||||||
quoteAmount,
|
|
||||||
setQuoteAmount,
|
|
||||||
sendAmount,
|
sendAmount,
|
||||||
setSendAmount,
|
setSendAmount,
|
||||||
|
sentToken,
|
||||||
|
setSentToken,
|
||||||
|
sentTokenQRCode,
|
||||||
|
} = tokenOps;
|
||||||
|
|
||||||
|
const {
|
||||||
|
quoteAmount,
|
||||||
|
setQuoteAmount,
|
||||||
lightningInvoice,
|
lightningInvoice,
|
||||||
setLightningInvoice,
|
setLightningInvoice,
|
||||||
lightningAddressInput,
|
lightningAddressInput,
|
||||||
@@ -137,30 +169,66 @@ export function CashuWallet() {
|
|||||||
setDecodedInvoiceAmount,
|
setDecodedInvoiceAmount,
|
||||||
pendingInvoice,
|
pendingInvoice,
|
||||||
setPendingInvoice,
|
setPendingInvoice,
|
||||||
|
showInvoiceModal,
|
||||||
|
setShowInvoiceModal,
|
||||||
|
currentInvoice,
|
||||||
|
handleConfirmInvoicePayment,
|
||||||
|
mintQuoteUnsubscribeRef,
|
||||||
|
} = lightningOps;
|
||||||
|
|
||||||
|
const {
|
||||||
pendingBitcoinSwapAddress,
|
pendingBitcoinSwapAddress,
|
||||||
setPendingBitcoinSwapAddress,
|
setPendingBitcoinSwapAddress,
|
||||||
bitcoinSwapAmount,
|
bitcoinSwapAmount,
|
||||||
setBitcoinSwapAmount,
|
setBitcoinSwapAmount,
|
||||||
swapStatus,
|
swapStatus,
|
||||||
sentToken,
|
} = reverseSwapOps;
|
||||||
setSentToken,
|
|
||||||
sentTokenQRCode,
|
const {
|
||||||
showInvoiceModal,
|
|
||||||
setShowInvoiceModal,
|
|
||||||
currentInvoice,
|
|
||||||
handleReceive,
|
|
||||||
handleSend,
|
|
||||||
handleConfirmInvoicePayment,
|
|
||||||
handleRestoreFromSeedPhrase,
|
handleRestoreFromSeedPhrase,
|
||||||
isRestoring,
|
isRestoring,
|
||||||
mintQuoteUnsubscribeRef,
|
} = restore;
|
||||||
} = useWalletTransactions({
|
|
||||||
coco,
|
// Combined receive handler that routes to appropriate operation
|
||||||
activeMintUrl,
|
const handleReceive = async () => {
|
||||||
generateQRCode,
|
if (tokenInput) {
|
||||||
getEncodedToken,
|
return tokenOps.handleTokenReceive();
|
||||||
getLightningInvoice,
|
} else if (quoteAmount) {
|
||||||
});
|
return lightningOps.handleLightningReceive();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Combined send handler that routes to appropriate operation
|
||||||
|
const handleSend = async () => {
|
||||||
|
// Check for token send first
|
||||||
|
if (sendAmount && activeMintUrl) {
|
||||||
|
return tokenOps.handleTokenSend();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for reverse swap
|
||||||
|
if (pendingBitcoinSwapAddress && bitcoinSwapAmount) {
|
||||||
|
return reverseSwapOps.handleReverseSwap();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for Lightning address payment
|
||||||
|
if (pendingLightningAddress) {
|
||||||
|
return lightningOps.handleLightningAddressPayment();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle Lightning invoice/address input detection
|
||||||
|
const input = lightningInvoice.trim() || lightningAddressInput.trim();
|
||||||
|
if (!input) return;
|
||||||
|
|
||||||
|
// First check if it's a Bitcoin address for reverse swap
|
||||||
|
if (reverseSwapOps.detectBitcoinAddress(input)) {
|
||||||
|
setLightningInvoice('');
|
||||||
|
setLightningAddressInput('');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then check for Lightning address or invoice
|
||||||
|
lightningOps.detectAndHandleLightningInput(input);
|
||||||
|
};
|
||||||
|
|
||||||
const {
|
const {
|
||||||
historyEntries,
|
historyEntries,
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Slider } from '@/components/ui/slider';
|
|
||||||
import { Send, Download, ArrowRight, Zap, X } from 'lucide-react';
|
import { Send, Download, ArrowRight, Zap, X } from 'lucide-react';
|
||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
|
|
||||||
@@ -115,43 +114,9 @@ export function TransactionCard({
|
|||||||
setBitcoinSwapAmount,
|
setBitcoinSwapAmount,
|
||||||
swapStatus,
|
swapStatus,
|
||||||
}: TransactionCardProps) {
|
}: TransactionCardProps) {
|
||||||
// Slider state for confirmation
|
|
||||||
const [invoiceSliderValue, setInvoiceSliderValue] = useState([0]);
|
|
||||||
const [addressSliderValue, setAddressSliderValue] = useState([0]);
|
|
||||||
const [bitcoinSliderValue, setBitcoinSliderValue] = useState([0]);
|
|
||||||
const [swapSliderValue, setSwapSliderValue] = useState([0]);
|
|
||||||
const [sendMaxEnabled, setSendMaxEnabled] = useState(false);
|
const [sendMaxEnabled, setSendMaxEnabled] = useState(false);
|
||||||
const [swapAmountError, setSwapAmountError] = useState<string | null>(null);
|
const [swapAmountError, setSwapAmountError] = useState<string | null>(null);
|
||||||
|
|
||||||
// Handle slider value changes and auto-submit at 100%
|
|
||||||
const handleInvoiceSliderChange = (value: number[]) => {
|
|
||||||
setInvoiceSliderValue(value);
|
|
||||||
if (value[0] === 100 && onConfirmInvoice) {
|
|
||||||
onConfirmInvoice();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleAddressSliderChange = (value: number[]) => {
|
|
||||||
setAddressSliderValue(value);
|
|
||||||
if (value[0] === 100) {
|
|
||||||
onSend();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleBitcoinSliderChange = (value: number[]) => {
|
|
||||||
setBitcoinSliderValue(value);
|
|
||||||
if (value[0] === 100) {
|
|
||||||
onSend();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSwapSliderChange = (value: number[]) => {
|
|
||||||
setSwapSliderValue(value);
|
|
||||||
if (value[0] === 100) {
|
|
||||||
onSend();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleSendMaxToggle = () => {
|
const handleSendMaxToggle = () => {
|
||||||
const newState = !sendMaxEnabled;
|
const newState = !sendMaxEnabled;
|
||||||
setSendMaxEnabled(newState);
|
setSendMaxEnabled(newState);
|
||||||
@@ -160,42 +125,16 @@ export function TransactionCard({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSliderMouseUp = (sliderId: string) => {
|
// Reset send max toggle when bitcoin recipient changes
|
||||||
// Reset the slider if it hasn't reached 100
|
|
||||||
if (sliderId === 'invoice' && invoiceSliderValue[0] !== 100) {
|
|
||||||
setInvoiceSliderValue([0]);
|
|
||||||
} else if (sliderId === 'address' && addressSliderValue[0] !== 100) {
|
|
||||||
setAddressSliderValue([0]);
|
|
||||||
} else if (sliderId === 'bitcoin' && bitcoinSliderValue[0] !== 100) {
|
|
||||||
setBitcoinSliderValue([0]);
|
|
||||||
} else if (sliderId === 'swap' && swapSliderValue[0] !== 100) {
|
|
||||||
setSwapSliderValue([0]);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Reset sliders when states change
|
|
||||||
useEffect(() => {
|
|
||||||
if (!pendingInvoice) {
|
|
||||||
setInvoiceSliderValue([0]);
|
|
||||||
}
|
|
||||||
}, [pendingInvoice]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!pendingLightningAddress) {
|
|
||||||
setAddressSliderValue([0]);
|
|
||||||
}
|
|
||||||
}, [pendingLightningAddress]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!pendingBitcoinRecipient) {
|
if (!pendingBitcoinRecipient) {
|
||||||
setBitcoinSliderValue([0]);
|
|
||||||
setSendMaxEnabled(false);
|
setSendMaxEnabled(false);
|
||||||
}
|
}
|
||||||
}, [pendingBitcoinRecipient]);
|
}, [pendingBitcoinRecipient]);
|
||||||
|
|
||||||
|
// Reset swap amount error when swap address changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!pendingBitcoinSwapAddress) {
|
if (!pendingBitcoinSwapAddress) {
|
||||||
setSwapSliderValue([0]);
|
|
||||||
setSwapAmountError(null);
|
setSwapAmountError(null);
|
||||||
}
|
}
|
||||||
}, [pendingBitcoinSwapAddress]);
|
}, [pendingBitcoinSwapAddress]);
|
||||||
@@ -329,7 +268,7 @@ export function TransactionCard({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : pendingBitcoinRecipient ? (
|
) : pendingBitcoinRecipient ? (
|
||||||
// Step 2: Amount Input with Slider
|
// Step 2: Amount Input
|
||||||
<div className="space-y-8">
|
<div className="space-y-8">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<Input
|
<Input
|
||||||
@@ -357,28 +296,15 @@ export function TransactionCard({
|
|||||||
Send Max
|
Send Max
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-6 mb-safe-bottom pb-6">
|
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
|
||||||
<div className="relative w-full">
|
<Button
|
||||||
<div
|
onClick={onSend}
|
||||||
onMouseUp={() => handleSliderMouseUp('bitcoin')}
|
disabled={(!bitcoinAmount && !sendMaxEnabled) || isLoading}
|
||||||
onMouseLeave={() => handleSliderMouseUp('bitcoin')}
|
className="h-12 px-12 rounded-full"
|
||||||
onTouchEnd={() => handleSliderMouseUp('bitcoin')}
|
size="lg"
|
||||||
>
|
>
|
||||||
<Slider
|
<Send className="h-5 w-5" />
|
||||||
value={bitcoinSliderValue}
|
</Button>
|
||||||
onValueChange={handleBitcoinSliderChange}
|
|
||||||
max={100}
|
|
||||||
step={1}
|
|
||||||
className="w-full h-12"
|
|
||||||
disabled={(!bitcoinAmount && !sendMaxEnabled) || isLoading}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
|
||||||
<span className="text-sm font-medium text-muted-foreground">
|
|
||||||
{bitcoinSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
@@ -440,34 +366,21 @@ export function TransactionCard({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : pendingInvoice && decodedInvoiceAmount ? (
|
) : pendingInvoice && decodedInvoiceAmount ? (
|
||||||
// Lightning Invoice Confirmation (with slider)
|
// Lightning Invoice Confirmation
|
||||||
<div className="space-y-8">
|
<div className="space-y-8">
|
||||||
<div className="mt-6 mb-safe-bottom pb-6">
|
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
|
||||||
<div className="relative">
|
<Button
|
||||||
<div
|
onClick={onConfirmInvoice}
|
||||||
onMouseUp={() => handleSliderMouseUp('invoice')}
|
disabled={!activeMintUrl || isLoading}
|
||||||
onMouseLeave={() => handleSliderMouseUp('invoice')}
|
className="h-12 px-12 rounded-full"
|
||||||
onTouchEnd={() => handleSliderMouseUp('invoice')}
|
size="lg"
|
||||||
>
|
>
|
||||||
<Slider
|
<Zap className="h-5 w-5" />
|
||||||
value={invoiceSliderValue}
|
</Button>
|
||||||
onValueChange={handleInvoiceSliderChange}
|
|
||||||
max={100}
|
|
||||||
step={1}
|
|
||||||
className="w-full h-12"
|
|
||||||
disabled={!activeMintUrl || isLoading}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
|
||||||
<span className="text-sm font-medium text-muted-foreground">
|
|
||||||
{invoiceSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : pendingBitcoinSwapAddress ? (
|
) : pendingBitcoinSwapAddress ? (
|
||||||
// Reverse Swap Amount Input with Slider
|
// Reverse Swap Amount Input
|
||||||
<div className="space-y-8">
|
<div className="space-y-8">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Input
|
<Input
|
||||||
@@ -499,32 +412,19 @@ export function TransactionCard({
|
|||||||
<p className="text-sm text-muted-foreground text-center">{swapStatus}</p>
|
<p className="text-sm text-muted-foreground text-center">{swapStatus}</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-6 mb-safe-bottom pb-6">
|
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
|
||||||
<div className="relative w-full">
|
<Button
|
||||||
<div
|
onClick={onSend}
|
||||||
onMouseUp={() => handleSliderMouseUp('swap')}
|
disabled={!bitcoinSwapAmount || !!swapAmountError || !activeMintUrl || isLoading}
|
||||||
onMouseLeave={() => handleSliderMouseUp('swap')}
|
className="h-12 px-12 rounded-full"
|
||||||
onTouchEnd={() => handleSliderMouseUp('swap')}
|
size="lg"
|
||||||
>
|
>
|
||||||
<Slider
|
<Send className="h-5 w-5" />
|
||||||
value={swapSliderValue}
|
</Button>
|
||||||
onValueChange={handleSwapSliderChange}
|
|
||||||
max={100}
|
|
||||||
step={1}
|
|
||||||
className="w-full h-12"
|
|
||||||
disabled={!bitcoinSwapAmount || !!swapAmountError || !activeMintUrl || isLoading}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
|
||||||
<span className="text-sm font-medium text-muted-foreground">
|
|
||||||
{swapSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : pendingLightningAddress ? (
|
) : pendingLightningAddress ? (
|
||||||
// Lightning Address Amount Input with Slider
|
// Lightning Address Amount Input
|
||||||
<div className="space-y-8">
|
<div className="space-y-8">
|
||||||
<Input
|
<Input
|
||||||
placeholder="Amount (sats)"
|
placeholder="Amount (sats)"
|
||||||
@@ -539,28 +439,15 @@ export function TransactionCard({
|
|||||||
disabled={!activeMintUrl}
|
disabled={!activeMintUrl}
|
||||||
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
|
className="w-full h-16 !text-base text-center border bg-background focus:ring-2 focus:ring-ring focus:ring-offset-2 [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none [-moz-appearance:textfield]"
|
||||||
/>
|
/>
|
||||||
<div className="mt-6 mb-safe-bottom pb-6">
|
<div className="flex justify-center mt-6 mb-safe-bottom pb-6">
|
||||||
<div className="relative w-full">
|
<Button
|
||||||
<div
|
onClick={onSend}
|
||||||
onMouseUp={() => handleSliderMouseUp('address')}
|
disabled={!lightningAddressAmount || !activeMintUrl || isResolvingAddress || isLoading}
|
||||||
onMouseLeave={() => handleSliderMouseUp('address')}
|
className="h-12 px-12 rounded-full"
|
||||||
onTouchEnd={() => handleSliderMouseUp('address')}
|
size="lg"
|
||||||
>
|
>
|
||||||
<Slider
|
<Zap className="h-5 w-5" />
|
||||||
value={addressSliderValue}
|
</Button>
|
||||||
onValueChange={handleAddressSliderChange}
|
|
||||||
max={100}
|
|
||||||
step={1}
|
|
||||||
className="w-full h-12"
|
|
||||||
disabled={!lightningAddressAmount || !activeMintUrl || isResolvingAddress || isLoading}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
|
||||||
<span className="text-sm font-medium text-muted-foreground">
|
|
||||||
{addressSliderValue[0] === 100 ? 'Confirmed!' : 'Slide to Confirm'}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { Zap, Coins, Copy, Check, QrCode, Link, Key } from 'lucide-react';
|
import { Zap, Coins, Copy, Check, QrCode, Link, Key } from 'lucide-react';
|
||||||
import { exchangeRateService } from '@/lib/exchangeRateService';
|
import { exchangeRateService } from '@/lib/exchangeRateService';
|
||||||
import { useToast } from '@/hooks/useToast';
|
|
||||||
import { LoginIcon } from '@/components/auth/LoginIcon';
|
import { LoginIcon } from '@/components/auth/LoginIcon';
|
||||||
import { MintSelector } from './MintSelector';
|
import { MintSelector } from './MintSelector';
|
||||||
import { UTXOSelector } from './UTXOSelector';
|
import { UTXOSelector } from './UTXOSelector';
|
||||||
@@ -76,24 +75,6 @@ const getToggleTitle = (showSats: boolean): string => {
|
|||||||
return `Click to show in ${showSats ? 'USD' : 'sats'}`;
|
return `Click to show in ${showSats ? 'USD' : 'sats'}`;
|
||||||
};
|
};
|
||||||
|
|
||||||
const getModeTitle = (mode: string): string => {
|
|
||||||
switch (mode) {
|
|
||||||
case 'tokens': return 'Cashu';
|
|
||||||
case 'lightning': return 'Lightning';
|
|
||||||
case 'bitcoin': return 'Bitcoin';
|
|
||||||
default: return 'Unknown';
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getModeDescription = (mode: string): string => {
|
|
||||||
switch (mode) {
|
|
||||||
case 'tokens': return 'Send and receive with Cashu eCash';
|
|
||||||
case 'lightning': return 'Send and receive with Lightning';
|
|
||||||
case 'bitcoin': return 'Send and receive with on-chain Bitcoin';
|
|
||||||
default: return '';
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getButtonTitle = (mode: string): string => {
|
const getButtonTitle = (mode: string): string => {
|
||||||
switch (mode) {
|
switch (mode) {
|
||||||
case 'tokens': return 'Switch to On-Chain';
|
case 'tokens': return 'Switch to On-Chain';
|
||||||
@@ -141,7 +122,6 @@ export function WalletHeader({
|
|||||||
const [bitcoinAddressCopied, setBitcoinAddressCopied] = useState(false);
|
const [bitcoinAddressCopied, setBitcoinAddressCopied] = useState(false);
|
||||||
const [mnemonicCopied, setMnemonicCopied] = useState(false);
|
const [mnemonicCopied, setMnemonicCopied] = useState(false);
|
||||||
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
|
const [btcUsdRate, setBtcUsdRate] = useState<number | null>(null);
|
||||||
const { toast } = useToast();
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
exchangeRateService.getBtcUsdRate()
|
exchangeRateService.getBtcUsdRate()
|
||||||
@@ -160,11 +140,6 @@ export function WalletHeader({
|
|||||||
}
|
}
|
||||||
|
|
||||||
setMode(newMode);
|
setMode(newMode);
|
||||||
|
|
||||||
toast({
|
|
||||||
title: `${getModeTitle(newMode)} Enabled!`,
|
|
||||||
description: getModeDescription(newMode)
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,305 @@
|
|||||||
|
import { useState, useCallback, useEffect, useRef } from 'react';
|
||||||
|
import { decodeBolt11Amount, isValidBolt11Invoice } from '@/lib/bolt11Decoder';
|
||||||
|
import type { Manager } from 'coco-cashu-core';
|
||||||
|
import { useToast } from '@/hooks/useToast';
|
||||||
|
|
||||||
|
interface UseLightningOperationsProps {
|
||||||
|
coco: Manager | null;
|
||||||
|
activeMintUrl: string | null;
|
||||||
|
generateQRCode: (text: string) => Promise<string>;
|
||||||
|
getLightningInvoice: (params: {
|
||||||
|
lightningAddress: string;
|
||||||
|
amountSats: number;
|
||||||
|
}) => Promise<string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useLightningOperations({
|
||||||
|
coco,
|
||||||
|
activeMintUrl,
|
||||||
|
generateQRCode,
|
||||||
|
getLightningInvoice,
|
||||||
|
}: UseLightningOperationsProps) {
|
||||||
|
const { toast } = useToast();
|
||||||
|
|
||||||
|
// Receive state
|
||||||
|
const [quoteAmount, setQuoteAmount] = useState('');
|
||||||
|
|
||||||
|
// Send state
|
||||||
|
const [lightningInvoice, setLightningInvoice] = useState('');
|
||||||
|
const [lightningAddressInput, setLightningAddressInput] = useState('');
|
||||||
|
const [lightningAddressAmount, setLightningAddressAmount] = useState('');
|
||||||
|
const [pendingLightningAddress, setPendingLightningAddress] = useState<string | null>(null);
|
||||||
|
const [decodedInvoiceAmount, setDecodedInvoiceAmount] = useState<number | null>(null);
|
||||||
|
const [pendingInvoice, setPendingInvoice] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Processing state to prevent concurrent executions
|
||||||
|
const [isProcessingPayment, setIsProcessingPayment] = useState(false);
|
||||||
|
|
||||||
|
// Invoice modal state
|
||||||
|
const [showInvoiceModal, setShowInvoiceModal] = useState(false);
|
||||||
|
const [currentInvoice, setCurrentInvoice] = useState<{
|
||||||
|
quoteId: string;
|
||||||
|
mintUrl: string;
|
||||||
|
amount: number;
|
||||||
|
invoice: string;
|
||||||
|
qrCodeUrl: string;
|
||||||
|
expiry: number;
|
||||||
|
} | null>(null);
|
||||||
|
|
||||||
|
// Ref to store the mint quote redeemed event unsubscribe function
|
||||||
|
const mintQuoteUnsubscribeRef = useRef<(() => void) | null>(null);
|
||||||
|
|
||||||
|
// Handle receive (Lightning quote/invoice creation)
|
||||||
|
const handleLightningReceive = useCallback(async () => {
|
||||||
|
if (!coco || !quoteAmount || !activeMintUrl) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const amount = parseInt(quoteAmount);
|
||||||
|
if (isNaN(amount) || amount <= 0) {
|
||||||
|
toast({
|
||||||
|
variant: 'destructive',
|
||||||
|
title: 'Invalid Amount',
|
||||||
|
description: 'Please enter a valid amount',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const quote = await coco.quotes.createMintQuote(activeMintUrl, amount);
|
||||||
|
|
||||||
|
// Generate QR code for the Lightning invoice
|
||||||
|
const qrCodeUrl = await generateQRCode(quote.request);
|
||||||
|
|
||||||
|
// Set the invoice data and show modal
|
||||||
|
setCurrentInvoice({
|
||||||
|
quoteId: quote.quote,
|
||||||
|
mintUrl: activeMintUrl,
|
||||||
|
amount,
|
||||||
|
invoice: quote.request,
|
||||||
|
qrCodeUrl,
|
||||||
|
expiry: quote.expiry,
|
||||||
|
});
|
||||||
|
|
||||||
|
setShowInvoiceModal(true);
|
||||||
|
setQuoteAmount('');
|
||||||
|
|
||||||
|
// Clean up any previous listener
|
||||||
|
if (mintQuoteUnsubscribeRef.current) {
|
||||||
|
mintQuoteUnsubscribeRef.current();
|
||||||
|
mintQuoteUnsubscribeRef.current = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Listen for payment notification via mint-quote:redeemed event
|
||||||
|
const quoteId = quote.quote;
|
||||||
|
const invoiceAmount = amount;
|
||||||
|
|
||||||
|
const unsubscribe = coco.on('mint-quote:redeemed', (payload: unknown) => {
|
||||||
|
const redeemedQuote = payload as { quoteId?: string };
|
||||||
|
|
||||||
|
// Check if this is the quote we're waiting for
|
||||||
|
if (redeemedQuote.quoteId === quoteId) {
|
||||||
|
toast({
|
||||||
|
title: 'Payment Received',
|
||||||
|
description: `Successfully received ${invoiceAmount} sats! Tokens have been added to your wallet.`,
|
||||||
|
});
|
||||||
|
setShowInvoiceModal(false);
|
||||||
|
setCurrentInvoice(null);
|
||||||
|
|
||||||
|
// Clean up the event listener
|
||||||
|
mintQuoteUnsubscribeRef.current = null;
|
||||||
|
unsubscribe();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Store unsubscribe function for cleanup
|
||||||
|
mintQuoteUnsubscribeRef.current = unsubscribe;
|
||||||
|
} catch (err) {
|
||||||
|
toast({
|
||||||
|
variant: 'destructive',
|
||||||
|
title: 'Quote Creation Failed',
|
||||||
|
description: err instanceof Error ? err.message : 'Unknown error',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [coco, quoteAmount, activeMintUrl, toast, generateQRCode]);
|
||||||
|
|
||||||
|
// Detect input type and handle Lightning address/invoice parsing
|
||||||
|
const detectAndHandleLightningInput = useCallback((input: string): 'lightning_address' | 'invoice' | null => {
|
||||||
|
const trimmed = input.trim();
|
||||||
|
if (!trimmed) return null;
|
||||||
|
|
||||||
|
// Check if it's a Lightning address (contains @)
|
||||||
|
if (trimmed.includes('@')) {
|
||||||
|
setPendingLightningAddress(trimmed);
|
||||||
|
setLightningAddressInput('');
|
||||||
|
return 'lightning_address';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if it's a Lightning invoice
|
||||||
|
if (isValidBolt11Invoice(trimmed)) {
|
||||||
|
const amount = decodeBolt11Amount(trimmed);
|
||||||
|
if (amount) {
|
||||||
|
// Show amount confirmation screen
|
||||||
|
setPendingInvoice(trimmed);
|
||||||
|
setDecodedInvoiceAmount(amount);
|
||||||
|
setLightningInvoice('');
|
||||||
|
return 'invoice';
|
||||||
|
} else {
|
||||||
|
// Failed to decode amount - show error
|
||||||
|
toast({
|
||||||
|
variant: 'destructive',
|
||||||
|
title: 'Invalid Invoice',
|
||||||
|
description: 'Unable to decode the lightning invoice amount. Please check the invoice format.',
|
||||||
|
});
|
||||||
|
setLightningInvoice('');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Not a valid BOLT11 invoice - show error
|
||||||
|
toast({
|
||||||
|
variant: 'destructive',
|
||||||
|
title: 'Invalid Invoice',
|
||||||
|
description: 'This does not appear to be a valid lightning invoice. Please check the format.',
|
||||||
|
});
|
||||||
|
setLightningInvoice('');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}, [toast]);
|
||||||
|
|
||||||
|
// Handle Lightning address payment
|
||||||
|
const handleLightningAddressPayment = useCallback(async () => {
|
||||||
|
// Prevent concurrent executions
|
||||||
|
if (isProcessingPayment) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!coco || !pendingLightningAddress || !lightningAddressAmount || !activeMintUrl) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsProcessingPayment(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const amount = parseInt(lightningAddressAmount);
|
||||||
|
if (isNaN(amount) || amount <= 0) {
|
||||||
|
toast({
|
||||||
|
variant: 'destructive',
|
||||||
|
title: 'Invalid Amount',
|
||||||
|
description: 'Please enter a valid amount',
|
||||||
|
});
|
||||||
|
setIsProcessingPayment(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const invoice = await getLightningInvoice({
|
||||||
|
lightningAddress: pendingLightningAddress,
|
||||||
|
amountSats: amount,
|
||||||
|
});
|
||||||
|
|
||||||
|
const meltQuote = await coco.quotes.createMeltQuote(
|
||||||
|
activeMintUrl,
|
||||||
|
invoice
|
||||||
|
);
|
||||||
|
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: 'Payment Sent',
|
||||||
|
description: `Successfully sent ${amount} sats to ${pendingLightningAddress}!`,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Reset state
|
||||||
|
setPendingLightningAddress(null);
|
||||||
|
setLightningAddressInput('');
|
||||||
|
setLightningAddressAmount('');
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Payment error:', err);
|
||||||
|
toast({
|
||||||
|
variant: 'destructive',
|
||||||
|
title: 'Payment Failed',
|
||||||
|
description: err instanceof Error ? err.message : 'Unknown error',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsProcessingPayment(false);
|
||||||
|
}
|
||||||
|
}, [coco, pendingLightningAddress, lightningAddressAmount, activeMintUrl, getLightningInvoice, toast, isProcessingPayment]);
|
||||||
|
|
||||||
|
// Handle confirmed invoice payment
|
||||||
|
const handleConfirmInvoicePayment = useCallback(async () => {
|
||||||
|
// Prevent concurrent executions
|
||||||
|
if (isProcessingPayment) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!coco || !pendingInvoice || !activeMintUrl) return;
|
||||||
|
|
||||||
|
setIsProcessingPayment(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const meltQuote = await coco.quotes.createMeltQuote(
|
||||||
|
activeMintUrl,
|
||||||
|
pendingInvoice
|
||||||
|
);
|
||||||
|
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: 'Invoice Paid',
|
||||||
|
description: `Lightning invoice paid successfully for ${decodedInvoiceAmount} sats!`,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Reset state
|
||||||
|
setPendingInvoice(null);
|
||||||
|
setDecodedInvoiceAmount(null);
|
||||||
|
} catch (err) {
|
||||||
|
toast({
|
||||||
|
variant: 'destructive',
|
||||||
|
title: 'Invoice Payment Failed',
|
||||||
|
description: err instanceof Error ? err.message : 'Unknown error',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
setIsProcessingPayment(false);
|
||||||
|
}
|
||||||
|
}, [coco, pendingInvoice, activeMintUrl, decodedInvoiceAmount, toast, isProcessingPayment]);
|
||||||
|
|
||||||
|
// Cleanup mint quote listener on component unmount
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
if (mintQuoteUnsubscribeRef.current) {
|
||||||
|
mintQuoteUnsubscribeRef.current();
|
||||||
|
mintQuoteUnsubscribeRef.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return {
|
||||||
|
// Receive state
|
||||||
|
quoteAmount,
|
||||||
|
setQuoteAmount,
|
||||||
|
// Send state
|
||||||
|
lightningInvoice,
|
||||||
|
setLightningInvoice,
|
||||||
|
lightningAddressInput,
|
||||||
|
setLightningAddressInput,
|
||||||
|
lightningAddressAmount,
|
||||||
|
setLightningAddressAmount,
|
||||||
|
pendingLightningAddress,
|
||||||
|
setPendingLightningAddress,
|
||||||
|
decodedInvoiceAmount,
|
||||||
|
setDecodedInvoiceAmount,
|
||||||
|
pendingInvoice,
|
||||||
|
setPendingInvoice,
|
||||||
|
// Invoice modal state
|
||||||
|
showInvoiceModal,
|
||||||
|
setShowInvoiceModal,
|
||||||
|
currentInvoice,
|
||||||
|
setCurrentInvoice,
|
||||||
|
// Processing state
|
||||||
|
isProcessingPayment,
|
||||||
|
// Handlers
|
||||||
|
handleLightningReceive,
|
||||||
|
detectAndHandleLightningInput,
|
||||||
|
handleLightningAddressPayment,
|
||||||
|
handleConfirmInvoicePayment,
|
||||||
|
// Refs
|
||||||
|
mintQuoteUnsubscribeRef,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
import { useState, useCallback, useEffect } from 'react';
|
||||||
|
import { nip19 } from 'nostr-tools';
|
||||||
|
import { createReverseSwap, type SwapStatusUpdate } from '@/hooks/useReverseSwap';
|
||||||
|
import { isValidBitcoinAddress, npubToBitcoinAddress } from '@/lib/bitcoin';
|
||||||
|
import type { Manager } from 'coco-cashu-core';
|
||||||
|
import { useToast } from '@/hooks/useToast';
|
||||||
|
|
||||||
|
interface UseReverseSwapOperationsProps {
|
||||||
|
coco: Manager | null;
|
||||||
|
activeMintUrl: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useReverseSwapOperations({ coco, activeMintUrl }: UseReverseSwapOperationsProps) {
|
||||||
|
const { toast } = useToast();
|
||||||
|
|
||||||
|
// Reverse swap state (Lightning -> Bitcoin)
|
||||||
|
const [pendingBitcoinSwapAddress, setPendingBitcoinSwapAddress] = useState<string | null>(null);
|
||||||
|
const [bitcoinSwapAmount, setBitcoinSwapAmount] = useState('');
|
||||||
|
const [swapStatus, setSwapStatus] = useState<string | null>(null);
|
||||||
|
const [reverseSwapClose, setReverseSwapClose] = useState<(() => void) | null>(null);
|
||||||
|
|
||||||
|
// Detect if input is a Bitcoin address or npub for reverse swap
|
||||||
|
const detectBitcoinAddress = useCallback((input: string): boolean => {
|
||||||
|
// Check if it's a Bitcoin address
|
||||||
|
if (isValidBitcoinAddress(input)) {
|
||||||
|
setPendingBitcoinSwapAddress(input);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if it's an npub (can be converted to Bitcoin address)
|
||||||
|
try {
|
||||||
|
const decoded = nip19.decode(input);
|
||||||
|
if (decoded.type === 'npub') {
|
||||||
|
const bitcoinAddr = npubToBitcoinAddress(input);
|
||||||
|
if (bitcoinAddr) {
|
||||||
|
setPendingBitcoinSwapAddress(input); // Store npub, will convert later
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Not an npub, continue
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Handle reverse swap execution
|
||||||
|
const handleReverseSwap = useCallback(async () => {
|
||||||
|
if (!coco || !pendingBitcoinSwapAddress || !bitcoinSwapAmount || !activeMintUrl) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const amount = parseInt(bitcoinSwapAmount);
|
||||||
|
if (isNaN(amount) || amount <= 0) {
|
||||||
|
toast({
|
||||||
|
variant: 'destructive',
|
||||||
|
title: 'Invalid Amount',
|
||||||
|
description: 'Please enter a valid amount',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate reverse swap amount limits (25,000 - 25,000,000 sats)
|
||||||
|
if (amount < 25_000 || amount > 25_000_000) {
|
||||||
|
toast({
|
||||||
|
variant: 'destructive',
|
||||||
|
title: 'Invalid Amount',
|
||||||
|
description: 'Reverse swap amount must be between 25,000 and 25,000,000 sats',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine destination address (could be Bitcoin address or npub)
|
||||||
|
let destinationAddress = pendingBitcoinSwapAddress;
|
||||||
|
try {
|
||||||
|
// Try to decode as npub first
|
||||||
|
const decoded = nip19.decode(pendingBitcoinSwapAddress);
|
||||||
|
if (decoded.type === 'npub') {
|
||||||
|
destinationAddress = npubToBitcoinAddress(pendingBitcoinSwapAddress);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Not an npub, assume it's already a Bitcoin address
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initiate reverse swap
|
||||||
|
setSwapStatus('Creating reverse swap...');
|
||||||
|
const swapResult = await createReverseSwap({
|
||||||
|
invoiceAmount: amount,
|
||||||
|
destinationAddress,
|
||||||
|
onStatusUpdate: (update: SwapStatusUpdate) => {
|
||||||
|
switch (update.status) {
|
||||||
|
case 'swap.created':
|
||||||
|
setSwapStatus('Waiting for invoice payment...');
|
||||||
|
break;
|
||||||
|
case 'transaction.mempool':
|
||||||
|
setSwapStatus('Swap transaction sent to blockchain...');
|
||||||
|
break;
|
||||||
|
case 'invoice.settled':
|
||||||
|
case 'transaction.confirmed':
|
||||||
|
setSwapStatus('Swap completed!');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
const displayAddress = destinationAddress.length > 26
|
||||||
|
? destinationAddress.slice(0, 12) + '...' + destinationAddress.slice(-12)
|
||||||
|
: destinationAddress;
|
||||||
|
toast({
|
||||||
|
title: 'Reverse Swap Completed',
|
||||||
|
description: `Successfully swapped ${amount} sats to Bitcoin address ${displayAddress}!`,
|
||||||
|
});
|
||||||
|
setSwapStatus(null);
|
||||||
|
setPendingBitcoinSwapAddress(null);
|
||||||
|
setBitcoinSwapAmount('');
|
||||||
|
if (reverseSwapClose) {
|
||||||
|
reverseSwapClose();
|
||||||
|
setReverseSwapClose(null);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onError: (error: Error) => {
|
||||||
|
toast({
|
||||||
|
variant: 'destructive',
|
||||||
|
title: 'Reverse Swap Failed',
|
||||||
|
description: error.message,
|
||||||
|
});
|
||||||
|
setSwapStatus(null);
|
||||||
|
setPendingBitcoinSwapAddress(null);
|
||||||
|
setBitcoinSwapAmount('');
|
||||||
|
if (reverseSwapClose) {
|
||||||
|
reverseSwapClose();
|
||||||
|
setReverseSwapClose(null);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Store close function for cleanup
|
||||||
|
setReverseSwapClose(() => swapResult.close);
|
||||||
|
|
||||||
|
// Pay the Lightning invoice from the swap using the active mint
|
||||||
|
setSwapStatus('Paying Lightning invoice...');
|
||||||
|
const meltQuote = await coco.quotes.createMeltQuote(
|
||||||
|
activeMintUrl,
|
||||||
|
swapResult.invoice
|
||||||
|
);
|
||||||
|
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: 'Invoice Paid',
|
||||||
|
description: `Lightning invoice paid. Swap in progress...`,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Reverse swap error:', err);
|
||||||
|
toast({
|
||||||
|
variant: 'destructive',
|
||||||
|
title: 'Reverse Swap Failed',
|
||||||
|
description: err instanceof Error ? err.message : 'Unknown error',
|
||||||
|
});
|
||||||
|
setSwapStatus(null);
|
||||||
|
setPendingBitcoinSwapAddress(null);
|
||||||
|
setBitcoinSwapAmount('');
|
||||||
|
if (reverseSwapClose) {
|
||||||
|
reverseSwapClose();
|
||||||
|
setReverseSwapClose(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [coco, pendingBitcoinSwapAddress, bitcoinSwapAmount, activeMintUrl, toast, reverseSwapClose]);
|
||||||
|
|
||||||
|
// Cleanup reverse swap WebSocket on unmount
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
if (reverseSwapClose) {
|
||||||
|
reverseSwapClose();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [reverseSwapClose]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
// State
|
||||||
|
pendingBitcoinSwapAddress,
|
||||||
|
setPendingBitcoinSwapAddress,
|
||||||
|
bitcoinSwapAmount,
|
||||||
|
setBitcoinSwapAmount,
|
||||||
|
swapStatus,
|
||||||
|
// Functions
|
||||||
|
detectBitcoinAddress,
|
||||||
|
handleReverseSwap,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import { useState, useCallback } from 'react';
|
||||||
|
import * as bip39 from '@scure/bip39';
|
||||||
|
import { wordlist } from '@scure/bip39/wordlists/english.js';
|
||||||
|
import { initializeCoco, ConsoleLogger } from 'coco-cashu-core';
|
||||||
|
import { IndexedDbRepositories } from 'coco-cashu-indexeddb';
|
||||||
|
import type { Manager } from 'coco-cashu-core';
|
||||||
|
import { useToast } from '@/hooks/useToast';
|
||||||
|
|
||||||
|
interface UseSeedPhraseRestoreProps {
|
||||||
|
coco: Manager | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useSeedPhraseRestore({ coco }: UseSeedPhraseRestoreProps) {
|
||||||
|
const { toast } = useToast();
|
||||||
|
const [isRestoring, setIsRestoring] = useState(false);
|
||||||
|
|
||||||
|
const handleRestoreFromSeedPhrase = useCallback(async (seedPhrase: string, mintUrl: string) => {
|
||||||
|
if (!coco) {
|
||||||
|
throw new Error('Wallet not initialized');
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsRestoring(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Clean and validate the seed phrase
|
||||||
|
const cleanedSeedPhrase = seedPhrase.trim().toLowerCase();
|
||||||
|
|
||||||
|
// Check if it's a valid mnemonic format
|
||||||
|
if (!bip39.validateMnemonic(cleanedSeedPhrase, wordlist)) {
|
||||||
|
// Try to provide more specific error information
|
||||||
|
const words = cleanedSeedPhrase.split(/\s+/);
|
||||||
|
if (words.length !== 12) {
|
||||||
|
throw new Error(`Seed phrase must have exactly 12 words, but found ${words.length} words`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if all words are valid
|
||||||
|
const invalidWords = words.filter(word => !wordlist.includes(word));
|
||||||
|
if (invalidWords.length > 0) {
|
||||||
|
throw new Error(`Invalid words found: ${invalidWords.join(', ')}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('Invalid seed phrase format. Please check that all words are spelled correctly.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify this is a different seed from the current wallet
|
||||||
|
const currentMnemonic = localStorage.getItem('cashu-mnemonic');
|
||||||
|
if (currentMnemonic && currentMnemonic.toLowerCase() === cleanedSeedPhrase) {
|
||||||
|
throw new Error('This is the same seed phrase as your current wallet. Please enter a different seed phrase to restore from.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert seed phrase to seed
|
||||||
|
const restoredSeed = bip39.mnemonicToSeedSync(cleanedSeedPhrase);
|
||||||
|
|
||||||
|
// Get current balance before restore
|
||||||
|
const balancesBefore = await coco.wallet.getBalances();
|
||||||
|
const balanceBefore = balancesBefore[mintUrl] || 0;
|
||||||
|
|
||||||
|
// Create a temporary coco instance with the restored seed to fetch proofs
|
||||||
|
const tempRepo = new IndexedDbRepositories({ name: `cashu-wallet-restore-${Date.now()}` });
|
||||||
|
await tempRepo.init();
|
||||||
|
|
||||||
|
const tempCoco = await initializeCoco({
|
||||||
|
repo: tempRepo,
|
||||||
|
seedGetter: async () => restoredSeed,
|
||||||
|
logger: new ConsoleLogger(`restore-${Date.now()}`, { level: "debug" })
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Restore the proofs in the temporary wallet
|
||||||
|
await tempCoco.wallet.restore(mintUrl);
|
||||||
|
|
||||||
|
// Get the restored balance from the temporary wallet
|
||||||
|
const tempBalances = await tempCoco.wallet.getBalances();
|
||||||
|
const restoredAmount = tempBalances[mintUrl] || 0;
|
||||||
|
|
||||||
|
if (restoredAmount <= 0) {
|
||||||
|
toast({
|
||||||
|
title: "No Tokens Found",
|
||||||
|
description: "No tokens were found for this seed phrase on the selected mint.",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send the restored tokens from the temporary wallet
|
||||||
|
const token = await tempCoco.wallet.send(mintUrl, restoredAmount);
|
||||||
|
|
||||||
|
// Receive the token in the main wallet
|
||||||
|
await coco.wallet.receive(token);
|
||||||
|
|
||||||
|
// Verify the transfer
|
||||||
|
const balancesAfter = await coco.wallet.getBalances();
|
||||||
|
const balanceAfter = balancesAfter[mintUrl] || 0;
|
||||||
|
const actualRestored = balanceAfter - balanceBefore;
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: "Restore Successful",
|
||||||
|
description: `Restored ${actualRestored} sats from the seed phrase and added to your current wallet.`,
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
// Clean up temporary database (optional - happens automatically on next session)
|
||||||
|
// The temporary IndexedDB will be isolated to the unique name we provided
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Restore failed:', error);
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
setIsRestoring(false);
|
||||||
|
}
|
||||||
|
}, [coco, toast]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
handleRestoreFromSeedPhrase,
|
||||||
|
isRestoring,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
import { useState, useCallback } from 'react';
|
||||||
|
import { isUnknownMintError, extractMintUrlFromError } from './walletUtils';
|
||||||
|
import type { Manager } from 'coco-cashu-core';
|
||||||
|
import type { Token } from '@cashu/cashu-ts';
|
||||||
|
import { useToast } from '@/hooks/useToast';
|
||||||
|
|
||||||
|
interface UseTokenOperationsProps {
|
||||||
|
coco: Manager | null;
|
||||||
|
activeMintUrl: string | null;
|
||||||
|
generateQRCode: (text: string) => Promise<string>;
|
||||||
|
getEncodedToken: (token: Token | string) => string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useTokenOperations({
|
||||||
|
coco,
|
||||||
|
activeMintUrl,
|
||||||
|
generateQRCode,
|
||||||
|
getEncodedToken,
|
||||||
|
}: UseTokenOperationsProps) {
|
||||||
|
const { toast } = useToast();
|
||||||
|
|
||||||
|
// Receive state
|
||||||
|
const [tokenInput, setTokenInput] = useState('');
|
||||||
|
|
||||||
|
// Send state
|
||||||
|
const [sendAmount, setSendAmount] = useState('');
|
||||||
|
|
||||||
|
// Transaction output state
|
||||||
|
const [sentToken, setSentToken] = useState<string | null>(null);
|
||||||
|
const [sentTokenQRCode, setSentTokenQRCode] = useState<string>('');
|
||||||
|
|
||||||
|
// Generate QR code for sent token
|
||||||
|
const generateSentTokenQRCode = useCallback(async (token: string) => {
|
||||||
|
try {
|
||||||
|
const qrCodeUrl = await generateQRCode(token);
|
||||||
|
setSentTokenQRCode(qrCodeUrl);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to generate sent token QR code:', err);
|
||||||
|
}
|
||||||
|
}, [generateQRCode]);
|
||||||
|
|
||||||
|
// Handle unknown mint error by adding the mint and retrying
|
||||||
|
const handleUnknownMintError = useCallback(
|
||||||
|
async (mintUrl: string) => {
|
||||||
|
if (!coco) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
console.log('Adding unknown mint:', mintUrl);
|
||||||
|
|
||||||
|
// Add the mint
|
||||||
|
await coco.mint.addMint(mintUrl);
|
||||||
|
|
||||||
|
// Retry receiving the token
|
||||||
|
await coco.wallet.receive(tokenInput);
|
||||||
|
setTokenInput('');
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: 'Token Received',
|
||||||
|
description: `Cashu token redeemed successfully! Added new mint: ${mintUrl}`,
|
||||||
|
});
|
||||||
|
} catch (retryErr) {
|
||||||
|
console.error('Failed to add mint and retry receive:', retryErr);
|
||||||
|
toast({
|
||||||
|
variant: 'destructive',
|
||||||
|
title: 'Receive Failed',
|
||||||
|
description: `Failed to add mint and receive token: ${retryErr instanceof Error ? retryErr.message : 'Unknown error'}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[coco, tokenInput, toast]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Handle receive (token)
|
||||||
|
const handleTokenReceive = useCallback(async () => {
|
||||||
|
if (!coco || !tokenInput) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
console.log(
|
||||||
|
'Attempting to receive token:',
|
||||||
|
tokenInput.substring(0, 20) + '...'
|
||||||
|
);
|
||||||
|
await coco.wallet.receive(tokenInput);
|
||||||
|
setTokenInput('');
|
||||||
|
toast({
|
||||||
|
title: 'Token Received',
|
||||||
|
description: 'Cashu token redeemed successfully!',
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Token receive error:', err);
|
||||||
|
|
||||||
|
// Handle UnknownMintError by automatically adding the mint
|
||||||
|
if (isUnknownMintError(err)) {
|
||||||
|
const mintUrl = extractMintUrlFromError(err);
|
||||||
|
if (mintUrl) {
|
||||||
|
await handleUnknownMintError(mintUrl);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
toast({
|
||||||
|
variant: 'destructive',
|
||||||
|
title: 'Receive Failed',
|
||||||
|
description: err instanceof Error ? err.message : 'Unknown error',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [coco, tokenInput, toast, handleUnknownMintError]);
|
||||||
|
|
||||||
|
// Handle send (token)
|
||||||
|
const handleTokenSend = useCallback(async () => {
|
||||||
|
if (!coco || !sendAmount || !activeMintUrl) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const amount = parseInt(sendAmount);
|
||||||
|
if (isNaN(amount) || amount <= 0) {
|
||||||
|
toast({
|
||||||
|
variant: 'destructive',
|
||||||
|
title: 'Invalid Amount',
|
||||||
|
description: 'Please enter a valid amount',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = await coco.wallet.send(activeMintUrl, amount);
|
||||||
|
const encodedToken = getEncodedToken(token);
|
||||||
|
setSentToken(encodedToken);
|
||||||
|
await generateSentTokenQRCode(encodedToken);
|
||||||
|
setSendAmount('');
|
||||||
|
} catch (err) {
|
||||||
|
toast({
|
||||||
|
variant: 'destructive',
|
||||||
|
title: 'Send Failed',
|
||||||
|
description: err instanceof Error ? err.message : 'Unknown error',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [coco, sendAmount, activeMintUrl, getEncodedToken, generateSentTokenQRCode, toast]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
// Receive state
|
||||||
|
tokenInput,
|
||||||
|
setTokenInput,
|
||||||
|
// Send state
|
||||||
|
sendAmount,
|
||||||
|
setSendAmount,
|
||||||
|
// Transaction output state
|
||||||
|
sentToken,
|
||||||
|
setSentToken,
|
||||||
|
sentTokenQRCode,
|
||||||
|
// Handlers
|
||||||
|
handleTokenReceive,
|
||||||
|
handleTokenSend,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,741 +0,0 @@
|
|||||||
import { useState, useCallback, useRef, useEffect } from 'react';
|
|
||||||
import { isUnknownMintError, extractMintUrlFromError } from './walletUtils';
|
|
||||||
import { decodeBolt11Amount, isValidBolt11Invoice } from '@/lib/bolt11Decoder';
|
|
||||||
import { isValidBitcoinAddress, npubToBitcoinAddress } from '@/lib/bitcoin';
|
|
||||||
import { createReverseSwap, type SwapStatusUpdate } from '@/hooks/useReverseSwap';
|
|
||||||
import { nip19 } from 'nostr-tools';
|
|
||||||
import type { Manager } from 'coco-cashu-core';
|
|
||||||
import type { Token } from '@cashu/cashu-ts';
|
|
||||||
import { useToast } from '@/hooks/useToast';
|
|
||||||
import * as bip39 from '@scure/bip39';
|
|
||||||
import { wordlist } from '@scure/bip39/wordlists/english.js';
|
|
||||||
import { initializeCoco, ConsoleLogger } from 'coco-cashu-core';
|
|
||||||
import { IndexedDbRepositories } from 'coco-cashu-indexeddb';
|
|
||||||
|
|
||||||
interface UseWalletTransactionsProps {
|
|
||||||
coco: Manager | null;
|
|
||||||
activeMintUrl: string | null;
|
|
||||||
generateQRCode: (text: string) => Promise<string>;
|
|
||||||
getEncodedToken: (token: Token | string) => string;
|
|
||||||
getLightningInvoice: (params: {
|
|
||||||
lightningAddress: string;
|
|
||||||
amountSats: number;
|
|
||||||
}) => Promise<string>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useWalletTransactions({
|
|
||||||
coco,
|
|
||||||
activeMintUrl,
|
|
||||||
generateQRCode,
|
|
||||||
getEncodedToken,
|
|
||||||
getLightningInvoice,
|
|
||||||
}: UseWalletTransactionsProps) {
|
|
||||||
const { toast } = useToast();
|
|
||||||
// Receive state
|
|
||||||
const [tokenInput, setTokenInput] = useState('');
|
|
||||||
const [quoteAmount, setQuoteAmount] = useState('');
|
|
||||||
|
|
||||||
// Send state
|
|
||||||
const [sendAmount, setSendAmount] = useState('');
|
|
||||||
const [lightningInvoice, setLightningInvoice] = useState('');
|
|
||||||
const [lightningAddressInput, setLightningAddressInput] = useState('');
|
|
||||||
const [lightningAddressAmount, setLightningAddressAmount] = useState('');
|
|
||||||
const [pendingLightningAddress, setPendingLightningAddress] = useState<
|
|
||||||
string | null
|
|
||||||
>(null);
|
|
||||||
const [decodedInvoiceAmount, setDecodedInvoiceAmount] = useState<number | null>(null);
|
|
||||||
const [pendingInvoice, setPendingInvoice] = useState<string | null>(null);
|
|
||||||
|
|
||||||
// Reverse swap state (Lightning -> Bitcoin)
|
|
||||||
const [pendingBitcoinSwapAddress, setPendingBitcoinSwapAddress] = useState<string | null>(null);
|
|
||||||
const [bitcoinSwapAmount, setBitcoinSwapAmount] = useState('');
|
|
||||||
const [swapStatus, setSwapStatus] = useState<string | null>(null);
|
|
||||||
const [reverseSwapClose, setReverseSwapClose] = useState<(() => void) | null>(null);
|
|
||||||
|
|
||||||
// Transaction output state
|
|
||||||
const [sentToken, setSentToken] = useState<string | null>(null);
|
|
||||||
const [sentTokenQRCode, setSentTokenQRCode] = useState<string>('');
|
|
||||||
|
|
||||||
// Invoice modal state
|
|
||||||
const [showInvoiceModal, setShowInvoiceModal] = useState(false);
|
|
||||||
const [currentInvoice, setCurrentInvoice] = useState<{
|
|
||||||
quoteId: string;
|
|
||||||
mintUrl: string;
|
|
||||||
amount: number;
|
|
||||||
invoice: string;
|
|
||||||
qrCodeUrl: string;
|
|
||||||
expiry: number;
|
|
||||||
} | null>(null);
|
|
||||||
|
|
||||||
// Restore state
|
|
||||||
const [isRestoring, setIsRestoring] = useState(false);
|
|
||||||
|
|
||||||
// Ref to store the mint quote redeemed event unsubscribe function
|
|
||||||
const mintQuoteUnsubscribeRef = useRef<(() => void) | null>(null);
|
|
||||||
|
|
||||||
// Generate QR code for sent token
|
|
||||||
const generateSentTokenQRCode = useCallback(async (token: string) => {
|
|
||||||
try {
|
|
||||||
const qrCodeUrl = await generateQRCode(token);
|
|
||||||
setSentTokenQRCode(qrCodeUrl);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Failed to generate sent token QR code:', err);
|
|
||||||
}
|
|
||||||
}, [generateQRCode]);
|
|
||||||
|
|
||||||
// Handle unknown mint error by adding the mint and retrying
|
|
||||||
const handleUnknownMintError = useCallback(
|
|
||||||
async (mintUrl: string) => {
|
|
||||||
if (!coco) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
console.log('Adding unknown mint:', mintUrl);
|
|
||||||
|
|
||||||
// Add the mint
|
|
||||||
await coco.mint.addMint(mintUrl);
|
|
||||||
|
|
||||||
// Retry receiving the token
|
|
||||||
await coco.wallet.receive(tokenInput);
|
|
||||||
setTokenInput('');
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: 'Token Received',
|
|
||||||
description: `Cashu token redeemed successfully! Added new mint: ${mintUrl}`,
|
|
||||||
});
|
|
||||||
} catch (retryErr) {
|
|
||||||
console.error('Failed to add mint and retry receive:', retryErr);
|
|
||||||
toast({
|
|
||||||
variant: 'destructive',
|
|
||||||
title: 'Receive Failed',
|
|
||||||
description: `Failed to add mint and receive token: ${retryErr instanceof Error ? retryErr.message : 'Unknown error'}`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[coco, tokenInput, toast]
|
|
||||||
);
|
|
||||||
|
|
||||||
// Handle receive (token or Lightning)
|
|
||||||
const handleReceive = useCallback(async () => {
|
|
||||||
if (!coco) return;
|
|
||||||
|
|
||||||
// Receive Cashu token mode
|
|
||||||
if (!tokenInput && !quoteAmount) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (tokenInput) {
|
|
||||||
// Receive token mode
|
|
||||||
try {
|
|
||||||
console.log(
|
|
||||||
'Attempting to receive token:',
|
|
||||||
tokenInput.substring(0, 20) + '...'
|
|
||||||
);
|
|
||||||
await coco.wallet.receive(tokenInput);
|
|
||||||
setTokenInput('');
|
|
||||||
toast({
|
|
||||||
title: 'Token Received',
|
|
||||||
description: 'Cashu token redeemed successfully!',
|
|
||||||
});
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Token receive error:', err);
|
|
||||||
|
|
||||||
// Handle UnknownMintError by automatically adding the mint
|
|
||||||
if (isUnknownMintError(err)) {
|
|
||||||
const mintUrl = extractMintUrlFromError(err);
|
|
||||||
if (mintUrl) {
|
|
||||||
await handleUnknownMintError(mintUrl);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
toast({
|
|
||||||
variant: 'destructive',
|
|
||||||
title: 'Receive Failed',
|
|
||||||
description: err instanceof Error ? err.message : 'Unknown error',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} else if (quoteAmount && activeMintUrl) {
|
|
||||||
// Lightning quote mode
|
|
||||||
try {
|
|
||||||
const amount = parseInt(quoteAmount);
|
|
||||||
if (isNaN(amount) || amount <= 0) {
|
|
||||||
toast({
|
|
||||||
variant: 'destructive',
|
|
||||||
title: 'Invalid Amount',
|
|
||||||
description: 'Please enter a valid amount',
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const quote = await coco.quotes.createMintQuote(activeMintUrl, amount);
|
|
||||||
|
|
||||||
// Generate QR code for the Lightning invoice
|
|
||||||
const qrCodeUrl = await generateQRCode(quote.request);
|
|
||||||
|
|
||||||
// Set the invoice data and show modal
|
|
||||||
setCurrentInvoice({
|
|
||||||
quoteId: quote.quote,
|
|
||||||
mintUrl: activeMintUrl,
|
|
||||||
amount,
|
|
||||||
invoice: quote.request,
|
|
||||||
qrCodeUrl,
|
|
||||||
expiry: quote.expiry,
|
|
||||||
});
|
|
||||||
|
|
||||||
setShowInvoiceModal(true);
|
|
||||||
setQuoteAmount('');
|
|
||||||
|
|
||||||
// Clean up any previous listener
|
|
||||||
if (mintQuoteUnsubscribeRef.current) {
|
|
||||||
mintQuoteUnsubscribeRef.current();
|
|
||||||
mintQuoteUnsubscribeRef.current = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Listen for payment notification via mint-quote:redeemed event
|
|
||||||
const quoteId = quote.quote;
|
|
||||||
const invoiceAmount = amount;
|
|
||||||
|
|
||||||
const unsubscribe = coco.on('mint-quote:redeemed', (payload: unknown) => {
|
|
||||||
const redeemedQuote = payload as { quoteId?: string };
|
|
||||||
|
|
||||||
// Check if this is the quote we're waiting for
|
|
||||||
if (redeemedQuote.quoteId === quoteId) {
|
|
||||||
toast({
|
|
||||||
title: 'Payment Received',
|
|
||||||
description: `Successfully received ${invoiceAmount} sats! Tokens have been added to your wallet.`,
|
|
||||||
});
|
|
||||||
setShowInvoiceModal(false);
|
|
||||||
setCurrentInvoice(null);
|
|
||||||
|
|
||||||
// Clean up the event listener
|
|
||||||
mintQuoteUnsubscribeRef.current = null;
|
|
||||||
unsubscribe();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Store unsubscribe function for cleanup
|
|
||||||
mintQuoteUnsubscribeRef.current = unsubscribe;
|
|
||||||
} catch (err) {
|
|
||||||
toast({
|
|
||||||
variant: 'destructive',
|
|
||||||
title: 'Quote Creation Failed',
|
|
||||||
description: err instanceof Error ? err.message : 'Unknown error',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [
|
|
||||||
coco,
|
|
||||||
tokenInput,
|
|
||||||
quoteAmount,
|
|
||||||
activeMintUrl,
|
|
||||||
toast,
|
|
||||||
generateQRCode,
|
|
||||||
handleUnknownMintError,
|
|
||||||
]);
|
|
||||||
|
|
||||||
// Handle send (token or Lightning)
|
|
||||||
const handleSend = useCallback(async () => {
|
|
||||||
console.log('[handleSend] Called with state:', {
|
|
||||||
hasCoco: !!coco,
|
|
||||||
sendAmount,
|
|
||||||
lightningInvoice,
|
|
||||||
lightningAddressInput,
|
|
||||||
pendingLightningAddress,
|
|
||||||
pendingBitcoinSwapAddress,
|
|
||||||
bitcoinSwapAmount,
|
|
||||||
activeMintUrl,
|
|
||||||
mode: 'lightning' // We're in Lightning mode when this is called
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!coco) {
|
|
||||||
console.log('[handleSend] No coco instance');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check for reverse swap first (this takes priority in Lightning mode)
|
|
||||||
if (pendingBitcoinSwapAddress && bitcoinSwapAmount) {
|
|
||||||
console.log('[handleSend] Reverse swap detected:', { pendingBitcoinSwapAddress, bitcoinSwapAmount });
|
|
||||||
// Don't return early - continue to reverse swap logic below
|
|
||||||
} else if (!sendAmount && !lightningInvoice && !lightningAddressInput && !pendingLightningAddress && !pendingBitcoinSwapAddress) {
|
|
||||||
console.log('[handleSend] No input provided - returning early');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send Cashu token mode
|
|
||||||
if (sendAmount && activeMintUrl) {
|
|
||||||
console.log('[handleSend] Handling token send mode');
|
|
||||||
try {
|
|
||||||
const amount = parseInt(sendAmount);
|
|
||||||
if (isNaN(amount) || amount <= 0) {
|
|
||||||
toast({
|
|
||||||
variant: 'destructive',
|
|
||||||
title: 'Invalid Amount',
|
|
||||||
description: 'Please enter a valid amount',
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const token = await coco.wallet.send(activeMintUrl, amount);
|
|
||||||
const encodedToken = getEncodedToken(token);
|
|
||||||
setSentToken(encodedToken);
|
|
||||||
await generateSentTokenQRCode(encodedToken);
|
|
||||||
setSendAmount('');
|
|
||||||
} catch (err) {
|
|
||||||
toast({
|
|
||||||
variant: 'destructive',
|
|
||||||
title: 'Send Failed',
|
|
||||||
description: err instanceof Error ? err.message : 'Unknown error',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} else if (activeMintUrl) {
|
|
||||||
// Lightning mode
|
|
||||||
console.log('[handleSend] Entering Lightning mode branch, activeMintUrl:', activeMintUrl);
|
|
||||||
// Step 1: Check if we have a pending Bitcoin swap address awaiting amount
|
|
||||||
if (pendingBitcoinSwapAddress) {
|
|
||||||
console.log('[handleSend] Found pendingBitcoinSwapAddress:', pendingBitcoinSwapAddress);
|
|
||||||
// Step 2: User entered amount, now initiate reverse swap
|
|
||||||
if (!bitcoinSwapAmount) {
|
|
||||||
console.log('[handleSend] Reverse swap pending but no amount provided');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('[handleSend] Starting reverse swap with:', {
|
|
||||||
address: pendingBitcoinSwapAddress,
|
|
||||||
amount: bitcoinSwapAmount,
|
|
||||||
activeMintUrl
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
const amount = parseInt(bitcoinSwapAmount);
|
|
||||||
if (isNaN(amount) || amount <= 0) {
|
|
||||||
toast({
|
|
||||||
variant: 'destructive',
|
|
||||||
title: 'Invalid Amount',
|
|
||||||
description: 'Please enter a valid amount',
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate reverse swap amount limits (25,000 - 25,000,000 sats)
|
|
||||||
if (amount < 25_000 || amount > 25_000_000) {
|
|
||||||
toast({
|
|
||||||
variant: 'destructive',
|
|
||||||
title: 'Invalid Amount',
|
|
||||||
description: 'Reverse swap amount must be between 25,000 and 25,000,000 sats',
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Determine destination address (could be Bitcoin address or npub)
|
|
||||||
let destinationAddress = pendingBitcoinSwapAddress;
|
|
||||||
try {
|
|
||||||
// Try to decode as npub first
|
|
||||||
const decoded = nip19.decode(pendingBitcoinSwapAddress);
|
|
||||||
if (decoded.type === 'npub') {
|
|
||||||
destinationAddress = npubToBitcoinAddress(pendingBitcoinSwapAddress);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// Not an npub, assume it's already a Bitcoin address
|
|
||||||
}
|
|
||||||
|
|
||||||
// Initiate reverse swap
|
|
||||||
console.log('[handleSend] Creating reverse swap...');
|
|
||||||
setSwapStatus('Creating reverse swap...');
|
|
||||||
const swapResult = await createReverseSwap({
|
|
||||||
invoiceAmount: amount,
|
|
||||||
destinationAddress,
|
|
||||||
onStatusUpdate: (update: SwapStatusUpdate) => {
|
|
||||||
switch (update.status) {
|
|
||||||
case 'swap.created':
|
|
||||||
setSwapStatus('Waiting for invoice payment...');
|
|
||||||
break;
|
|
||||||
case 'transaction.mempool':
|
|
||||||
setSwapStatus('Swap transaction sent to blockchain...');
|
|
||||||
break;
|
|
||||||
case 'invoice.settled':
|
|
||||||
case 'transaction.confirmed':
|
|
||||||
setSwapStatus('Swap completed!');
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onSuccess: () => {
|
|
||||||
const displayAddress = destinationAddress.length > 26
|
|
||||||
? destinationAddress.slice(0, 12) + '...' + destinationAddress.slice(-12)
|
|
||||||
: destinationAddress;
|
|
||||||
toast({
|
|
||||||
title: 'Reverse Swap Completed',
|
|
||||||
description: `Successfully swapped ${amount} sats to Bitcoin address ${displayAddress}!`,
|
|
||||||
});
|
|
||||||
setSwapStatus(null);
|
|
||||||
setPendingBitcoinSwapAddress(null);
|
|
||||||
setBitcoinSwapAmount('');
|
|
||||||
if (reverseSwapClose) {
|
|
||||||
reverseSwapClose();
|
|
||||||
setReverseSwapClose(null);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onError: (error: Error) => {
|
|
||||||
toast({
|
|
||||||
variant: 'destructive',
|
|
||||||
title: 'Reverse Swap Failed',
|
|
||||||
description: error.message,
|
|
||||||
});
|
|
||||||
setSwapStatus(null);
|
|
||||||
setPendingBitcoinSwapAddress(null);
|
|
||||||
setBitcoinSwapAmount('');
|
|
||||||
if (reverseSwapClose) {
|
|
||||||
reverseSwapClose();
|
|
||||||
setReverseSwapClose(null);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// Store close function for cleanup
|
|
||||||
setReverseSwapClose(() => swapResult.close);
|
|
||||||
|
|
||||||
// Pay the Lightning invoice from the swap using the active mint
|
|
||||||
console.log('[handleSend] Paying Lightning invoice:', swapResult.invoice);
|
|
||||||
setSwapStatus('Paying Lightning invoice...');
|
|
||||||
const meltQuote = await coco.quotes.createMeltQuote(
|
|
||||||
activeMintUrl,
|
|
||||||
swapResult.invoice
|
|
||||||
);
|
|
||||||
console.log('[handleSend] Melt quote created, paying...');
|
|
||||||
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
|
|
||||||
console.log('[handleSend] Invoice paid successfully');
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: 'Invoice Paid',
|
|
||||||
description: `Lightning invoice paid. Swap in progress...`,
|
|
||||||
});
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Reverse swap error:', err);
|
|
||||||
toast({
|
|
||||||
variant: 'destructive',
|
|
||||||
title: 'Reverse Swap Failed',
|
|
||||||
description: err instanceof Error ? err.message : 'Unknown error',
|
|
||||||
});
|
|
||||||
setSwapStatus(null);
|
|
||||||
setPendingBitcoinSwapAddress(null);
|
|
||||||
setBitcoinSwapAmount('');
|
|
||||||
if (reverseSwapClose) {
|
|
||||||
reverseSwapClose();
|
|
||||||
setReverseSwapClose(null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if (pendingLightningAddress) {
|
|
||||||
console.log('[handleSend] Handling Lightning address payment');
|
|
||||||
// Step 2: User entered amount, now resolve address and pay
|
|
||||||
if (!lightningAddressAmount) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const amount = parseInt(lightningAddressAmount);
|
|
||||||
if (isNaN(amount) || amount <= 0) {
|
|
||||||
toast({
|
|
||||||
variant: 'destructive',
|
|
||||||
title: 'Invalid Amount',
|
|
||||||
description: 'Please enter a valid amount',
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const invoice = await getLightningInvoice({
|
|
||||||
lightningAddress: pendingLightningAddress,
|
|
||||||
amountSats: amount,
|
|
||||||
});
|
|
||||||
|
|
||||||
const meltQuote = await coco.quotes.createMeltQuote(
|
|
||||||
activeMintUrl,
|
|
||||||
invoice
|
|
||||||
);
|
|
||||||
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: 'Payment Sent',
|
|
||||||
description: `Successfully sent ${amount} sats to ${pendingLightningAddress}!`,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Reset state
|
|
||||||
setPendingLightningAddress(null);
|
|
||||||
setLightningAddressInput('');
|
|
||||||
setLightningAddressAmount('');
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Payment error:', err);
|
|
||||||
toast({
|
|
||||||
variant: 'destructive',
|
|
||||||
title: 'Payment Failed',
|
|
||||||
description: err instanceof Error ? err.message : 'Unknown error',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Step 1: Check if input is a Bitcoin address, Lightning address, or invoice
|
|
||||||
const input = lightningInvoice.trim() || lightningAddressInput.trim();
|
|
||||||
if (!input) return;
|
|
||||||
|
|
||||||
// Check if it's a Bitcoin address (for reverse swap)
|
|
||||||
if (isValidBitcoinAddress(input)) {
|
|
||||||
setPendingBitcoinSwapAddress(input);
|
|
||||||
setLightningInvoice('');
|
|
||||||
setLightningAddressInput('');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if it's an npub (can be converted to Bitcoin address)
|
|
||||||
try {
|
|
||||||
const decoded = nip19.decode(input);
|
|
||||||
if (decoded.type === 'npub') {
|
|
||||||
const bitcoinAddr = npubToBitcoinAddress(input);
|
|
||||||
if (bitcoinAddr) {
|
|
||||||
setPendingBitcoinSwapAddress(input); // Store npub, will convert later
|
|
||||||
setLightningInvoice('');
|
|
||||||
setLightningAddressInput('');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// Not an npub, continue to check other formats
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if it's a Lightning address (contains @)
|
|
||||||
if (input.includes('@')) {
|
|
||||||
setPendingLightningAddress(input);
|
|
||||||
setLightningAddressInput('');
|
|
||||||
} else {
|
|
||||||
// It's a regular Lightning invoice - decode to show amount first
|
|
||||||
if (isValidBolt11Invoice(input)) {
|
|
||||||
const amount = decodeBolt11Amount(input);
|
|
||||||
if (amount) {
|
|
||||||
// Show amount confirmation screen
|
|
||||||
setPendingInvoice(input);
|
|
||||||
setDecodedInvoiceAmount(amount);
|
|
||||||
setLightningInvoice('');
|
|
||||||
return;
|
|
||||||
} else {
|
|
||||||
// Failed to decode amount - show error and don't attempt payment
|
|
||||||
toast({
|
|
||||||
variant: 'destructive',
|
|
||||||
title: 'Invalid Invoice',
|
|
||||||
description: 'Unable to decode the lightning invoice amount. Please check the invoice format.',
|
|
||||||
});
|
|
||||||
setLightningInvoice('');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Not a valid BOLT11 invoice - show error and don't attempt payment
|
|
||||||
toast({
|
|
||||||
variant: 'destructive',
|
|
||||||
title: 'Invalid Invoice',
|
|
||||||
description: 'This does not appear to be a valid lightning invoice. Please check the format.',
|
|
||||||
});
|
|
||||||
setLightningInvoice('');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [
|
|
||||||
coco,
|
|
||||||
sendAmount,
|
|
||||||
lightningInvoice,
|
|
||||||
lightningAddressInput,
|
|
||||||
lightningAddressAmount,
|
|
||||||
pendingLightningAddress,
|
|
||||||
pendingBitcoinSwapAddress,
|
|
||||||
bitcoinSwapAmount,
|
|
||||||
activeMintUrl,
|
|
||||||
toast,
|
|
||||||
getEncodedToken,
|
|
||||||
generateSentTokenQRCode,
|
|
||||||
getLightningInvoice,
|
|
||||||
reverseSwapClose,
|
|
||||||
npubToBitcoinAddress,
|
|
||||||
]);
|
|
||||||
|
|
||||||
// Handle confirmed invoice payment
|
|
||||||
const handleConfirmInvoicePayment = useCallback(async () => {
|
|
||||||
if (!coco || !pendingInvoice || !activeMintUrl) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const meltQuote = await coco.quotes.createMeltQuote(
|
|
||||||
activeMintUrl,
|
|
||||||
pendingInvoice
|
|
||||||
);
|
|
||||||
await coco.quotes.payMeltQuote(activeMintUrl, meltQuote.quote);
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: 'Invoice Paid',
|
|
||||||
description: `Lightning invoice paid successfully for ${decodedInvoiceAmount} sats!`,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Reset state
|
|
||||||
setPendingInvoice(null);
|
|
||||||
setDecodedInvoiceAmount(null);
|
|
||||||
} catch (err) {
|
|
||||||
toast({
|
|
||||||
variant: 'destructive',
|
|
||||||
title: 'Invoice Payment Failed',
|
|
||||||
description: err instanceof Error ? err.message : 'Unknown error',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}, [coco, pendingInvoice, activeMintUrl, decodedInvoiceAmount, toast]);
|
|
||||||
|
|
||||||
// Handle restore from seed phrase
|
|
||||||
const handleRestoreFromSeedPhrase = useCallback(async (seedPhrase: string, mintUrl: string) => {
|
|
||||||
if (!coco) {
|
|
||||||
throw new Error('Wallet not initialized');
|
|
||||||
}
|
|
||||||
|
|
||||||
setIsRestoring(true);
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Clean and validate the seed phrase
|
|
||||||
const cleanedSeedPhrase = seedPhrase.trim().toLowerCase();
|
|
||||||
|
|
||||||
// Check if it's a valid mnemonic format
|
|
||||||
if (!bip39.validateMnemonic(cleanedSeedPhrase, wordlist)) {
|
|
||||||
// Try to provide more specific error information
|
|
||||||
const words = cleanedSeedPhrase.split(/\s+/);
|
|
||||||
if (words.length !== 12) {
|
|
||||||
throw new Error(`Seed phrase must have exactly 12 words, but found ${words.length} words`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if all words are valid
|
|
||||||
const invalidWords = words.filter(word => !wordlist.includes(word));
|
|
||||||
if (invalidWords.length > 0) {
|
|
||||||
throw new Error(`Invalid words found: ${invalidWords.join(', ')}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error('Invalid seed phrase format. Please check that all words are spelled correctly.');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify this is a different seed from the current wallet
|
|
||||||
const currentMnemonic = localStorage.getItem('cashu-mnemonic');
|
|
||||||
if (currentMnemonic && currentMnemonic.toLowerCase() === cleanedSeedPhrase) {
|
|
||||||
throw new Error('This is the same seed phrase as your current wallet. Please enter a different seed phrase to restore from.');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Convert seed phrase to seed
|
|
||||||
const restoredSeed = bip39.mnemonicToSeedSync(cleanedSeedPhrase);
|
|
||||||
|
|
||||||
// Get current balance before restore
|
|
||||||
const balancesBefore = await coco.wallet.getBalances();
|
|
||||||
const balanceBefore = balancesBefore[mintUrl] || 0;
|
|
||||||
|
|
||||||
// Create a temporary coco instance with the restored seed to fetch proofs
|
|
||||||
const tempRepo = new IndexedDbRepositories({ name: `cashu-wallet-restore-${Date.now()}` });
|
|
||||||
await tempRepo.init();
|
|
||||||
|
|
||||||
const tempCoco = await initializeCoco({
|
|
||||||
repo: tempRepo,
|
|
||||||
seedGetter: async () => restoredSeed,
|
|
||||||
logger: new ConsoleLogger(`restore-${Date.now()}`, { level: "debug" })
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Restore the proofs in the temporary wallet
|
|
||||||
await tempCoco.wallet.restore(mintUrl);
|
|
||||||
|
|
||||||
// Get the restored balance from the temporary wallet
|
|
||||||
const tempBalances = await tempCoco.wallet.getBalances();
|
|
||||||
const restoredAmount = tempBalances[mintUrl] || 0;
|
|
||||||
|
|
||||||
if (restoredAmount <= 0) {
|
|
||||||
toast({
|
|
||||||
title: "No Tokens Found",
|
|
||||||
description: "No tokens were found for this seed phrase on the selected mint.",
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send the restored tokens from the temporary wallet
|
|
||||||
const token = await tempCoco.wallet.send(mintUrl, restoredAmount);
|
|
||||||
|
|
||||||
// Receive the token in the main wallet
|
|
||||||
await coco.wallet.receive(token);
|
|
||||||
|
|
||||||
// Verify the transfer
|
|
||||||
const balancesAfter = await coco.wallet.getBalances();
|
|
||||||
const balanceAfter = balancesAfter[mintUrl] || 0;
|
|
||||||
const actualRestored = balanceAfter - balanceBefore;
|
|
||||||
|
|
||||||
toast({
|
|
||||||
title: "Restore Successful",
|
|
||||||
description: `Restored ${actualRestored} sats from the seed phrase and added to your current wallet.`,
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
// Clean up temporary database (optional - happens automatically on next session)
|
|
||||||
// The temporary IndexedDB will be isolated to the unique name we provided
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Restore failed:', error);
|
|
||||||
throw error;
|
|
||||||
} finally {
|
|
||||||
setIsRestoring(false);
|
|
||||||
}
|
|
||||||
}, [coco, toast]);
|
|
||||||
|
|
||||||
// Cleanup mint quote listener on component unmount
|
|
||||||
useEffect(() => {
|
|
||||||
return () => {
|
|
||||||
if (mintQuoteUnsubscribeRef.current) {
|
|
||||||
mintQuoteUnsubscribeRef.current();
|
|
||||||
mintQuoteUnsubscribeRef.current = null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// Cleanup reverse swap WebSocket on unmount
|
|
||||||
useEffect(() => {
|
|
||||||
return () => {
|
|
||||||
if (reverseSwapClose) {
|
|
||||||
reverseSwapClose();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}, [reverseSwapClose]);
|
|
||||||
|
|
||||||
return {
|
|
||||||
// Receive state
|
|
||||||
tokenInput,
|
|
||||||
setTokenInput,
|
|
||||||
quoteAmount,
|
|
||||||
setQuoteAmount,
|
|
||||||
// Send state
|
|
||||||
sendAmount,
|
|
||||||
setSendAmount,
|
|
||||||
lightningInvoice,
|
|
||||||
setLightningInvoice,
|
|
||||||
lightningAddressInput,
|
|
||||||
setLightningAddressInput,
|
|
||||||
lightningAddressAmount,
|
|
||||||
setLightningAddressAmount,
|
|
||||||
pendingLightningAddress,
|
|
||||||
setPendingLightningAddress,
|
|
||||||
decodedInvoiceAmount,
|
|
||||||
setDecodedInvoiceAmount,
|
|
||||||
pendingInvoice,
|
|
||||||
setPendingInvoice,
|
|
||||||
// Reverse swap state
|
|
||||||
pendingBitcoinSwapAddress,
|
|
||||||
setPendingBitcoinSwapAddress,
|
|
||||||
bitcoinSwapAmount,
|
|
||||||
setBitcoinSwapAmount,
|
|
||||||
swapStatus,
|
|
||||||
// Transaction output state
|
|
||||||
sentToken,
|
|
||||||
setSentToken,
|
|
||||||
sentTokenQRCode,
|
|
||||||
// Invoice modal state
|
|
||||||
showInvoiceModal,
|
|
||||||
setShowInvoiceModal,
|
|
||||||
currentInvoice,
|
|
||||||
setCurrentInvoice,
|
|
||||||
// Handlers
|
|
||||||
handleReceive,
|
|
||||||
handleSend,
|
|
||||||
handleConfirmInvoicePayment,
|
|
||||||
// Restore functionality
|
|
||||||
handleRestoreFromSeedPhrase,
|
|
||||||
isRestoring,
|
|
||||||
// Refs
|
|
||||||
mintQuoteUnsubscribeRef,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
Reference in new issue
Block a user