Skip to main content

Introduction to Contracts

Blue contracts are the foundation of dynamic, event-driven behavior in Blue documents. While the Blue language itself provides structure and content addressing, contracts bring documents to life by defining how they respond to events and interact with the world.

What Are Blue Contracts?

Blue contracts are components within documents that define:

  1. Event channels that documents listen to
  2. Processing rules determining how to handle events
  3. State transitions that update document content
  4. Operations that documents expose to the outside world

Unlike traditional smart contracts on blockchain platforms, Blue contracts don't require global consensus or a specific runtime environment. Instead, they focus on deterministic behavior that any compliant processor can verify independently.

Core Philosophy

Blue contracts are built on four key principles:

  • Event-Driven Architecture: Documents react to events from multiple sources
  • Deterministic Processing: Given the same inputs, deterministic contracts produce identical results across all processors
  • Channel-First Design: All interactions begin with channels
  • Composable Behavior: Contracts combine to create sophisticated applications

Core Components

1. Channels

Channels are the entry points for all events into a document:

contracts:
userTimeline:
type: Timeline Channel
account: alice@example.com

Every event that affects a document must enter through a channel. Channels can represent user timelines, document changes, REST API endpoints, or external systems.

2. Handlers

Handlers process events from channels and execute business logic:

contracts:
paymentHandler:
type: Sequential Workflow
channel: paymentEvents
steps:
- name: Verify Amount
# Step details...

The most common handler is the Sequential Workflow, which executes a series of steps in response to events.

3. Additional Contract Types

Beyond channels and handlers, Blue supports other specialized contracts:

contracts:
schemaValidator:
type: Schema Validator
amount:
minimum: 0
maximum: 1000000

These contracts serve specific purposes like validating document content, defining operations that others can invoke, or specifying how processors should handle the document. Each contract type focuses on a particular aspect of document behavior.

Hierarchical Processing

Blue documents can contain nested nodes with their own contracts:

name: Payment Agreement
status: pending
btcPayment:
type: BTC Payment
contracts:
btcChannel:
# BTC-specific contracts
contracts:
statusChannel:
# Parent document contracts

When processing such documents, the processor evaluates all contracts at all levels of the hierarchy, creating a composed system that respects all defined behaviors.

Document Processing Mechanics

The Blue processing model follows a single-event pattern:

  1. An event arrives at a document through a channel
  2. The processor identifies workflows listening to that channel
  3. Workflows execute their logic, potentially updating the document
  4. If updates occur, Document Update Channels may trigger additional processing
  5. Workflows may also emit new events, causing further processing
  6. This cycle continues until the document reaches a stable state
  7. The processor returns the final updated document and any triggered events

This approach ensures that all compliant processors will reach exactly the same final state, given the same inputs. The deterministic nature of this processing is fundamental to Blue's trust model - allowing independent verification without requiring global consensus.

A critical aspect of this model is maintaining consistent event ordering when processing events from multiple channels, and ensuring that all processors reference the same external reality. For example, when processors handle events from external systems like cryptocurrency transactions or sports results, they must agree on the canonical source of truth. Blue addresses these challenges through channel coordination patterns and specialization mechanisms, which we'll explore in detail in the "Channel-Based Event Model" section.

Comparison to Traditional Smart Contracts

FeatureBlue ContractsBlockchain Smart Contracts
Execution EnvironmentAny Blue processorSpecific blockchain VM
Consensus MechanismIndependent verificationGlobal network consensus
State StorageDocument-centricGlobal ledger
Integration ApproachMultiple channelsLimited oracle integrations
Privacy ModelFlexible, document-specificPublic by default
Scripting CapabilitiesJavaScript and morePlatform-specific language
Reality ModelMultiple verified perspectivesSingle global state

Blue's approach mirrors real-world reasoning - individuals independently observe events, apply shared rules, and reach compatible conclusions without central coordination. Unlike blockchain's enforced global consensus, Blue enables multiple valid perspectives while maintaining verification through clear rules and shared evidence. This provides flexibility without sacrificing trust, allowing systems to model reality more naturally.

A Minimal Example

Here's a complete working example of a Blue document with contracts:

name: Simple Counter
counter: 0
contracts:
# Define a channel for events
incrementChannel:
type: Timeline Channel
account: user@example.com

# Define a workflow for those events
counterWorkflow:
type: Sequential Workflow
channel: incrementChannel
steps:
- name: Increment Counter
type: Update Document
changeset:
- op: replace
path: /counter
val: ${document('/counter') + 1}

This document listens to a timeline and increments a counter each time an event arrives.

Processing Example

Here's how this document would be processed in Java:

// Parse the document
Blue blue = new Blue(nodeProvider);
Node doc = blue.yamlToNode(yaml);

// Create a processor for the document
DocumentProcessor processor = blue.processor(doc);

// Process an incoming event
ProcessingResult result = processor.processEvent(timelineEvent);

// Get the updated document and triggered events
Node updatedDoc = result.getUpdatedDocument();
List<Node> triggeredEvents = result.getTriggeredEvents();

// The counter is now incremented
// updatedDoc will have counter = 1

We can also convert the Blue document to a Java object:

// Define a Java class representing the document
@Data
public class SimpleCounter {
private int counter;
}

// Convert the updated document to a Java object
SimpleCounter simpleCounter = blue.nodeToObject(updatedDoc, SimpleCounter.class);

// Access the counter property
assert simpleCounter.getCounter() == 1;

This example demonstrates the complete lifecycle of contract processing:

  1. An event arrives through the incrementChannel
  2. The counterWorkflow processes the event
  3. The document is updated with counter incremented
  4. The processor returns the updated document
  5. The document can be mapped to Java objects for easier manipulation

Each processor following the Blue contract specification will reach identical results when processing the same events in the same order.