
DartChain SDK: Advanced Features
DartChain SDK: Advanced Features
The DartChain SDK provides powerful tools for developers who need custom functionality beyond our visual workflow builder. Whether you're building custom components, integrating with proprietary systems, or creating entirely new workflow types, the SDK gives you the flexibility and power you need.
Why Use the SDK?
While DartChain's visual interface handles most automation needs, the SDK unlocks advanced capabilities:
- Custom Components: Build reusable workflow components for your team
- System Integrations: Connect to proprietary or legacy systems
- Advanced Logic: Implement complex business rules and algorithms
- Performance Optimization: Fine-tune critical workflows for maximum efficiency
- Enterprise Features: Add custom security, compliance, and governance layers
SDK Architecture Overview
The DartChain SDK is built on a plugin architecture that integrates seamlessly with our visual platform:
import { DartChainSDK, Component, Trigger, Action } from '@dartchain/sdk'
const sdk = new DartChainSDK({
apiKey: process.env.DARTCHAIN_API_KEY,
environment: 'production'
})
Core Concepts
Components
Reusable building blocks that encapsulate functionality:
@Component({
name: 'custom-data-processor',
version: '1.0.0',
description: 'Processes customer data with advanced analytics'
})
export class CustomDataProcessor {
@Input() customerData: CustomerData
@Output() processedData: ProcessedCustomerData
async execute() {
// Your custom logic here
return this.processData(this.customerData)
}
}
Triggers
Event sources that start workflows:
@Trigger({
name: 'webhook-trigger',
description: 'Responds to incoming webhook calls'
})
export class WebhookTrigger {
@Config() endpoint: string
@Config() authentication: AuthConfig
async setup() {
// Register webhook endpoint
return this.registerWebhook()
}
}
Actions
Operations that perform work within workflows:
@Action({
name: 'send-slack-message',
description: 'Sends formatted messages to Slack'
})
export class SlackAction {
@Input() message: string
@Input() channel: string
@Config() botToken: string
async execute() {
return this.slackClient.send(this.message, this.channel)
}
}
Advanced SDK Features
1. Custom Data Types
Define domain-specific data structures:
@DataType('CustomerProfile')
export interface CustomerProfile {
id: string
personalInfo: PersonalInfo
preferences: UserPreferences
analytics: AnalyticsData
}
@DataType('ProcessingResult')
export interface ProcessingResult {
score: number
recommendations: Recommendation[]
flags: SecurityFlag[]
}
2. State Management
Handle complex stateful operations:
@Component()
export class StatefulProcessor {
@State() private processingState: ProcessingState
async processChunk(data: DataChunk) {
this.processingState.update({
totalProcessed: this.processingState.totalProcessed + data.length,
lastProcessedAt: new Date()
})
return this.processData(data)
}
}
3. Error Handling and Retries
Implement sophisticated error handling:
@Component({
retryPolicy: {
maxAttempts: 3,
backoffStrategy: 'exponential',
retryableErrors: ['NETWORK_ERROR', 'RATE_LIMIT']
}
})
export class ResilientProcessor {
@ErrorHandler('NETWORK_ERROR')
async handleNetworkError(error: NetworkError) {
// Custom network error handling
await this.switchToBackupEndpoint()
return 'RETRY'
}
@ErrorHandler('RATE_LIMIT')
async handleRateLimit(error: RateLimitError) {
// Wait for rate limit reset
await this.delay(error.resetTime)
return 'RETRY'
}
}
4. Performance Optimization
Optimize critical workflows:
@Component({
caching: {
enabled: true,
ttl: 3600, // 1 hour
strategy: 'LRU'
},
parallelization: {
maxConcurrency: 10,
batchSize: 100
}
})
export class OptimizedProcessor {
@Cached()
async expensiveOperation(input: ComplexInput) {
// This result will be cached
return this.performComplexCalculation(input)
}
@Parallel()
async processBatch(items: Item[]) {
// Automatically parallelized
return items.map(item => this.processItem(item))
}
}
Real-World Use Cases
Custom CRM Integration
@Component('salesforce-sync')
export class SalesforceSync {
@Config() salesforceConfig: SalesforceConfig
@Input() customerUpdates: CustomerUpdate[]
async execute() {
const sfClient = new SalesforceClient(this.salesforceConfig)
const results = await Promise.allSettled(
this.customerUpdates.map(update =>
sfClient.updateContact(update.id, update.changes)
)
)
return this.aggregateResults(results)
}
}
Advanced Analytics Pipeline
@Component('ml-prediction')
export class MLPredictionComponent {
@Config() modelEndpoint: string
@Input() features: FeatureVector
@Output() prediction: PredictionResult
async execute() {
const prediction = await this.mlService.predict(
this.features,
{ model: 'customer-churn-v2' }
)
return {
score: prediction.score,
confidence: prediction.confidence,
factors: prediction.explanations
}
}
}
Custom Security Layer
@Component('security-scan')
export class SecurityScanComponent {
@Config() scannerConfig: SecurityConfig
@Input() payload: any
@Output() scanResult: SecurityScanResult
async execute() {
const scanners = [
new XSSScanner(),
new SQLInjectionScanner(),
new MalwareScanner()
]
const results = await Promise.all(
scanners.map(scanner => scanner.scan(this.payload))
)
return this.aggregateScanResults(results)
}
}
Testing SDK Components
Unit Testing
import { TestHarness } from '@dartchain/sdk-testing'
describe('CustomDataProcessor', () => {
let harness: TestHarness
let processor: CustomDataProcessor
beforeEach(() => {
harness = new TestHarness()
processor = harness.createComponent(CustomDataProcessor)
})
it('should process customer data correctly', async () => {
const inputData = harness.mockCustomerData()
const result = await processor.execute(inputData)
expect(result.score).toBeGreaterThan(0)
expect(result.recommendations).toHaveLength(3)
})
})
Integration Testing
import { WorkflowTestRunner } from '@dartchain/sdk-testing'
describe('Customer Onboarding Workflow', () => {
it('should complete full onboarding process', async () => {
const runner = new WorkflowTestRunner()
const result = await runner
.loadWorkflow('customer-onboarding')
.withInput('newCustomer', mockCustomerData)
.withMockComponent('email-service', mockEmailService)
.execute()
expect(result.status).toBe('completed')
expect(result.outputs.welcomeEmailSent).toBe(true)
})
})
Deployment and Distribution
Component Registry
Publish your components to share with your team:
# Build your component
npm run build
# Publish to DartChain registry
dartchain publish --component custom-data-processor
# Install in other projects
dartchain install custom-data-processor@1.0.0
Version Management
@Component({
name: 'data-processor',
version: '2.0.0',
compatibility: {
minSdkVersion: '1.5.0',
deprecatedIn: '3.0.0'
}
})
export class DataProcessorV2 {
// Implementation
}
Best Practices
1. Design for Reusability
- Keep components focused on single responsibilities
- Use configuration for flexibility
- Provide clear documentation and examples
2. Handle Errors Gracefully
- Use typed error classes
- Provide meaningful error messages
- Implement proper retry logic
3. Optimize Performance
- Use caching for expensive operations
- Implement proper batching
- Monitor resource usage
4. Security Considerations
- Validate all inputs
- Use secure credential management
- Implement proper access controls
Getting Started
Ready to build with the SDK? Here's what you need:
- Get SDK Access: Request access through your DartChain dashboard
- Review Documentation: Comprehensive guides at docs.dartchain.io/sdk
- Join Developer Community: Connect with other SDK developers
- Start Building: Use our starter templates to get up and running quickly
The DartChain SDK opens up limitless possibilities for customization and integration. Whether you're building simple utilities or complex enterprise integrations, the SDK provides the foundation you need to succeed.
Ready to get started? Request SDK access and begin building today!