Skip to main content
Developers build applications and services on top of Centrix. Integrate decentralized compute into your products using our SDKs and APIs.

Quick Start Guide

Get up and running in 5 minutes:
  1. Install SDK for your language
  2. Get API key from dashboard
  3. Submit your first task
  4. Monitor and retrieve results
Prerequisites:
  • Basic programming knowledge
  • Wallet with CXT tokens (testnet faucet available)
  • Docker knowledge (for custom tasks)

SDK Integration

Installation

# Node.js / JavaScript
npm install @centrix/sdk

# Python
pip install centrix-sdk

# Go
go get github.com/centrix/sdk-go

Basic Usage (JavaScript)

import { Centrix } from '@centrix/sdk';

// Initialize client
const centrix = new Centrix({
  apiKey: process.env.CENTRIX_API_KEY,
  network: 'mainnet'
});

// Submit task
const task = await centrix.tasks.submit({
  name: 'Process Data',
  container: 'centrix/python:3.11',
  command: ['python', '/app/process.py'],
  resources: {
    cpu: 4,
    memory: 8000,
    storage: 50
  },
  input: {
    files: ['data.csv']
  },
  pricing: {
    maxPrice: 10  // CXT
  }
});

// Monitor progress
task.on('started', () => console.log('Task started'));
task.on('progress', (pct) => console.log(`Progress: ${pct}%`));
task.on('completed', (results) => {
  console.log('Task completed!');
  console.log(results);
});

// Wait for completion
const results = await task.wait();
console.log(results);

Basic Usage (Python)

from centrix import Centrix

# Initialize client
centrix = Centrix(api_key='YOUR_API_KEY')

# Submit task
task = centrix.tasks.submit(
    name='ML Training',
    container='centrix/pytorch:latest',
    command=['python', '/app/train.py'],
    resources={
        'cpu': 8,
        'memory': 16000,
        'storage': 100,
        'gpu': 'NVIDIA RTX 3080'
    },
    input_files=['model.py', 'data.tar.gz'],
    max_price=50  # CXT
)

# Monitor and retrieve results
for status in task.monitor():
    print(f'Status: {status}')

results = task.get_results()
print(f'Output files: {results["files"]}')

Basic Usage (Go)

package main

import (
	"fmt"
	centrix "github.com/centrix/sdk-go"
)

func main() {
	// Initialize client
	client := centrix.NewClient(
		centrix.WithAPIKey("YOUR_API_KEY"),
		centrix.WithNetwork("mainnet"),
	)

	// Submit task
	task, err := client.Tasks.Submit(ctx, &centrix.TaskRequest{
		Name:      "Process Data",
		Container: "centrix/python:3.11",
		Command:   []string{"python", "/app/process.py"},
		Resources: &centrix.Resources{
			CPU:    4,
			Memory: 8000,
		},
		MaxPrice: centrix.NewBigInt(10),
	})
	if err != nil {
		panic(err)
	}

	// Wait for completion
	results, err := task.Wait(ctx)
	fmt.Println(results)
}

Advanced Features

Monitoring and Analytics

// Get task history
const history = await centrix.tasks.list({
  limit: 100,
  status: 'completed'
});

// Analyze costs
const analytics = await centrix.analytics.getCostBreakdown({
  period: '30d',
  groupBy: 'container'
});

// Monitor provider reputation
const provider = await centrix.providers.get(providerId);
console.log(`Reputation: ${provider.reputation.score}/5.0`);
console.log(`Success Rate: ${provider.reputation.successRate}%`);

Custom Verification

// Define custom verification
const task = await centrix.tasks.submit({
  // ... task config ...
  verification: {
    method: 'custom',
    function: async (result1, result2, result3) => {
      // Custom comparison logic
      return result1.hash === result2.hash && 
             result2.hash === result3.hash;
    }
  }
});

Webhooks for Async Processing

// Register webhook
await centrix.webhooks.create({
  url: 'https://myapi.example.com/centrix-callback',
  events: ['task.completed', 'task.failed'],
  secret: 'webhook_secret_key'
});

// Backend receives webhook
app.post('/centrix-callback', (req, res) => {
  const { event, task_id, results } = req.body;
  
  if (event === 'task.completed') {
    // Process completed task
    processResults(task_id, results);
  }
  
  res.status(200).json({ ok: true });
});

Batch Processing

// Submit multiple tasks efficiently
const tasks = await centrix.tasks.submitBatch([
  {
    name: 'Task 1',
    container: 'centrix/python:3.11',
    command: ['python', '/app/task1.py']
  },
  {
    name: 'Task 2',
    container: 'centrix/python:3.11',
    command: ['python', '/app/task2.py']
  },
  // ... more tasks
]);

// Wait for all to complete
const results = await Promise.all(
  tasks.map(t => t.wait())
);

Best Practices

Error Handling

Implement robust error recovery:
try {
  const task = await centrix.tasks.submit(taskConfig);
  const results = await task.wait();
} catch (error) {
  if (error.code === 'TIMEOUT') {
    // Handle timeout - retry with longer duration
    console.error('Task timed out, retrying...');
    await retryWithTimeout(taskConfig, timeout * 2);
  } else if (error.code === 'PROVIDER_FAILED') {
    // Provider reassignment already happened automatically
    console.error('Provider failed, automatic retry in progress');
  } else if (error.code === 'INSUFFICIENT_FUNDS') {
    // Alert user to add funds
    console.error('Insufficient CXT balance');
  } else {
    // Log unexpected errors
    console.error('Unexpected error:', error);
  }
}

Resource Optimization

Right-size your resource requests:
  • Start with conservative estimates
  • Monitor actual usage from analytics dashboard
  • Iterate based on real performance data
  • Use profiling tools to identify bottlenecks
Example optimization workflow:
// Initial conservative request
const initialTask = await centrix.tasks.submit({
  cpu: 8,
  memory: 16000,
  // ... other config
});

// After analyzing usage
const analytics = await centrix.analytics.getResourceUsage(initialTask.id);
console.log(`Actual CPU usage: ${analytics.cpuUsage}%`);
console.log(`Actual memory: ${analytics.memoryUsed}MB`);

// Optimize subsequent requests
const optimizedTask = await centrix.tasks.submit({
  cpu: Math.ceil(analytics.cpuUsage * 0.8), // 80% buffer
  memory: Math.ceil(analytics.memoryUsed * 1.2), // 20% buffer
  // ... other config
});

Best Practices Checklist

Use task templates when possible:
  • Pre-optimized for common workloads
  • Better performance and cost efficiency
  • Community-tested and verified
  • Quick start without configuration
Batch related tasks efficiently:
  • Combine multiple small tasks into batches
  • Reduced per-task coordination overhead
  • Better provider selection and pricing
  • Up to 20% cost savings

Security Best Practices

API Key Management:
// ❌ Bad - Never hardcode API keys
const centrix = new Centrix({ apiKey: 'abc123...' });

// ✅ Good - Use environment variables
const centrix = new Centrix({
  apiKey: process.env.CENTRIX_API_KEY
});
Result Verification:
// Always verify results before using in production
const result = await task.getResult();
if (!verifyResultIntegrity(result)) {
  throw new Error('Result verification failed');
}
Webhook Security:
app.post('/centrix-callback', (req, res) => {
  // Verify webhook signature
  if (!verifyWebhookSignature(req)) {
    return res.status(401).send('Unauthorized');
  }
  // Process verified webhook
  processTaskUpdate(req.body);
  res.status(200).json({ ok: true });
});

Testing Strategy

Local Testing:
# Test tasks locally before submitting to network
centrix task test ./my-task.yml --local

# Validate configuration
centrix task validate ./my-task.yml
Development Environment:
// Use testnet for development and testing
const centrix = new Centrix({
  apiKey: process.env.CENTRIX_API_KEY,
  network: 'testnet'  // Free testnet tokens available
});
Monitoring and Alerts:
// Set up event handlers for production monitoring
task.on('failed', (error) => {
  sendAlert('Critical: Task failed', {
    taskId: task.id,
    error: error.message
  });
});

task.on('timeout', () => {
  sendAlert('Warning: Task timeout', {
    taskId: task.id,
    duration: task.duration
  });
});

task.on('completed', (results) => {
  logMetrics('task_completed', {
    taskId: task.id,
    cost: results.cost,
    duration: results.duration
  });
});

Example Applications

Data Processing Pipeline

async function processLargeDataset(filename) {
  const task = await centrix.tasks.submit({
    name: `Process ${filename}`,
    container: 'centrix/python:3.11',
    command: ['python', '/app/process.py', filename],
    resources: { cpu: 16, memory: 32000 },
    input: { files: [filename] },
    output: { files: ['output.csv'] }
  });
  
  return task.wait();
}

Machine Learning Training

async function trainModel(dataPath, hyperparams) {
  const task = await centrix.tasks.submit({
    name: 'ML Training',
    container: 'centrix/pytorch:latest',
    command: [
      'python', '/app/train.py',
      `--data=${dataPath}`,
      `--hyperparams=${JSON.stringify(hyperparams)}`
    ],
    resources: { cpu: 8, memory: 16000, gpu: 'RTX 3080' },
    maxPrice: 100
  });
  
  const results = await task.wait();
  return results.model;
}

Rendering Pipeline

async function renderFrames(sceneFile, frameRange) {
  const task = await centrix.tasks.submit({
    name: `Render ${sceneFile}`,
    container: 'centrix/blender:4.0',
    command: [
      'blender', '-b', sceneFile,
      '-o', '/output/frame_####',
      '-f', frameRange
    ],
    resources: { cpu: 8, gpu: 'RTX 3080' },
    output: { files: ['/output/*.png'] }
  });
  
  return task.wait();
}

Resources and Support

Official Documentation: Community & Support: Additional Resources: