Skip to content

Instantly share code, notes, and snippets.

@scasplte2
Created August 7, 2025 14:18
Show Gist options
  • Save scasplte2/4797643944665308e61ac876f9f03f33 to your computer and use it in GitHub Desktop.
Save scasplte2/4797643944665308e61ac876f9f03f33 to your computer and use it in GitHub Desktop.
Tokenized event streams v1

Tokenized Event-Stream Protocol Documentation

00_introduction.md

Introduction

The Tokenized Event-Stream Protocol provides a verifiable, append-only system for modeling complex relationships and event streams in professional sports ecosystems. Built on a foundation of cryptographically-committed state and declarative policies, the protocol enables transparent, auditable interactions among athletes, teams, leagues, medical professionals, sponsors, fans, and autonomous agents.

Key Innovation

This protocol introduces a novel approach to multi-party coordination through:

  • Pairwise Agreements: All relationships are modeled as agreements between producer and validator participants
  • Tokenized Event Streams: Activities generate verifiable event streams that become tradeable assets
  • Policy-Driven State Machines: DFAs with JsonLogic guards control lifecycle transitions
  • Authenticated State Commitments: Merkle tries provide cryptographic proofs of all states
  • Producer-Validator Model: Clear separation between data generators and decision makers

Design Principles

  1. Append-Only History: Events are immutable; modifications create new events
  2. Composable Relationships: Complex n-to-n relationships built from pairwise agreements
  3. Declarative Policies: Business logic expressed as data, not code
  4. Universal Tokenization: Permissions, memberships, and data streams all become tokens
  5. Verifiable Computation: Every state transition can be independently validated
  6. Cryptographic Signatures: All data is signed at the source by producers

Core Flow

The protocol operates on a simple but powerful model:

  1. Agreements define relationships between participants (producers and validators)
  2. Activities generate streams of signed events from these agreements
  3. Tokens represent the accumulated state of event streams
  4. Policies govern how tokens can be created, modified, and transferred
  5. Tries commit the state for verification and proof generation

Target Use Cases

While designed for professional sports, the protocol generalizes to any domain requiring:

  • Multi-party data sharing with granular permissions
  • Auditable state transitions with compliance requirements
  • Time-bounded access rights with automatic expiration
  • Royalty distribution based on data usage
  • Delegation of authority with revocation capabilities
  • Fan engagement through verifiable digital collectibles

01_core_concepts.md

Core Concepts

Participants

The atomic actors in the system. Every participant has a unique identifier and belongs to one of four types:

  • USER: Individual human actors (athletes, coaches, doctors, fans)
  • ORG: Organizational actors (teams, leagues, associations, sponsors)
  • AGENT: Human/AI actor acting on behalf of users/orgs with authority to create proofs to satisfy agreements (non-interactive)
  • DELEGATE: Human/AI actor acting on behalf of users/orgs where authority to create proofs reside with the user/org (interactive)

Each participant can play different roles in different contexts:

  • As a producer: Generates and signs data (e.g., athlete generating performance data)
  • As a validator: Confirms data validity and has decision power (e.g., team validating athlete data)
  • As a consumer: Uses data under specific permissions (e.g., game developer using stats)

Agreements

Agreements represent the foundational relationships in the system. Each agreement is structured as:

  • Left Participants: The producers who generate and sign data
  • Right Participants: The validators who confirm data validity and governance

This producer-validator model ensures:

  • Clear ownership and accountability for data
  • Built-in validation mechanisms
  • Natural permission boundaries

Examples:

  • (athlete, athlete): Self agreement for personal data management
  • (athlete, team): Employment relationship where athlete produces, team validates
  • (team, league): Membership where team produces data for league validation
  • (fans[], team): Multiple fans as producers in a collective ownership model

Groups

Groups are collections of agreements sharing a common purpose and governance model. Each group has:

  • Owner Agreement: The agreement that created and manages the group
  • Member Agreements: Set of agreements participating in the group
  • Group Policy: Rules governing token behavior within the group

Groups enable:

  • Many-to-many relationships while maintaining pairwise clarity
  • Shared governance models
  • Collective data management
  • Hierarchical organization structures

Example: A "Team Roster" group might contain all athlete-team agreements for a specific season.

Series

Series represent specific activity types within a group. They provide context and specialization:

  • In a "Team Roster" group: "Training Camp", "Regular Season", "Playoffs"
  • In a "Fan Collectibles" group: "Game Highlights", "Player Cards", "Championship Moments"
  • In a "Medical Records" group: "Injury Reports", "Recovery Plans", "Performance Tests"

Each series can have additional policies that compose with the group policy.

Tokens

Tokens are the crystallized output of event streams. Unlike traditional tokens, these:

  • Represent accumulated state from a stream of signed events
  • Maintain a hash-chain reference to their generating events
  • Can have varying levels of fungibility based on policy
  • Track their current state in a lifecycle DFA

Key properties:

  • Quantity: Can represent counts, amounts, or unique identifiers
  • State: Current position in the lifecycle state machine
  • Parent Reference: Hash pointer to the generating event
  • Signature: Cryptographic proof from the producer

Events

Events are signed data points in an activity stream:

  • Generated by producer participants who sign the EventContent
  • Stored in the DAG with additional metadata
  • Immutable once created
  • Linked in a hash chain for provenance

Event structure:

  • EventContent: The immutable, signed portion containing activity data
  • SignedEventContent: EventContent + producer proofs (signatures)
  • Event: The full DAG node with signed content + metadata

Tokenization Process

When an event is created:

  1. Producer generates EventContent with activity data
  2. Producer signs creating SignedEventContent with proofs
  3. Event stored in DAG with content hash and metadata
  4. Agreement's DFA rules evaluate the event
  5. Tokens generated based on rule application
  6. Validator's role is encoded in the DFA rules, not signatures

This separation ensures:

  • Producers maintain control over their data
  • Validators govern through pre-agreed rules
  • Token generation is deterministic
  • No double-signing bottleneck

Policies

Policies control token behavior through multiple mechanisms:

Fungibility Rules

  • Whether tokens of the same type can be combined
  • Useful for differentiating unique collectibles from aggregatable stats

Quantity Rules

  • Allow Increase: Can create more than the original amount
  • Allow Decrease: Can destroy or reduce amounts
  • Conflict Resolution: When group and series policies conflict, XOR determines final rule

State Machines (DFA)

  • Define valid lifecycle transitions
  • Enforce business logic through state
  • Enable complex workflows

Guard Conditions (JsonLogic)

  • Declarative rules that must be satisfied
  • Can reference event data, state, and context
  • Evaluated at each transition

DAG (Directed Acyclic Graph)

The DAG provides the immutable backbone:

  • Append-only: No modifications, only additions
  • Hash-linked: Each node references its parents
  • Multi-dimensional: Tracks time, events, permissions, and relationships
  • Verifiable: Any path can be independently validated

Tries (Authenticated Data Structures)

Different tries serve different purposes:

Permissions Trie

  • Stores delegation tokens and access rights
  • Tracks who can act on behalf of whom
  • Enables revocable, time-bounded permissions

Relationships Trie

  • Maps agreements to groups
  • Tracks membership status
  • Maintains organizational hierarchies

Activities Trie

  • Indexes event streams by agreement and series
  • Provides efficient access to activity history
  • Enables activity-based queries

Assets Trie

  • Current token balances and states
  • Ownership records
  • Locked or restricted amounts

Group Trie

  • Shared state for group members
  • Canonical activity logs
  • Group-wide policies and rules

02_data_model.md

Data Model

This document provides the complete protobuf schema definitions for the protocol.

Core Types

syntax = "proto3";

package tokenstream.v1;

import "google/protobuf/timestamp.proto";
import "google/protobuf/struct.proto";

// Basic participant in the system
message Participant {
  string id = 1;  // Unique identifier (public key or DID)
  
  enum Type {
    TYPE_UNSPECIFIED = 0;
    USER = 1;
    ORG = 2;
    USER_AGENT = 3;
    ORG_AGENT = 4;
  }
  Type type = 2;
  
  string name = 3;
  bytes public_key = 4;  // For signature verification
  map<string, string> metadata = 5;  // Extensible attributes
}

// Agreement represents a pairwise relationship
message Agreement {
  string id = 1;  // Unique identifier
  
  // Producers: generate and sign data
  repeated Participant left = 2;
  
  // Validators: confirm and govern data  
  repeated Participant right = 3;
  
  google.protobuf.Timestamp created_at = 4;
  string agreement_type = 5;  // e.g., "employment", "membership", "self"
  
  // DFA rules for tokenization
  repeated string applicable_dfa_rules = 6;  // Which DFAs apply to events from this agreement
  
  map<string, string> metadata = 7;
}

// Group definition
message Group {
  string id = 1;
  string name = 2;
  string owner_agreement_id = 3;
  repeated string member_agreement_ids = 4;
  GroupPolicy policy = 5;
  google.protobuf.Timestamp created_at = 6;
  map<string, string> metadata = 7;
}

// Series within a group
message Series {
  string id = 1;
  string group_id = 2;
  string name = 3;
  SeriesPolicy policy = 4;
  google.protobuf.Timestamp created_at = 5;
  map<string, string> metadata = 6;
}

Policy Definitions

// DFA for state machine definition
message DFA {
  repeated State states = 1;
  string initial_state_id = 2;
  repeated Transition transitions = 3;
}

message State {
  string id = 1;
  string name = 2;
  bool is_terminal = 3;  // Cannot transition out
  bool is_accepting = 4;  // Valid end state
  map<string, string> metadata = 5;
}

message Transition {
  string id = 1;
  string from_state_id = 2;
  string to_state_id = 3;
  string event_type = 4;
  string json_logic_rule = 5;  // Guard condition
  map<string, string> metadata = 6;
}

// Policy structures with boolean array approach
message GroupPolicy {
  string id = 1;
  
  // Core boolean properties
  bool fungible = 2;
  bool allow_increase = 3;
  bool allow_decrease = 4;
  
  // State machine
  DFA dfa = 5;
  
  // Global validation rules
  string json_logic_validation = 6;
  
  map<string, string> metadata = 7;
}

message SeriesPolicy {
  string id = 1;
  
  // Series must specify all properties (no optionals)
  bool fungible = 2;
  bool allow_increase = 3;
  bool allow_decrease = 4;
  
  // Series-specific DFA (composes with group DFA)
  optional DFA dfa = 5;
  
  // Series validation rules
  string json_logic_validation = 6;
  
  map<string, string> metadata = 7;
}

// Token behavior is determined by the combination of booleans
// This creates 16 possible token types based on:
// [group_fungible, series_fungible, allow_increase, allow_decrease]
message TokenBehavior {
  bool group_fungible = 1;
  bool series_fungible = 2;
  bool allow_increase = 3;
  bool allow_decrease = 4;
  
  // Tokens can only interact if all four booleans match
  // This ensures clear, predictable behavior
}

Token and Event Structures

// Immutable content that gets signed by producer
message EventContent {
  string agreement_id = 1;  // Which agreement produced this
  string activity_type = 2;  // What kind of activity
  
  // Hash chain
  string parent_event_hash = 3;  // Previous event in stream
  
  // Ordering
  int64 ordinal = 4;  // Position in stream
  google.protobuf.Timestamp timestamp = 5;
  
  // State transition  
  string from_state_id = 6;
  string to_state_id = 7;
  
  // Data payload
  google.protobuf.Struct data = 8;  // The actual event data
  
  // Cross-references
  repeated string referenced_token_ids = 9;
}

// Signed wrapper (only producer includes proofs)
message SignedEventContent {
  EventContent content = 1;
  repeated Proof proofs = 2;  // Producer signatures/authorizations
}

// Event as stored in the DAG
message Event {
  string id = 1;
  
  // The signed content
  SignedEventContent signed_content = 2;
  
  // Hash of the signed content
  string content_hash = 3;
  
  // Additional metadata (not part of signed content)
  map<string, string> metadata = 4;
  
  // Validator confirmation (optional)
  string validator_agreement_id = 5;
  google.protobuf.Timestamp validated_at = 6;
  
  // Agreement's DFA rule is applied during tokenization
  // The validator doesn't sign the event, but the agreement's
  // DFA rules govern how events become tokens
}

// Token as crystallized event stream output
message Token {
  string id = 1;
  string group_id = 2;
  string series_id = 3;
  string owner_agreement_id = 4;
  
  // Current state
  int64 quantity = 5;
  string current_state_id = 6;
  
  // Token behavior (derived from group + series policies)
  TokenBehavior behavior = 7;
  
  // Reference to generating event
  string parent_event_content_hash = 8;  // Hash of EventContent
  string generation_event_id = 9;
  
  // Creation info
  google.protobuf.Timestamp created_at = 10;
  string created_by_agreement_id = 11;
  
  // DFA rule application result
  string applied_dfa_rule_id = 12;  // Which rule validated this token
  
  // For NFT-like tokens
  optional string unique_id = 13;  // For non-fungible tokens
  optional google.protobuf.Struct attributes = 14;  // NFT metadata
  
  map<string, string> metadata = 15;
}

Transaction Semantics

// Transaction update message
message TransactionUpdate {
  string method = 1;  // Method name to invoke
  google.protobuf.Struct parameters = 2;  // Method parameters
  repeated Proof proofs = 3;  // Signatures/authorizations
  
  // Sensitive data handling
  google.protobuf.Struct signed_sensitive_data = 4;
  bytes sensitive_data_signature = 5;
  
  map<string, string> metadata = 6;
}

// State representation (for Constellation metagraph)
message State {
  google.protobuf.Struct onchain = 1;  // Public state on metagraph
  google.protobuf.Struct calculated = 2;  // Derived state
  google.protobuf.Struct sensitive = 3;  // Encrypted/private state
  google.protobuf.Timestamp last_updated = 4;
}

// Generalized proof structure supporting multiple proof types
message Proof {
  string id = 1;
  
  enum ProofType {
    PROOF_TYPE_UNSPECIFIED = 0;
    SIGNATURE = 1;          // Cryptographic signature
    MERKLE_INCLUSION = 2;   // Merkle tree inclusion proof
    ZERO_KNOWLEDGE = 3;     // ZK proof
    THRESHOLD = 4;          // Threshold signature
    DELEGATION = 5;         // Delegation chain proof
    ORACLE = 6;             // External oracle attestation
  }
  ProofType type = 2;
  
  // Common fields
  string prover_id = 3;  // Who generated this proof
  google.protobuf.Timestamp timestamp = 4;
  
  // Type-specific proof data
  oneof proof_data {
    SignatureProof signature = 5;
    MerkleProof merkle = 6;
    ZKProof zk = 7;
    ThresholdProof threshold = 8;
    DelegationProof delegation = 9;
    OracleProof oracle = 10;
  }
  
  map<string, string> metadata = 11;
}

message SignatureProof {
  bytes signature = 1;
  string algorithm = 2;  // e.g., "ECDSA", "Ed25519"
  string public_key = 3;
}

message MerkleProof {
  repeated bytes path = 1;
  repeated bool directions = 2;  // left/right at each level
  bytes root = 3;
  bytes leaf = 4;
}

message DelegationProof {
  repeated string delegation_chain = 1;  // Chain of delegation tokens
  repeated Proof sub_proofs = 2;  // Proofs for each delegation
}

// Transaction result
message TransactionResult {
  bool success = 1;
  State new_state = 2;
  string error_message = 3;
  repeated Event generated_events = 4;
  repeated string new_trie_roots = 5;  // Updated merkle roots
}

DAG Node Types

// Base node in the DAG
message DAGNode {
  string id = 1;
  
  oneof node_type {
    AgreementNode agreement = 2;
    GroupNode group = 3;
    SeriesNode series = 4;
    TokenNode token = 5;
    EventNode event = 6;
    DelegationNode delegation = 7;
    MembershipNode membership = 8;
  }
  
  repeated string parent_ids = 9;  // References to parent nodes
  string hash = 10;  // Content hash
  google.protobuf.Timestamp created_at = 11;
  string created_by_agreement_id = 12;
  
  // Signature from creator
  bytes signature = 13;
  
  map<string, string> metadata = 14;
}

message AgreementNode {
  Agreement agreement = 1;
}

message GroupNode {
  Group group = 1;
}

message SeriesNode {
  Series series = 1;
}

message TokenNode {
  Token token = 1;
}

message EventNode {
  Event event = 1;
}

message DelegationNode {
  string delegator_agreement_id = 1;
  string delegate_agreement_id = 2;
  repeated string permissions = 3;
  google.protobuf.Timestamp expires_at = 4;
  bool revoked = 5;
  string delegation_token_id = 6;  // Reference to delegation token
}

message MembershipNode {
  string agreement_id = 1;
  string group_id = 2;
  string membership_token_id = 3;
  bool active = 4;
}

Trie Structures

// Trie root commitment
message TrieRoot {
  string agreement_id = 1;  // Which agreement's view
  
  enum TrieType {
    TRIE_TYPE_UNSPECIFIED = 0;
    PERMISSIONS = 1;
    RELATIONSHIPS = 2;
    ACTIVITIES = 3;
    ASSETS = 4;
    GROUP = 5;
  }
  TrieType type = 2;
  
  string root_hash = 3;
  int64 block_height = 4;
  google.protobuf.Timestamp timestamp = 5;
  
  // Constellation metagraph snapshot reference
  string metagraph_snapshot_ordinal = 6;
}

// Account state (collection of trie roots)
message AccountState {
  string agreement_id = 1;
  repeated TrieRoot trie_roots = 2;
  int64 nonce = 3;
  google.protobuf.Timestamp last_updated = 4;
  
  // Metagraph state reference
  string metagraph_address = 5;
}

03_transaction_semantics.md

Transaction Semantics

The protocol uses a functional approach to state transitions based on the pattern:

(update, state) => state'

Where:

  • update: The requested change (method + parameters + signed data)
  • state: Current state (onchain + calculated + sensitive)
  • state': New state after validation and combination

State Model

State is divided into three components:

Onchain State

  • Publicly visible on Constellation metagraph
  • Committed to blockchain for verification
  • Examples: token ownership, public achievements, roster status

Calculated State

  • Derived from onchain state and events
  • Maintained by metagraph for efficiency
  • Examples: aggregated statistics, rankings, totals

Sensitive State

  • Encrypted or private information
  • Signed by producer, verified by validator
  • Examples: detailed medical data, personal performance metrics

Client-Signed Data Flow

The protocol ensures data authenticity through client-side signing:

  1. Producer generates EventContent (e.g., athlete records performance)
  2. Producer signs EventContent creating SignedEventContent
  3. Signed content sent to application along with any metadata
  4. Application verifies producer signature against public key
  5. Application evaluates agreement's DFA rules to determine token generation
  6. New tokens created based on DFA state transitions
  7. Trie roots updated incorporating new tokens
  8. Metagraph transaction commits state changes

Producer-Validator Separation

The protocol separates concerns between producers and validators:

Producers (Left Participants)

  • Generate and sign data
  • Control what data is shared
  • Cannot forge data from others
  • Maintain data sovereignty

Validators (Right Participants)

  • Define DFA rules in agreements
  • Govern token generation logic
  • Set quality standards
  • Enable/disable tokenization

Example: Athlete Performance

// Agreement between athlete (producer) and team (validator)
agreement = {
  left: ["athlete_123"],  // Producer
  right: ["team_456"],    // Validator
  applicable_dfa_rules: [
    "dfa_performance_stats",     // Creates stats tokens
    "dfa_highlight_moments",     // Creates NFT moments
    "dfa_achievement_badges"     // Creates achievement tokens
  ]
}

// Athlete produces and signs performance data
eventContent = {
  agreement_id: "agreement_athlete_team",
  activity_type: "GAME_PERFORMANCE",
  data: { points: 30, assists: 10 }
}

// Team's DFA rules determine:
// - Whether this creates tokens
// - What types of tokens
// - Token attributes and states
// No team signature required on the event

Validation and Combination

Each transaction follows a two-phase process:

1. Validation Phase

{
  "validate_rule": {
    "and": [
      {"signature_valid": {"var": "producer_signature"}},
      {"authorized": {"var": "producer_agreement"}},
      {"dfa_allows": {"var": "proposed_transition"}},
      {"guard_satisfied": {"var": "json_logic_guard"}}
    ]
  }
}

2. Combination Phase

On validation success:

  • Apply state modifications
  • Generate new events
  • Update relevant tries
  • Create metagraph transaction

Policy Conflict Resolution

When group and series policies disagree on quantity rules:

// XOR Conflict Resolution
if (group_policy.conflict_resolution === "XOR") {
  const allow_increase = group_policy.allow_increase ^ series_policy.allow_increase;
  const allow_decrease = group_policy.allow_decrease ^ series_policy.allow_decrease;
}

This ensures clear, deterministic behavior when policies overlap.

Example: NBA TopShot-Style Collectible

Unlike simple token transfers, let's examine how digital collectibles work:

{
  "method": "mint_moment",
  "parameters": {
    "player_agreement_id": "agreement_lebron_lakers",
    "game_id": "2024_finals_game_5",
    "moment_type": "game_winning_shot",
    "rarity": "legendary",
    "max_supply": 100
  },
  "signed_data": {
    "video_hash": "ipfs://QmXoypiz...",
    "stats": {
      "points": 45,
      "time_remaining": "0.8s",
      "distance": "35ft"
    }
  },
  "producer_signature": "0x1234..."
}

Validation ensures:

  • Player agreement authorizes moment creation
  • Game data is authentic (signed by league)
  • Rarity rules are followed
  • Supply limits enforced

Cross-Group Transactions

When events reference tokens from other groups:

  1. Load referenced states from multiple tries
  2. Validate across all policies involved
  3. Atomic state updates to all affected tries
  4. Propagate events to relevant streams

Metagraph Integration

The Constellation metagraph provides:

  • Consensus on state transitions
  • Snapshot ordering for global consistency
  • L0 validation of signed data
  • Cross-chain interoperability

State updates flow:

Client → Signed Data → App Validation → Trie Updates → Metagraph Transaction → L0 Consensus

04_dag_and_tries.md

DAG and Authenticated Tries

The protocol uses complementary data structures for different purposes:

  • DAG: Captures relationships, events, and provenance
  • Tries: Enable efficient state queries and merkle proofs
  • Metagraph: Provides consensus and global ordering

DAG Structure

graph TD
    subgraph "Agreements Layer"
        A1[Athlete-Team Agreement]
        A2[Team-League Agreement]
        A3[Athlete-Sponsor Agreement]
    end
    
    subgraph "Groups Layer"
        G1[Team Roster Group]
        G2[League Stats Group]
        G3[Sponsorship Group]
    end
    
    subgraph "Events Layer"
        E1[Training Session]
        E2[Game Performance]
        E3[Injury Report]
        E4[Brand Activity]
    end
    
    subgraph "Tokens Layer"
        T1[Performance Token]
        T2[Collectible Moment]
        T3[Sponsorship Token]
    end
    
    A1 --> G1
    A2 --> G2
    A1 --> E1
    A1 --> E2
    A1 --> E3
    A3 --> E4
    
    E1 --> T1
    E2 --> T2
    E4 --> T3
    
    E2 -.->|references| E1
    E3 -.->|affects| T1
Loading

Hash Chain Structure

Events form hash chains within activity streams:

graph LR
    E1[Event 1<br/>hash: 0xabc] --> E2[Event 2<br/>parent: 0xabc<br/>hash: 0xdef]
    E2 --> E3[Event 3<br/>parent: 0xdef<br/>hash: 0x123]
    E3 --> T1[Token<br/>parent_event: 0x123]
Loading

Trie Organization

Agreement-Specific Tries

Each agreement maintains its own view through tries:

Permissions Trie

/delegations/outgoing/{delegate_id}/{permission} => DelegationToken
/delegations/incoming/{delegator_id}/{permission} => DelegationToken
/revocations/{delegation_id} => RevocationRecord

Used for:

  • Granting specific rights to other agreements
  • Tracking received permissions
  • Managing revocations

Relationships Trie

/agreements/{agreement_id} => AgreementDetails
/groups/{group_id}/membership => MembershipToken
/groups/{group_id}/role => Role

Used for:

  • Tracking which groups an agreement belongs to
  • Recording roles within groups
  • Maintaining relationship hierarchies

Activities Trie

/events/{group_id}/{series_id}/{ordinal} => EventHash
/streams/{activity_type}/latest => LatestEventHash
/streams/{activity_type}/count => EventCount

Used for:

  • Indexing events by activity type
  • Quick access to latest events
  • Activity statistics

Assets Trie

/tokens/{group_id}/{series_id}/{token_id} => TokenState
/balances/{group_id}/{series_id} => Balance
/locked/{group_id}/{series_id} => LockedAmount
/collectibles/{unique_id} => NFTToken

Used for:

  • Token ownership and state
  • Fungible token balances
  • Non-fungible collectibles
  • Locked or vesting amounts

Group-Level Tries

Groups maintain shared state visible to members:

Group Trie

/members/{agreement_id} => MembershipDetails
/policies/current => PolicyDefinition
/policies/history/{version} => HistoricalPolicy
/series/{series_id} => SeriesDefinition
/stats/aggregate => GroupStatistics

State Commitment Process

sequenceDiagram
    participant Producer
    participant App
    participant Tries
    participant Metagraph
    participant L0
    
    Producer->>Producer: Generate & Sign Data
    Producer->>App: Submit Signed Event
    App->>App: Verify Signature
    App->>App: Validate Rules
    App->>Tries: Update Relevant Tries
    Tries->>Tries: Calculate New Roots
    App->>Metagraph: Submit Transaction
    Metagraph->>L0: Consensus Round
    L0->>L0: Global Ordering
    L0-->>App: Confirmation
    App-->>Producer: Success Response
Loading

Multi-Dimensional Evolution

The DAG evolves along several dimensions simultaneously:

Time Dimension

  • Events ordered by timestamp and ordinal
  • Enables temporal queries and replay
  • Supports time-based policies

Event Dimension

  • Different event types create parallel streams
  • Each stream maintains its own hash chain
  • Cross-stream references create rich relationships

Permission Dimension

  • Delegations create a permission graph
  • Time-bounded edges expire automatically
  • Revocations prune permission paths

Relationship Dimension

  • Agreements join and leave groups
  • Hierarchical structures emerge
  • Role changes affect capabilities

Query Patterns

Current State Query

trie.get("/tokens/{group_id}/{series_id}/{token_id}")
  • Direct lookup at latest root
  • O(log n) complexity
  • Includes merkle proof

Historical Query

trie.at_height(block_height).get(path)
  • Reconstruct trie at any height
  • Verify against historical root
  • Useful for disputes and audits

Range Query

trie.range("/events/{group_id}/{series_id}/", start_ordinal, end_ordinal)
  • Retrieve event sequences
  • Supports pagination
  • Maintains order guarantees

Cross-Agreement Query

traverse_delegations(agreement_id, permission_type)
  • Follow delegation edges
  • Respect permission boundaries
  • Aggregate authorized data

05_policies_and_dfa.md

Policies and State Machines

Policies in the protocol combine multiple control mechanisms to govern token behavior throughout their lifecycle.

Policies and State Machines

Policies in the protocol use a boolean array approach that creates 16 distinct token behavior types.

The 16-Combination Model

Each token's behavior is determined by four boolean flags:

  1. Group Fungible: Whether tokens are fungible at the group level
  2. Series Fungible: Whether tokens are fungible at the series level
  3. Allow Increase: Whether quantity can increase from original
  4. Allow Decrease: Whether quantity can decrease from original

This creates a 4-bit identifier for each token type:

[group_fungible, series_fungible, allow_increase, allow_decrease]

Token Compatibility Rule

Tokens can only interact (transfer, combine, split) if all four booleans match exactly.

This ensures:

  • No ambiguity about token behavior
  • Clear rules for exchanges
  • Predictable outcomes
  • Type safety at the protocol level

Example Token Types

Type GF SF AI AD Use Case
0000 Unique, immutable certificates
0011 Unique items with variable quantity
1100 Fixed-supply fungible tokens
1111 Fully flexible fungible tokens
1010 Series-unique accumulator tokens
0101 Burnable series collectibles

Real-World Examples

Type 1111 (Fully Flexible)

  • Fan points that can be earned and spent
  • In-game currency
  • Loyalty rewards

Type 1100 (Fixed Supply Fungible)

  • Limited edition merchandise tokens
  • Season pass tokens
  • Governance tokens with fixed supply

Type 0000 (Fully Unique)

  • Achievement badges
  • Certificates of authenticity
  • Non-transferable credentials

Type 1010 (Accumulator)

  • Total career points (can only increase)
  • Games played counter
  • Experience points

Policy Composition

Since both group and series must specify all four booleans, composition is straightforward:

function determineTokenBehavior(groupPolicy, seriesPolicy) {
  return {
    group_fungible: groupPolicy.fungible,
    series_fungible: seriesPolicy.fungible,
    allow_increase: seriesPolicy.allow_increase,
    allow_decrease: seriesPolicy.allow_decrease
  };
}

// Tokens can interact only if behaviors match exactly
function canInteract(token1, token2) {
  return token1.behavior.group_fungible === token2.behavior.group_fungible &&
         token1.behavior.series_fungible === token2.behavior.series_fungible &&
         token1.behavior.allow_increase === token2.behavior.allow_increase &&
         token1.behavior.allow_decrease === token2.behavior.allow_decrease;
}

DFA Fundamentals

Each DFA consists of:

  • States: Named positions in lifecycle
  • Transitions: Allowed movements between states
  • Guards: JsonLogic conditions on transitions
  • Terminal States: No outbound transitions allowed
  • Accepting States: Valid endpoints for token lifecycle

Example: Digital Collectible DFA

stateDiagram-v2
    [*] --> MINTED: mint
    MINTED --> LISTED: list_for_sale
    LISTED --> MINTED: cancel_listing
    LISTED --> SOLD: purchase
    SOLD --> LISTED: relist
    SOLD --> SHOWCASED: showcase
    SHOWCASED --> SOLD: end_showcase
    SOLD --> BURNED: burn
    SHOWCASED --> BURNED: burn
    BURNED --> [*]
    
    note right of MINTED: Owned but not for sale
    note right of LISTED: Available on marketplace
    note right of SOLD: Transferred to new owner
    note right of SHOWCASED: Display in collection
    note left of BURNED: Permanently destroyed
Loading

JsonLogic Guard Examples

Rarity-Based Minting

{
  "if": [
    {"==": [{"var": "rarity"}, "legendary"]},
    {"<=": [{"var": "current_supply"}, 100]},
    {"<=": [{"var": "current_supply"}, 10000]}
  ]
}

Time-Limited Sales

{
  "and": [
    {">": [{"var": "current_time"}, {"var": "sale_start"}]},
    {"<": [{"var": "current_time"}, {"var": "sale_end"}]},
    {"has_permission": [{"var": "buyer"}, "purchase"]}
  ]
}

Multi-Signature Requirement

{
  ">=": [
    {"count": [
      {"filter": [
        {"var": "signatures"},
        {"valid_signature": {"var": ""}}
      ]}
    ]},
    {"var": "required_signatures"}
  ]
}

Policy Templates

1. Performance Statistics

  • Fungible: true
  • Allow increase: true
  • Allow decrease: false
  • DFA: Single state (ACTIVE)
  • Use case: Accumulating total points, assists, minutes played

Example: Total Time Played

{
  "group": "player_stats",
  "series": "2024_season",
  "fungible": true,
  "allow_increase": true,
  "allow_decrease": false,
  "validation": {
    "and": [
      {">=": [{"var": "minutes_played"}, 0]},
      {"<=": [{"var": "minutes_played"}, 48]},
      {"valid_game": {"var": "game_id"}}
    ]
  }
}

2. Limited Edition Collectible

  • Fungible: false
  • Allow increase: false (fixed supply)
  • Allow decrease: true (can burn)
  • DFA: MINTED → LISTED ↔ SOLD → BURNED
stateDiagram-v2
    [*] --> MINTED: mint(edition_number)
    MINTED --> LISTED: list(price)
    LISTED --> SOLD: buy()
    SOLD --> LISTED: relist(price)
    MINTED --> BURNED: burn()
    SOLD --> BURNED: burn()
    BURNED --> [*]
Loading

3. Vesting Shares

  • Fungible: true
  • Allow increase: false
  • Allow decrease: true (with conditions)
  • DFA: Time-based state progression
stateDiagram-v2
    [*] --> LOCKED: grant
    LOCKED --> VESTING: start_date_reached
    VESTING --> PARTIAL: milestone_met
    PARTIAL --> PARTIAL: more_vested
    PARTIAL --> UNLOCKED: fully_vested
    UNLOCKED --> CLAIMED: withdraw
    CLAIMED --> [*]
Loading

4. Fan Voting Rights

  • Fungible: true (can aggregate votes)
  • Allow increase: true (earn more votes)
  • Allow decrease: true (use votes)
  • DFA: EARNED → DELEGATED/CAST → COUNTED
stateDiagram-v2
    [*] --> EARNED: fan_activity
    EARNED --> EARNED: more_activity
    EARNED --> DELEGATED: delegate(to)
    EARNED --> CAST: vote(proposal)
    DELEGATED --> CAST: vote(proposal)
    CAST --> COUNTED: tally
    COUNTED --> [*]
Loading

5. Achievement Badge

  • Fungible: false
  • Allow increase: false
  • Allow decrease: false
  • DFA: EARNED → VERIFIED → DISPLAYED
stateDiagram-v2
    [*] --> PENDING: achievement_claimed
    PENDING --> VERIFIED: validate_proof
    VERIFIED --> DISPLAYED: add_to_profile
    VERIFIED --> PRIVATE: hide_badge
    DISPLAYED --> PRIVATE: hide_badge
    PRIVATE --> DISPLAYED: show_badge
    
    note right of PENDING: Awaiting verification
    note right of VERIFIED: Confirmed by validator
    note right of DISPLAYED: Visible on profile
    note right of PRIVATE: Hidden but owned
Loading

Composing Complex Behaviors

Policies can reference other tokens to create dependencies:

{
  "transition": "ACTIVATE_PREMIUM",
  "guard": {
    "and": [
      {"owns_token": [{"var": "user"}, "season_pass"]},
      {"token_state": ["season_pass", "ACTIVE"]},
      {">=": [{"var": "fan_points"}, 1000]}
    ]
  }
}

This enables:

  • Gated access based on other holdings
  • Composite achievements
  • Hierarchical unlocks
  • Cross-series dependencies

06_example_roster_lifecycle.md

Example: Roster Lifecycle

This example demonstrates how an athlete joins a team, progresses through roster states, and is eventually traded. Throughout, various types of tokens are generated representing different aspects of the relationship.

Participants and Agreements

// Participants
athlete = Participant{
  id: "did:athlete:lebron_james",
  type: USER,
  name: "LeBron James",
  public_key: "0xABC..."
}

lakers = Participant{
  id: "did:org:lakers", 
  type: ORG,
  name: "Los Angeles Lakers"
}

heat = Participant{
  id: "did:org:heat",
  type: ORG,
  name: "Miami Heat"
}

// Agreements
athlete_self = Agreement{
  id: "agreement_self_lebron",
  left: [athlete],  // Producer of personal data
  right: [athlete], // Self-validator
  agreement_type: "self"
}

athlete_lakers = Agreement{
  id: "agreement_lebron_lakers",
  left: [athlete],  // Athlete produces performance data
  right: [lakers],  // Team validates and governs
  agreement_type: "employment"
}

athlete_heat = Agreement{
  id: "agreement_lebron_heat",
  left: [athlete],
  right: [heat],
  agreement_type: "employment"
}

Group and Series Setup

roster_group = Group{
  id: "group_lakers_roster_2024",
  name: "Lakers 2024 Roster",
  owner_agreement_id: "agreement_lakers_nba",
  policy: GroupPolicy{
    fungible: false,  // Roster positions are unique
    allow_increase: false,  // Can't duplicate roster spots
    allow_decrease: false,  // Can't destroy roster spots
    conflict_resolution: XOR,
    dfa: roster_dfa
  }
}

roster_series = Series{
  id: "series_2024_season",
  group_id: "group_lakers_roster_2024",
  name: "2024 Regular Season",
  policy: SeriesPolicy{} // Inherits from group
}

// Separate group for performance data
stats_group = Group{
  id: "group_nba_stats_2024",
  name: "NBA Statistics 2024",
  policy: GroupPolicy{
    fungible: true,  // Stats can be aggregated
    allow_increase: true,  // Stats accumulate
    allow_decrease: false,  // Can't remove historical stats
    conflict_resolution: XOR
  }
}

Roster Lifecycle DFA

stateDiagram-v2
    [*] --> PROSPECT: scout
    PROSPECT --> TRYOUT: invite
    TRYOUT --> SIGNED: offer_accepted
    TRYOUT --> RELEASED: cut
    SIGNED --> TRAINING: training_camp
    TRAINING --> ACTIVE: make_roster
    TRAINING --> GLEAGUE: assign_gleague  
    TRAINING --> RELEASED: cut
    ACTIVE --> BENCH: coach_decision
    BENCH --> ACTIVE: coach_decision
    ACTIVE --> INJURED: injury_report
    INJURED --> REHAB: treatment_plan
    REHAB --> ACTIVE: medical_clearance
    ACTIVE --> TRADED: trade_executed
    GLEAGUE --> ACTIVE: call_up
    GLEAGUE --> TRADED: trade_executed
    TRADED --> [*]
    RELEASED --> [*]
    
    note right of ACTIVE: Starting lineup eligible
    note right of BENCH: Roster but not starting
    note right of GLEAGUE: Development league
    note right of TRADED: Moved to another team
Loading

Event Sequence

sequenceDiagram
    participant Athlete
    participant Lakers
    participant NBA
    participant Heat
    
    Note over Athlete,Lakers: Tryout Phase
    Athlete->>Athlete: Sign tryout data
    Athlete->>Lakers: Submit signed performance
    Lakers->>Lakers: Validate performance
    Lakers->>NBA: Register tryout event
    
    Note over Athlete,Lakers: Contract Signing
    Lakers->>Athlete: Offer contract
    Athlete->>Athlete: Sign acceptance
    Athlete->>Lakers: Submit signed contract
    Lakers->>NBA: Register roster addition
    NBA->>NBA: Update league records
    
    Note over Athlete,Lakers: Active Play
    loop Each Game
        Athlete->>Athlete: Generate performance data
        Athlete->>Lakers: Submit signed stats
        Lakers->>NBA: Validate and forward
        NBA->>NBA: Update official records
    end
    
    Note over Athlete,Heat: Trade Process
    Lakers->>NBA: Initiate trade
    Heat->>NBA: Accept trade
    Athlete->>NBA: Approve trade
    NBA->>NBA: Execute trade
    NBA->>Lakers: Update rosters
    NBA->>Heat: Update rosters
    Athlete->>Heat: Begin new agreement
Loading

1. Athlete Joins Tryout

// Producer creates and signs event content
tryout_content = EventContent{
  agreement_id: "agreement_lebron_lakers",
  activity_type: "TRYOUT_PERFORMANCE",
  parent_event_hash: "",  // First event
  ordinal: 1,
  timestamp: "2024-01-15T09:00:00Z",
  from_state_id: "",
  to_state_id: "TRYOUT",
  data: {
    "drill_results": {
      "three_point_shooting": "15/20",
      "free_throws": "18/20",
      "sprint_time": "4.2s",
      "vertical_jump": "38in"
    }
  }
}

// Producer signs the content with different proof types
signed_tryout = SignedEventContent{
  content: tryout_content,
  proofs: [
    Proof{
      id: "proof_001",
      type: SIGNATURE,
      prover_id: "did:athlete:lebron_james",
      timestamp: "2024-01-15T09:00:00Z",
      signature: SignatureProof{
        signature: "0xABC...",
        algorithm: "ECDSA",
        public_key: "0xPUBKEY..."
      }
    },
    // Could also include delegation proof if someone else submitted
    Proof{
      id: "proof_002", 
      type: DELEGATION,
      prover_id: "did:user:agent_smith",
      timestamp: "2024-01-15T09:00:00Z",
      delegation: DelegationProof{
        delegation_chain: ["token_delegation_001"],
        sub_proofs: [
          // Proof that agent has valid delegation
        ]
      }
    }
  ]
}

// Event stored in DAG
tryout_event = Event{
  id: "evt_001",
  signed_content: signed_tryout,
  content_hash: "0x123...",  // Hash of signed_tryout
  metadata: {
    "venue": "Lakers Training Facility",
    "coaches_present": "3"
  },
  validator_agreement_id: "agreement_lebron_lakers",
  validated_at: "2024-01-15T09:05:00Z"
}

// Token generated based on agreement's DFA rules
roster_token = Token{
  id: "token_roster_lebron_lakers",
  group_id: "group_lakers_roster_2024",
  series_id: "series_2024_season",
  owner_agreement_id: "agreement_lebron_lakers",
  quantity: 1,
  current_state_id: "TRYOUT",
  parent_event_content_hash: "0x123...",
  generation_event_id: "evt_001",
  applied_dfa_rule_id: "dfa_roster_lifecycle",
  created_at: "2024-01-15T09:05:00Z"
}

2. Contract Signing

contract_event = Event{
  id: "evt_002",
  agreement_id: "agreement_lebron_lakers",
  activity_type: "CONTRACT_SIGNED",
  parent_event_hash: "0x123...",
  self_hash: "0x456...",
  ordinal: 2,
  timestamp: "2024-01-20T14:00:00Z",
  from_state_id: "TRYOUT",
  to_state_id: "SIGNED",
  signed_data: {
    "contract_terms": {
      "duration_years": 2,
      "base_salary": "47654321",
      "incentives": ["playoffs", "all_star"],
      "jersey_number": "23"
    }
  },
  producer_signature: "0xGHI...",  // Athlete signs terms
  validator_signature: "0xJKL...",  // Team confirms
}

3. Performance Token Generation

While active, the athlete generates performance tokens:

// Game performance content signed by athlete
performance_content = EventContent{
  agreement_id: "agreement_lebron_lakers",
  activity_type: "GAME_PERFORMANCE",
  parent_event_hash: "0x789...",
  ordinal: 45,  // 45th game
  timestamp: "2024-02-15T19:30:00Z",
  from_state_id: "ACTIVE",
  to_state_id: "ACTIVE",  // State doesn't change
  data: {
    "game_id": "LAL_vs_BOS_20240215",
    "stats": {
      "points": 38,
      "rebounds": 12,
      "assists": 11,
      "triple_double": true
    },
    "highlights": [
      {
        "time": "Q4 0:30",
        "play": "game_winning_three",
        "video_hash": "ipfs://Qm..."
      }
    ]
  }
}

// Athlete signs the performance data
signed_performance = SignedEventContent{
  content: performance_content,
  proofs: [
    Proof{
      agreement_id: "agreement_lebron_lakers",
      participant_id: "did:athlete:lebron_james",
      signature: "0xMNO...",
      timestamp: "2024-02-15T21:00:00Z"
    }
  ]
}

// Event in DAG
game_performance_event = Event{
  id: "evt_003",
  signed_content: signed_performance,
  content_hash: "0xABC...",
  metadata: {
    "broadcast": "ESPN",
    "attendance": "18997",
    "league_validated": "true"
  },
  validator_agreement_id: "agreement_lebron_lakers",
  validated_at: "2024-02-15T22:00:00Z"
}

// Agreement's DFA rules create multiple tokens from one event
// Stats token (fungible)
stats_token = Token{
  id: "token_stats_lebron_game_45",
  group_id: "group_nba_stats_2024",
  series_id: "series_regular_season",
  quantity: 38,  // Points scored
  current_state_id: "RECORDED",
  parent_event_content_hash: "0xABC...",
  generation_event_id: "evt_003",
  applied_dfa_rule_id: "dfa_stats_accumulator",
  attributes: {
    "stat_type": "points",
    "game_id": "LAL_vs_BOS_20240215"
  }
}

// Moment token (non-fungible collectible)
moment_token = Token{
  id: "token_moment_lebron_20240215",
  group_id: "group_nba_topshot",
  series_id: "series_legendary_moments",
  quantity: 1,
  unique_id: "LEBRON_TRIPLE_DOUBLE_45",
  current_state_id: "MINTED",
  parent_event_content_hash: "0xABC...",
  generation_event_id: "evt_003",
  applied_dfa_rule_id: "dfa_collectible_minting",
  attributes: {
    "rarity": "legendary",
    "serial": "001/100",
    "video_ipfs": "ipfs://Qm...",
    "stats": {
      "points": 38,
      "rebounds": 12,
      "assists": 11
    }
  }
}

4. Trade Execution

trade_event = Event{
  id: "evt_004",
  agreement_id: "agreement_lebron_lakers",
  activity_type: "TRADE_EXECUTED",
  parent_event_hash: "0xDEF...",
  self_hash: "0x999...",
  ordinal: 156,
  timestamp: "2024-03-15T12:00:00Z",
  from_state_id: "ACTIVE",
  to_state_id: "TRADED",
  signed_data: {
    "trade_details": {
      "from_team": "did:org:lakers",
      "to_team": "did:org:heat",
      "compensation": {
        "draft_picks": ["2025_first_round", "2027_second_round"],
        "cash": "5000000"
      },
      "effective_date": "2024-03-16T00:00:00Z"
    }
  },
  producer_signature: "0xSTU...",  // Athlete consent
  validator_signature: "0xVWX...",  // League approval
  referenced_token_ids: [
    "token_roster_lebron_heat"  // New roster token
  ]
}

// Lakers roster token becomes TRADED (terminal state)
// Heat roster token becomes ACTIVE
new_roster_token = Token{
  id: "token_roster_lebron_heat",
  group_id: "group_heat_roster_2024",
  series_id: "series_2024_season",
  owner_agreement_id: "agreement_lebron_heat",
  quantity: 1,
  current_state_id: "ACTIVE",
  parent_event_hash: "0x999..."
}

State Updates

Athlete's Tries

  • Activities: Full history of tryout → signed → active → traded
  • Relationships: Lakers membership revoked, Heat membership added
  • Assets: All performance tokens and moments retained
  • Permissions: Team-specific permissions updated

Lakers' Tries

  • Group: Athlete removed from active roster
  • Assets: Historical performance data retained
  • Activities: Trade event recorded
  • Relationships: Employment agreement terminated

Heat's Tries

  • Group: Athlete added to active roster
  • Assets: New performance tracking begins
  • Activities: New roster token created
  • Relationships: New employment agreement active

Token Types Generated

  1. Roster Token: Non-fungible position on team
  2. Performance Tokens: Fungible statistics (points, assists, etc.)
  3. Moment Tokens: Non-fungible collectible highlights
  4. Achievement Tokens: Badges for milestones (triple-doubles, etc.)
  5. Contract Token: Terms and conditions of employment

Key Observations

  • Performance data persists across team changes
  • Collectible moments remain with original team branding
  • Trade requires multi-party consensus (athlete, both teams, league)
  • Each agreement maintains independent state and permissions
  • Historical data provides complete career trajectory

07_example_injury_recovery.md

Example: Injury and Recovery

This example shows how injury and recovery states interact with roster status, involving medical professionals and coaching staff. It demonstrates cross-group dependencies and privacy-preserving data sharing.

Additional Participants

team_doctor = Participant{
  id: "did:user:dr_anderson",
  type: USER,
  name: "Dr. Sarah Anderson, MD",
  public_key: "0x111..."
}

physical_therapist = Participant{
  id: "did:user:pt_chen",
  type: USER,
  name: "Mike Chen, DPT",
  public_key: "0x222..."
}

league_medical = Participant{
  id: "did:org:nba_medical",
  type: ORG,
  name: "NBA Medical Committee",
  public_key: "0x333..."
}

// Medical agreements
athlete_doctor = Agreement{
  id: "agreement_lebron_dr_anderson",
  left: [athlete],  // Athlete provides medical data
  right: [team_doctor],  // Doctor validates and treats
  agreement_type: "medical_care"
}

athlete_therapist = Agreement{
  id: "agreement_lebron_pt_chen",
  left: [athlete],
  right: [physical_therapist],
  agreement_type: "rehabilitation"
}

doctor_league = Agreement{
  id: "agreement_anderson_nba",
  left: [team_doctor],
  right: [league_medical],
  agreement_type: "medical_reporting"
}

Medical Group Setup

medical_group = Group{
  id: "group_lakers_medical_2024",
  name: "Lakers Medical Records 2024",
  owner_agreement_id: "agreement_lakers_medical_staff",
  policy: GroupPolicy{
    fungible: false,  // Medical records are unique
    allow_increase: true,  // Can add new medical events
    allow_decrease: false, // Can't delete medical history
    conflict_resolution: XOR,
    dfa: medical_dfa
  }
}

injury_series = Series{
  id: "series_knee_injury_2024_001",
  name: "Right Knee Injury March 2024",
  group_id: "group_lakers_medical_2024"
}

Injury/Recovery DFA

stateDiagram-v2
    [*] --> HEALTHY: baseline_exam
    HEALTHY --> INJURED: injury_diagnosed
    INJURED --> EVALUATED: initial_assessment
    EVALUATED --> TREATMENT: treatment_approved
    EVALUATED --> SURGERY: surgery_required
    SURGERY --> TREATMENT: post_surgery
    TREATMENT --> REHAB: treatment_complete
    REHAB --> TESTING: progress_check
    TESTING --> REHAB: needs_more_time
    TESTING --> CLEARED: tests_passed
    CLEARED --> MONITORING: return_to_play
    MONITORING --> HEALTHY: observation_complete
    MONITORING --> INJURED: re_injury
    
    note right of INJURED: Immediate eval required
    note right of TREATMENT: Active medical care
    note right of REHAB: Physical therapy phase
    note right of CLEARED: Medically approved
    note right of MONITORING: Gradual return
Loading

Integrated Event Flow

sequenceDiagram
    participant Athlete
    participant TeamDoctor
    participant PT
    participant Coach
    participant League
    
    Note over Athlete,TeamDoctor: Injury Occurs
    Athlete->>Athlete: Report symptoms
    Athlete->>TeamDoctor: Request evaluation
    TeamDoctor->>TeamDoctor: Examine athlete
    TeamDoctor->>Athlete: Diagnosis
    TeamDoctor->>League: Injury report (sanitized)
    
    Note over Athlete,PT: Treatment Phase
    TeamDoctor->>PT: Treatment plan
    PT->>Athlete: Begin rehab
    loop Daily Sessions
        Athlete->>Athlete: Complete exercises
        Athlete->>PT: Progress data
        PT->>TeamDoctor: Progress report
    end
    
    Note over Athlete,Coach: Return Protocol
    TeamDoctor->>Coach: Status update (limited)
    Coach->>TeamDoctor: Request timeline
    TeamDoctor->>Athlete: Clearance tests
    Athlete->>TeamDoctor: Test results
    TeamDoctor->>Coach: Cleared to play
    TeamDoctor->>League: Update status
Loading

1. Injury Occurs During Game

// Injury during game affects both roster and medical tokens
injury_event = Event{
  id: "evt_inj_001",
  agreement_id: "agreement_lebron_dr_anderson",
  activity_type: "INJURY_DIAGNOSED",
  parent_event_hash: "",
  self_hash: "0xAAA...",
  ordinal: 1,
  timestamp: "2024-03-20T19:30:00Z",
  from_state_id: "HEALTHY",
  to_state_id: "INJURED",
  signed_data: {
    "injury_details": {
      "body_part": "right_knee",
      "type": "sprain",
      "severity": "grade_2",
      "occurred_during": "LAL_vs_DEN_20240320",
      "mechanism": "landing_after_dunk",
      "initial_treatment": "ice_compression_elevation"
    },
    "sensitive_data_hash": "0xBBB..."  // Detailed medical data
  },
  producer_signature: "0xCCC...",  // Athlete consent
  validator_signature: "0xDDD...",  // Doctor diagnosis
}

// Simultaneously update roster status
roster_injury_event = Event{
  id: "evt_roster_005",
  agreement_id: "agreement_lebron_lakers",
  activity_type: "INJURY_DESIGNATION",
  from_state_id: "ACTIVE",
  to_state_id: "INJURED",
  signed_data: {
    "status": "day_to_day",
    "estimated_return": "2_3_weeks",
    "injury_report": "right_knee_sprain"  // Public version
  },
  referenced_token_ids: ["token_medical_inj_001"]
}

// Medical token created
medical_token = Token{
  id: "token_medical_inj_001",
  group_id: "group_lakers_medical_2024",
  series_id: "series_knee_injury_2024_001",
  owner_agreement_id: "agreement_lebron_dr_anderson",
  quantity: 1,
  current_state_id: "INJURED",
  parent_event_hash: "0xAAA...",
  attributes: {
    "injury_code": "S83.6",  // ICD-10
    "severity": "moderate",
    "private_data_ref": "encrypted_ipfs://..."
  }
}

2. Medical Delegation Created

// Athlete delegates limited medical info to coach
medical_delegation = DelegationNode{
  delegator_agreement_id: "agreement_self_lebron",
  delegate_agreement_id: "agreement_coach_lakers",
  permissions: [
    "view_injury_status",
    "view_recovery_timeline",
    "view_cleared_to_play"
  ],
  expires_at: "2024-06-20T00:00:00Z",
  delegation_token_id: "token_delegation_medical_001"
}

// Separate delegation for detailed medical data
detailed_delegation = DelegationNode{
  delegator_agreement_id: "agreement_self_lebron",
  delegate_agreement_id: "agreement_lebron_dr_anderson",
  permissions: [
    "view_all_medical",
    "update_treatment",
    "order_tests",
    "clear_for_activity"
  ],
  expires_at: "2024-12-31T00:00:00Z",
  delegation_token_id: "token_delegation_medical_002"
}

3. Treatment Plan Initiated

treatment_event = Event{
  id: "evt_inj_002",
  agreement_id: "agreement_lebron_dr_anderson",
  activity_type: "BEGIN_TREATMENT",
  parent_event_hash: "0xAAA...",
  self_hash: "0xEEE...",
  ordinal: 2,
  timestamp: "2024-03-21T10:00:00Z",
  from_state_id: "INJURED",
  to_state_id: "TREATMENT",
  signed_data: {
    "treatment_plan": {
      "phase_1": {
        "duration_days": 7,
        "interventions": ["rest", "ice", "compression", "elevation"],
        "medications": ["ibuprofen_800mg"]
      },
      "phase_2": {
        "duration_days": 14,
        "interventions": ["physical_therapy", "strength_training"],
        "goals": ["full_range_of_motion", "no_pain_walking"]
      }
    },
    "therapist_assigned": "did:user:pt_chen"
  },
  producer_signature: "0xFFF...",  // Doctor prescribes
  validator_signature: "0xGGG...",  // Athlete consents
}

4. Rehabilitation Progress Tracking

Multiple events track recovery with privacy preservation:

// Daily rehab session - sensitive details
rehab_session_event = Event{
  id: "evt_rehab_015",
  agreement_id: "agreement_lebron_pt_chen",
  activity_type: "REHAB_SESSION",
  parent_event_hash: "0xHHH...",
  self_hash: "0xIII...",
  ordinal: 15,
  timestamp: "2024-04-05T14:00:00Z",
  signed_data: {
    "session_summary": {
      "exercises_completed": 12,
      "pain_level": "2/10",
      "range_of_motion": "95%",
      "strength_test": "85%"
    },
    "sensitive_details_hash": "0xJJJ..."  // Full session data
  },
  producer_signature: "0xKKK...",  // Athlete confirms
  validator_signature: "0xLLL...",  // PT validates
}

// Progress token for coach visibility
progress_token = Token{
  id: "token_rehab_progress_015",
  group_id: "group_lakers_medical_2024",
  series_id: "series_rehab_tracking",
  quantity: 85,  // Strength percentage
  current_state_id: "IMPROVING",
  attributes: {
    "metric": "strength_recovery",
    "trend": "positive",
    "sessions_complete": 15
  }
}

5. Coach Queries Recovery Status

// Coach uses delegation to check status
status_query = {
  "agreement_id": "agreement_coach_lakers",
  "query_type": "injury_status",
  "player_agreement": "agreement_lebron_lakers",
  "requested_fields": [
    "current_status",
    "estimated_return",
    "cleared_for_practice"
  ],
  "authorization": {
    "delegation_token": "token_delegation_medical_001",
    "signature": "0xMMM..."
  }
}

// Returns sanitized view
status_response = {
  "current_status": "REHAB",
  "estimated_return": "2024-04-15",
  "cleared_for_practice": false,
  "last_updated": "2024-04-05T16:00:00Z"
}

6. Medical Clearance Process

// Series of tests before clearance
clearance_test_event = Event{
  id: "evt_clear_001",
  agreement_id: "agreement_lebron_dr_anderson",
  activity_type: "CLEARANCE_TESTS",
  parent_event_hash: "0xNNN...",
  self_hash: "0xOOO...",
  ordinal: 25,
  timestamp: "2024-04-10T09:00:00Z",
  signed_data: {
    "test_results": {
      "mri_scan": "no_structural_damage",
      "strength_test": "95%_of_baseline",
      "functional_test": "passed",
      "pain_assessment": "0/10"
    },
    "sensitive_results_hash": "0xPPP..."
  },
  producer_signature: "0xQQQ...",  // Test results
  validator_signature: "0xRRR...",  // Doctor confirms
}

// Final clearance
clearance_event = Event{
  id: "evt_clear_002",
  agreement_id: "agreement_lebron_dr_anderson",
  activity_type: "MEDICAL_CLEARANCE",
  parent_event_hash: "0xOOO...",
  self_hash: "0xSSS...",
  ordinal: 26,
  timestamp: "2024-04-10T14:00:00Z",
  from_state_id: "TESTING",
  to_state_id: "CLEARED",
  signed_data: {
    "clearance": {
      "cleared_for": ["practice", "games"],
      "restrictions": ["minutes_limit_20"],
      "follow_up_required": "2024-04-20"
    }
  },
  producer_signature: "0xTTT...",  // Doctor clears
  validator_signature: "0xUUU...",  // Athlete acknowledges
}

7. Return to Active Roster

// Roster reactivation with medical reference
roster_return_event = Event{
  id: "evt_roster_006",
  agreement_id: "agreement_lebron_lakers",
  activity_type: "ACTIVATE_FROM_INJURY",
  from_state_id: "INJURED",
  to_state_id: "ACTIVE",
  signed_data: {
    "medical_clearance": true,
    "clearance_token_ref": "token_medical_clear_001",
    "return_conditions": {
      "minutes_restriction": 20,
      "monitoring_period_days": 14
    }
  },
  referenced_token_ids: ["token_medical_clear_001"]
}

// Monitoring token created
monitoring_token = Token{
  id: "token_monitoring_001",
  group_id: "group_lakers_medical_2024",
  series_id: "series_return_protocol",
  quantity: 14,  // Days of monitoring
  current_state_id: "MONITORING",
  attributes: {
    "player": "did:athlete:lebron_james",
    "injury_ref": "token_medical_inj_001",
    "daily_check_required": true
  }
}

Privacy Architecture

Three-Tier Data Model

  1. Public Data (Onchain)

    • Injury designation (DTD, Out, etc.)
    • Estimated return timeline
    • Cleared/not cleared status
  2. Restricted Data (Delegated Access)

    • Recovery percentage
    • Treatment phase
    • Practice limitations
  3. Private Data (Encrypted/Off-chain)

    • Detailed medical records
    • Test results and imaging
    • Medication details

Access Control Matrix

Data Type Athlete Doctor PT Coach League Public
Detailed Medical Limited
Treatment Plan
Recovery Progress Summary
Injury Status Basic
Return Timeline

Key Features Demonstrated

  1. Privacy-Preserving Medical Data: Sensitive data stays encrypted while status is public
  2. Multi-Party Coordination: Doctor, PT, coach, and league all have appropriate access
  3. Cross-Token References: Injury affects roster status through token references
  4. Time-Bounded Delegations: Medical permissions expire automatically
  5. Progressive Disclosure: Different stakeholders see different levels of detail
  6. Audit Trail: Complete history while maintaining privacy

08_example_data_deal.md

Example: Data Licensing Deal

This example demonstrates a comprehensive data licensing agreement where athletes' performance data is aggregated by the players' association and licensed to various parties including video game developers, with automatic royalty distribution.

Additional Participants

players_association = Participant{
  id: "did:org:nbpa",
  type: ORG,
  name: "National Basketball Players Association",
  public_key: "0x444..."
}

game_developer = Participant{
  id: "did:org:2k_sports",
  type: ORG,
  name: "2K Sports",
  public_key: "0x555..."
}

analytics_firm = Participant{
  id: "did:org:stats_perform",
  type: ORG,
  name: "Stats Perform",
  public_key: "0x666..."
}

// Agreements
athlete_pa = Agreement{
  id: "agreement_lebron_nbpa",
  left: [athlete],  // Athlete provides data rights
  right: [players_association],  // PA manages and protects
  agreement_type: "collective_representation"
}

pa_gamedev = Agreement{
  id: "agreement_nbpa_2k",
  left: [players_association],  // PA provides aggregated data
  right: [game_developer],  // Developer validates usage
  agreement_type: "data_licensing"
}

pa_analytics = Agreement{
  id: "agreement_nbpa_stats",
  left: [players_association],
  right: [analytics_firm],
  agreement_type: "data_licensing"
}

Data Licensing Groups

licensing_group = Group{
  id: "group_nbpa_licensing_2024",
  name: "NBPA Data Licensing Program",
  owner_agreement_id: "agreement_nbpa_board",
  policy: GroupPolicy{
    fungible: true,  // Data can be aggregated
    allow_increase: true,  // More data adds value
    allow_decrease: false, // Historical data preserved
    conflict_resolution: XOR,
    dfa: licensing_dfa
  }
}

game_data_series = Series{
  id: "series_video_game_2024",
  name: "Video Game License 2024-2025",
  group_id: "group_nbpa_licensing_2024",
  policy: SeriesPolicy{
    fungible: false,  // Specific license terms
    allow_increase: false,  // Fixed deal
  }
}

royalty_group = Group{
  id: "group_royalty_distribution",
  name: "Player Royalty Distribution",
  policy: GroupPolicy{
    fungible: true,  // Royalties are fungible
    allow_increase: true,  // Earnings accumulate
    allow_decrease: true,  // Withdrawals allowed
    conflict_resolution: AND
  }
}

Data Licensing DFA

stateDiagram-v2
    [*] --> PROPOSED: initiate_deal
    PROPOSED --> NEGOTIATING: counter_offer
    NEGOTIATING --> NEGOTIATING: revise_terms
    NEGOTIATING --> PROPOSED: reject
    PROPOSED --> PLAYER_VOTE: terms_agreed
    PLAYER_VOTE --> APPROVED: majority_yes
    PLAYER_VOTE --> REJECTED: majority_no
    APPROVED --> SIGNED: execute_contracts
    SIGNED --> ACTIVE: start_date_reached
    ACTIVE --> RENEWING: approach_expiry
    RENEWING --> ACTIVE: renewal_signed
    ACTIVE --> EXPIRED: end_date_reached
    EXPIRED --> ARCHIVED: final_accounting
    REJECTED --> [*]
    ARCHIVED --> [*]
    
    note right of PROPOSED: Initial terms presented
    note right of PLAYER_VOTE: Democratic approval
    note right of ACTIVE: Data flowing, royalties generating
    note right of RENEWING: 90 days before expiry
Loading

Deal Lifecycle

sequenceDiagram
    participant Athletes
    participant NBPA
    participant GameDev
    participant League
    participant Bank
    
    Note over Athletes,GameDev: Deal Negotiation
    GameDev->>NBPA: Propose data license
    NBPA->>NBPA: Review terms
    NBPA->>Athletes: Present for vote
    Athletes->>NBPA: Vote on deal
    NBPA->>GameDev: Accept terms
    
    Note over Athletes,GameDev: Data Delegation
    Athletes->>Athletes: Sign data rights
    Athletes->>NBPA: Delegate data access
    NBPA->>GameDev: Grant limited access
    
    Note over NBPA,League: Data Collection
    loop Each Game
        League->>NBPA: Official stats
        Athletes->>NBPA: Biometric data
        NBPA->>NBPA: Aggregate & anonymize
        NBPA->>GameDev: Provide data feed
    end
    
    Note over GameDev,Bank: Royalty Flow
    GameDev->>GameDev: Track usage
    GameDev->>Bank: Royalty payment
    Bank->>NBPA: Receive payment
    NBPA->>Athletes: Distribute royalties
Loading

1. Deal Proposal with Democratic Voting

// Initial proposal
proposal_event = Event{
  id: "evt_deal_001",
  agreement_id: "agreement_nbpa_2k",
  activity_type: "PROPOSE_LICENSE",
  parent_event_hash: "",
  self_hash: "0x777...",
  ordinal: 1,
  timestamp: "2024-01-01T09:00:00Z",
  from_state_id: "",
  to_state_id: "PROPOSED",
  signed_data: {
    "license_terms": {
      "duration_months": 12,
      "start_date": "2024-02-01",
      "end_date": "2025-01-31",
      "data_types": [
        "player_attributes",
        "shooting_tendencies", 
        "movement_patterns",
        "signature_moves",
        "career_statistics"
      ],
      "usage_rights": {
        "platforms": ["console", "pc", "mobile"],
        "game_modes": ["all"],
        "territorial": "worldwide"
      },
      "financial_terms": {
        "upfront_payment": "5000000",
        "royalty_rate": "0.015",  // 1.5% of revenue
        "minimum_guarantee": "10000000",
        "payment_frequency": "quarterly"
      }
    }
  },
  producer_signature: "0x888...",  // Game dev proposes
  validator_signature: "0x999...",  // NBPA acknowledges
}

// Player voting token
voting_token = Token{
  id: "token_vote_2k_deal_2024",
  group_id: "group_nbpa_voting",
  series_id: "series_2024_votes", 
  quantity: 450,  // Number of players
  current_state_id: "OPEN",
  attributes: {
    "proposal_ref": "evt_deal_001",
    "voting_deadline": "2024-01-15T23:59:59Z",
    "quorum_required": 225,
    "approval_threshold": 0.5
  }
}

2. Individual Player Consent

// Each player votes and consents
consent_event = Event{
  id: "evt_consent_lebron",
  agreement_id: "agreement_lebron_nbpa",
  activity_type: "DATA_LICENSE_CONSENT",
  parent_event_hash: "0xAAA...",
  self_hash: "0xBBB...",
  ordinal: 1,
  timestamp: "2024-01-10T14:00:00Z",
  signed_data: {
    "vote": "approve",
    "consent_to_license": true,
    "data_categories_approved": [
      "player_attributes",
      "shooting_tendencies",
      "movement_patterns",
      "signature_moves",
      "career_statistics"
    ],
    "opt_out_categories": [],  // Can exclude sensitive data
    "royalty_distribution_preference": {
      "method": "equal_split",
      "charity_percentage": 0.1
    }
  },
  producer_signature: "0xCCC...",  // Player's consent
  validator_signature: "0xDDD...",  // NBPA confirms
}

// This creates a consent token
consent_token = Token{
  id: "token_consent_lebron_2k_2024",
  group_id: "group_nbpa_licensing_2024",
  series_id: "series_video_game_2024",
  owner_agreement_id: "agreement_lebron_nbpa",
  quantity: 1,
  current_state_id: "CONSENTED",
  attributes: {
    "player_id": "did:athlete:lebron_james",
    "license_ref": "token_license_2k_2024",
    "valid_until": "2025-01-31"
  }
}

3. Data Access Delegation

// NBPA creates master delegation for game developer
data_delegation = DelegationNode{
  delegator_agreement_id: "agreement_nbpa_board",
  delegate_agreement_id: "agreement_nbpa_2k",
  permissions: [
    "read_aggregated_stats",
    "read_player_attributes",
    "read_tendency_data",
    "subscribe_to_updates"
  ],
  expires_at: "2025-02-01T00:00:00Z",
  delegation_token_id: "token_delegation_2k_data"
}

// Individual player delegation to NBPA
player_delegation = DelegationNode{
  delegator_agreement_id: "agreement_self_lebron",
  delegate_agreement_id: "agreement_lebron_nbpa",
  permissions: [
    "aggregate_performance_data",
    "license_to_approved_parties",
    "collect_royalties",
    "anonymize_sensitive_data"
  ],
  expires_at: "2025-02-01T00:00:00Z",
  delegation_token_id: "token_delegation_nbpa_lebron"
}

4. Deal Activation and Data Flow

activation_event = Event{
  id: "evt_deal_activate",
  agreement_id: "agreement_nbpa_2k",
  activity_type: "ACTIVATE_LICENSE",
  parent_event_hash: "0xEEE...",
  self_hash: "0xFFF...",
  ordinal: 5,
  timestamp: "2024-02-01T00:00:00Z",
  from_state_id: "SIGNED",
  to_state_id: "ACTIVE",
  signed_data: {
    "activation_details": {
      "players_included": 450,
      "data_feed_endpoint": "https://api.nbpa.org/game-data",
      "api_key_hash": "0xGGG...",
      "update_frequency": "daily",
      "initial_data_package": "ipfs://QmHistoricalData..."
    }
  },
  producer_signature: "0xHHH...",
  validator_signature: "0xIII...",
}

// License token representing active deal
license_token = Token{
  id: "token_license_2k_2024",
  group_id: "group_nbpa_licensing_2024",
  series_id: "series_video_game_2024",
  owner_agreement_id: "agreement_nbpa_2k",
  quantity: 1,
  current_state_id: "ACTIVE",
  unique_id: "LICENSE_2K_2024",
  attributes: {
    "licensee": "did:org:2k_sports",
    "revenue_share": 0.015,
    "minimum_guarantee": 10000000,
    "players_count": 450
  }
}

5. Performance Data Aggregation

// Regular data aggregation events
aggregation_event = Event{
  id: "evt_aggregate_week_10",
  agreement_id: "agreement_nbpa_board",
  activity_type: "AGGREGATE_PLAYER_DATA",
  parent_event_hash: "0xJJJ...",
  self_hash: "0xKKK...",
  ordinal: 70,  // Week 10 of season
  timestamp: "2024-04-15T00:00:00Z",
  signed_data: {
    "aggregation_summary": {
      "period": "2024_week_10",
      "players_included": 445,
      "games_processed": 82,
      "data_points": 125000,
      "anonymization_applied": true,
      "statistical_noise_added": true
    },
    "data_categories": {
      "shooting_efficiency": {
        "samples": 15000,
        "mean": 0.457,
        "std_dev": 0.082
      },
      "movement_patterns": {
        "distance_per_game_avg": 2.54,
        "sprint_frequency": 24.3
      }
    }
  },
  producer_signature: "0xLLL...",
  referenced_token_ids: [
    // References individual player performance tokens
    "token_perf_lebron_w10_g1",
    "token_perf_lebron_w10_g2",
    // ... hundreds more
  ]
}

6. Royalty Generation and Distribution

// Quarterly royalty calculation
royalty_event = Event{
  id: "evt_royalty_q1_2024",
  agreement_id: "agreement_nbpa_2k",
  activity_type: "ROYALTY_PAYMENT",
  parent_event_hash: "0xMMM...",
  self_hash: "0xNNN...",
  ordinal: 1,
  timestamp: "2024-05-01T00:00:00Z",
  signed_data: {
    "royalty_calculation": {
      "period": "2024_Q1",
      "gross_revenue": 125000000,
      "royalty_rate": 0.015,
      "royalty_amount": 1875000,
      "minimum_guarantee_credit": 2500000,
      "amount_due": 2500000  // Greater of calculated or minimum
    },
    "usage_metrics": {
      "game_copies_sold": 2500000,
      "myteam_cards_created": 45000000,
      "online_games_played": 125000000
    }
  },
  producer_signature: "0xOOO...",  // 2K reports
  validator_signature: "0xPPP...",  // NBPA verifies
}

// Individual royalty tokens created
royalty_token = Token{
  id: "token_royalty_lebron_q1_2024",
  group_id: "group_royalty_distribution",
  series_id: "series_2k_royalties",
  owner_agreement_id: "agreement_self_lebron",
  quantity: 5555,  // $5,555 (1/450 of $2.5M)
  current_state_id: "PAYABLE",
  attributes: {
    "source_license": "token_license_2k_2024",
    "calculation_method": "equal_split",
    "period": "2024_Q1",
    "payment_date": "2024-05-15"
  }
}

7. Usage Tracking and Compliance

// Game developer reports usage
usage_event = Event{
  id: "evt_usage_report_march",
  agreement_id: "agreement_nbpa_2k",
  activity_type: "USAGE_REPORT",
  parent_event_hash: "0xQQQ...",
  self_hash: "0xRRR...",
  ordinal: 30,
  timestamp: "2024-04-01T00:00:00Z",
  signed_data: {
    "usage_details": {
      "month": "2024_03",
      "player_cards_generated": 15000000,
      "simulations_run": 45000000,
      "ai_training_iterations": 0,  // Not permitted
      "platforms": {
        "playstation": 0.45,
        "xbox": 0.35,
        "pc": 0.20
      }
    },
    "compliance_attestation": {
      "data_retention_policy_followed": true,
      "no_unauthorized_sharing": true,
      "security_audit_passed": true
    }
  },
  producer_signature: "0xSSS...",
  validator_signature: "0xTTT...",
}

8. Automatic Renewal Decision

// 90 days before expiry, renewal process begins
renewal_proposal = Event{
  id: "evt_renewal_proposal",
  agreement_id: "agreement_nbpa_2k",
  activity_type: "PROPOSE_RENEWAL",
  parent_event_hash: "0xUUU...",
  self_hash: "0xVVV...",
  ordinal: 100,
  timestamp: "2024-11-01T00:00:00Z",
  from_state_id: "ACTIVE",
  to_state_id: "RENEWING",
  signed_data: {
    "renewal_terms": {
      "duration_months": 12,
      "royalty_rate": 0.018,  // Increased
      "minimum_guarantee": 12000000,  // Increased
      "new_data_types": ["voice_samples", "celebration_animations"],
      "performance_metrics": {
        "previous_year_revenue": 500000000,
        "player_satisfaction": 0.85,
        "compliance_score": 0.98
      }
    }
  },
  producer_signature: "0xWWW...",
}

// Triggers new voting round
renewal_vote_token = Token{
  id: "token_vote_renewal_2k_2025",
  group_id: "group_nbpa_voting",
  series_id: "series_2025_votes",
  quantity: 455,  // More players now
  current_state_id: "OPEN",
  attributes: {
    "proposal_ref": "evt_renewal_proposal",
    "changes_from_previous": [
      "royalty_rate_increase",
      "minimum_guarantee_increase",
      "new_data_categories"
    ]
  }
}

Token Economics

Revenue Flow

graph TD
    GameSales[Game Sales Revenue] --> GameDev[Game Developer]
    MTX[Microtransactions] --> GameDev
    GameDev -->|1.5%| RoyaltyPool[Royalty Pool]
    RoyaltyPool -->|90%| Players[Player Distribution]
    RoyaltyPool -->|10%| NBPA[NBPA Operations]
    Players -->|Equal Split| Individual[Individual Players]
    Individual -->|10%| Charity[Player Charities]
    Individual -->|90%| PlayerAccount[Player Account]
Loading

Token Types in Data Ecosystem

  1. License Tokens: Represent active agreements
  2. Consent Tokens: Individual player approvals
  3. Royalty Tokens: Distributable earnings
  4. Usage Tokens: Track data consumption
  5. Voting Tokens: Democratic governance
  6. Delegation Tokens: Time-bounded permissions

Privacy and Data Protection

Data Anonymization Pipeline

anonymization_event = Event{
  id: "evt_anonymize_batch_050",
  agreement_id: "agreement_nbpa_board",
  activity_type: "ANONYMIZE_DATA",
  signed_data: {
    "anonymization_techniques": [
      "differential_privacy",
      "k_anonymity",
      "statistical_noise"
    ],
    "privacy_budget": 0.1,
    "aggregation_threshold": 5,  // Min 5 players per stat
    "sensitive_fields_removed": [
      "injury_history",
      "personal_maximums",
      "fatigue_indicators"
    ]
  }
}

Tiered Data Access

  1. Public: Basic stats, no PII
  2. Licensed: Aggregated, anonymized data
  3. Premium: Detailed patterns (additional license)
  4. Restricted: Never shared (medical, personal)

Expanding to Other Use Cases

Fan Token Ownership Model

fan_ownership_token = Token{
  id: "token_fan_ownership_lakers",
  group_id: "group_fan_ownership",
  series_id: "series_lakers_shares",
  quantity: 1000000,  // 1M shares available
  current_state_id: "TRADING",
  attributes: {
    "voting_rights": true,
    "revenue_share": 0.001,  // 0.1% of merchandise
    "perks": ["exclusive_content", "meet_greets", "draft_input"],
    "transferable": true,
    "vesting_period": "none"
  }
}

Limited Time Offers vs Permanent Rights

// Flash collectible - 24 hour availability
flash_moment = Token{
  id: "token_moment_flash_001",
  group_id: "group_limited_drops",
  series_id: "series_24h_specials",
  quantity: 10000,
  current_state_id: "AVAILABLE",
  attributes: {
    "availability_window": "24_hours",
    "mint_end_time": "2024-05-02T00:00:00Z",
    "burn_if_unsold": true,
    "rarity_tier": "uncommon"
  }
}

// Permanent collectible
permanent_moment = Token{
  id: "token_moment_championship",
  group_id: "group_eternal_moments",
  series_id: "series_championships",
  quantity: 1,
  unique_id: "2024_CHAMPIONSHIP_WINNER",
  current_state_id: "MINTED",
  attributes: {
    "availability": "permanent",
    "historical_significance": "maximum",
    "appreciation_potential": "high"
  }
}

Key Innovations Demonstrated

  1. Democratic Governance: Players vote on data usage
  2. Automatic Royalty Distribution: Smart contract-like behavior
  3. Privacy-Preserving Aggregation: Individual data protected
  4. Time-Bounded Licensing: Automatic expiration and renewal
  5. Multi-Tier Monetization: Different licenses for different uses
  6. Compliance Tracking: Usage monitored and verified
  7. Collective Bargaining: PA represents all players efficiently

09_api_reference.md

API Reference

This section outlines key operations for interacting with the protocol. Full implementation details will be provided in future releases.

Agreement Operations

Create Agreement

Creates a new pairwise agreement between participants.

interface CreateAgreementRequest {
  left_participants: ParticipantId[];  // Producers
  right_participants: ParticipantId[];  // Validators
  agreement_type: string;
  metadata?: Record<string, string>;
  signatures: Signature[];  // From all participants
}

interface CreateAgreementResponse {
  agreement_id: string;
  created_at: timestamp;
  initial_tries: TrieRoot[];
}

Query Agreement

Retrieves agreement details and current state.

interface QueryAgreementRequest {
  agreement_id: string;
  include_tries?: boolean;
  as_of_height?: number;  // Historical query
}

Group Operations

Create Group

Establishes a new group with policy.

interface CreateGroupRequest {
  name: string;
  owner_agreement_id: string;
  policy: GroupPolicy;
  initial_members?: string[];
  founder_signature: Signature;
}

Join Group

Agreement requests to join existing group.

interface JoinGroupRequest {
  agreement_id: string;
  group_id: string;
  role?: string;
  delegation_proofs?: Proof[];
}

Token Operations

Create Token

Generates token from event stream.

interface CreateTokenRequest {
  group_id: string;
  series_id: string;
  parent_event_hash: string;
  quantity: number;
  attributes?: Record<string, any>;
  producer_signature: Signature;
  validator_signature?: Signature;
}

Transition Token

Moves token through state machine.

