useVault Hook
TheuseVault hook provides deposit, withdraw, and transfer operations.
Basic Usage
Copy
import { useVault } from '@testinprod-io/privacy-boost-react';
function VaultOperations() {
const {
deposit,
withdraw,
send,
getBalance,
getAllBalances,
syncBalance,
syncAllBalances,
} = useVault();
// ...
}
Return Value
Copy
interface UseVaultResult {
// Operations (accept string or bigint for amounts)
deposit(params: SimpleDepositParams): Promise<DepositResult>;
withdraw(params: SimpleWithdrawParams): Promise<WithdrawResult>;
send(params: SimpleSendParams): Promise<TransactionResult>;
// Balance operations
getBalance(tokenAddress: string): Promise<bigint>;
getAllBalances(): Promise<TokenBalance[]>;
syncBalance(tokenAddress: Hex): Promise<void>;
syncAllBalances(): Promise<void>;
}
Deposit
Thedeposit method accepts string amounts for convenience:
Copy
const { deposit } = useVault();
// With string amount (auto-parsed using token decimals)
await deposit({
tokenAddress: '0x...',
amount: '1.5', // 1.5 tokens
});
// With bigint amount
await deposit({
tokenAddress: '0x...',
amount: 1500000000000000000n,
});
// With progress tracking
await deposit({
tokenAddress: '0x...',
amount: '1.0',
onProgress: ({ step, message, txHash }) => {
setStatus(message);
},
});
Deposit Parameters
Copy
interface SimpleDepositParams {
tokenAddress: Hex;
amount: string | bigint;
onProgress?: OnProgress;
}
Withdraw
Copy
const { withdraw } = useVault();
// Basic withdrawal
await withdraw({
tokenAddress: '0x...',
amount: '1.0',
recipientAddress: '0x...recipient',
});
// With ETH unwrap
await withdraw({
tokenAddress: WETH_ADDRESS,
amount: '1.0',
recipientAddress: '0x...',
unwrapWeth: true, // Receive ETH instead of WETH
});
// With progress tracking
await withdraw({
tokenAddress: '0x...',
amount: '1.0',
recipientAddress: '0x...',
onProgress: ({ step, message }) => {
setStatus(message);
},
});
Withdraw Parameters
Copy
interface SimpleWithdrawParams {
tokenAddress: Hex;
amount: string | bigint;
recipientAddress?: Hex; // Defaults to connected wallet
unwrapWeth?: boolean;
onProgress?: OnProgress;
}
Send (Private Transfer)
Copy
const { send } = useVault();
// Send to privacy address
await send({
to: '0x04...recipient-privacy-address',
tokenAddress: '0x...',
amount: '0.5',
});
Send Parameters
Copy
interface SimpleSendParams {
to: Hex | string; // Privacy address
tokenAddress: Hex;
amount: string | bigint;
}
Balance Operations
Copy
const { getBalance, getAllBalances, syncBalance, syncAllBalances } = useVault();
// Get single balance
const balance = await getBalance('0x...token');
// Get all balances
const balances = await getAllBalances();
// Sync from indexer
await syncBalance('0x...token');
await syncAllBalances();
Complete Example
Copy
import { useState } from 'react';
import { useVault, useAuth } from '@testinprod-io/privacy-boost-react';
function DepositForm({ tokenAddress }: { tokenAddress: string }) {
const { deposit } = useVault();
const { isAuthenticated } = useAuth();
const [amount, setAmount] = useState('');
const [status, setStatus] = useState('');
const [loading, setLoading] = useState(false);
const handleDeposit = async () => {
if (!isAuthenticated) {
alert('Please connect wallet first');
return;
}
setLoading(true);
setStatus('Starting deposit...');
try {
const result = await deposit({
tokenAddress,
amount,
onProgress: ({ step, message, txHash }) => {
setStatus(message);
if (txHash) {
console.log('Transaction:', txHash);
}
},
});
setStatus(`Deposit complete! Tx: ${result.txHash}`);
setAmount('');
} catch (error) {
if (error.code === 'WALLET_USER_REJECTED') {
setStatus('Cancelled');
} else if (error.code === 'INSUFFICIENT_BALANCE') {
setStatus('Insufficient balance');
} else {
setStatus(`Error: ${error.message}`);
}
} finally {
setLoading(false);
}
};
return (
<div>
<input
type="text"
value={amount}
onChange={(e) => setAmount(e.target.value)}
placeholder="Amount"
disabled={loading}
/>
<button onClick={handleDeposit} disabled={loading || !amount}>
{loading ? 'Processing...' : 'Deposit'}
</button>
{status && <p>{status}</p>}
</div>
);
}
Transfer Form Example
Copy
function TransferForm() {
const { send } = useVault();
const [recipient, setRecipient] = useState('');
const [amount, setAmount] = useState('');
const [loading, setLoading] = useState(false);
const handleSend = async () => {
setLoading(true);
try {
await send({
to: recipient,
tokenAddress: '0x...',
amount,
});
alert('Transfer successful!');
} catch (error) {
alert(`Transfer failed: ${error.message}`);
} finally {
setLoading(false);
}
};
return (
<form onSubmit={(e) => { e.preventDefault(); handleSend(); }}>
<input
value={recipient}
onChange={(e) => setRecipient(e.target.value)}
placeholder="Recipient privacy address"
/>
<input
value={amount}
onChange={(e) => setAmount(e.target.value)}
placeholder="Amount"
/>
<button type="submit" disabled={loading}>
{loading ? 'Sending...' : 'Send'}
</button>
</form>
);
}
Error Handling
Copy
try {
await deposit(params);
} catch (error) {
switch (error.code) {
case 'INSUFFICIENT_BALANCE':
showError('Not enough tokens');
break;
case 'WALLET_USER_REJECTED':
// User cancelled, no error needed
break;
case 'INVALID_AMOUNT':
showError('Invalid amount');
break;
default:
showError('Operation failed');
}
}