@loosechain/delta-bundle-builder
v0.1.0
Published
Universal bundle builder for Loosechain Delta Engine - transforms DataSpec arrays into DeltaBundle objects
Maintainers
Readme
@loosechain/delta-bundle-builder
Universal bundle builder for Loosechain Delta Engine. Transforms DataSpec[] arrays into valid DeltaBundle objects for verification.
Features
- ✅ Fluent API - Ergonomic method chaining for bundle construction
- ✅ Type-Safe - Full TypeScript support with strict validation
- ✅ Domain-Agnostic - Works with any adapter type (market, code, price, etc.)
- ✅ Validation - Comprehensive bundle validation before submission
- ✅ Flexible - Supports both pre-fetched data and adapter execution
- ✅ Well-Tested - >90% test coverage
Installation
npm install @loosechain/delta-bundle-builder @loosechain/collection-core @loosechain/delta-engine-coreQuick Start
import { BundleBuilder } from '@loosechain/delta-bundle-builder';
// Using fluent API
const bundle = await new BundleBuilder()
.claim("Market trend is rising")
.threshold(0.05)
.addSourceData(dataSpecs)
.build();
// Using helper functions
import { createBundleFromSpecs } from '@loosechain/delta-bundle-builder';
const bundle = await createBundleFromSpecs(
"Verify price increase",
0.05,
[spec1, spec2, spec3]
);API Reference
BundleBuilder Class
claim(description: string): this
Sets the verification claim for the bundle.
builder.claim("Widget price increased by 10%");threshold(pct: number): this
Sets the convergence threshold (must be between 0 and 1).
builder.threshold(0.05); // 5% thresholdaddSourceData(specs: DataSpec[]): this
Adds pre-fetched DataSpec objects to the bundle.
builder.addSourceData([spec1, spec2, spec3]);addAdapter(adapter: BaseAdapter, query: AdapterQuery): this
Adds an adapter to be executed at build time.
builder.addAdapter(trendsAdapter, { keyword: "AI" });build(): Promise<DeltaBundle>
Builds and validates the bundle. Executes any pending adapters.
const bundle = await builder.build();validate(): BundleValidationResult
Validates the current builder state without building.
const result = builder.validate();
if (!result.valid) {
console.error('Validation errors:', result.errors);
}reset(): this
Resets the builder to initial state for reuse.
builder.reset();Helper Functions
createBundleFromSpecs(claim, threshold, specs): Promise<DeltaBundle>
Quick helper for creating bundles from pre-fetched data.
const bundle = await createBundleFromSpecs(
"Test claim",
0.05,
[spec1, spec2]
);createBundleFromAdapters(claim, threshold,adapters): Promise<DeltaBundle>
Creates a bundle by executing adapters.
const bundle = await createBundleFromAdapters(
"Price verification",
0.05,
[
{ adapter: adapter1, query: { source: "api1.com" } },
{ adapter: adapter2, query: { source: "api2.com" } }
]
);createMinimalBundle(claim, specs): Promise<DeltaBundle>
Creates a bundle with default threshold (0.05).
const bundle = await createMinimalBundle("Test claim", [spec1, spec2]);Validation Functions
validateBundle(bundle): BundleValidationResult
Validates a bundle and returns detailed results.
const result = validateBundle(myBundle);
if (!result.valid) {
console.error('Errors:', result.errors);
console.warn('Warnings:', result.warnings);
}assertValidBundle(bundle): asserts bundle is DeltaBundle
Validates and throws if invalid.
try {
assertValidBundle(myBundle);
// Bundle is valid
} catch (error) {
console.error('Invalid bundle:', error.message);
}isValidBundle(bundle): bundle is DeltaBundle
Type guard for boolean validation.
if (isValidBundle(bundle)) {
// TypeScript knows bundle is DeltaBundle
console.log(bundle.claim);
}Examples
Basic Usage
import { BundleBuilder } from '@loosechain/delta-bundle-builder';
import type { DataSpec } from '@loosechain/collection-core';
const specs: DataSpec[] = [
// ... your data specs
];
const bundle = await new BundleBuilder()
.claim("Verify market consensus")
.threshold(0.05)
.addSourceData(specs)
.build();
console.log('Bundle created:', bundle);With Adapters
import { BundleBuilder } from '@loosechain/delta-bundle-builder';
import { GoogleTrendsAdapter } from '@loosechain/collection-adapters-api';
const trendsAdapter = new GoogleTrendsAdapter();
const bundle = await new BundleBuilder()
.claim("AI interest is rising")
.threshold(0.05)
.addAdapter(trendsAdapter, { keyword: "artificial intelligence" })
.build();Error Handling
import { BundleBuilder, isValidBundle } from '@loosechain/delta-bundle-builder';
try {
const bundle = await new BundleBuilder()
.claim("Test claim")
.threshold(0.05)
.addSourceData(specs)
.build();
if (isValidBundle(bundle)) {
// Submit to Delta Engine
const receipt = await deltaEngine.run(bundle);
}
} catch (error) {
console.error('Bundle creation failed:', error);
}Bundle Structure
The DeltaBundle structure conforms to Layer-1 contract:
interface DeltaBundle {
claim: string; // Verification claim
threshold: number; // Convergence threshold (0 < n < 1)
sourceData: DataSpec[]; // Array of DataSpec objects
metadata?: { // Optional metadata
createdAt?: string;
createdBy?: string;
bundleId?: string;
};
}Validation Rules
The bundle builder validates:
- Claim: Must be non-empty string
- Threshold: Must be number in range (0, 1)
- Source Data: Must have at least one DataSpec
- DataSpec Fields: All required fields present
- Metrics: Each DataSpec has metrics array
Warnings are issued for:
- Very low thresholds (< 0.01)
- High thresholds (> 0.25)
- Few sources (< 3)
- Empty metrics arrays
TypeScript Support
Full TypeScript definitions included:
import type {
DeltaBundle,
BundleBuilderOptions,
BundleValidationResult,
BundleValidationError,
BundleValidationWarning,
} from '@loosechain/delta-bundle-builder';Testing
The package includes comprehensive tests:
npm testCoverage: >90% across all files
License
UNLICENSED - Proprietary to Loosechain AI
Related Packages
@loosechain/collection-core- Adapter framework@loosechain/delta-engine-core- Delta Engine Layer-1@loosechain/collection-cli- CLI for bundle orchestration (Phase C.2)
