Getting Started Examples

Basic Agent Setup

import { Treeship } from '@treeship/sdk';

const treeship = new Treeship({
  apiKey: process.env.TREESHIP_API_KEY
});

// Create a simple agent
const agent = await treeship.agents.create({
  name: "HelloWorld",
  capabilities: ["text-generation"],
  description: "My first Treeship agent"
});

console.log(`Agent created: ${agent.id}`);

First Zero-Knowledge Proof

// Generate your first proof
const proof = await treeship.proofs.generate({
  proofType: 'performance',
  circuitType: 'zk-SNARK',
  
  publicInputs: {
    timestamp: Date.now(),
    modelVersion: 'v1.0'
  },
  
  privateInputs: {
    accuracy: 0.97,
    testResults: [0.96, 0.97, 0.98]
  },
  
  assertions: [
    'accuracy > 0.95'
  ]
});

// Verify the proof
const verification = await treeship.proofs.verify(proof.proofId);
console.log('Proof verified:', verification.isValid);

Real-World Use Cases

1. Medical AI Compliance

Create a medical AI agent with HIPAA compliance proofs:
// Medical AI with compliance
const medicalAgent = await treeship.agents.create({
  name: "DiagnosticAI",
  type: "medical",
  capabilities: ["image-analysis", "diagnosis-generation"],
  
  compliance: {
    frameworks: ["HIPAA", "FDA"],
    certifications: ["iso_13485", "soc2_type2"]
  }
});

// Generate compliance proof for patient data processing
const hipaaProof = await treeship.proofs.generate({
  proofType: 'compliance',
  
  publicInputs: {
    regulation: 'HIPAA',
    processingDate: new Date().toISOString(),
    dataType: 'medical_images'
  },
  
  privateInputs: {
    patientData: encryptedPatientData,
    diagnosticResults: results,
    accessLogs: auditLogs
  },
  
  assertions: [
    'minimum_necessary_standard_met',
    'patient_consent_obtained',
    'data_encrypted_at_rest',
    'access_properly_logged'
  ]
});

// Create attestation for medical device clearance
const fdaAttestation = await treeship.attestations.create({
  type: 'compliance',
  subject: {
    id: medicalAgent.id,
    type: 'agent'
  },
  claims: [
    {
      property: 'fda_510k_cleared',
      value: true,
      clearanceNumber: 'K123456789'
    },
    {
      property: 'diagnostic_accuracy',
      value: 0.97,
      operator: '>=',
      threshold: 0.95
    }
  ],
  evidence: {
    proofs: [hipaaProof.proofId],
    documents: [
      {
        type: 'fda_clearance_letter',
        hash: '0x...'
      }
    ]
  }
});

2. Financial Trading Bot

Build a compliant financial trading agent:
// Create trading agent with financial compliance
const tradingAgent = await treeship.agents.create({
  name: "AlgoTrader",
  type: "financial",
  capabilities: ["market-analysis", "risk-management", "order-execution"],
  
  compliance: {
    frameworks: ["SOX", "MiFID2", "AML"],
    jurisdiction: "US",
    riskProfile: "medium"
  }
});

// Generate proof of trading performance
const performanceProof = await treeship.proofs.generate({
  proofType: 'performance',
  
  publicInputs: {
    timeframe: '2024-Q1',
    assetClass: 'equities',
    benchmarkIndex: 'SP500'
  },
  
  privateInputs: {
    returns: [0.02, 0.015, -0.005, 0.025], // Daily returns
    sharpeRatio: 2.3,
    maxDrawdown: 0.03,
    tradingVolume: 50000000 // $50M
  },
  
  assertions: [
    'sharpe_ratio > 2.0',
    'max_drawdown < 0.05',
    'positive_alpha',
    'risk_controls_active'
  ]
});

// Generate compliance proof for SOX requirements
const soxProof = await treeship.proofs.generate({
  proofType: 'compliance',
  
  publicInputs: {
    regulation: 'SOX',
    auditPeriod: '2024-Q1'
  },
  
  privateInputs: {
    internalControls: controlsData,
    auditTrails: auditData,
    segregationOfDuties: roleData
  },
  
  assertions: [
    'internal_controls_effective',
    'audit_trail_complete',
    'segregation_of_duties_maintained',
    'financial_reporting_accurate'
  ]
});

