)
}
```
--------------------------------
### Environment Configuration for NOWPayments API Keys
Source: https://github.com/hanslove/nowpayments-components/blob/main/docs/examples/basic-integration.mdx
Configures public and private API keys for NOWPayments using a .env.local file. NEXT_PUBLIC_NOWPAYMENTS_API_KEY is for public currency fetching, while NOWPAYMENTS_API_KEY is for private payment processing.
```bash
# NOWPayments API Key (public - for currency fetching only)
NEXT_PUBLIC_NOWPAYMENTS_API_KEY=your-public-api-key
# NOWPayments API Key (private - for payment processing)
NOWPAYMENTS_API_KEY=your-private-api-key
```
--------------------------------
### Backend Withdrawal Request Data
Source: https://github.com/hanslove/nowpayments-components/blob/main/docs/components/withdraw-modal.mdx
Example of the data structure expected by the backend for processing a withdrawal request.
```javascript
{
currency: "usdttrc20",
amount: 100,
destinationAddress: "TYour1WalletAddress2Here..."
}
```
--------------------------------
### Validate Withdrawal Amount
Source: https://github.com/hanslove/nowpayments-components/blob/main/docs/components/withdraw-modal.mdx
Example of validating a withdrawal amount against available balance and minimum withdrawal limits before conversion.
```typescript
const convertToUsdt = async (amount: number) => {
if (amount > availableBalance) {
throw new Error('Amount exceeds available balance')
}
if (amount < minimumWithdraw) {
throw new Error(`Minimum withdrawal is ${minimumWithdraw}`)
}
return amount * exchangeRate
}
```
--------------------------------
### Initialize NowPaymentsProvider
Source: https://context7.com/hanslove/nowpayments-components/llms.txt
Wraps the application to provide the NOWPayments API key via React Context. Must be rendered as an ancestor of any modal or hook from this library. The apiKey is forwarded to NowPaymentsAPI for currency fetching.
```tsx
import { NowPaymentsProvider } from '@taloon/nowpayments-components'
import '@taloon/nowpayments-components/styles'
// Place at the root of your app or around the payment section only.
// The apiKey is forwarded to NowPaymentsAPI for currency fetching.
function App() {
return (
)
}
```
--------------------------------
### WithdrawFormData Currency Example
Source: https://github.com/hanslove/nowpayments-components/blob/main/docs/components/withdraw-modal.mdx
Illustrates the possible values for the `currency` field within the `WithdrawFormData` interface. This determines the network for the withdrawal.
```tsx
// The form data will contain the selected network
const formData = {
currency: 'usdttrc20', // or 'usdtmatic'
amount: 100,
destinationAddress: 'TXYZabc123...'
}
```
--------------------------------
### Troubleshooting: Styles Not Applied
Source: https://github.com/hanslove/nowpayments-components/blob/main/docs/styling-guide.mdx
If components appear unstyled, ensure the base styles are imported correctly. Add `import '@taloon/nowpayments-components/styles'` to your entry point.
```tsx
import '@taloon/nowpayments-components/styles' // ← Add this line
```
--------------------------------
### Instantiate NowPaymentsAPI Client
Source: https://context7.com/hanslove/nowpayments-components/llms.txt
Instantiate the NowPaymentsAPI client with your API key for direct integration. Use this for custom solutions outside of the modal components.
```typescript
import { NowPaymentsAPI } from '@taloon/nowpayments-components'
const api = new NowPaymentsAPI('YOUR_NOWPAYMENTS_API_KEY')
```
--------------------------------
### Configure NowPaymentsProvider
Source: https://github.com/hanslove/nowpayments-components/blob/main/docs/getting-started.mdx
Wrap your application with NowPaymentsProvider to configure the API key globally. This is the simplest way to set up the library.
```tsx
import { NowPaymentsProvider } from '@taloon/nowpayments-components'
import '@taloon/nowpayments-components/styles'
function App() {
return (
)
}
```
--------------------------------
### Get Enabled Currencies for Merchant
Source: https://context7.com/hanslove/nowpayments-components/llms.txt
Retrieve a list of currency codes that are enabled for the current merchant account. Useful for displaying available payment options.
```typescript
// 2. Get only the currencies enabled for this merchant account
const enabledResult = await api.getEnabledCurrencies()
if (enabledResult.success) {
console.log('Enabled codes:', enabledResult.data?.selectedCurrencies)
// e.g. ["btc", "eth", "usdttrc20", "sol"]
}
```
--------------------------------
### Vite Library Build Configuration
Source: https://github.com/hanslove/nowpayments-components/blob/main/progress.md
Configures Vite for building the library, specifying the entry point, library name, and formats. External dependencies like React are also listed.
```typescript
build: {
lib: {
entry: resolve(__dirname, 'src/index.ts'),
name: 'NowpaymentsComponents',
formats: ['es'],
},
rollupOptions: {
external: ['react', 'react-dom'],
},
}
```
--------------------------------
### Get Minimum Deposit Amount
Source: https://context7.com/hanslove/nowpayments-components/llms.txt
Fetch the minimum deposit amount for a specific currency, including its fiat equivalent. Handles potential errors during the API call.
```typescript
// 3. Get minimum deposit amount for a specific currency
const minResult = await api.getMinimumAmount('btc')
if (minResult.success && minResult.data) {
const { min_amount, fiat_equivalent } = minResult.data
console.log(`Minimum BTC deposit: ${min_amount} BTC (~$${fiat_equivalent} USD)`)
// min_amount: 0.0001, fiat_equivalent: "5.23"
} else {
console.error('getMinimumAmount failed:', minResult.error)
}
```
--------------------------------
### Basic Component Usage with Styles
Source: https://github.com/hanslove/nowpayments-components/blob/main/docs/styling-guide.mdx
Integrate NOWPayments components by importing them and the necessary styles within your application's provider.
```tsx
import { DepositModal, NowPaymentsProvider } from '@taloon/nowpayments-components'
import '@taloon/nowpayments-components/styles'
function App() {
return (
)
}
```
--------------------------------
### Theme Integration for ContinueWithNowPayments
Source: https://github.com/hanslove/nowpayments-components/blob/main/docs/components/continue-with-nowpayments.mdx
Shows how to integrate ContinueWithNowPayments styling with dark and light themes using CSS variables and attribute selectors.
```css
/* Dark theme support */
[data-theme="dark"] .np-continue-btn--default {
background: var(--np-surface-variant);
color: var(--np-on-surface);
}
/* Light theme support */
[data-theme="light"] .np-continue-btn--default {
background: #ffffff;
color: #1a1a1a;
border: 1px solid #e0e0e0;
}
```
--------------------------------
### Storybook Directory Structure
Source: https://github.com/hanslove/nowpayments-components/blob/main/src/stories/README.md
Overview of the file structure for Storybook stories within the project.
```bash
src/stories/
├── Introduction.mdx # Main introduction page
├── README.md # This file
├── caos-theme.css # Caos Engines inspired theme
├── CaosThemeDemo.stories.tsx # Theme demonstration stories
├── DepositModal/
│ ├── DepositModal.stories.tsx # All DepositModal variations
│ └── mocks.ts # Deposit-specific mock data
└── WithdrawModal/
├── WithdrawModal.stories.tsx # All WithdrawModal variations
└── mocks.ts # Withdraw-specific mock data
```
--------------------------------
### Custom Styling for Withdrawal Component
Source: https://github.com/hanslove/nowpayments-components/blob/main/docs/components/withdraw-modal.mdx
Provides CSS examples for customizing various elements of the withdrawal component, including network options, sliders, conversion displays, and payment status details.
```css
/* Customize network selection */
.nowpayments-network-option {
border: 1px solid var(--np-border);
border-radius: var(--np-radius);
}
.nowpayments-network-option:has(input:checked) {
border-color: var(--np-primary);
background: var(--np-surface-variant);
}
/* Style the amount slider */
input[type="range"] {
accent-color: var(--np-primary);
}
/* Customize USDT conversion display */
.conversion-display {
background: var(--np-surface-variant);
border-radius: var(--np-radius);
padding: var(--np-spacing-md);
}
/* Customize withdrawal details step */
.nowpayments-payment-status {
/* Status indicator styles */
}
.nowpayments-payment-info--compact {
/* Details display styles */
}
```
--------------------------------
### Import Components and Styles
Source: https://github.com/hanslove/nowpayments-components/blob/main/CSS_THEMING.md
Import the necessary components and global styles for the NowPayments components library.
```tsx
import { DepositModal } from '@taloon/nowpayments-components'
import '@taloon/nowpayments-components/styles'
```
--------------------------------
### Direct Store Configuration with API Key
Source: https://github.com/hanslove/nowpayments-components/blob/main/docs/getting-started.mdx
Configure the API key directly using the useNowPaymentsStore hook for more control. This is useful for setting the API key on app initialization.
```tsx
import { useEffect } from 'react'
import { useNowPaymentsStore } from '@taloon/nowpayments-components'
import '@taloon/nowpayments-components/styles'
function App() {
const store = useNowPaymentsStore()
// Configure on app initialization
useEffect(() => {
store.setApiKey('your-nowpayments-api-key')
}, [])
return
}
```
--------------------------------
### Use CSS Variables and Classes for Styling
Source: https://github.com/hanslove/nowpayments-components/blob/main/CLAUDE.md
Presents the recommended approach for styling components using CSS variables and BEM-based classes. This promotes consistency and maintainability.
```jsx
// Correct
```
--------------------------------
### WithdrawModal Integration Example
Source: https://context7.com/hanslove/nowpayments-components/llms.txt
Integrates the WithdrawModal component into a React application. It fetches user balance and exchange rates, and defines handlers for submission, success, and error states. Ensure API endpoints for balance and withdrawals are correctly configured.
```tsx
import {
useState,
useEffect
} from 'react'
import {
WithdrawModal,
USDTNetwork,
type WithdrawFormData,
type WithdrawalDetails,
} from '@taloon/nowpayments-components'
function WithdrawButton({ userId }: { userId: string }) {
const [open, setOpen] = useState(false)
const [balance, setBalance] = useState(0)
const [rate, setRate] = useState(1) // points-to-USDT exchange rate
useEffect(() => {
fetch(`/api/users/${userId}/balance`)
.then(r => r.json())
.then(data => setBalance(data.balance))
// Refresh rate every 30 s
const refreshRate = async () => {
const r = await fetch('/api/exchange-rates/usdt')
const d = await r.json()
setRate(d.rate)
}
refreshRate()
const interval = setInterval(refreshRate, 30_000)
return () => clearInterval(interval)
}, [userId])
const handleSubmit = async (formData: WithdrawFormData): Promise => {
// formData: { currency: string, amount: number, destinationAddress: string }
const response = await fetch('/api/withdrawals', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...formData, userId }),
})
if (!response.ok) throw new Error(`HTTP ${response.status}`)
return response.json()
// Expected backend response (example):
// { data: { id: "txn_def456", status: "pending", estimatedTime: "5-10 min" } }
}
const handleSuccess = (res: any): WithdrawalDetails => ({
transactionId: res.data?.id ?? res.withdrawalId ?? 'PENDING',
})
const handleError = (error: Error): string => {
if (error.message.includes('limit')) return 'Daily withdrawal limit reached.'
if (error.message.includes('insufficient')) return 'Insufficient balance.'
return 'Withdrawal failed. Please contact support.'
}
return (
<>
setOpen(false)}
availableBalance={balance}
balanceToUsdtConverter={async (amount) => amount * rate}
// Restrict to two networks; defaults are [USDTTRC20, USDTMATIC]
supportedNetworks={[
USDTNetwork.USDTTRC20,
USDTNetwork.USDTMATIC,
USDTNetwork.USDTBSC,
]}
showPoweredByNowpayments={false}
onSubmit={handleSubmit}
onSuccess={handleSuccess}
onError={handleError}
/>
>
)
}
```
--------------------------------
### Integrate ContinueWithNowPayments with Deposit Modal
Source: https://github.com/hanslove/nowpayments-components/blob/main/docs/components/continue-with-nowpayments.mdx
Shows how to use the ContinueWithNowPayments component to trigger a deposit modal, managing its visibility state.
```tsx
import { useState } from 'react'
import { ContinueWithNowPayments, DepositModal } from '@taloon/nowpayments-components'
function PaymentFlow() {
const [showDeposit, setShowDeposit] = useState(false)
return (