import { createClient, PaymentRequiredError, X402Quote } from '@onchaindb/sdk';
const client = createClient({
endpoint: 'https://api.onchaindb.io',
appKey: 'your-app-key',
appId: 'your-app-id'
});
async function queryWithPayment() {
try {
// Query using QueryBuilder
const result = await client.queryBuilder()
.collection('premium_data')
.whereField('category').equals('exclusive')
.selectFields(['title', 'content', 'price'])
.limit(10)
.execute();
// No payment required - free query
console.log(`Received ${result.records.length} records`);
return result.records;
} catch (error) {
if (error instanceof PaymentRequiredError) {
const quote: X402Quote = error.quote;
console.log(`Payment required: ${quote.totalCostTia} TIA`);
console.log(`Pay to: ${quote.brokerAddress}`);
// Make payment using your wallet
const paymentTx = await wallet.sendTokens(
quote.brokerAddress,
`${quote.totalCostTia}tia`,
'OnchainDB Read Payment'
);
// Re-query with payment proof
const paidResult = await client.query({
collection: 'premium_data',
find: { category: { is: 'exclusive' } },
select: { title: true, content: true, price: true },
limit: 10,
quote_id: quote.quoteId,
payment_proof: paymentTx.transactionHash
});
console.log(`Received ${paidResult.records.length} records`);
return paidResult.records;
}
throw error;
}
}