// Create commerce transaction with proofs
const transaction = await treeship.commerce.createTransaction({
  type: 'equity_purchase',
  amount: 100000,
  currency: 'USD',
  
  from: { agentId: tradingAgent.id },
  to: { exchange: 'NYSE', symbol: 'AAPL' },
  
  compliance: {
    requiredProofs: [performanceProof.proofId, soxProof.proofId],
    frameworks: ['SOX', 'MiFID2']
  }
});

3. Supply Chain Verification

Track products through supply chain with privacy:
// Create supply chain agents
const suppliers = await Promise.all([
  treeship.agents.create({
    name: "RawMaterialSupplier",
    type: "supplier",
    capabilities: ["material-sourcing", "quality-testing"],
    compliance: { frameworks: ["ISO9001", "FairTrade"] }
  }),
  treeship.agents.create({
    name: "Manufacturer", 
    type: "manufacturer",
    capabilities: ["production", "quality-control"],
    compliance: { frameworks: ["ISO9001", "OSHA"] }
  }),
  treeship.agents.create({
    name: "Distributor",
    type: "distributor", 
    capabilities: ["logistics", "cold-chain"],
    compliance: { frameworks: ["HACCP", "GDP"] }
  })
]);

// Generate proof of ethical sourcing
const sourcingProof = await treeship.proofs.generate({
  proofType: 'compliance',
  
  publicInputs: {
    productId: 'PROD_001',
    standard: 'FairTrade',
    originCountry: 'Colombia'
  },
  
  privateInputs: {
    supplierAudits: auditResults,
    laborConditions: laborData,
    environmentalImpact: envData,
    paymentRecords: paymentData
  },
  
  assertions: [
    'fair_wages_paid',
    'safe_working_conditions',
    'no_child_labor',
    'environmental_standards_met'
  ]
});

// Create product attestation
const productAttestation = await treeship.attestations.create({
  type: 'credential',
  
  subject: {
    id: 'PROD_001',
    type: 'product'
  },
  
  claims: [
    {
      property: 'ethically_sourced',
      value: true,
      standard: 'FairTrade'
    },
    {
      property: 'quality_grade',
      value: 'A+',
      testDate: new Date().toISOString()
    }
  ],
  
  evidence: {
    proofs: [sourcingProof.proofId],
    witnessAgents: suppliers.map(s => s.id)
  }
});

// Track through supply chain
const supplyChainTx = await treeship.commerce.createTransaction({
  type: 'supply_chain_transfer',
  
  from: { agentId: suppliers[0].id },
  to: { agentId: suppliers[1].id },
  
  asset: {
    productId: 'PROD_001',
    quantity: 1000,
    unit: 'kg'
  },
  
  attestations: [productAttestation.attestationId],
  
  zkConfig: {
    hideCommercialTerms: true,
    provideIntegrityProof: true
  }
});

Machine Learning Integration

Scikit-learn Model Verification

// Note: This example shows the concept - actual ML integration 
// would typically be done in Python

// Create proof of model training process
const mlProof = await treeship.proofs.generate({
  proofType: 'performance',
  
  publicInputs: {
    modelType: 'RandomForest',
    datasetSize: 10000,
    featureCount: 50,
    trainingTime: '2024-01-15T10:00:00Z'
  },
  
  privateInputs: {
    // Hashed/encrypted training data
    trainingDataHash: '0x7d8f9e8a...',
    hyperparameters: {
      n_estimators: 100,
      max_depth: 10,
      random_state: 42
    },
    crossValidationScores: [0.96, 0.97, 0.95, 0.98, 0.96]
  },
  
  assertions: [
    'cv_mean_accuracy > 0.95',
    'cv_std_accuracy < 0.02',
    'no_data_leakage',
    'hyperparameters_valid'
  ]
});

// Create model attestation
const modelAttestation = await treeship.attestations.create({
  type: 'performance',
  
  subject: {
    id: 'model_rf_001',
    type: 'ml_model'
  },
  
  claims: [
    {
      property: 'accuracy',
      value: 0.96,
      operator: '>=',
      threshold: 0.95
    },
    {
      property: 'training_data_private',
      value: true
    }
  ],
  
  evidence: {
    proofs: [mlProof.proofId]
  }
});

TensorFlow Model Certification

import tensorflow as tf
from treeship.integrations.tensorflow import TensorFlowProofGenerator

