# Overview

AI today sits behind closed doors: proprietary models, scarce compute, and centralized control leave creators uncompensated and users locked in. **Function Network** tears down these walls with a blockchain-powered protocol that makes AI **open, decentralized, and permissionless**, so anyone can contribute, anyone can consume, and no single entity can censor or gate access.

### The Problem: Open-Source AI Isn’t Accessible for All

* **Zero Creator Revenue**\
  Open source model authors publish to the world yet earn nothing. Every dollar goes to the hosting or application layer, leaving open-source contributions undervalued and unsustainable. As costs go up, there becomes an increasingly pressure to find private funding and ultimately close sourcing their model to fund their development.
* **Poor Model Discoverability & Bootstrapping**\
  Even the best models languish unseen: without a clear on-chain marketplace or incentive to spotlight high-quality work, infrastructure providers won’t host them and therefore, developers can’t find or use them.
* **Centralized Infrastructure & High Barriers to Entry**\
  Without a direct path to monetization, only large players backed by deep private funding can afford the massive investment in large datasets and compute fleets required for AI at scale. This centralizes control and stifles innovation due to more models becoming closed source.

### Our Solution: Democratize AI with Function Network

1. **Tokenized Model Marketplace**\
   A unified, onchain registry where creators publish model metadata, weights, and transparent pricing for their IP.\
   Community ratings and usage statistics surface the best models and drive quality improvements.
2. **Onchain Monetization**\
   Usage fees and royalties are settled instantly in FUNC tokens.\
   Fine-grained payout rules let creators set per-model or per-endpoint rates, while providers earn proportional to compute delivered.
3. **Distributed infrastructure**\
   Break large inference jobs into parallel shards distributed across any GPU provider (from RTX 30-series to datacenter GPUs).\
   Dynamic load-balancing and redundancy guarantee low latency, high throughput, and resilient uptime.\
   End-to-end orchestration, monitoring, and failover are enforced by smart contracts.\
   Providers commit SLAs onchain: missed targets trigger automated penalties and re-allocation.

### Incentive Alignment: How the Network Works

The best-performing models attract developers, who pay compute providers to use them. In turn, compute providers share a portion of their earnings with the model creators. This creates a sustainable flywheel: developers get access to top-tier AI, compute providers earn by supplying the necessary infrastructure, and model creators are funded to continue innovating. This virtuous cycle encourages the creation of more high-quality, open-source models.

Every protocol action is powered by **FUNC**:

* **Developers** deposit FUNC to reserve inference capacity and pay per request.
* **Compute Providers** stake FUNC to signal reliability, host models, and collect fees for each inference shard served.
* **Model Creators** receive an onchain royalty split every time their model is invoked, turning traffic into recurring income.

### The Function Flywheel

<figure><img src="/files/trLP1rt7UjfZTsipga2W" alt=""><figcaption></figcaption></figure>


# Using Function Network

Function Network is designed to **empower anyone** to contribute to and access **decentralized AI**. Whether you're a **user, developer, compute provider, or model creator**, the network offers a seamless way to **earn, interact, and build.**

***

## **For Users**

Access **powerful AI models** on a decentralized network, ensuring **scalability, privacy, and reliability**.

🔗 [**Try Function Chat**](https://github.com/fxnlabs/function-public-docs/blob/branch/function-network/using-function-network/broken-reference/README.md) – Experience decentralized AI-powered chat on the web and your mobile device.

***

## **For Developers**

Integrate **Function-powered AI** into your applications and dApps.

📖 [**Docs**](https://github.com/fxnlabs/function-public-docs/blob/branch/function-network/using-function-network/broken-reference/README.md) – Explore APIs, SDKs, and integration guides.\
🔗 [**Function Router**](https://platform.fxnrouter.com/) – Start building with Function.

***

## **For Compute Providers**

Contribute **compute power** and earn rewards by **providing AI resources**.

📖 [**Docs**](/function-network/using-function-network/run-a-node) – Learn how to set up and operate as a provider.\
🔗 [**Provider Page**](https://www.function.network/dashboard) – Manage your provider status and stake directly on the Dapp.

***

## **For Model Creators**

Function Network empowers model creators to monetize their work opensource AI community. By publishing your models to the network, you can earn royalties, gain visiblity and secure funding to continue training your model.

📖 [**Docs**](/function-network/using-function-network/provide-a-model) – Learn how to provide a model to the network.\
🔗 [**Models**](https://www.function.network/models) – View existing models on the network and provide your own permisonlessly.

***

Function Network is shaping the **future of AI** where **compute is distributed, access is open, and innovation is unstoppable.** 🚀


# For Node Operators

This guide will walk you through the process of setting up and running a Function Network node. You can run a node either as a standalone binary or using Docker.

## Quick Start

1. **Get FUNC Tokens**: To stake your node, you'll need FUNC tokens. You can get testnet tokens from the [Function Network Faucet](https://www.function.network/faucet).
2. **Start the Node & Get Your Node ID**: Follow one of the guides below to start your node. When you start the node, it will output your unique Node ID.
3. **Stake Your Node**: Once you have your Node ID and publicly accessible node URL, go to the [staking page](https://www.function.network/provide) to stake it on the network.

> **Note**: Before staking your node, we recommend reviewing our [Best Practices](https://github.com/fxnlabs/function-public-docs/blob/branch/function-network/using-function-network/best-practices.md) guide for tips on security and performance.

## Running as a Binary

For users who prefer to run the node directly on their machine:

1. **Install and Start the Node**: Use the following command to install and start the node. This will also provide your Node ID.

   ```bash
   brew tap fxnlabs/homebrew-tap && fxn start --tui
   ```
2. Proceed to stake your node as described in the "Getting Started" section.

## Running with Docker

For users who prefer to use Docker, we provide images for different hardware configurations.

1. **Pull the Docker Image**:
   * For **Nvidia GPUs (CUDA acceleration)**:

     ```bash
     docker pull ghcr.io/fxnlabs/function-node:0.2.0-cuda
     ```
   * For **standard hardware (MACs, CPUs)**:

     ```bash
     docker pull ghcr.io/fxnlabs/function-node:0.2.0
     ```

> **Note**: AMD GPU acceleration is on our roadmap and will be supported in a future release.

2. **Run the Docker Container**: Start a container with the image you pulled. This will start the node and give you your Node ID.
3. Proceed to stake your node as described in the "Getting Started" section.

## Open Source

The Function Network node software is fully open source. You can view the source code, contribute, and track development on our [GitHub repository](https://github.com/fxnlabs/function-node).


# Configuration

The Function node uses a set of configuration files located in the `~/.fxn` directory in your user's home folder.

* `config.yaml`: The main configuration file for the node server.
* `model_backend.yaml`: Configuration for the model backend
* `nodekey.json`: Stores your node's private key.

## Starting the Node

You can start the node using:

```bash
fxn start
```

`nodekey.json` will created for you upon start if it wasn't created before.

### Text-based User Interface (TUI)

For a more interactive experience with easier debugging and state monitoring, you can start the node with a Text-based User Interface (TUI):

```bash
fxn start --tui
```

## Account Management

Before starting a node, you need to generate a node key. This key is used to identify your node on the Function Network.

### Creating a New Account

To generate a new node key, run the following command:

```bash
fxn account new
```

This command will create a `nodekey.json` file in your `~/.fxn` directory.

### Viewing Your Account

To display your existing node key and address, use:

```bash
fxn account show
```

## Configuration Details

For a detailed breakdown of the configuration options, please see the following sections:

* [Node](/function-network/using-function-network/run-a-node/configuration/config)
* [Model Backend](/function-network/using-function-network/run-a-node/configuration/model-backend)


# Config

This section details the configuration for the `node` section of the `config.yml` file.

A full configuration template can be found [here](https://github.com/fxnlabs/function-node/blob/main/fixtures/config/config.yaml.template).

```yaml
node:
  listenPort: 8080
  listenAddress: "127.0.0.1"
```

## Parameters

### `listenPort`

* **Description**: The port on which the Function node will listen for incoming connections.
* **Default**: `8080`
* **Type**: `integer`

### `listenAddress`

* **Description**: The address on which the Function node will listen for incoming connections. Using `127.0.0.1` (localhost) is recommended for security, as it restricts access to the local machine. To allow external access, you can set this to `0.0.0.0`. It is recommended that you expose the node through a reverse proxy, i.e NGINX or HAProxy
* **Default**: `"127.0.0.1"`
* **Type**: `string`


# Model Backend

The `model_backend.yaml` file allows node operators to configure a specific model and point it to a different URL (backend).

## Template

```yaml
backendProvider: "custom" # "fxn", "custom", "vllm" or "ollama"
url: "http://your-backend:8082" # required for "custom"
fxnId: "2" # can be be found here https://www.function.network/models
apiKey: "your-api-key" # optional
bearerToken: "your-bearer-token" # optional
modelNameAlias: "your-model-name-alias" # optional
```

## Parameters

### `backendProvider`

* **Description**: Specifies the type of backend provider.
* **Options**: `"fxn"`, `"custom"`, `"vllm"`, `"ollama"`
* **Type**: `string`

While `"custom"` is the primary supported provider for now, we are actively developing a native Function Network inference engine. See "The Future: Custom Inference Engine" below for more details.

### `url`

* **Description**: The URL of your custom backend. This is required when `backendProvider` is set to `"custom"`.
* **Type**: `string`

### `fxnId`

* **Description**: The Function Network model ID to participate in
* **Type**: `string`

The `fxnId` for the model you want to participate in can be found [here](https://www.function.network/models)

### `apiKey`

* **Description**: Your API key for the backend service (optional).
* **Type**: `string`

### `bearerToken`

* **Description**: Your bearer token for authentication (optional).
* **Type**: `string`

### `modelNameAlias`

* **Description**: Your backend may reference the model name differently in OpenAI requests in comparsion to what's onchain. So this allows you to specify the mapping between Function's model name and your backend model name via an alias.
* **Type**: `string`

## The Future: Custom Inference Engine

While the current `"custom"` backend provider allows the node to act as a proxy to any existing model endpoint, this is an interim solution. We are actively developing a native, high-performance inference engine that will become the standard for the Function Network.

This upcoming engine is being built from the ground up for true, distributed inference. It will feature advanced optimizations such as:

* **Pipeline Parallelism**: Processing different stages of inference simultaneously across multiple nodes.
* **Sharding**: Splitting a model into smaller pieces (shards or layers) that are distributed across the network.
* **Custom Network Transport**: A highly optimized network layer to reduce unnecessary data transfer between nodes, ensuring the most efficient communication for distributed inference.

Eventually, this means a single node will only need to hold and compute one shard of a model, rather than the entire model. This distributed approach will significantly lower the hardware barrier for node operators and enable the network to run much larger and more powerful models collectively.

This custom engine is a core part of our roadmap and will become the default inference backend as it becomes available. In the meantime, the `"custom"` provider offers the flexibility to connect to any inference engine you choose to run.


# Hardware Requirement

While the network is open to a variety of hardware, here are some of the most commonly used and recommended setups for running a node on the Function Network.

| Category            | Manufacturer | Recommended Models                  |
| ------------------- | ------------ | ----------------------------------- |
| **Apple Silicon**   | Apple        | M1, M2, M3, M4 (and their variants) |
| **Consumer GPUs**   | Nvidia       | RTX 3090, RTX 4090                  |
| **Enterprise GPUs** | Nvidia       | A100, H100, H200                    |

> **Note:** This list is not comprehensive. We encourage anyone with capable hardware to join the network. If you have a different setup, you can still participate and contribute.

> **For Testnet Participants:** For testnet purposes, the network is more lenient and will allow CPU-based hardware for running smaller models (e.g., those with fewer than 14 billion parameters). This is to encourage broader participation and testing.


# Best Practices

### Use a Reverse Proxy

It is highly recommended to expose your node through a reverse proxy, such as NGINX or HAProxy. This provides several benefits:

* **Efficient Connection Pooling**: A reverse proxy can manage incoming connections more effectively, reducing the load on your node.
* **Enhanced Security**: By acting as an intermediary, a reverse proxy can protect your node from direct exposure to the internet, mitigating potential security risks.
* **Customizability**: You can implement custom rules, caching, and other advanced features to further optimize your setup.

### For Nvidia Users

For optimal performance with Nvidia GPUs, we recommend leveraging our CUDA docker binaries for GPU acceleration. This will ensure that your hardware is utilized efficiently, providing faster processing and better overall performance.


# FAQs

### Is the Function Node just a proxy?

No. While the current `"custom"` backend provider allows the node to act as a proxy to an existing model endpoint, this is just an interim solution to provide maximum flexibility. The long-term vision is a native, high-performance inference engine built for distributed inference.

This engine will use techniques like pipeline parallelism, sharding, and a custom network transport to distribute the load of a single model across many nodes. This will allow the network to run massive models that no single operator could run on their own. You can read more about this in the [Model Backend Configuration](/function-network/using-function-network/run-a-node/configuration/model-backend#the-future-custom-inference-engine) documentation.

### How are rewards calculated?

Rewards are calculated based on a combination of your node's uptime and its tokens-per-second performance.

### How is performance quantified?

The network has an on-chain entity known as the "scheduler" that enforces quality of service. The scheduler performs various checks to ensure your node is running healthily, including health checks, matrix multiplication challenges, and response quality checks. It also monitors for proper resource allocation. If a node's resources are shared or improperly allocated, the scheduler may jail the node and slash its stake.

### How many models can a single node support?

A single node should be dedicated to serving one model. Sharing a single node's resources across multiple models is not supported and can lead to poor performance. This prevents proper resource allocation, and the scheduler may jail and slash your stake as a result.

### Is the node software open source?

Yes, the Function Network node is fully open source. You can find the source code and contribute on our [GitHub repository](https://github.com/fxnlabs/function-node).


# For Model Creators

Bring your AI models on-chain with Function Network and become a key part of a decentralized AI ecosystem. As a model creator, you enable developers and users to access your unique models while benefiting from the network's infrastructure and economic incentives.

## What Do Model Creators Do?

Model creators are responsible for registering their AI models on the Function Network. This involves:

1. **Publishing Your Model**: Using the [Function Publish](https://www.function.network/publish) portal, you provide the model's metadata, such as its name, parameters, and resource requirements.
2. **On-Chain Registration**: The model is registered on the blockchain, creating an immutable record of its existence and configuration.
3. **Enabling Consumption**: Once registered, your model becomes available for the network's compute providers to host and for end-users to consume for AI inference tasks.

## What Do Model Creators Get?

The relationship between model creators and compute providers is symbiotic and designed to be mutually beneficial.

* **Revenue Sharing**: Model creators earn a portion of the revenue generated every time their model is used. This revenue split is handled transparently on-chain, ensuring you are fairly compensated for your contribution.
* **Access to a Global Compute Network**: You don't need to worry about hosting or scaling. The Function Network consists of a decentralized network of compute providers who run your model, ensuring it's always available to users.
* **Increased Adoption**: By listing your model on the Function Network, you gain visibility and access to a growing community of developers and applications looking to integrate AI.


# Tokenomics

FUNC is the **utility token** powering the Function Network, facilitating **staking, rewards, and governance** in a decentralized AI ecosystem.

***

## 🔗 **FUNC Token Utility**

1. **🔒 Staking** – Providers and gateways must stake FUNC tokens to participate in the network.
2. **🎁 Rewards** – Staked participants earn FUNC based on their contribution to AI inference.
3. **⚖️ Governance** – Future governance proposals and treasury management may be **FUNC-holder driven**.

***

## 💰 **Earning FUNC**

🔹 **Compute providers & gateways** earn FUNC by contributing compute power during each epoch.\
🔹 **Rewards are proportional** to the share of total **shards (work units) contributed**.

### **Example Calculation:**

* **Total epoch reward pool**: 10,000 FUNC
* **Your contribution**: 10% of total shards
* **Your earnings**: 🎯 **1,000 FUNC**

***

## 📈 **Economic Design**

### **🔗 Fixed Supply & Scarcity**

* FUNC has a **fixed supply of 1,000,000,000 tokens**, ensuring long-term value retention.
* No inflationary mechanisms. FUNC’s utility is **driven by demand and network participation**.

### **🏦 Treasury & Network Growth**

* The treasury is allocated for **ecosystem development, community initiatives, and staking rewards**.
* Governance mechanisms will allow **FUNC holders to propose and vote on treasury allocation**.

***

FUNC fuels **a decentralized, scalable AI network**, ensuring **fair rewards, governance, and long-term sustainability**. 🚀


# Earn Points

The Function Network is a decentralized AI marketplace powered by its community. It thrives on a symbiotic relationship between users, developers, and infrastructure providers. Every contribution, regardless of its size, adds direct value to the network and advances the mission of creating a more open and transparent AI landscape.

To recognize and incentivize these crucial contributions, the network features a rewards system. Participants earn Points that reflect their value added to the ecosystem. Whether you **chat with AI, develop models, integrate applications, or provide computing power**, you can **earn points** by helping to achieve the mission of the Function Network.

## Points

During our current testnet phase, contributions are rewarded with **Points**. These points serve as a measure of your early involvement and will play a role in the ecosystem's future. Upon the transition to mainnet, these contributions will be rewarded with the network's native token, FUNC\*

We have designed several pathways for participation, ensuring that anyone can contribute to the network's growth and share in its success.

### Chat

The simplest and most direct way to contribute is by using Function's tools, like **Function Chat**. Engage with decentralized AI models through Function Chat. Use it for daily tasks, creative brainstorming, or complex research. Your usage generates valuable data that strengthens the network. [Learn More](/function-network/earn-rewards/chat)

### Develop & Earn

Developers are the driver of the Function Network's revenue. They use Function to power AI applications. Integrate Function into your dApp or application to give your users access to powerful, decentralized AI. Early integrators may receive enhanced access, dedicated support, and premium tooling. [Learn More](/function-network/earn-rewards/develop)

### Provide Compute & Earn

Decentralized AI relies on a distributed, global network of compute resources. By providing hardware, you become the backbone of the Function Network. [Learn More](/function-network/earn-rewards/provide-compute)

### Publish Models & Earn

The network needs a diverse range of high-quality AI models. Contribute by fine-tuning existing models or training new ones specifically for the Function Network's decentralized environment. [Learn More](/function-network/earn-rewards/publish-models)

## Start Earning with Function Network!

The more you **chat, develop, provide, or publish**, the more you **earn points**. Whether you're a user, a developer, or an infrastructure provider, there is a way for you to participate in the decentralized AI revolution.

**Get started and earn points today!**

\*For additional details, please see our [Terms & Conditions](https://www.function.network/tos.txt).


# Chat

**Function Chat** is a **decentralized, AI-powered chat application** that empowers users to interact with cutting-edge AI models while contributing to a transparent, community-driven ecosystem. By engaging with Function Chat, you not only access powerful AI capabilities for assistance, creativity, or problem-solving but also earn eligibility for **rewards** through your participation in the **Function Network**.

Whether you're brainstorming ideas, coding, or simply exploring, Function Chat makes every interaction rewarding and impactful.

## Why Function Chat?

Function Chat stands out by combining a seamless user experience with the power of decentralized AI:

* **AI-Powered Conversations**: Interact with advanced, Function-hosted AI models for tasks like answering questions, generating ideas, writing code, or casual chats.
* **Decentralized Infrastructure**: Built on the **Function Network**, a distributed system that ensures efficiency, transparency, and resilience.
* **Earn Rewards**: Every chat contributes to optimizing AI inference on the network, making you eligible for **points** or other rewards.
* **Privacy and Transparency**: Leverage a decentralized platform designed to prioritize fairness, security, and user control.
* **No Complex Setup**: Start chatting instantly—no need for technical expertise or additional configurations.

## How It Works

Function Chat seamlessly connects users to decentralized AI models hosted on the Function Network. Here's a breakdown of the process:

1. **Access Function Chat**: Visit the [Function Chat platform](https://chat.function.network/) via your browser or supported app.
2. **Interact with AI**: Use the intuitive chat interface to engage with AI models.
3. **Earn Rewards**: Your activity earns **points** or other incentives, determined by the Function Network's reward system. The more you engage, the greater your contribution and potential rewards.

## Getting Started

Ready to dive into decentralized AI? Follow these simple steps to start using Function Chat:

1. **Visit Function Chat**: Go to [chat.function.network](https://chat.function.network/) on your desktop or mobile browser.
2. **Sign In or Create an Account**: Use your existing Function Network account or create a new one to track your contributions and rewards.
3. **Start Chatting**: Enter your query or conversation prompt in the chat interface to engage with AI models.
4. **Explore Advanced Features**: Experiment with different models or use cases, such as coding assistance or creative writing, to maximize your impact on the network.

**Pro Tip**: The more you interact, the more you contribute to the network’s growth, increasing your eligibility for rewards. Try asking complex questions or engaging in multi-turn conversations to fully explore the AI’s capabilities!

## Use Cases

Function Chat is versatile and supports a wide range of applications:

* **Developers**: Debug code, generate scripts, or explore API integrations with AI assistance.
* **Creatives**: Write stories, design marketing content, or brainstorm innovative ideas.
* **Students and Educators**: Get explanations for complex topics or create study aids.
* **Business Professionals**: Draft emails, analyze data, or generate reports with AI support.
* **Casual Users**: Have fun with open-ended conversations or explore AI’s creative potential.

## Frequently Asked Questions

### Is Function Chat free to use?

Yes, Function Chat is free to access! Simply visit [chat.function.network](https://chat.function.network/) and start chatting. Rewards and advanced features may depend on your participation level or network status.

### What makes Function Chat decentralized?

Function Chat runs on the Function Network, a distributed system of nodes that host AI models. This eliminates reliance on centralized servers, ensuring transparency, resilience, and community-driven governance.

### Can I use Function Chat for professional tasks?

Absolutely! Function Chat is designed for both casual and professional use cases, from coding and content creation to research and brainstorming.

### How secure is my data?

Function Chat prioritizes user privacy through its decentralized architecture and cryptographic protocols. No centralized entity controls your data, and interactions are processed securely across the network.

**Get Started Now**: [Function Chat](https://chat.function.network/)


# Develop

Function Network is a decentralized AI infrastructure platform that empowers developers to build innovative, scalable, and secure AI-powered and AI-enabled applications. By contributing to the ecosystem, developers can create cutting-edge AI-powered solutions and earn points as rewards for their efforts.

## How It Works

Function Network enables developers to integrate decentralized AI inference into their applications, create new tools, and expand the ecosystem's capabilities. Here's how you can participate:

* **Integrate AI into Your Applications**: Seamlessly inco rporate Function Network's decentralized AI inference capabilities into your platforms, enabling features such as real-time data processing, predictive analytics, or natural language processing.
* **Build AI-Powered Tools**: Extend Function Network by developing innovative tools and use cases, such as chatbots, recommendation systems, or advanced data analytics solutions, tailored to specific industries or user needs.
* **Contribute to Ecosystem Growth**: Drive the adoption of decentralized AI by integrating Function Network into real-world applications, fostering collaboration, and promoting a more accessible and transparent AI ecosystem.

By actively participating, developers not only add decentralized AI capabilities to their projects but also contribute to the broader vision of decentralized AI, earning points as a reward for their contributions.


# Provide Compute

Function Network enables users to **contribute GPU and compute resources** to power decentralized AI inference. By providing your hardware, you help scale AI while **earning onchain points**.

## **💡 How It Works**

✅ **Contribute Compute Resources** – Share your **GPU or other computing power** with the Function Network.\
✅ **Power AI Inference** – Your hardware helps run AI models efficiently in a decentralized system. ✅ **Earn Onchain Points** – Get points for your contribution. The more you provide, the higher your chance of receiving points.

## **🚀 Start Providing & Earn Points!**

By sharing your computing power, you become part of the **next-generation AI infrastructure**, helping Function Network scale while earning points.

🔗 **Get Started:** \[Function Network Dapp]


# Publish Models

Function Network is a **decentralized AI infrastructure** where developers can **build, fine-tune, and deploy AI models**. Contribute to the ecosystem and **earn points**.

## **💡 How It Works**

✅ **Train & Deploy Models** – Contribute new AI models to Function Network.\
✅ **Fine-Tune for Optimization** – Improve existing models for better efficiency and inference.\
✅ **Scale with Decentralized Compute** – Deploy models to leverage the distributed AI infrastructure and earn a portion of compute provider rewards.

## **🚀 Start Publishing & Earn Points!**

By contributing your AI models, you help shape the **future of decentralized AI** while gaining access to points.

🔗 **Get Started:** [Function Router](https://platform.fxnrouter.com)


# Smart Contracts

Note that we aim to keep these documents up to date, but they may not always reflect the latest changes in the codebase prior to release on mainnet. If you notice a discrepency, reach out to us: <contact@function.network>.

## **FUNC Token**

FUNC is the native utility token of the Function Network. It powers the ecosystem by:

* **Staking**: Required for providers and gateways to participate.
* **Rewards**: Distributed to contributors based on performance.
* **Governance (Roadmap)**: FUNC holders influence decisions about the network's evolution.

## **Providers**

Providers supply computational resources for running AI models. They:

* Stake FUNC to participate.
* Execute AI inference tasks and earn FUNC rewards.
* Support specific models by aligning with their staking and performance requirements.

## **Gateways**

Gateways enable users to interact with the network. They:

* Stake FUNC to operate.
* Route user requests to providers and ensure task execution.
* Earn FUNC for their role in connecting users to the network.

## **Models**

AI models define the computational workloads to be executed on the network. Each model:

* Specifies computational requirements like shards and compute units.
* Requires providers to stake FUNC to support them.

## **Model Creators**

Model creators are responsible for bringing AI models on-chain. They:

* **Publish Models**: Register models on the Function Network, making them available for compute providers to host.
* **Earn Revenue**: Receive a share of the revenue generated when their models are used.
* **Expand Reach**: Gain access to a decentralized network of compute and a growing user base.

## **Router**

The Router acts as the central management hub, connecting providers, gateways, models, and other core components.

## **Treasury**

The Treasury manages FUNC tokens and ensures accurate reward distribution to providers and gateways.

## **Checkpoints**

Checkpoint contracts track contributions and performance over time:

* **Provider Checkpoints**: Monitor provider activity and shards contributed.
* **Gateway Checkpoints**: Track gateway usage and compute units consumed.


# Router.sol

The `Router` contract serves as the central registry for key FUNC system contracts, managing their addresses and ensuring seamless integration and communication between components.

***

## Key Features

1. **Centralized Management**:
   * Stores and manages addresses of all core contracts within the FUNC ecosystem.
2. **Role-Based Access Control**:
   * Ensures only authorized entities can update the stored contract addresses.
3. **Initializable Design**:
   * Supports initialization to securely set up the contract with required addresses.
4. **Provider Staking Management**:
   * Links staking pools with models and facilitates updates.

***

## Roles and Access Control

* **`DEFAULT_ADMIN_ROLE`**:
  * Full administrative control over the contract.
  * Can update the addresses of core system contracts and staking pools.

***

## State Variables

### Core Contracts

* `providerStakingFactory`: Factory contract for creating provider staking pools.
* `providerRegistry`: Registry for managing providers.
* `providerCheckpoint`: Tracks provider state history and checkpoints.
* `gatewayStaking`: Manages staking operations for gateways.
* `gatewayRegistry`: Registry for managing gateways.
* `gatewayCheckpoint`: Tracks gateway state history and checkpoints.
* `epochController`: Handles epoch-based logic and scheduling.
* `permissions`: Manages permissions for providers and gateways.
* `treasury`: Treasury contract for managing funds.
* `model`: Model contract for managing models.
* `logic`: Logic contract for managing computation and reward functions.

### Provider Staking Pools

* `providerStakingPools`: Mapping of model IDs to their associated staking pools.

***

## Key Functions

### Initialization

#### `initialize`

Initializes the `Router` contract with addresses of all core contracts.

* **Parameters**:
  * `_initializeAddresses`: A struct containing the addresses of all required contracts.

***

### Contract Address Management

#### `setProviderStakingFactory`

Updates the `ProviderStakingFactory` address.

* **Access**: `DEFAULT_ADMIN_ROLE`
* **Parameters**:
  * `_providerStakingFactory`: New address of the `ProviderStakingFactory`.

#### `setProviderCheckpoint`

Updates the `ProviderCheckpoint` address.

* **Access**: `DEFAULT_ADMIN_ROLE`
* **Parameters**:
  * `_providerCheckpoint`: New address of the `ProviderCheckpoint`.

#### `setProviderRegistry`

Updates the `ProviderRegistry` address.

* **Access**: `DEFAULT_ADMIN_ROLE`
* **Parameters**:
  * `_providerRegistry`: New address of the `ProviderRegistry`.

#### `setGatewayStaking`

Updates the `GatewayStaking` address.

* **Access**: `DEFAULT_ADMIN_ROLE`
* **Parameters**:
  * `_gatewayStaking`: New address of the `GatewayStaking`.

#### `setGatewayCheckpoint`

Updates the `GatewayCheckpoint` address.

* **Access**: `DEFAULT_ADMIN_ROLE`
* **Parameters**:
  * `_gatewayCheckpoint`: New address of the `GatewayCheckpoint`.

#### `setGatewayRegistry`

Updates the `GatewayRegistry` address.

* **Access**: `DEFAULT_ADMIN_ROLE`
* **Parameters**:
  * `_gatewayRegistry`: New address of the `GatewayRegistry`.

#### `setEpochController`

Updates the `EpochController` address.

* **Access**: `DEFAULT_ADMIN_ROLE`
* **Parameters**:
  * `_epochController`: New address of the `EpochController`.

#### `setTreasury`

Updates the `Treasury` address.

* **Access**: `DEFAULT_ADMIN_ROLE`
* **Parameters**:
  * `_treasury`: New address of the `Treasury`.

#### `setPermissions`

Updates the `Permissions` address.

* **Access**: `DEFAULT_ADMIN_ROLE`
* **Parameters**:
  * `_permissions`: New address of the `Permissions`.

#### `setLogic`

Updates the `Logic` address.

* **Access**: `DEFAULT_ADMIN_ROLE`
* **Parameters**:
  * `_logic`: New address of the `Logic`.

#### `setModel`

Updates the `Model` address.

* **Access**: `DEFAULT_ADMIN_ROLE`
* **Parameters**:
  * `_model`: New address of the `Model`.

***

### Provider Staking Pool Management

#### `providerStaking`

Retrieves the staking pool associated with a given model ID.

* **Parameters**:
  * `_modelId`: Model ID to retrieve the staking pool for.
* **Returns**: Address of the associated `ProviderStaking` contract.

#### `setStakingPool`

Updates the staking pool associated with a given model ID.

* **Access**: `DEFAULT_ADMIN_ROLE` or `Model` contract.
* **Parameters**:
  * `_modelId`: Model ID to update.
  * `_stakingPool`: New staking pool address.

***

## Events

* **`ProviderStakingFactoryUpdated(IProviderStakingFactory providerStakingFactory)`**:
  * Emitted when the `ProviderStakingFactory` address is updated.
* **`ProviderCheckpointUpdated(IProviderCheckpoint providerCheckpoint)`**:
  * Emitted when the `ProviderCheckpoint` address is updated.
* **`ProviderRegistryUpdated(IProviderRegistry providerRegistry)`**:
  * Emitted when the `ProviderRegistry` address is updated.
* **`GatewayStakingUpdated(IGatewayStaking gatewayStaking)`**:
  * Emitted when the `GatewayStaking` address is updated.
* **`GatewayCheckpointUpdated(IGatewayCheckpoint gatewayCheckpoint)`**:
  * Emitted when the `GatewayCheckpoint` address is updated.
* **`GatewayRegistryUpdated(IGatewayRegistry gatewayRegistry)`**:
  * Emitted when the `GatewayRegistry` address is updated.
* **`EpochControllerUpdated(IEpochController epochController)`**:
  * Emitted when the `EpochController` address is updated.
* **`TreasuryUpdated(ITreasury treasury)`**:
  * Emitted when the `Treasury` address is updated.
* **`PermissionsUpdated(IPermissions permissions)`**:
  * Emitted when the `Permissions` address is updated.
* **`LogicUpdated(ILogic logic)`**:
  * Emitted when the `Logic` address is updated.
* **`ModelUpdated(IModel model)`**:
  * Emitted when the `Model` address is updated.
* **`ProviderStakingUpdated(uint256 modelId, IProviderStaking stakingPool)`**:
  * Emitted when the staking pool for a model is updated.

***

## Fallback Functions

* **`receive()`**: Rejects Ether transfers.
* **`fallback()`**: Rejects Ether transfers and invalid calls.


# EpochController.sol

The `EpochController` contract is a critical component for managing and tracking epochs in a blockchain-based system. Epochs are defined as fixed intervals of blocks and are used for various time-based operations, such as staking, reward distribution, and lock periods. This contract provides administrators the ability to configure epoch parameters and query epoch-related information in a decentralized manner.

***

## Key Features

1. **Epoch Management**:
   * Tracks the current epoch and calculates the start of the next epoch.
   * Allows modification of epoch-related parameters like length, lock periods, and reward delays.
2. **Admin-Restricted Modifications**:
   * All configuration changes can only be performed by accounts with the `DEFAULT_ADMIN_ROLE`.
3. **Parameter Validations**:
   * Ensures epoch parameters fall within specified minimum and maximum bounds to maintain system stability.
4. **Event Emission**:
   * Emits events whenever epoch parameters are updated, enabling off-chain monitoring and integration.

***

## Key Parameters

### Public Constants

* **`MIN_EPOCH_LENGTH` / `MAX_EPOCH_LENGTH`**: Minimum and maximum allowed blocks per epoch.
* **`MIN_EPOCH_LOCK` / `MAX_EPOCH_LOCK`**: Bounds for the minimum number of epochs tokens can be locked.
* **`MIN_REWARD_DELAY` / `MAX_REWARD_DELAY`**: Bounds for the delay in epochs before rewards can be claimed.

### State Variables

* **`epochLength`**: The number of blocks in an epoch.
* **`firstEpochBlock`**: The block number of the first epoch.
* **`minEpochsLocked`**: Minimum number of epochs tokens are locked.
* **`epochRewardDelay`**: Number of epochs before rewards are claimable.
* **`epochCheckpoint`**: The current epoch checkpoint number.
* **`epochCheckpointBlock`**: Block number when the last checkpoint was updated.

***

## Key Functions

### Constructor

Sets the initial values for the epoch parameters and validates them against the defined bounds.

#### Parameters:

* **`_epochLength`**: Number of blocks in an epoch.
* **`_firstEpochBlock`**: Block number of the first epoch. If zero, it defaults to the next epoch block.
* **`_minEpochsLocked`**: Minimum number of epochs tokens are locked.
* **`_epochRewardDelay`**: Number of epochs before rewards are claimable.

#### Emits:

* `EpochRewardDelayUpdated`
* `MinEpochsLockedUpdated`
* `EpochLengthUpdated`

***

### Epoch Parameter Setters

#### `setEpochLength(uint256 _epochLength)`

* Updates the number of blocks per epoch.
* Reverts if the new epoch length is outside the allowed range or if reducing the epoch length in the current epoch.

#### Emits:

* `EpochLengthUpdated`

***

#### `setMinEpochsLocked(uint256 _minEpochsLocked)`

* Updates the minimum number of epochs tokens are locked.
* Reverts if the new value is outside the allowed range.

#### Emits:

* `MinEpochsLockedUpdated`

***

#### `setEpochRewardDelay(uint256 _epochRewardDelay)`

* Updates the reward delay in epochs.
* Reverts if the new value is outside the allowed range.

#### Emits:

* `EpochRewardDelayUpdated`

***

### Epoch Queries

#### `nextEpochBlock()`

* Returns the block number of the next epoch based on the current block and configured parameters.

***

#### `epochNumber()`

* Returns the current epoch number based on the current block, `epochLength`, and `epochCheckpoint`.

***

## Access Control

The contract uses OpenZeppelin's `AccessControl` for role-based access management.

### Roles:

* **`DEFAULT_ADMIN_ROLE`**:
  * Has the authority to update epoch parameters.
  * Assigned to the deploying account during contract initialization.

***

## Events

* **`EpochLengthUpdated(uint256 epochLength)`**\
  Emitted when the epoch length is updated.
* **`MinEpochsLockedUpdated(uint256 minEpochsLocked)`**\
  Emitted when the minimum epochs lock parameter is updated.
* **`EpochRewardDelayUpdated(uint256 epochRewardDelay)`**\
  Emitted when the epoch reward delay parameter is updated.

## Usage Examples

### Initialization

```solidity
EpochController epochController = new EpochController(
    100,        // epochLength (blocks)
    1000000,    // firstEpochBlock
    10,         // minEpochsLocked
    5           // epochRewardDelay
);
```

### Querying Epoch Information

```solidity
uint256 currentEpoch = epochController.epochNumber();
uint256 nextEpochStartBlock = epochController.nextEpochBlock();
```

This contract is designed to be a robust and flexible controller for epoch-based systems, enabling precise control over time-sensitive operations in decentralized environments.


# GatewayRegistry.sol

The `GatewayRegistry` contract serves as a management system for gateways, facilitating their registration, staking, metadata updates, and lifecycle operations. It ensures secure, role-based access and maintains an organized registry of gateways.

***

## Key Features

1. **Gateway Registration**:
   * Allows users to register gateways with unique identifiers and metadata.
   * Supports optional FUNC token staking during registration.
2. **Metadata Management**:
   * Provides functions to update metadata associated with gateways.
3. **Lifecycle Operations**:
   * Supports activation, deactivation, and wind-down of gateways.
4. **Access Control**:
   * Enforces role-based access for administrative functions.
   * Restricts gateway-specific actions to their respective owners.
5. **Event Logging**:
   * Logs key events such as gateway registration, updates, and lifecycle changes.

***

## Contract Roles

### Access Control

The contract uses OpenZeppelin's `AccessControl` to implement role-based permissions.

* **`DEFAULT_ADMIN_ROLE`**:
  * Grants access to administrative functions like toggling auto-whitelist.

### Modifiers

* **`onlyRegisteredGatewayOwner`**:
  * Restricts certain actions to the owner of a registered gateway.

***

## Data Structures

### Gateway

Represents a registered gateway.

* **`owner`**: Address of the gateway's owner.
* **`id`**: Unique identifier for the gateway.
* **`registeredAt`**: Block number when the gateway was registered.
* **`metadata`**: Metadata string associated with the gateway.
* **`active`**: Boolean indicating whether the gateway is active.

***

## Key Functions

### Constructor

Initializes the `GatewayRegistry` contract with references to the FUNC token and Router contract.

#### Parameters:

* **`_FUNC`**: Address of the FUNC ERC20 token contract.
* **`_router`**: Address of the Router contract.

***

### Registration and Staking

#### `register(bytes calldata _id, string memory metadata)`

Registers a new gateway with optional metadata.

* **Parameters**:
  * `_id`: Unique identifier for the gateway.
  * `metadata`: Metadata string (max length: `1024`).
* **Emits**:
  * `GatewayRegistered(_id, metadata)`

***

#### `registerAndStake(bytes calldata _id, string memory metadata, uint256 amount)`

Registers a new gateway and stakes FUNC tokens.

* **Parameters**:
  * `_id`: Unique identifier for the gateway.
  * `metadata`: Metadata string (max length: `1024`).
  * `amount`: Amount of FUNC tokens to stake.
* **Emits**:
  * `GatewayRegisteredAndStaked(_id, amount, metadata)`

***

### Lifecycle Operations

#### `windDownCluster()`

Winds down all gateways owned by the caller.

* **Emits**:
  * `GatewayClusterWindDown(msg.sender)`

***

#### `unstakeCluster()`

Unstakes all gateways owned by the caller.

* **Emits**:
  * `GatewayClusterUnstake(msg.sender)`
  * Logs errors for failed unstaking attempts.

***

### Metadata Management

#### `updateMetadata(bytes calldata _id, string memory metadata)`

Updates the metadata of a registered gateway.

* **Parameters**:
  * `_id`: Unique identifier for the gateway.
  * `metadata`: New metadata string (max length: `1024`).
* **Emits**:
  * `GatewayMetadataUpdated(_id)`

***

### Activation and Deactivation

#### `deactivate(bytes calldata _id)`

Deactivates a registered gateway.

* **Parameters**:
  * `_id`: Unique identifier for the gateway.
* **Emits**:
  * `GatewayDeactivated(_id)`

***

#### `reactivate(bytes calldata _id)`

Reactivates a registered gateway.

* **Parameters**:
  * `_id`: Unique identifier for the gateway.
* **Emits**:
  * `GatewayReactivated(_id)`

***

### Query Functions

#### `getGatewayIds()`

Returns the list of all registered gateway IDs.

* **Returns**:
  * Array of all gateway IDs.

***

#### `getGatewayIdsByOwner(address _owner)`

Returns the list of gateway IDs owned by a specific address.

* **Parameters**:
  * `_owner`: Address of the gateway owner.
* **Returns**:
  * Array of gateway IDs owned by the specified address.

***

#### `getActiveGatewayIds()`

Returns the IDs of all currently active gateways.

* **Returns**:
  * Array of active gateway IDs.

***

#### `getActiveGateways()`

Returns a list of all currently active gateways.

* **Returns**:
  * Array of `Gateway` structs representing active gateways.

***

#### `getActiveGatewayCount()`

Returns the count of currently active gateways.

* **Returns**:
  * Number of active gateways.

***

#### `getGateway(bytes calldata _id)`

Returns the `Gateway` struct associated with a given `_id`.

* **Parameters**:
  * `_id`: Unique identifier of the gateway.
* **Returns**:
  * A `Gateway` struct containing the gateway's details.

***

#### `registered(bytes calldata _id)`

Checks if a gateway is registered.

* **Parameters**:
  * `_id`: Unique identifier of the gateway.
* **Returns**:
  * Boolean indicating whether the gateway is registered.

***

## Events

* **`GatewayRegistered(bytes id, string metadata)`**\
  Emitted when a gateway is registered.
* **`GatewayRegisteredAndStaked(bytes id, uint256 amount, string metadata)`**\
  Emitted when a gateway is registered and staked.
* **`GatewayClusterWindDown(address indexed owner)`**\
  Emitted when a gateway cluster is wound down.
* **`GatewayClusterUnstake(address indexed owner)`**\
  Emitted when a gateway cluster is unstaked.
* **`GatewayMetadataUpdated(bytes id)`**\
  Emitted when a gateway's metadata is updated.
* **`GatewayDeactivated(bytes id)`**\
  Emitted when a gateway is deactivated.
* **`GatewayReactivated(bytes id)`**\
  Emitted when a gateway is reactivated.
* **`LogError(string message)`**\
  Emitted when an error occurs during gateway unstaking operations.


# GatewayCheckpoint.sol

The `GatewayCheckpoint` contract is a core component for managing gateway-related state and historical data. It allows administrators and schedulers to create and update checkpoints for gateways, enabling operations such as staking, unstaking, and compute unit tracking.

***

## Key Features

1. **Gateway Checkpoint Management**:
   * Supports the creation of scheduler and operation checkpoints for gateways.
   * Tracks gateway states by epoch for accurate reporting and auditing.
2. **Role-Based Access Control**:
   * Admins and schedulers can update scheduler checkpoints.
   * Gateway staking contracts can update operation checkpoints.
3. **Event-Driven Architecture**:
   * Emits events for every checkpoint update, facilitating off-chain integration and monitoring.

***

## Contract Roles

### Access Control

The contract uses OpenZeppelin's `AccessControl` to enforce role-based access.

* **`DEFAULT_ADMIN_ROLE`**:
  * Can manage scheduler checkpoints.
  * Assigned to the deploying address by default.
* **`SCHEDULER_ROLE`**:
  * Can update scheduler checkpoints.

### Modifiers

* **`onlyAdminOrScheduler`**: Restricts function calls to accounts with `DEFAULT_ADMIN_ROLE` or `SCHEDULER_ROLE`.
* **`onlyStaking`**: Restricts function calls to the address of the `GatewayStaking` contract.

***

## Data Structures

### GatewaySchedulerCheckpoint

Represents a scheduler checkpoint for a gateway in a specific epoch.

* **`epoch`**: The epoch of the checkpoint.
* **`gatewayIds`**: Array of gateway IDs included in the checkpoint.
* **`computeUnits`**: Array of compute units for each gateway.
* **`isFinalized`**: Boolean indicating whether the checkpoint is set.

***

### GatewayOperationCheckpoint

Represents an operation checkpoint for a gateway in a specific epoch.

* **`id`**: Gateway ID.
* **`epoch`**: Epoch of the operation.
* **`amount`**: Amount involved in the operation.
* **`totalPoolBalanceAfterOperation`**: Pool balance after the operation.
* **`operation`**: Operation code (e.g., stake, unstake, consume units).

***

## Key Functions

### Constructor

Initializes the `GatewayCheckpoint` contract and sets the router reference.

#### Parameters:

* **`_router`**: Address of the Router contract (cannot be zero).

***

### Scheduler Checkpoints

#### `updateGatewaySchedulerCheckpoint(uint256 _epoch, bytes[] calldata _gatewayIds, uint256[] calldata _computeUnits)`

Creates or updates a scheduler checkpoint for a specified epoch.

* **Parameters**:
  * `_epoch`: The epoch of the checkpoint.
  * `_gatewayIds`: List of gateway IDs.
  * `_computeUnits`: List of compute units for each gateway.
* **Requirements**:
  * `_gatewayIds` and `_computeUnits` must have the same length.
  * A checkpoint for the specified epoch must not already exist.
* **Emits**:
  * `GatewaySchedulerCheckpointUpdated(_epoch)`

***

#### `getGatewaySchedulerCheckpoint(uint256 _epoch)`

Retrieves the scheduler checkpoint for a given epoch.

* **Parameters**:
  * `_epoch`: The epoch of the checkpoint.
* **Returns**:
  * The `GatewaySchedulerCheckpoint` for the epoch.
* **Reverts**:
  * If the checkpoint for the epoch is not set.

***

### Operation Checkpoints

#### `createGatewayOperationCheckpoint(bytes calldata _id, uint256 _amount, uint256 _poolBalanceAfterOperation, uint8 _operation)`

Creates a new operation checkpoint for a gateway.

* **Parameters**:
  * `_id`: Gateway ID.
  * `_amount`: Amount involved in the operation.
  * `_poolBalanceAfterOperation`: Pool balance after the operation.
  * `_operation`: Operation code:
    * `0`: Unstake
    * `1`: Stake
    * `2`: Consume Compute Units
* **Requirements**:
  * Caller must be the `GatewayStaking` contract.
  * `_operation` must be a valid operation code.
* **Emits**:
  * `GatewayOperationCheckpointUpdated(_id, _amount, _operation)`

***

#### `getGatewayOperationCheckpoints(uint256 _epoch)`

Retrieves all operation checkpoints for a given epoch.

* **Parameters**:
  * `_epoch`: The epoch of the checkpoints.
* **Returns**:
  * An array of `GatewayOperationCheckpoint` structs.

***

## Events

* **`GatewaySchedulerCheckpointUpdated(uint256 epoch)`**\
  Emitted when a scheduler checkpoint is updated.
* **`GatewayOperationCheckpointUpdated(bytes id, uint256 amount, uint8 operation)`**\
  Emitted when an operation checkpoint is updated.
  * **`id`**: Gateway ID.
  * **`amount`**: Amount involved in the operation.
  * **`operation`**: Operation code (e.g., stake, unstake, consume units).

## Access and Security

### Role Management

* Admins can assign and revoke roles (`DEFAULT_ADMIN_ROLE`, `SCHEDULER_ROLE`).
* `SCHEDULER_ROLE` is intended for accounts managing scheduler checkpoints.

### Validations

* Checkpoint updates validate input parameters (e.g., lengths, uniqueness).
* Only authorized accounts or contracts can interact with checkpoint creation.

***

## Usage Examples

### Create Scheduler Checkpoint

```solidity
gatewayCheckpoint.updateGatewaySchedulerCheckpoint(
    1,                      // Epoch
    [gatewayId1, gatewayId2], // Gateway IDs
    [100, 200]               // Compute units
);
```

### Create Operation Checkpoint

```solidity
gatewayCheckpoint.createGatewayOperationCheckpoint(
    gatewayId,      // Gateway ID
    50,             // Amount
    1000,           // Pool balance after operation
    1               // Operation code (stake)
);
```


# GatewayStaking.sol

The `GatewayStaking` contract facilitates staking of FUNC tokens for gateways, enabling operations like staking, unstaking, usage tracking, and balance management. It integrates with other ecosystem components for secure and efficient functionality.

***

## Key Features

1. **FUNC Token Staking**:
   * Users can stake FUNC tokens for specific gateways.
   * Supports secure and efficient staking with role-based access controls.
2. **Gateway Lifecycle Management**:
   * Includes operations to wind down gateways, restart them, and track their states.
3. **Overdraw Handling**:
   * Tracks overdrawn stakes for gateways and adjusts balances accordingly.
4. **Burn Functionality**:
   * Implements optional burning of FUNC tokens during gateway operations.
5. **Integration with Ecosystem**:
   * Interacts with Router, GatewayRegistry, and GatewayCheckpoint contracts.

***

## Contract Roles

### Access Control

The contract uses `AccessControlledPausable` for role-based access and pause functionality.

* **`DEFAULT_ADMIN_ROLE`**:
  * Grants access to administrative functions like toggling burn functionality.
* **`onlyCheckpoint` Modifier**:
  * Restricts certain functions to the GatewayCheckpoint contract.

***

## Data Structures

### Gateway State

* **`gatewayShutdownEpochs`**: Tracks shutdown epochs for gateways.
* **`gatewayMostRecentStakeEpochs`**: Tracks the most recent staked epoch for gateways.
* **`gatewayStakeOverdrawn`**: Tracks overdrawn FUNC amounts for gateways.
* **`gatewayStakes`**: Tracks staked FUNC balances for gateways.

***

## Key Functions

### Constructor

#### `constructor(IERC20 _token, IRouter _router)`

Initializes the `GatewayStaking` contract.

* **Parameters**:
  * `_token`: Address of the FUNC ERC20 token contract.
  * `_router`: Address of the Router contract.

***

### Staking Operations

#### `stakeForGateway(bytes calldata _id, uint256 amount)`

Stakes FUNC tokens for a gateway.

* **Parameters**:
  * `_id`: ID of the gateway.
  * `amount`: Amount of FUNC tokens to stake.
* **Requirements**:
  * Gateway must be registered and whitelisted.
  * Caller must be the gateway owner or the registry.
* **Emits**:
  * `GatewayStaked`.

***

#### `unstakeForGateway(bytes calldata _id)`

Unstakes FUNC tokens for a gateway.

* **Parameters**:
  * `_id`: ID of the gateway.
* **Requirements**:
  * Gateway must meet conditions like being shut down and not overdrawn.
  * Minimum epochs locked must be satisfied.
* **Emits**:
  * `GatewayUnstaked`.

***

#### `windDownGateways(bytes[] calldata _gatewayIdsToWindDown)`

Winds down specified gateways.

* **Parameters**:
  * `_gatewayIdsToWindDown`: List of gateway IDs to wind down.
* **Emits**:
  * `GatewayWoundDown`.

***

### Burn and Usage Tracking

#### `checkpointUpdateGatewayUsage(bytes[] calldata _gatewayIds, uint256[] calldata _computeUnits)`

Updates gateway usage and burns FUNC tokens if enabled.

* **Parameters**:
  * `_gatewayIds`: List of gateway IDs.
  * `_computeUnits`: Compute units consumed by the gateways.

***

#### `toggleBurn()`

Toggles the burn functionality.

* **Emits**:
  * `BurnToggled`.

***

### Gateway State Management

#### `restartGateway(bytes calldata _id)`

Restarts a gateway by resetting its shutdown state.

* **Parameters**:
  * `_id`: ID of the gateway.
* **Emits**:
  * `GatewayRestarted`.

***

### Query Functions

#### `getAvailableComputeUnitsForGateways(bytes[] calldata _ids)`

Returns available compute units for specified gateways.

* **Parameters**:
  * `_ids`: List of gateway IDs.
* **Returns**:
  * Array of available compute units for each gateway.

***

#### `getGatewayShutdownEpoch(bytes calldata _id)`

Returns the shutdown epoch for a gateway.

* **Parameters**:
  * `_id`: ID of the gateway.
* **Returns**:
  * Shutdown epoch or `0` if not shut down.

***

#### `getGatewayMostRecentStakedEpoch(bytes calldata _id)`

Returns the most recent staked epoch for a gateway.

* **Parameters**:
  * `_id`: ID of the gateway.
* **Returns**:
  * Most recent staked epoch.

***

#### `getGatewayStakeOverdrawnAmount(bytes calldata _id)`

Returns the overdrawn FUNC amount for a gateway.

* **Parameters**:
  * `_id`: ID of the gateway.
* **Returns**:
  * Overdrawn FUNC amount.

***

#### `getGatewayStakedAmount(bytes calldata _id)`

Returns the staked FUNC amount for a gateway.

* **Parameters**:
  * `_id`: ID of the gateway.
* **Returns**:
  * Staked FUNC amount.

***

#### `getGatewayTotalBalance()`

Returns the total FUNC balance staked across all gateways.

* **Returns**:
  * Total staked FUNC balance.

***

## Events

* **`GatewayStaked(bytes id, uint256 epoch, uint256 amount)`**\
  Emitted when FUNC is staked for a gateway.
* **`GatewayUnstaked(bytes id, uint256 epoch, uint256 amount)`**\
  Emitted when FUNC is unstaked for a gateway.
* **`GatewayWoundDown(bytes id, uint256 epoch)`**\
  Emitted when a gateway is wound down.
* **`GatewayRestarted(bytes id, uint256 epoch)`**\
  Emitted when a gateway is restarted.
* **`GatewayBurn(bytes id, uint256 epoch, uint256 amount)`**\
  Emitted when FUNC is burned during a gateway operation.
* **`GatewayOverdrawn(bytes id, uint256 epoch, uint256 amount)`**\
  Emitted when a gateway becomes overdrawn.
* **`BurnToggled()`**\
  Emitted when burn functionality is toggled.


# ProviderStakingFactory.sol

The `ProviderStakingFactory` contract is responsible for creating and managing instances of `ProviderStaking` contracts. It facilitates model registration, minimal proxy cloning for efficiency, and integration with the `Model` and `Router` contracts.

***

## Key Features

1. **Dynamic Staking Contract Creation**:
   * Creates new `ProviderStaking` contracts using the minimal proxy pattern.
   * Links new contracts to models in the `Model` contract.
2. **Model Integration**:
   * Registers newly created `ProviderStaking` instances with the `Model` contract and links them to the `Router`.
3. **Access Control**:
   * Role-based access control ensures secure operations.
   * Supports admin and model creator roles.
4. **Efficiency**:
   * Uses the minimal proxy pattern (via OpenZeppelin's `Clones`) to optimize contract deployment.

***

## Roles and Access Control

* **`DEFAULT_ADMIN_ROLE`**:
  * Full administrative control over the contract.
  * Can set the `ProviderStaking` implementation address.
* **`MODEL_CREATOR_ROLE`**:
  * Limited to creating new models and associated `ProviderStaking` contracts.

***

## State Variables

* **Core Components**:
  * `FUNC`: Address of the FUNC ERC20 token.
  * `router`: Address of the Router contract.
* **Provider Staking Implementation**:
  * `providerStakingImplementation`: Address of the `ProviderStaking` implementation contract.
  * `providerStakingImplementationAddressSet`: Tracks whether the implementation address has been set.

***

## Key Functions

### Administrative Functions

#### `setProviderStakingImplementation`

Sets the address of the `ProviderStaking` implementation contract for minimal proxy cloning.

* **Access**: `DEFAULT_ADMIN_ROLE`
* **Parameters**:
  * `_implementation`: Address of the `ProviderStaking` implementation contract.

***

### Staking Contract Creation

#### `createNewProviderStaking`

Creates a new `ProviderStaking` contract using a minimal proxy, registers it with the `Model` contract, and links it in the `Router`.

* **Access**: `DEFAULT_ADMIN_ROLE` or `MODEL_CREATOR_ROLE`
* **Parameters**:
  * `_modelId`: Unique ID for the model being created.
  * `_shards`: Number of shards allocated to the model.
  * `_computeUnits`: Number of compute units associated with the model.
  * `_stakeAmount`: Required stake amount for the model.
  * `_modelName`: Name of the model.
* **Returns**: Address of the newly created `ProviderStaking` contract.

***

## Workflow

1. **Set ProviderStaking Implementation**:
   * Admin sets the address of the `ProviderStaking` implementation contract via `setProviderStakingImplementation`.
2. **Create New Provider Staking**:
   * A user with the appropriate role calls `createNewProviderStaking`.
   * A new `ProviderStaking` instance is created using the minimal proxy pattern.
   * The new instance is initialized and registered with the `Model` contract.

***

## Events

* **`ProviderStakingCreated(uint256 indexed modelId, address indexed providerStakingAddress, string modelName)`**:
  * Emitted when a new `ProviderStaking` contract is created.

***

## Example Usage

1. **Setting the ProviderStaking Implementation**:

```solidity
providerStakingFactory.setProviderStakingImplementation(address(providerStakingImplementation));
```

2. **Creating a New ProviderStaking Contract**:

```solidity
providerStakingFactory.createNewProviderStaking(
    1,            // Model ID
    100,          // Number of shards
    1000,         // Compute units
    500 * 10**18, // Required stake amount
    "Example Model" // Model name
);
```


# ProviderRegistry.sol

The `ProviderRegistry` contract manages provider registration, metadata updates, staking integration, and lifecycle management. It is a core component of the system, facilitating interactions between providers and the broader staking and rewards framework.

***

## Key Features

1. **Provider Registration**:
   * Providers can register with or without metadata.
   * Supports staking during registration for seamless integration.
2. **Metadata Management**:
   * Providers can update their metadata post-registration.
3. **Staking Integration**:
   * Automatically stakes FUNC tokens during registration if enabled.
   * Integrates with `ProviderStaking` for staking and reward management.
4. **Lifecycle Management**:
   * Supports activation and deactivation of providers.
   * Handles provider unstaking and reward claims.
5. **Access Control**:
   * Role-based access ensures secure operations.
   * Owner-only modifications for registered providers.
6. **Whitelisting**:
   * Automatic or manual whitelisting of providers upon registration.

***

## Roles and Access Control

* **`DEFAULT_ADMIN_ROLE`**:
  * Full administrative control over the contract.
* **Modifiers**:
  * `onlyRegisteredProvider`: Ensures the caller is the owner of a registered provider.

***

## State Variables

* **Core Components**:
  * `FUNC`: The FUNC token used for staking.
  * `router`: Router contract for system integration.
* **Provider Data**:
  * `providerIds`: List of all registered provider IDs.
  * `providers`: Mapping from provider IDs to provider details.
  * `providerIdsByOwner`: Mapping from owner addresses to their provider IDs.
* **Whitelisting**:
  * `autoWhitelist`: Boolean to control automatic whitelisting of registered providers.

***

## Key Functions

### Registration

#### `register`

Registers a provider with optional metadata.

* **Parameters**:
  * `_id`: Unique provider ID.
  * `_modelId`: Model ID associated with the provider.
  * `metadata`: Metadata string (optional).

***

#### `registerAndStake`

Registers a provider and stakes FUNC tokens for the associated staking contract.

* **Parameters**:
  * `_id`: Unique provider ID.
  * `_modelId`: Model ID associated with the provider.
  * `metadata`: Metadata string.

***

### Provider Management

#### `deactivate`

Deactivates a provider, marking it as inactive.

* **Parameters**:
  * `_id`: Unique provider ID.

***

#### `reactivate`

Reactivates a provider, marking it as active.

* **Parameters**:
  * `_id`: Unique provider ID.

***

#### `updateMetadata`

Updates the metadata for a specific provider.

* **Parameters**:
  * `_id`: Unique provider ID.
  * `metadata`: New metadata string.

***

### Staking and Rewards

#### `claimRewardsCluster`

Claims rewards for all providers owned by the caller within a specified epoch range.

* **Parameters**:
  * `_fromEpoch`: Starting epoch.
  * `_toEpoch`: Ending epoch.

***

#### `unstakeCluster`

Unstakes all providers owned by the caller.

***

### Whitelisting

#### `toggleAutomaticWhitelist`

Toggles the automatic whitelisting feature.

***

### View Functions

#### `getProvider`

Retrieves details of a provider by ID.

* **Parameters**:
  * `_id`: Unique provider ID.
* **Returns**:
  * `Provider` struct containing provider details.

***

#### `getActiveProviders`

Returns a list of all active providers.

* **Returns**:
  * Array of `Provider` structs representing active providers.

***

#### `getActiveProviderIds`

Returns a list of IDs for all active providers.

* **Returns**:
  * Array of provider IDs.

***

#### `getProviderIds`

Returns a list of all registered provider IDs.

* **Returns**:
  * Array of provider IDs.

***

#### `getProviderIdsByOwner`

Returns a list of provider IDs owned by a specific address.

* **Parameters**:
  * `_owner`: Owner address.
* **Returns**:
  * Array of provider IDs.

***

#### `active`

Checks if a provider is active.

* **Parameters**:
  * `_id`: Unique provider ID.
* **Returns**:
  * Boolean indicating if the provider is active.

***

#### `registered`

Checks if a provider is registered.

* **Parameters**:
  * `_id`: Unique provider ID.
* **Returns**:
  * Boolean indicating if the provider is registered.

***

## Events

* **`ProviderRegistered(bytes id)`**:
  * Emitted when a provider is registered.
* **`ProviderRegisteredAndStaked(bytes id)`**:
  * Emitted when a provider is registered and staked.
* **`ProviderDeactivated(bytes id)`**:
  * Emitted when a provider is deactivated.
* **`ProviderReactivated(bytes id)`**:
  * Emitted when a provider is reactivated.
* **`ProviderMetadataUpdated(bytes id)`**:
  * Emitted when a provider's metadata is updated.
* **`RewardClaimedForCluster(address indexed owner, uint256 succeeded, uint256 attempted, uint256 fromEpoch, uint256 toEpoch)`**:
  * Emitted when rewards are claimed for a cluster of providers.
* **`UnstakeCluster(address indexed owner, uint256 succeeded, uint256 attempted)`**:
  * Emitted when unstaking is performed for a cluster of providers.


# ProviderCheckpoint.sol

The `ProviderCheckpoint` contract manages state tracking, checkpoint creation, and reward distribution for Providers. It integrates with other system components, including the Router, to facilitate operations like staking, unstaking, and rewards management.

***

## Key Features

1. **Provider Checkpoints**:
   * Tracks provider-related operations (e.g., staking, unstaking, rewards) using operation checkpoints.
2. **Scheduler Integration**:
   * Creates scheduler checkpoints for models to aggregate and finalize shard contributions and rewards.
3. **Reward Management**:
   * Tracks and finalizes provider reward checkpoints for specific epochs.
4. **Access Control**:
   * Securely restricts functions to admin or scheduler roles.
5. **Router Integration**:
   * Facilitates interactions with other system components via the Router.

***

## Roles

### Access Control

The contract uses `AccessControl` to manage roles and permissions.

* **`DEFAULT_ADMIN_ROLE`**:
  * Grants full administrative access to the contract.
* **`SCHEDULER_ROLE`**:
  * Allows schedulers to perform operations like creating checkpoints.

***

## State Variables

* **Router Reference**:
  * `router`: The Router contract used to interact with other system components.
* **Checkpoint Mappings**:
  * `providerSchedulerCheckpoints`: Maps model IDs and epochs to scheduler checkpoints.
  * `providerOperationCheckpoints`: Maps model IDs to an array of operation checkpoints.
  * `providerOperationCheckpointsByEpoch`: Maps model IDs and epochs to an array of operation checkpoints.
  * `providerRewardCheckpoints`: Maps provider IDs and epochs to reward checkpoints.
  * `shardSumsForEpoch`: Tracks the sum of shards for each model ID and epoch.
  * `providerShardsInEpoch`: Tracks provider shards for each model ID and epoch.
  * `rewardCheckpointBatch`: Tracks the reward batch ID for each model ID and epoch.
* **Last Updated Epoch**:
  * `lastSchedulerUpdatedEpochForModel`: Tracks the last epoch where a scheduler checkpoint was updated for each model.

***

## Key Functions

### Constructor

#### `constructor(IRouter _router)`

Initializes the contract and assigns the deployer the `DEFAULT_ADMIN_ROLE`.

* **Parameters**:
  * `_router`: Address of the `Router` contract.

***

### Checkpoint Creation

#### `createProviderRewardsCheckpoints`

Creates provider reward checkpoints for a specified model ID and epoch.

* **Parameters**:
  * `_batchId`: The reward batch ID.
  * `_modelId`: The ID of the model.
  * `_epoch`: The epoch for the rewards.
  * `_providerShards`: Array of provider shards contributing to the rewards.
* **Access Control**:
  * Callable by accounts with `DEFAULT_ADMIN_ROLE` or `SCHEDULER_ROLE`.

***

#### `createProviderSchedulerCheckpoint`

Creates a scheduler checkpoint for a specified model ID and epoch.

* **Parameters**:
  * `_modelId`: The ID of the model.
  * `_epoch`: The epoch for the checkpoint.
  * `_totalShards`: Total shards in the epoch.
  * `_totalRewardsForEpoch`: Total rewards for the epoch.
  * `_expectedRewardBatchId`: The expected batch ID for rewards.
* **Access Control**:
  * Callable by accounts with `DEFAULT_ADMIN_ROLE` or `SCHEDULER_ROLE`.

***

#### `createProviderOperationCheckpoint`

Creates an operation checkpoint for a specific provider.

* **Parameters**:
  * `_id`: The ID of the provider.
  * `_amount`: The amount involved in the operation.
  * `_poolBalanceAfterOperation`: The balance after the operation.
  * `_operation`: The type of operation (unstake, stake, or claim rewards).
* **Access Control**:
  * Callable only by authorized staking addresses.

***

### Data Retrieval

#### `getProviderSchedulerCheckpoint`

Retrieves the scheduler checkpoint for a specified model ID and epoch.

* **Parameters**:
  * `_modelId`: The ID of the model.
  * `_epoch`: The epoch for which the checkpoint is requested.
* **Returns**:
  * A `ProviderSchedulerCheckpoint` struct.

***

#### `getProviderOperationCheckpoints`

Retrieves all operation checkpoints for a specified model ID.

* **Parameters**:
  * `_modelId`: The ID of the model.
* **Returns**:
  * An array of `ProviderOperationCheckpoint` structs.

***

#### `getProviderOperationCheckpointsByEpoch`

Retrieves operation checkpoints for a specific model ID and epoch.

* **Parameters**:
  * `_modelId`: The ID of the model.
  * `_epoch`: The epoch for which the checkpoints are requested.
* **Returns**:
  * An array of `ProviderOperationCheckpoint` structs.

***

#### `getProviderRewardCheckpoint`

Retrieves the reward checkpoint for a specific provider ID and epoch.

* **Parameters**:
  * `_id`: The ID of the provider.
  * `_epoch`: The epoch for which the reward checkpoint is requested.
* **Returns**:
  * A `ProviderRewardCheckpoint` struct.

***

## Events

* **`ProviderSchedulerCheckpointUpdated(uint256 indexed modelId, uint256 indexed epoch)`**:
  * Emitted when a scheduler checkpoint is updated.
* **`ProviderOperationCheckpointUpdated(bytes id, uint256 amount, uint8 operation)`**:
  * Emitted when an operation checkpoint is created.


# ProviderStaking.sol

The `ProviderStaking` contract enables staking FUNC tokens to earn rewards for providers. It integrates with other system components to handle staking, unstaking, reward claiming, and tracking provider states.

***

## Key Features

1. **Staking and Unstaking**:
   * Providers can stake FUNC tokens to participate in the system and earn rewards.
   * Unstaking is permitted after a lock period.
2. **Reward Management**:
   * Tracks and distributes rewards to providers based on their contributions during specific epochs.
3. **Boost Mechanism**:
   * Allows additional rewards to be distributed across a fixed number of epochs.
4. **Epoch Tracking**:
   * Maintains balances and rewards at the epoch level for accurate distribution and historical tracking.
5. **Integration with Router**:
   * Interacts with system components such as the `Router`, `ProviderCheckpoint`, and `ProviderRegistry`.
6. **Access Control**:
   * Securely restricts function access using roles and modifiers.

***

## Roles and Access Control

* **`DEFAULT_ADMIN_ROLE`**:
  * Full administrative access to the contract.
* **Modifiers**:
  * `onlyInitialized`: Ensures the contract is initialized.
  * `onlyRegisteredProvider`: Ensures the provider is registered.
  * `onlyWhitelistedProvider`: Ensures the provider is whitelisted.
  * `onlyProviderCheckpoint`: Restricts access to the `ProviderCheckpoint` contract.

***

## State Variables

* **Core Contracts**:
  * `FUNC`: The FUNC token used for staking.
  * `router`: The Router contract for system integration.
  * `modelId`: The unique ID of the model associated with this staking pool.
* **Staking and Rewards**:
  * `effectiveStakedBalance`: Total effective staked balance in the pool.
  * `providerStakeEpochs`: Tracks the most recent epoch a provider staked in.
  * `providerStakes`: Tracks the amount staked by each provider.
  * `providerRewardsClaimed`: Tracks claimed rewards for providers by epoch.
* **Epoch Management**:
  * `epochRewardHardCap`: Maximum rewards distributed in an epoch.
  * `lastUpdatedEpoch`: The last epoch when balances were updated.
  * `rewardsToBeDistributedAtEpoch`: Rewards distributed in each epoch.
  * `effectiveStakedBalanceAtEpoch`: Effective staked balance at each epoch.
* **Boosts**:
  * `boosts`: Array of additional rewards distributed over epochs.
  * `boostIndex`: Current index of boosts yet to be applied.

***

## Key Functions

### Initialization

#### `initialize`

Initializes the contract with the FUNC token, router, model ID, and admin.

* **Parameters**:
  * `_token`: The FUNC token address.
  * `_router`: The Router contract address.
  * `_modelId`: The unique model ID for this pool.
  * `_admin`: The address granted `DEFAULT_ADMIN_ROLE`.

***

### Staking and Unstaking

#### `stakeForProvider`

Allows providers to stake FUNC tokens for their participation.

* **Requirements**:
  * Provider must be registered and whitelisted.
  * Model associated with the provider must exist and be enabled.
  * Staking amount must not exceed the required stake amount.

***

#### `unstakeProvider`

Enables providers to unstake FUNC tokens after the lock period.

* **Requirements**:
  * Provider must be registered and whitelisted.
  * Lock period must have elapsed.
  * Staking amount must be greater than zero.

***

### Reward Management

#### `claimRewards`

Allows providers to claim rewards for a specified range of epochs.

* **Parameters**:
  * `_id`: The provider ID.
  * `_fromEpoch`: The starting epoch for claiming rewards.
  * `_toEpoch`: The ending epoch for claiming rewards.
* **Requirements**:
  * Provider must have valid rewards for the specified epochs.
  * Rewards cannot be claimed for future epochs or epochs within the lock period.

***

#### `boostRewardsForNEpochs`

Boosts rewards for the next N epochs.

* **Parameters**:
  * `_epochs`: Number of epochs to boost.
  * `_amount`: Total FUNC amount to boost.
* **Requirements**:
  * `_epochs` and `_amount` must be greater than zero.
  * `_amount` must be evenly divisible by `_epochs`.

***

#### `setTotalRewardForEpoch`

Sets the total rewards for a specific epoch.

* **Parameters**:
  * `_epoch`: The epoch to set the reward for.
  * `_rewardAmount`: The reward amount.
  * `_utilized`: Whether to apply boosts.
* **Access Control**:
  * Callable only by the `ProviderCheckpoint` contract.

***

### View Functions

#### `viewRewards`

Returns the total rewards available for a provider within a specified epoch range.

***

#### `totalRewardForEpoch`

Returns the total rewards for a given epoch.

***

#### `isProviderLive`

Checks if a provider is live based on its stake and eligibility.

***

#### `getProviderStakedAmount`

Returns the staked amount for a specific provider.

***

#### `getEffectiveStakedBalance`

Returns the current effective staked balance of the pool.

***

## Events

* **`ProviderStaked(bytes id, uint256 modelId, uint256 epoch, uint256 amount)`**:
  * Emitted when a provider stakes FUNC.
* **`ProviderUnstaked(bytes id, uint256 modelId, uint256 epoch, uint256 amount)`**:
  * Emitted when a provider unstakes FUNC.
* **`ProviderClaimedRewards(bytes id, uint256 modelId, uint256 fromEpoch, uint256 toEpoch, uint256 amount)`**:
  * Emitted when a provider claims rewards.
* **`BoostForNEpochs(address indexed sender, uint256 epochs, uint256 amount)`**:
  * Emitted when boosts are added for epochs.
* **`EpochHardCapUpdated(uint256 indexed epoch, uint256 hardCap)`**:
  * Emitted when the reward hard cap is updated.
* **`RewardSetForEpoch(uint256 indexed epoch, uint256 rewardAmount)`**:
  * Emitted when rewards are set for an epoch.
* **`EpochBalancesUpdated(uint256 lastUpdatedEpoch, uint256 currentEpoch)`**:
  * Emitted when epoch balances are updated.


# Model.sol

The `Model` contract manages the registration and lifecycle of machine learning models within the system. It handles operations such as enabling/disabling models, updating staking requirements, and associating staking pools with models.

***

## Key Features

1. **Model Registration and Management**:
   * Supports registering new models with metadata and staking requirements.
   * Allows enabling or disabling of registered models.
2. **Stake Requirement Management**:
   * Admins can update the required staking amount for models.
3. **Integration with Staking Pools**:
   * Models are associated with staking pools for FUNC token staking.
4. **Access Control**:
   * Role-based access control for secure management.

***

## Roles

### Access Control

The contract uses `AccessControl` to secure critical functions.

* **`DEFAULT_ADMIN_ROLE`**:
  * Full control over all administrative functions.
* **`MODEL_CREATOR_ROLE`**:
  * Grants permission to create new models.

***

## State Variables

* **`router`**:
  * Reference to the `Router` contract for system-wide functionalities.
* **`modelIdExists`**:
  * Mapping of model IDs to their existence status.
* **`existingModels`**:
  * Mapping of model IDs to their corresponding `ModelInfo` struct.
* **`modelIds`**:
  * Array of all registered model IDs.

***

## Key Functions

### Constructor

#### `constructor(IRouter _router)`

Initializes the contract and assigns the deployer the `DEFAULT_ADMIN_ROLE`.

* **Parameters**:
  * `_router`: The address of the router contract.

***

### Model Registration

#### `createModel(uint256 _modelId, uint256 _shards, uint256 _computeUnits, uint256 _stakeAmount, IProviderStaking _staking, string _modelName)`

Registers a new model with specified parameters.

* **Parameters**:
  * `_modelId`: Unique ID of the model.
  * `_shards`: Number of shards associated with the model.
  * `_computeUnits`: Compute units required for the model.
  * `_stakeAmount`: Required FUNC staking amount.
  * `_staking`: Associated staking pool.
  * `_modelName`: Name of the model.
* **Access Control**:
  * Callable by accounts with `MODEL_CREATOR_ROLE` or the `ProviderStakingFactory`.

***

### Model Management

#### `enableModel(uint256 _modelId)`

Enables a previously disabled model.

* **Parameters**:
  * `_modelId`: The ID of the model to enable.
* **Access Control**:
  * Callable by accounts with `DEFAULT_ADMIN_ROLE`.

***

#### `disableModel(uint256 _modelId)`

Disables an active model.

* **Parameters**:
  * `_modelId`: The ID of the model to disable.
* **Access Control**:
  * Callable by accounts with `DEFAULT_ADMIN_ROLE`.

***

#### `updateModel(uint256 _modelId, uint256 _shards, uint256 _computeUnits, string _modelName)`

Updates the metadata of an existing model.

* **Parameters**:
  * `_modelId`: The ID of the model.
  * `_shards`: Updated number of shards.
  * `_computeUnits`: Updated compute units.
  * `_modelName`: Updated model name.
* **Access Control**:
  * Callable by accounts with `DEFAULT_ADMIN_ROLE`.

***

### Staking Management

#### `updateModelStakeRequirement(uint256 _modelId, uint256 amount)`

Updates the FUNC staking requirement for a model.

* **Parameters**:
  * `_modelId`: The ID of the model.
  * `amount`: New FUNC staking requirement.
* **Access Control**:
  * Callable by accounts with `DEFAULT_ADMIN_ROLE`.

***

#### `updateModelStakingPool(uint256 _modelId, IProviderStaking _staking)`

Updates the staking pool associated with a model.

* **Parameters**:
  * `_modelId`: The ID of the model.
  * `_staking`: Address of the new staking pool.
* **Access Control**:
  * Callable by accounts with `DEFAULT_ADMIN_ROLE`.

***

### View Functions

#### `modelStakeAmount(uint256 _modelId) -> uint256`

Returns the staking requirement for a given model ID.

* **Parameters**:
  * `_modelId`: The ID of the model.
* **Returns**:
  * Required FUNC staking amount.

***

#### `modelExists(uint256 _modelId) -> bool`

Checks whether a model with the given ID exists.

* **Parameters**:
  * `_modelId`: The ID of the model.
* **Returns**:
  * `true` if the model exists, `false` otherwise.

***

#### `modelEnabled(uint256 _modelId) -> bool`

Checks if a model is both registered and enabled.

* **Parameters**:
  * `_modelId`: The ID of the model.
* **Returns**:
  * `true` if the model is enabled, `false` otherwise.

***

#### `modelsIds() -> uint256[]`

Returns a list of all registered model IDs.

* **Returns**:
  * An array of model IDs.

***

#### `models() -> ModelInfo[]`

Returns detailed information for all registered models.

* **Returns**:
  * An array of `ModelInfo` structs for all models.

***

## Data Structures

### `ModelInfo`

Represents information about a model.

* **Fields**:
  * `modelId`: Unique ID of the model.
  * `shards`: Number of shards associated with the model.
  * `computeUnits`: Compute units required for the model.
  * `stakeAmount`: Required FUNC staking amount.
  * `providerStakingPool`: Address of the associated staking pool.
  * `modelName`: Name of the model.
  * `enabled`: Boolean indicating if the model is enabled.

***

## Events

* **`ModelCreated(uint256 indexed modelId, string modelName)`**:
  * Emitted when a new model is created.
* **`ModelEnabled(uint256 indexed modelId, bool enabled)`**:
  * Emitted when a model is enabled or disabled.
* **`ModelUpdated(uint256 indexed modelId, string modelName)`**:
  * Emitted when a model's metadata is updated.
* **`ModelStakeRequirementUpdated(uint256 indexed modelId, uint256 oldStakeAmount, uint256 newStakeAmount)`**:
  * Emitted when a model's staking requirement is updated.
* **`ModelStakingPoolUpdated(uint256 indexed modelId, address oldPool, address newPool)`**:
  * Emitted when a model's staking pool is updated.


# Permissions.sol

The `Permissions` contract manages the whitelisting and jailing of Gateways and Providers within the system. It ensures secure access control through role-based mechanisms and integrates with other components for entity registration and epoch management.

***

## Key Features

1. **Whitelisting**:
   * Enables adding or removing Gateways and Providers to/from the whitelist.
   * Entities must be registered before they can be whitelisted.
2. **Jailing**:
   * Allows Gateways or Providers to be temporarily jailed for a specified number of epochs.
   * Supports unjailing entities manually.
3. **Access Control**:
   * Role-based access for admins and whitelisters to manage entities securely.
4. **Batch Processing**:
   * Supports batch operations with a defined maximum batch size to optimize gas usage.

***

## Roles

### Access Control

The contract employs `AccessControl` for secure operations.

* **`DEFAULT_ADMIN_ROLE`**:
  * Grants full administrative privileges for managing the contract.
* **`WHITELISTER_ROLE`**:
  * Allows managing the whitelist and jailing entities.

***

## State Variables

* **`router`**:
  * Reference to the `Router` contract for system-wide integrations.
* **`PROVIDER` / `GATEWAY`**:
  * Constants representing the entity types:
    * `PROVIDER = 0`
    * `GATEWAY = 1`
* **`providerJailedTilEpoch` / `gatewayJailedTilEpoch`**:
  * Mappings of entity IDs to the epoch until which they are jailed.
* **`providerWhitelist` / `gatewayWhitelist`**:
  * Mappings of entity IDs to their whitelist status.
* **`MAX_BATCH_SIZE`**:
  * The maximum number of entities that can be processed in a single batch operation (default: 100).

***

## Key Functions

### Constructor

#### `constructor(IRouter _router)`

Initializes the contract and assigns the deployer the `DEFAULT_ADMIN_ROLE`.

* **Parameters**:
  * `_router`: Address of the `Router` contract.

***

### Whitelisting Functions

#### `whitelisted(bytes calldata _id, uint8 _type) -> bool`

Checks if a Gateway or Provider is whitelisted and not jailed.

* **Parameters**:
  * `_id`: The ID of the entity.
  * `_type`: The entity type (`0` for Provider, `1` for Gateway).
* **Returns**:
  * `true` if the entity is whitelisted and not jailed, otherwise `false`.

***

#### `whitelist(bytes[] calldata _ids, uint8 _type)`

Adds a batch of IDs to the whitelist.

* **Parameters**:
  * `_ids`: Array of IDs to whitelist.
  * `_type`: The entity type (`0` for Provider, `1` for Gateway).
* **Access Control**:
  * Callable by accounts with `DEFAULT_ADMIN_ROLE` or `WHITELISTER_ROLE`.

***

#### `removeFromWhitelist(bytes[] calldata _ids, uint8 _type)`

Removes a batch of IDs from the whitelist.

* **Parameters**:
  * `_ids`: Array of IDs to remove.
  * `_type`: The entity type (`0` for Provider, `1` for Gateway).
* **Access Control**:
  * Callable by accounts with `DEFAULT_ADMIN_ROLE` or `WHITELISTER_ROLE`.

***

### Jailing Functions

#### `jailForEpochs(bytes calldata _id, uint8 _type, uint256 _numEpochs)`

Temporarily jails a Gateway or Provider for a specified number of epochs.

* **Parameters**:
  * `_id`: The ID of the entity.
  * `_type`: The entity type (`0` for Provider, `1` for Gateway).
  * `_numEpochs`: The number of epochs to jail the entity.
* **Access Control**:
  * Callable by accounts with `DEFAULT_ADMIN_ROLE` or `WHITELISTER_ROLE`.

***

#### `unjail(bytes calldata _id, uint8 _type)`

Manually unjails a Gateway or Provider.

* **Parameters**:
  * `_id`: The ID of the entity.
  * `_type`: The entity type (`0` for Provider, `1` for Gateway).
* **Access Control**:
  * Callable by accounts with `DEFAULT_ADMIN_ROLE` or `WHITELISTER_ROLE`.

***

## Events

* **`Whitelisted(bytes id, uint8 indexed type)`**:
  * Emitted when an entity is added to the whitelist.
* **`RemovedFromWhitelist(bytes id, uint8 indexed type)`**:
  * Emitted when an entity is removed from the whitelist.
* **`Jailed(bytes id, uint8 indexed type, uint256 numEpochs, uint256 jailUntil)`**:
  * Emitted when an entity is jailed.
* **`Unjailed(bytes id, uint8 indexed type)`**:
  * Emitted when an entity is unjailed.


# Logic.sol

The `Logic` contract is responsible for handling reward calculations and conversions between FUNC tokens and Compute Units (CU) in a blockchain-based ecosystem. It provides functionality to determine FUNC burn amounts, available compute units, and allows for configurable conversion ratios, fee structures, and duration-based discounts.

***

## Key Features

1. **Conversion Logic**:
   * Calculates FUNC burn amounts based on consumed compute units (CU) and dynamic fee structures.
   * Converts FUNC staked amounts into available compute units.
2. **Configurable Tiers**:
   * Allows dynamic fee structures based on staking tiers.
   * Provides additional discounts for long-term staking using epoch-based duration tiers.
3. **Configurable Ratios**:
   * Allows updating of the stake-to-CU conversion ratio via admin-controlled functions.
4. **Access Control**:
   * Utilizes role-based access control for secure administration.

***

## Contract Roles

### Access Control

The contract uses `AccessControl` to restrict access to critical functions.

* **`DEFAULT_ADMIN_ROLE`**:
  * Grants full control over administrative functions like updating the stake-to-CU ratio and configuring tiers.
* **`GOVERNANCE_ROLE`**:
  * Provides governance with permission to update configuration parameters.

***

## State Variables

* **`getStakeToCUNumerator`**:
  * Numerator of the stake-to-CU conversion ratio.
  * Default value: `1`.
* **`getStakeToCUDenominator`**:
  * Denominator of the stake-to-CU conversion ratio.
  * Default value: `1`.
* **`stakeTiers`**:
  * Array of stake tiers defining the minimum stake required and the corresponding final fee (percentage in basis points).
* **`epochDurationTiers`**:
  * Array of duration tiers defining the minimum epochs required and the corresponding discount (percentage in basis points).
* **`minEpochsRequired`**:
  * The global minimum epochs required for staking eligibility to access lower fees.

***

## Key Functions

### Constructor

#### `constructor()`

Initializes the contract with default values and assigns the `DEFAULT_ADMIN_ROLE` to the deployer.

* **Default Values**:
  * `getStakeToCUNumerator`: `1`
  * `getStakeToCUDenominator`: `1`

***

### Conversion Functions

#### `getBurnAmountByCU(uint256 _computeUnits, uint256 _stakedAmount, uint256 _currentEpoch, uint256 _stakeEpoch) -> uint256`

Converts compute units (CU) into the equivalent FUNC burn amount. Incorporates the dynamic fee structure and duration discounts.

* **Parameters**:
  * `_computeUnits`: The number of compute units.
  * `_stakedAmount`: The amount of FUNC staked.
  * `_currentEpoch`: The current epoch.
  * `_stakeEpoch`: The epoch when staking started.
* **Returns**:
  * FUNC amount equivalent to the specified compute units after applying the fee structure.

***

#### `getAvailableCUByStakeAmount(uint256 _amount, uint256 _currentEpoch, uint256 _stakeEpoch) -> uint256`

Converts FUNC staked amounts into available compute units (CU), factoring in the dynamic fee structure.

* **Parameters**:
  * `_amount`: The FUNC amount staked.
  * `_currentEpoch`: The current epoch.
  * `_stakeEpoch`: The epoch when staking started.
* **Returns**:
  * Compute units equivalent to the specified FUNC amount after applying the fee structure.

***

#### `getFinalFee(uint256 _stakedAmount, uint256 _currentEpoch, uint256 _stakeEpoch) -> uint256`

Calculates the final fee percentage for a given stake amount and staking duration. Discounts are combined additively instead of being compounded.

* **Parameters**:
  * `_stakedAmount`: The amount of FUNC staked.
  * `_currentEpoch`: The current epoch.
  * `_stakeEpoch`: The epoch when staking started.
* **Returns**:
  * Final fee percentage (in basis points) after applying the dynamic fee structure and duration discounts.

***

### Configuration Functions

#### `setStakeTiers(uint256[] calldata _minStakes, uint256[] calldata _finalFees)`

Sets the stake tiers for fee calculation. Tiers must be in descending order of `minStakes` and `finalFees`.

* **Parameters**:
  * `_minStakes`: Array of minimum stake amounts for each tier.
  * `_finalFees`: Array of final fees (in basis points) for each tier.
* **Requirements**:
  * Arrays must have the same length.
  * Arrays must be in descending order.

***

#### `setEpochDurationTiers(uint256[] calldata _minEpochs, uint256[] calldata _discounts)`

Sets the duration tiers for additional discounts based on staking duration. Tiers must be in descending order of `minEpochs` and `discounts`.

* **Parameters**:
  * `_minEpochs`: Array of minimum epochs for each tier.
  * `_discounts`: Array of discount percentages (in basis points) for each tier.
* **Requirements**:
  * Arrays must have the same length.
  * Arrays must be in descending order.

***

#### `setMinEpochsRequired(uint256 _minEpochsRequired)`

Updates the global minimum epochs required for staking eligibility to access lower fees.

* **Parameters**:
  * `_minEpochsRequired`: New minimum epochs required.

***

#### `setStakeToCUNumeratorDenominator(uint256 _stakeToCUNumerator, uint256 _stakeToCUDenominator)`

Updates the stake-to-CU conversion ratio.

* **Parameters**:
  * `_stakeToCUNumerator`: New numerator for the stake-to-CU ratio.
  * `_stakeToCUDenominator`: New denominator for the stake-to-CU ratio.
* **Requirements**:
  * Both `_stakeToCUNumerator` and `_stakeToCUDenominator` must be non-zero.

***

## Events

This contract does not currently emit any events.

***

## Access Control Summary

| Function                           | Role Required    |
| ---------------------------------- | ---------------- |
| `setStakeTiers`                    | Admin/Governance |
| `setEpochDurationTiers`            | Admin/Governance |
| `setMinEpochsRequired`             | Admin/Governance |
| `setStakeToCUNumeratorDenominator` | Admin/Governance |

***


# Treasury.sol

The `Treasury` contract is responsible for managing FUNC tokens held within the treasury and distributing rewards to providers. It ensures secure and efficient reward handling with proper access control and integration with the FUNC ecosystem.

***

## Key Features

1. **Reward Distribution**:
   * Allows distribution of FUNC tokens to providers as rewards.
   * Verifies the validity of reward claims using the Router contract.
2. **Access Control**:
   * Ensures only authorized entities (admins or staking contracts) can distribute rewards.
3. **Reentrancy Protection**:
   * Incorporates protection mechanisms to prevent reentrancy attacks.

***

## Roles and Access Control

* **`DEFAULT_ADMIN_ROLE`**:
  * Full administrative control over the contract.
  * Can distribute rewards to providers.

***

## State Variables

* **`FUNC`**:
  * Reference to the FUNC ERC20 token contract.
* **`router`**:
  * Reference to the Router contract for accessing provider and staking information.

***

## Constructor

### `constructor`

Initializes the Treasury contract with the FUNC token and Router contract addresses.

* **Parameters**:
  * `_FUNC`: Address of the FUNC ERC20 token contract.
  * `_router`: Address of the Router contract.
* **Access Control**:
  * Grants the deployer the `DEFAULT_ADMIN_ROLE`.

***

## Key Functions

### Reward Distribution

#### `rewardProvider`

Distributes FUNC rewards to a provider.

* **Access**:
  * Only callable by the admin or the staking contract for the provider's model.
* **Parameters**:
  * `_id`: Unique identifier of the provider.
  * `_rewardAmount`: Amount of FUNC tokens to reward the provider.
* **Process**:
  1. Retrieves the provider's model ID using the Router.
  2. Ensures the caller is authorized (either the admin or the staking contract for the model).
  3. Fetches the provider's owner address from the Router.
  4. Transfers the specified reward amount to the provider's owner.
  5. Emits a `ProviderRewarded` event upon successful transfer.
* **Events**:
  * **`ProviderRewarded(bytes _id, address indexed providerOwner, uint256 rewardAmount)`**:
    * Emitted when a provider successfully receives their reward.

***

## Events

* **`ProviderRewarded(bytes _id, address indexed providerOwner, uint256 rewardAmount)`**:
  * Logs the distribution of rewards to a provider.

***

## Reentrancy Protection

The contract implements the `ReentrancyGuard` modifier to prevent reentrancy attacks during reward distribution.

***

## Security Considerations

* Only authorized entities (admin or staking contracts) can distribute rewards.
* Ensures the recipient's owner address is valid before transferring tokens.
* Prevents reward distribution with zero amounts to avoid unnecessary operations.

***

## Fallback Functions

* **`receive()`**: Not implemented; rejects Ether transfers.
* **`fallback()`**: Not implemented; rejects Ether transfers and invalid calls.


# Roadmap

## 🚀 Roadmap for a Decentralized AI Economy

### **🌱 Short-Term (1–6 Months): Laying the Foundation**

1. **Testnet Launch Ceremony**
   * Deploy the **inaugural testnet ceremony**, featuring a high-performance AI model to showcase network capabilities.
   * **Incentivized testing & security bounties**, rewarding early participants for stress-testing, reporting issues, and optimizing performance.
2. **Breaking Barriers to Entry**
   * Open **provider registration**, allowing both consumer-grade and enterprise GPUs to contribute and earn rewards.
   * Enhance the **consumer platform**, improving AI inference access, developer SDKs, and streamlined integration for real-world applications.
3. **AI Compute for Everyone**
   * Seamless **staking & rewards tracking**, providing real-time insights into contributions, earnings, and governance participation.
   * Launch an **intuitive dashboard**, offering compute providers and users an easy way to manage their AI interactions.

***

### **🔧 Medium-Term (6–12 Months): Unlocking the Ecosystem**

1. **Mainnet Launch Ceremony**

* Deploy the the protocol to **mainnet on base network**, supporting over 40+ open source models.
* Rewards for points holders, and starting the journey of **decentralized user-owned AI**.

2. **Bridging Web3 & AI**
   * Enable **FUNC staking for AI inference**, where users can **prepay for AI access using decentralized pools**.
   * Launch **developer tools and SDKs** to integrate Function-powered AI into **dApps, smart contracts, and open-source applications**.

***

### **🌐 Long-Term (12+ Months & Beyond): The Autonomous AI Network**

1. **Decentralizing AI Governance**
   * Give **FUNC holders control** over network parameters like **epoch length, staking requirements, and rewards**.
   * Launch a **transparent proposal system** for **open community decision-making**.
2. **AI as a Public Utility**
   * Build a **decentralized AI model marketplace**, where developers can **upload, share, and monetize their AI models**.
   * Create **functioning inference APIs** that allow **seamless AI access without central intermediaries**.
3. **Privacy-Preserving A**
   * Introduce ZK, FHE, and latest privacy research **for AI inference**, allowing **users to run models on private data without exposing it**.
4. **Self-Regulating AI Network**
   * Implement **dynamic incentive models** where rewards **automatically adjust** based on **demand, compute availability, and participation**.
   * Introduce **autonomous AI model selection**, where the **community decides which models are prioritized**.

***

### **🏆 A Future Where AI Belongs to Everyone**

AI is the most powerful technology of our generation, **but who controls it will define the future.**

We refuse to let AI remain in the hands of a few.

With **Function Network**, we are building an ecosystem where **compute is accessible, AI is open, and intelligence is free.** A world where **anyone can contribute, anyone can access, and no one can control** the future of machine intelligence.

🚀 Join us in shaping the **new era of AI** where intelligence is not a service, but a **right.**


# FAQ

This FAQ provides answers to common questions about the Function Network, covering general information, provider-specific details, gateway operations, and future incentives like points and airdrops.

## General Questions

1. **What is the Function Network?**

   The Function Network is a decentralized platform for AI inference, enabling seamless connections between developers and AI compute providers. It leverages FUNC tokens for staking, rewards, and potentially governance, ensuring a trustless and scalable ecosystem for AI workloads.

   **Why is this important?**

   By decentralizing AI inference, the Function Network reduces dependency on centralized providers, offering greater accessibility, censorship resistance, and cost efficiency. This empowers developers, businesses, and individuals to access AI compute resources securely and affordably.
2. **What are FUNC tokens used for?**

   FUNC tokens are the native currency of the Function Network, used for staking by providers and gateways, distributing rewards for compute contributions, and potentially enabling governance participation in the future.

   **How does this benefit me?**

   Whether you're an AI developer, model creator, compute provider, or end-user, FUNC tokens incentivize participation. Early adopters may gain additional benefits through staking rewards, potential airdrops, or future governance influence, fostering a vibrant and rewarding ecosystem.
3. **Will there be points or airdrops for early users before onchain incentives begin?**

   Yes, early participants engaging in inference requests, compute provision, or FUNC staking may earn points. These points could translate into future airdrops, staking bonuses, or governance influence, with details announced via official channels.

   **How can I participate?**

   Engage early by using the network for AI inference, staking FUNC tokens, or providing compute resources. Active participation increases your eligibility for points and potential future rewards.
4. **How does the Function Network ensure security and reliability?**

   The network employs decentralized consensus mechanisms, staking requirements, and penalties for malicious behavior to maintain security. Providers and gateways are incentivized to uphold high standards, ensuring reliable AI Inference services.

   **Why does this matter to me?**

   A secure and reliable network protects users from disruptions and ensures consistent access to AI compute resources, fostering trust and encouraging widespread adoption.

***

## Provider Questions

1. **What is required to register as a provider?**

   To become a provider, you must register with metadata (typically your node’s URL), stake the required amount of FUNC tokens, and obtain whitelist approval from the network.

   **Why should I become a provider?**

   Providers with idle GPUs or compute resources can earn rewards by contributing to AI inference workloads. This creates a revenue stream while supporting the decentralized AI ecosystem.
2. **What happens if I don’t claim my rewards?**

   Unclaimed rewards remain available indefinitely but are subject to an epoch-based delay before they can be accessed.

   **Can I lose unclaimed rewards?**

   No, unclaimed rewards are safe and won’t expire. However, claiming them promptly allows for reinvestment or additional staking to maximize your network participation.
3. **What is the penalty for being jailed?**

   Jailed providers are temporarily barred from staking or claiming rewards during the jail period, which is triggered by network rule violations or insufficient performance.

   **How can I avoid being jailed?**

   Ensure high node availability, maintain correct configurations, and adhere to network protocols. Avoiding malicious or unreliable behavior is critical to staying active and earning rewards.
4. **What does provider metadata represent?**

   Provider metadata typically includes the URL where the provider’s node can be accessed for inference requests, along with other relevant details like supported models or compute capabilities.

   **Why is metadata important?**

   Accurate metadata ensures gateways can efficiently route requests to your node, maximizing your compute utilization and reward potential.
5. **What types of compute resources are most valuable to the network?**

   High-performance GPUs, reliable network connectivity, and optimized software stacks are highly valued, as they enable efficient and scalable AI inference.

   **How can I optimize my setup?**

   Invest in robust hardware, maintain low-latency connections, and regularly update your node’s software to align with network requirements, ensuring competitive performance and higher rewards.
6. **What is an epoch, and how does it function?**

   An epoch is a fixed time period, measured in blocks, during which staking, reward distribution, and network updates are synchronized. Epochs ensure consistent and predictable operations across the network. Understanding epochs is essential for participants involved in staking, providing compute, or receiving rewards. Epoch cycles determine the timing of reward payouts and network updates, helping users plan their participation effectively.
7. **How are rewards calculated and distributed?**

   Rewards are calculated based on the shards (units of computational work) contributed by providers during an epoch. These rewards are distributed proportionally from the epoch’s reward pool, incentivizing active participation.

   **How can I maximize my rewards?**

   Providers can increase rewards by maintaining high node uptime, optimizing compute efficiency, and ensuring reliable infrastructure. Consistent participation and high-quality service lead to greater reward allocations per epoch.
8. **What is the significance of `minEpochsLocked`?**

   The `minEpochsLocked` parameter specifies the minimum number of epochs that staked FUNC tokens must remain locked before they can be unstaked, ensuring network stability and commitment from participants. Participants should plan their staking duration carefully, as `minEpochsLocked` impacts liquidity. Longer staking periods may offer additional incentives, but users must balance this with their need for token accessibility.

***

## Gateway Questions

1. **How do gateways interact with providers?**

   Gateways aggregate client requests for AI inference and route them to suitable providers based on availability, compute capacity, and performance metrics. Gateways optimize the distribution of AI workloads, reducing latency, minimizing costs, and ensuring efficient resource utilization across the network.
2. **Can gateways unstake immediately?**

   No, gateways must initiate a wind-down process and wait through a staking delay period before unstaking their FUNC tokens, ensuring network stability.

   **What are the risks of unstaking?**

   Unstaking resets your current burn discount tier, which may reduce future incentives. Long-term staking often provides better rewards, so plan your strategy accordingly.
3. **What metadata do gateways need?**

   Gateway metadata includes routing-related information, such as endpoint URLs, supported regions, and availability details, to facilitate efficient request handling. Accurate metadata ensures gateways can effectively match client requests with providers, improving network performance and user experience.
4. **How can gateways optimize their operations?**

   Gateways can enhance performance by maintaining robust infrastructure, minimizing latency, and supporting a wide range of providers and regions. Optimized gateways attract more client requests, increasing their influence and potential rewards within the network.

***

## Additional Questions (Airdrops, Points, and Future Benefits)

1. **Will there be a points system, and how does it work?**

   Before onchain rewards are fully implemented, the Function Network may introduce a points system to track user engagement and contributions. Points could be redeemed for future rewards, airdrops, or governance influence.

   **How can I earn points?**

   Participate in AI inference tasks, stake FUNC tokens, provide compute resources, or use Function Chat to qualify for points. Early and active engagement maximizes your point accumulation.
2. **What is the difference between points and rewards?**

   Rewards are onchain incentives paid in FUNC tokens for contributions like compute provision or staking. Points, however, are offchain metrics of engagement and may qualify users for future onchain benefits, such as airdrops or governance roles. Points reward early adopters and active participants, potentially unlocking exclusive benefits as the network grows, giving you a head start in the ecosystem.
3. **When will airdrops be distributed?**

   Airdrop eligibility criteria and distribution timelines will be announced through official Function Network channels. Stay updated to ensure you don’t miss opportunities. Early adopters who engage through inference, staking, or compute provision have the highest likelihood of qualifying for airdrops and other incentives, maximizing their long-term benefits.
4. **How can I stay informed about network updates and opportunities?**

   Follow Function Network’s official channels, including the website, blog, and social media, for the latest announcements on airdrops, points, and network developments. Timely updates ensure you can take advantage of new features, incentives, and governance opportunities, keeping you ahead in the decentralized AI ecosystem.

For further questions or support, contact the Function Network team through our official channels or refer to the [Terms & Conditions](https://www.function.network/tos.txt).


# Glossary of Terms

### **Function Network Core Concepts**

* **Function Network:** A decentralized system designed for AI inference, connecting **Gateways** (clients) to **Providers** (AI model operators) through a tokenized staking and reward mechanism.
* **FUNC Token:** The native utility token of the Function Network, used for staking, rewarding, and facilitating transactions.
* **Provider:** An operator hosting and maintaining AI inference models, offering services through the Function Network.
* **Gateway:** An entity that connects users to providers, aggregating and routing AI inference requests.
* **Epoch:** A fixed time period (in blocks) during which staking, rewards, and network activities are synchronized.
* **Shard:** A unit of work or compute contribution attributed to providers, determining rewards.
* **Stake:** FUNC tokens locked to participate in network operations, either as a provider or gateway.
* **Whitelist:** A status allowing providers or gateways to participate in the network.
* **Jail:** A status temporarily restricting a provider or gateway due to violations or inactivity.


