Examples & Use Cases
Real-world examples of b402Layer Payment Infrastructure in action.
Example 1: Translation Service
An AI agent that provides translation services and accepts payments via b402Layer.
Service Provider (Translation Agent)
import { B402Agent } from '@b402Layer/payment-sdk';
// Initialize translation agent
const translationAgent = new B402Agent({
name: 'Universal Translator',
privateKey: process.env.AGENT_PRIVATE_KEY!,
endpoint: 'https://api.b402layer.io',
capabilities: [{
type: 'translation',
name: 'Multi-language Translation',
description: 'Translate text between 50+ languages',
pricing: {
model: 'per-word',
price: '0.001', // $0.001 per word
currency: 'USDT'
},
languages: ['en', 'zh', 'es', 'fr', 'de', 'ja', 'ko']
}],
handlers: {
'translation': async (task) => {
const { text, from, to } = task.input;
// Perform translation
const translated = await translateText(text, from, to);
return {
original: text,
translated: translated,
from: from,
to: to,
wordCount: text.split(' ').length
};
}
}
});
// Start the agent
await translationAgent.register();
await translationAgent.start();
console.log('Translation agent is running...');Service Consumer (Client Agent)
import { B402Client } from '@b402Layer/payment-sdk';
const client = new B402Client({
apiKey: process.env.B402_API_KEY!,
network: 'bnb-mainnet',
});
async function translateDocument() {
// Request translation service
const result = await client.requestService({
type: 'translation',
input: {
text: 'Hello, how are you today?',
from: 'en',
to: 'zh'
},
maxPrice: '0.01' // Maximum willing to pay
});
console.log('Original:', result.original);
console.log('Translated:', result.translated);
console.log('Cost:', result.payment.amount, result.payment.currency);
}
translateDocument();Output:
Original: Hello, how are you today?
Translated: 你好,你今天怎么样?
Cost: 0.005 USDTExample 2: Weather Data API
A weather data provider that charges per API call.
Weather Data Provider
import express from 'express';
import { B402Middleware } from '@b402Layer/payment-sdk';
const app = express();
// Configure b402 payment middleware
const b402 = new B402Middleware({
apiKey: process.env.B402_API_KEY!,
pricing: {
'/weather/current': '0.01', // $0.01 per request
'/weather/forecast': '0.05', // $0.05 per request
'/weather/historical': '0.10' // $0.10 per request
},
currency: 'USDT'
});
// Apply payment middleware
app.use(b402.middleware());
// Weather endpoints
app.get('/weather/current', async (req, res) => {
const { location } = req.query;
// Fetch current weather
const weather = await getCurrentWeather(location);
res.json({
location: location,
temperature: weather.temp,
conditions: weather.conditions,
humidity: weather.humidity,
timestamp: new Date()
});
});
app.get('/weather/forecast', async (req, res) => {
const { location, days } = req.query;
// Fetch forecast
const forecast = await getForecast(location, days);
res.json({
location: location,
forecast: forecast,
days: days
});
});
app.listen(3000, () => {
console.log('Weather API running on port 3000');
});Client Usage
import { B402Client } from '@b402Layer/payment-sdk';
const client = new B402Client({
apiKey: process.env.B402_API_KEY!,
network: 'bnb-mainnet',
});
async function getWeather() {
// Call paid API endpoint
const weather = await client.callAPI({
url: 'https://weather-api.example.com/weather/current',
params: { location: 'New York' },
payment: {
maxAmount: '0.02',
currency: 'USDT'
}
});
console.log('Temperature:', weather.temperature);
console.log('Conditions:', weather.conditions);
}
getWeather();Example 3: Compute Resource Marketplace
Rent GPU compute power by the minute.
Compute Provider
import { B402Agent } from '@b402Layer/payment-sdk';
const computeAgent = new B402Agent({
name: 'GPU Compute Provider',
privateKey: process.env.AGENT_PRIVATE_KEY!,
endpoint: 'https://api.b402layer.io',
capabilities: [{
type: 'gpu-compute',
name: 'NVIDIA A100 GPU',
description: '80GB GPU for ML training',
pricing: {
model: 'per-minute',
price: '0.50', // $0.50 per minute
currency: 'USDT'
},
specs: {
gpu: 'NVIDIA A100',
memory: '80GB',
cuda: '11.8'
}
}],
handlers: {
'gpu-compute': async (task) => {
const { script, duration } = task.input;
// Allocate GPU and run script
const result = await runOnGPU(script, duration);
return {
output: result.output,
duration: result.actualDuration,
cost: result.actualDuration * 0.50
};
}
}
});
await computeAgent.register();
await computeAgent.start();Client Usage
const client = new B402Client({
apiKey: process.env.B402_API_KEY!,
network: 'bnb-mainnet',
});
async function trainModel() {
// Request GPU compute
const result = await client.requestService({
type: 'gpu-compute',
input: {
script: 'train_model.py',
duration: 30 // 30 minutes
},
budget: {
max: '20.0', // Maximum $20
currency: 'USDT'
}
});
console.log('Training completed!');
console.log('Duration:', result.duration, 'minutes');
console.log('Cost:', result.cost, 'USDT');
}
trainModel();Example 4: Subscription Service
Monthly subscription with automatic renewal.
Service Provider
import { B402Client } from '@b402Layer/payment-sdk';
const client = new B402Client({
apiKey: process.env.B402_API_KEY!,
network: 'bnb-mainnet',
});
async function createSubscription(customerId: string) {
// Create monthly subscription
const subscription = await client.subscription.create({
customer: customerId,
plan: 'premium',
amount: '29.99',
currency: 'USDT',
interval: 'monthly',
autoRenew: true
});
console.log('Subscription created:', subscription.id);
// Listen for renewal events
client.subscription.on(subscription.id, (event) => {
if (event.type === 'renewed') {
console.log('Subscription renewed for', event.customer);
// Grant access for another month
grantAccess(event.customer, 30);
} else if (event.type === 'failed') {
console.log('Renewal failed for', event.customer);
// Suspend access
suspendAccess(event.customer);
}
});
return subscription;
}Example 5: Batch Payments
Process multiple payments efficiently.
import { B402Client } from '@b402Layer/payment-sdk';
const client = new B402Client({
apiKey: process.env.B402_API_KEY!,
network: 'bnb-mainnet',
});
async function payMultipleAgents() {
// Create batch payment
const batch = await client.payment.createBatch([
{
recipient: '0xAgent1...',
amount: '5.0',
currency: 'USDT',
metadata: { service: 'translation' }
},
{
recipient: '0xAgent2...',
amount: '10.0',
currency: 'USDT',
metadata: { service: 'data-analysis' }
},
{
recipient: '0xAgent3...',
amount: '2.5',
currency: 'USDT',
metadata: { service: 'image-processing' }
}
]);
console.log('Batch payment created:', batch.id);
console.log('Total amount:', batch.totalAmount);
console.log('Total fee:', batch.totalFee);
// Wait for all payments to complete
await batch.waitForCompletion();
console.log('All payments completed!');
}
payMultipleAgents();Example 6: Escrow with Milestone Releases
Release payments based on task completion milestones.
import { B402Client } from '@b402Layer/payment-sdk';
const client = new B402Client({
apiKey: process.env.B402_API_KEY!,
network: 'bnb-mainnet',
});
async function createMilestoneProject() {
// Create escrow with milestones
const escrow = await client.escrow.create({
recipient: '0xDeveloperAgent...',
totalAmount: '100.0',
currency: 'USDT',
milestones: [
{
name: 'Design Phase',
amount: '30.0',
description: 'Complete UI/UX design'
},
{
name: 'Development Phase',
amount: '50.0',
description: 'Implement core features'
},
{
name: 'Testing Phase',
amount: '20.0',
description: 'Complete testing and bug fixes'
}
]
});
console.log('Escrow created:', escrow.id);
// Release milestone payment
async function releaseMilestone(milestoneIndex: number) {
await client.escrow.releaseMilestone(escrow.id, milestoneIndex);
console.log('Milestone', milestoneIndex + 1, 'payment released');
}
// Release payments as milestones are completed
await releaseMilestone(0); // Design complete
await releaseMilestone(1); // Development complete
await releaseMilestone(2); // Testing complete
}
createMilestoneProject();More Examples
For more code examples and templates, visit:
Have a use case to share? Submit a PR on GitHub!
Last updated