Filament Technical Documentation

Introduction

Filament is a decentralized protocol for token distribution that aligns incentives between token issuers and recipients. The protocol coordinates Campaigners, Delegates, and Indexers through a series of smart contracts and state machines distributed across Layer 1 and Layer 2 networks.

This documentation provides comprehensive technical details for developers looking to understand, integrate with, or contribute to the Filament protocol.

Documentation Structure

1. Core Components

The protocol consists of three main components working together to enable secure and efficient token distribution:

  • Control - Smart contract deployed on L1 manage staking and bonding
  • Filament Hub - A Layer 2 state machine that coordinates campaigns, processes votes, and manages state transitions
  • Outposts - Smart contracts deployed on various chains that handle token operations and distributions
  • Relayer - Infrastructure ensuring reliable cross-chain message delivery and state synchronization

2. Campaign Protocol

The Campaign Protocol defines how campaigns execute through five distinct phases:

  1. Init - Campaign setup and delegate election
  2. Criteria - Collaborative development of distribution criteria
  3. Publish - Data collection and validation
  4. Distribution - Reward allocation decisions
  5. Settle - Final distribution and campaign completion

The next phase of the protocol with better guarentees is defined in Campaign Protocol v1

3. Economics

The Economics describes the token economics and incentive mechanisms:

  • $FILA Token - Native network token used for staking and bonds
  • $FILUM - Computational gas token for the Filament Hub
  • Campaign Bonds - Security deposits ensuring campaign completion
  • Commission Structure - Reward system for delegate participation
  • Treasury Window - Facility for reliable FILA acquisition

Key Concepts

Campaign Execution

Campaigns progress through predefined phases with clear state transitions and validation requirements. The protocol ensures campaigns always terminate, either through successful completion or controlled failure modes.

Economic Security

The protocol uses various economic mechanisms to ensure secure operation:

  • Staking requirements for delegates and indexers
  • Campaign bonds from campaigners
  • Commission rewards for participation
  • Slashing for misbehavior

Cross-chain Architecture

Filament operates across multiple chains through:

  • Layer 2 optimization for cheap and verifaible storage of segment data
  • Smart contracts for token operations
  • Relayer network for message passing
  • Proof validation for security

Getting Started

  1. Review the Core Components documentation to understand the system architecture
  2. Study the Campaign Protocol to learn how campaigns execute
  3. Understand the Economic Model for incentive mechanisms

Additional Resources

Support

For technical support and questions:

  • Join our Telegram
  • Email: support@filament.network

Core Components

The Filament protocol consists of four main components working together to enable secure and decentralized token distribution campaigns: the Filament Hub, Control system, Outposts, and Relayer network. Each component plays a critical role in maintaining the protocol’s security, coordination, and cross-chain functionality.

  • Filament Hub: A layer 2 state machine that coordinates campaign execution, delegate governance, and cross-chain communication. It manages campaign lifecycles and processes delegate votes to achieve consensus on distribution criteria.

  • Control System: A set of Ethereum smart contracts managing the economic security through FILA token staking, delegation mechanics, and voting power. It includes the staking contract, voting vault, and delegate registry.

  • Outposts: Smart contracts deployed on various chains that handle the financial aspects of campaigns, including budget management and reward distribution. Each outpost maintains alignment with the Hub while providing chain-specific distribution mechanics.

  • Paymster: The Paymaster contract is the component responsible for managing funds and executing payments within the Filament protocol. It acts as a secure intermediary between the Filament Hub (on a Layer 2) and on-chain assets (FILA and USDC) on Ethereum (Layer 1). The Paymaster handles campaign bonds, facilitates interactions with the Treasury Window, and generates proofs of payment for verification by the Filament Hub, ensuring secure and reliable transactions.

  • Relayer Network: A decentralized network of relayers that bridge communication between the Hub, Control system, and Outposts. Relayers monitor network states, synchronize information, and ensure proper execution of cross-chain operations.

Together, these components create a comprehensive system for executing token distribution campaigns while maintaining security, decentralization, and cross-chain interoperability. The following sections detail each component’s architecture, functionality, and interaction with the broader system.

Filament Hub

The Filament Hub serves as the central coordination point for token distribution campaigns, implemented as a specialized layer 2 state machine. Its primary purpose is to orchestrate the interaction between campaigners, delegates, and indexers in a trustless manner, ensuring that token distributions follow agreed-upon criteria while maintaining economic security through the bond mechanism. The Hub manages campaign lifecycles, processes delegate votes to achieve consensus, and coordinates with outposts through a network of relayers.

Campaign Lifecycle Management

At its core, the Hub enforces a strict state machine that guides campaigns through distinct phases: Draft, Init, Criteria, Publish, Indexing, Distribution, and Settlement. Each phase transition requires specific conditions to be met - for example, moving from Init to Criteria requires the campaigner to have locked sufficient bonds, while transitioning from Criteria to Publish requires achieving delegate consensus on distribution criteria. This rigid structure ensures that all participants have clarity about the current state and what actions are permitted.

The Hub also handles failure modes gracefully. If a campaign fails to progress (for example, due to lack of delegate consensus or timeout), it transitions to either Canceled or Rejected states, triggering the settlement phase to handle bond distribution and delegate compensation. This ensures that even failed campaigns have clear resolution paths and that delegates are compensated for their participation.

Delegate Governance

Delegate participation is managed through a sophisticated voting system. During the Criteria and Distribution phases, delegates vote on proposals with voting power derived from their staked FILA tokens. The Hub tracks these votes, calculates quorum, and enforces voting rules such as minimum participation requirements. This voting mechanism is crucial for achieving decentralized consensus on both the criteria for distribution and the final distribution itself.

Economic Coordination

The Hub coordinates the economic aspects of campaigns through interaction with outposts. When state transitions require payments (such as delegate compensation or distribution execution), the Hub queues these payments and validates proof of their execution through relayers. This creates a bridge between the Hub’s state machine and the actual token movements on various chains, ensuring that economic actions are properly sequenced and verified.

TODO: Link to Economics

Cross-Chain Integration

The Hub achieves cross-chain functionality through registered relayers and indexers. Relayers facilitate communication with outposts, ensuring that state transitions in the Hub are properly reflected in token movements across different chains. Indexers, on the other hand, are responsible for materializing campaign criteria into concrete segment data, providing the Hub with verifiable information about which addresses should receive distributions.

TODO: Describe segments TODO: Link to Relayers

Campaign State Management

Each campaign maintains comprehensive state including:

  • Current phase and transition history
  • Delegate participation and voting records
  • Payment queue and settlement status
  • Indexer commitments and segment data
  • Campaign parameters and variables

The Hub represents a crucial innovation in token distribution mechanics, providing a structured yet flexible framework for executing complex distribution strategies while maintaining security and fairness through delegate governance. Its design allows for evolution of distribution strategies while ensuring that all participants operate within a well-defined and economically secure environment.

TODO: Link to campaign protocol

Control

The Filament Control system is the economic backbone of the Filament Hub, managing FILA token staking, delegation, and voting mechanics. At its core, it enables token holders to participate in campaigns through a delegation system that creates economic security while ensuring fair governance. Through a set of smart contracts deployed on Ethereum, the Control system creates the foundation for secure and incentivized participation in the Filament ecosystem.

TODO: Link to source code TODO: Link to contract addresses

The system is built around several key components that work together to manage stake and voting power. The Ethereum Staking Contract serves as the primary custody layer for FILA tokens, while the VotingVault, implementing the ERC4626 standard, manages staking positions and their associated voting power. The Delegate Registry maintains a curated list of approved delegates who can participate in campaign governance. These components are coordinated by the Filament Hub to ensure proper campaign participation and stake management.

The delegation mechanism allows FILA holders to stake their tokens to approved delegates, who then participate in campaign governance on behalf of their delegators. This system creates a two-tiered structure where delegates actively shape campaign outcomes while delegators provide the economic backing through their stakes. Stakes are locked during active campaign participation, with an unbonding mechanism that protects against manipulation by queuing withdrawal requests until all campaign commitments are completed. To maintain system security, staked tokens remain subject to slashing penalties during the unbonding period.

The economic model incentivizes participation through a commission system where successful campaign outcomes result in rewards distributed to both delegates and their delegators. Delegates receive a fixed percentage of commissions, with the remaining portion distributed to delegators proportional to their stake. This structure, combined with slashing penalties for misbehavior or non-participation, creates strong economic incentives for positive participation in the Filament ecosystem.

Outposts

The Outpost manages the financial aspects of campaigns, including budget management, incentive distribution, and fee handling on Neutron. It implements a state machine that tracks campaign progress and ensures proper distribution of rewards according to campaign rules.

Campaign Lifecycle

The contract manages campaigns through several states:

  1. Created -> Initial campaign setup
  2. Funded -> Budget locked and ready for execution
  3. Indexing -> Data collection phase
  4. Attesting -> Verification of conversions
  5. Finished -> Campaign completed successfully
  6. Canceled/Failed -> Terminal states for unsuccessful campaigns

Key Features

Campaign Management

pub struct Campaign {
    pub admin: Addr,
    pub status: CampaignStatus,
    pub budget: Option<CampaignBudget>,
    pub spent: u128,
    pub indexer: Addr,
    pub attester: Addr,
    pub segment_desc: SegmentDesc,
    pub segment_size: u64,
    pub conversion_desc: ConversionDesc,
    pub payout_mech: PayoutMechanism,
    pub ends_at: u64,
    pub fee_claimed: bool,
}

Distribution Mechanics

  • Supports proportional distribution per conversion
  • Handles budget tracking and spending limits
  • Manages fee distribution between indexers, attesters, and protocol

Security Features

  • Role-based access control (admin, indexer, attester)
  • Budget validation and tracking
  • Conversion verification and duplicate prevention
  • Deadline enforcement

The Outpost serves as a critical component in the Filament ecosystem by providing secure and verifiable token distribution mechanics on the Neutron blockchain while maintaining alignment with the Hub’s campaign coordination.

Relayers