interface TransitionTokenRequest {
  token_id: string;
  event_type: string;
  json_logic_context: object;
  signatures: Signature[];
  referenced_tokens?: string[];
}

Query Token History

Retrieves token state and event chain.

interface QueryTokenHistoryRequest {
  token_id: string;
  include_events?: boolean;
  from_ordinal?: number;
  to_ordinal?: number;
  verify_chain?: boolean;
}

Event Operations

Submit Event

Records new event in activity stream.

interface SubmitEventRequest {
  agreement_id: string;
  activity_type: string;
  signed_data: object;
  sensitive_data?: EncryptedData;
  parent_event_hash: string;
  producer_signature: Signature;
  validator_signature?: Signature;
}

Query Events

Retrieves events matching criteria.

interface QueryEventsRequest {
  agreement_id?: string;
  group_id?: string;
  series_id?: string;
  activity_type?: string;
  from_timestamp?: timestamp;
  to_timestamp?: timestamp;
  limit?: number;
}

Delegation Operations

Create Delegation

Grants permissions to another agreement.

interface CreateDelegationRequest {
  delegator_agreement_id: string;
  delegate_agreement_id: string;
  permissions: string[];
  expires_at: timestamp;
  conditions?: JsonLogicRule;
  delegator_signature: Signature;
}

Revoke Delegation

Cancels existing delegation.

interface RevokeDelegationRequest {
  delegation_id: string;
  reason?: string;
  immediate?: boolean;
  revoker_signature: Signature;
}

Query Delegations

Finds active delegations.

interface QueryDelegationsRequest {
  agreement_id: string;
  direction: 'incoming' | 'outgoing' | 'both';
  permission_type?: string;
  include_expired?: boolean;
}

Trie Operations

Get Trie Root

Retrieves current merkle root.

interface GetTrieRootRequest {
  agreement_id: string;
  trie_type: TrieType;
  block_height?: number;
}

interface GetTrieRootResponse {
  root_hash: string;
  block_height: number;
  timestamp: timestamp;
  metagraph_snapshot: string;
}

Generate Proof

Creates merkle proof for trie element.

interface GenerateProofRequest {
  agreement_id: string;
  trie_type: TrieType;
  path: string;
  as_of_height?: number;
}

interface GenerateProofResponse {
  value: any;
  proof: MerkleProof;
  root_hash: string;
  block_height: number;
}

Verify Proof

Validates merkle proof.

interface VerifyProofRequest {
  proof: MerkleProof;
  expected_root: string;
  path: string;
  value: any;
}

Transaction Processing

Submit Transaction

Processes state change with validation.

interface SubmitTransactionRequest {
  update: TransactionUpdate;
  current_state_hash: string;
  proofs: Proof[];
  metagraph_fee?: number;
}

interface SubmitTransactionResponse {
  success: boolean;
  new_state?: State;
  new_trie_roots?: TrieRoot[];
  generated_events?: Event[];
  error?: string;
  metagraph_tx_hash?: string;
}

Subscription Operations

Subscribe to Events

Real-time event streaming.

interface SubscribeRequest {
  filters: {
    agreement_ids?: string[];
    group_ids?: string[];
    event_types?: string[];
    delegated_access?: DelegationProof;
  };
  from_timestamp?: timestamp;
  include_historical?: boolean;
}

// Returns WebSocket connection or SSE stream

Subscribe to State Changes

Monitor trie updates.

interface StateSubscriptionRequest {
  agreement_id: string;
  trie_types: TrieType[];
  paths?: string[];  // Specific paths to watch
  delegation_proof?: DelegationProof;
}

Utility Operations

Validate Policy

Checks policy consistency.

interface ValidatePolicyRequest {
  group_policy: GroupPolicy;
  series_policy?: SeriesPolicy;
  test_scenarios?: TestCase[];
}

interface ValidatePolicyResponse {
  valid: boolean;
  conflicts?: string[];
  unreachable_states?: string[];
  suggestions?: string[];
}

Estimate Transaction

Previews transaction effects.

interface EstimateTransactionRequest {
  transaction: TransactionUpdate;
  current_state: State;
  include_side_effects?: boolean;
}

interface EstimateTransactionResponse {
  would_succeed: boolean;
  state_changes: StateDiff;
  generated_events: Event[];
  affected_tries: TrieType[];
  validation_details: object;
}

Error Codes

Standard error responses:

enum ErrorCode {
  // Validation errors
  INVALID_SIGNATURE = 'INVALID_SIGNATURE',
  UNAUTHORIZED = 'UNAUTHORIZED',
  INVALID_STATE_TRANSITION = 'INVALID_STATE_TRANSITION',
  POLICY_VIOLATION = 'POLICY_VIOLATION',
  
  // State errors
  AGREEMENT_NOT_FOUND = 'AGREEMENT_NOT_FOUND',
  TOKEN_NOT_FOUND = 'TOKEN_NOT_FOUND',
  STALE_STATE = 'STALE_STATE',
  
  // Delegation errors
  DELEGATION_EXPIRED = 'DELEGATION_EXPIRED',
  INSUFFICIENT_PERMISSIONS = 'INSUFFICIENT_PERMISSIONS',
  
  // System errors
  RATE_LIMITED = 'RATE_LIMITED',
  METAGRAPH_ERROR = 'METAGRAPH_ERROR',
  INTERNAL_ERROR = 'INTERNAL_ERROR'
}

Rate Limits

Default limits per agreement:

  • Transactions: 100/minute
  • Queries: 1000/minute
  • Subscriptions: 10 concurrent
  • Proof generation: 50/minute

SDKs

Official SDKs planned for:

  • TypeScript/JavaScript
  • Python
  • Rust
  • Go
  • Java

10_future_work.md

Future Work

This protocol provides a foundation for tokenized event streams with authenticated state management. Several areas warrant future development to enhance capabilities and broaden adoption.

Technical Enhancements

1. Advanced Cryptography

  • Zero-Knowledge Proofs

    • Private state transitions without revealing data
    • Selective disclosure of attributes
    • Aggregate proofs for batch verification
    • zkSNARK/zkSTARK integration
  • Threshold Signatures

    • Multi-party computation for sensitive operations
    • Distributed key generation
    • Social recovery mechanisms
    • Hardware security module integration
  • Homomorphic Encryption

    • Compute on encrypted data
    • Privacy-preserving analytics
    • Secure multi-party aggregation

2. Scalability Solutions

  • State Channels

    • Off-chain transaction batching
    • Instant finality for high-frequency updates
    • Reduced on-chain footprint
  • Sidechains

    • Sport-specific chains
    • Geographic sharding
    • Cross-chain atomic swaps
  • Data Availability Layers

    • Decentralized storage integration
    • IPFS pinning networks
    • Ceramic Network integration

3. Interoperability

  • Cross-Chain Bridges

    • Token portability across ecosystems
    • Unified identity management
    • Cross-chain delegation
  • Standard Protocols

    • W3C DID integration
    • OAuth/OIDC compatibility
    • FHIR for medical data

4. Advanced State Management

  • Versioned Schemas

    • Backward-compatible upgrades
    • Migration tooling
    • Type safety guarantees
  • Conflict Resolution

    • CRDTs for distributed state
    • Automatic merge strategies
    • Dispute resolution protocols

Feature Extensions

1. Enhanced Policy Language

  • Visual Policy Builder

    • Drag-and-drop DFA creation
    • JsonLogic rule templates
    • Simulation environment
  • Formal Verification

    • Model checking for policies
    • Automated security analysis
    • Property-based testing
  • Machine Learning Integration

    • Anomaly detection in event streams
    • Predictive policy suggestions
    • Automated optimization

2. Advanced Token Mechanics

  • Fractional Ownership

    • Divisible NFTs
    • Shared revenue rights
    • Collective governance
  • Dynamic NFTs

    • Stats that update in real-time
    • Evolving artwork/attributes
    • Achievement unlocking
  • Token Composability

    • Combine tokens for new properties
    • Hierarchical token structures
    • Cross-series synthesis

3. Governance Mechanisms

  • DAO Integration

    • On-chain voting for groups
    • Treasury management
    • Proposal systems
  • Reputation Systems

    • Participant scoring
    • Trust networks
    • Stake-weighted influence
  • Automated Compliance

    • Regulatory rule engines
    • Automated reporting
    • Audit trail generation

4. Economic Primitives

  • Automated Market Makers

    • Liquidity pools for tokens
    • Price discovery mechanisms
    • Yield generation
  • Bonding Curves

    • Dynamic pricing for scarce assets
    • Creator economies
    • Fan token mechanics
  • Prediction Markets

    • Performance forecasting
    • Event outcome trading
    • Information aggregation

Domain Expansions

1. Esports Integration

  • Tournament management
  • Stream verification
  • Prize distribution
  • Player contracts

2. Entertainment Rights

  • Music royalty tracking
  • Film/TV residuals
  • Content licensing
  • Merchandise rights

3. Healthcare Expansion

  • Clinical trial management
  • Insurance claim processing
  • Medical credentialing
  • Research data sharing

4. Education Credentials

  • Verifiable diplomas
  • Skill certifications
  • Learning pathways
  • Peer assessment

5. Supply Chain

  • Provenance tracking
  • Quality assurance
  • Sustainability metrics
  • Fair trade verification

Infrastructure Improvements

1. Developer Experience

  • CLI Tools

    • Scaffold projects
    • Deploy contracts
    • Manage policies
  • IDE Integration

    • Syntax highlighting
    • Lint rules
    • Debuggers
  • Testing Frameworks

    • Unit test helpers
    • Integration test suites
    • Load testing tools

2. Monitoring and Analytics

  • Dashboard Templates

    • Real-time metrics
    • Custom visualizations
    • Alert configuration
  • Data Pipeline

    • ETL for analytics
    • Data warehouse integration
    • BI tool connectors

3. Security Enhancements

  • Penetration Testing

    • Automated vulnerability scanning
    • Bug bounty programs
    • Security audit trails
  • Key Management

    • HSM integration
    • Key rotation protocols
    • Recovery procedures

Research Directions

1. Privacy Research

  • Differential privacy budgets
  • Secure enclaves
  • Confidential computing
  • Privacy-preserving ML

2. Consensus Mechanisms

  • Sport-specific consensus
  • Reputation-based validation
  • Energy-efficient alternatives

3. Token Economics

  • Optimal royalty structures
  • Incentive alignment
  • Market stability mechanisms

4. Legal Frameworks

  • Smart legal contracts
  • Dispute resolution protocols
  • Regulatory compliance automation

Community Building

1. Open Source Initiatives

  • Core protocol development
  • Reference implementations
  • Community governance

2. Standards Bodies

  • Protocol specifications
  • Interoperability standards
  • Best practices documentation

3. Education Programs

  • Developer certification
  • Business case studies
  • Academic partnerships

4. Ecosystem Funds

  • Developer grants
  • Integration bounties
  • Research funding

Conclusion

The tokenized event-stream protocol represents a paradigm shift in how we model and manage complex multi-party relationships. By combining cryptographic commitments, declarative policies, and authenticated state management, it enables use cases previously impossible or impractical.

As the ecosystem matures, we expect to see:

  • Emergent token economies around sports data and fan engagement
  • New business models for athlete compensation and data rights
  • Enhanced privacy while maintaining verifiability and compliance
  • Global interoperability across sports, leagues, and platforms

The protocol's true power lies not in any single feature, but in how simple primitives compose into sophisticated systems. By maintaining this compositional philosophy while adding capabilities, we can build the foundation for the next generation of sports technology and beyond.

Join us in building this future at: [github.com/constellation-labs/tokenstream-protocol]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment