mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-06 08:47:23 +00:00
Merge branch 'main' of gitlab.com:soapbox-pub/mkstack
This commit is contained in:
8 files changed
+207
-141
No files matched your search
+147
-18
@@ -1,11 +1,82 @@
|
|||||||
### AI Integration with Shakespeare API
|
### AI Integration with Shakespeare API
|
||||||
|
|
||||||
Use the `useShakespeare` hook for AI chat completions with Nostr authentication.
|
Use the `useShakespeare` hook for AI chat completions with Nostr authentication. The API dynamically provides available models, so you should query them at runtime rather than hardcoding model names.
|
||||||
|
|
||||||
```tsx
|
```tsx
|
||||||
import { useShakespeare, type ChatMessage } from '@/hooks/useShakespeare';
|
import { useShakespeare, type ChatMessage, type Model } from '@/hooks/useShakespeare';
|
||||||
|
|
||||||
const { sendChatMessage, sendStreamingMessage, isLoading, error, isAuthenticated } = useShakespeare();
|
const {
|
||||||
|
sendChatMessage,
|
||||||
|
sendStreamingMessage,
|
||||||
|
getAvailableModels,
|
||||||
|
isLoading,
|
||||||
|
error,
|
||||||
|
isAuthenticated
|
||||||
|
} = useShakespeare();
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Model Selector Component
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function ModelSelector({ onModelSelect }: { onModelSelect: (modelId: string) => void }) {
|
||||||
|
const { getAvailableModels, isLoading } = useShakespeare();
|
||||||
|
const [models, setModels] = useState<Model[]>([]);
|
||||||
|
const [selectedModel, setSelectedModel] = useState<string>('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchModels = async () => {
|
||||||
|
try {
|
||||||
|
const response = await getAvailableModels();
|
||||||
|
// Sort models by total cost (cheapest first)
|
||||||
|
const sortedModels = response.data.sort((a, b) => {
|
||||||
|
const costA = parseFloat(a.pricing.prompt) + parseFloat(a.pricing.completion);
|
||||||
|
const costB = parseFloat(b.pricing.prompt) + parseFloat(b.pricing.completion);
|
||||||
|
return costA - costB;
|
||||||
|
});
|
||||||
|
setModels(sortedModels);
|
||||||
|
|
||||||
|
// Select the cheapest model by default
|
||||||
|
if (sortedModels.length > 0) {
|
||||||
|
const cheapestModel = sortedModels[0];
|
||||||
|
setSelectedModel(cheapestModel.id);
|
||||||
|
onModelSelect(cheapestModel.id);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to fetch models:', err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchModels();
|
||||||
|
}, [getAvailableModels, onModelSelect]);
|
||||||
|
|
||||||
|
const handleModelChange = (modelId: string) => {
|
||||||
|
setSelectedModel(modelId);
|
||||||
|
onModelSelect(modelId);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<label htmlFor="model-select">Choose Model:</label>
|
||||||
|
<select
|
||||||
|
id="model-select"
|
||||||
|
value={selectedModel}
|
||||||
|
onChange={(e) => handleModelChange(e.target.value)}
|
||||||
|
disabled={isLoading}
|
||||||
|
>
|
||||||
|
<option value="">Select a model...</option>
|
||||||
|
{models.map((model, index) => {
|
||||||
|
const totalCost = parseFloat(model.pricing.prompt) + parseFloat(model.pricing.completion);
|
||||||
|
const isCheapest = index === 0;
|
||||||
|
return (
|
||||||
|
<option key={model.id} value={model.id}>
|
||||||
|
{model.name} - {isCheapest ? "Cheapest" : `$${totalCost.toFixed(6)}/token`}
|
||||||
|
</option>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Basic Chat Example
|
#### Basic Chat Example
|
||||||
@@ -15,19 +86,24 @@ function AIChat() {
|
|||||||
const { sendChatMessage, isLoading, error, isAuthenticated } = useShakespeare();
|
const { sendChatMessage, isLoading, error, isAuthenticated } = useShakespeare();
|
||||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||||
const [input, setInput] = useState('');
|
const [input, setInput] = useState('');
|
||||||
|
const [selectedModel, setSelectedModel] = useState<string>('');
|
||||||
|
|
||||||
const handleSend = async () => {
|
const handleSend = async () => {
|
||||||
if (!input.trim()) return;
|
if (!input.trim() || !selectedModel) return;
|
||||||
|
|
||||||
const newMessages = [...messages, { role: 'user', content: input }];
|
const newMessages = [...messages, { role: 'user', content: input }];
|
||||||
setMessages(newMessages);
|
setMessages(newMessages);
|
||||||
setInput('');
|
setInput('');
|
||||||
|
|
||||||
const response = await sendChatMessage(newMessages, 'tybalt'); // Free model
|
try {
|
||||||
|
const response = await sendChatMessage(newMessages, selectedModel);
|
||||||
setMessages(prev => [...prev, {
|
setMessages(prev => [...prev, {
|
||||||
role: 'assistant',
|
role: 'assistant',
|
||||||
content: response.choices[0].message.content as string
|
content: response.choices[0].message.content as string
|
||||||
}]);
|
}]);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Chat error:', err);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!isAuthenticated) return <div>Please log in to use AI</div>;
|
if (!isAuthenticated) return <div>Please log in to use AI</div>;
|
||||||
@@ -36,6 +112,11 @@ function AIChat() {
|
|||||||
<div className="max-w-2xl mx-auto p-4">
|
<div className="max-w-2xl mx-auto p-4">
|
||||||
{error && <div className="text-red-500 mb-4">{error}</div>}
|
{error && <div className="text-red-500 mb-4">{error}</div>}
|
||||||
|
|
||||||
|
{/* Model Selection */}
|
||||||
|
<div className="mb-4">
|
||||||
|
<ModelSelector onModelSelect={setSelectedModel} />
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2 mb-4">
|
<div className="space-y-2 mb-4">
|
||||||
{messages.map((msg, i) => (
|
{messages.map((msg, i) => (
|
||||||
<div key={i} className={`p-2 rounded ${msg.role === 'user' ? 'bg-blue-100' : 'bg-gray-100'}`}>
|
<div key={i} className={`p-2 rounded ${msg.role === 'user' ? 'bg-blue-100' : 'bg-gray-100'}`}>
|
||||||
@@ -50,9 +131,14 @@ function AIChat() {
|
|||||||
onChange={(e) => setInput(e.target.value)}
|
onChange={(e) => setInput(e.target.value)}
|
||||||
onKeyPress={(e) => e.key === 'Enter' && handleSend()}
|
onKeyPress={(e) => e.key === 'Enter' && handleSend()}
|
||||||
className="flex-1 p-2 border rounded"
|
className="flex-1 p-2 border rounded"
|
||||||
disabled={isLoading}
|
disabled={isLoading || !selectedModel}
|
||||||
|
placeholder={!selectedModel ? "Select a model first..." : "Type your message..."}
|
||||||
/>
|
/>
|
||||||
<button onClick={handleSend} disabled={isLoading} className="px-4 py-2 bg-blue-500 text-white rounded">
|
<button
|
||||||
|
onClick={handleSend}
|
||||||
|
disabled={isLoading || !selectedModel}
|
||||||
|
className="px-4 py-2 bg-blue-500 text-white rounded disabled:opacity-50"
|
||||||
|
>
|
||||||
Send
|
Send
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -61,30 +147,73 @@ function AIChat() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Streaming Chat
|
#### Streaming Chat Example
|
||||||
|
|
||||||
```tsx
|
```tsx
|
||||||
|
function StreamingChat() {
|
||||||
|
const { sendStreamingMessage } = useShakespeare();
|
||||||
|
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||||
const [currentResponse, setCurrentResponse] = useState('');
|
const [currentResponse, setCurrentResponse] = useState('');
|
||||||
|
const [selectedModel, setSelectedModel] = useState<string>('');
|
||||||
|
|
||||||
const handleStreaming = async (content: string) => {
|
const handleStreaming = async (content: string) => {
|
||||||
|
if (!selectedModel) return;
|
||||||
|
|
||||||
setCurrentResponse('');
|
setCurrentResponse('');
|
||||||
await sendStreamingMessage(messages, 'shakespeare', (chunk) => {
|
const newMessages = [...messages, { role: 'user', content }];
|
||||||
|
setMessages(newMessages);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await sendStreamingMessage(newMessages, selectedModel, (chunk) => {
|
||||||
setCurrentResponse(prev => prev + chunk);
|
setCurrentResponse(prev => prev + chunk);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Add the complete response to messages
|
||||||
|
if (currentResponse.trim()) {
|
||||||
|
setMessages(prev => [...prev, {
|
||||||
|
role: 'assistant',
|
||||||
|
content: currentResponse
|
||||||
|
}]);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Streaming error:', err);
|
||||||
|
} finally {
|
||||||
|
setCurrentResponse('');
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{/* Model selection UI */}
|
||||||
|
<div className="mb-4">
|
||||||
|
<ModelSelector onModelSelect={setSelectedModel} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Chat interface */}
|
||||||
|
{/* ... rest of your chat UI */}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Models
|
#### Model Information
|
||||||
|
|
||||||
- **`tybalt`**: Free model for development
|
Models are dynamically fetched from the Shakespeare API and include:
|
||||||
- **`shakespeare`**: Premium model (requires credits)
|
|
||||||
|
- **Model ID**: Unique identifier for the model
|
||||||
|
- **Name**: Human-readable model name
|
||||||
|
- **Description**: Model capabilities and use cases
|
||||||
|
- **Context Window**: Maximum token limit for conversations
|
||||||
|
- **Pricing**: Cost per token for prompt and completion
|
||||||
|
- **Free Models**: Models with `pricing.prompt === "0"` and `pricing.completion === "0"`
|
||||||
|
|
||||||
#### Key Points
|
#### Key Points
|
||||||
|
|
||||||
- User must be logged in with Nostr account
|
- **Dynamic Model Discovery**: Always fetch available models using `getAvailableModels()`
|
||||||
- Use `tybalt` for free testing
|
- **Authentication Required**: User must be logged in with Nostr account
|
||||||
- Handle `isLoading` and `error` states
|
- **Free vs Premium**: Check pricing to determine if model requires credits
|
||||||
- Check `isAuthenticated` before API calls
|
- **Error Handling**: Handle `isLoading` and `error` states appropriately
|
||||||
|
- **Model Selection**: Provide UI for users to choose between available models
|
||||||
|
|
||||||
## Implementation Patterns and Best Practices
|
## Implementation Patterns and Best Practices
|
||||||
|
|
||||||
@@ -182,9 +311,9 @@ function AIChatWithErrorBoundary() {
|
|||||||
function useAIWithErrorHandling() {
|
function useAIWithErrorHandling() {
|
||||||
const { sendChatMessage, error, clearError } = useShakespeare();
|
const { sendChatMessage, error, clearError } = useShakespeare();
|
||||||
|
|
||||||
const sendMessage = async (messages: ChatMessage[]) => {
|
const sendMessage = async (messages: ChatMessage[], modelId: string) => {
|
||||||
try {
|
try {
|
||||||
await sendChatMessage(messages, 'tybalt');
|
await sendChatMessage(messages, modelId);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Handle specific error types with user-friendly messages
|
// Handle specific error types with user-friendly messages
|
||||||
if (err.message.includes('401')) {
|
if (err.message.includes('401')) {
|
||||||
|
|||||||
@@ -34,18 +34,27 @@ Example usage with intersection observer for automatic loading:
|
|||||||
|
|
||||||
```tsx
|
```tsx
|
||||||
import { useInView } from 'react-intersection-observer';
|
import { useInView } from 'react-intersection-observer';
|
||||||
|
import { useMemo } from 'react';
|
||||||
|
|
||||||
function GlobalFeed() {
|
function GlobalFeed() {
|
||||||
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useGlobalFeed();
|
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useGlobalFeed();
|
||||||
const { ref, inView } = useInView();
|
const { ref, inView } = useInView();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (inView && hasNextPage) {
|
if (inView && hasNextPage && !isFetchingNextPage) {
|
||||||
fetchNextPage();
|
fetchNextPage();
|
||||||
}
|
}
|
||||||
}, [inView, hasNextPage, fetchNextPage]);
|
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage]);
|
||||||
|
|
||||||
const posts = data?.pages.flat() || [];
|
// Remove duplicate events by ID
|
||||||
|
const posts = useMemo(() => {
|
||||||
|
const seen = new Set();
|
||||||
|
return data?.pages.flat().filter(event => {
|
||||||
|
if (!event.id || seen.has(event.id)) return false;
|
||||||
|
seen.add(event.id);
|
||||||
|
return true;
|
||||||
|
}) || [];
|
||||||
|
}, [data?.pages]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
|
|||||||
Generated
+12
-34
@@ -63,7 +63,6 @@
|
|||||||
"tailwind-merge": "^2.5.2",
|
"tailwind-merge": "^2.5.2",
|
||||||
"tailwindcss-animate": "^1.0.7",
|
"tailwindcss-animate": "^1.0.7",
|
||||||
"vaul": "^0.9.3",
|
"vaul": "^0.9.3",
|
||||||
"webln": "^0.3.2",
|
|
||||||
"zod": "^3.25.71"
|
"zod": "^3.25.71"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -78,6 +77,7 @@
|
|||||||
"@types/react": "^18.3.1",
|
"@types/react": "^18.3.1",
|
||||||
"@types/react-dom": "^18.3.1",
|
"@types/react-dom": "^18.3.1",
|
||||||
"@vitejs/plugin-react-swc": "^3.5.0",
|
"@vitejs/plugin-react-swc": "^3.5.0",
|
||||||
|
"@webbtc/webln-types": "^3.0.0",
|
||||||
"autoprefixer": "^10.4.20",
|
"autoprefixer": "^10.4.20",
|
||||||
"eslint": "^9.9.0",
|
"eslint": "^9.9.0",
|
||||||
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
|
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
|
||||||
@@ -3416,15 +3416,6 @@
|
|||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true
|
"peer": true
|
||||||
},
|
},
|
||||||
"node_modules/@types/chrome": {
|
|
||||||
"version": "0.0.74",
|
|
||||||
"resolved": "https://registry.npmjs.org/@types/chrome/-/chrome-0.0.74.tgz",
|
|
||||||
"integrity": "sha512-hzosS5CkQcIKCgxcsV2AzbJ36KNxG/Db2YEN/erEu7Boprg+KpMDLBQqKFmSo+JkQMGqRcicUyqCowJpuT+C6A==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@types/filesystem": "*"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@types/d3-array": {
|
"node_modules/@types/d3-array": {
|
||||||
"version": "3.2.1",
|
"version": "3.2.1",
|
||||||
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.1.tgz",
|
||||||
@@ -3494,21 +3485,6 @@
|
|||||||
"integrity": "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ==",
|
"integrity": "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@types/filesystem": {
|
|
||||||
"version": "0.0.36",
|
|
||||||
"resolved": "https://registry.npmjs.org/@types/filesystem/-/filesystem-0.0.36.tgz",
|
|
||||||
"integrity": "sha512-vPDXOZuannb9FZdxgHnqSwAG/jvdGM8Wq+6N4D/d80z+D4HWH+bItqsZaVRQykAn6WEVeEkLm2oQigyHtgb0RA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@types/filewriter": "*"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@types/filewriter": {
|
|
||||||
"version": "0.0.33",
|
|
||||||
"resolved": "https://registry.npmjs.org/@types/filewriter/-/filewriter-0.0.33.tgz",
|
|
||||||
"integrity": "sha512-xFU8ZXTw4gd358lb2jw25nxY9QAgqn2+bKKjKOYfNCzN4DKCFetK7sPtrlpg66Ywe3vWY9FNxprZawAh9wfJ3g==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/@types/json-schema": {
|
"node_modules/@types/json-schema": {
|
||||||
"version": "7.0.15",
|
"version": "7.0.15",
|
||||||
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
|
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
|
||||||
@@ -3929,6 +3905,17 @@
|
|||||||
"url": "https://opencollective.com/vitest"
|
"url": "https://opencollective.com/vitest"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@webbtc/webln-types": {
|
||||||
|
"version": "3.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@webbtc/webln-types/-/webln-types-3.0.0.tgz",
|
||||||
|
"integrity": "sha512-aXfTHLKz5lysd+6xTeWl+qHNh/p3qVYbeLo+yDN5cUDmhie2ZoGvkppfWxzbGkcFBzb6dJyQ2/i2cbmDHas+zQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"type": "lightning",
|
||||||
|
"url": "lightning:[email protected]"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/acorn": {
|
"node_modules/acorn": {
|
||||||
"version": "8.15.0",
|
"version": "8.15.0",
|
||||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
|
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
|
||||||
@@ -8011,15 +7998,6 @@
|
|||||||
"node": ">=12"
|
"node": ">=12"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/webln": {
|
|
||||||
"version": "0.3.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/webln/-/webln-0.3.2.tgz",
|
|
||||||
"integrity": "sha512-YYT83aOCLup2AmqvJdKtdeBTaZpjC6/JDMe8o6x1kbTYWwiwrtWHyO//PAsPixF3jwFsAkj5DmiceB6w/QSe7Q==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@types/chrome": "^0.0.74"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/webpack-virtual-modules": {
|
"node_modules/webpack-virtual-modules": {
|
||||||
"version": "0.6.2",
|
"version": "0.6.2",
|
||||||
"resolved": "https://registry.npmjs.org/webpack-virtual-modules/-/webpack-virtual-modules-0.6.2.tgz",
|
"resolved": "https://registry.npmjs.org/webpack-virtual-modules/-/webpack-virtual-modules-0.6.2.tgz",
|
||||||
|
|||||||
+1
-1
@@ -65,7 +65,6 @@
|
|||||||
"tailwind-merge": "^2.5.2",
|
"tailwind-merge": "^2.5.2",
|
||||||
"tailwindcss-animate": "^1.0.7",
|
"tailwindcss-animate": "^1.0.7",
|
||||||
"vaul": "^0.9.3",
|
"vaul": "^0.9.3",
|
||||||
"webln": "^0.3.2",
|
|
||||||
"zod": "^3.25.71"
|
"zod": "^3.25.71"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -80,6 +79,7 @@
|
|||||||
"@types/react": "^18.3.1",
|
"@types/react": "^18.3.1",
|
||||||
"@types/react-dom": "^18.3.1",
|
"@types/react-dom": "^18.3.1",
|
||||||
"@vitejs/plugin-react-swc": "^3.5.0",
|
"@vitejs/plugin-react-swc": "^3.5.0",
|
||||||
|
"@webbtc/webln-types": "^3.0.0",
|
||||||
"autoprefixer": "^10.4.20",
|
"autoprefixer": "^10.4.20",
|
||||||
"eslint": "^9.9.0",
|
"eslint": "^9.9.0",
|
||||||
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
|
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ import { useWallet } from '@/hooks/useWallet';
|
|||||||
import { useToast } from '@/hooks/useToast';
|
import { useToast } from '@/hooks/useToast';
|
||||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||||
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC';
|
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC';
|
||||||
|
import type { WebLNProvider } from "@webbtc/webln-types";
|
||||||
|
|
||||||
interface WalletModalProps {
|
interface WalletModalProps {
|
||||||
children?: React.ReactNode;
|
children?: React.ReactNode;
|
||||||
@@ -68,8 +69,7 @@ AddWalletContent.displayName = 'AddWalletContent';
|
|||||||
|
|
||||||
// Extracted WalletContent to prevent re-renders
|
// Extracted WalletContent to prevent re-renders
|
||||||
const WalletContent = forwardRef<HTMLDivElement, {
|
const WalletContent = forwardRef<HTMLDivElement, {
|
||||||
hasWebLN: boolean;
|
webln: WebLNProvider | null;
|
||||||
isDetecting: boolean;
|
|
||||||
hasNWC: boolean;
|
hasNWC: boolean;
|
||||||
connections: NWCConnection[];
|
connections: NWCConnection[];
|
||||||
connectionInfo: Record<string, NWCInfo>;
|
connectionInfo: Record<string, NWCInfo>;
|
||||||
@@ -78,8 +78,7 @@ const WalletContent = forwardRef<HTMLDivElement, {
|
|||||||
handleRemoveConnection: (cs: string) => void;
|
handleRemoveConnection: (cs: string) => void;
|
||||||
setAddDialogOpen: (open: boolean) => void;
|
setAddDialogOpen: (open: boolean) => void;
|
||||||
}>(({
|
}>(({
|
||||||
hasWebLN,
|
webln,
|
||||||
isDetecting,
|
|
||||||
hasNWC,
|
hasNWC,
|
||||||
connections,
|
connections,
|
||||||
connectionInfo,
|
connectionInfo,
|
||||||
@@ -103,9 +102,9 @@ const WalletContent = forwardRef<HTMLDivElement, {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
{hasWebLN && <CheckCircle className="h-4 w-4 text-green-600" />}
|
{webln && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||||
<Badge variant={hasWebLN ? "default" : "secondary"} className="text-xs">
|
<Badge variant={webln ? "default" : "secondary"} className="text-xs">
|
||||||
{isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found"}
|
{webln ? "Ready" : "Not Found"}
|
||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -191,7 +190,7 @@ const WalletContent = forwardRef<HTMLDivElement, {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{/* Help */}
|
{/* Help */}
|
||||||
{!hasWebLN && connections.length === 0 && (
|
{!webln && connections.length === 0 && (
|
||||||
<>
|
<>
|
||||||
<Separator />
|
<Separator />
|
||||||
<div className="text-center py-4 space-y-2">
|
<div className="text-center py-4 space-y-2">
|
||||||
@@ -222,7 +221,7 @@ export function WalletModal({ children, className }: WalletModalProps) {
|
|||||||
setActiveConnection
|
setActiveConnection
|
||||||
} = useNWC();
|
} = useNWC();
|
||||||
|
|
||||||
const { hasWebLN, isDetecting } = useWallet();
|
const { webln } = useWallet();
|
||||||
|
|
||||||
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
|
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
@@ -263,8 +262,7 @@ export function WalletModal({ children, className }: WalletModalProps) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const walletContentProps = {
|
const walletContentProps = {
|
||||||
hasWebLN,
|
webln,
|
||||||
isDetecting,
|
|
||||||
hasNWC,
|
hasNWC,
|
||||||
connections,
|
connections,
|
||||||
connectionInfo,
|
connectionInfo,
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ import { useWallet } from '@/hooks/useWallet';
|
|||||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||||
import type { Event } from 'nostr-tools';
|
import type { Event } from 'nostr-tools';
|
||||||
import QRCode from 'qrcode';
|
import QRCode from 'qrcode';
|
||||||
|
import type { WebLNProvider } from "@webbtc/webln-types";
|
||||||
|
|
||||||
interface ZapDialogProps {
|
interface ZapDialogProps {
|
||||||
target: Event;
|
target: Event;
|
||||||
@@ -55,7 +56,7 @@ interface ZapContentProps {
|
|||||||
isZapping: boolean;
|
isZapping: boolean;
|
||||||
qrCodeUrl: string;
|
qrCodeUrl: string;
|
||||||
copied: boolean;
|
copied: boolean;
|
||||||
hasWebLN: boolean;
|
webln: WebLNProvider | null;
|
||||||
handleZap: () => void;
|
handleZap: () => void;
|
||||||
handleCopy: () => void;
|
handleCopy: () => void;
|
||||||
openInWallet: () => void;
|
openInWallet: () => void;
|
||||||
@@ -73,7 +74,7 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
|||||||
isZapping,
|
isZapping,
|
||||||
qrCodeUrl,
|
qrCodeUrl,
|
||||||
copied,
|
copied,
|
||||||
hasWebLN,
|
webln,
|
||||||
handleZap,
|
handleZap,
|
||||||
handleCopy,
|
handleCopy,
|
||||||
openInWallet,
|
openInWallet,
|
||||||
@@ -138,7 +139,7 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
|||||||
|
|
||||||
{/* Payment buttons */}
|
{/* Payment buttons */}
|
||||||
<div className="space-y-3 mt-4">
|
<div className="space-y-3 mt-4">
|
||||||
{hasWebLN && (
|
{webln && (
|
||||||
<Button
|
<Button
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
||||||
@@ -234,13 +235,12 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
|||||||
));
|
));
|
||||||
ZapContent.displayName = 'ZapContent';
|
ZapContent.displayName = 'ZapContent';
|
||||||
|
|
||||||
|
|
||||||
export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const { user } = useCurrentUser();
|
const { user } = useCurrentUser();
|
||||||
const { data: author } = useAuthor(target.pubkey);
|
const { data: author } = useAuthor(target.pubkey);
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const { webln, activeNWC, hasWebLN, detectWebLN } = useWallet();
|
const { webln, activeNWC } = useWallet();
|
||||||
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
|
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
|
||||||
const [amount, setAmount] = useState<number | string>(100);
|
const [amount, setAmount] = useState<number | string>(100);
|
||||||
const [comment, setComment] = useState<string>('');
|
const [comment, setComment] = useState<string>('');
|
||||||
@@ -255,13 +255,6 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
|||||||
}
|
}
|
||||||
}, [target]);
|
}, [target]);
|
||||||
|
|
||||||
// Detect WebLN when dialog opens
|
|
||||||
useEffect(() => {
|
|
||||||
if (open && !hasWebLN) {
|
|
||||||
detectWebLN();
|
|
||||||
}
|
|
||||||
}, [open, hasWebLN, detectWebLN]);
|
|
||||||
|
|
||||||
// Generate QR code
|
// Generate QR code
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let isCancelled = false;
|
let isCancelled = false;
|
||||||
@@ -345,7 +338,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
|||||||
isZapping,
|
isZapping,
|
||||||
qrCodeUrl,
|
qrCodeUrl,
|
||||||
copied,
|
copied,
|
||||||
hasWebLN,
|
webln,
|
||||||
handleZap,
|
handleZap,
|
||||||
handleCopy,
|
handleCopy,
|
||||||
openInWallet,
|
openInWallet,
|
||||||
|
|||||||
+5
-58
@@ -1,68 +1,22 @@
|
|||||||
import { useState, useEffect, useCallback, useMemo } from 'react';
|
import { useMemo } from 'react';
|
||||||
import { useNWC } from '@/hooks/useNWCContext';
|
import { useNWC } from '@/hooks/useNWCContext';
|
||||||
import type { WebLNProvider } from 'webln';
|
import type { WebLNProvider } from '@webbtc/webln-types';
|
||||||
import { requestProvider } from 'webln';
|
|
||||||
|
|
||||||
export interface WalletStatus {
|
export interface WalletStatus {
|
||||||
hasWebLN: boolean;
|
|
||||||
hasNWC: boolean;
|
hasNWC: boolean;
|
||||||
webln: WebLNProvider | null;
|
webln: WebLNProvider | null;
|
||||||
activeNWC: ReturnType<typeof useNWC>['getActiveConnection'] extends () => infer T ? T : null;
|
activeNWC: ReturnType<typeof useNWC>['getActiveConnection'] extends () => infer T ? T : null;
|
||||||
isDetecting: boolean;
|
|
||||||
preferredMethod: 'nwc' | 'webln' | 'manual';
|
preferredMethod: 'nwc' | 'webln' | 'manual';
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useWallet() {
|
export function useWallet() {
|
||||||
const [webln, setWebln] = useState<WebLNProvider | null>(null);
|
|
||||||
const [isDetecting, setIsDetecting] = useState(false);
|
|
||||||
const [hasAttemptedDetection, setHasAttemptedDetection] = useState(false);
|
|
||||||
const { connections, getActiveConnection } = useNWC();
|
const { connections, getActiveConnection } = useNWC();
|
||||||
|
|
||||||
// Get the active connection directly - no memoization to avoid stale state
|
// Get the active connection directly - no memoization to avoid stale state
|
||||||
const activeNWC = getActiveConnection();
|
const activeNWC = getActiveConnection();
|
||||||
|
|
||||||
// Detect WebLN
|
// Access WebLN directly from browser global scope
|
||||||
const detectWebLN = useCallback(async () => {
|
const webln = (globalThis as { webln?: WebLNProvider }).webln || null;
|
||||||
if (webln || isDetecting) return webln;
|
|
||||||
|
|
||||||
setIsDetecting(true);
|
|
||||||
try {
|
|
||||||
const provider = await requestProvider();
|
|
||||||
setWebln(provider);
|
|
||||||
setHasAttemptedDetection(true);
|
|
||||||
return provider;
|
|
||||||
} catch (error) {
|
|
||||||
// Only log the error if it's not the common "no provider" error
|
|
||||||
if (error instanceof Error && !error.message.includes('no WebLN provider')) {
|
|
||||||
console.warn('WebLN detection error:', error);
|
|
||||||
}
|
|
||||||
setWebln(null);
|
|
||||||
setHasAttemptedDetection(true);
|
|
||||||
return null;
|
|
||||||
} finally {
|
|
||||||
setIsDetecting(false);
|
|
||||||
}
|
|
||||||
}, [webln, isDetecting]);
|
|
||||||
|
|
||||||
// Only auto-detect once on mount
|
|
||||||
useEffect(() => {
|
|
||||||
if (!hasAttemptedDetection) {
|
|
||||||
detectWebLN();
|
|
||||||
}
|
|
||||||
}, [detectWebLN, hasAttemptedDetection]);
|
|
||||||
|
|
||||||
// Test WebLN connection
|
|
||||||
const testWebLN = useCallback(async (): Promise<boolean> => {
|
|
||||||
if (!webln) return false;
|
|
||||||
|
|
||||||
try {
|
|
||||||
await webln.enable();
|
|
||||||
return true;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('WebLN test failed:', error);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}, [webln]);
|
|
||||||
|
|
||||||
// Calculate status values reactively
|
// Calculate status values reactively
|
||||||
const hasNWC = useMemo(() => {
|
const hasNWC = useMemo(() => {
|
||||||
@@ -77,18 +31,11 @@ export function useWallet() {
|
|||||||
: 'manual';
|
: 'manual';
|
||||||
|
|
||||||
const status: WalletStatus = {
|
const status: WalletStatus = {
|
||||||
hasWebLN: !!webln,
|
|
||||||
hasNWC,
|
hasNWC,
|
||||||
webln,
|
webln,
|
||||||
activeNWC,
|
activeNWC,
|
||||||
isDetecting,
|
|
||||||
preferredMethod,
|
preferredMethod,
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return status;
|
||||||
...status,
|
|
||||||
hasAttemptedDetection,
|
|
||||||
detectWebLN,
|
|
||||||
testWebLN,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
+15
-3
@@ -7,7 +7,7 @@ import { useNWC } from '@/hooks/useNWCContext';
|
|||||||
import type { NWCConnection } from '@/hooks/useNWC';
|
import type { NWCConnection } from '@/hooks/useNWC';
|
||||||
import { nip57 } from 'nostr-tools';
|
import { nip57 } from 'nostr-tools';
|
||||||
import type { Event } from 'nostr-tools';
|
import type { Event } from 'nostr-tools';
|
||||||
import type { WebLNProvider } from 'webln';
|
import type { WebLNProvider } from '@webbtc/webln-types';
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
import { useNostr } from '@nostrify/react';
|
import { useNostr } from '@nostrify/react';
|
||||||
import type { NostrEvent } from '@nostrify/nostrify';
|
import type { NostrEvent } from '@nostrify/nostrify';
|
||||||
@@ -266,7 +266,19 @@ export function useZaps(
|
|||||||
|
|
||||||
if (webln) { // Try WebLN next
|
if (webln) { // Try WebLN next
|
||||||
try {
|
try {
|
||||||
await webln.sendPayment(newInvoice);
|
// For native WebLN, we may need to enable it first
|
||||||
|
let webLnProvider = webln;
|
||||||
|
if (webln.enable && typeof webln.enable === 'function') {
|
||||||
|
const enabledProvider = await webln.enable();
|
||||||
|
// Some implementations return the provider, others return void
|
||||||
|
// Cast to WebLNProvider to handle both cases
|
||||||
|
const provider = enabledProvider as WebLNProvider | undefined;
|
||||||
|
if (provider) {
|
||||||
|
webLnProvider = provider;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await webLnProvider.sendPayment(newInvoice);
|
||||||
|
|
||||||
// Clear states immediately on success
|
// Clear states immediately on success
|
||||||
setIsZapping(false);
|
setIsZapping(false);
|
||||||
@@ -283,7 +295,7 @@ export function useZaps(
|
|||||||
// Close dialog last to ensure clean state
|
// Close dialog last to ensure clean state
|
||||||
onZapSuccess?.();
|
onZapSuccess?.();
|
||||||
} catch (weblnError) {
|
} catch (weblnError) {
|
||||||
console.error('webln payment failed, falling back:', weblnError);
|
console.error('WebLN payment failed, falling back:', weblnError);
|
||||||
|
|
||||||
// Show specific WebLN error to user for debugging
|
// Show specific WebLN error to user for debugging
|
||||||
const errorMessage = weblnError instanceof Error ? weblnError.message : 'Unknown WebLN error';
|
const errorMessage = weblnError instanceof Error ? weblnError.message : 'Unknown WebLN error';
|
||||||
|
|||||||
Reference in new issue
Block a user