The Filament Relayer serves as a bridge between the Ethereum network and the Filament Hub, facilitating cross-chain communication and state synchronization. It monitors both networks and ensures proper coordination of campaign-related activities.

Core Components

1. Network Monitors

  • Block Watcher: Monitors Ethereum blocks for relevant events and state changes
  • Slot Watcher: Tracks Filament Hub slots for campaign progression
  • Account Watcher: Maintains synchronized state of accounts across chains

2. Contract Interfaces

  • FilamentToken: Interacts with the FILA token contract on Ethereum
  • DelegateRegistry: Manages delegate registration and validation
  • Hub Interface: Communicates with the Filament Hub for campaign coordination

3. Event Handling

The relayer processes various events including:

  • Campaign initialization and progression
  • Delegate registration and updates
  • Voting power changes
  • Segment posting and validation

Key Responsibilities

  1. State Synchronization

    • Monitors delegate status on Ethereum
    • Updates voting power in the Hub based on staked positions
  2. Cross-Chain Communication

    • Relays proofs of payment between chains
    • Handles delegate registration across networks
    • Ensures consistent state between Ethereum and the Hub
  3. Security & Validation

    • Verifies transaction signatures
    • Ensures proper authorization for operations
    • Maintains atomic operations across chains

The relayer is crucial for maintaining the trustless bridge between Ethereum’s security and the Filament Hub’s campaign execution capabilities.

Paymaster

The Paymaster contract is a central component of the Filament protocol, responsible for managing funds and ensuring secure and reliable payments between Campaigners, Delegates, and potentially Indexers. It acts as an intermediary between the Filament Hub (on a Layer 2) and on-chain assets (FILA and USDC) on Ethereum (Layer 1). The Paymaster handles campaign bonds, facilitates interactions with the Treasury Window, and generates proofs of payment for verification by the Filament Hub.

Motivation

The Paymaster addresses several key challenges:

  • Security: It provides a secure way to manage funds and execute payments, minimizing the risk of theft or loss.
  • Reliability: It ensures that payments are made correctly and that Delegates are compensated even if a Campaigner abandons a campaign.
  • Gas Abstraction (Partial): While FILUM handles computation costs on the Filament Hub, the Paymaster interacts with Layer 1 assets, and the Campaigner is ultimately responsible for those gas costs.
  • Cross-Layer Communication: It facilitates communication between the Filament Hub (on a Layer 2) and the Ethereum blockchain (Layer 1), where the FILA and USDC tokens reside.
  • Treasury Window Integration: It provides a seamless way for Campaigners to purchase FILA through the Treasury Window and use it for campaign bonds.

Key Concepts

  • Campaign Bond: A deposit of FILA tokens made by a Campaigner before starting a campaign. This bond guarantees Delegate payments. The Paymaster manages these bonds.
  • Watermark: A dynamic value representing the minimum amount of FILA that must remain locked in a Campaigner’s overall bond across all their campaigns. The Paymaster tracks and enforces the watermark.
  • RequestForPayment: A message generated by the Filament Hub, instructing the Paymaster to make a payment. This includes information about the recipient, amount, campaign, and phase.
  • PaymentTransaction: A structure generated by the Paymaster, encapsulating the details of a payment to be made. This is signed by the Campaigner.
  • ProofOfPayment: A cryptographic proof generated by the Paymaster after a payment has been successfully executed. This proof is relayed to the Filament Hub to verify the payment.
  • PaymentConfirmation: An acknowledgment from the Filament Hub that a payment has been processed and the corresponding state transition has been applied.
  • Fund Source: The Paymaster determines the source of funds for a payment:
    • CampaignBond: Funds are deducted from the Campaigner’s campaign-specific bond.
    • FilaBalance: Funds are deducted from the Campaigner’s general FILA balance.
    • TreasuryWindow: Funds are acquired by purchasing FILA with USDC through the Treasury Window.
  • Relayer: Relays messages between the Paymaster and the Filament Hub.

Actors

  • Campaigner: Interacts with the Paymaster to create campaign bonds, make payments, and withdraw funds.
  • Filament Hub: Sends RequestForPayment messages to the Paymaster and verifies ProofOfPayment messages.
  • Paymaster (Smart Contract): Manages funds, executes payments, and generates proofs.
  • Relayer: Facilitates communication between the Filament Hub and the Paymaster.
  • Treasury Window: Provides a mechanism for purchasing FILA with USDC.

Protocol Flow (Simplified)

  1. Campaign Creation:
    • The Campaigner interacts with the Paymaster to create a campaign bond (depositing FILA). This may involve purchasing FILA through the Treasury Window.
  2. Campaign Progression:
    • As the campaign progresses through its phases, the Filament Hub calculates fees and generates RequestForPayment messages.
    • These requests are sent to the Campaigner (off-chain).
  3. Payment Generation:
    • The Campaigner, upon recieving the RequestForPayment, interacts with the Paymaster using generatePaymentTransaction which returns a PaymentTransaction.
    • The Campaigner signs the PaymentTransaction.
  4. Payment Execution:
    • The Campaigner sends the signed PaymentTransaction to the Paymaster’s executePayment function.
    • The Paymaster verifies the signature and checks for sufficient funds.
    • The Paymaster executes the payment, deducting funds from the appropriate source (Campaign Bond, FILA balance, or Treasury Window).
    • The Paymaster generates a ProofOfPayment.
  5. Proof Relaying:
    • A Relayer monitors the Paymaster for ProofOfPayment events.
    • The Relayer relays the ProofOfPayment to the Filament Hub.
  6. Verification and State Transition:
    • The Filament Hub verifies the ProofOfPayment.
    • If the proof is valid, the Filament Hub applies the corresponding state transition (e.g., confirming criteria, confirming segments).
    • The Filament Hub generates and queues PaymentConfirmation.
  7. Confirmation Relaying:
    • A Relayer monitors the Filament Hub’s PaymentConfirmation queue.
    • The Relayer relays PaymentConfirmation back to the Paymaster.

Data Structures

// Paymaster (Solidity)

struct CampaignBond {
    uint256 balance;
    uint256 watermark;
}

struct PaymentTransaction {
    uint256 requestId; // Corresponds to the RequestForPayment nonce
    uint256 campaignId;
    uint8 phase;        // Enum: Criteria, Publish, Distribution
    uint8 message;      // Enum: Commit, Reject
    uint256 amount;
    address from;
    uint256 nonce;
    FundSource fundSource;
}

enum FundSource {
    CampaignBond,
    FilaBalance,
    TreasuryWindow
}

struct ProofOfPayment {
    uint256 requestId;
    uint256 campaignId;
    uint8 phase;
    uint8 message;
    uint256 amount;
    address from;
    uint256 nonce;
    FundSource fundSource;
}

// --- Filament Hub (Rust - Conceptual) ---
struct RequestForPayment {
    campaign_id: u64,
    phase: Phase, // Enum: Criteria, Publish, Distribution
    message: Message, // Enum: Commit, Reject
    amount: u64,
    from: Address, // Campaigner address
    nonce: u64,     // Unique identifier
}

struct RelayedProofOfPayment {
    proof: ProofOfPayment,
    relayer: Address,
}

struct PaymentConfirmation {
    request_id: u64,
    status: PaymentStatus,  // Enum: Confirmed, Failed
    action_result: ActionResult,
}
enum PaymentStatus {
    Confirmed,
    Failed,
}

enum Phase {
    Criteria,
    Publish,
    Distribution,
}

enum Message {
    Commit,
    Reject,
}

Functions (Solidity - Paymaster)

  • addToCampaignBond(uint256 campaignId, uint256 amount): Allows a Campaigner to add FILA to their campaign bond.
  • setCampaignBondWatermark(uint256 campaignId, uint256 watermark): Sets the watermark for a specific campaign. This should only be callable by the Filament Hub (or a trusted administrator).
  • withdrawFromCampaignBond(uint256 campaignId, uint256 amount): Allows a Campaigner to withdraw FILA from their campaign bond, provided the withdrawal does not bring the balance below the watermark.
  • generatePaymentTransaction(RequestForPayment memory request) public view returns (PaymentTransaction memory): Takes a RequestForPayment as input and generates a PaymentTransaction. This function determines the appropriate FundSource.
  • executePayment(PaymentTransaction memory transaction, bytes memory signature): Executes a payment based on a signed PaymentTransaction. Verifies the signature, checks for sufficient funds, performs the transfer, and generates a ProofOfPayment.
  • determineFundSource(...) internal view returns (FundSource): Determines the source of funds for a payment (Campaign Bond, FILA balance, or Treasury Window).
  • receiveBondedFila(address campaigner, uint256 amount): Interface Function, called by the TreasuryWindow to credit FILA to a campaigner’s bond.

Security Considerations

  • Signature Verification: The executePayment function must rigorously verify the Campaigner’s signature on the PaymentTransaction to prevent unauthorized payments.
  • Replay Protection: The nonce field in the RequestForPayment and PaymentTransaction prevents replay attacks (where a valid transaction is submitted multiple times).
  • Watermark Enforcement: The Paymaster must strictly enforce the watermark to ensure that sufficient funds are always available for Delegate payments.
  • Access Control: Functions like setCampaignBondWatermark must have appropriate access control to prevent unauthorized modifications.
  • Safe Math: Use SafeMath (or Solidity 0.8+’s built-in overflow/underflow checks) to prevent arithmetic errors.
  • Oracle Reliability: The Treasury Window integration relies on price oracles. Oracle manipulation must be carefully considered.

Failure Modes and Handling

  • Insufficient Funds: If a Campaigner does not have sufficient funds (in their bond, FILA balance, or through the Treasury Window), the executePayment function will revert. The Filament Hub should handle this failure gracefully (e.g., by transitioning to a failure state).
  • Invalid Signature: If the signature on the PaymentTransaction is invalid, the executePayment function will revert.
  • Relayer Failure: If a Relayer fails to relay a ProofOfPayment or PaymentConfirmation, the system should have mechanisms for retries and eventual consistency.
  • Treasury Window Failure: If the Treasury Window is unavailable or the exchange rate changes unexpectedly, the executePayment function may fail. The system should handle this gracefully.
  • Replay Attacks: Mitigated using nonces.
  • Double Spend: Prevented by atomically executing the payment and generating the ProofOfPayment.

Conclusion

The Paymaster contract is a critical component of the Filament protocol, providing a secure and reliable mechanism for managing funds and executing payments. Its integration with the Filament Hub, Treasury Window, and Relayers ensures a seamless and robust system for decentralized token distributions. The careful consideration of security and failure modes is essential for the proper functioning of the Paymaster.

RPC

The Filament Hub Core API provides REST endpoints for interacting with campaign-related functionality. The primary endpoint /campaigns/{campaign_id} allows clients to retrieve detailed information about a specific campaign by providing its unique identifier.

TODO: Link to API Documentation

Currently, the API supports fetching individual campaign details which includes the campaigner’s address. The endpoint returns a 200 status code with campaign data on success, or a 404 status code if the specified campaign is not found. This API serves as a fundamental interface for applications to query campaign state from the Filament Hub.

The endpoint returns a Campaign object containing:

  • id: A unique identifier for the campaign (uint64)
  • campaigner: The address of the campaign creator
  • phase: Current state of the campaign (one of: Draft, Init, Criteria, Publish, Indexing, Distribution, Settle, Settled, Canceled, or Rejected)
  • title: Campaign name/title
  • description: Detailed campaign description
  • criteria: Distribution criteria specifications
  • evictions: List of evicted delegates
  • delegates: List of participating delegates
  • indexer: Optional address of the assigned indexer

Campaign Protocol V0

I. Overview

The Filament Campaign Protocol v0 is a mechanism for determining the distribution of tokens in a credible and transaprent way. It allows a Campaigner to define a campaign, select Delegates to help determine the distribution criteria, and ultimately distribute tokens to Participants based on those criteria. This simplified v0 version focuses on the core state transitions within the Filament Hub, with some external interactions (like Relayer updates of voting power) simplified or omitted for the testnet. The v0 protocol does not actually distribute funds but instead provides a mechanism for determining the distribution with the expectation that the funds are disbursed out of band. Actors participating are not punishable (slashable) and those are expected to act in good faith. Future version (v1) of the protocol provide much stronger guarentees.

The v1 protocol will include:

  • Full Budget Management: Locking, releasing, and using the budget for payments.
  • Advanced Delegate Selection: Using staking weight, reputation, and randomness.
  • Weighted Voting and Quorum: Votes will be weighted by staking power, and a quorum will be required for proposals to pass.
  • Complete Distribution and Settle Phases: Implementing the logic for determining the final token distribution and making payments.
  • Timeouts: Implementing timeouts for each phase and handling them appropriately.
  • Paymaster and Outpost Integration: Interacting with external contracts for payment management and token distribution.
  • Full Relayer Functionality: Synchronizing state and confirming payments.
  • Slashing: Implementing a mechanism to penalize bad actors (Timeouts).

Learn more about the Campaign Protocol V1

II. Actors

  • Campaigner: The entity initiating and funding the campaign.
  • Delegates: Trusted actors who propose and vote on criteria.
  • Indexers: Actors who provide data (segments) based on the criteria.
  • Relayers: Off-chain services that update voting power information.
  • Protocol (Filament Hub): The core smart contract managing the campaign lifecycle.

III. Data Structures

struct Campaign {
    id: u64,
    campaigner: S::Address,
    phase: Phase,
    title: String,          // Added for usability
    description: String,    // Added for usability
    criteria: Criteria,     // Initial criteria, *not* optional
    evictions: Vec<Eviction<S>>, // Delegates to be evicted
    delegates: Vec<S::Address>, // List of selected Delegates
    indexer: Option<S::Address>, // Registered indexer for the campaign
}

enum Phase {
    Draft,      // Initial phase after creation
    Criteria,   // Delegates propose and vote on criteria
    Publish,    // Indexers submit segments
    Indexing,   // Indexer is gathering data.
    Distribution, // Segments are available.
    // Settle,  // (Not Implemented) Final phase for distribution and cleanup
}
struct Criteria {
    criteria: Vec<Criterion>,
}

struct Criterion {
    dataset_id: String, // e.g., "historical_transactions", "token_balances"
    parameters: HashMap<String, String>, // e.g., {"min_balance": "100", "token_address": "0x..."}
}

struct Eviction<S: Spec> {
	addr: S::Address
}

struct Segment {
    // ... (Structure defined elsewhere, mapping addresses to data)
}

struct CriteriaProposal<S: Spec> {
    campaign_id: u64,
    proposer: S::Address,
    criteria: Criteria,
}

// Simplified VoteOption (could be more complex in the full protocol)
enum VoteOption {
    Yes,
    No
}

IV. Campaign Phases and State Transitions

1. Draft Phase

  • Entry Condition: A Campaigner calls draft_campaign.

  • Purpose: To initialize the basic campaign parameters and select an initial set of Delegates.

  • Actions:

    • Campaigner provides:
      • title: A human-readable title for the campaign.
      • description: A description of the campaign’s goals.
      • criteria: The initial criteria for the campaign. Note: In the simplified protocol, these criteria are required, unlike the full protocol where they are a suggestion.
      • evictions: A list of Delegates to be evicted.
    • The Protocol:
      • Assigns a unique campaign_id.
      • Stores the campaign data.
      • Selects Delegates (simplified logic in testnet - see “Key Differences”).
      • Removes evicted Delegates from the list.
  • State Transition Function:

    fn draft_campaign(
        title: String,
        description: String,
        criteria: Criteria,
        evictions: Vec<Eviction<S>>,
        sender: &S::Address,
        state: &mut impl TxState<S>,
    ) -> Result<u64, Error>;
  • Exit Condition: Campaigner calls init_campaign.

  • Failure Modes:

    • Invalid criteria.
    • Invalid eviction requests (evicting non-proposed delegates).
    • Campaign ID collision (should be prevented by the next_campaign_id counter).

2. Init Phase

  • Entry Condition: Campaigner calls init_campaign.

  • Purpose: To formally start the campaign and transition to the Criteria phase.

  • Actions:

    • The Protocol:
      • Verifies that the caller is the Campaigner.
      • Verifies that the campaign is in the Draft phase.
      • TODO: (Full Protocol) Check and lock the campaign bond.
      • TODO: (Full Protocol) Settle payments for evictions.
  • State Transition Function:

    fn init_campaign(
        campaign_id: u64,
        sender: &S::Address,
        state: &mut impl TxState<S>,
    ) -> Result<(), Error>;
  • Exit Condition: Successful execution of init_campaign. The campaign’s phase is set to Criteria.

  • Failure Modes:

    • Campaign not found.
    • Caller is not the Campaigner.
    • Campaign is not in the Draft phase.

3. Criteria Phase

  • Entry Condition: Campaign is in the Criteria phase.

  • Purpose: For Delegates to propose and vote on the criteria for the distribution.

  • Actions:

    • Delegates call propose_criteria to submit their proposed criteria.
    • Delegates call vote_criteria to vote on proposals (Yes/No). Note: In the v0 protocol, votes are not weighted by staking power, and there is no quorum.
    • Campaigner calls confirm_criteria to select the final criteria. Note: In the v0 protocol, the Campaigner can choose any proposal, regardless of votes.
      • The Campaigner may provide a proposal_id.
    • Campaigner calls reject_criteria to reject the criteria.
  • State Transition Functions:

    fn propose_criteria(
        campaign_id: u64,
        criteria: Criteria,
        sender: &S::Address,
        state: &mut impl TxState<S>,
    ) -> Result<(), Error>;
    
    fn vote_criteria(
        campaign_id: u64,
        option: VoteOption,
        sender: &S::Address,
        state: &mut impl TxState<S>,
    ) -> Result<(), Error>;
    
    fn confirm_criteria(
        campaign_id: u64,
        proposal_id: Option<u64>,
        sender: &S::Address,
        state: &mut impl TxState<S>,
    ) -> Result<(), Error>;
    
    fn reject_criteria(
      campaign_id: u64,
      sender: &S::Address,
      state: &mut impl TxState<S>,
    ) -> Result<(), Error>;
  • Exit Condition: Campaigner calls confirm_criteria (transition to Publish phase) or reject_criteria (transition to Settle).

  • Failure Modes:

    • Campaign not found.
    • Caller is not a Delegate (for propose_criteria and vote_criteria).
    • Caller is not the Campaigner (for confirm_criteria and reject_criteria).
    • Campaign is not in the Criteria phase.

4. Publish Phase

  • Entry Condition: Campaign is in the Publish phase.

  • Purpose: For Indexers to submit data (segments) that match the confirmed criteria.

  • Actions:

    • The Protocol transitions the campaign to the Indexing Phase.
    • Indexer calls post_segment to submit a segment.
  • State Transition Functions:

    fn index_campaign(
        campaign_id: u64,
        sender: &S::Address,
        state: &mut impl TxState<S>,
    ) -> Result<(), Error>;
    
    fn post_segment(
        campaign_id: u64,
        segment: Segment,
        sender: &S::Address,
        state: &mut impl TxState<S>,
    ) -> Result<(), Error>;
  • Exit Condition: Indexer calls post_segment. The campaign phase is changed to Distribution.

  • Failure Modes:

    • Caller is not the registered Indexer.
    • Campaign not found.
    • Campaign is not in the Indexing phase.
    • Segment already exists.

5. Distribution Phase

  • Entry Condition: Campaign is in the Distribution phase.
  • Purpose: Await for the final settlement to happen and mark the campaign as completed.
  • Note: The v0 protocol does not implement the full Distribution phase logic (voting on distributions, alternative proposals).

6. Settle Phase

  • Note: The v0 protocol does not implement the Settle phase.

Indexer and Relayer Management

  • The v0 protocol includes functions for registering and unregistering Indexers and Relayers. These are currently restricted to an admin account.
  • register_indexer, unregister_indexer
  • register_relayer, unregister_relayer
  • Relayers can call update_voting_power to update the voting power of addresses. This is a simplified mechanism for the testnet; the full protocol will involve more robust synchronization with a staking contract.

V. V1 Key Differences

  • Budget Handling: The v0 protocol does not fully handle the campaign budget (locking, releasing, using for payments). This is a placeholder and will be fully implemented in the future with interactions with a Paymaster contract and Outpost contracts.
  • Delegate Selection: The initial delegate selection process is simplified. The full protocol will incorporate staking weight, reputation, and randomness.
  • Eviction Payments: Payments to evicted delegates are not yet implemented.
  • Voting Power: While the system tracks voting power, votes are not currently weighted by this power. Each delegate effectively has one vote. The full protocol will implement weighted voting.
  • Quorum: The concept of a quorum (minimum voting power needed for a proposal to pass) is not implemented in the v0 protocol.
  • Criteria Confirmation: The Campaigner can confirm any proposal, regardless of votes. The full protocol will enforce quorum requirements and allow the Campaigner to provide variables.
  • Publish Phase: The v0 protocol has basic support for Indexers and segments, but does not handle competing segments or disputes.
  • Distribution Phase: The Distribution phase (where the final token allocation is determined) is completely absent in the v0 protocol. This is a major future addition.
  • Settle Phase: The Settle phase (where tokens are distributed and the campaign is finalized) is completely absent in the v0 protocol.
  • Timeouts: Timeouts for each phase are not implemented.
  • Full Relayer Integration: The Relayer’s role is limited to updating voting power. The full protocol will involve the Relayer in synchronizing state and confirming payments.
  • Treasury Window: No interaction with a treasury window for acquiring bonded FILA.
  • Slashing: No mechanism to slash delegators

Campaign Protocol V1

The Campaign Protocol defines how Campaigners, Delegates, and Indexers collaborate to execute campaigns through a series of well-defined phases. Each phase has specific rules, requirements, and state transitions that ensure secure and predictable campaign execution.

The current campaign protocol v0 omits many economic guarentees. Learn more about the Campaign Protocol V0

Campaign Lifecycle

A campaign progresses through five distinct phases:

  1. Init - Campaign setup and delegate election
  2. Criteria - Collaborative development of distribution criteria
  3. Publish - Data collection and validation
  4. Distribution - Reward allocation decisions
  5. Settle - Final distribution and campaign completion

Each phase must complete successfully or timeout before moving to the next phase. The protocol ensures campaigns always terminate in the Settle phase, even in failure cases.

Phase Details

1. Init Phase

  • Purpose: To set up the campaign, define the budget, and select the initial set of Delegates.

  • Actions:

    • Campaigner creates a campaign, providing:
      • budget: The total amount of tokens to be distributed.
      • initial_criteria: A suggestion for the criteria (this is not binding). This helps inform the initial delegate selection.
      • delegate_candidates: A list of potential delegates.
    • The Protocol (Filament Hub) selects a subset of delegate_candidates to be the Delegates for this campaign. The selection process might involve:
      • Staking weight: Delegates with more FILA staked have a higher chance of being selected.
      • Reputation: Delegates with a good track record might be preferred.
      • Randomness: To prevent bias.
    • The Campaigner confirms the selected Delegates. They can choose to evict a limited number of Delegates (paying a fee for each eviction). This allows the Campaigner to have some control over the Delegate set.
  • State Transitions:

    // Campaigner initiates the campaign
    #[authorized(Campaigner)]
    fn init_campaign(budget: Budget, initial_criteria: Criteria, delegate_candidates: Vec<Address>) -> Result<Campaign, Error> {
        // 1. Validate inputs (e.g., sufficient budget, valid addresses)
        // 2. Select Delegates (using staking weight, reputation, randomness)
        // 3. Create Campaign struct
        // 4. Store Campaign in the Hub's state
        // 5. Lock the budget (transfer tokens to the Hub or an escrow contract)
        // 6. Return the new Campaign
    }
    
    // Campaigner confirms the selected Delegates, potentially evicting some
    #[authorized(Campaigner)]
    fn confirm_delegates(campaign_id: u64, delegates_to_evict: Vec<Address>) -> Result<(), Error> {
        // 1. Verify that the Campaigner owns the campaign
        // 2. Verify that the number of evictions is within the allowed limit (MAX_EVICTIONS)
        // 3. Calculate the eviction cost (MIN_DELEGATE_PAYMENT * number of evictions)
        // 4. Deduct the eviction cost from the Campaigner's bond or balance
        // 5. Pay the evicted Delegates
        // 6. Update the Campaign's delegate list
        // 7. Start the Criteria phase timer
    }
  • Failure Modes:

    • Insufficient budget.
    • Invalid delegate candidates.
    • Campaigner tries to evict too many Delegates.
    • Campaigner doesn’t have enough funds to pay eviction fees.
  • Timeout Logic: There might be a timeout for the confirm_delegates step. If the Campaigner doesn’t confirm within the time limit, the campaign could be aborted, and the budget (minus any applicable fees) returned.

2. Criteria Phase

  • Purpose: To determine the rules for the distribution. This is where Delegates use their expertise to decide who should receive tokens and why.

  • Actions:

    • Delegates propose and vote on Criteria. A Criterion might be something like:
      • “Users who have held at least 100 UNI tokens for 6 months.”
      • “Users who have participated in at least 3 governance proposals on Compound.”
      • “Users who have a Gitcoin Grants score above 50.”
    • Delegates can propose different sets of Criteria.
    • Voting is weighted by the Delegates’ staking power (how much FILA they have staked).
    • A Tally object tracks the votes for each proposal. A proposal needs to reach a certain quorum (minimum voting power) to be considered valid.
    • The Campaigner can confirm a proposal that has reached quorum. They can also provide variables to parameterize the criteria (e.g., the specific date for a snapshot).
    • The Campaigner can reject the proposals. This leads to the Settle phase (and likely some penalties).
  • State Transitions:

    // Delegate proposes a set of Criteria
    #[authorized(Delegate)]
    fn propose_criteria(campaign_id: u64, criteria: Criteria) -> Result<u64, Error> { // Returns proposal ID
        // 1. Verify that the Delegate is part of the campaign
        // 2. Create a new Proposal
        // 3. Add the Proposal to the Tally
        // 4. Return the Proposal ID
    }
    
    // Delegate votes on a proposal
    #[authorized(Delegate)]
    fn vote(campaign_id: u64, proposal_id: u64, choice: bool) -> Result<(), Error> {
        // 1. Verify that the Delegate is part of the campaign
        // 2. Verify that the proposal exists
        // 3. Get the Delegate's voting power
        // 4. Update the Tally with the vote
    }
    
    // Campaigner confirms a set of Criteria that has reached quorum
    #[authorized(Campaigner)]
    fn confirm_criteria(campaign_id: u64, proposal_id: u64, variables: HashMap<String, Value>) -> Result<(), Error> {
        // 1. Verify that the Campaigner owns the campaign
        // 2. Verify that the proposal has reached quorum
        // 3. Set the Campaign's criteria to the chosen proposal's criteria
        // 4. Set campaign variables
        // 5. Transition to the Publish phase
        // 6. Start Publish phase timer
    }
    // Campaigner rejects
    #[authorized(Campaigner)]
    fn reject_criteria(campaign_id: u64)-> Result<(),Error>{
        // 1. Verify that the Campaigner owns the campaign
        // 2. Transition to settle phase
    }
    
    // Called by the Protocol when the Criteria phase timer expires
    #[authorized(Protocol)]
    fn timeout_criteria(campaign_id: u64) -> Result<(), Error> {
      // 1. Slash Delegates that did not vote
      // 2. Transition to the settle phase.
    }
  • Failure Modes:

    • No proposal reaches quorum.
    • The Campaigner rejects all proposals.
    • The Criteria phase timer expires.
  • Timeout Logic: If the Criteria phase times out, Delegates who didn’t vote might be slashed, and the campaign transitions to the Settle phase.

3. Publish Phase

  • Purpose: To gather the data that matches the chosen Criteria. This is where Indexers come in.

  • Actions:

    • Based on the confirmed Criteria, the Protocol assigns specific data-gathering tasks to Indexers. For example, one Indexer might be responsible for gathering data about Uniswap holders, while another might focus on Compound governance participants.
    • Indexers submit Segments. A Segment is a list of addresses (and associated data) that meet a specific Criterion.
    • Multiple Indexers might submit competing Segments for the same Criterion.
    • The Campaigner confirms the Segments they believe are correct. This involves resolving any disputes between competing Indexers.
  • State Transitions:

    // Indexer publishes a Segment
    #[authorized(Indexer)]
    fn publish_segment(campaign_id: u64, criterion_index: u64, segment: HashMap<Address, u256>) -> Result<(), Error> {
        // 1. Verify that the Indexer is assigned to this campaign and criterion
        // 2. Verify the segment data (e.g., check for duplicates, invalid addresses)
        // 3. Store the Segment
    }
    
    // Campaigner confirms the segments
    #[authorized(Campaigner)]
    fn confirm_segments(campaign_id: u64, resolution: HashMap<u64, Address>) -> Result<(), Error>{ // criterion index -> selected indexer address
        // 1. Verify the Campaigner
        // 2. Verify segment choices (no duplicates, valid indexers)
        // 3. Transition to the distribution phase.
    }
        // Called by the Protocol when the Publish phase timer expires
    #[authorized(Protocol)]
    fn timeout_publish(campaign_id: u64) -> Result<(), Error> {
        // 1. Slash indexers that did not submit their assigned work.
        // 2. Transition to the settle phase.
    }
    
  • Failure Modes:

    • Indexers fail to submit their assigned Segments.
    • The Campaigner doesn’t confirm the Segments.
    • The Publish phase timer expires.
  • Timeout Logic: If the Publish phase times out, Indexers who didn’t submit their assigned data might be slashed, and the campaign transitions to the Settle phase.

4. Distribution Phase

  • Purpose: To determine the final allocation of tokens to participants, based on the confirmed Criteria and Segments.

  • Actions:

    • The Protocol calculates a proposed Distribution based on the confirmed Criteria and Segments. This is a mapping of addresses to token amounts.
    • Delegates vote on the proposed Distribution. They can also propose alternative distributions.
    • The Campaigner confirms a Distribution that has reached quorum.
    • The Campaigner can reject the proposed Distribution. This leads to the Settle phase.
  • State Transitions:

    // Delegate votes on the proposed Distribution
    #[authorized(Delegate)]
    fn vote_distribution(campaign_id: u64, proposal_id: u64, choice: bool) -> Result<(), Error> {
        // Similar to the vote function in the Criteria phase
    }
    // Delegate propose a set of Distributions
    #[authorized(Delegate)]
    fn propose_distribution(campaign_id: u64, distribution: Distribution) -> Result<u64, Error> { // Returns proposal ID
        // 1. Verify that the Delegate is part of the campaign
        // 2. Create a new Proposal
        // 3. Add the Proposal to the Tally
        // 4. Return the Proposal ID
    }
    
    // Campaigner confirms a Distribution
    #[authorized(Campaigner)]
    fn confirm_distribution(campaign_id: u64, proposal_id: u64) -> Result<(), Error> {
        // 1. Verify Campaigner
        // 2. Verify that the proposal has reached quorum
        // 3. Set the Campaign's distribution
        // 4. Transition to the Settle phase
    }
    
    // Campaigner rejects
    #[authorized(Campaigner)]
    fn reject_distribution(campaign_id: u64)-> Result<(),Error>{
        // 1. Verify that the Campaigner owns the campaign
        // 2. Transition to settle phase
    }
        // Called by the Protocol when the Distribution phase timer expires
    #[authorized(Protocol)]
    fn timeout_distribution(campaign_id: u64) -> Result<(), Error> {
      // 1. Slash Delegates that did not vote
      // 2. Transition to the settle phase.
    }
    
  • Failure Modes:

    • No proposal reaches quorum.
    • The Campaigner rejects the proposed Distribution.
    • The Distribution phase timer expires.
  • Timeout Logic: If the Distribution phase times out, Delegates who didn’t vote might be slashed, and the campaign transitions to the Settle phase.

5. Settle Phase

  • Purpose: To finalize the campaign, distribute the tokens, and release any remaining resources.
  • Actions:
    • The Protocol makes payments to:
      • Participants (according to the confirmed Distribution).
      • Delegates (their commission).
      • Indexers (their payment for providing data).
    • Any remaining funds from the budget (e.g., if the distribution didn’t use the entire budget) are returned to the Campaigner.
    • The Campaigner’s bond is released (if they had to post a bond).
    • The campaign is marked as complete.
  • State Transitions
    // This function might be called automatically by the Protocol after the Distribution phase
    fn settle_campaign(campaign_id: u64) -> Result<(), Error> {
        // 1. Verify that the campaign is in the Distribution phase
        // 2. Make payments to Participants, Delegates, and Indexers
        // 3. Return any remaining funds to the Campaigner
        // 4. Release the Campaigner's bond
        // 5. Mark the campaign as complete
    }
    // The state machine receives settlement messages confirming that payments have been processed
    #[authorize(Protocol)]
    fn clear(campaign_id: u64, payment: Payment) -> Result<(),Error>{
        // 1. verify payment information
        // 2. update payment status.
    }
  • Failure Modes:
    • Payment failures (e.g., insufficient funds in the Outpost contract). This is a critical area and needs robust error handling and retry mechanisms.
  • Timeout Logic: There might be a timeout for the Settle phase, but the primary concern here is ensuring that all payments are made correctly.

IV. Key Mechanisms

  • Voting: Weighted by staking power. Delegates with more FILA staked have more influence.
  • Quorum: A minimum amount of voting power is required for a proposal to be considered valid. This prevents a small number of Delegates from controlling the outcome.
  • Slashing: Delegates and Indexers can be penalized for misbehavior (e.g., not voting, providing incorrect data).
  • Timeouts: Each phase has a time limit. If the phase doesn’t complete within the time limit, the campaign might be aborted, and penalties might be applied.
  • Relayers: Ensure that state is synchronized between the Filament Hub (on a Layer 2) and Outposts (on Layer 1 chains). This is crucial for ensuring that payments are made correctly.
  • Paymaster: A contract that manages payments, potentially using a Campaign Bond and the Treasury Window to provide FILA for campaign operations.

V. Example Scenario

Let’s say a project called “AwesomeFi” wants to distribute their token, $AWESOME, to users who have provided liquidity to their Uniswap V3 pool.

  1. Init: AwesomeFi creates a campaign on the Filament Hub, specifying a budget of 1 million $AWESOME tokens. They propose some initial criteria (e.g., “users who have provided at least $1000 of liquidity”). A set of Delegates is selected.
  2. Criteria: The Delegates refine the criteria. They might add criteria like “users who have provided liquidity for at least 3 months” or “users who have also staked $AWESOME in our governance contract.” They vote on these criteria, and the winning set of criteria is confirmed by AwesomeFi.
  3. Publish: Indexers gather data about Uniswap V3 liquidity providers and submit Segments to the Filament Hub.
  4. Distribution: The Protocol calculates a proposed distribution based on the confirmed criteria and segments. Delegates vote on this distribution, and AwesomeFi confirms it.
  5. Settle: The 1 million $AWESOME tokens are distributed to the eligible users via an Outpost contract on Ethereum. Delegates and Indexers receive their payments.

Economics

The Filament protocol’s economic model is designed to incentivize participation, ensure the security and reliability of the system, and align the interests of all actors: Campaigners, Delegates, Indexers, and Participants. This section provides an overview of the key economic components and mechanisms within Filament.

Core Principles

  • Incentivized Participation: All actors in the system are economically incentivized to contribute positively. Delegates and Indexers are rewarded for their work, and Campaigners benefit from successful token distributions.
  • Security through Staking: FILA, the native token, is used for staking. Staking provides economic security, as misbehavior can result in slashing (loss of staked tokens).
  • Sybil Resistance: FILUM, a non-transferable gas token, prevents spam and ensures fair access to the Filament Hub’s computational resources. Campaign bonds also provide Sybil resistance at the campaign level.
  • Sustainable Operations: The system is designed to be self-sustaining, with fees and commissions providing ongoing funding for operations and development.
  • Price Stability for Campaigners: The Treasury Window provides a predictable price for acquiring FILA, protecting Campaigners for volatility.

Key Economic Components

The Filament economic model comprises the following key elements:

1. $FILA Token

FILA is the native token of the Filament network. It serves multiple critical roles:

  • Staking: Delegates stake FILA to gain voting power and participate in campaigns. Their rewards are proportional to their stake.
  • Bonding: Campaigners can use FILA for campaign bonds, providing a security deposit that guarantees delegate payments even if the campaign is abandoned.
  • Governance: FILA may be used for governance of the Filament protocol itself (details to be determined).
  • Medium of Exchange: Payment for Indexers and Delegates services.

Learn more about the FILA Token

2. $FILUM (Gas Token)

FILUM is a non-transferable gas token used to pay for computation on the Filament Hub. It provides Sybil resistance and prevents spam.

  • Non-Transferable: FILUM cannot be bought, sold, or transferred between users.
  • Periodic Allocation: Users with a minimum FILA bond receive a periodic allocation of FILUM.
  • Usage-Based Consumption: FILUM is consumed when interacting with the Filament Hub (e.g., creating campaigns, voting, submitting data).
  • Prevents Spam: By requiring FILUM, the protocol avoids spam by malicious actors who would have unlimited requests.

Learn more about FILUM

3. Campaign Bonds

Campaign Bonds are a crucial security mechanism in Filament. They ensure that Delegates are compensated for their work, even if a Campaigner abandons a campaign.

  • Security Deposit: Campaigners deposit FILA as a bond before starting a campaign.
  • Delegate Payment Guarantee: The bond guarantees a minimum payment to each Delegate, even if the campaign fails.
  • Slashing: If a campaign fails due to Campaigner inaction (e.g., not confirming criteria), a portion of the bond may be slashed and distributed to Delegates.
  • Watermark: A mechanism to ensure sufficient funds remain locked in the bond.

Learn more about Campaign Bonds

4. Commission Structure

The Commission Structure defines how Delegates are rewarded for their participation in campaigns.

  • Proportional to Voting Power: Delegates receive a commission based on their voting power (which is proportional to their staked FILA).
  • Incentivizes Participation: Delegates must actively participate (vote) to be eligible for rewards.
  • Delegator Rewards: A portion of the Delegate’s commission is distributed to users who have delegated their FILA to that Delegate.
  • Proposals: Delegates who provide winning proposals may earn additional rewards.

Learn more about the Commission Structure

5. Treasury Window

The Treasury Window provides a mechanism for Campaigners to acquire FILA at a predictable price, even if market liquidity is low.

  • Stable Price: The Treasury Window offers FILA at a controlled exchange rate (likely based on a time-weighted average price, TWAP, plus a discount).
  • USDC Exchange: Campaigners can purchase FILA using USDC.
  • Controlled Supply: The Treasury Window helps manage the supply of FILA in circulation.
  • Discount: The Treasury Window provides a discount on FILA, incentivizing campaign creation.

Learn more about the Treasury Window

Interactions and Flows

These economic components interact in various ways:

  1. Staking: Users stake FILA to become Delegates or to delegate to existing Delegates.
  2. Campaign Creation: Campaigners bond FILA (potentially acquired through the Treasury Window) to create a campaign.
  3. Voting: Delegates use their voting power (proportional to their stake) to vote on criteria and distributions.
  4. Commission Distribution: Delegates (and their delegators) receive commissions based on their participation and voting power.
  5. Gas Consumption: Users consume FILUM when interacting with the Filament Hub.
  6. Slashing: Campaigners, Delegates and Indexers may be slashed for misbehavior or inaction.

This economic model is designed to create a robust and self-sustaining ecosystem for decentralized token distributions. The interplay of these mechanisms ensures that all actors are incentivized to act in the best interests of the network and its users.

$FILA Token

FILA is the native token of the Filament network, and it plays a central role in the protocol’s operation, security, and governance. It serves as the primary mechanism for incentivizing participation, aligning interests, and ensuring the long-term health of the ecosystem.

Key Functions

FILA has several key functions within the Filament protocol:

  1. Staking:

    • Delegates: Users who wish to become Delegates (and participate in campaign governance) must stake FILA. A Delegate’s voting power is directly proportional to the amount of FILA they have staked. This “stake-weighted voting” ensures that those with more at stake have a greater influence on campaign outcomes.
    • Delegators: Users who don’t want to run a Delegate node themselves can delegate their FILA to an existing Delegate. This increases the Delegate’s voting power and allows the delegator to earn a portion of the Delegate’s rewards (commission).
    • Security: Staking FILA provides economic security for the network. Delegates are incentivized to act honestly because misbehavior can result in slashing – the loss of a portion of their staked FILA (and their delegators’ FILA).
  2. Bonding:

    • Campaign Bonds: Campaigners (those who create token distribution campaigns) can use FILA to create campaign bonds. These bonds serve as a security deposit, guaranteeing that Delegates will be paid even if the Campaigner abandons the campaign. This prevents malicious or negligent Campaigners from wasting Delegates’ time and resources. Bonds can be created using existing FILA or purchased using the Treasury Window.
    • Sybil Resistance: Bonds create a disincentive for creating multiple campaigns.
  3. Medium of Exchange:

    • Payments: Indexers receive payments in FILA, and delegates receive a portion of their commission in FILA
  4. Governance (Future):

    • FILA is intended to be used for governance of the Filament protocol itself. This could involve voting on protocol upgrades, parameter changes (e.g., commission rates, slashing penalties), and other decisions that affect the network’s operation. The specific governance mechanisms are still under development.

Token Supply and Distribution

  • Fixed Supply: FILA has a fixed total supply. This means that no new FILA will be created beyond the initial allocation. This scarcity is designed to maintain the token’s value over time. (Note: The exact total supply needs to be specified.)
  • Initial Distribution: The initial distribution of FILA will likely involve several components:
    • Team and Advisors: A portion allocated to the team and advisors who developed the protocol.
    • Early Investors: A portion allocated to early investors who provided funding.
    • Community Incentives: A significant portion allocated to incentivizing early participation in the network (e.g., staking rewards, airdrops to early users). This may include allocations to early Campaigners, Delegates, and Indexers.
    • Treasury: A portion held in a treasury to fund ongoing development, marketing, and other initiatives. This treasury may be managed by a DAO (Decentralized Autonomous Organization) controlled by FILA holders.
  • No Inflation: Unlike many proof-of-stake networks that use inflation to reward stakers, Filament does not have ongoing FILA emissions. Staking rewards (commissions) come from fees paid by Campaigners, not from newly created tokens. The treasury window functions as a money multiplier.

Tokenomics and Value Accrual

The value of FILA is expected to accrue through several mechanisms:

  • Demand for Staking: As more users want to become Delegates or delegate their tokens, the demand for FILA will increase.
  • Demand for Bonding: As more Campaigners use the Filament protocol to distribute tokens, the demand for FILA to create campaign bonds will increase.
  • Network Effects: As the Filament network grows and attracts more users, the utility of FILA (for staking, governance, and potentially other uses) will increase.
  • Scarcity: The fixed supply of FILA means that increased demand should, in theory, lead to an increase in price.
  • Governance Rights: The ability to participate in governance decisions gives FILA holders a say in the future direction of the protocol, adding intrinsic value.

Risks

  • Price Volatility: Like all cryptocurrencies, FILA is subject to price volatility.
  • Smart Contract Risk: There is always a risk of bugs or vulnerabilities in the smart contracts that govern FILA and the Filament protocol.
  • Adoption Risk: The success of FILA depends on the adoption of the Filament protocol. If the protocol does not attract enough users, the demand for FILA may be limited.

Conclusion

FILA is the lifeblood of the Filament ecosystem. Its carefully designed tokenomics aim to create a sustainable and valuable network, aligning the incentives of all participants and fostering a robust platform for decentralized token distributions. The fixed supply, staking mechanisms, and governance rights are all intended to drive long-term value accrual for FILA holders.

$FILUM (Gas Token)

FILUM is a non-transferable gas token used to pay for computation on the Filament Hub. It plays a crucial role in preventing spam and ensuring fair access to the Hub’s resources. Unlike FILA, the network’s native token, FILUM cannot be bought, sold, or transferred between users. It is solely used internally to measure and limit resource consumption.

Key Features

  • Non-Transferable: FILUM is not a typical cryptocurrency. It cannot be traded on exchanges or sent between wallets. This is a critical design choice that prevents the creation of a secondary market for FILUM and ensures its sole purpose is to pay for computation.
  • Periodic Allocation: Users who have a minimum amount of FILA bonded in their account receive a periodic allocation of FILUM. This allocation replenishes automatically, allowing active users to interact with the Hub without needing to acquire FILUM externally. The allocation are not cumulative.
  • Usage-Based Consumption: Every interaction with the Filament Hub that requires computation (e.g., creating a campaign, submitting a proposal, voting, posting a segment) consumes a certain amount of FILUM. The amount of FILUM consumed depends on the complexity of the operation.
  • Sybil Resistance: Because acquiring FILUM requires bonding FILA, and FILUM itself is non-transferable, it becomes economically infeasible for malicious actors to spam the network with a large number of requests. This protects the Hub’s resources and ensures fair access for legitimate users.
  • Prevents Denial-of-Service: FILUM limits the rate at which users can interact with the Hub, preventing denial-of-service (DoS) attacks that could overwhelm the system.

How FILUM Works

  1. Bonding FILA: To be eligible for FILUM, users must have a minimum amount of FILA bonded in their account. This bond demonstrates a commitment to the network and helps prevent Sybil attacks. The specific minimum bond amount (MIN_BOND) is a governance parameter.
  2. Periodic Allocation: Every epoch (a defined period, e.g., 24 hours), eligible users receive a fixed amount of FILUM. This amount (FILUM_EMISSIONS) is also a governance parameter. The amount is set to provide a reasonable number of interactions.
  3. Maximum Balance: There is a maximum limit on the amount of FILUM an account can hold (MAX_FILUM_BALANCE). This prevents users from hoarding FILUM and ensures a fair distribution.
  4. Consumption: When a user interacts with the Hub, the required FILUM is deducted from their balance. If a user does not have enough FILUM, the transaction will fail.
  5. Replenishment: At the start of each epoch, eligible users’ FILUM balances are replenished up to the MAX_FILUM_BALANCE. Any unused FILUM from the previous epoch is effectively “lost” (it does not accumulate).

Governance Parameters

The following parameters, which are subject to change through governance, control the FILUM mechanism:

  • MIN_BOND: The minimum amount of FILA that must be bonded to be eligible for FILUM allocations.
  • FILUM_EMISSIONS: The amount of FILUM allocated to eligible users each epoch.
  • MAX_FILUM_BALANCE: The maximum amount of FILUM an account can hold.
  • EPOCH_LENGTH: The duration of an epoch (e.g., 24 hours).

Example

Let’s say:

  • MIN_BOND = 100 FILA
  • FILUM_EMISSIONS = 50 FILUM
  • MAX_FILUM_BALANCE = 50 FILUM
  • EPOCH_LENGTH = 24 hours

A user who has 150 FILA bonded would receive 50 FILUM at the start of each epoch. If they use 20 FILUM during the day, their balance will be 30 FILUM. At the start of the next epoch, their balance will be replenished back to 50 FILUM (not 80 FILUM). A user who has only 50 FILA bonded would not receive any FILUM.

Why a Separate Gas Token?

Using a separate, non-transferable gas token like FILUM offers several advantages over using FILA directly for gas:

  • Price Stability: The cost of interacting with the Hub is not directly tied to the price of FILA, which can be volatile. This makes it easier for users to predict and budget for their interactions.
  • Prevents Hoarding: Because FILUM is non-transferable and replenishes periodically, there is no incentive to hoard it. This ensures a fair distribution and prevents a small number of users from monopolizing access to the Hub.
  • Simplified User Experience: Users don’t need to worry about acquiring FILUM on the open market. As long as they have a sufficient FILA bond, they will automatically receive enough FILUM to interact with the Hub.

Conclusion

FILUM is a vital component of the Filament protocol, providing a robust and user-friendly mechanism for managing computational resources and preventing abuse. Its non-transferable nature and periodic allocation ensure fair access and prevent the creation of a secondary market, keeping its focus solely on its intended purpose: paying for computation on the Filament Hub.

Commission Structure

The Filament protocol uses a sophisticated commission structure to reward Delegates for their participation in campaigns and, crucially, to incentivize them to make decisions that lead to positive economic outcomes. This structure combines a base commission with a mechanism based on the Vickrey-Clarke-Groves (VCG) auction, ensuring that Delegates are rewarded proportionally to their contribution to the campaign’s success.

I. Base Commission

The base commission provides a fundamental reward for Delegate participation, regardless of the specific economic outcome of the campaign. This ensures that Delegates are compensated for their time and effort in reviewing proposals and casting votes.

  • Eligibility: To be eligible for the base commission, Delegates must participate in the relevant voting phases of the campaign (Criteria and, in the full protocol, Distribution). Delegates who fail to vote may be slashed (although slashing is not implemented in the simplified testnet version).
  • Calculation:
    • The total commission for a campaign is calculated as: median_campaign_reward * COMMISSION_MULTIPLE.
      • median_campaign_reward: The median reward received by Participants in the campaign. This ties the Delegate commission to the overall scale of the distribution. This is calculated after the Distribution phase.
      • COMMISSION_MULTIPLE: A protocol-wide parameter (set by governance) that determines the overall size of the commission pool.
    • This total commission pool is then divided among the eligible Delegates proportional to their voting power. A Delegate’s voting power is determined by the amount of FILA they have staked (and any FILA delegated to them).
  • Delegator Share: Delegates keep a portion of the commission (DELEGATE_COMMISSION_CARVEOUT) and distribute the rest to users that delegated their FILA to them.

Example:

  • median_campaign_reward = 1000 tokens
  • COMMISSION_MULTIPLE = 0.1 (10%)
  • Total Commission Pool = 1000 * 0.1 = 100 tokens
  • Delegate A has 20% of the total voting power.
  • Delegate A’s base commission = 100 tokens * 0.2 = 20 tokens.
  • DELEGATE_COMMISSION_CARVEOUT = 0.2 (20%)
  • Delegate A keeps = 20 tokens * 0.2 = 4 tokens
  • Delegate A distributes = 20 - 4 = 16 tokens, to delegators

II. VCG Mechanism (Incentivizing Economic Outcomes)

The core innovation of Filament’s commission structure is the integration of a VCG (Vickrey-Clarke-Groves) mechanism. The VCG mechanism is a type of auction designed to incentivize truthful revelation of preferences. In Filament’s context, this means incentivizing Delegates to vote for criteria and distributions that maximize the economic value generated by the campaign.

A. Defining the Economic Metric (VG)

Each campaign defines an economic metric (V_G) that the Campaigner wants to maximize. This metric represents the desired outcome of the campaign. Examples include:

  • Total Fees Generated: For a campaign distributing tokens to liquidity providers on a DEX, the metric could be the total trading fees generated by those LPs over a specific period.
  • Active Users: For a campaign aimed at increasing user engagement, the metric could be the number of active users (defined by some specific actions) after the distribution.
  • Governance Participation: For a campaign focused on governance, the metric could be the participation rate in governance proposals.
  • Value Locked: For a campaign related to lending, the metric could be the total value locked by users who received tokens.

The Campaigner defines this metric when creating the campaign. The Delegates are then incentivized to choose criteria and distributions that maximize this metric.

B. Marginal Contribution

The VCG mechanism rewards Delegates based on their marginal contribution to the economic metric. This is calculated as follows:

  1. V_G (with all Delegates): Calculate the economic metric achieved with all Delegates’ votes included.
  2. V_G(-d) (without Delegate d): For each Delegate d, recalculate the economic metric as if that Delegate had not participated. This means removing their votes and re-running the criteria selection and distribution calculation.
  3. Marginal Contribution (ΔV_G(d)): The difference between the two: \deltaV_G(d) = V_G - V_G(-d)

This ΔV_G(d) value represents the impact of Delegate d’s votes on the overall economic outcome. If their votes led to a better outcome (higher V_G), their marginal contribution is positive. If their votes led to a worse outcome, their marginal contribution is negative.

C. VCG Payment

The VCG payment to a Delegate is based on their marginal contribution. The formula is conceptually:

Payment(d) = ΔV_G(d) + h(other_delegates)
  • ΔV_G(d): The Delegate’s marginal contribution.
  • h(other_delegates): A function that depends only on the other Delegates’ votes (not Delegate d’s votes). This term ensures incentive compatibility.

In practice, in Filament, the h(other_delegates) is set to zero. So, the core of the VCG payment is simply the Delegate’s marginal contribution. The total reward is then some constant multiplied by the marginal contribution, or zero if negative.

D. Incentive Compatibility

The VCG mechanism is incentive-compatible, meaning that the dominant strategy for each Delegate is to vote truthfully according to their beliefs about which criteria and distributions will maximize the economic metric.

  • Why? If a Delegate tries to manipulate the outcome by voting strategically (not according to their true beliefs), they risk decreasing their own marginal contribution and, therefore, their payment. The only way to reliably maximize their payment is to vote in a way that they believe will maximize the overall V_G.

E. Practical Implementation in Filament

  1. Criteria Phase: Delegates vote on criteria. The VCG mechanism is applied after the criteria are confirmed and the economic metric (V_G) is measured. The system calculates each Delegate’s marginal contribution by hypothetically removing their votes and recalculating the outcome.
  2. Distribution Phase (Full Protocol): In the full protocol (not the simplified testnet version), Delegates will also vote on the final distribution. The VCG mechanism will be applied similarly, calculating the marginal contribution of each Delegate’s votes on the distribution.
  3. Reward Calculation: The Delegate’s final reward is a combination of the base commission and their VCG-based payment (proportional to their marginal contribution). This reward is then distributed in FILA.

III. Example

Let’s say a campaign aims to increase trading fees generated on a DEX.

  1. Campaign Setup: The Campaigner defines the economic metric as “total trading fees generated by recipients of the token distribution over the next month.”
  2. Criteria Selection: Delegates propose and vote on criteria (e.g., “users who have provided liquidity to pool X,” “users who have traded at least $Y in the past”).
  3. Distribution (Simplified): In the simplified version, there is no distribution vote.
  4. Measurement: After one month, the total trading fees generated by the token recipients are measured (this is V_G).
  5. VCG Calculation:
    • The system recalculates the expected V_G without Delegate A’s votes. Let’s say this is V_G(-A).
    • Delegate A’s marginal contribution is ΔV_G(A) = V_G - V_G(-A).
    • If ΔV_G(A) is positive, Delegate A receives a payment proportional to this contribution. If it’s negative, they receive no VCG-based payment (but they still get the base commission if they participated).
    • This process is repeated for all Delegates.

IV. Benefits of the VCG Mechanism

  • Incentive Alignment: Aligns Delegates’ incentives with the Campaigner’s goals. Delegates are directly rewarded for contributing to the campaign’s success.
  • Truthful Revelation: Encourages Delegates to vote honestly and share their expertise.
  • Efficiency: Leads to more efficient token distributions, as the criteria and distribution are optimized to maximize the desired economic outcome.
  • Resistance to Manipulation: Makes it difficult for Delegates to manipulate the outcome for their own benefit.
  • Sybil Resistance: By tying rewards to economic outcomes, sybil attacks become less profitable.

V. Conclusion

The Filament commission structure, with its combination of a base commission and the VCG mechanism, provides a powerful and sophisticated way to incentivize Delegates and ensure that token distribution campaigns achieve their intended economic goals. This approach promotes fairness, efficiency, and alignment of interests among all participants in the Filament ecosystem. The VCG mechanism, in particular, is a key innovation that differentiates Filament from simpler airdrop mechanisms.

Campaign Bonds

Campaign Bonds are a core security mechanism within the Filament protocol. They ensure that Delegates are fairly compensated for their work, even if a Campaigner abandons a campaign or acts maliciously. This mechanism builds trust and incentivizes responsible behavior from Campaigners.

Purpose

The primary purpose of Campaign Bonds is to guarantee a minimum payment to Delegates who participate in a campaign. Since Delegates expend effort (and potentially incur opportunity costs) by participating, the bond ensures they receive compensation regardless of the Campaigner’s actions. This protection is particularly important because Delegates don’t inherently trust Campaigners.

Key Concepts

  • Bonding: The process by which a Campaigner deposits FILA tokens into a smart contract (the Paymaster) as a security deposit. This happens before the campaign begins.
  • Locked FILA: The bonded FILA is locked during the active phases of the campaign. This means the Campaigner cannot withdraw it until the campaign completes successfully or is settled after a failure.
  • Watermark: A dynamic value representing the minimum amount of FILA that must remain locked in the bond. The watermark moves up and down as campaigns progress. It ensures that enough FILA is always available to cover potential Delegate payments and slashing penalties.
  • Unbonding: The process by which a Campaigner can withdraw their FILA after a campaign has successfully completed or has been settled.
  • Slashing: If a campaign fails due to Campaigner inaction (e.g., not confirming criteria, not confirming segments) or a timeout, a portion of the bond is slashed. This slashed FILA is distributed to the Delegates as compensation.
  • MIN_DELEGATE_PAYMENT: A fixed amount of FILA that represents the minimum payment each Delegate will receive, even if the campaign is abandoned. This value is a protocol-wide parameter (set by governance).
  • NUM_DELEGATES: The number of delegates participating in that campaign.

How it Works

  1. Bond Calculation: Before a campaign starts, the required bond amount is calculated:

    required_bond = NUM_DELEGATES * MIN_DELEGATE_PAYMENT
  2. Bonding (Locking FILA): The Campaigner must deposit at least the required_bond amount of FILA into the Paymaster contract. This FILA becomes “bonded” and is associated with the specific campaign. The Paymaster contract keeps track of the total bonded FILA and the watermark. When a campaign begins, the watermark is increased by the required_bond.

  3. Campaign Progression: As the campaign progresses through its phases (Init, Criteria, Publish, Distribution, Settle), the bond remains locked.

  4. Successful Completion: If the campaign completes successfully (tokens are distributed), the bond (minus any commissions or fees paid) is unlocked. The watermark is decreased. The Campaigner can then unbond (withdraw) their FILA.

  5. Campaign Failure/Timeout: If the campaign fails due to Campaigner inaction or a timeout at any stage before settlement:

    • The bond is slashed. The amount slashed is typically equal to the required_bond ( NUM_DELEGATES * MIN_DELEGATE_PAYMENT ).
    • The slashed FILA is distributed to the Delegates, proportional to their voting power (in the full protocol). This ensures they are compensated for their time and effort.
    • The watermark is decreased.
  6. Unbonding: After the campaign has concluded successfully or after a failure and slashing, and once all payments have been processed, the campaigner may be able to unbond remaining FILA. If they unbond FILA that brings their total bond amount below the watermark, they may incur an “unbonding tax” (this detail needs further clarification in the original documentation).

Example Scenario

Let’s say:

  • MIN_DELEGATE_PAYMENT = 100 FILA
  • NUM_DELEGATES = 10

The required_bond would be 10 * 100 = 1000 FILA.

  1. The Campaigner bonds 1000 FILA. The watermark increases by 1000.
  2. The campaign proceeds to the Criteria phase.
  3. The Campaigner fails to confirm the criteria within the allowed time.
  4. The bond is slashed by 1000 FILA. The watermark is decreased by 1000.
  5. Each Delegate receives 100 FILA (their minimum payment).

Relationship with Paymaster

The Paymaster contract is responsible for:

  • Holding the bonded FILA.
  • Tracking the watermark.
  • Executing the locking, unlocking, and slashing of bonds.
  • Facilitating payments to Delegates (and potentially other actors).

The Filament Hub interacts with the Paymaster to manage the campaign bonds.

Code Example (Conceptual - Combining Rust and Solidity Ideas)

// Simplified Rust representation (Conceptual)
struct CampaignBond {
    total_bonded_fila: u256, // Total FILA bonded by all Campaigners
    watermark: u256,          // Minimum amount that must remain locked
    min_delegate_payment: u256,
    campaign_bonds: HashMap<u64, CampaignSpecificBond>, // Campaign ID -> Bond details
}

struct CampaignSpecificBond {
  campaign_id: u64,
	campaigner: Address,
  num_delegates: u32,
	locked_bond: u256,
}

impl CampaignBond {
    // ... (Functions for bonding, locking, unlocking, slashing)
}

// --- Solidity (Paymaster - Partial) ---
pragma solidity ^0.8.0;

contract Paymaster {
    // ... (Other parts of the Paymaster)

    struct CampaignBond {
        uint256 balance;
        uint256 watermark;
    }

    mapping(address => mapping(uint256 => CampaignBond)) public campaignBonds; // Campaigner -> CampaignID -> Bond
		// ...
		// Add to bond
    function addToCampaignBond(uint256 campaignId, uint256 amount) public {
        filaToken.safeTransferFrom(msg.sender, address(this), amount);
        campaignBonds[msg.sender][campaignId].balance += amount;
    }
		// set watermark
    function setCampaignBondWatermark(uint256 campaignId, uint256 watermark) public {
        // Add appropriate access control here
        campaignBonds[msg.sender][campaignId].watermark = watermark;
    }
		// withdraw from bond
    function withdrawFromCampaignBond(uint256 campaignId, uint256 amount) public {
        CampaignBond storage bond = campaignBonds[msg.sender][campaignId];
        require(bond.balance - amount >= bond.watermark, "Cannot withdraw below watermark");
        bond.balance -= amount;
        filaToken.safeTransfer(msg.sender, amount);
    }
}

Benefits

  • Trustless System: Delegates don’t need to trust Campaigners directly. The bond mechanism ensures they will be paid.
  • Incentivizes Completion: Campaigners are incentivized to complete campaigns successfully to avoid losing their bond.
  • Fair Compensation: Delegates are guaranteed a minimum payment for their work.
  • Sybil Resistance: The bond requirement makes it more expensive for malicious actors to create many fake campaigns.

Conclusion

Campaign Bonds are a fundamental part of the Filament protocol’s security and incentive model. They provide a robust mechanism for ensuring that Delegates are compensated for their contributions, fostering a trustworthy and reliable environment for decentralized token distributions. The interaction with the Paymaster contract is crucial for the secure management of these bonds.

Treasury Window

The Treasury Window is a critical component of the Filament protocol’s economic model, providing a mechanism for Campaigners to acquire FILA tokens at a predictable and potentially discounted price. This facility addresses the challenges of price volatility and potential liquidity issues when obtaining FILA on the open market, ensuring that Campaigners can reliably fund their campaigns.

Purpose

The primary purposes of the Treasury Window are:

  1. Price Stability for Campaigners: Campaigners need FILA to create campaign bonds and potentially cover other fees. However, the price of FILA on the open market can be volatile. The Treasury Window offers a stable and predictable price, allowing Campaigners to budget effectively.
  2. Controlled FILA Supply: The Treasury Window allows the protocol to manage the release of FILA into circulation, helping to maintain a healthy token economy.
  3. Acquire USDC: The treasury can acquire USDC to finance protocol development without putting price pressure on $FILA.
  4. Bootstrapping Campaigns: By offering a discount, new campaign creation is incentivized.

Key Concepts

  • Exchange Rate: The Treasury Window offers FILA at a defined exchange rate, typically based on a Time-Weighted Average Price (TWAP) of FILA/USDC.
  • Discount: The Treasury Window may offer FILA at a discount relative to the TWAP. This discount incentivizes Campaigners to use the Treasury Window and helps bootstrap the network. The discount level is a governance parameter.
  • TWAP (Time-Weighted Average Price): A measure of the average price of FILA over a specific period (e.g., 7 days). This helps smooth out short-term price fluctuations. An oracle (e.g., Chainlink) is typically used to provide the TWAP.
  • LIMIT: A limit on the amount of FILA that can be purchased through the Treasury Window within a given period (e.g., per epoch or per day). This prevents excessive dilution of the FILA supply.
  • Bonded FILA: The FILA purchased through the Treasury Window is bonded directly to the campaign. This means it is locked and can only be used for campaign-related purposes (primarily the campaign bond).

How it Works

  1. Access: Campaigners interact with the Treasury Window contract (likely through the Paymaster).
  2. Quote: The Campaigner requests a quote for a specific amount of FILA. The Treasury Window contract calculates the required USDC amount based on the current exchange rate and discount.
    • Exchange Rate = TWAP($FILA/USDC) * (1 - Discount)
  3. Payment: The Campaigner sends the required USDC to the Treasury Window contract.
  4. FILA Issuance: The Treasury Window contract mints the requested amount of FILA and directly bonds it to the Campaigner’s specified campaign. This is a crucial point: the FILA is not sent to the Campaigner’s wallet as freely transferable tokens.
  5. Limit Enforcement: The Treasury Window contract checks if the LIMIT has been reached. If so, the transaction is rejected (or potentially queued, depending on the implementation).

Example

Let’s say:

  • TWAP(0.10 (FILA is trading at 10 cents on average)
  • Discount = 20%
  • Campaigner wants to acquire 10,000 FILA for a campaign bond.
  1. The exchange rate is calculated: 0.08
  2. The required USDC is: 10,000 FILA * 800
  3. The Campaigner sends 800 USDC to the Treasury Window contract.
  4. The Treasury Window contract mints 10,000 FILA and bonds it to the Campaigner’s campaign.

Governance Parameters

The following parameters are likely controlled by governance:

  • DISCOUNT: The discount percentage applied to the TWAP.
  • LIMIT: The maximum amount of FILA that can be purchased through the Treasury Window within a given period.
  • TWAP_PERIOD: The time period over which the TWAP is calculated (e.g., 7 days).
  • Oracle Address: The contract to source the TWAP price.

Integration with Paymaster

The Paymaster contract likely plays a key role in integrating the Treasury Window:

  • Funding Source: When a Campaigner initiates a payment (e.g., to cover Delegate fees), the Paymaster can check if the Campaigner has sufficient funds in their campaign bond. If not, it can offer the option to purchase additional FILA through the Treasury Window.
  • Atomic Operations: The Paymaster can ensure that the purchase of FILA through the Treasury Window and the subsequent payment are performed atomically (in a single transaction). This prevents race conditions and ensures that the Campaigner has sufficient funds.

Code Example (Conceptual Solidity)

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface IOracle {
    function getPrice(string memory symbol) external view returns (uint256);
}

contract TreasuryWindow {
    IERC20 public filaToken;
    IERC20 public usdcToken;
    IOracle public oracle;

    uint256 public discount; // e.g., 20 for 20%
    uint256 public limit;
    uint256 public twapPeriod; // in seconds
		address public admin;

    // ... (Other state variables)

		constructor(address _filaToken, address _usdcToken, address _oracle, uint256 _twapPeriod) {
        filaToken = IERC20(_filaToken);
        usdcToken = IERC20(_usdcToken);
        oracle = IOracle(_oracle);
        twapPeriod = _twapPeriod;
    }

    function getRequiredUsdcForFila(uint256 filaAmount) public view returns (uint256) {
        uint256 twap = getTwap(); // Implement TWAP calculation using the oracle
        uint256 exchangeRate = twap * (100 - discount) / 100;
        return filaAmount * exchangeRate / 1e18; // Assuming FILA has 18 decimals
    }

    function buyFilaWithUsdc(uint256 usdcAmount) public returns (uint256) {
        // 1. Check limit
        //require(currentPeriodSales + filaAmount <= limit, "Treasury Window limit reached");

        // 2. Calculate FILA amount based on TWAP and discount
        uint256 filaAmount = usdcAmount * 1e18 * 100 / (getTwap() * (100- discount));

        // 3. Transfer USDC from user
        usdcToken.transferFrom(msg.sender, address(this), usdcAmount);

        // 4. Mint FILA *directly to the Paymaster, bonded to the campaign* (Requires interaction with Paymaster)
        //    This is a KEY difference from a typical exchange.
        //    The Paymaster contract would have a function like `receiveBondedFila(campaignId, amount)`
        //    We assume the Paymaster address is stored in a variable called `paymaster`
        IPaymaster(paymaster).receiveBondedFila(msg.sender, filaAmount); // NOTE: Hypothetical function

        // 5. Update sales for current period
        //currentPeriodSales += amount;

        return filaAmount;
    }

		function getTwap() public view returns (uint256){
			return oracle.getPrice("FILA");
		}

    // ... (Functions for setting parameters, potentially by governance)
		function setDiscount(uint256 _discount) external {
			require(msg.sender == admin, "Only admin");
			discount = _discount;
		}
		function setLimit(uint256 _limit) external{
			require(msg.sender == admin, "Only admin");
			limit = _limit;
		}

}

interface IPaymaster {
		function receiveBondedFila(address campaigner, uint256 amount) external;
}

Benefits

  • Price Predictability: Campaigners can budget effectively, knowing the cost of acquiring FILA.
  • Liquidity Support: Provides a reliable source of FILA, even if market liquidity is low.
  • Controlled Inflation: The LIMIT parameter helps manage the supply of FILA.
  • Bootstrapping: The discount incentivizes early adoption of the Filament protocol.
  • Funds Protocol: Provides a mechanism for the treasury to accumulate USDC.

Conclusion

The Treasury Window is a vital part of the Filament economic ecosystem. It provides a stable and predictable way for Campaigners to acquire the FILA needed to run campaigns, while also helping to manage the overall FILA supply. Its integration with the Paymaster contract ensures a seamless and secure user experience. This mechanism addresses a key challenge in many token-based systems – the volatility and potential illiquidity of the native token – making Filament more accessible and attractive to Campaigners.