Integration Examples
Basic Settlement
A simple end-to-end flow: emit deltas, query balance, verify agreement.
This example walks through a complete settlement flow using PacSpace: record usage deltas, query the running balance, and verify that both parties agree on the total.
Prerequisites
- A PacSpace account with a provisioned environment
- An API key (see API Key Management)
Full Example
javascript
const API_BASE = 'https://balance-api.pacspace.io';
const API_KEY = process.env.PACSPACE_API_KEY; // pk_live_PUBLIC.SECRET
// Helper for API calls
async function pacspace(method, path, body = null) {
const options = {
method,
headers: {
'X-Api-Key': API_KEY,
'Content-Type': 'application/json'
}
};
if (body) options.body = JSON.stringify(body);
const response = await fetch(`${API_BASE}${path}`, options);
if (!response.ok) {
const error = await response.json();
throw new Error(`PacSpace error ${response.status}: ${error.message}`);
}
return response.json();
}
// Step 1: Record usage deltas
async function recordUsage(accountId, recordKey, amount, description) {
const result = await pacspace('POST', '/api/v1/writes', {
items: [
{
key: recordKey,
accountId: accountId,
bits: amount,
metadata: {
description,
timestamp: new Date().toISOString()
}
}
]
});
console.log(`Recorded: ${amount} for ${recordKey} → batch ${result.data.batchId}`);
return result.data;
}
// Step 2: Query the running balance
async function getBalance(recordKey) {
const result = await pacspace('GET', `/api/v1/reads/bucket/${recordKey}`);
console.log(`Balance for ${recordKey}: ${result.data.currentBits} (${result.data.totalWrites} writes)`);
return result.data;
}
// Step 3: Verify agreement between counterparties
async function verifyWithCounterparty(recordKey, expectedBalance) {
const record = await getBalance(recordKey);
if (!record.verified) {
console.log('Record not yet verified. Waiting for confirmation...');
return { agreed: false, reason: 'pending_verification' };
}
if (record.currentBits === expectedBalance) {
console.log(`Agreement confirmed: both parties agree on ${expectedBalance}`);
return { agreed: true, balance: record.currentBits };
} else {
console.log(`Discrepancy: PacSpace says ${record.currentBits}, expected ${expectedBalance}`);
return {
agreed: false,
reason: 'mismatch',
pacspaceBalance: record.currentBits,
expectedBalance
};
}
}
// --- Run the full flow ---
async function main() {
const ACCOUNT = 'customer-acme';
const RECORD_KEY = 'settlement-2025-06';
// Record three usage events
await recordUsage(ACCOUNT, RECORD_KEY, 100, 'API calls — week 1');
await recordUsage(ACCOUNT, RECORD_KEY, 250, 'API calls — week 2');
await recordUsage(ACCOUNT, RECORD_KEY, 150, 'API calls — week 3');
// Check the running balance
const balance = await getBalance(RECORD_KEY);
console.log(`Total usage recorded: ${balance.currentBits}`);
// Verify both parties agree
const localTotal = 100 + 250 + 150; // 500
const result = await verifyWithCounterparty(RECORD_KEY, localTotal);
if (result.agreed) {
console.log('Settlement complete. Generating invoice for', result.balance);
} else {
console.log('Settlement blocked:', result.reason);
}
}
main().catch(console.error);
What's Happening
-
Record usage — Three write operations record weekly API usage deltas for a customer. Each is queued and verified automatically.
-
Query balance — A read operation retrieves the accumulated total across all writes for that record key.
-
Verify agreement — Both parties (provider and customer) can independently read the same record key and confirm the total matches their local records.
Expected Output
Recorded: 100 for settlement-2025-06 → batch batch_abc001
Recorded: 250 for settlement-2025-06 → batch batch_abc002
Recorded: 150 for settlement-2025-06 → batch batch_abc003
Balance for settlement-2025-06: 500 (3 writes)
Total usage recorded: 500
Balance for settlement-2025-06: 500 (3 writes)
Agreement confirmed: both parties agree on 500
Settlement complete. Generating invoice for 500
Next Steps
- Add webhook listeners so you don't need to poll for verification status
- See Autonomous Settlement Agent for a more advanced flow with automatic discrepancy detection
- Review Error Handling for retry strategies
Was this page helpful?
Last updated February 11, 2026