# Create and train model
model = tf.keras.Sequential([
    tf.keras.layers.Dense(128, activation='relu', input_shape=(784,)),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(
    optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)

# Train with history tracking
history = model.fit(
    x_train, y_train,
    epochs=10,
    validation_data=(x_test, y_test),
    verbose=1
)

# Generate proof using Treeship TensorFlow integration
proof_generator = TensorFlowProofGenerator(treeship)

training_proof = proof_generator.create_training_proof(
    model=model,
    training_history=history,
    test_data=(x_test, y_test),
    
    privacy_config={
        'hide_weights': True,
        'hide_training_data': True,
        'provide_performance_metrics': True
    },
    
    assertions=[
        'final_accuracy > 0.95',
        'validation_accuracy > 0.90',
        'no_overfitting_detected',
        'training_stable'
    ]
)

# Create comprehensive model attestation
model_attestation = treeship.attestations.create(
    type='performance',
    
    subject={
        'id': f'tf_model_{model.name}',
        'type': 'neural_network',
        'metadata': {
            'framework': 'tensorflow',
            'architecture': 'feedforward',
            'parameters': model.count_params()
        }
    },
    
    claims=[
        {
            'property': 'test_accuracy',
            'value': float(history.history['val_accuracy'][-1]),
            'operator': '>=',
            'threshold': 0.95
        },
        {
            'property': 'model_size',
            'value': model.count_params(),
            'operator': '<',
            'threshold': 1000000  # Less than 1M parameters
        }
    ],
    
    evidence={
        'proofs': [training_proof.proof_id]
    }
)

Advanced Patterns

Multi-Party Verification

Create systems where multiple parties can verify without revealing private data:
// Multi-party verification scenario
class MultiPartyVerification {
  constructor(treeship) {
    this.treeship = treeship;
    this.parties = new Map();
  }
  
  async addParty(name, agent) {
    this.parties.set(name, agent);
  }
  
  async createConsortiumProof(sharedAssertion, privateData) {
    const proofs = [];
    
    // Each party generates their own proof
    for (const [name, agent] of this.parties) {
      const proof = await this.treeship.proofs.generate({
        proofType: 'consortium',
        
        publicInputs: {
          assertion: sharedAssertion,
          partyId: agent.id,
          timestamp: Date.now()
        },
        
        privateInputs: privateData[name],
        
        assertions: [sharedAssertion]
      });
      
      proofs.push({ party: name, proof });
    }
    
    // Aggregate proofs
    const aggregatedProof = await this.treeship.proofs.aggregate({
      proofs: proofs.map(p => p.proof.proofId),
      aggregationType: 'threshold',
      threshold: Math.ceil(this.parties.size * 0.67) // 2/3 majority
    });
    
    return aggregatedProof;
  }
}

// Usage
const consortium = new MultiPartyVerification(treeship);

await consortium.addParty('bank_a', bankAgentA);
await consortium.addParty('bank_b', bankAgentB);
await consortium.addParty('bank_c', bankAgentC);

const proof = await consortium.createConsortiumProof(
  'transaction_amount_within_limits',
  {
    'bank_a': { localTransaction: 100000, localLimits: 500000 },
    'bank_b': { localTransaction: 75000, localLimits: 300000 },
    'bank_c': { localTransaction: 125000, localLimits: 600000 }
  }
);

Attestation Marketplace

Build a marketplace for trading verified attestations:
class AttestationMarketplace {
  constructor(treeship) {
    this.treeship = treeship;
  }
  
  async listAttestation(attestationId, price, terms) {
    // Create marketplace listing
    const listing = await this.treeship.commerce.createListing({
      type: 'attestation_sale',
      attestationId,
      price,
      currency: 'USD',
      terms,
      
      // Privacy settings
      privacy: {
        hideSellerIdentity: true,
        provideVerificationOnly: true
      }
    });
    
    return listing;
  }
  
  async searchAttestations(criteria) {
    const results = await this.treeship.attestations.search({
      types: criteria.types,
      claims: criteria.requiredClaims,
      issuer_reputation: '>= 0.9',
      valid_only: true,
      
      // Marketplace filters
      for_sale: true,
      price_range: criteria.priceRange
    });
    
    // Verify each attestation
    const verifiedResults = [];
    for (const result of results) {
      const verification = await this.treeship.attestations.verify(
        result.attestationId
      );
      
      if (verification.isValid) {
        verifiedResults.push({
          ...result,
          verification,
          trustScore: verification.trustScore
        });
      }
    }
    
    return verifiedResults.sort((a, b) => b.trustScore - a.trustScore);
  }
  
  async purchaseAttestation(listingId, buyerAgentId) {
    // Create secure purchase transaction
    const transaction = await this.treeship.commerce.createTransaction({
      type: 'attestation_purchase',
      listingId,
      buyerAgentId,
      
      // Escrow settings
      escrow: {
        enabled: true,
        releaseConditions: [
          'attestation_verified',
          'buyer_confirms_receipt'
        ]
      }
    });
    
    return transaction;
  }
}

// Usage
const marketplace = new AttestationMarketplace(treeship);

// List an attestation for sale
await marketplace.listAttestation(
  'attest_performance_123',
  1000, // $1000
  {
    transferable: true,
    exclusiveUse: false,
    validityGuarantee: '1y'
  }
);

// Search and buy attestations
const results = await marketplace.searchAttestations({
  types: ['performance', 'capability'],
  requiredClaims: ['accuracy > 0.95'],
  priceRange: [100, 2000]
});

if (results.length > 0) {
  const purchase = await marketplace.purchaseAttestation(
    results[0].listingId,
    'buyer_agent_001'
  );
}

Testing Examples

Unit Testing with Mocks

// Jest testing example
import { Treeship } from '@treeship/sdk';
import { jest } from '@jest/globals';

// Mock the SDK
jest.mock('@treeship/sdk');

describe('Agent Management', () => {
  let treeship;
  
  beforeEach(() => {
    treeship = new Treeship({ apiKey: 'test-key' });
  });
  
  test('should create agent with correct parameters', async () => {
    const mockAgent = {
      id: 'agent_test_123',
      name: 'TestAgent',
      status: 'active'
    };
    
    treeship.agents.create.mockResolvedValue(mockAgent);
    
    const agent = await treeship.agents.create({
      name: 'TestAgent',
      capabilities: ['test-capability']
    });
    
    expect(agent.id).toBe('agent_test_123');
    expect(treeship.agents.create).toHaveBeenCalledWith({
      name: 'TestAgent',
      capabilities: ['test-capability']
    });
  });
  
  test('should handle agent creation errors', async () => {
    const error = new Error('API Error');
    treeship.agents.create.mockRejectedValue(error);
    
    await expect(
      treeship.agents.create({ name: 'InvalidAgent' })
    ).rejects.toThrow('API Error');
  });
});

Integration Testing

// Integration test with real API
describe('Treeship Integration Tests', () => {
  let treeship;
  const createdResources = [];
  
  beforeAll(() => {
    treeship = new Treeship({
      apiKey: process.env.TREESHIP_TEST_API_KEY,
      environment: 'sandbox'
    });
  });
  
  afterAll(async () => {
    // Cleanup created resources
    for (const resource of createdResources) {
      try {
        if (resource.type === 'agent') {
          await treeship.agents.delete(resource.id);
        }
      } catch (error) {
        console.warn(`Failed to cleanup ${resource.type} ${resource.id}:`, error);
      }
    }
  });
  
  test('end-to-end agent verification workflow', async () => {
    // Create agent
    const agent = await treeship.agents.create({
      name: 'IntegrationTestAgent',
      capabilities: ['test-capability'],
      compliance: { frameworks: ['TEST'] }
    });
    
    createdResources.push({ type: 'agent', id: agent.id });
    
    // Generate proof
    const proof = await treeship.proofs.generate({
      proofType: 'capability',
      publicInputs: { agentId: agent.id },
      privateInputs: { testData: [1, 2, 3] },
      assertions: ['agent_exists']
    });
    
    // Verify proof
    const verification = await treeship.proofs.verify(proof.proofId);
    expect(verification.isValid).toBe(true);
    
    // Create attestation
    const attestation = await treeship.attestations.create({
      type: 'capability',
      subject: { id: agent.id, type: 'agent' },
      claims: [{ property: 'test_capability', value: true }],
      evidence: { proofs: [proof.proofId] }
    });
    
    // Verify attestation
    const attVerification = await treeship.attestations.verify(
      attestation.attestationId
    );
    expect(attVerification.isValid).toBe(true);
  }, 30000); // 30 second timeout
});

Next Steps