Examples
Practical code examples for integrating DobProtocol into your application.
Read-Only: Display Pool Metrics
No authentication or API key needed for basic queries.
import { DobProtocolClient } from '@dobprotocol/sdk';
const dob = new DobProtocolClient({ network: 'mainnet' });
// Get public pools
const pools = await dob.pools.getPublicPools({ limit: 10 });
for (const pool of pools) {
console.log(`${pool.name} - ${pool.ticker}`);
console.log(` Participants: ${pool.quantity_participants}`);
console.log(` APR: ${pool.estimated_apr}%`);
}
External Site: Query with API Key
Use an API key to access the SDK from any domain.
import { DobProtocolClient } from '@dobprotocol/sdk';
const dob = new DobProtocolClient({
apiKey: process.env.DOB_SDK_KEY,
network: 'mainnet',
});
// Pool dashboard
async function getPoolDashboard(poolAddress: string) {
const pool = await dob.pools.getPool(poolAddress);
const stats = await dob.pools.getMarketplaceStats(poolAddress);
const listings = await dob.pools.getPoolListings(poolAddress);
return {
name: pool.name,
apr: pool.estimated_apr,
realApr: pool.real_apr,
participants: pool.quantity_participants,
totalDistributed: pool.total_distributed,
distributionPeriod: pool.distribution_period,
nextDistribution: pool.next_distribution,
performance: pool.performance_metrics?.performance_status,
marketplace: {
activeListings: stats.active_listings,
floorPrice: stats.floor_price,
totalVolume: stats.total_volume,
listings: listings.map(l => ({
seller: l.owner_address,
shares: l.shares_amount,
price: l.price_per_share,
})),
},
};
}
Create a Pool with Freighter
Full pool creation flow using Freighter wallet.
import { DobProtocolClient } from '@dobprotocol/sdk';
import { signTransaction, signMessage } from '@stellar/freighter-api';
const dob = new DobProtocolClient({
apiKey: process.env.DOB_SDK_KEY,
network: 'mainnet',
});
const userPublicKey = 'GBDM6KRX...';
// 1. Authenticate
const { message } = await dob.auth.getNonce(userPublicKey);
const sig = await signMessage(message);
await dob.auth.signIn({ wallet: userPublicKey, signature: sig, provider: 'freighter' });
// 2. Create pool
const result = await dob.pools.createPool({
userPublicKey,
poolConfig: {
name: 'Solar Panel Revenue',
ticker: 'SPR',
description: 'Revenue sharing from solar panel installations',
access: 'public',
joinMode: 'buy',
distributionType: 'trusted',
maxParticipants: 100,
estimatedApr: 15,
},
participants: [
{ address: userPublicKey, percentage: 70 },
{ address: 'GDJTUK3ER...', percentage: 30 },
],
signTransaction: async (xdr) => {
return await signTransaction(xdr, {
networkPassphrase: dob.networkPassphrase,
});
},
onStep: (step) => {
document.getElementById('status').textContent = step.message;
},
});
console.log('Pool created:', result.contractId);
Create a DobLink Widget
After creating a pool, embed it on your website.
// Create widget
const widget = await dob.widgets.create({
name: 'Solar Panel Widget',
pool_address: result.contractId,
theme: 'dark',
primary_color: '#22C55E',
button_text: 'Invest in Solar',
show_apr: true,
show_members: true,
allowed_domains: ['solarpanels.com', '*.solarpanels.com'],
});
console.log('Widget ID:', widget.widget_id);
// Embed URL: https://link.dobprotocol.com/embed/{widget.widget_id}
Track Widget Analytics
// Record a view (call from your embed page)
await dob.widgets.recordView(widget.widget_id, window.location.hostname);
// Get analytics (requires auth)
const analytics = await dob.widgets.getAnalytics(widget.widget_id, 30);
console.log('Last 30 days:');
console.log(` Total views: ${analytics.total_views}`);
console.log(' Daily views:', analytics.daily_views);
console.log(' Top referrers:', analytics.top_referrers);
Pool Actions: Deposit and Distribute
// Deposit tokens to pool
const { xdr: depositXdr } = await dob.pools.prepareDepositToken({
userPublicKey,
contractId: poolAddress,
tokenAddress: 'CDU3Q...', // fUSDC SAC address
amount: '10000000', // 1.0 fUSDC (7 decimals)
});
const signedDeposit = await signTransaction(depositXdr, {
networkPassphrase: dob.networkPassphrase,
});
await dob.pools.submitDepositToken(signedDeposit);
// Distribute to shareholders (admin only)
const { xdr: distXdr } = await dob.pools.prepareDistributeTokens({
userPublicKey,
contractId: poolAddress,
tokenAddress: 'CDU3Q...',
amount: '5000000',
});
const signedDist = await signTransaction(distXdr, {
networkPassphrase: dob.networkPassphrase,
});
await dob.pools.submitDistributeTokens(signedDist);
React Integration
import { useState, useEffect } from 'react';
import { DobProtocolClient, PoolMetrics } from '@dobprotocol/sdk';
const dob = new DobProtocolClient({
apiKey: process.env.NEXT_PUBLIC_DOB_KEY,
network: 'mainnet',
});
function PoolCard({ poolAddress }: { poolAddress: string }) {
const [pool, setPool] = useState<PoolMetrics | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
dob.pools.getPool(poolAddress)
.then(setPool)
.catch(console.error)
.finally(() => setLoading(false));
}, [poolAddress]);
if (loading) return <div>Loading...</div>;
if (!pool) return <div>Pool not found</div>;
return (
<div className="pool-card">
<h3>{pool.name} ({pool.ticker})</h3>
<p>APR: {pool.estimated_apr}%</p>
<p>Participants: {pool.quantity_participants}/{pool.max_participants}</p>
<p>Total Distributed: {pool.total_distributed}</p>
<p>Next Distribution: {
pool.next_distribution
? new Date(pool.next_distribution * 1000).toLocaleDateString()
: 'N/A'
}</p>
{pool.performance_metrics && (
<p>Status: {pool.performance_metrics.performance_status}</p>
)}
</div>
);
}
Node.js Server Integration
import express from 'express';
import { DobProtocolClient } from '@dobprotocol/sdk';
const app = express();
const dob = new DobProtocolClient({
apiKey: process.env.DOB_SDK_KEY,
network: 'mainnet',
});
// Proxy pool data through your own API
app.get('/api/pools', async (req, res) => {
try {
const pools = await dob.pools.getPublicPools({
limit: parseInt(req.query.limit as string) || 20,
page: parseInt(req.query.page as string) || 1,
});
res.json(pools);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.get('/api/pools/:address', async (req, res) => {
try {
const pool = await dob.pools.getPool(req.params.address);
res.json(pool);
} catch (err) {
res.status(err.statusCode || 500).json({ error: err.message });
}
});
app.listen(3000);
Error Handling Pattern
import {
DobProtocolError,
AuthenticationError,
NotFoundError,
TransactionError,
} from '@dobprotocol/sdk';
async function safePoolQuery(address: string) {
try {
return await dob.pools.getPool(address);
} catch (err) {
if (err instanceof NotFoundError) {
return null; // Pool doesn't exist
}
if (err instanceof AuthenticationError) {
// Redirect to login
window.location.href = '/login';
return null;
}
if (err instanceof DobProtocolError && err.statusCode === 429) {
// Rate limited -- wait and retry
const retryAfter = err.details?.retry_after || 5;
await new Promise(r => setTimeout(r, retryAfter * 1000));
return safePoolQuery(address);
}
throw err; // Unknown error
}
}