# Getting Started

Welcome to the **Swan Chain Docs**, your centralized resource for all technical documentation and information about the **Swan Chain ecosystem**. Here, you’ll find everything you need to explore and leverage the power of decentralized cloud computing using Swan Chain.

For more details on Swan Chain's governance, community, and vision, visit the [**Swan Chain Governance**](https://github.com/swanchain/governance).

***

## **Guides for Builders**

Whether you're a developer building decentralized applications, a GPU provider looking to join the Swan Chain network, or a contributor creating tools and integrations, this documentation hub has all the resources you need to get started.Explore our comprehensive guides for:

* **Developers** building on Swan Chain and integrating decentralized GPU resources into their applications.
* **Computing Providers** interested in contributing computational power to Swan’s decentralized cloud.
* **Contributors** and community members seeking to create open-source tools, applications, and extensions within the Swan ecosystem.

Start exploring now and join the movement to unlock the potential of decentralized cloud computing!

<table data-view="cards"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td>📄 <strong>Guides</strong></td><td>Get started with a simple guide such as <a href="/pages/bIPhC5gakfUlCQA7QUf2">deploying a contract</a></td></tr><tr><td><strong>🌐 Network reference</strong></td><td>View details about the Swan Chain mainnet such as various important addresses <a href="/pages/LBCYaBlvKrLzxwdPyX9p">here</a>.</td></tr><tr><td><strong>🌟 Core concepts</strong></td><td>Learn about core concepts such as "What is Swan Chain" <a href="https://github.com/swanchain/docs/blob/main/core-concepts/README.md">here</a><a href="https://github.com/swanchain/docs/blob/main/core-concepts/README.md">.</a></td></tr></tbody></table>

***

## I want to become a ...

<table data-view="cards"><thead><tr><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>DApp Developer</strong></td><td><a href="/pages/bIPhC5gakfUlCQA7QUf2">/pages/bIPhC5gakfUlCQA7QUf2</a></td></tr><tr><td><strong>App Developer</strong></td><td><a href="/pages/dg4iKhnN6tmDNYG6Yaer">/pages/dg4iKhnN6tmDNYG6Yaer</a></td></tr><tr><td><strong>Computing Provider</strong></td><td><a href="/pages/d4Dg2uz77btWGvNlQGiT">/pages/d4Dg2uz77btWGvNlQGiT</a></td></tr><tr><td><strong>Storage Provider</strong></td><td><a href="/pages/LsQ717QJ0DpgWFVN6zlJ">/pages/LsQ717QJ0DpgWFVN6zlJ</a></td></tr></tbody></table>


# DApp Developer


# Deploying Your First Smart Contract with Remix

Smart Contracts are written in Solidity, a statically-typed programming language designed for Ethereum and other EVM-compatible chains. This tutorial uses [Remix](https://remix.ethereum.org/#lang=en\&optimize=false\&runs=200\&evmVersion=null), a browser-based IDE that requires minimal setup.

**1.Open Remix IDE:** Navigate to [Remix](https://remix.ethereum.org/).

**2.Create a New Contract:** In the workspace, create a new file with the ".sol" extension, e.g., "MyFirstContract.sol".

**3.Code a Basic Contract:**

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract MessageContract {
    string private message;

    function writeMessage(string calldata newMessage) public {
        message = newMessage;
    }

    function readMessage() public view returns (string memory) {
        return message;
    }
}
```

Remix automatically compiles the contract when saved. Ensure there are no compilation errors.

**4.Compile Manually (Optional):** Click the "Advanced Configurations" tab and select the Solidity version `london`.

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

**5.Deploy the Contract:** Click the "Deploy" icon logo (it looks like an Ethereum logo with an arrow pointing to the right).

<figure><img src="https://lh7-us.googleusercontent.com/ipWX5Hf3N3dLz03VSskdtYs5Y_8wUjy-XAriWpYbZpsX8jucpNBqOMu5sNomIfa8Q3oBCzvqtVsIAlBAsbFVvDC7cERlspm80AbtZEI-oJtWq3mN87yxCagZr1LiXnlK8rbt3b8AqgkAmmkncjpDesw" alt=""><figcaption></figcaption></figure>

**6.Configure Deployment:**

* Select the basic contract.
* Under "Environment," choose "Injected Provider - MetaMask."
* Connect Remix to MetaMask.

<figure><img src="https://lh7-us.googleusercontent.com/IBSDB3_h_dspP8TmnYITbxN6evUr3qi8fkSmi9esFp8lkqNWNCFRh4DoNON58N4Lip38QR9SarNebFAXiIa4VpdRMFgfOPCFbghccUMBi_C6bt0NvVNQlT7XD3bSqTJy5O0Z_Fl7TaO7WDieYtX1gXA" alt=""><figcaption></figcaption></figure>

**7.Initiate Deployment:** Click "Deploy" and confirm the MetaMask transaction.

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

**8.Interact With Your Contract:**

Step1: After deployment, find your contract under "Deployed Contracts."

<figure><img src="https://lh7-us.googleusercontent.com/ll7xe7898NMnbD0klTFPS1lh31XCBPU4tALhEju4Fbz1wot78quV-bhKIXeW-LybFehbPUHHcTEkQ-E_eiGbpZA8t9mQaygJOT9BNDhekkvX09qzvevv3QPe5w6KaAOo6OVL93a4Sbzt1UMnPBnS5Eo" alt=""><figcaption></figcaption></figure>

Step2: Expand the contract and call `writeMessage` by entering a message and clicking the button.

<figure><img src="https://lh7-us.googleusercontent.com/4VaxPuh7P7C0ovrielVb-VRSH89SUmfJngYVpGdDSbA_cK2xu8wm_WFpAsWjXP6nvtnQqvhw3CDWogzlFcf7R549RxJ0IjNM9FqMBgu34pwGXIA1B-vaSlHLljXUVn9Rd-LBP6YjvLIaoVoqhtVKbFk" alt=""><figcaption></figcaption></figure>

<figure><img src="https://lh7-us.googleusercontent.com/pxJUuzfByMz7j1KVU9MDAIxG1S1-2cWTtwUTJgZHreFpVq6KHuh6rnOM-xs_fTrT5KkSYwbo3CMcS5YksjMWmA51TDzKBBLSKv1WzC8TGdP0WgKytCZdv-5O_ENyRZwqU7phYIQI6TKRW7sMPETgLXs" alt=""><figcaption></figcaption></figure>

Step3: Confirm the MetaMask transaction.

**Step4: Read the Message:**

Click the blue "readMessage" button to read the on-chain message.

<figure><img src="https://lh7-us.googleusercontent.com/Og4j16JQNEGhVqxe0p_t9B4prneNgTh_SxOr0g3hOU8q_uZ_7eUxCYIf6nj1LSGxQ4_Is3p_lE3IVGV7qLarKK9c9xZo93LBdep6PmKfsy_MHzJrB5o8XBfnw5e1A__F55nqaKJ-_VCsRyZmO-IGqG0" alt=""><figcaption></figcaption></figure>

Now you've successfully deployed and interacted with your first smart contract using Remix and MetaMask.


# Interacting with Smart Contract on Swan Chain Using Go

#### Introduction to Swan Chain and Connecting to RPC

* Exploring Swan Chain: An Overview of Its Blockchain Features
* Setting up the Go Development Environment for Swan Chain
* Connecting to a Swan Chain RPC Using Go
* Fetching Basic Blockchain Data from Swan Chain

#### 1.Setting up the Go Development Environment for Swan Chain

<pre><code>package main
// Shared RPC URL
<strong>const rpcURL = "https://mainnet-rpc.swanchain.org" // Replace with your testnet's RPC URL
</strong></code></pre>

#### 2.Connecting to a Swan Chain RPC Using Go

```
func TestConnectToTestnet(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()

	// Assuming rpcURL is defined as a constant or variable that contains your Ethereum testnet RPC URL
	client, err := ethclient.DialContext(ctx, rpcURL)
	if err != nil {
		t.Fatalf("Failed to connect to the testnet: %v", err)
	}
	defer client.Close()

	// Fetching the network ID
	networkID, err := client.NetworkID(ctx)
	if err != nil {
		t.Fatalf("Failed to get network ID: %v", err)
	}

	// Fetching the latest block number
	blockNumber, err := client.BlockNumber(ctx)
	if err != nil {
		t.Fatalf("Failed to get the latest block number: %v", err)
	}

	t.Logf("Network ID: %v", networkID)
	t.Logf("Latest block number: %d", blockNumber)
}
```

#### 3.Managing Wallets and Checking Balances

* Creating and Managing Swan Chain Wallets with Go
* Understanding and Checking Wallet Balances on Swan Chain
* Handling Swan Chain's Native Cryptocurrency Units

```
// TestGetAccountBalance tests fetching the balance for a specific account
func TestGetAccountBalance(t *testing.T) {
   accountAddress := "0xA41c36BCd65bDbFB62FE93E3b7a28d290E63C1F7" // Replace with the account address

   ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
   defer cancel()

   client, err := ethclient.DialContext(ctx, rpcURL)
   if err != nil {
      t.Fatalf("Failed to connect to the mainnet: %v", err)
   }
   defer client.Close()

   address := common.HexToAddress(accountAddress)
   balanceWei, err := client.BalanceAt(ctx, address, nil) // Balance in Wei
   if err != nil {
      t.Fatalf("Failed to get the account balance: %v", err)
   }

   // Convert balance from Wei (big.Int) to Ether (float64)
   balanceEther := new(big.Float).Quo(new(big.Float).SetInt(balanceWei), big.NewFloat(math.Pow10(18)))

   t.Logf("Balance of account [%s]: %f Ether", accountAddress, balanceEther)

}
```

Output:

> \=== RUN TestGetAccountBalance ethclient\_test.go:64: Balance of account \[0xA41c36BCd65bDbFB62FE93E3b7a28d290E63C1F7]: 0.045930 Ether
>
> \--- PASS: TestGetAccountBalance (0.21s)

{% embed url="<https://www.youtube.com/watch?feature=youtu.be&v=o0X_7oDG9T4>" %}

#### 4.Writing and Reading from a Smart Contract

* Setting up Go for Smart Contract Interaction
* Writing Data to a Smart Contract on Swan Chain
* Reading and Interpreting Data from a Smart Contract

Source code can be found here:

{% embed url="<https://github.com/swanchain/ether-test>" %}


# App Developer

Welcome, Web2 developers! This guide will walk you through the process of building applications on [Swan Chain Mainnet](/swan-chain-campaign/swan-chain-mainnet/network-information). If you're new to the web3 world, don't worry - we'll start with the basics and gradually move to more advanced topics.

### Getting Started

Before diving into development, make sure you:

* [Set up your wallet](https://docs.swanchain.io/network-reference/readme/set-up-your-wallet)
* [Bridge tokens from Ethereum to Swan Mainnet](https://docs.swanchain.io/network-reference/readme/bridge-token)

### What You Can Do with Swan Chain

#### **AI Inference with Swan Inference API**

* Access **42+ AI models** (LLM, image, audio, embedding, multimodal) via an **OpenAI-compatible API**
* Drop-in replacement — use any existing OpenAI SDK by changing the base URL to `https://inference.swanchain.io/v1`
* Supports streaming, embeddings, image generation, and audio transcription

Get started with Swan Inference [here](/bulders/app-developer/swan-inference-api).

#### **Deploying with Swan SDK**

* The Swan SDK simplifies interactions with the Swan Chain Network Resource.
* Learn to create and manage computational tasks, retrieve hardware information, process payments, and monitor task statuses.

Explore Swan SDK deployment [here](/bulders/app-developer/deploying-with-swan-sdk).

#### **Store and Retrieve Files with Swan Storage**

* Utilize Multi-Chain Storage (MCS), Swan Chain's decentralized storage solution.
* Learn to install and configure the MCS SDK, manage storage buckets, and handle file operations.

Discover Swan Storage capabilities [here](/bulders/app-developer/store-and-retrieve-a-file-with-swan-storage).

**Building and Pushing Docker Images**

* Learn how to create Docker images for your applications.
* Explore the process of pushing your Docker images to repositories.

Get started with Docker [here](https://github.com/swanchain/docs/blob/main/bulders/app-developer/broken-reference/README.md).

#### Creating Deployment Files with LDL

* The basics of LDL and its relationship to YAML
* How to create `deploy.yaml` files for your Swan Chain projects
* Key components of an LDL file: version, services, profiles, and deployment

Dive into LDL and deployment files [here](/bulders/app-developer/building-docker-images-and-deployment-file-with-ldl/creating-deployment-files-with-ldl).

***

These guides will empower you to harness the full potential of Swan Chain's ecosystem for your applications, from efficient computation management to secure, decentralized file storage.


# Swan Inference API

Call 42+ AI Models via an OpenAI-Compatible API

Swan Inference provides an **OpenAI-compatible REST API** for accessing decentralized AI models. If you've used the OpenAI API or any OpenAI-compatible client, you already know how to use Swan Inference — just change the base URL and API key.

**Base URL**: `https://inference.swanchain.io`

## Quick Start

### 1. Get an API Key

Sign up at [inference.swanchain.io](https://inference.swanchain.io) to get your API key. Keys use the `sk-swan-` prefix.

### 2. Make Your First Request

{% tabs %}
{% tab title="cURL" %}

```bash
curl https://inference.swanchain.io/v1/chat/completions \
  -H "Authorization: Bearer sk-swan-YOUR-API-KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-r1-distill-llama-70b",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "What is Swan Chain?"}
    ]
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
from openai import OpenAI

client = OpenAI(
    base_url="https://inference.swanchain.io/v1",
    api_key="sk-swan-YOUR-API-KEY",
)

response = client.chat.completions.create(
    model="deepseek-r1-distill-llama-70b",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is Swan Chain?"},
    ],
)

print(response.choices[0].message.content)
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://inference.swanchain.io/v1",
  apiKey: "sk-swan-YOUR-API-KEY",
});

const response = await client.chat.completions.create({
  model: "deepseek-r1-distill-llama-70b",
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "What is Swan Chain?" },
  ],
});

console.log(response.choices[0].message.content);
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
    "context"
    "fmt"
    openai "github.com/sashabaranov/go-openai"
)

func main() {
    config := openai.DefaultConfig("sk-swan-YOUR-API-KEY")
    config.BaseURL = "https://inference.swanchain.io/v1"
    client := openai.NewClientWithConfig(config)

    resp, err := client.CreateChatCompletion(
        context.Background(),
        openai.ChatCompletionRequest{
            Model: "deepseek-r1-distill-llama-70b",
            Messages: []openai.ChatCompletionMessage{
                {Role: "system", Content: "You are a helpful assistant."},
                {Role: "user", Content: "What is Swan Chain?"},
            },
        },
    )
    if err != nil {
        panic(err)
    }
    fmt.Println(resp.Choices[0].Message.Content)
}
```

{% endtab %}
{% endtabs %}

That's it — any library or tool that supports the OpenAI API format works with Swan Inference.

***

## Try Without an API Key

Swan Inference offers a **public playground** that lets you try AI inference without signing up.

```bash
curl https://inference.swanchain.io/v1/playground/chat \
  -H "Content-Type: application/json" \
  -d '{
    "model": "MadeAgents/Hammer2.1-0.5b",
    "messages": [{"role": "user", "content": "Hello!"}]
  }'
```

No `Authorization` header required. To list available playground models:

```bash
curl https://inference.swanchain.io/v1/playground/models
```

| Limit             | Value         |
| ----------------- | ------------- |
| Requests per hour | 5 per IP      |
| Max output tokens | 100           |
| Streaming         | Not supported |

{% hint style="info" %}
For full access to all models with higher limits, [sign up](https://inference.swanchain.io/signup) for a free account.
{% endhint %}

### Subscription Plan

For heavy users, Swan Inference offers a **Pro plan at $6/month** with unlimited open-source model access:

| Feature            | Pay-As-You-Go  | Pro ($6/month)                    |
| ------------------ | -------------- | --------------------------------- |
| Open-source models | Pay per token  | Included                          |
| Premium models     | Pay per token  | Pay per token                     |
| Requests/day       | Unlimited      | 1,500                             |
| Tokens/week        | Unlimited      | 40M                               |
| Payment            | Credit balance | Stripe or crypto (USDC/USDT/SWAN) |

***

## Authentication

All API requests require an API key passed in the `Authorization` header:

```
Authorization: Bearer sk-swan-YOUR-API-KEY
```

| Key Prefix  | Purpose                                                        |
| ----------- | -------------------------------------------------------------- |
| `sk-swan-*` | Consumer API key — for making inference requests               |
| `sk-prov-*` | Provider API key — for GPU providers connecting to the network |

***

## API Endpoints

### List Models

Retrieve all available models and their current status.

```
GET /v1/models
```

```bash
curl https://inference.swanchain.io/v1/models \
  -H "Authorization: Bearer sk-swan-YOUR-API-KEY"
```

**Response:**

```json
{
  "object": "list",
  "data": [
    {
      "id": "deepseek-r1-distill-llama-70b",
      "object": "model",
      "owned_by": "swan-inference"
    },
    {
      "id": "llama-3.2-3b",
      "object": "model",
      "owned_by": "swan-inference"
    }
  ]
}
```

You can also browse the full model catalog with pricing at [inference.swanchain.io/models](https://inference.swanchain.io/models).

***

### Chat Completions

Generate chat-based text responses. This is the primary endpoint for interacting with LLMs.

```
POST /v1/chat/completions
```

**Request Body:**

| Parameter           | Type         | Required | Description                                          |
| ------------------- | ------------ | -------- | ---------------------------------------------------- |
| `model`             | string       | Yes      | Model ID (e.g., `deepseek-r1-distill-llama-70b`)     |
| `messages`          | array        | Yes      | Array of message objects with `role` and `content`   |
| `temperature`       | float        | No       | Sampling temperature (0-2). Default: 1.0             |
| `max_tokens`        | integer      | No       | Maximum tokens to generate. Default: model-dependent |
| `stream`            | boolean      | No       | Enable streaming responses. Default: false           |
| `top_p`             | float        | No       | Nucleus sampling threshold. Default: 1.0             |
| `stop`              | string/array | No       | Stop sequence(s)                                     |
| `frequency_penalty` | float        | No       | Frequency penalty (-2 to 2). Default: 0              |
| `presence_penalty`  | float        | No       | Presence penalty (-2 to 2). Default: 0               |

**Example — Standard Request:**

```bash
curl https://inference.swanchain.io/v1/chat/completions \
  -H "Authorization: Bearer sk-swan-YOUR-API-KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "llama-3.2-3b",
    "messages": [
      {"role": "user", "content": "Explain blockchain in one sentence."}
    ],
    "temperature": 0.7,
    "max_tokens": 100
  }'
```

**Response:**

```json
{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1709500000,
  "model": "llama-3.2-3b",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Blockchain is a decentralized, distributed digital ledger that records transactions across many computers so that no single record can be altered retroactively without the alteration of all subsequent blocks."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 12,
    "completion_tokens": 38,
    "total_tokens": 50
  }
}
```

***

### Streaming

Enable real-time token-by-token responses by setting `stream: true`. The response uses **Server-Sent Events (SSE)**.

{% tabs %}
{% tab title="cURL" %}

```bash
curl https://inference.swanchain.io/v1/chat/completions \
  -H "Authorization: Bearer sk-swan-YOUR-API-KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-r1-distill-llama-70b",
    "messages": [{"role": "user", "content": "Write a haiku about GPUs."}],
    "stream": true
  }'
```

{% endtab %}

{% tab title="Python" %}

```python
from openai import OpenAI

client = OpenAI(
    base_url="https://inference.swanchain.io/v1",
    api_key="sk-swan-YOUR-API-KEY",
)

stream = client.chat.completions.create(
    model="deepseek-r1-distill-llama-70b",
    messages=[{"role": "user", "content": "Write a haiku about GPUs."}],
    stream=True,
)

for chunk in stream:
    if chunk.choices[0].delta.content is not None:
        print(chunk.choices[0].delta.content, end="")
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://inference.swanchain.io/v1",
  apiKey: "sk-swan-YOUR-API-KEY",
});

const stream = await client.chat.completions.create({
  model: "deepseek-r1-distill-llama-70b",
  messages: [{ role: "user", content: "Write a haiku about GPUs." }],
  stream: true,
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content || "");
}
```

{% endtab %}
{% endtabs %}

**Stream Response Format:**

Each SSE event contains a JSON chunk:

```
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","choices":[{"delta":{"content":"Silicon"},"index":0}]}

data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","choices":[{"delta":{"content":" hearts"},"index":0}]}

data: [DONE]
```

***

### Embeddings

Generate vector embeddings for text. Useful for search, similarity, and RAG applications.

```
POST /v1/embeddings
```

**Request Body:**

| Parameter | Type         | Required | Description                                |
| --------- | ------------ | -------- | ------------------------------------------ |
| `model`   | string       | Yes      | Embedding model ID                         |
| `input`   | string/array | Yes      | Text to embed (string or array of strings) |

**Example:**

```bash
curl https://inference.swanchain.io/v1/embeddings \
  -H "Authorization: Bearer sk-swan-YOUR-API-KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "bge-large-en-v1.5",
    "input": "Swan Chain is a decentralized AI computing blockchain."
  }'
```

**Response:**

```json
{
  "object": "list",
  "data": [
    {
      "object": "embedding",
      "index": 0,
      "embedding": [0.0023, -0.0091, 0.0152, ...]
    }
  ],
  "model": "bge-large-en-v1.5",
  "usage": {
    "prompt_tokens": 10,
    "total_tokens": 10
  }
}
```

***

### Image Generation

Generate images from text prompts.

```
POST /v1/images/generations
```

**Request Body:**

| Parameter | Type    | Required | Description                               |
| --------- | ------- | -------- | ----------------------------------------- |
| `model`   | string  | Yes      | Image model ID (e.g., `flux-1-schnell`)   |
| `prompt`  | string  | Yes      | Text description of the image to generate |
| `n`       | integer | No       | Number of images to generate. Default: 1  |
| `size`    | string  | No       | Image size (e.g., `1024x1024`)            |

**Example:**

```bash
curl https://inference.swanchain.io/v1/images/generations \
  -H "Authorization: Bearer sk-swan-YOUR-API-KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "flux-1-schnell",
    "prompt": "A futuristic data center powered by blockchain, digital art style",
    "n": 1,
    "size": "1024x1024"
  }'
```

**Response:**

```json
{
  "created": 1709500000,
  "data": [
    {
      "url": "https://inference.swanchain.io/images/generated/abc123.png"
    }
  ]
}
```

***

### Audio Transcription

Transcribe audio files to text.

```
POST /v1/audio/transcriptions
```

**Request Body** (multipart/form-data):

| Parameter  | Type   | Required | Description                               |
| ---------- | ------ | -------- | ----------------------------------------- |
| `file`     | file   | Yes      | Audio file (mp3, mp4, wav, webm, etc.)    |
| `model`    | string | Yes      | Audio model ID (e.g., `whisper-large-v3`) |
| `language` | string | No       | Language code (e.g., `en`)                |

**Example:**

```bash
curl https://inference.swanchain.io/v1/audio/transcriptions \
  -H "Authorization: Bearer sk-swan-YOUR-API-KEY" \
  -F file="@audio.mp3" \
  -F model="whisper-large-v3"
```

**Response:**

```json
{
  "text": "Hello, welcome to Swan Chain's decentralized AI inference platform."
}
```

***

## Supported Models

Swan Inference hosts **42+ models** across five categories:

| Category       | Models                                                             | Pricing                |
| -------------- | ------------------------------------------------------------------ | ---------------------- |
| **LLM**        | DeepSeek R1 (70B), Llama 3 (3B, 8B, 70B), Qwen 2.5, Mistral, Phi-3 | Per input/output token |
| **Image**      | FLUX.1 Schnell, Stable Diffusion XL                                | Per request            |
| **Audio**      | Whisper Large V3                                                   | Per request            |
| **Embedding**  | BGE Large, E5 Large                                                | Per token              |
| **Multimodal** | Llama 3.2 Vision, Qwen-VL                                          | Per token              |

{% hint style="info" %}
Model availability depends on online providers. Check real-time status at [inference.swanchain.io/models](https://inference.swanchain.io/models) or call `GET /v1/models`.
{% endhint %}

***

## Rate Limits

Requests are rate-limited per API key:

| Model Category | Requests per Minute |
| -------------- | ------------------- |
| LLM            | 200                 |
| Image          | 60                  |
| Embedding      | 500                 |
| Other          | 200                 |

Maximum concurrent requests: **100** per API key.

When rate-limited, the API returns HTTP `429 Too Many Requests` with a `Retry-After` header.

***

## Request Limits

| Parameter                    | Limit              |
| ---------------------------- | ------------------ |
| Max input tokens (LLM)       | 128,000            |
| Max output tokens (LLM)      | 16,384             |
| Max input tokens (Embedding) | 8,192              |
| Max request body size        | 10 MB              |
| Max messages per request     | 100                |
| Max message length           | 100,000 characters |
| Request timeout              | 120 seconds        |

***

## Error Handling

The API returns standard HTTP error codes with JSON error bodies:

```json
{
  "error": {
    "message": "Invalid API key provided",
    "type": "authentication_error",
    "code": "invalid_api_key"
  }
}
```

| Status Code | Meaning                                   |
| ----------- | ----------------------------------------- |
| `400`       | Bad request — check your request body     |
| `401`       | Unauthorized — invalid or missing API key |
| `404`       | Model not found or no providers available |
| `429`       | Rate limit exceeded — slow down           |
| `500`       | Internal server error                     |
| `503`       | Service unavailable — all providers busy  |

The platform automatically retries failed requests (up to 2 retries with exponential backoff) when a provider is temporarily unavailable, so most transient errors are handled transparently.

***

## Response Headers

Swan Inference includes helpful headers in every response:

| Header                   | Description                                           |
| ------------------------ | ----------------------------------------------------- |
| `X-Request-ID`           | Unique request correlation ID for tracing             |
| `X-Swan-Connection-Mode` | How the request was routed: `websocket` or `external` |

Use `X-Request-ID` when contacting support or debugging request issues.

***

## Using with LLM Frameworks

Swan Inference works with any framework that supports OpenAI-compatible APIs.

### LangChain (Python)

```python
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    base_url="https://inference.swanchain.io/v1",
    api_key="sk-swan-YOUR-API-KEY",
    model="deepseek-r1-distill-llama-70b",
)

response = llm.invoke("What is decentralized AI?")
print(response.content)
```

### LlamaIndex

```python
from llama_index.llms.openai_like import OpenAILike

llm = OpenAILike(
    api_base="https://inference.swanchain.io/v1",
    api_key="sk-swan-YOUR-API-KEY",
    model="deepseek-r1-distill-llama-70b",
)

response = llm.complete("Explain DePIN in simple terms.")
print(response.text)
```

### LiteLLM

```python
import litellm

response = litellm.completion(
    model="openai/deepseek-r1-distill-llama-70b",
    messages=[{"role": "user", "content": "Hello!"}],
    api_base="https://inference.swanchain.io/v1",
    api_key="sk-swan-YOUR-API-KEY",
)

print(response.choices[0].message.content)
```

### Vercel AI SDK (TypeScript)

```typescript
import { createOpenAI } from "@ai-sdk/openai";
import { generateText } from "ai";

const swan = createOpenAI({
  baseURL: "https://inference.swanchain.io/v1",
  apiKey: "sk-swan-YOUR-API-KEY",
});

const { text } = await generateText({
  model: swan("deepseek-r1-distill-llama-70b"),
  prompt: "What is Swan Chain?",
});

console.log(text);
```

***

## Pricing

| Category      | Pricing Unit                       | Billed In |
| ------------- | ---------------------------------- | --------- |
| **LLM**       | Per input token + per output token | USDC      |
| **Embedding** | Per token                          | USDC      |
| **Image**     | Per request                        | USDC      |
| **Audio**     | Per request                        | USDC      |

View current pricing for each model at [inference.swanchain.io/models](https://inference.swanchain.io/models).

Token usage is included in every response under the `usage` field.

***

## Network Stats

Public endpoints are available for monitoring network health:

| Endpoint                         | Description                                                             |
| -------------------------------- | ----------------------------------------------------------------------- |
| `GET /api/v1/stats/network`      | Aggregate network stats (providers, requests, capacity)                 |
| `GET /api/v1/stats/leaderboard`  | Provider leaderboard ranked by performance                              |
| `GET /api/v1/stats/gpu`          | GPU distribution and VRAM capacity across the network                   |
| `GET /api/v1/stats/utilization`  | Network utilization metrics                                             |
| `GET /api/v1/stats/model-demand` | Model demand data (useful for providers choosing which models to serve) |
| `GET /api/v1/dashboard/summary`  | Dashboard summary with request and capacity metrics                     |

These endpoints do not require authentication.

***

## Learn More

* [**Swan 2.0: Inference Cloud**](https://github.com/swanchain/docs/blob/main/core-concepts/swan-2.0-inference-cloud.md) — Architecture and platform overview
* [**Inference Marketplace**](/core-concepts/market-provider/inference-marketplace) — How the marketplace works (routing, pricing, settlement)
* [**Model Catalog**](https://inference.swanchain.io/models) — Browse all available models with real-time availability and pricing


# Claw-Family AI Agent Integration

Connect OpenClaw, ZeroClaw, Nanobot, and other Claw-family AI agents to Swan Inference

Swan Inference provides an OpenAI-compatible API that works with all Claw-family AI agent tools. This guide covers how to connect each tool to Swan Inference for decentralized AI inference.

## Prerequisites

1. A Swan Inference API key (`sk-swan-*`) — [sign up here](https://inference.swanchain.io/signup)
2. The Claw tool of your choice installed

## Quick Start

All Claw-family tools support custom OpenAI-compatible endpoints. The core configuration is the same across all tools:

| Setting  | Value                                                                                 |
| -------- | ------------------------------------------------------------------------------------- |
| Base URL | `https://inference.swanchain.io/v1`                                                   |
| API Key  | `sk-swan-YOUR-API-KEY`                                                                |
| Model    | Any model from [inference.swanchain.io/models](https://inference.swanchain.io/models) |

Popular models available on Swan Inference:

| Model                               | Category | Use Case                     |
| ----------------------------------- | -------- | ---------------------------- |
| `deepseek-r1-distill-llama-70b`     | LLM      | Reasoning, code generation   |
| `Qwen/Qwen2.5-7B-Instruct`          | LLM      | General chat, fast responses |
| `meta-llama/Llama-3.3-70B-Instruct` | LLM      | General purpose              |

***

## Tool-Specific Setup

### OpenClaw (TypeScript, 250K+ stars)

The most popular AI assistant in the Claw family. Supports 25+ messaging platforms.

{% tabs %}
{% tab title="Config File" %}
Edit your OpenClaw configuration to add Swan Inference as a provider:

```json
{
  "models": {
    "providers": {
      "swan": {
        "api": "openai-completions",
        "baseUrl": "https://inference.swanchain.io/v1",
        "apiKey": "sk-swan-YOUR-API-KEY",
        "models": [
          "deepseek-r1-distill-llama-70b",
          "Qwen/Qwen2.5-7B-Instruct"
        ]
      }
    },
    "default": "swan:deepseek-r1-distill-llama-70b"
  }
}
```

{% endtab %}

{% tab title="Environment Variables" %}

```bash
export OPENAI_API_BASE=https://inference.swanchain.io/v1
export OPENAI_API_KEY=sk-swan-YOUR-API-KEY
openclaw
```

{% endtab %}
{% endtabs %}

***

### ZeroClaw (Rust, 28K+ stars)

Ultra-lightweight (3.4MB binary, <10ms startup). Best for quick testing.

{% tabs %}
{% tab title="config.toml" %}

```toml
[provider]
name = "openai-compatible"
base_url = "https://inference.swanchain.io/v1"
api_key = "sk-swan-YOUR-API-KEY"
model = "deepseek-r1-distill-llama-70b"
```

{% endtab %}

{% tab title="CLI" %}

```bash
zeroclaw --provider "custom:https://inference.swanchain.io/v1" \
         --api-key "sk-swan-YOUR-API-KEY" \
         --model "deepseek-r1-distill-llama-70b"
```

{% endtab %}
{% endtabs %}

***

### PicoClaw (Go, 26K+ stars)

Lightweight Go binary (<8MB). Designed for edge and ARM devices.

```yaml
# config.yaml
provider:
  type: openai-compatible
  base_url: https://inference.swanchain.io/v1
  api_key: sk-swan-YOUR-API-KEY
  model: deepseek-r1-distill-llama-70b
```

***

### Nanobot (Python, 32K+ stars)

Python-native, installable via pip. Best for Python developers.

{% tabs %}
{% tab title="Install" %}

```bash
pip install nanobot-ai
```

{% endtab %}

{% tab title="Config" %}

```json
{
  "provider": "custom",
  "apiBase": "https://inference.swanchain.io/v1",
  "apiKey": "sk-swan-YOUR-API-KEY",
  "model": "deepseek-r1-distill-llama-70b"
}
```

{% endtab %}

{% tab title="Python API" %}

```python
from nanobot import Agent

agent = Agent(
    provider="custom",
    api_base="https://inference.swanchain.io/v1",
    api_key="sk-swan-YOUR-API-KEY",
    model="deepseek-r1-distill-llama-70b",
)

response = agent.chat("Explain quantum computing in simple terms")
print(response)
```

{% endtab %}
{% endtabs %}

***

### NanoClaw (TypeScript, 25K+ stars)

Container-per-session isolation. Good for multi-tenant deployments.

```json
{
  "llm": {
    "provider": "openai-compatible",
    "baseUrl": "https://inference.swanchain.io/v1",
    "apiKey": "sk-swan-YOUR-API-KEY",
    "model": "deepseek-r1-distill-llama-70b"
  }
}
```

***

### IronClaw (Rust, 10K+ stars)

Security-focused with TEE and encrypted vault. Built by NEAR AI.

```bash
export LLM_BACKEND=openai_compatible
export LLM_BASE_URL=https://inference.swanchain.io/v1
export API_KEY=sk-swan-YOUR-API-KEY
export MODEL=deepseek-r1-distill-llama-70b

ironclaw
```

***

### NemoClaw (TypeScript + Python, 15K+ stars)

NVIDIA's reference stack with kernel sandbox and privacy router.

Configure the inference provider in your NemoClaw deployment:

```yaml
inference:
  provider: openai-compatible
  base_url: https://inference.swanchain.io/v1
  api_key: sk-swan-YOUR-API-KEY
  model: deepseek-r1-distill-llama-70b
```

{% hint style="info" %}
NemoClaw is in early preview (alpha). Configuration may change.
{% endhint %}

***

### Moltworker (TypeScript, Cloudflare Workers)

Runs on Cloudflare's edge network (330+ cities).

```json
{
  "models": {
    "providers": {
      "swan": {
        "type": "openai-compatible",
        "baseUrl": "https://inference.swanchain.io/v1",
        "apiKey": "sk-swan-YOUR-API-KEY"
      }
    }
  }
}
```

Or set via Cloudflare AI Gateway:

```bash
AI_GATEWAY_BASE_URL=https://inference.swanchain.io/v1
```

***

### NullClaw (Zig, 6.7K+ stars)

Ultra-minimal (678KB binary, 1MB RAM). For IoT and embedded devices.

```bash
nullclaw --provider "custom:https://inference.swanchain.io/v1" \
         --api-key "sk-swan-YOUR-API-KEY" \
         --model "Qwen/Qwen2.5-7B-Instruct"
```

Or in config:

```toml
[provider]
url = "custom:https://inference.swanchain.io/v1"
api_key = "sk-swan-YOUR-API-KEY"
model = "Qwen/Qwen2.5-7B-Instruct"
```

{% hint style="info" %}
For resource-constrained devices, use smaller models like `Qwen/Qwen2.5-7B-Instruct` for faster responses.
{% endhint %}

***

## Choosing the Right Tool

| Scenario            | Recommended Tool | Why                                |
| ------------------- | ---------------- | ---------------------------------- |
| Quick local testing | **ZeroClaw**     | 3.4MB, boots in <10ms              |
| Python project      | **Nanobot**      | pip install, native Python API     |
| Multi-platform bot  | **OpenClaw**     | 25+ messaging platforms            |
| Edge / ARM device   | **PicoClaw**     | 8MB Go binary, runs anywhere       |
| IoT / embedded      | **NullClaw**     | 678KB, runs on $5 hardware         |
| Security-critical   | **IronClaw**     | TEE, encrypted vault, WASM sandbox |
| Multi-tenant SaaS   | **NanoClaw**     | Container-per-session isolation    |
| Enterprise / NVIDIA | **NemoClaw**     | Kernel sandbox, policy enforcement |
| Global edge deploy  | **Moltworker**   | Cloudflare Workers, 330+ cities    |

## Playground (No API Key)

All tools can also use Swan Inference's public playground for testing without an API key:

```
Base URL: https://inference.swanchain.io/v1/playground
```

The playground is rate-limited (5 requests/hour per IP) with restricted models, but requires no signup.

## Troubleshooting

### Connection refused / timeout

* Verify the base URL includes `/v1`: `https://inference.swanchain.io/v1`
* Check your API key starts with `sk-swan-`

### Model not found

* List available models: `curl https://inference.swanchain.io/v1/models -H "Authorization: Bearer sk-swan-YOUR-KEY"`
* Model IDs are case-sensitive (e.g., `Qwen/Qwen2.5-7B-Instruct`, not `qwen2.5-7b`)

### Rate limited (429)

* Default rate limit is 200 requests/min for LLM models
* Check `X-RateLimit-Remaining` header in responses
* Consider upgrading to Pro subscription ($6/month) for higher limits

### Streaming not working

* Ensure your tool is configured for streaming (`stream: true`)
* Swan Inference supports SSE streaming on `/v1/chat/completions`

## Learn More

* [Swan Inference API Reference](/bulders/app-developer/swan-inference-api)
* [Available Models](https://inference.swanchain.io/models)
* [Sign Up](https://inference.swanchain.io/signup)
* [Subscription Plans](/bulders/app-developer/swan-inference-api#subscription-plan)


# Building Docker Images and Deployment file with LDL

This guide will walk you through the process of building and pushing a Docker image, and then creating a deployment file using Lagrange Definition Language (LDL) to deploy your application on the Swan Chain network.

### Background

When you deploy your application to SwanChain using the Swan SDK, you need to upload a project with a Dockerfile or a deploy.yaml to GitHub. This article describes how to create a project with a Dockerfile or a deploy.yaml file and upload it to GitHub.

### Key Concepts

* A `Dockerfile` is a text document containing commands to assemble a Docker image.
* A `deploy.yaml` file, written in [Lagrange Definition Language (LDL)](/bulders/app-developer/building-docker-images-and-deployment-file-with-ldl/creating-deployment-files-with-ldl), specifies deployment details for your Applications. This gives you more flexibility to add multiple dependent services and more configurations to your application

### Building and Pushing Your Docker Image

1. **Download the template:** Download the [docker-application-template](https://github.com/swanchain/docker-application-template/archive/refs/heads/main.zip)
2. **Navigate to the app folder:**

```
cd docker-application-template/app
```

3. **Modify the application code:** Edit the `main.py` file.

For example:

```python
from fastapi import FastAPI
from datetime import datetime

app = FastAPI()

@app.get("/")
def read_root():
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return {"Hello!"  f"Today is - {current_time}"}
```

4. **Push your code to GitHub**

{% hint style="info" %}
You’re now ready to use your repo URL and the Swan SDK to [deploy your first application](/bulders/app-developer/deploying-with-swan-sdk)!
{% endhint %}

***

*If you believe the Dockerfile alone cannot meet your complex deployment requirements, the next steps will guide you in preparing and creating a deploy.yaml file yourself.*

5. **Build the Docker image:** Navigate to the root folder and run:

```
cd docker-application-template
docker build --platform linux/amd64 --tag <username>/<repo>:<tag> .
```

6. **Push to container registry:**

```
docker push <username>/<repo>:<tag>
```

### Creating Deployment Files with LDL

7. **Create a new project folder:**

```
mkdir my-swan-app-with-ldl
cd my-swan-app-with-ldl
```

8. **Create the deploy.yaml file:**

Create a `deploy.yaml` file in the root of the folder with the following content:

```yaml
version: "2.0"
services:
  hello-world:
    image: <username>/<repo>:<tag>
    expose:
      - port: 7860
        as: 80
deployment:
  hello-world:
    lagrange:
      count: 1
```

Note: Replace `<username>/<repo>:<tag>` with your Docker image information.

9. **Push the LDL project to GitHub**

### Next Steps

With your Docker image built and pushed, and your LDL deployment file created, you're now ready to deploy your application on the Swan Chain network using Swan SDK. Refer to the [Swan SDK documentation](/bulders/app-developer/deploying-with-swan-sdk) for the next steps in the deployment process.

For more information on customizing your deployment settings with LDL, check out the [LDL documentation.](/bulders/app-developer/building-docker-images-and-deployment-file-with-ldl/creating-deployment-files-with-ldl)


# Lagrange Definition Language(LDL)

Lagrange Definition Language (LDL) is essentially a YAML-based configuration language used for defining deployment requirements in Swan Chain. Similar to how Dockerfiles are used to define container builds, LDL files (deploy.yaml) are used to specify how your application should be deployed and run on the Swan Chain network.

## Lagrange Definition Language (LDL)

LDL is a human-friendly data standard for declaring deployment attributes. The LDL file is a "form" to request resources from the Network. LDL is compatible with the YAML standard and similar to Docker Compose files.

Configuration files may end in `.yml` or `.yaml`.A complete deployment has the following sections:

* [networking](#networking)
* [​version​](#version)
* [​services](#services)​
* [​profiles​](#profiles)
* [​deployment​](#deployment)

### **networking**

Networking - allowing connectivity to and between workloads - can be configured via the LDL file for a deployment. By default, workloads in a deployment group are isolated - nothing else is allowed to connect to them. This restriction can be relaxed.

### version

Indicates the version of the configuration file. Currently only `"2.0"` one is accepted.

### services

The top-level `services` entry contains a map of workloads to be run on the deployment. Each key is a service name; values are a map containing the following keys:

| Name         | Required | Meaning                                                                                                                                                       |
| ------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `image`      | Yes      | <p>Docker image of the container Best practices:</p><ul><li>avoid using <code>:latest</code> image tags as Computing Providers heavily cache images</li></ul> |
| `expose`     | Yes      | Entities allowed to connect to the services. See services.expose​                                                                                             |
| `depends-on` | No       | specifying dependencies for a particular service, indicates that the mentioned service relies on or requires certain other service to function properly       |
| `command`    | No       | Custom command use when executing container                                                                                                                   |
| `args`       | No       | Arguments to custom command use when executing the container                                                                                                  |
| `env`        | No       | Environment variables to set in running container. See services.env​                                                                                          |
| `ready`      | No       | ***NOTE - field is marked for future use and currently has no impact on deployments.***                                                                       |
| `model`      | No       | A configuration section that defines a list of models for the service                                                                                         |

**services.depends-on**

`depends-on` specifies dependencies for a particular service, indicates that the mentioned service relies on or requires certain other service to function properly

```
    depends-on:
       - db
```

**services.env**

A list of environment variables to expose to the running container.

```
env:
- "GF_PATHS_CONFIG=/opt/grafana/grafana.ini"
```

**services.expose**

**Notes Regarding Port Use in the Expose Stanza**

* HTTPS is possible in Lagrange deployments but only self-signed certs are generated.
* To implement signed certs the deployment must be front-ended via a solution such as Cloudflare.
* You can expose any other port besides 80 as the ingress port (HTTP, HTTPS) port using as: 80 directive if the app understands HTTP / HTTPS. Example of exposing a React web app using this method:

```
    expose:
      - port: 3000 
        as: 80
```

* In the LDL it is only necessary to expose port 80 for web apps. With this specification, both ports 80 and 443 are exposed.

`expose` is a list describing what can connect to the service. Each entry is a map containing one or more of the following fields:

| Name     | Required | Meaning                                                      |
| -------- | -------- | ------------------------------------------------------------ |
| `port`   | Yes      | Container port to expose                                     |
| `as`     | No       | Port number to expose the container port as                  |
| `accept` | No       | List of hosts to accept connections for                      |
| `proto`  | No       | Protocol type (`tcp, udp, or http`)                          |
| `to`     | No       | List of entities allowed to connect. See services.expose.to​ |

The `as` value governs the default `proto` value as follows:

> ***NOTE*** - when as is not set, it will default to the value set by the port mandatory directive.

> ***NOTE*** - when one exposes as: 80 (HTTP), the Kubernetes ingress controler makes the application available over HTTPS as well, though with the default self-signed ingress certs.

| `port`     | `proto` default |
| ---------- | --------------- |
| 80         | http, https     |
| all others | tcp             |

**services.expose.to**

`expose.to` is a list of clients to accept connections from. Each item is a map with one or more of the following entries:

| Name      | Value                        | Default | Description                        |
| --------- | ---------------------------- | ------- | ---------------------------------- |
| `service` | A service in this deployment | ​       | Allow the given service to connect |

**service.model**

`model` is a configuration section that defines a list of models for the service.Each model in the list has the following properties:

* **name**: This property specifies the name of the model.
* **url**: This property specifies the URL from which the model's data can be downloaded.
* **dir**: This property specifies the directory path within the container where the model's files will be stored after they are downloaded from the specified URL.

Example:

```
services:
  stable-diffusion-ui:
    image: sonic868/stable-diffusion:v1.0
    models:
      - name: illustroV3.safetensors
        url: https://civitai.com/api/download/models/151490
        dir: "/easy-diffusion/models/stable-diffusion"
```

### profiles

The `profiles` section contains named compute and placement profiles to be used in the deployment.

### deployment

The `deployment` section defines how to deploy the services. It is a mapping of service name to deployment configuration.

Each service to be deployed has an entry in the `deployment`. This entry is maps datacenter profiles to compute profiles to create a final desired configuration for the resources required for the service.

Example:

```
deployment:
  minesweeper:
    lagrange:
      count: 1
```

This says that the instances of the `minesweeper` service should be deployed to a [Computing Provider](/bulders/computing-provider) within Lagrange.

**The final `deploy.yaml` should look like this:**

```
version: "2.0"

services:
  minesweeper:
    image: creepto/minesweeper
    expose:
      - port: 3000
        as: 80
    
deployment:
  minesweeper:
    lagrange:
      count: 1
```

Check out [here](https://lagrange.computer/spaces/0x7E0c07e66CD480CDa94dEaaeEB5a84Fa9F8215e6/miner-bomb-bomb/files) to interact with the sample.

**Here is another sample `deploy.yaml`:**

```
version: "2.0"

services:
  db:
    image: postgres:11.6-alpine
    env:
      - POSTGRES_USER=codimd
      - POSTGRES_PASSWORD=rootadmin
      - POSTGRES_DB=codimd
    expose:
        - port: 5432
          as: 5432
          to:
            - service: db
    ready-cmd:
        - "psql"
        - "-w"
        - "-U"
        - "codimd"
        - "-d"
        - "codimd"
        - "-c"
        - "SELECT 1"
  codimd:
    image: hackmdio/hackmd:2.4.1
    env:
      - CMD_DB_URL=postgres://codimd:rootadmin@127.0.0.1:5432/codimd
      - CMD_USECDN=false
    depends-on:
      - db
    expose:
        - port: 3000
          as: 3000
          to:
            - global: true

deployment:
  db:
    lagrange:
      count: 1
  codimd:
    lagrange:
      count: 1
```

Check out [here](https://lagrange.computer/spaces/0x7E0c07e66CD480CDa94dEaaeEB5a84Fa9F8215e6/CodiMD-Test/files) to interact with the sample.


# Deploying with Swan SDK

The Swan SDK is a toolkit designed to simplify interactions with the Swan Chain Network Resource. It provides a streamlined interface for creating and managing computational tasks, retrieving hardware information, processing payments, and monitoring task statuses.

{% hint style="info" %}
***For more sample tutorial, please refer to*** [***Python Swan SDK Samples***](https://github.com/swanchain/python-sdk-docs-samples) ***or*** [***Go Swan SDK Samples***](https://github.com/swanchain/go-swan-sdk-samples)***.***
{% endhint %}

### Get Swan API Key <a href="#get-orchestrator-api-key" id="get-orchestrator-api-key"></a>

To use `swan-sdk`, a Swan API key is required. Steps to get an API Key:

* Go to [Swan Console](https://console.swanchain.io/), switch network to [Swan Chain Mainnet](https://docs.swanchain.io/network-reference/readme).
* Login with your wallet.
* Click `API Keys` -> `Generate API Key`

## Quick Start <a href="#installation" id="installation"></a>

{% tabs %}
{% tab title="Python" %}
**Installation**

To use Python Swan SDK, you first need to install it and its dependencies. Before installing Swan SDK, install Python 3.8 or later and web3.py(==6.20.3).

Install the latest Swan SDK release via **pip**:

```sh
pip install swan-sdk
```

Or install via GitHub:

```sh
git clone https://github.com/swanchain/python-swan-sdk.git
cd python-swan-sdk
pip install .
```

**Using Python Swan SDK**

To use Python Swan SDK, you must first import it and indicate which service you're going to use:

```python
import swan

swan_orchestrator = swan.resource(api_key='<SWAN_API_KEY>', service_name='Orchestrator')
```

Now that you have an `Orchestrator` service, you can create and deploy instance applications as an Orchestrator task with the service.

```python
result = swan_orchestrator.create_task(
    repo_uri='https://github.com/swanchain/awesome-swanchain/tree/main/hello_world', # Or your own repo URI
    wallet_address='<WALLET_ADDRESS>',
    private_key='<PRIVATE_KEY>',
    instance_type='C1ae.medium'
)
task_uuid = result['task_uuid']
```

Then you can follow up task deployment information and the URL for running applications.

```python
# Get task deployment info
task_deployment_info = swan_orchestrator.get_deployment_info(task_uuid=task_uuid)
print(task_deployment_info)

# Get application instances URL
app_urls = swan_orchestrator.get_real_url(task_uuid)
print(app_urls)
```

{% endtab %}

{% tab title="Go" %}
**Installation**

**Go Version**

`go-swan-sdk` requires [Go](https://go.dev/) version [1.21](https://go.dev/doc/devel/release#go1.21.0) or above.

**Using go-swan-sdk**

With [Go's module support](https://go.dev/wiki/Modules#how-to-use-modules), `go [build|run|test]` automatically fetches the necessary dependencies when you add `import`in your project:

```go
import "github.com/swanchain/go-swan-sdk"
```

To update the SDK use `go get -u` to retrieve the latest version of the SDK:

```go
go get -u github.com/swanchain/go-swan-sdk
```

**Quickstart**

To use `go-swan-sdk`, you must first import it, and you can create and deploy instance applications quickly.

```go
package main

import (
	"github.com/swanchain/go-swan-sdk"
	"log"
	"time"
)

func main() {
	client, err := swan.NewAPIClient("<YOUR_API_KEY>")
	if err != nil {
		log.Fatalf("failed to init swan client, error: %v \n", err)
	}
	task, err := client.CreateTask(&swan.CreateTaskReq{
		PrivateKey:   "<PRIVATE_KEY>",
		RepoUri:      "https://github.com/swanchain/awesome-swanchain/tree/main/hello_world",
		Duration:     2 * time.Hour,
		InstanceType: "C1ae.medium",
	})
	taskUUID := task.Task.UUID

	// Get task deployment info
	resp, err := client.TaskInfo(taskUUID)
	if err != nil {
		log.Fatalln(err)
	}
	log.Printf("task info: %+v \n", resp)

	//Get application instances URL
	appUrls, err := client.GetRealUrl(taskUUID)
	if err != nil {
		log.Fatalln(err)
	}
	log.Printf("app urls: %v \n", appUrls)
}

```

{% endtab %}
{% endtabs %}

### Documentation and Support <a href="#documentation-and-support" id="documentation-and-support"></a>

More resources about swan SDK can be found here:

* [Swan Console platform](https://console.swanchain.io/)
* [Python-swan-sdk](/bulders/tools/swan-sdk/python-swan-sdk)
* [Go-swan-sdk](/bulders/tools/swan-sdk/go-swan-sdk)
* [Python-swan-sdk-samples](https://github.com/swanchain/python-sdk-docs-samples)
* [Go-swan-sdk-samples](https://github.com/swanchain/go-swan-sdk-samples)


# Store and Retrieve a File with Swan Storage

## Introduction

[Swan IPFS Storage](https://swanipfs.com/)(formerly Multichain Storage) is the core component of Swan Chain's decentralized storage solution. MCS integrates multiple blockchain networks to provide a secure, efficient, and scalable storage service. It leverages smart contracts for enhanced security, ensures data redundancy through decentralized storage on IPFS and the Filecoin network, and offers a user-friendly interface for seamless interaction with the storage system.

This guide will walk you through the steps to install and configure the MCS SDK, create and manage storage buckets, upload and download files, and maintain your storage environment.

### Overview of Steps

1. [Set up the python-MCS-SDK](/bulders/app-developer/store-and-retrieve-a-file-with-swan-storage/1.-set-up-the-python-mcs-sdk)
2. [Create amd Manage Buckets](/bulders/app-developer/store-and-retrieve-a-file-with-swan-storage/2.create-and-manage-buckets)
3. [Upload Files and Folders](/bulders/app-developer/store-and-retrieve-a-file-with-swan-storage/3.upload-files-and-folders)
4. [Retrieve and Download Files](/bulders/app-developer/store-and-retrieve-a-file-with-swan-storage/4.retrieve-and-download-files)
5. [Delete Files and Buckets](/bulders/app-developer/store-and-retrieve-a-file-with-swan-storage/5.delete-files-and-buckets)


# 1. Set up the python-MCS-SDK

To begin using Swan Storage, you need to install and configure the python-MCS-SDK.

### 1.1 Install Python

Ensure you have Python 3.7 or later installed on your system.

For information about how to get the latest version of Python, see the official [Python documentation](https://www.python.org/downloads/).

### 1.2 Install python-MCS-SDK

Install the latest python-MCS-SDK release via **pip:**

`pip install python-MCS-SDK`

{% hint style="info" %}
The latest development version of python-MCS-SDK is on [GitHub](https://github.com/filswan/python-mcs-sdk)
{% endhint %}

### 1.3 Configure the SDK

Before using the SDK, you need to generate an API key from the MCS website.

1. Visit [https://swanipfs.com/#/my\_account](https://www.multichain.storage/#/my_account)
2. Generate an API key
3. Save your API key securely

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

### 1.4 Initialize the SDK

To use python-MCS-SDK, you must first import it and state your identity.

```python
from swan_mcs import APIClient
import logging
# Set logging level to be sure that you can see the info level message
logging.basicConfig(level=logging.INFO)
# Let's initialize the Python-MCS-SDK
mcs_api = APIClient("<API_KEY>")
```

If you see "Login Successful" in the console, you have logged in successfully. The following code will take you through the initialization of services.

```python
from swan_mcs import BucketAPI
# Init bucket client
bucket_client = BucketAPI(mcs_api)
```


# 2.Create and Manage Buckets

A bucket in MCS is a logical container for storing files and folders.

### 2.1 Create a new bucket

Use the `create_bucket` method to create a new bucket:

```python
from swan_mcs import APIClient, BucketAPI
mcs_api = APIClient("<API_KEY>")
bucket_client = BucketAPI(mcs_api)

bucket_client.create_bucket("<BUCKET_NAME>")
```

### 2.2 List existing buckets

List all existing buckets using `list_buckets`:

```python
from swan_mcs import APIClient, BucketAPI
mcs_api = APIClient("<API_KEY>")
bucket_client = BucketAPI(mcs_api)

for i in bucket_client.list_buckets():
    print(i.to_json())
```

### 2.3 Get bucket information

Use `get_bucket(bucket_name)`to get specific bucket info

```
from swan_mcs import APIClient, BucketAPI
mcs_api = APIClient("<API_KEY>")
bucket_client = BucketAPI(mcs_api)

print(bucket_client.get_bucket("<BUCKET_NAME>").to_json())
```

### 2.4 Create folder

`create_folder(bucket_name, folder_name, prefix='')`

The `create_folder` the method allows you to create a folder in the specified bucket. It accepts bucket names, folder names, and prefixes. The folder will be created in `bucket_name/prefix/folder_name`

```python
from swan_mcs import APIClient, BucketAPI
mcs_api = APIClient("<API_KEY>")
bucket_client = BucketAPI(mcs_api)

# If you want to place the folder directly in the root directory, you can leave the prefix field empty
bucket_client.create_folder("<BUCKET_NAME>","<FOLDER_NAME>","<PREFIX>")
```

**Parameters**

* **bucket\_name**: The name of the bucket
* **folder\_name:** The name of the folder to create
* **prefix:** The prefix for the folder's object name


# 3.Upload Files and Folders

### 3.1 Upload a single file

`upload_file(bucket_name, object_name, file_path, replace=False)`

Uploads a file to a bucket. Use the `bucket_name` to select the bucket, and `object_name` to select the path and file name of the uploaded file. `file_path` is the local path of the file.

```python
from swan_mcs import APIClient, BucketAPI
mcs_api = APIClient("<API_KEY>")
bucket_client = BucketAPI(mcs_api)

# Object name is the destination path you want to upload to the bucket
# For example, if you want to upload the testfile.json file to path 111/222 in the TEST bucket, you would write: 
# bucket_client.upload_file("TEST", "111/222/testfile.json", "<FILE_PATH>")
bucket_client.upload_file("<BUCKET_NAME>", "<OBJECT_NAME>", "<FILE_PATH>")
```

**Parameters**

* **bucket\_name**: The name of the bucket
* **object\_name:** The object name of the file ex. `'folder1/file.png'` will upload the file as `file.png` inside `bucket_name/folder1`
* **file\_path:** The local file path
* **replace:** File's of the same name cannot be uploaded. When replace is set to True, it will overwrite the previous file of the same name.

**Return**

Returns a File Object

### 3.2 Upload a folder

Uploads `folder_path` as an MCS folder under `bucket_name`/`object_name`

```python
from swan_mcs import APIClient, BucketAPI
mcs_api = APIClient("<API_KEY>")
bucket_client = BucketAPI(mcs_api)

bucket_client.upload_folder("<BUCKET_NAME>", "<OBJECT_NAME>", "<FOLDER_PATH>")
```

**Parameters**

* bucket\_name: The name of the bucket
* object\_name: The object name for the folder
* folder\_path: Local path of your folder

**Return**

Returns a list of File Objects

### 3.3 Upload as IPFS folder

Uploads `folder_path` as an IPFS folder to MCS. This gives the folder its own CID, sharable to others.

```python
from swan_mcs import APIClient, BucketAPI
mcs_api = APIClient("<API_KEY>")
bucket_client = BucketAPI(mcs_api)

bucket_client.upload_ipfs_folder("<BUCKET_NAME>", "<OBJECT_NAME>", "<FOLDER_PATH>")
```

**Parameters**

* bucket\_name: The name of the bucket
* object\_name: The object name for the folder
* folder\_path: Local path of your folder

**Return**

Returns a File Object for your IPFS folder


# 4.Retrieve and Download Files

### 4.1 List files in a bucket

Get a list of file information from one of your buckets

```python
from swan_mcs import APIClient, BucketAPI
mcs_api = APIClient("<API_KEY>")
bucket_client = BucketAPI(mcs_api)

for i in bucket_client.list_files("<BUCKET_NAME>", '<PREFIX>', "<LIMIT>", '<OFFSET>'):
    print(i.to_json())
```

### 4.2 Get file information

Get the file information of a file in one of your buckets

```python
from swan_mcs import APIClient, BucketAPI
mcs_api = APIClient("<API_KEY>")
bucket_client = BucketAPI(mcs_api)

print(bucket_client.get_file("<BUCKET_NAME>", "<OBJECT_NAME>").to_json())
```

**Parameters**

* **bucket\_name**: The name of the bucket
* **object\_name:** The object name of the file

### 4.3 Download a file

Downloads the file (located using `bucket_name`/`object_name` from IPFS and writes it to `local_filename`

```python
from swan_mcs import APIClient, BucketAPI
mcs_api = APIClient("<API_KEY>")
bucket_client = BucketAPI(mcs_api)

bucket_client.download_file("<BUCKET_NAME>", "<OBJECT_NAME>", "<LOCAL_FILENAME>")
```

**Parameters**

* **bucket\_name**: The name of the bucket
* **object\_name:** The object name to download
* **local\_filename:** The download destination and filename


# 5.Delete Files and Buckets

### 5.1 Delete a file

Removes a file from a bucket

```python
from swan_mcs import APIClient, BucketAPI
mcs_api = APIClient("<API_KEY>")
bucket_client = BucketAPI(mcs_api)

bucket_client.delete_file("<BUCKET_NAME>", "<OBJECT_NAME>")
```

### 5.2 Delete a bucket

Removes a bucket from your account.

> Once you delete your bucket, all your file and folder under the bucket will be deteled

```python
from swan_mcs import APIClient, BucketAPI
mcs_api = APIClient("<API_KEY>")
bucket_client = BucketAPI(mcs_api)

bucket_client.delete_bucket("<BUCKET_NAME>")
```


# Node Operator

Welcome to the Swan Mainnet Node Operator Guide! This page provides a Docker image for running a Swan Mainnet node. The image is built on the official `nebulablock/swan-node-mainnet` image and is designed to be easy to use and highly configurable.

### Getting Started

To start a new container, use the following command:

```sh
docker run -d \
  -v /opt/swan:/opt/swan \
  -p 8545:8545 \
  -e L1RPC=$L1_RPC \
  -e L1BEACON=$L1_Beacon_RPC \
  --name swan-node \
  nebulablock/swan-node-mainnet
```

**Tip**: Looking to speed up your node initialization? Check out our[ Snapshots guide](/bulders/swan-node/swan-node-snapshots) for a faster synchronization method that can significantly reduce your initial setup time.

This command will start a new container in detached mode, mapping the container's port 8545 to the host's port 8545 and persisting data in the `/opt/swan` directory.

### Environment Variables

The image supports the following environment variables:

* `L1RPC`: The URL of the L1 RPC provider.
* `L1BEACON`: The URL of the L1 Beacon RPC provider.

These variables can be set using the `-e` flag when running the container, as shown in the example command above.

### Volumes

The image uses a volume at `/opt/swan` to persist data between container restarts. This volume can be mounted using the `-v` flag when running the container, as shown in the example command above.

### Ports

The image exposes port 8545 for RPC connections. This port can be mapped to a host port using the `-p` flag when running the container, as shown in the example command above.


# Swan Node Snapshots

This guide provides an advanced optimization method for SWAN Node operators looking to expedite their node initialization process. As a complementary resource to the [Node Operator](/bulders/swan-node) guide, snapshots offer a time-saving alternative to full chain synchronization.

### Key Components

**Hardware Requirements**

* 8-Core CPU
* Minimum 16 GB RAM
* Locally attached NVMe SSD
* Sufficient storage (recommended: 2 \* current chain size + snapshot size + 20% buffer)

**Prerequisite**

* This tutorial assumes you are familiar with [Docker](https://www.docker.com/) and have it running on your machine.

#### Running a Swan Node

This tutorial will walk you through setting up your own Swan Node, you can see here: <https://docs.swanchain.io/bulders/swan-node>

#### Snapshots

If you're a prospective or current SWAN Node operator and would like to restore from a snapshot to save time on the initial sync, it's possible to always get the latest available snapshot of the Swan chain on mainnet by using the following CLI commands. The snapshots are updated every two weeks.

***

## Snapshot Restoration Process

In the home directory of your SWAN Node, create a folder(`$SWAN_NODE_DATA`). If you already have this folder, remove it to clear the existing state and recreate it. Next, run the following code and wait for the operation to complete.

#### Init Swan Node configuration

```
docker run --rm -v $SWAN_NODE_DATA:/opt/swan swanchain254/swan-node-mainnet:latest init

```

#### Download the snapshot and untar it

* Swan Mainnet Snapshot:
  * [swanchain\_snapshot\_2025\_02\_17\_height\_4226078.tar.gz](https://6ba96e4b2881.acl.swanipfs.com/ipfs/QmPmWtiABBmZP5rtV9sX36K8Y8gA74udXKnqqy5KgKqi5z)

```
wget https://6ba96e4b2881.acl.swanipfs.com/ipfs/QmUgXvTLggufGisAYgjTEBt3AoJANRFjWdSfCQrpC9gsti -O swanchain_snapshot_2024_11_29_height_2845579.tar.gz
```

You'll then need to untar the downloaded snapshot and place the `$SWAN_NODE_DATA/data/geth/` subfolder

```
tar -zxvf ​swanchain_snapshot_2025_02_17_height_4226078.tar.gz -C $SWAN_NODE_DATA/data/geth/
```

#### Start Swan node

* `L1RPC` URL and `L1BEACON`

You'll need your own `L1RPC` URL and `L1BEACON` URL. This can be one that you run yourself.

* Run the docker command

```
docker run -dit --name swan-node --restart=always -v $SWAN_NODE_DATA:/opt/swan -p 8545:8545 -e L1RPC=$L1RPC -e  L1BEACON=$L1BEACON swanchain254/swan-node-mainnet:latest

```

#### Confirm you get a response from:

```
curl -d '{"id":0,"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["latest",false]}' \
  -H "Content-Type: application/json" http://localhost:8545
```

#### Check the node sync status

```
tail -f $SWAN_NODE_DATA/log/geth.log
```


# Market Provider

Market Providers (MPs) are crucial components in the Swan Chain ecosystem, facilitating the allocation of computing resources and managing transactions between job requesters and providers. This overview introduces you to the concept of Market Providers and MPs available in the Swan Chain network.

### 1. Storage Market

Swan Storage Market simplifies and optimizes the process of finding and utilizing decentralized storage on Filecoin. It addresses key challenges faced by users, such as lack of information on service quality, limited matching functionality, and high costs for beginners.

Read more about the Storage Market [here](/bulders/market-provider/storage-market).

### 2. AI/ML Orchestrator

The AI/ML Orchestrator is a specialized Market Provider focused on artificial intelligence and machine learning tasks. It efficiently manages and distributes AI/ML computing jobs across the decentralized network, ensuring optimal utilization of computational resources.

Read more about the Orchestrator [here](/bulders/market-provider/ai-ml-orchestrator).

### 3. Web3 ZK Computing Market

The Web3 ZK Computing Market is a Market Provider specifically designed for Zero-Knowledge (ZK) computations within the Swan Chain ecosystem. Key components includes:

* [**ZK Auction Engine**](/bulders/market-provider/web3-zk-computing-market/zk-auction-engine): Manages the bidding and allocation of ZK computation tasks
* [**Sequencer**](/bulders/market-provider/web3-zk-computing-market/sequencer): Plays a crucial role in processing ZK tasks and proofs efficiently
* [**zk-UBI-task**](/bulders/market-provider/web3-zk-computing-market/contribute-zk-ubi-task): Supports specific tasks related to [Universal Basic Income](/core-concepts/token/swan-universal-basic-income-ubi) concepts using zero-knowledge proofs

Read more about the ZK Computing Market [here](https://docs.swanchain.io/bulders/market-provider/web3-zk-computing-market).

### 4. Customized Market Provider

Swan Chain offers a flexible framework that enables developers to create their own customized Market Providers. This allows for:

* Development of specialized smart contracts for unique markets
* Creation of tailored marketplaces based on Swan Chain's computing layer
* Optimization of Market Providers for specific industry needs or computational requirements

Follow [this guide](/bulders/market-provider/customized-market-provider) to develop your own Market Provider.


# Storage Market

[Swan Storage Market ](https://docs.filswan.com/swan-storage-market/overview)simplifies and optimizes the process of finding and utilizing decentralized storage on Filecoin. It addresses key challenges faced by users, such as lack of information on service quality, limited matching functionality, and high costs for beginners.

**Key Features:**

1. **Auction System**:
   * **Manual Bid**: Users can actively select storage providers based on specific criteria like bandwidth, storage capacity, and geographic location, and participate in an open public deal.
   * **Auto-Bid**: A reputation-based system where storage providers are automatically matched with users, ensuring fairness and efficiency.
2. **Transparency and Efficiency**:
   * Open and transparent matching system reduces the learning curve for users.
   * Ensures quick and efficient pairing of users and storage providers, promoting time-efficient storage and backup services.
3. **Task Management**:
   * Introduces the concept of "tasks" to manage and batch send multiple deals, simplifying the process of handling large datasets.
4. **Swan Provider**:
   * Runs on the same node as lotus miner nodes and assists in deal processing.
   * Requires authentication from the Filswan platform for better information sharing.
   * Provides a Restful API interface for easy integration into other systems.

By integrating these features, Swan Storage Market enhances the accessibility and usability of decentralized storage, offering a comprehensive and user-friendly solution for both novice and experienced users.


# AI/ML Orchestrator

The orchestrator within the Swan Chain ecosystem serves as a critical component, designed to efficiently manage and distribute computing tasks across its decentralized network. This sophisticated system plays a pivotal role in ensuring that the computational resources available within the Swan Chain are utilized optimally, facilitating seamless operation and interaction among various stakeholders. Below is an overview of the orchestrator's functionalities, architecture, and its significance in the Swan Chain ecosystem.

#### Core Functions

* **Task Allocation and Distribution**: The orchestrator is responsible for assigning computing tasks to the most appropriate providers within the network, based on criteria such as computing power availability, task complexity, and provider performance history. This ensures that tasks are completed efficiently and effectively.
* **Computing Provider Registration**: It allows computing providers to register themselves within the Swan Chain ecosystem, making their resources available for tasks. This registry is crucial for maintaining an up-to-date inventory of available computational resources.
* **Task Validation and Verification**: After a task is completed, the orchestrator verifies the output against predetermined criteria to ensure accuracy and integrity. This step is vital for maintaining trust within the ecosystem.
* **Auto Payment Execution**: Upon successful task verification, the orchestrator facilitates automatic payments to the computing providers through smart contracts, ensuring timely and fair compensation for their services.
* **Resource Optimization**: The Orchestrator continuously monitors the network to optimize the allocation of computing resources, ensuring high efficiency and minimizing idle resources.

[Read more](/core-concepts/market-provider/decentralized-ai-computing-marketplace/web3-task-auction) about Orchestrator. \\


# Decentralized AI Marketplace

The Decentralized Auction Marketplace is an innovative system designed to enable efficient and secure interactions between users and providers in a decentralized environment. This system utilizes smart contracts, a bidding engine, and decentralized storage to create a transparent and efficient marketplace for various tasks.

Providers in the system contribute their resources, such as storage, network bandwidth, CPU, and GPU, to offer services to users who publish tasks on the platform. These tasks are stored on decentralized storage like IPFS/Filecoin, ensuring data security and transparency.

The bidding engine manages a competitive bidding process, where providers with different resource capabilities bid on tasks. Smart contracts on the Ethereum blockchain govern the bidding rules, enforce fair competition, and ensure the security of transactions.

Upon completion of a task by the selected provider, the final results are uploaded to the decentralized storage, maintaining data integrity and tamper-proofing. The smart contract then facilitates the automatic transfer of rewards from the task publisher to the provider as compensation for their services.

In summary, the Decentralized Auction Marketplace offers a secure and efficient platform for users to outsource tasks to a global network of providers with various resources. By leveraging blockchain technology, smart contracts, and decentralized storage, the system ensures transparency, security, and fairness in the bidding process and the execution of tasks.

### Key concepts

**Bidder (Provider)**: A bidder, also known as a provider, is a participant in the marketplace who offers their services to complete tasks. These services may include storage, network bandwidth, CPU, and GPU resources. Bidders are typically composed of blockchain nodes worldwide, and they actively participate in the competitive bidding process to secure tasks. Once assigned a task, bidders work to complete it to the best of their abilities, and the one with the best performance is rewarded by the task publisher.

**Publisher (User)**: A publisher, also known as a user, is an individual or organization that creates tasks in the marketplace. Publishers are responsible for defining the tasks, providing necessary details, and setting the rewards. They rely on the Decentralized Auction Marketplace to find suitable providers (bidders) to complete their tasks. Once the bidding process is complete and a provider has successfully delivered the task, the publisher rewards the provider through the smart contract system.

**Decentralized Storage**: Decentralized storage systems like IPFS/Filecoin are used to store tasks and their associated data. This ensures that the data remains secure, transparent, and tamper-proof, while also allowing for easy access by authorized parties.

**Bidding Engine**: The bidding engine manages the competitive bidding process, where providers bid on tasks based on their resource capabilities and offered prices. This component ensures that tasks are allocated to providers in a fair and efficient manner.

**Smart Contracts**: Smart contracts are self-executing contracts on the EVM blockchain that govern the bidding rules, enforce fair competition, and ensure the security of transactions. They facilitate the automatic transfer of rewards from users to providers upon task completion and manage other aspects of the bidding process.

## Auction Engine

The auction engine is a critical component of the Lagrange system. It manages the bidding process for tasks, ensuring that tasks are assigned to the most suitable computing providers. Here's a breakdown of its key functionalities:

1. **Load Provider Pool**: The auction engine initially loads all active computing providers into a pool. These providers are potential bidders for tasks.
2. **Place Bid**: When a task is open for bidding, the auction engine allows a computing provider (bidder) to place a bid on the task. The bid is only successful if the task is currently accepting bids, the bidder has not already placed a bid, and the bidder's collateral is sufficient.
3. **Load Tasks from Redis**: The auction engine fetches all tasks from Redis that are in a state where they can accept bids. It also handles state transitions for tasks, such as moving a task from the 'accepting\_bids' state to the 'bidding\_closed' state when the bidding period ends.
4. **Select Bidders**: The auction engine selects bidders based on certain criteria. For example, it might select the bidders with the highest collateral.
5. **Run Bidding Process**: For each task that is open for bidding, the auction engine runs the bidding process. It allows the selected bidders to place their bids on the task.
6. **List Tasks Available for Bidding**: The auction engine can provide a list of all tasks that are currently open for bidding.

The auction engine is designed to be fair and efficient, ensuring that tasks are distributed evenly among computing providers and that the bidding process is competitive. It plays a crucial role in the operation of the Lagrange network.

The data structure for each task in the platform includes:

* uuid: A unique identifier for the task.
* status: The current status of the task (e.g., open, closed, in progress, completed).
* task\_detail\_cid: A content identifier for the task details, stored on a decentralized storage system like IPFS.
* type: The type or category of the task.
* reference\_id: A reference ID for linking related tasks or resources.
* name: The name or title of the task.
* leading\_job\_id: The ID of the job currently in the leading processing status, used for tracking purposes.
* created\_at: The timestamp when the task was created.
* updated\_at: The timestamp when the task was last updated.
* user\_id: The ID of the user who created the task.

When a user publishes a task, multiple providers (blockchain nodes worldwide) can bid on the task. The Bidding Engine evaluates these bids and assigns the task to several bidders with the potential to complete the task effectively. Once they complete the task, the Bidding Engine assesses the quality of their work, updating the leading\_job\_id as necessary to keep track of the best-performing bidder.

Finally, the provider who delivers the highest-quality work is marked as successful and receives a reward from the task publisher. By employing this mechanism, the Bidding Engine promotes efficiency and transparency in the Decentralized Bidding Marketplace, ensuring that tasks are matched with the most suitable providers and completed to the highest standards.

### Autobid

The Decentralized Bidding Marketplace can be configured to include an auto-bid mode for providers, which allows them to automatically participate in all bids without manual intervention. This feature can be particularly useful for providers who want to streamline their bidding process and maximize their chances of securing tasks.

To enable the auto-bid mode, providers need to set up their capability and resource availability for bidding. This information includes the type of resources they can offer (such as storage, network bandwidth, CPU, and GPU), their capacity for each resource, and any other relevant details that may impact their ability to complete tasks.

When auto-bid mode is enabled, the Bidding Engine automatically pushes tasks to the provider based on their configured capabilities and resource availability. The Bidding Engine evaluates the provider's suitability for each task and includes their bid in the competitive bidding process. This automatic participation ensures that providers have a constant presence in the marketplace and can secure tasks that match their expertise and resources.

## Task State Machine

The bidding task state machine is a system designed to manage the bidding process for tasks, taking into account task details such as price and timeout. In this setup, each task allows a maximum of three bidders to compete simultaneously, with each bidder being assigned a job to complete.

Bidders have the ability to set a limit on the number of bids they can process at the same time. This feature prevents them from accepting new bids once they reach their specified limit, enabling bidders to effectively manage their workload and participate in multiple tasks without overextending themselves.

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

### States

The Bidding State Machine has several predefined states:

1. **created**: This is the initial state when a task is first created. The task stays in this state until bidding is opened.
2. **accepting\_bids**: In this state, the task is open for bidders to place their bids. The task remains in this state until bidding is closed, the bid is cancelled, or the bid fails.
3. **bidding\_closed**: This state indicates that the bidding process for the task has ended. The task transitions to this state from the 'accepting\_bids' state. From here, the task can either be marked as 'submitted' or 'failed'.
4. **submitted**: This state signifies that the task has been submitted successfully. The task moves to this state from the 'bidding\_closed' state. Once a task is in the 'submitted' state, it can then be completed.
5. **completed**: This is the final state indicating that the task has been completed successfully. The task transitions to this state from the 'submitted' state.
6. **failed**: This state indicates that the task has failed. The task can enter this state from the 'bidding\_closed' state. If a task fails, it can be reset to the 'created' state.
7. **cancelled**: This state signifies that the bid for the task has been cancelled. The task can enter this state from the 'accepting\_bids' state. If a bid is cancelled or fails, the task can be reset to the 'created' state.

The transitions between these states are managed by the state machine, which ensures that the task moves through its lifecycle in a controlled and predictable manner.

* `open_bidding`: Transition from Created to Accepting\_Bids.
* `close_bidding`: Transition from Accepting\_Bids to Processing.
* `cancel_bid`: Transition from Accepting\_Bids to Cancelled.
* `failed_bids`: Transition from Accepting\_Bids to Cancelled.
* `complete_task`: Transition from Submitted to Completed.
* `mark_as_submitted`: Transition from Processing to Submitted.
* `mark_as_failed`: Transition from Processing to Failed.
* `reset_accepting_bids_to_created`: Transition from Accepting\_Bids to Created.
* `reset_failed_bids_to_created`: Transition from Failed to Created.

The Bidding State Machine has defined transitions between states:

### Transition Between States

1. open\_bidding: Transition from 'Created' to 'Accepting\_Bids'.
2. close\_bidding: Transition from 'Accepting\_Bids' to 'Processing'.
3. cancel\_bid: Transition from 'Accepting\_Bids' to 'Cancelled'.
4. failed\_bids: Transition from 'Accepting\_Bids' to 'Cancelled'.
5. complete\_task: Transition from 'Submitted' to 'Completed'.
6. mark\_as\_submitted: Transition from 'Processing' to 'Submitted'.
7. mark\_as\_failed: Transition from 'Processing' to 'Failed'.
8. reset\_accepting\_bids\_to\_created: Transition from 'Accepting\_Bids' to 'Created'.
9. reset\_failed\_bids\_to\_created: Transition from 'Failed' to 'Created'.

### Rules

The bidding task state machine should include the following rules:

* A bidder cannot place a bid if they have exceeded their limit on the number of jobs they can process simultaneously.
* Once a bidder has completed a job, they cannot be assigned any further jobs on the same task.

If the task is cancelled, all bids and jobs associated with the task are cancelled as well


# Connect to Orchestrator

**Prerequisites :**

* **ETH**
  * Ensure that you have sufficient ETH for gas fee.
    * You can bridge ETH from Etherum to Swan Chain by visiting [https://bridge.swanchain.io](https://bridge.swanchain.io/).
  * Ensure that you have sufficient Swan Credit Token (SWANC) for collateral.
    * You can obtain SWANC by following this [guide](/swan-chain-campaign/swan-chain-mainnet/swan-credit-token).
* **Obtain Filecoin V28 Parameters (optional)**
  * To complete UBI tasks, you need to have the Filecoin V28 parameters.
  * Make sure you have the parameters corresponding to 512M and 32G sectors, as these cater to different task requirements.

Ensure that you have completed all these preparations before connecting to the Orchestrator.

**Step 1: Setup Your Computing Provider**

Follow this [guide](/bulders/computing-provider/fog-computing-provider-fcp/computing-provider-setup) to deploy your Computing Provider and make sure you have the latest version installed.

{% embed url="<https://github.com/swanchain/go-computing-provider>" %}

**Step 2: Deposit SWANC Tokens as Collateral**

```
 computing-provider collateral add --fcp --from <YOUR_WALLET_ADDRESS>  <amount>
```

**Note:** Currently one AI task requires 5 `SWANC`. Please deposit enough collaterals for the tasks

**Step 3: Real-Time Monitoring**

Stay informed about your collateral balance by checking it in real-time. If the balance falls below the configured threshold, a warning `No sufficient collateral Balance, the current collateral balance is ...`will be logged.

**Option 1:** Check your collateral information by using the following command:

```bash
# Check CP wallet Swan token balance and collateral information
computing-provider collateral info
```

**Option 2:** Log in to Dashboard > Profile > CP Collateral Check

<figure><img src="/files/2MZ97d7J4KOcW5dNDvv9" alt=""><figcaption></figcaption></figure>

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

**Congratulations!**

Your nodes are now ready to receive task assignments. You can check the status of your nodes [here](https://orchestrator.swanchain.io/provider-status).


# Web3 ZK Computing Market


# ZK Auction Engine

### 1. Introduction

The **ZK Computing Market** is a crucial component of the Swan Chain ecosystem, serving as the primary Market Provider (MP) for Zero-Knowledge (ZK) computations. One of its sub-components, the **ZK Sequencer**, plays a pivotal role in processing tasks and proofs.

### 2. ZK Engine Component

**1. Functions**

* **Task Collection and Assignment**: The ZK Engine collects and assigns ZK tasks to appropriate CPs based on available resources.
* **Proof Validation and Settlement:** It validates proofs submitted to the Swan Chain, handling the financial settlement, including rewards and penalties.

**2. ZK Sequencer**

* **Proof Management:** The Sequencer verifies and batches proofs into blobs, storing them in the Swan IPFS Storage and creating unique identifiers (CIDs). **This step minimizes gas costs for the network**.
* **Collateral Management:** It ensures CPs have sufficient collateral and handles batch settlement of tasks, including reward distribution, slashing, and gas payments.
* **Data Integrity:** The Sequencer ensures the integrity of task data, checking for modifications and confirming the authenticity of proofs. It also manages the CID creation process and records it on the Swan Chain.

### 3. Workflow

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

1. Task Assignment and Pooling:
   * The ZK Engine aggregates various ZK tasks (such as FIL-C2-512M, FIL-C2-32G, ALEO, etc.) into the ZK Tasks Pool.
2. Proof Submission by ECPs:
   * Edge Computing Providers (ECPs) receive tasks from the ZK Tasks Pool.
   * After completing the required computations, ECPs generate proofs for the completed tasks.
   * ECPs have two options for submitting proofs:
     * Direct Submission: Proofs are submitted directly to the Swan Chain, incurring standard gas fees.
     * Submission via Sequencer: Proofs are submitted through the Sequencer, which aggregates the proofs, potentially reducing gas fees due to the more efficient batching and storage process.
3. Proof Processing and Verification:
   * Proof Engine: Processes the submitted proofs. It verifies the proofs for correctness.
   * If proof is valid, the process moves forward to collateral checking; if invalid, it may lead to penalties.
4. Collateral Checking:
   * The system checks whether the ECP has sufficient collateral locked.
   * This check determines the outcome for the ECP based on proof validity and collateral status.
5. Outcome Determination:
   * Reward Distribution: If the proof is valid and the collateral is sufficient, the Reward Engine processes rewards for the ECP.
   * Slashing: If the proof is invalid or collateral is insufficient, the Slash Engine applies penalties, potentially deducting funds from the ECP's CP Account.
6. Sequencer Operations:
   * For proofs submitted via the Sequencer, the Sequencer aggregates the proofs into blobs.
   * These blobs are stored in the Swan IPFS Storage, which optimizes gas costs and ensures data integrity.
7. Swan Chain Integration:
   * The Sequencer or direct submission mechanisms create an AggregateTask entry on the Swan Chain, which records the aggregated proofs and associated data.
   * The Swan Chain manages collateral, GAS fees, rewards, and slashing information, maintaining transparency and accountability.
8. Batch Settlement:
   * The ZK Engine periodically settles all submitted and verified proofs.
   * This settlement process includes distributing rewards to ECPs or imposing penalties for invalid proofs or inadequate collateral.

### 5. Interaction with External Modules

#### 1. Swan Chain Contracts

* Collateral Contract:
  * Manages CP stakes
  * Handles locking and unlocking of collateral
  * Executes slashing when necessary
* AggregatorTask Contract:
  * Records task blob CIDs on-chain
  * Provides a transparent, immutable record of processed tasks
* TaskRegister Contract:
  * Handles task registration and tracking

#### 2. Swan IPFS Storage

* Stores aggregated task data as blobs
* Generates unique CIDs for each stored blob
* Provides efficient retrieval of task data when needed

#### 3. Filecoin Network

* Acts as a backup storage solution for Swan IPFS Storage data
* Ensures long-term data availability and redundancy


# Sequencer

The Sequencer plays a crucial role in:

* **Receiving Proofs:** Securely receives proofs from CPs.
* **Validating Proofs:** Checks the integrity, authenticity, and timeliness of proofs, including CP signatures.
* **Batching Proofs:** Aggregates proofs into blobs for efficient storage and processing.
* **Submitting Data:** Submits aggregated task data to the Swan Chain, creating AggregateTask contracts with blob CIDs.
* **Gas Fee Management:** Manages gas fees for CPs, maintaining separate accounts for gas costs and charging a small fee per task.

**Dynamic Pricing Strategy**

Due to significant increases in ETH mainnet gas prices, the Sequencer has implemented a dynamic pricing strategy to maintain stable L3 operations. The price per proof is calculated using the following formula:

$$
Gas = \frac{ \frac{Gas\_{base}}{GasPrice\_{base}}\*GasPrice\_{real}}{Count\_{proof}}
$$

$$
Gas\_{L3} =  \min(Gas, Gas\_{max})
$$

Where:

* $$Gas\_{base}$$ = 0.01 ETH
* $$GasPrice\_{base}$$ = 20 Gwei
* $$GasPrice\_{real}$$ = Current ETH mainnet gas price at the time of L3 chain interaction
* $$Gas\_{max}$$ = 0.00001 ETH

For example, based on recent network conditions (as of November 12):

* Daily network-wide proof submissions ($$Count\_{proof}$$) = 8,500
* Average gas price ($$GasPrice\_{real}$$) = 25 Gwei

$$
Gas\_{L3} = \min( \frac{ \frac{0.01}{20}\*25 }{8500}, 0.00001)=0.000001470588235 ETH
$$

This results in an adjusted gas fee that ensures efficient operation while maintaining cost-effectiveness for all participants.


# Contribute zk-UBI-task

**About UBI:**

[Universal Basic Income(UBI)](https://docs.swanchain.io/getting-started/protocol-stack/economic-system/swan-universal-basic-income-ubi), powered by Filecoin zk-SNARK proof mechanisms, aims to provide a basic level of compensation to qualified [Computing Providers](https://docs.swanchain.io/orchestrator/as-a-computing-provider) within the Swan decentralized computing ecosystem.

**About UBI Task**

A UBI task is a specific computing activity within the Swan decentralized computing ecosystem, designed to reward Computing Providers with tokens(SWAN) based on their contributions to the network's overall functionality.

**About UBI Task Pool**

The **UBI Task Pool** in Swan's UBI Engine is dedicated to handling **resource-intensive computational tasks**. To submit such tasks, follow the process below, and Computing Providers in the Swan network will efficiently manage and complete these computational tasks on your behalf.


# How to Contribute

To contribute your zk-tasks to the UBI Task Pool, please follow these steps. For each task, submit a separate application. If you have multiple tasks, kindly submit individual applications for each.

### Step 1: Fill out Information:

Provide details below and create a new [GitHub Issue](https://github.com/swanchain/devgrants/issues).

**ZK-Task Information:**

* Describe your zk-task, including task details, completion requirements, and minimal resource prerequisites.
* **Resource Requirements:**
  * RAM:
  * Storage:
  * vCPU numbers:
  * GPU:
* **Input Parameters:**
  * Specify input parameters required for your zk-task.
* **Task Completion:**
  * Clarify the method to complete your task (customized binary, or other).
* **Output:**
  * Describe the zk proof generated as output.
* **Verification:**
  * Explain how to verify your proof.
* **Additional Parameters:**
  * Mention any other necessary parameters.
* ***A complete example**: Include the task sample, proof, verify result etc.*

> *Note: Repeat these steps for each zk-task if multiple tasks are being submitted.*

**Example Application:**

> **ZK-Task Information:**
>
> * *Description:* Implementing a customized binary for secure data processing.
> * *Resource Requirements:*
>   * RAM: 16GB
>   * Storage: 200GB
>   * vCPU numbers: 4
>   * GPU: Nvidia GTX 1080
> * *Input Parameters:* JSON file with task specifications.
> * *Task Completion:* Utilize the provided binary for data processing.
> * *Output:* ZK proof generated after task completion.
> * *Verification:* Refer to the attached verification guide.
> * Additional Parameters: *Any additional information, requirements, or dependencies.*
> * *A complete example: Include the task sample, proof, verify result etc.*

**Submission Guidelines:**

1. Fill out the information above.
2. Create a new [GitHub Issue](https://github.com/swanchain/devgrants/issues). with this information.Once the issue is reviewed and approved, we will provide you with the "ubi\_engine\_base\_url" for you to submit your zk-task.
3. Label the issue with "zk-task" and any specific task identifiers.

We appreciate your contributions to elevate the UBI Task Pool with your innovative zk-tasks.

### Step 2: Submit your ZK-task to the UBI Task Pool

You can submit your zk-task to the pool through the API.

* Method: \[POST] {ubi\_hub\_base\_url}/v1/tasks
* Request Parameters:

```
//Parameters examples:
{
  "name": "example_task",
  "type": 1,
  "zk_type": "fil-c2-512M",
  "input_param": "example_input_zsdt_url",
  "verify_param": "example_verify_url",
  "resource_id": 1
}
```

| Parameter      | Type   | Description                                                                                                                            |
| -------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------- |
| `name`         | string | Task name                                                                                                                              |
| `type`         | int    | Task type 0: CPU; 1: GPU                                                                                                               |
| `zk_type`      | string | ZK type (e.g., fil-c2-512M、fil-c2-32G)                                                                                                 |
| `input_param`  | string | Network storage address of the input parameter file for executing UBI-task, compressed in zsdt format (recommended to use MCS storage) |
| `verify_param` | string | Network storage address of the input parameter file for verifying UBI-task results (recommended to use MCS storage)                    |
| `resource_id`  | int    | Resource ID 1,2,3,4                                                                                                                    |

* Response:

```
// return the task_id
{
  "task_id": 1,
}
```

#### Request Demo

```
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/swanchain/ubi-benchmark/utils"
	"net/http"
)

func main() {
	var task = Task{
		Name:        "example_task",
		Type:        1,
		ZkType:      "fil-c2-512M",
		InputParam:  "example_input_zsdt_url",
		VerifyParam: "example_verify_url",
		ResourceID:  GPU512,
	}

	jsonData, err := json.Marshal(task)
	if err != nil {
		log.Errorf("JSON encoding failed: %v", err)
		return
	}

	resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatal("POST request failed: %v", err)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode == http.StatusOK {
		fmt.Printf("Request successful, status code: %d \n", resp.StatusCode)
	} else {
		fmt.Printf("Request failed, status code: %d \n", resp.StatusCode)
	}
}

type Task struct {
	Name        string `json:"name"`
	Type        int    `json:"type"`
	ZkType      string `json:"zk_type"`
	InputParam  string `json:"input_param"`
	VerifyParam string `json:"verify_param"`
	ResourceID  int    `json:"resource_id"`
}

const (
	CPU512 = 1
	CPU32G = 2
	GPU512 = 3
	GPU32G = 4
)
```

<table><thead><tr><th width="87">resourceId</th><th width="87">type</th><th width="87">cpu</th><th width="87">memory_gb</th><th width="87">storage_gb</th></tr></thead><tbody><tr><td>1</td><td>CPU512</td><td>5</td><td>3</td><td>30</td></tr><tr><td>2</td><td>CPU32G</td><td>8</td><td>275</td><td>50</td></tr><tr><td>3</td><td>GPU512</td><td>5</td><td>3</td><td>30</td></tr><tr><td>4</td><td>GPU32G</td><td>8</td><td>275</td><td>50</td></tr></tbody></table>

***Note**: If the configurations mentioned above (GPU/CPU) do not meet your requirements, please leave your specific requirements in the* [*GitHub issue*](https://github.com/swanchain/devgrants/issues)*.*

### Step 3: Get the ZK-Task Proof

You can request your zk-task's result from the pool through the API.

* Method: \[GET] {ubi\_hub\_base\_url}/v1/tasks/{taskId}
* Request Parameters:

```
// Parameters Examples:
{
  "id": 1,
  "type": 1,
  "zk_type": "fil-c2-512M",
  "proof": "xxxxx"
}
```

| Parameter | Type   | Description                                   |
| --------- | ------ | --------------------------------------------- |
| `id`      | string | Task id                                       |
| `type`    | int    | Task type                                     |
| `zk_type` | string | ZK type                                       |
| `proof`   | string | Proof/result after the completion of the task |

* Response:

```
// return the task result.
{
  "proof": "xxxxx",
}
```

Thank you for your contribution, and we hope your zk-task brings added value to the Swan decentralized computing ecosystem!


# Example

**Example Application:**

> **ZK-Task Information:**
>
> * *Description:* Implementing a customized binary for secure data processing.
> * *Resource Requirements:*
>   * RAM: 16GB
>   * Storage: 200GB
>   * vCPU numbers: 4
>   * GPU: Nvidia GTX 1080
> * *Input Parameters:* JSON file with task specifications.
> * *Task Completion:* Utilize the provided binary for data processing.
> * *Output:* ZK proof generated after task completion.
> * *Verification:* Refer to the attached verification guide.
> * Additional Parameters: *Any additional information, requirements, or dependencies.*
> * *An complete example: include the task sample, proof, verify result etc.*


# Customized Market Provider

### Introduction

SwanChain provides a flexible framework that allows you to develop your own market provider. By building your own smart contracts and markets based on SwanChain's computing layer, you can customize and optimize your market provider to meet specific needs and requirements.

### Steps to Develop Your Own Market Provider

#### 1. Understand the Computing Provider Protocol

The first step is to familiarize yourself with the Computing Provider Protocol. This protocol defines the standards and operations for computing providers within the SwanChain ecosystem. You can find detailed information and guidelines here: [Computing Provider Protocol](https://docs.swanchain.io/getting-started/protocol-stack/computing-layer/computing-provider-protocol)

#### 2. Set Up a Computing Provider Account

Next, you'll need to set up a computing provider account. This account will manage your interactions with the SwanChain network, including task submissions, resource management, and payment handling. Detailed instructions can be found here: [Computing Provider Account](https://docs.swanchain.io/getting-started/protocol-stack/computing-layer/computing-provider-account)

#### 3. Develop Your Smart Contracts

With the protocol and account in place, you can start developing your smart contracts. These contracts will define the rules and operations of your market provider. Ensure that your contracts are compliant with SwanChain's standards to ensure compatibility and security.

#### 4. Create Your Market

Once your smart contracts are ready, you can create your market. This involves deploying your smart contracts to the SwanChain network and setting up the necessary infrastructure to support market operations. You can tailor your market to specific use cases, such as AI/ML tasks, storage solutions, or zero-knowledge proofs.

#### 5. Integrate with SwanChain Ecosystem

To maximize the potential of your market provider, integrate it with the broader SwanChain ecosystem. This includes connecting with other market providers, leveraging existing resources, and participating in the governance and development of the network.

#### 6. Test and Optimize

Thoroughly test your market provider to ensure it operates smoothly and efficiently. Optimize your contracts and market operations based on performance metrics and user feedback to provide the best possible service.

#### 7. Launch and Promote

Once your market provider is fully developed and tested, you can launch it on the SwanChain network. Promote your market provider to attract users and computing providers, and continuously improve your offerings based on market demand and technological advancements.

### Conclusion

Developing your own market provider on SwanChain offers the flexibility to customize and optimize market operations to meet specific needs. By following the guidelines and leveraging SwanChain's robust framework, you can build a successful market provider that enhances the capabilities of the decentralized computing ecosystem.

For more detailed information and guidance, refer to the official SwanChain documentation linked above or ask help in [discord](https://discord.com/invite/swanchain) and [telegram](https://t.me/swan_chain/1)


# Computing Provider

A Computing Provider (CP) is a third-party individual or organization that offers scalable computing resources, which businesses can access on demand over Swan network. These resources include cloud-based compute, storage, platform, and application services.

As a resource provider, you can run a **ECP** (Edge Computing Provider) and **FCP** (Fog Computing Provider) to contribute yourcomputing resource.

* **ECP (Edge Computing Provider)** specializes in processing data at the source of data generation, using minimal latency setups ideal for real-time applications. This provider handles specific, localized tasks directly on devices at the network’s edge, such as IoT devices. At the current stage, ECP supports the generation of **ZK-Snark proof of Filecoin network**, and more ZK proof types will be gradually supported, such as Aleo, Scroll, starkNet, etc. Check [Install Guideline](https://docs.swanchain.io/bulders/computing-provider/edge-computing-provider-ecp/ecp-setup) here.
* **FCP (Fog Computing Provider)** Offers a layered network that extends cloud capabilities to the edge of the network, providing services such as AI model training and deployment. This provider utilizes infrastructure like Kubernetes (K8S) to support scalable, distributed computing tasks. **FCP** will execute tasks assigned by Market Provider, like [Orchestrator](https://orchestrator.swanchain.io/) on the [Swan chain](https://swanchain.io/). Check [Install Guideline](https://docs.swanchain.io/bulders/computing-provider/fog-computing-provider-fcp/computing-provider-setup) here.

For the current status of Swan Provider Network, please check here: [https://provider.swanchain.io](https://provider.swanchain.io/overview)

### **Address Types**

A CP account has three different wallet addresses to ensure security and separation of responsibilities:

* `ownerAddress`: This is the owner account of the CP account. The owner has permission to change account information such as the multi-address, worker address, and beneficiary address. In most situations, the private key of the `ownerAddress` does not need to be present on the server for security reasons.
* `workerAddress`: This is the actual working address used for submitting proofs (`submitProof`). It needs to be funded with a certain amount of ETH to pay for gas fees when submitting proofs.
* `beneficiaryAddress`: This is the address where all earnings from the CP account will be sent. It is solely used for receiving funds. For security purposes, the private key of the `beneficiaryAddress` should not be stored on the server to maintain isolation.

By separating these address, the system ensures that only the necessary `workerAddress` private key is present on the server, while the more sensitive `ownerAddress` and `beneficiaryAddress` private keys are kept separate, enhancing the overall security of the system.

## **Exit Procedure for a Computing Provider (CP)**

If a CP wishes to exit and stop providing computing services, two steps are required:

### **Step 1**

Set the `taskTypes` to exit status (taskTypes = 100). The specific command is:

Execute the following command:

```
computing-provider --repo <YOUR_CP_REPO> account changeTaskTypes --ownerAddress <YOUR_OWNER_ADDRESS> 100
```

### **Step 2**

Withdraw collateral from both **Collateral and Escrow accounts.** The amount in the **Collateral account** can be directly withdrawn, while the amount in the **Escrow account** requires 7 days to complete the withdrawal. The process is as follows:

#### **For an ECP:**

To withdraw from the **Collateral account:**

```
computing-provider --repo <YOUR_CP_REPO> collateral withdraw --ecp --owner <YOUR_WALLET_ADDRESS> --account <YOUR_CP_ACCOUNT> <amount>
```

To withdraw from the **Escrow account:**

Submit withdrawal request:

```
computing-provider --repo <YOUR_CP_REPO> collateral withdraw-request --ecp --owner <YOUR_OWNER_ADDRESS> <AMOUNT>
```

Confirm withdrawal (after 7-day waiting period):

```
computing-provider --repo <YOUR_CP_REPO> collateral withdraw-confirm --ecp --owner <YOUR_OWNER_ADDRESS>
```

#### For an FCP:

To withdraw from the **Collateral account:**

```
computing-provider --repo <YOUR_CP_REPO> collateral withdraw --fcp --owner <YOUR_WALLET_ADDRESS> --account <YOUR_CP_ACCOUNT> <amount>
```

To withdraw from the **Escrow account:**

Submit withdrawal request:

```
computing-provider --repo <YOUR_CP_REPO> collateral withdraw-request --fcp --owner <YOUR_OWNER_ADDRESS> <AMOUNT>
```

Confirm withdrawal (after 7-day waiting period):

```
computing-provider --repo <YOUR_CP_REPO> collateral withdraw-confirm --fcp --owner <YOUR_OWNER_ADDRESS>
```

### **Notes**

* It’s recommended to perform Step 2 (withdrawing from Escrow) 24 hours after completing Step 1, as the engine periodically settles CP accounts. This includes actions like locking collaterals, slashing collaterals, sending UBI rewards, etc., all of which may impact the success rate of your withdrawal.
* After completing Step 1, the CP will no longer receive any tasks, including UBI tasks and regular AI tasks.


# Fog Computing Provider(FCP)

Fog Computing Provider(FCP)**:** Offers a layered network that extends cloud capabilities to the edge of the network, providing services such as AI model training and deployment. This provider utilizes infrastructure like Kubernetes (K8S) to support scalable, distributed computing tasks.

**FCP hardware requirements:**

* Possess a public IP
* Have a domain name (\*.example.com)
* Have an SSL certificate
* Have at least one GPU
* At least 8 vCPUs
* Minimum 100GB SSD storage
* Minimum 64GB memory
* Minimum 50MB bandwidth

#### FCP (Fog Computing Provider) Status:

The FCP (Fog Computing Provider) status indicates the current operational state of the provider:

* **Online**: Has an FCP taskType, query is successful, sufficient collateral, and not rejecting tasks (Normal operation)
* **Offline**: Has an FCP taskType, but the query is unsuccessful
* **Version Too Low**: CP version and resource-exporter version need to be upgraded. Current latest versions are CP (v1.1.1) and resource-exporter (v12.0.0)
* **Cheating**: CP resource information collection is incorrect and fails verification
* **Sibyl**: Multiple CPs are running on the same server, indicating Sybil behavior.


# FCP Setup

## Table of Content

* [Prerequisites](#prerequisites)
* [Install the Kubernetes](#install-the-kubernetes)
  * [Install Container Runtime Environment](#install-container-runtime-environment)
  * [Optional - Setup a docker registry server](#optional-setup-a-docker-registry-server)
  * [Create a Kubernetes Cluster](#create-a-kubernetes-cluster)
  * [Install the Network Plugin](#install-the-network-plugin)
  * [Install the NVIDIA Plugin](#install-the-nvidia-plugin)
  * [Install the Ingress-nginx Controller](#install-the-ingress-nginx-controller)
* [Install and config the Nginx](#install-and-config-the-nginx)
* [Install the Hardware resource-exporter](#install-the-hardware-resource-exporter)
* [Build and config the Computing Provider](#build-and-config-the-computing-provider)
* [Install AI Inference Dependency(Optional)](#optional-install-ai-inference-dependency)
* [Install Node-Port Dependency (Optional)](#optional-install-node-port-dependency)
* [Config and Receive UBI Tasks(Optional)](#optional-config-and-receive-zk-tasks)
* [Start the Computing Provider](#start-the-computing-provider)
* [CLI of Computing Provider](#cli-of-computing-provider)

### Prerequisites

Before you install the Computing Provider, you need to know there are some resources required:

* Possess a public IP
* Have a domain name (\*.example.com)
* Have an SSL certificate
* `Go` version must 1.21+, you can refer here:

```bash
wget -c https://golang.org/dl/go1.21.7.linux-amd64.tar.gz -O - | sudo tar -xz -C /usr/local

echo "export PATH=$PATH:/usr/local/go/bin" >> ~/.bashrc && source ~/.bashrc
```

### Install the Kubernetes

The Kubernetes version should be `v1.24.0+`

#### Install Container Runtime Environment

If you plan to run a Kubernetes cluster, you need to install a container runtime into each node in the cluster so that Pods can run there, refer to [here](https://kubernetes.io/docs/setup/production-environment/container-runtimes/). And you just need to choose one option to install the `Container Runtime Environment`

**Option 1: Install the `Docker` and `cri-dockerd` （Recommended）**

To install the `Docker Container Runtime` and the `cri-dockerd`, follow the steps below:

* Install the `Docker`:
  * Please refer to the official documentation from [here](https://docs.docker.com/engine/install/).
* Install `cri-dockerd`:
  * `cri-dockerd` is a CRI (Container Runtime Interface) implementation for Docker. You can install it refer to [here](https://github.com/Mirantis/cri-dockerd).

**Option 2: Install the `Docker` and the`Containerd`**

* Install the `Docker`:
  * Please refer to the official documentation from [here](https://docs.docker.com/engine/install/).
* To install `Containerd` on your system:
  * `Containerd` is an industry-standard container runtime that can be used as an alternative to Docker. To install `containerd` on your system, follow the instructions on [getting started with containerd](https://github.com/containerd/containerd/blob/main/docs/getting-started.md).

#### Optional-Setup a docker registry server

**If you are using the docker and you have only one node, the step can be skipped**.

If you have deployed a Kubernetes cluster with multiple nodes, it is recommended to set up a **private Docker Registry** to allow other nodes to quickly pull images within the intranet.

* Create a directory `/docker_repo` on your docker server. It will be mounted on the registry container as persistent storage for our docker registry.

```bash
sudo mkdir /docker_repo
sudo chmod -R 777 /docker_repo
```

* Launch the docker registry container:

```bash
sudo docker run --detach \
  --restart=always \
  --name registry \
  --volume /docker_repo:/docker_repo \
  --env REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY=/docker_repo \
  --publish 5000:5000 \
  registry:2
```

![1](https://github.com/lagrangedao/go-computing-provider/assets/102578774/0c4cd53d-fb5f-43d9-b804-be83faf33986)

* Add the registry server to the node

  * If you have installed the `Docker` and `cri-dockerd`(**Option 1**), you can update every node's configuration:

  ```bash
  sudo vi /etc/docker/daemon.json
  ```

  ```
  ## Add the following config
  "insecure-registries": ["<Your_registry_server_IP>:5000"]
  ```

  Then restart the docker service

  ```bash
  sudo systemctl restart docker
  ```

  * If you have installed the `containerd`(**Option 2**), you can update every node's configuration:

```bash
[plugins."io.containerd.grpc.v1.cri".registry]
  [plugins."io.containerd.grpc.v1.cri".registry.mirrors]
    [plugins."io.containerd.grpc.v1.cri".registry.mirrors."<Your_registry_server_IP>:5000"]
      endpoint = ["http://<Your_registry_server_IP>:5000"]

[plugins."io.containerd.grpc.v1.cri".registry.configs]
  [plugins."io.containerd.grpc.v1.cri".registry.configs."<Your_registry_server_IP>:5000".tls]
      insecure_skip_verify = true                                                               
```

Then restart `containerd` service

```bash
sudo systemctl restart containerd
```

**\<Your\_registry\_server\_IP>:** the intranet IP address of your registry server.

Finally, you can check the installation by the command:

```bash
docker system info
```

![2](https://github.com/lagrangedao/go-computing-provider/assets/102578774/4cfc1981-3fca-415c-948f-86c496915cff)

#### Create a Kubernetes Cluster

To create a Kubernetes cluster, you can use a container management tool like `kubeadm`. The below steps can be followed:

* [Install the kubeadm toolbox](https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/install-kubeadm/).
* [Create a Kubernetes cluster with kubeadm](https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/create-cluster-kubeadm/)

#### Install the Network Plugin

Calico is an open-source **networking and network security solution for containers**, virtual machines, and native host-based workloads. Calico supports a broad range of platforms including **Kubernetes**, OpenShift, Mirantis Kubernetes Engine (MKE), OpenStack, and bare metal services.

To install Calico, you can follow the below steps, more information can be found [here](https://docs.tigera.io/calico/3.25/getting-started/kubernetes/quickstart).

**step 1**: Install the Tigera Calico operator and custom resource definitions

```
kubectl create -f https://raw.githubusercontent.com/projectcalico/calico/v3.25.1/manifests/tigera-operator.yaml
```

**step 2**: Install Calico by creating the necessary custom resource

```
kubectl create -f https://raw.githubusercontent.com/projectcalico/calico/v3.25.1/manifests/custom-resources.yaml
```

**step 3**: Confirm that all of the pods are running with the following command

```
watch kubectl get pods -n calico-system
```

**step 4**: Remove the taints on the control plane so that you can schedule pods on it.

```
kubectl taint nodes --all node-role.kubernetes.io/control-plane-
kubectl taint nodes --all node-role.kubernetes.io/master-
```

If you have installed it correctly, you can see the result shown in the figure by the command `kubectl get po -A`

![3](https://github.com/lagrangedao/go-computing-provider/assets/102578774/91ef353f-72af-41b2-82e8-061b92bfb999)

**Note:**

* If you are a single-host Kubernetes cluster, remember to remove the taint mark, otherwise, the task can not be scheduled to it.

```bash
kubectl taint node ${nodeName}  node-role.kubernetes.io/control-plane:NoSchedule-
```

#### Install the NVIDIA Plugin

If your computing provider wants to provide a GPU resource, the NVIDIA Plugin should be installed, please follow the steps:

* [Install NVIDIA Driver](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html#nvidia-drivers).

> Recommend NVIDIA Linux drivers version should be 470.xx+

* [Install NVIDIA Device Plugin for Kubernetes](https://github.com/NVIDIA/k8s-device-plugin#quick-start).

If you have installed it correctly, you can see the result shown in the figure by the command `kubectl get po -n kube-system`

![4](https://github.com/lagrangedao/go-computing-provider/assets/102578774/8209c589-d561-43ad-adea-5ecb52618909)

#### Install the Ingress-nginx Controller

The `ingress-nginx` is an ingress controller for Kubernetes using `NGINX` as a reverse proxy and load balancer. You can run the following command to install it:

```bash
kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.7.1/deploy/static/provider/cloud/deploy.yaml
```

**Note**

* If you want to support the deployment of jobs with IP whitelists, you need to change the configuration of the configmap of the Ingress-nginx Controller and apply it. First download the `deploy.yaml` file, modify the `ConfigMap` resource object in the configuration file, and add a line under`data`:

```bash
use-forwarded-headers: "true"
```

If you have installed it correctly, you can see the result shown in the figure by the command:

* Run `kubectl get po -n ingress-nginx`

![5](https://github.com/lagrangedao/go-computing-provider/assets/102578774/f3c0585a-df19-4971-91fe-d03365f4edee)

* Run `kubectl get svc -n ingress-nginx`

![6](https://github.com/lagrangedao/go-computing-provider/assets/102578774/e3b3dadc-77c1-4dc0-843c-5b946e252b65)

#### Install and config the Nginx

* Install `Nginx` service to the Server

```bash
sudo apt update
sudo apt install nginx
```

* Add a configuration for your Domain name Assume your domain name is `*.example.com`

```
vi /etc/nginx/conf.d/example.conf
```

```bash
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
        listen 80;
        listen [::]:80;
        server_name *.example.com;                                           # need to your domain
        return 301 https://$host$request_uri;
        #client_max_body_size 1G;
}
server {
        listen 443 ssl;
        listen [::]:443 ssl;
        ssl_certificate  /etc/letsencrypt/live/example.com/fullchain.pem;     # need to config SSL certificate
        ssl_certificate_key  /etc/letsencrypt/live/example.com/privkey.pem;   # need to config SSL certificate

        server_name *.example.com;                                            # need to config your domain
        location / {
          proxy_pass http://127.0.0.1:<port>;  	# Need to configure the Intranet port corresponding to ingress-nginx-controller service port 80
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection $connection_upgrade;
          proxy_cookie_path / "/; HttpOnly; Secure; SameSite=None";
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;
       }
}
```

* **Note:**
  * `server_name`: a generic domain name
  * `ssl_certificate` and `ssl_certificate_key`: certificate for https.
  * `proxy_pass`: The port should be the Intranet port corresponding to `ingress-nginx-controller` service port 80
* Reload the `Nginx` config

  ```bash
  sudo nginx -s reload
  ```
* Map your "catch-all (wildcard) subdomain(\*.example.com)" to a public IP address

#### Install the Hardware resource-exporter

The `resource-exporter` plugin is developed to collect the node resource constantly, computing provider will report the resource to the Lagrange Auction Engine to match the space requirement. To get the computing task, every node in the cluster must install the plugin. You just need to run the following command:

```bash
cat <<EOF | kubectl apply -f -
apiVersion: apps/v1
kind: DaemonSet
metadata:
  namespace: kube-system
  name: resource-exporter-ds
  labels:
    app: resource-exporter
spec:
  selector:
    matchLabels:
      app: resource-exporter
  template:
    metadata:
      labels:
        app: resource-exporter
    spec:
      containers:
        - name: resource-exporter
          image: swanhub/resource-exporter:v13.0.5
          imagePullPolicy: IfNotPresent
          securityContext:
            # Privileged is often required when accessing host paths like /sys and /proc
            privileged: true 
          volumeMounts:
            # Existing binding
            - name: machine-id
              mountPath: /etc/machine-id
              readOnly: true
            # New binding for /proc
            - name: host-proc
              mountPath: /host/proc
              readOnly: true
            # New binding for /sys
            - name: host-sys
              mountPath: /host/sys
              readOnly: true
      volumes:
        # Existing volume for /etc/machine-id
        - name: machine-id
          hostPath:
            path: /etc/machine-id
            type: File
        # Volume for /proc (mapped to /host/proc)
        - name: host-proc
          hostPath:
            path: /proc
            type: Directory
        # Volume for /sys (mapped to /host/sys)
        - name: host-sys
          hostPath:
            path: /sys
            type: Directory
EOF
```

If you have installed it correctly, you can see the result shown in the figure by the command: `kubectl get po -n kube-system`

![7](https://github.com/lagrangedao/go-computing-provider/assets/102578774/38b0e15f-5ff9-4edc-a313-d0f6f4a0bda8)

### Build and config the Computing Provider

* Build the Computing Provider

  Firstly, clone the code to your local:

```bash
git clone https://github.com/swanchain/go-computing-provider.git
cd go-computing-provider
git checkout releases
```

Then build the Computing provider on the **Swan Mainnet** by following the below steps:

```bash
make clean && make mainnet
make install
```

> If you want to test the CP in the **testnet**, please build a testnet version:
>
> ```bash
> make clean && make testnet
> make install
> ```

### Initialize CP repo and Update Configuration

1. Initialize repo

   ```
   computing-provider init --multi-address=/ip4/<YOUR_PUBLIC_IP>/tcp/<YOUR_PORT> --node-name=<YOUR_NODE_NAME>
   ```

   **Note:**

   * By default, the CP's repo is `~/.swan/computing`, you can configure it by `export CP_PATH="<YOUR_CP_PATH>"`
   * The CP service port (`8085` by default) must be mapped to the public IP address and port
2. Update `config.toml`

   Edit the necessary configuration files according to your deployment requirements.

   ```toml
      [API]
      Port = 8085                                    # The port number that the web server listens on
      MultiAddress = "/ip4/<public_ip>/tcp/<port>"   # The multiAddress for libp2p
      Domain = ""                                    # The domain name
      NodeName = ""                                  # The computing-provider node name
      WalletWhiteList = ""                           # CP only accepts user addresses from this whitelist for space deployment
      WalletBlackList = ""                           # CP reject user addresses from this blacklist for space deployment
      Pricing = "true"                               # default True, indicating acceptance of smart pricing orders, which may include orders priced lower than self-determined pricing.
      AutoDeleteImage = false                        # Default false, automatically delete unused images
      ClearLogDuration = 24                          # The interval for automatically clearing the log, the unit is hours
      PortRange= ["40000-40050","40070"]             # Externally exposed port number for deploying ECP image tasks
     
      [UBI]
      UbiEnginePk = "0xB5aeb540B4895cd024c1625E146684940A849ED9"              # UBI Engine's public key, CP only accept the task from this UBI engine
      EnableSequencer = true                                                  # Submit the proof to Sequencer service(default: true)
      AutoChainProof = true                                                   # When Sequencer doesn't have enough funds or the service is unavailable, automatically submit proof to the Swan chain 
      SequencerUrl = "https://sequencer.swanchain.io"                         # Sequencer service's API address
      EdgeUrl = "https://edge-api.swanchain.io/v1"                            # Edge service's API address
      VerifySign = true                                                       # Verify that the task signature is from Engine
                                      
      [LOG]
      CrtFile = "/YOUR_DOMAIN_NAME_CRT_PATH/server.crt"                       # Your domain name SSL .crt file path
      KeyFile = "/YOUR_DOMAIN_NAME_KEY_PATH/server.key"                       # Your domain name SSL .key file path

      [HUB]
      BalanceThreshold= 10                                                    # The cp’s collateral balance threshold
      OrchestratorPk = "0xd875bD44158208fD0FDD46729Aab6709f62C7821"           # Orchestrator's public key, CP only accept the task from this Orchestrator
      VerifySign = true                                                       # Verify that the task signature is from Orchestrator

      [MCS]
      ApiKey = ""                                   # Acquired from "https://swanipfs.com/" -> setting -> Create API Key
      BucketName = ""                               # Acquired from "https://swanipfs.com/" -> bucket -> Add Bucket
      Network = "polygon.mainnet"                   # polygon.mainnet for mainnet, polygon.mumbai for testnet

      [Registry]
      ServerAddress = ""                            # The docker container image registry address, if only a single node, you can ignore
      UserName = ""                                 # The login username, if only a single node, you can ignore
      Password = ""                                 # The login password, if only a single node, you can ignore

      [RPC]
      SWAN_CHAIN_RPC = "https://mainnet-rpc-01.swanchain.org"     # Swan chain RPC
   ```

**Note:**

* Example `[api].WalletWhiteList` hosted on GitHub can be found [here](https://raw.githubusercontent.com/swanchain/market-providers/main/clients/whitelist.txt).
* Example `[api].WalletBlackList` hosted on GitHub can be found [here](https://raw.githubusercontent.com/swanchain/market-providers/main/clients/blacklist.txt).

### Initialize a Wallet and Deposit `SwanETH`

1. Generate a new wallet address or import the previous wallet:

   ```bash
   computing-provider wallet new
   ```

   Example output:

   ```
   0x7791f48931DB81668854921fA70bFf0eB85B8211
   ```

   **or** import your wallet:

   ```bash
   # Import wallet using the private key
   computing-provider wallet import <YOUR_PRIVATE_KEY_FILE>
   ```

   **Note:** `<YOUR_PRIVATE_KEY_FILE>` is a file that contains the private key
2. Deposit `SwanETH` to the wallet address:

   ```bash
   computing-provider wallet send --from <YOUR_WALLET_ADDRESS> 0x7791f48931DB81668854921fA70bFf0eB85B8211 0.01
   ```

   **Note:** If you don't have `SwanETH` and `SWAN`, please follow [the guideline](https://docs.swanchain.io/swan-mainnet/getting-started-guide) to [bridge ETH to Swan Mainnet](https://bridge.swanchain.io).

### Initialization CP Account

Deploy a CP account contract:

```bash
computing-provider account create --ownerAddress <YOUR_OWNER_WALLET_ADDRESS> \
	--workerAddress <YOUR_WORKER_WALLET_ADDRESS> \
	--beneficiaryAddress <YOUR_BENEFICIARY_WALLET_ADDRESS>  \
	--task-types 3
```

**Note:** `--task-types`: Supports 5 task types (`1`: Fil-C2, `2`: Mining, `3`: AI, `4`: Inference, `5`: NodePort), separated by commas. For FCP, it needs to be set to 3.

**Output:**

```
Contract deployed! Address: 0x3091c9647Ea5248079273B52C3707c958a3f2658
Transaction hash: 0xb8fd9cc9bfac2b2890230b4f14999b9d449e050339b252273379ab11fac15926
```

### Collateral `SWAN` for FCP

```bash
 computing-provider collateral add --fcp --from <YOUR_WALLET_ADDRESS>  <amount>
```

**Note:** Please deposit enough collaterals for the tasks

### Withdraw `SWAN` from FCP

```bash
 computing-provider collateral withdraw --fcp --owner <YOUR_WALLET_ADDRESS> --account <YOUR_CP_ACCOUNT> <amount>
```

**Note:** If you want to withdraw the funds from FCP, you can run the above command

### Start the Computing Provider

You can run `computing-provider` using the following command

```bash
export CP_PATH=<YOUR_CP_PATH>
nohup computing-provider run >> cp.log 2>&1 & 
```

***

### \[**OPTIONAL**] Install AI Inference Dependency

It is necessary for the Computing Provider to deploy the AI inference endpoint. But if you do not want to support the feature, you can skip it.

```bash
export CP_PATH=<YOUR_CP_PATH>
./install.sh
```

### \[**OPTIONAL**] Install Node-Port Dependency

* Install Resource Isolation service on the k8s cluster In order to view the actual available resources of the container, you need to install a resource isolation service on the cluster.
  * For Ubuntu 20.04:

    ```
    kubectl apply -f https://raw.githubusercontent.com/swanchain/go-computing-provider/refs/heads/releases/resource-isolation-20.04.yaml
    ```
  * For Ubuntu 22.04 and higher.

    * Edit `/etc/default/grub` and modify it to the following content:

    ```bash
       GRUB_CMDLINE_LINUX_DEFAULT="quiet splash systemd.unified_cgroup_hierarchy=0"
    ```

    * Update grub configuration

    ```
    update-grub
    ```

    * Reboot the system

    ```bash
       reboot now
    ```

    * Install resource-isolation service on k8s

    ```
      kubectl apply -f https://raw.githubusercontent.com/swanchain/go-computing-provider/refs/heads/releases/resource-isolation.yaml
    ```
* Install network policies

  * Generate Network Policy (location at $CP\_PATH/network-policy.yaml )

  ```bash
  computing-provider network generate
  ```

  * Deploy Network Policy

  ```bash
  kubectl apply -f $CP_PATH/network-policy.yaml
  ```

  * Confirm that all of the network policy are running with the following command.

  ```
  # kubectl get gnp
  NAME                    CREATED AT
  global-01kls78xh7dk4n   2024-09-25T04:00:59Z
  global-ao9kq72mjc0sl3   2024-09-25T04:00:59Z
  global-e59cad59af9c65   2024-09-25T04:00:59Z
  global-pd6sdo8cjd61yd   2024-09-25T04:00:59Z
  global-pod1namespace1   2024-09-25T04:01:00Z
  global-s92ms87dl3j6do   2024-09-25T04:01:00Z

  # kubectl get globalnetworksets
  NAME                    CREATED AT
  netset-2300e518e9ad45   2024-09-25T04:00:59Z
  ```

  **Note:** The nodes for deploying CP need to open ports in the range of `30000-32767`
* Change the `tasktypes`

```bash
computing-provider account changeTaskTypes --ownerAddress <YOUR_OWNER_WALLET_ADDRESS> 3,5
```

> **Note:** `--task-types` Supports 5 task types:
>
> * `1`: FIL-C2
> * `2`: Mining
> * `3`: AI
> * `4`: Inference
> * `5`: NodePort

### \[**OPTIONAL**] Config and Receive ZK Tasks

This section mainly introduces how to enable the function of receiving ZK tasks on FCP, which is equivalent to running an ECP. This function is optional. Once enabled, FCP can earn double benefits simultaneously, but it will also consume certain resources.

#### **Step 1: Prerequisites:** Perform Filecoin Commit2 (fil-c2) ZK tasks.

1. Download parameters (specify the path with PARENT\_PATH variable):

   ```bash
   # At least 200G storage is needed
   export PARENT_PATH="<V28_PARAMS_PATH>"

   # 512MiB parameters
   curl -fsSL https://raw.githubusercontent.com/swanchain/go-computing-provider/releases/ubi/fetch-param-512.sh | bash

   # 32GiB parameters
   curl -fsSL https://raw.githubusercontent.com/swanchain/go-computing-provider/releases/ubi/fetch-param-32.sh | bash
   ```
2. Configure environment variables in `fil-c2.env` under CP repo (`$CP_PATH`):

   ```bash
   FIL_PROOFS_PARAMETER_CACHE=$PARENT_PATH
   RUST_GPU_TOOLS_CUSTOM_GPU="GeForce RTX 3080:8704" 
   ```

* Adjust the value of `RUST_GPU_TOOLS_CUSTOM_GPU` based on the GPU used by the CP's Kubernetes cluster for fil-c2 tasks.
* For more device choices, please refer to this page:<https://github.com/filecoin-project/bellperson>

#### Step 2: Collateral `SWAN` for ZK tasks

```bash
computing-provider collateral add --ecp --from <YOUR_WALLET_ADDRESS>  <amount>
```

> If you want to withdraw the collateral `SWAN`:
>
> ```bash
> computing-provider collateral withdraw --ecp --owner <YOUR_WALLET_ADDRESS> --account <YOUR_CP_ACCOUNT> <amount>
> ```

#### Step 3: Change the `tasktypes`

```bash
computing-provider account changeTaskTypes --ownerAddress <YOUR_OWNER_WALLET_ADDRESS> 1,2,3,4
```

> **Note:** `--task-types` Supports 5 task types:
>
> * `1`: FIL-C2
> * `2`: Mining
> * `3`: AI
> * `4`: Inference
> * `5`: NodePort

> If you need to run FCP and ECP at the same time, you need to set it to `1,2,3,4`

#### Step 4: Deposit `SwanETH` for Sequencer Account

```bash
computing-provider sequencer add --from <YOUR_WALLET_ADDRESS>  <amount>
```

> If you want to Withdraw SwanETH from Sequencer Account
>
> ```bash
> computing-provider sequencer withdraw --owner <YOUR_OWNER_WALLET_ADDRESS>  <amount>
> ```

#### **Step 5: Account Management**

Use `computing-provider account` subcommands to update CP details:

```
computing-provider account -h
NAME:
   computing-provider account - Manage account info of CP

USAGE:
   computing-provider account command [command options] [arguments...]

COMMANDS:
   create                    Create a cp account to chain
   changeMultiAddress        Update MultiAddress of CP (/ip4/<public_ip>/tcp/<port>)
   changeOwnerAddress        Update OwnerAddress of CP
   changeWorkerAddress       Update workerAddress of CP
   changeBeneficiaryAddress  Update beneficiaryAddress of CP
   changeTaskTypes           Update taskTypes of CP (1:Fil-C2, 2:Mining, 3: AI, 4:Inference, 5:NodePort, 100:Exit), separated by commas
   help, h                   Show a list of commands or help for one command

OPTIONS:
   --help, -h  show help
```

#### Step 6: Check the Status of ZK task

To check the ZK task list, use the following command:

```
computing-provider ubi list --show-failed
```

Example output:

```
TASK ID TASK CONTRACT                                   TASK TYPE       ZK TYPE STATUS          SEQUENCER       CREATE TIME         
1114203 0x89580E512915cB33bB5Ac419196835fC19affaEe      GPU             fil-c2  verified        YES             2024-11-12 01:52:47
1113642 0x89580E512915cB33bB5Ac419196835fC19affaEe      GPU             fil-c2  verified        YES             2024-11-12 02:22:30
1132325 0x89580E512915cB33bB5Ac419196835fC19affaEe      GPU             fil-c2  verified        YES             2024-11-12 02:52:29
1114228 0x89580E512915cB33bB5Ac419196835fC19affaEe      GPU             fil-c2  verified        YES             2024-11-12 03:22:10
1113911 0xF222604e4628d0c15bFAfD1AABf23F7FF5756056      GPU             fil-c2  verified        YES             2024-11-12 04:22:43
1114105 0xF222604e4628d0c15bFAfD1AABf23F7FF5756056      GPU             fil-c2  verified        YES             2024-11-12 04:52:46
1113869 0xF222604e4628d0c15bFAfD1AABf23F7FF5756056      GPU             fil-c2  verified        YES             2024-11-12 05:22:29
1114219 0xF222604e4628d0c15bFAfD1AABf23F7FF5756056      GPU             fil-c2  verified        YES             2024-11-12 05:52:44
1113349 0xF222604e4628d0c15bFAfD1AABf23F7FF5756056      GPU             fil-c2  verified        YES             2024-11-12 06:22:50
1114204 0xF222604e4628d0c15bFAfD1AABf23F7FF5756056      GPU             fil-c2  verified        YES             2024-11-12 06:52:40
1113259 0xF222604e4628d0c15bFAfD1AABf23F7FF5756056      GPU             fil-c2  verified        YES             2024-11-12 07:22:29
1113568 0xF222604e4628d0c15bFAfD1AABf23F7FF5756056      GPU             fil-c2  verified        YES             2024-11-12 07:52:37
1132314 0xF222604e4628d0c15bFAfD1AABf23F7FF5756056      GPU             fil-c2  verified        YES             2024-11-12 08:22:39
1132312 0xF222604e4628d0c15bFAfD1AABf23F7FF5756056      GPU             fil-c2  verified        YES             2024-11-12 08:52:39
1113823 0xF222604e4628d0c15bFAfD1AABf23F7FF5756056      GPU             fil-c2  verified        YES             2024-11-12 09:22:28
1132500 0xF222604e4628d0c15bFAfD1AABf23F7FF5756056      GPU             fil-c2  verified        YES             2024-11-12 09:52:37
```

### Restart the Computing Provider

You can run `computing-provider` using the following command

```bash
export CP_PATH=<YOUR_CP_PATH>
nohup computing-provider run >> cp.log 2>&1 & 
```

### CLI of Computing Provider

* Check the current list of tasks running on CP, display detailed information for tasks using `-v`

```
computing-provider task list --fcp
```

* Retrieve detailed information for a specific task using `job_uuid`

```
computing-provider task get --fcp [job_uuid]
```

* Delete task by `job_uuid`

```
computing-provider task delete --fcp [job_uuid]
```

### Getting Help

For usage questions or issues reach out to the Swan team either in the [Discord channel](https://discord.gg/3uQUWzaS7U) or open a new issue here on GitHub.

### License

Apache


# Migrating FCP to Swan Mainnet

Now all CPs can migrate to the mainnet to participate in Swan Mainnet Campaign

## How to Upgrade and Migrate to Swan Mainnet

### First-time Deployment

If you are deploying for the first time, you can follow the instructions in the latest version: Swan Chain Computing Provider v1.0.2: <https://github.com/swanchain/go-computing-provider/releases/tag/v1.0.2>

### Migration from Proxima to Mainnet

1. **Update `resource-exporter` to the latest version `v12.0.0`**: Follow the instructions in this issue: [Update Resource Exporter to v11.3.0.](https://github.com/swanchain/go-computing-provider/issues/14)
2. **Specify a new CP\_PATH**:

   ```bash
   export CP_PATH="/YOUR/CP/PATH"
   ```
3. **Download the mainnet version of the computing-provider**:

   ```bash
   wget https://github.com/swanchain/go-computing-provider/releases/download/v1.0.2/computing-provider
   ```
4. **Verify CP version**:

   ```bash
   computing-provider -v
   ```

   Ensure it shows `version 1.0.2+mainnet`.
5. **Initialize CP repo and update configuration**: Refer to [Initialize CP Repo and Update Configuration](https://github.com/swanchain/go-computing-provider/tree/v0.6.1?tab=readme-ov-file#initialize-cp-repo-and-update-configuration)

   Note:

   * No need to modify parts of the configuration file with default values.
   * The "contract address" is now built into the program, no separate configuration is needed.
   * The default configuration file template can be found [here](https://github.com/swanchain/go-computing-provider/blob/v0.6.1/config.toml.sample).
6. **Initialize a Wallet and Deposit SwanETH**: Refer to [Initialize a Wallet and Deposit SwanETH](https://github.com/swanchain/go-computing-provider/tree/v0.6.1?tab=readme-ov-file#initialize-a-wallet-and-deposit-swaneth).
7. **Initialization CP Account**: Refer to [Initialization CP Account](https://github.com/swanchain/go-computing-provider/tree/v0.6.1?tab=readme-ov-file#initialization-cp-account).
8. **Collateral SWANC for FCP**: Refer to [Collateral SWANC for FCP](https://github.com/swanchain/go-computing-provider/tree/v0.6.1?tab=readme-ov-file#collateral-swanc-for-fcp).
9. **Withdraw SWANC from FCP**: Refer to [Withdraw SWANC from FCP](https://github.com/swanchain/go-computing-provider/tree/v0.6.1?tab=readme-ov-file#withdraw-swanc-from-fcp).
10. **Start the Computing Provider**: Refer to [Start the Computing Provider](https://github.com/swanchain/go-computing-provider/tree/v0.6.1?tab=readme-ov-file#start-the-computing-provider).

### Mainnet Changes

1. **Different Compilation Method**:
   * Mainnet version: `make mainnet`
   * Testnet version: `make testnet`
2. **Different Collateral**:
   * In the mainnet, FCP collateral is SwanC. Each task requires 5 SwanC collateral (claim from <https://faucet.swanchain.io>).
3. **Different Task Distribution Platform**:
   * Mainnet task distribution platform: <https://lagrange.computer>, same as the testnet lagrangeDAO platform.
4. **Funds Operations**:
   * Refer to [Funds Operations Guide](https://docs.swanchain.io/swan-provider/computing-provider-cp/fog-computing-provider-fcp/fcp-token-operations-guide).
5. **ECP (Edge Computing Provider)**:
   * The new version will support ECP running independently or with FCP, allowing FCP to earn both rewards simultaneously.
   * ECP tasks are more frequent but offer lower rewards.

For any questions, refer to the detailed documentation on the [Swan Mainnet Campaign](https://docs.swanchain.io/swan-chain/swan-chain-mainnet/swan-provider-campaign).


# FCP Funding Operations Guide

## Introduction

This guide provides detailed instructions on how to manage token-related operations required for Fog Computing Providers (FCP) in the Swan Chain network. Follow this guide to ensure you have the necessary tokens and collateral for your tasks.

### 1. Preparation

#### 1.1 Obtaining ETH for Gas Fees

FCP requires `ETH` as transaction gas fees. Follow these steps to get `ETH`:

* Visit Swan Chain's official bridge website: [bridge.swanchain.io](https://bridge.swanchain.io)
* Cross-chain your `ETH` to Swan Chain to get `Swan ETH`.
* It is recommended to prepare enough `ETH` to account for fluctuations in network gas fees.

#### 1.2 Obtaining SWAN for Collateral

FCP requires SWAN as collateral, you can buy it from CEXs.

SWAN is currently listed on [Gate.io](https://www.gate.io/trade/SWAN_USDT), [MEXC](https://www.mexc.com/exchange/SWAN_USDT), and [LBank](https://www.lbank.com/trade/swan_usdt).

Contract Address: 0xBb4eC1b56cB624863298740Fd264ef2f910d5564

### 2. Collateral Management

#### 2.1 Collateral Requirements

* Collateral amounts dynamically adjust based on network computing power.
  * Review our[ comprehensive collateral documentation](https://docs.swanchain.io/core-concepts/token/computing-provider-collateral/collateral-requirement-and-earning-multiplier) for detailed information
* Monitor the [Swan dashboard](https://provider.swanchain.io/overview) for computing units and base collateral trends(upcoming feature)
* Maintain sufficient collateral to ensure continuous task eligibility

**2.2 Slash Collateral**

To maintain network performance and accountability, CPs are subject to a precise slashing mechanism that penalizes inefficient or unreliable computing services. For each failed task, CPs face graduated penalties:

* Fog Computing Providers (FCP) lose 0.1% of their current full collateral amount per failed task (approximately 3.533 SWAN for a 3080 GPU), with around 14 tasks processed daily.

If a CP's collateral amount falls below the required threshold, they become ineligible to receive Universal Basic Income (UBI) tasks. To mitigate the risk of unexpected task exclusion, CPs are advised to maintain a buffer in their collateral amount.

More details about Slash Collateral, check here: <https://docs.swanchain.io/core-concepts/token/computing-provider-collateral#slashing-mechanism>

### 3. Reward Mechanism

#### 3.1 Task Completion Reward

* FCPs can earn rewards after completing tasks.
* Users are billed hourly based on the resources provided by the FCP.
* Different configurations have different pricing, check the price [here](https://docs.lagrangedao.org/spaces/space-settings/space-hardware).

#### 3.2 Revenue Distribution (coming soon)

* The revenue distribution for each deployment is as follows:
  * The platform takes a 5% service fee.
  * The remaining 95% is divided among up to three FCPs (task processors).

***


# FCP FAQ

### Q: What is the current version of Computing Provider, and are there any tutorials?

**A:**

The latest version is v1.1.2: <https://github.com/swanchain/go-computing-provider/releases/tag/v1.1.2>

Check the dashboard here : <https://provider.swanchain.io>

Tutorials

* [Deploy your ECP](/bulders/computing-provider/edge-computing-provider-ecp/ecp-setup)
* [Depoy your FCP](/bulders/computing-provider/fog-computing-provider-fcp/computing-provider-setup)

### **Q: How can I verify whether the FCP environment is installed successfully?**

```
curl -k https://<PUBLIC_IP>:<PORT>/api/v1/computing/cp
```

out:

```

{
    "node_id": "04f4af161995c1cc0f8a4c1dd316a64b809c879e1cc7",
    "region": "North Carolina-US",
    "cluster_info": [
        {
            "machine_id": "4c4c4544-0046-3510-8058-b1c04f504433",
            "cpu_name": "AMD",
            "cpu": {
                "total": "192",
                "used": "16",
                "free": "176"
            },
            "memory": {
                "total": "2003 GiB",
                "used": "62 GiB",
                "free": "1822 GiB"
            },
            "gpu": {
                "driver_version": "535.104.05",
                "cuda_version": "12020",
                "attached_gpus": 1,
                "details": [
                    {
                        "product_name": "NVIDIA 3080",
                        "status": "available",
                        "fb_memory_usage": {
                            "total": "10240 MiB",
                            "used": "235 MiB",
                            "free": "10004 MiB"
                        },
                        "bar1_memory_usage": {
                            "total": "256 MiB",
                            "used": "2 MiB",
                            "free": "253 MiB"
                        }
                    }
                ]
            },
            "storage": {
                "total": "877 GiB",
                "used": "456 GiB",
                "free": "376 GiB"
            }
        }
    ],
    "multi_address": "/ip4/provider.cp.cn/tcp/9085",
    "node_name": "fcp-001"
}
```

### **Q: How to verify if FCP is running properly?**

* **Step 1: Check Collateral**:

```
computing-provider --repo info
```

[![image](https://private-user-images.githubusercontent.com/102578774/403743114-61fb8bc2-71cd-4dc1-bcf0-fb9fd073d4b0.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MzczNjU4NDUsIm5iZiI6MTczNzM2NTU0NSwicGF0aCI6Ii8xMDI1Nzg3NzQvNDAzNzQzMTE0LTYxZmI4YmMyLTcxY2QtNGRjMS1iY2YwLWZiOWZkMDczZDRiMC5wbmc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjUwMTIwJTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI1MDEyMFQwOTMyMjVaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT1kNGViYWNjNjZmOGZlMzk5ZWFlMWI2YTdjOWIzODY5MzcxODFjMDgyMWM2N2FhODAxYmY2ODZmNTA2MTUyZjYwJlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCJ9.pZv0WwUht5iaNj_u9_mYh8v7w3o9KUIVeAzJKdF6llI)](https://private-user-images.githubusercontent.com/102578774/403743114-61fb8bc2-71cd-4dc1-bcf0-fb9fd073d4b0.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MzczNjU4NDUsIm5iZiI6MTczNzM2NTU0NSwicGF0aCI6Ii8xMDI1Nzg3NzQvNDAzNzQzMTE0LTYxZmI4YmMyLTcxY2QtNGRjMS1iY2YwLWZiOWZkMDczZDRiMC5wbmc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjUwMTIwJTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI1MDEyMFQwOTMyMjVaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT1kNGViYWNjNjZmOGZlMzk5ZWFlMWI2YTdjOWIzODY5MzcxODFjMDgyMWM2N2FhODAxYmY2ODZmNTA2MTUyZjYwJlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCJ9.pZv0WwUht5iaNj_u9_mYh8v7w3o9KUIVeAzJKdF6llI)

Ensure that the sum of `Collateral` and `Escrow` under the `FCP Balance` is greater than the calculated collateral amount for proper staking.

* **Step 2: Check Versions**:
  * **CP Version**:

```
computing-provider -v
```

Verify the CP version by checking the commit number in the official [go-computing-provider](https://github.com/swanchain/go-computing-provider) repository to confirm if your version is up-to-date or the recommended stable version.

* **Resource-Exporter Version**:

```
kubectl get daemonset resource-exporter-ds -n kube-system -o yaml | grep image:
```

Verify the version of `resource-exporter` by checking the required version in the [official repository](https://github.com/swanchain/go-computing-provider/tree/releases?tab=readme-ov-file#Install-the-Hardware-resource-exporter).

* **Step 3: Check Resource Endpoint**:

```
curl -k https://<cp-ip>:<port>/api/v1/computing/cp
```

> **Note**: Replace `<cp-ip>` and `<port>` with the corresponding information from your `CP_REPO` configuration file, where `MultiAddress = "/ip4/<ip>/tcp/<port>"`.

* **Step 4: Self-check by submitting a job**:

```
curl -k --location --request POST 'https://<cp-ip>:<port>/api/v1/computing/lagrange/jobs' \
--header 'Content-Type: application/json' \
--data-raw '{
"uuid": "5641877b-dc94-469a-bb3b-ecab6d10f7dd",
"name": "Job-5641877b-dc94-469a-bb3b-ecab6d10f7dd",
"status": "Submitted",
"duration": 900,
"job_source_uri": "https://api.lagrange.computer/spaces/97e1a802-0f80-4806-9b3f-8d8dce173e21",
"storage_source": "lagrange",
"task_uuid": "92cd5595-9789-4af3-9100-7c7e4aacb456"
}'
```

* **Step 5: Dashboard Status Check**:\
  In the [Provider Dashboard](https://provider.swanchain.io/), locate your CP using the `cpAccount`. Check that the status is `Online`, and ensure collateral is sufficient (as shown in the example). If so, your CP is running properly.

[![image](https://private-user-images.githubusercontent.com/102578774/403743342-47049468-d9bb-4aac-8870-6dafa84a3866.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MzczNjU4NDUsIm5iZiI6MTczNzM2NTU0NSwicGF0aCI6Ii8xMDI1Nzg3NzQvNDAzNzQzMzQyLTQ3MDQ5NDY4LWQ5YmItNGFhYy04ODcwLTZkYWZhODRhMzg2Ni5wbmc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjUwMTIwJTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI1MDEyMFQwOTMyMjVaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT1lNjIxYjQ4MjE4NWU0MWRlNjQ5ZDY4MGM0MTg3MmI4NGVmMzc4ZWNlNWYwMDE5OWI1NzU3MGMxMDRlOWZkYTQ5JlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCJ9.EcB2kTi8-iSWx_ots34RfO3JT8fvL99TI1zmMGtAptA)](https://private-user-images.githubusercontent.com/102578774/403743342-47049468-d9bb-4aac-8870-6dafa84a3866.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MzczNjU4NDUsIm5iZiI6MTczNzM2NTU0NSwicGF0aCI6Ii8xMDI1Nzg3NzQvNDAzNzQzMzQyLTQ3MDQ5NDY4LWQ5YmItNGFhYy04ODcwLTZkYWZhODRhMzg2Ni5wbmc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjUwMTIwJTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI1MDEyMFQwOTMyMjVaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT1lNjIxYjQ4MjE4NWU0MWRlNjQ5ZDY4MGM0MTg3MmI4NGVmMzc4ZWNlNWYwMDE5OWI1NzU3MGMxMDRlOWZkYTQ5JlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCJ9.EcB2kTi8-iSWx_ots34RfO3JT8fvL99TI1zmMGtAptA)

### Q: How can I know if the status of the computing provider is normal?

**A**:

Set the `[HUB].VerifySign` in the **`$CP_PATH/config.toml`** file

```
[HUB]
VerifySign = false
```

Run the following command:

{% hint style="info" %}
***\*Note: Please replace\*\*\*\*****&#x20;****`<YOUR_MULTI_ADDRESS_IP>:<PORT>`****&#x20;****\*\*\*\*with your actual multi-address IP and port.***
{% endhint %}

```
curl -k --location --request POST 'https://<YOUR_MULTI_ADDRESS_IP>:<PORT>/api/v1/computing/lagrange/jobs' \
--header 'Content-Type: application/json' \
--data-raw '{
"uuid": "5641877b-dc94-469a-bb3b-ecab6d10f7dd",
"name": "Job-5641877b-dc94-469a-bb3b-ecab6d10f7dd",
"status": "Submitted",
"duration": 900,
"job_source_uri": "https://api.lagrangedao.org/spaces/51d6abbb-f928-43e4-91fd-79e93e2b276f",
"storage_source": "lagrange",
"task_uuid": "92cd5595-9789-4af3-9100-7c7e4aacb456"
}'
```

After running this command, wait for 3-5 minutes, and then execute

<pre><code><strong>kubectl get ing -n ns-0x6091b2f5678952cafbf02755d78973ebff302e11
</strong></code></pre>

Find the hosts corresponding to the name `ing-minesweeper` and ensure that the domain can be accessed in a browser to confirm its normal status.

### **Q: How can I verify if my Computing Provider is set up to receive UBI tasks?**

**A**:

1. Replace the UbiEnginePk in the **`$CP_PATH/config.toml`** file with the `ownerAddress`:

   Copy

   ```
   [UBI]
   UbiEnginePk ="0xxxxx"
   ```
2. Restart `computing-provider`.
3. Generate the signature using the following command:

   Copy

   ```
   computing-provider wallet sign <ownerAddress> <nodeid+contract_addr>
   ```

   For example, if nodeid is abcd and task contract\_addr is 11:

   Copy

   ```
   computing-provider wallet sign <ownerAddress> abcd11
   ```
4. Prepare raw data for the ubi-task test task:

   Copy

   ```
   {

   "id": 26384,
   "name": "1000-0-7-26381",
   "type": 1,
   "resource_type": 0,
   "deadline": 2000000,
   "check_code": "check_code-demo",
   "input_param": "https://286cb2c989.acl.swanipfs.com/ipfs/QmTgoX6LkzZTsTjSjXvujzgJEHBLTEg3KMUadQGnyTrNFG",
   "verify_param": "https://286cb2c989.acl.swanipfs.com/ipfs/QmTgoX6LkzZTsTjSjXvujzgJEHBLTEg3KMUadQGnyTrNFG.verify",
   "resource":{"cpu":"10","memory":"5.00 GiB","storage":"10.00 GiB"}
   "signature":"Signing_cpAccountAddress_and_id_with_ownerAddress"

   }
   ```
5. Submit the `ubi-task` using the following command(using your public IP and port ):

   Copy

   ```
   curl --location --request POST 'http://<public_IP>:<port>/api/v1/computing/cp/ubi' \
   --header 'Content-Type: application/json' \
   --data-raw '{
       "id": 26384,
       "name": "1000-0-7-26381",
       "type": 1,
       "resource_type": 0,
       "deadline": 2000000,
       "check_code": "check_code-demo",
       "input_param": "https://286cb2c989.acl.swanipfs.com/ipfs/QmTgoX6LkzZTsTjSjXvujzgJEHBLTEg3KMUadQGnyTrNFG",
       "verify_param": "https://286cb2c989.acl.swanipfs.com/ipfs/QmTgoX6LkzZTsTjSjXvujzgJEHBLTEg3KMUadQGnyTrNFG.verify",
       "resource":{"cpu":"10","memory":"5.00 GiB","storage":"10.00 GiB"}
       "signature":"Signing_cpAccountAddress_and_id_with_ownerAddress"
   }'
   ```
6. After running ubi-task, check if the task status is success:

   Copy

   ```
   computing-provider ubi list
   ```
7. If the test is successful, restore the `UbiEnginePk` in the `config.toml` file to its original value\\

### Q: How to upgrade resource-exporter in FCP

**A**:

1. Stop the computing-provider service.
2. Delete component `resource-exporter` and `filswan/resource-exporter` local image

```
kubectl delete ds -n kube-system resource-exporter-ds

docker rmi -f filswan/resource-exporter:v11.3.2
```

3. Reinstall `resource-exporter` by the command:

```
cat <<EOF | kubectl apply -f -
apiVersion: apps/v1
kind: DaemonSet
metadata:
 namespace: kube-system
 name: resource-exporter-ds
 labels:
   app: resource-exporter
spec:
 selector:
   matchLabels:
     app: resource-exporter
 template:
   metadata:
     labels:
       app: resource-exporter
   spec:
     containers:
     - name: resource-exporter
       image: filswan/resource-exporter:v12.0.0
       imagePullPolicy: IfNotPresent
       securityContext:
         privileged: true
       volumeMounts:
         - name: machine-id
           mountPath: /etc/machine-id
           readOnly: true
     volumes:
       - name: machine-id
         hostPath:
           path: /etc/machine-id
           type: File

EOF
```

4. Check the `resource-exporter` version:

```
kubectl describe po -n kube-system resource-exporter-ds |grep "Image:"
```

It should be:

```
Image:          filswan/resource-exporter:v12.0.0
```

and ensure it is running by `kubectl get po -n kube-system`

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

5. Start `computing-provider`

### Q: Which ports need to be mapped?

**A**: Here are the ports you need to map

1\. You need to map the CP's internal IP and its port (default 8085), as well as the public IP and port.

2\. Map your wildcard domain (\*.example.com) to your public IP.

3\. Additionally, you need to map port 80 of your internal IP to port 80 of your public IP, as well as port 443 of your internal IP to port 443 of your public IP.

####

### Q: Where should I create the API key?

**A**: you must use the API of <https://swanipfs.com/>, and login in it using Polygon mainnet wallet.

####

### Q: What are the requirements for SSL certificates needed in CP?

**A:** Please use certificates issued by trusted Certificate Authorities (CA). Currently, certificates generated by Certbot are not functioning properly.

Otherwise, the application won't be displayed correctly on the Space App page.

####

### **Q: Is it possible to use a port other than 80 and 443 in the wildcard domain(\*.exmaple.com)?**

**A**: No, it is not possible.

####

### Q: Is the "`pod"` used for communication, and "`Calico`" is used to manage this communication within the cluster?

**A**: Both are used for intra-cluster communication. You can use one of these approaches.

####

### Q: If someone didn't apply for early bird, can they still join and run the computing provider tasks?

**A**: Of course, they can also follow the [instruction](https://github.com/swanchain/docs/blob/main/bulders/computing-provider/fog-computing-provider-fcp/broken-reference/README.md) to set up a Computing Provider.

####

### Q: Can I move my computing provider to a new one while maintaining my previous server? Will this reset my uptime?

**A**: Yes, you need to move `.swan_node` to the new server. The uptime will not be reset.

####

### **Q: How can I migrate my CP (Computing Provider) to a new environment?**

**A:** To migrate your CP to a new environment, follow these steps:

1. **Backup CP Repo**: Copy all files under the old CP directory (`$CP_PATH`) to a directory on the new server, for example: `/data/swan`.
2. **Set Environment Variable**: Set the environment variable `CP_PATH` to the directory where you copied the CP files on the new server. For example, you can do this by running the command: `export CP_PATH=/data/swan`.
3. **Start CP Service**: Once the files are copied and the environment variable is set, start the CP service process on the new server.

By following these steps, you'll successfully migrate your CP to the new environment, ensuring that it operates smoothly in the new environment.

### **Q: How can I resolve the error `(error) MISCONF Redis is configured to save RDB snapshots`seen in the FCP logs?**

**A:** MISCONF Redis is configured to save RDB snapshots but is currently not able to persist on disk, Commands that may modify the data set are disabled.

You can try to change the setting:

```
$ redis-cli
> config set stop-writes-on-bgsave-error no
```

### Q: **How do I withdraw collateral from FCP?**

To withdraw collateral from FCP, use the following command:

```bash
computing-provider --repo <YOUR_CP_PATH> collateral withdraw --fcp --owner <YOUR_OWNER_WALLET_ADDRESS> --account <YOUR_CP_ACCOUNT> <AMOUNT>
```


# Edge Computing Provider (ECP)

## Edge Computing Provider (ECP)

**ECP (Edge Computing Provider)** specializes in processing data at the source of data generation, using minimal latency setups ideal for real-time applications. This provider handles specific, localized tasks directly on devices at the network’s edge, such as IoT devices.

At the current stage, ECP supports the generation of **ZK-Snark proof of Filecoin network**, and more ZK proof types will be gradually supported, such as Aleo, Scroll, starkNet, etc

\
**ECP hardware requirements:**

* Possess a public IP
* Have at least one GPU
* At least 4 vCPUs
* Minimum 300GB HDD storage
* Minimum 32GB memory
* Minimum 20MB bandwidth

#### ECP (Edge Computing Provider) Status:

The ECP (Edge Computing Provider) status indicates the current operational state of the provider:

* **Inactive**: Previously had an ECP taskType, but no longer does.
* **Online**: Has an ECP taskType, query is successful, sufficient collateral, and not rejecting tasks (Normal operation).
* **Offline**: Has an ECP taskType, but query is unsuccessful.
* **NSC (Not Sufficient Collateral)**: Has an ECP taskType, but insufficient collateral.
* **NSR (No sufficient resource):** Has an ECP taskType, but lacks the necessary resources (e.g., CPU, memory, or storage) to perform tasks.
* **Declined**: Has an ECP taskType, but rejecting tasks (due to insufficient resources or sequencer).
* **Inconsistent**: Local information does not match on-chain information (e.g., CP account, multiaddress, nodeID).
* **Version Too Low:** CP version and resource-exporter version need to be upgraded. Current latest versions are CP (v1.1.1) and resource-exporter (v12.0.0)
* **Cheating:** CP resource information collection is incorrect and fails verification
* **Sibyl**: Multiple CPs are running on the same server, indicating Sybil behavior.


# ECP Setup

> Source link: <https://github.com/swanchain/go-computing-provider/blob/releases/ubi/README.md>\
> **Please refer to the above link for up-to-date information.**

**ECP (Edge Computing Provider)** specializes in processing data at the source of data generation, using minimal latency setups ideal for real-time applications. This provider handles specific, localized tasks directly on devices at the network’s edge, such as IoT devices.

At the current stage, ECP supports the generation of **ZK-Snark proof of Filecoin network**, and more ZK proof types will be gradually endorsed, such as Aleo, Scroll, starkNet, etc

### Prerequisites

* Need to map the ECP service port of the intranet to the public network, the default port is`9085`:

```
 <Intranet_IP>:<9085> <--> <Public_IP>:<PORT>
```

* Running the `setup.sh`

```bash
curl -fsSL https://raw.githubusercontent.com/swanchain/go-computing-provider/releases/ubi/setup.sh | bash
```

* Download the v28 parameters for `ZK-FIL` task:

```bash
# At least 200G storage is needed
export PARENT_PATH="<V28_PARAMS_PATH>"

# 512MiB parameters
curl -fsSL https://raw.githubusercontent.com/swanchain/go-computing-provider/releases/ubi/fetch-param-512.sh | bash

# 32GiB parameters
curl -fsSL https://raw.githubusercontent.com/swanchain/go-computing-provider/releases/ubi/fetch-param-32.sh | bash

```

### Install ECP and Init CP Account

* Download `computing-provider`

```bash
wget https://github.com/swanchain/go-computing-provider/releases/download/v1.1.1/computing-provider
```

* Initialize ECP repo

```bash
 ./computing-provider init --multi-address=/ip4/<YOUR_PUBLIC_IP>/tcp/<YOUR_PORT> --node-name=<YOUR_NODE_NAME>
```

* Generate a new wallet address and deposit the `SwanETH`, refer [here](https://docs.swanchain.io/swan-mainnet/getting-started-guide):

```bash
./computing-provider wallet new
```

Output:

```
 0x9024a875f44172591373b92...31d67AcCEa
```

* **\[OPTIONAL]** You can also import your own wallet by private key

```
./computing-provider wallet import private.key
```

> **Note:**
>
> 1. By default, the CP's repo is `~/.swan/computing`, you can configure it by `export CP_PATH="<YOUR_CP_PATH>"`
> 2. `private.key` is a file that contains the private key

* Initialize ECP Account

```bash
./computing-provider account create \
                    --ownerAddress <YOUR_OWNER_ADDRESS> \
                    --workerAddress <YOUR_WORKER_ADDRESS> \
                    --beneficiaryAddress <YOUR_BENEFICIAERY_ADDRESS>  \
                    --task-types 1,2,4
```

**Note:** `--task-types`: Supports 5 task types (1: Fil-C2, 2: Mining, 3: AI, 4: Inference, 5: NodePort, 100: Exit), separated by commas. For ECP, it needs to be set to 1,2,4.

* Collateral `SWAN` for ECP

```bash
computing-provider collateral add --ecp --from <YOUR_WALLET_ADDRESS>  <AMOUNT>   
```

> If you want to withdraw `SWAN` from ECP
>
> ```bash
> computing-provider collateral withdraw --ecp --owner <YOUR_WALLET_ADDRESS> --account <YOUR_CP_ACCOUNT> <amount>
> ```

* Deposit `SwanETH` to Sequencer Account

  ```bash
  computing-provider sequencer add --from <YOUR_WALLET_ADDRESS>  <amount>
  ```

> If you want to Withdraw `SwanETH` from Sequencer Account
>
> ```bash
> computing-provider sequencer withdraw --owner <YOUR_OWNER_WALLET_ADDRESS>  <amount>
> ```

> **Note:** the gas cost is decided by the [**Dynamic Pricing Strategy**](https://docs.swanchain.io/bulders/market-provider/web3-zk-computing-market/sequencer)

### Config resource price

**Pricing:** Indicating acceptance of smart pricing orders, which may include orders priced lower than self-determined pricing. default "true"

Configure it in the `$CP_PATH/price.toml`:

```
[API]
Pricing = "true"   
```

1. Generate the pricing config with default values(Located at `$CP_PATH/price.toml`):

```
computing-provider --repo <YOUR_CP_PATH> price generate
```

2. Customize your resource prices, adjust resource prices based on how many swans are configured per hour

```
vi $CP_PATH/price.toml
```

example:

```
TARGET_CPU="0.2"            # SWAN/thread-hour
TARGET_MEMORY="0.1"         # SWAN/GB-hour
TARGET_HD_EPHEMERAL="0.005" # SWAN/GB-hour
TARGET_GPU_DEFAULT="1.6"    # SWAN/Default GPU unit a hour
TARGET_GPU_3080=""          # SWAN/3080 GPU unit a hour
```

3. View the configured price information:

```
computing-provider --repo <YOUR_CP_PATH> price view
```

CP Hardware Price Info:\
TARGET\_CPU: 0.2 SWAN/thread-hour\
TARGET\_MEMORY: 0.1 SWAN/GB-hour\
TARGET\_HD\_EPHEMERAL: 0.005 SWAN/GB-hour\
TARGET\_GPU\_DEFAULT: 1.6 SWAN/Default GPU unit a hour TARGET\_GPU\_3080: SWAN/GPU unit a hour

### Config and Receive Inference task

The task type is configured as 4 (inference), and need to be configured as follows:

* For container services with a single port, use `traefik`. Using `traefik` as the entry point for requests, you need to configure a domain(\*.example.com) to resolve to the IP where CP is running. The port 9000 must be open for external access.
* For container services with multiple ports, use the public IP + port. Need to configure `PortRange`( one-to-one mapping between host ports and the public network IP).

Configure it in the `$CP_PATH/config.toml`:

```
[API]
Domain = ""                                 # The domain name
AutoDeleteImage = false                     # Default false, automatically delete unused images
PortRange = ["40000-40050","40060",""40065] # Externally exposed port number for deploying multi-port image tasks  
```

Check the Status of Inference and Mining task

* Use the following command:

```
computing-provider task list --ecp
```

* Example output:

```
TASK UUID                               TASK NAME                               IMAGE NAME                              CONTAINER NAME                                  CONTAINER STATUS        REWARD  CREATE TIME  
75f9df4e-b6a5-40b0-b7ac-02fb1840dafa    iron02                                  swanchain254/iron_mainnet_f2pool:latest iron02-2b0d5                                    terminated              0.0000  2024-10-24 10:23:32
842dd7d3-e9f0-4795-af3b-104fa5527099    Zil1                                    swanchain254/zil_mainnet_f2pool:latest  Zil1-gb5sq                                      terminated              0.6195  2024-11-15 03:49:44
30f60c6f-085e-4cd3-b751-bf6081a6a2e2    rvn-f2-003                              swanchain254/rvn_mainnet_f2pool:latest  rvn-f2-003-082ei                                terminated              7.5016  2024-11-15 05:40:14
9b16aa08-66aa-4ffe-b7d6-7a6db512ea6c    rvn-004                                 swanchain254/rvn_mainnet_f2pool:latest  rvn-004-to2cr                                   terminated              5.9034  2024-11-15 05:44:21
4c95d6e6-34b2-49de-be7d-7ee326b641c7    Zil                                     swanchain254/zil_mainnet_f2pool:latest  Zil-81ydq                                       terminated              0.1155  2024-11-15 06:56:49
```

### Start ECP service

```bash
#!/bin/bash
export FIL_PROOFS_PARAMETER_CACHE=$PARENT_PATH
export RUST_GPU_TOOLS_CUSTOM_GPU="GeForce RTX 4090:16384"
        
nohup ./computing-provider ubi daemon >> cp.log 2>&1 &
```

**Note:**

* `<FIL_PROOFS_PARAMETER_CACHE>` is your parameters directory,
* `RUST_GPU_TOOLS_CUSTOM_GPU` is your GPU model and cores, you should update it to your own GPU model. More examples can be found [here](https://github.com/filecoin-project/bellperson?tab=readme-ov-file#supported--tested-cards)
* `<YOUR_PUBLIC_IP>`, `<YOUR_PORT>` are your public IP and port ,
* `<YOUR_NODE_NAME>` is your CP name which will show in the dashboard, If not specified, the default is `hostname`.

### About Sequencer

#### Why need Sequencer?

In past tests, we discovered that due to the frequent interactions required by ECP (Ethereum Compliance Proof) to submit proofs to the blockchain, ECP incurs significant gas costs. To reduce these gas costs, the Sequencer has emerged as a Layer 3 solution.

The ECP can submit proofs to the Sequencer service, which will then package and submit all proofs from the entire network over a period of time (**currently 24 hours**) in a single transaction. This way, ECP only needs to pay a minimal gas fee to the Sequencer (currently, the gas is decided by the [Dynamic Pricing Strategy](https://docs.swanchain.io/bulders/market-provider/web3-zk-computing-market/sequencer)). For more detailed information, see [here](https://docs.swanchain.io/swan-provider/market-provider-mp/zk-engine/sequencer).

#### How to Set it?

We **strongly recommend** enabling the Sequencer feature (enabled by default). The steps to enable it are as follows:

* Modify the `config.toml` file.

```
[UBI]
EnableSequencer = true             # Submit the proof to Sequencer service(default: true)
AutoChainProof = false             # when sequencer doesn't have enough funds or the service is unavailable, automatically submit proof to the Swan chain 

```

* Deposit SwanETH into the Sequencer account.

```
computing-provider sequencer add --from <YOUR_WALLET_ADDRESS>  <amount>
```

* Restart the ECP

```
#!/bin/bash
export FIL_PROOFS_PARAMETER_CACHE=$PARENT_PATH
export RUST_GPU_TOOLS_CUSTOM_GPU="GeForce RTX 4090:16384"
        
nohup ./computing-provider ubi daemon >> cp.log 2>&1 &
```


# ECP Funding Operations Guide

### Introduction

**ECP (Edge Computing Provider)** is a crucial component in the Swan Chain ecosystem and is responsible for executing Zero-Knowledge (ZK) computation tasks. The Sequencer is an optimization component aggregating proofs submitted by multiple ECPs, processing them in batches to reduce gas fees and improve overall efficiency.

### Account Overview

* **CP Account (Computing Provider Account)**: An independent on-chain contract account for CP operations and fund management. FCP and ECP have the same account structure.
  * **Owner Address**: Hold the highest authority to manage the CP account.
  * **Beneficiary Address**: Receives rewards for ZK tasks.
  * **Worker Address**: Used for submitting proofs.
* **Collateral Account**: ECP's collateral account in the collateral contract (SwanC).
  * **Escrow Account**: A account for storing ECP's collateral in collateral contarct, ensuring that ECP can receive ZK tasks.
* **Sequencer Account**: ECP's account in the sequencer contract, used to pay for gas fees required when submitting ZK proofs.

### Table of Content:

* [Initial Setup](#id-1.-initial-setup)
  * [Obtaining ETH for Gas Fees](#id-1.1-obtaining-eth-for-gas-fees)
  * [Obtaining SwanC for Collateral](#id-1.2-obtaining-swanc-for-collateral)
* [Account Setup](#id-2.-account-setup)
* [Configuring Sequencer (Recommended)](#id-3.-configuring-sequencer-recommended)
  * [Enabling Sequencer Functionality](#id-3.1-enabling-sequencer-functionality)
  * [Funding the Sequencer Account](#id-3.2-funding-the-sequencer-account)
* [Task Execution and Rewards](#id-4.-task-execution-and-rewards)
  * [Reward Distribution](#id-4.1-reward-distribution)
  * [Viewing UBI tasks](#id-4.2-viewing-ubi-tasks)
  * [Slash Mechanism](#id-4.3-slash-mechanism)
* [Exit Procedure](#id-5.-exit-procedure)
  * [Stop Receiving New Tasks](#id-5.1-stop-receiving-new-tasks)
  * [Data Backup](#id-5.2-data-backup)
  * [Withdrawal Process](#id-5.3-withdrawal-process)

### 1. Initial Setup

#### 1.1 Obtaining ETH for Gas Fees

ETH is required for transaction gas fees. Follow these steps:

1. Visit Swan Chain's official bridge website:[ https://bridge.swanchain.io](https://bridge.swanchain.io)
2. Cross-chain your ETH to Swan Chain to obtain ETH
3. Prepare sufficient ETH to account for potential fluctuations in network gas fees

#### 1.2 Obtaining SWAN for Collateral

ECP requires SWAN as collateral. You can purchase SWAN from centralized exchanges (CEXs).

SWAN is currently listed on [Gate.io](https://www.gate.io/trade/SWAN_USDT), [MEXC](https://www.mexc.com/exchange/SWAN_USDT), and [LBank](https://www.lbank.com/trade/swan_usdt).

Contract Address: 0xBb4eC1b56cB624863298740Fd264ef2f910d5564

#### 1.3 Collateral Requirements

* Collateral amounts dynamically adjust based on network computing power.
  * Review our[ comprehensive collateral documentation](https://docs.swanchain.io/core-concepts/token/computing-provider-collateral/collateral-requirement-and-earning-multiplier) for detailed information
* Monitor the [Swan dashboard](https://provider.swanchain.io/overview) for computing units and base collateral trends(upcoming feature)
* Maintain sufficient collateral to ensure continuous task eligibility

### 2. Account Setup <a href="#id-2.-account-setup" id="id-2.-account-setup"></a>

Depositing SWANU to the Collateral Account: Use the following command:

```
computing-provider collateral add --ecp --from <WALLET_ADDRESS> --account <CP_ACCOUNT> <Amount>
```

### 3. Configuring Sequencer (Recommended)

#### 3.1 Enabling Sequencer Functionality

In the ECP configuration file, set `EnableSequencer = true` and `autoChainProof = true`

When `autoChainProof` is true, ECP will prioritize submitting proofs via the sequencer. If the sequencer lacks sufficient gas, it will automatically submit proofs on-chain. If set to false, ECP won't submit tasks when the sequencer lacks gas.

{% hint style="info" %}
*Note: ECPs can submit proofs in two ways:*

* *Directly to Swan Chain as a contract (higher gas consumption per transaction)*
* *To the zk-sequencer for batch aggregation (lower gas consumption, recommended)*
  {% endhint %}

#### 3.2 Funding the Sequencer Account

When using the sequencer, pre-fund the CP's sequencer account with ETH on Swan Chain. Currently, the gas is decided by the [Dynamic Pricing Strategy](https://docs.swanchain.io/bulders/market-provider/web3-zk-computing-market/sequencer). For more detailed information, see [here](https://docs.swanchain.io/swan-provider/market-provider-mp/zk-engine/sequencer).

```
computing-provider sequencer add --from <WALLET_ADDRESS> --account <CP_ACCOUNT> <Amount>
```

***Note**: The sequencer periodically processes tasks and deducts from the sequencer account. If the balance is insufficient during settlement, it may become negative. ECPs need to refund to receive new tasks.*

### 4. Task Execution and Rewards

#### 4.1 Reward Distribution

Rewards are distributed during the next settlement cycle after 24 hours following the [CP UBI-0](/swan-chain-campaign/swan-cp-ubi) event rules, typically within 48 hours of task proof submission, to the beneficiary account.

Read [Computing Provider Income](/core-concepts/token/swan-provider-income) to learn more.

#### 4.2 Viewing UBI tasks

Check the transaction list of the beneficiary account on the blockchain explorer: <https://swanscan.io>.

Alternatively, you can use the CP command to view UBI tasks:

```
computing-provider ubi list
```

The result will look like this:

```
TASK ID  TASK CONTRACT                               TASK TYPE  ZK TYPE      STATUS    REWARD  SEQUENCER  CREATE TIME         
1081868  0x23AC299fA44aa7Df2ddDFE09cDB0331DD1945043  GPU        fil-c2-32G   verified  0.00    YES        2024-11-03 10:40:31  
1081072  0x23AC299fA44aa7Df2ddDFE09cDB0331DD1945043  GPU        fil-c2-32G   verified  0.00    YES        2024-11-03 11:10:30  
1081749  0x23AC299fA44aa7Df2ddDFE09cDB0331DD1945043  GPU        fil-c2-32G   verified  0.00    YES        2024-11-03 11:40:33  
1081904  0x23AC299fA44aa7Df2ddDFE09cDB0331DD1945043  GPU        fil-c2-32G   verified  0.00    YES        2024-11-03 12:10:34  
1081748  0x23AC299fA44aa7Df2ddDFE09cDB0331DD1945043  GPU        fil-c2-32G   verified  0.00    YES        2024-11-03 13:10:26  
1081562  0x23AC299fA44aa7Df2ddDFE09cDB0331DD1945043  GPU        fil-c2-32G   verified  0.00    YES        2024-11-03 13:40:29  
1081980  0x008E2334B34737D42128d13Ee50A78322663d7a7  GPU        fil-c2-32G   verified  0.00    YES        2024-11-03 14:10:31  
1081861  0x008E2334B34737D42128d13Ee50A78322663d7a7  GPU        fil-c2-32G   received  0.00    YES        2024-11-03 14:40:27  
```

#### 4.3 Slash Mechanism

To maintain network performance and accountability, CPs are subject to a precise slashing mechanism that penalizes inefficient or unreliable computing services. For each failed task, CPs face graduated penalties:

* Edge Computing Providers (ECP) lose 0.025% of their current full collateral amount per failed task (approximately 0.88 SWAN for a 3080 GPU), with around 48 tasks processed daily.

If a CP's collateral amount falls below the required threshold, they become ineligible to receive Universal Basic Income (UBI) tasks. To mitigate the risk of unexpected task exclusion, CPs are advised to maintain a buffer in their collateral amount.

More details about Slash Collateral, check here: <https://docs.swanchain.io/core-concepts/token/computing-provider-collateral#slashing-mechanism>

### 5. Exit Procedure

#### 5.1 Stop Receiving New Tasks

```
computing-provider account changeTaskTypes --ownerAddress=<OWNER_ADDRESS> 0
```

#### 5.2 Data Backup

Backup the CP\_PATH directory (default: \~/.swan/computing)

#### 5.3 Withdrawal Process

**a) Withdraw from collateral account:**

```
computing-provider collateral withdraw --ecp --owner=<OWNER_ADDRESS> <AMOUNT>
```

**b) Withdraw from sequencer account:**

```
computing-provider sequencer withdraw --owner=<OWNER_ADDRESS> <AMOUNT>
```

**c) Withdraw from escrow account:**

* Initiate withdrawal request:

```
computing-provider collateral withdraw-request --owner=<OWNER_ADDRESS> --account=<CP_ACCOUNT> --ecp <AMOUNT>
```

* Confirm withdrawal after 7 days:

```
computing-provider collateral withdraw-confirm --owner=<OWNER_ADDRESS> --account=<CP_ACCOUNT> --ecp
```

***Note:** Escrow account balance may fluctuate due to periodic settlements. It's advisable to wait 24 hours after changing `taskTypes` before requesting the withdrawal. Confirmation can only be made 7 days after the initial request. Funds will be withdrawn to the CP's `ownerAddress` upon confirmation.*


# ECP FAQ

### Q: How can I verify whether the ECP environment is installed successfully?

```bash
curl http://<PUBLIC_IP>:<PORT>/api/v1/computing/cp
```

out:

```json

{
    "node_id": "04f4af161995c1cc0f8a4c1dd316a64b809c879e1cc7",
    "region": "North Carolina-US",
    "cluster_info": [
        {
            "machine_id": "4c4c4544-0046-3510-8058-b1c04f504433",
            "cpu_name": "AMD",
            "cpu": {
                "total": "192",
                "used": "16",
                "free": "176"
            },
            "memory": {
                "total": "2003 GiB",
                "used": "62 GiB",
                "free": "1822 GiB"
            },
            "gpu": {
                "driver_version": "535.104.05",
                "cuda_version": "12020",
                "attached_gpus": 1,
                "details": [
                    {
                        "product_name": "NVIDIA 3080",
                        "status": "available",
                        "fb_memory_usage": {
                            "total": "10240 MiB",
                            "used": "235 MiB",
                            "free": "10004 MiB"
                        },
                        "bar1_memory_usage": {
                            "total": "256 MiB",
                            "used": "2 MiB",
                            "free": "253 MiB"
                        }
                    }
                ]
            },
            "storage": {
                "total": "877 GiB",
                "used": "456 GiB",
                "free": "376 GiB"
            }
        }
    ],
    "multi_address": "/ip4/provider.cp.cn/tcp/9085",
    "node_name": "ecp-001"
}
```

### **Q: What are `ownerAddress`, `workerAddress`, and `beneficiaryAddress`?**

**A:** These are three different types of accounts used in the system for security and separation of concerns:

* `ownerAddress`: This is the owner account of the CP account. The owner has permission to change account information such as the multi-address, worker address, and beneficiary address. In most situations, the private key of the `ownerAddress` does not need to be present on the server for security reasons.
* `workerAddress`: This is the actual working address used for submitting proofs (`submitProof`). It needs to be funded with a certain amount of ETH to pay for gas fees when submitting proofs.
* `beneficiaryAddress`: This is the address where all earnings from the CP account will be sent. It is solely used for receiving funds. For security purposes, the private key of the `beneficiaryAddress` should not be stored on the server to maintain isolation.

By separating these accounts, the system ensures that only the necessary `workerAddress` private key is present on the server, while the more sensitive `ownerAddress` and `beneficiaryAddress` private keys are kept separate, enhancing the overall security of the system.

### Q: How to upgrade resource-exporter in ECP

**A**:

1. Delete container `resource-exporter` and `filswan/resource-exporter` local image

```
docker rm -f resource-exporter
docker rmi -f filswan/resource-exporter:v11.3.2
```

2. CP will automatically pull the image and run the resource-exporter container

### **Q: How to verify if ECP is running properly?**

* **Step 1: Check Collateral**:

```
computing-provider --repo info
```

[![image](https://private-user-images.githubusercontent.com/102578774/403743479-92e14ebd-cb46-4b3e-98f7-aa50ad544f0c.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MzczNjU4NDUsIm5iZiI6MTczNzM2NTU0NSwicGF0aCI6Ii8xMDI1Nzg3NzQvNDAzNzQzNDc5LTkyZTE0ZWJkLWNiNDYtNGIzZS05OGY3LWFhNTBhZDU0NGYwYy5wbmc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjUwMTIwJTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI1MDEyMFQwOTMyMjVaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT04ZmE5N2MyYzU0MTZiN2ViZmQ2ZDM4NTNiNmUxYmU2MWFlMWQyMDcyYzhlMDFmZTE5MTQ3MzEzZTU4M2VhMjA1JlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCJ9.3Fa97VNSN0WgnTFigMG0RbFtWEGOx_xmvisfuTnIkJM)](https://private-user-images.githubusercontent.com/102578774/403743479-92e14ebd-cb46-4b3e-98f7-aa50ad544f0c.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MzczNjU4NDUsIm5iZiI6MTczNzM2NTU0NSwicGF0aCI6Ii8xMDI1Nzg3NzQvNDAzNzQzNDc5LTkyZTE0ZWJkLWNiNDYtNGIzZS05OGY3LWFhNTBhZDU0NGYwYy5wbmc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjUwMTIwJTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI1MDEyMFQwOTMyMjVaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT04ZmE5N2MyYzU0MTZiN2ViZmQ2ZDM4NTNiNmUxYmU2MWFlMWQyMDcyYzhlMDFmZTE5MTQ3MzEzZTU4M2VhMjA1JlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCJ9.3Fa97VNSN0WgnTFigMG0RbFtWEGOx_xmvisfuTnIkJM)

Ensure that the sum of `Collateral` and `Escrow` under the `ECP Balance` is greater than the calculated collateral amount for proper staking.

* **Step 2:Check Versions**:
  * **CP Version**:

```
computing-provider -v
```

Verify the CP version by checking the commit number in the official [go-computing-provider](https://github.com/swanchain/go-computing-provider) repository to confirm if your version is up-to-date or the recommended stable version.

* **Resource-Exporter Version**:

```
docker inspect resource-exporter |grep filswan/resource-exporter
```

Verify the version of `resource-exporter` by checking the required version in the [official repository](https://github.com/swanchain/go-computing-provider/tree/releases?tab=readme-ov-file#Install-the-Hardware-resource-exporter).

* **Step 3: Check Resource Endpoint**:

```
curl http://<cp-ip>:<port>/api/v1/computing/cp
```

> **Note**: Replace `<cp-ip>` and `<port>` with the corresponding information from your `CP_REPO` configuration file, where `MultiAddress = "/ip4/<ip>/tcp/<port>"`.

* **Step 4: Self-check by submitting a job**:

```
curl --location --request POST 'http://<cp-ip>:<port>/api/v1/computing/cp/ubi' \
--header 'Content-Type: application/json' \
--data-raw '{
    "id": 26384,
    "name": "1000-0-7-26381",
    "type": 1,
    "resource_type": 0,
    "deadline": 2000000,
    "check_code": "check_code-demo",
    "input_param": "https://286cb2c989.acl.swanipfs.com/ipfs/QmTgoX6LkzZTsTjSjXvujzgJEHBLTEg3KMUadQGnyTrNFG",
    "verify_param": "https://286cb2c989.acl.swanipfs.com/ipfs/QmTgoX6LkzZTsTjSjXvujzgJEHBLTEg3KMUadQGnyTrNFG.verify",
    "resource":{"cpu":"10","memory":"5.00 GiB","storage":"10.00 GiB"}
    "signature":"Signing_cpAccountAddress_and_id_with_ownerAddress"
}'
```

* **Dashboard Status Check**:\
  In the [Provider Dashboard](https://provider.swanchain.io/), locate your CP using the `cpAccount`. Check that the status is `Online`, and ensure collateral is sufficient (as shown in the example). If so, your CP is running properly.

[![image](https://private-user-images.githubusercontent.com/102578774/403743659-087a96f3-a1c3-4607-b802-b343a51246e6.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MzczNjU4NDUsIm5iZiI6MTczNzM2NTU0NSwicGF0aCI6Ii8xMDI1Nzg3NzQvNDAzNzQzNjU5LTA4N2E5NmYzLWExYzMtNDYwNy1iODAyLWIzNDNhNTEyNDZlNi5wbmc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjUwMTIwJTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI1MDEyMFQwOTMyMjVaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT05ZjZkZWU2NjM4Mjc2NDg0NmU4OWFjYjM4N2Y3YzBmMzM1NGM2MGMxMThhNzA5NDhhNGVjNWNmZjVjZjMyN2NhJlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCJ9.Op8W10YxMo1lnZ-x1-NFKcQZ-dnSlFFEF1obDO4Z-k8)](https://private-user-images.githubusercontent.com/102578774/403743659-087a96f3-a1c3-4607-b802-b343a51246e6.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MzczNjU4NDUsIm5iZiI6MTczNzM2NTU0NSwicGF0aCI6Ii8xMDI1Nzg3NzQvNDAzNzQzNjU5LTA4N2E5NmYzLWExYzMtNDYwNy1iODAyLWIzNDNhNTEyNDZlNi5wbmc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjUwMTIwJTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI1MDEyMFQwOTMyMjVaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT05ZjZkZWU2NjM4Mjc2NDg0NmU4OWFjYjM4N2Y3YzBmMzM1NGM2MGMxMThhNzA5NDhhNGVjNWNmZjVjZjMyN2NhJlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCJ9.Op8W10YxMo1lnZ-x1-NFKcQZ-dnSlFFEF1obDO4Z-k8)

### **Q: How do I withdraw collateral from ECP?**

To withdraw collateral from ECP, use the following command:

```bash
computing-provider --repo <YOUR_CP_PATH> collateral withdraw --ecp --owner <YOUR_OWNER_WALLET_ADDRESS> --account <YOUR_CP_ACCOUNT> <AMOUNT>
```


# FAQ

### **Q: What is CU?**

CU, short for **Computing Unit**, is a key parameter in Swan Chain. It is a virtual unit used to measure the computing resource contributions of **Computing Providers (CPs)**. CU plays a crucial role in determining the collateral requirements for CPs.

The primary function of CU is to help calculate the collateral requirements for CPs. This ensures that CPs have sufficient staking to qualify for **UBI rewards** and **task allocations** on Swan Chain. Each CP’s CU value can be checked via the [**Provider Dashboard**](https://provider.swanchain.io/).

### **Q: How is the CP collateral calculated?**

The required **collateral** is calculated using the following formula:

$$
Collateral=CU×Base Collateral
$$

Currently, the **Base Collateral** is set at **3,533**.

**Example Calculation**

If a CP has a CU of **100**, the collateral requirement would be:

$$
100×3,533=353,300
$$

### **Q: How to Change Owner Address**

To change the `owner address` of your CP account, use the following command:

```bash
computing-provider --repo <YOUR_CP_REPO> account changeOwnerAddress --ownerAddress <YOUR_OLD_OWNER_ADDRESS> <YOUR_NEW_OWNER_ADDRESS>
```

**Note**: The `YOUR_NEW_OWNER_ADDRESS` does not need to be on the CP machine, but the owner’s private key is required for this operation.

### **Q: How to Change Worker Address**

To change the `worker address`, run:

```bash
computing-provider --repo <YOUR_CP_REPO> account changeWorkerAddress --ownerAddress <YOUR_OWNER_ADDRESS> <YOUR_NEW_WORKER_ADDRESS>
```

**Note**: The `YOUR_NEW_WORKER_ADDRESS` must be stored on the CP machine for two essential purposes:

* Verification of bidirectional signatures by the UBI engine when receiving UBI tasks. Tasks will not be accepted if verification fails.
* Proof submission to the chain. While this direct submission method provides faster confirmation, it requires the worker wallet to maintain an ETH balance for gas fees. Alternatively, using the sequencer method for submission can help reduce gas costs

### **Q: How to Change Beneficiary Address**

Update the `beneficiary address` with:

```bash
computing-provider --repo <YOUR_CP_REPO> account changeBeneficiaryAddress --ownerAddress <YOUR_OWNER_ADDRESS> <YOUR_NEW_BENEFICIARY_ADDRESS>
```

**Note**: The beneficiary address is for receiving rewards, and no private key is required on the CP machine.

* For CP maintenance personnel, this separation enhances security as they can manage the CP without direct access to the beneficiary wallet. Additionally, all CP rewards (including UBI rewards, application deployment rewards, etc.) are distributed to this address.

### **Q: How to Change Task Types**

CP currently supports five task types, each corresponding to different workloads and associated rewards. The more task types you set, the more diverse tasks your CP can accept.

There are two CP roles: FCP and ECP.

* **For FCP**: The default task types are 3 and 4. To accept more tasks, additional configurations are needed, such as enabling [NodePort](https://github.com/swanchain/go-computing-provider/tree/releases?tab=readme-ov-file#optional-install-node-port-dependency).
* **For ECP**: The default task types are 1 and 2. To accept more tasks, additional configurations are needed, such as enabling [Inference](https://github.com/swanchain/go-computing-provider/blob/releases/ubi/README.md#config-and-receive-inference-task).

You can set the task types using the following command:

```bash
computing-provider --repo <YOUR_CP_REPO> account changeTaskTypes --ownerAddress <YOUR_OWNER_ADDRESS> <task_type1>,<task_type2>,...
```

**Note**: Separate task types with commas. The full list of task types can be found in the Swan Chain documentation [here](https://docs.swanchain.io/bulders/computing-provider/fog-computing-provider-fcp/computing-provider-setup#step-3-change-the-tasktypes).

**Task Types**:

1. **Fil-C2**: Time-space proof tasks for Filecoin.
2. **Mining**: Mining-related tasks.
3. **AI**: AI and web service tasks.
4. **Inference**: Large model inference API tasks.
5. **NodePort**: VM-like services or multi-port services.

### **Q: How to Change Multi-Address**

MultiAddress defines how your CP is accessible on the network.

1. Update network configuration:

* For cloud providers: Configure in provider console
* For private datacenters: Configure on network egress devices

2. To update the public IP or internal port mapping, modify the `config.toml` file:

```toml
[API]
MultiAddress = "/ip4/<public_ip>/tcp/<port>"
```

3. Then run the update command:

```bash
computing-provider --repo <YOUR_CP_REPO> account changeMultiAddress --ownerAddress <YOUR_OLD_OWNER_ADDRESS> <YOUR_NEW_MULTI_ADDRESS>
```

4. Finally, verify the update:

```bash
# Step 1: Check local configuration
computing-provider --repo <YOUR_CP_REPO> info

# Step 2: Verify API accessibility
# For FCP:
curl -k https://<PUBLIC_IP>:<PORT>/api/v1/computing/cp
# For ECP:
curl http://<PUBLIC_IP>:<PORT>/api/v1/computing/cp
```

***

## ECP FAQ

### **Q: How to Initialize Repository**

The first step in setting up an ECP is initializing the repository. This creates a `config.toml` file containing essential configuration settings and defines data storage parameters.

```bash
computing-provider --repo <YOUR_CP_REPO> init --multi-address=/ip4/<YOUR_PUBLIC_IP>/tcp/<YOUR_PORT> --node-name=<YOUR_NODE_NAME>
```

### **Q: How to Create Account**

In the Swan network, each CP exists as a contract address. The CP account serves as your unique identifier for all operations, including task distribution, reward collection, and collateral management. It represents your primary token of identity within the Swan network.

```bash
computing-provider --repo <YOUR_CP_REPO> account create \
    --ownerAddress <YOUR_OWNER_WALLET_ADDRESS> \
    --workerAddress <YOUR_WORKER_WALLET_ADDRESS> \
    --beneficiaryAddress <YOUR_BENEFICIARY_WALLET_ADDRESS> \
    --task-types 1,2
```

### **Q: How to Add Collateral**

To participate in the Swan network and receive tasks, ECPs must stake SWAN tokens as collateral. This stake serves as a security mechanism - if service availability falls below acceptable levels, penalties may be applied against this collateral.

```bash
computing-provider --repo <YOUR_CP_REPO> collateral add --ecp --from <YOUR_WALLET_ADDRESS> <amount>
```

check details about collateral [here](https://docs.swanchain.io/core-concepts/token/computing-provider-collateral/collateral-requirement-and-earning-multiplier).

### **Q: How to Withdraw Collateral**

There are two methods for withdrawing collateral, each with different processing times:

1. **Direct Withdrawal from `Collateral Balance`**

   ```bash
   computing-provider --repo <YOUR_CP_REPO> collateral withdraw --ecp --owner <YOUR_WALLET_ADDRESS> --account <YOUR_CP_ACCOUNT> <amount>
   ```

   *Note: Funds are transferred immediately to the owner address.*
2. **Withdrawal from `Escrow Balance`** This process requires a waiting period and multiple steps:

   ```bash
   # Submit withdrawal request
   computing-provider --repo <YOUR_CP_REPO> collateral withdraw-request --ecp --owner <YOUR_OWNER_ADDRESS> <AMOUNT>

   # Confirm withdrawal (after 7-day waiting period)
   computing-provider --repo <YOUR_CP_REPO> collateral withdraw-confirm --ecp --owner <YOUR_OWNER_ADDRESS>

   # Check withdrawal status
   computing-provider --repo <YOUR_CP_REPO> collateral withdraw-view --ecp
   ```

   *Note: After submitting the withdrawal request, there is **a mandatory 7-day waiting period** before confirmation can be processed. Use the command `withdraw-view` to monitor the withdrawal status.*

### **Q: How to Manag Sequencer Balance**

1. **Adding Funds to Sequencer**

   ```bash
   computing-provider --repo <YOUR_CP_REPO> sequencer add --from <YOUR_WALLET_ADDRESS> <amount>
   ```
2. **Withdrawing from Sequencer**

   ```bash
   computing-provider --repo <YOUR_CP_REPO> sequencer withdraw --owner <YOUR_OWNER_ADDRESS> <amount>
   ```

***

## FCP FAQ

### **Q: How to Initialize Repository**

The first step in setting up an FCP is initializing the repository. This creates a `config.toml` file that contains essential configuration settings and defines data storage parameters.

```bash
computing-provider --repo <YOUR_CP_REPO> init --multi-address=/ip4/<YOUR_PUBLIC_IP>/tcp/<YOUR_PORT> --node-name=<YOUR_NODE_NAME>
```

### **Q: How to Create Account**

In the Swan network, each CP exists as a contract address, with the CP account serving as the unique identifier for all operations. This account handles task distribution, reward collection, and collateral management. It's your primary token of identity within the Swan network.

```bash
computing-provider --repo <YOUR_CP_REPO> account create \
    --ownerAddress <YOUR_OWNER_WALLET_ADDRESS> \
    --workerAddress <YOUR_WORKER_WALLET_ADDRESS> \
    --beneficiaryAddress <YOUR_BENEFICIARY_WALLET_ADDRESS> \
    --task-types 3
```

### **Q: How to Add Collateral**

To participate in the Swan network and receive tasks, FCPs must stake SWAN tokens as collateral. This stake serves as a security mechanism - if service availability falls below acceptable levels, penalties may be applied against this collateral.

```bash
computing-provider --repo <YOUR_CP_REPO> collateral add --fcp --from <YOUR_WALLET_ADDRESS> <amount>
```

check details about collateral [here](https://docs.swanchain.io/core-concepts/token/computing-provider-collateral/collateral-requirement-and-earning-multiplier).

### **Q: How to Withdraw Collateral**

There are two methods for withdrawing collateral, each with different processing times:

1. **Direct Withdrawal from `Collateral Balance`**

   ```bash
   computing-provider --repo <YOUR_CP_REPO> collateral withdraw --fcp --owner <YOUR_WALLET_ADDRESS> --account <YOUR_CP_ACCOUNT> <amount>
   ```

   *Note: Funds are transferred immediately to the owner address.*
2. **Withdrawal from `Escrow Balance`** This process requires a waiting period and multiple steps:

   ```bash
   # Submit withdrawal request
   computing-provider --repo <YOUR_CP_REPO> collateral withdraw-request --fcp --owner <YOUR_OWNER_ADDRESS> <AMOUNT>

   # Confirm withdrawal (after 7-day waiting period)
   computing-provider --repo <YOUR_CP_REPO> collateral withdraw-confirm --fcp --owner <YOUR_OWNER_ADDRESS> 

   # Check withdrawal status
   computing-provider --repo <YOUR_CP_REPO> collateral withdraw-view --fcp
   ```

   *Note: After submitting the withdrawal request, there is **a mandatory 7-day waiting period** before confirmation can be processed. Use the view command to monitor the withdrawal status.*

### **Q: What is the difference between ECP and FCP, and what are the minimum configuration requirements?**

**FCP:**

* For applications deployed with Kubernetes or large model inference API services. Users can directly offer services via a running URL. Kubernetes deployment and maintenance are technically more challenging but provide higher rewards.
* **Configuration Requirements**:
  * A public IP
  * A wildcard domain (e.g., `*.example.com`)
  * An SSL certificate, primarily for Kubernetes Ingress reverse proxy
  * At least 1 GPU
  * At least 8 vCPUs
  * At least 100 GB SSD storage
  * At least 64 GB RAM
  * At least 50 MB bandwidth

**ECP:**

* For applications deployed with Docker or Mining-type services. Easier to deploy with scripts available for quick setup.
* **Configuration Requirements**:
  * A public IP
  * At least 1 GPU
  * At least 4 vCPUs
  * At least 300 GB HDD storage
  * At least 32 GB RAM
  * At least 20 MB bandwidth

***

### **Q: What do the `Owner`, `Worker`, and `Beneficiary` addresses represent, and what are the differences?**

* **ownerAddress**: The owner of the `cpAccount`. Only the owner has permission to change account details, such as `multi-address`, `worker address`, `beneficiary address`, etc. The owner's private key should not appear on the server under normal circumstances.
* **workerAddress**: The working address, used for submitting messages (e.g., `submitProof`). A certain amount of sETH is required for gas fees.
* **beneficiaryAddress**: The beneficiary address where earnings from the `cpAccount` are paid. This address is only used to receive funds, so its private key should not be stored on the server for security reasons. The purpose of these three address types is to ensure the security of the `cpAccount`. Typically, the server should only need to maintain the private key for the worker address, not the owner or beneficiary addresses.

***

### **Q: What should I do if my server's public IP changes?**

Follow the instructions in the **CP Common Account Operations** section to change the `multiAddress`.

### **Q: How can I check how much collateral my CP needs, and is my collateral sufficient?**

* **Collateral Calculation**:
  * First, visit the [Provider Dashboard](https://provider.swanchain.io/overview) to query your `cpAccount` and find the CU value.
  * The collateral formula is: `cu * base_collateral`. Currently, `base_collateral = 3533`. It’s recommended to add 10% extra for safety.
* You can check your collateral status via the CP Dashboard:

**Sufficient collateral** (Example):

![image](https://github.com/user-attachments/assets/21b014b6-73fa-4bdf-844a-938fa18a796a)

**Insufficient collateral** (Example):

![image](https://github.com/user-attachments/assets/bba214de-355e-48b2-b165-1ec0bfddffd7)

### **Q: What is the current slashing mechanism for CP?**

When you deploy an application to CP, the CP runs the service, and the SWAN monitoring system will penalize the CP if the service's availability is deemed poor. For more details, refer to the [Slashing Mechanism](https://docs.swanchain.io/core-concepts/token/computing-provider-collateral#slashing-mechanism).

### **Q: How to verify if FCP is running properly?**

* **Step 1: Check Collateral**:

```
computing-provider --repo info
```

![image](https://github.com/user-attachments/assets/61fb8bc2-71cd-4dc1-bcf0-fb9fd073d4b0)

Ensure that the sum of `Collateral` and `Escrow` under the `FCP Balance` is greater than the calculated collateral amount for proper staking.

* **Step 2: Check Versions**:
  * **CP Version**:

```
computing-provider -v
```

Verify the CP version by checking the commit number in the official [go-computing-provider](https://github.com/swanchain/go-computing-provider) repository to confirm if your version is up-to-date or the recommended stable version.

* **Resource-Exporter Version**:

```
kubectl get daemonset resource-exporter-ds -n kube-system -o yaml | grep image:
```

Verify the version of `resource-exporter` by checking the required version in the [official repository](https://github.com/swanchain/go-computing-provider/tree/releases?tab=readme-ov-file#Install-the-Hardware-resource-exporter).

* **Step 3: Check Resource Endpoint**:

```
curl -k https://<cp-ip>:<port>/api/v1/computing/cp
```

> **Note**: Replace `<cp-ip>` and `<port>` with the corresponding information from your `CP_REPO` configuration file, where `MultiAddress = "/ip4/<ip>/tcp/<port>"`.

* **Step 4: Self-check by submitting a job**:

```
curl -k --location --request POST 'https://<cp-ip>:<port>/api/v1/computing/lagrange/jobs' \
--header 'Content-Type: application/json' \
--data-raw '{
"uuid": "5641877b-dc94-469a-bb3b-ecab6d10f7dd",
"name": "Job-5641877b-dc94-469a-bb3b-ecab6d10f7dd",
"status": "Submitted",
"duration": 900,
"job_source_uri": "https://api.lagrangedao.org/spaces/51d6abbb-f928-43e4-91fd-79e93e2b276f",
"storage_source": "lagrange",
"task_uuid": "92cd5595-9789-4af3-9100-7c7e4aacb456"
}'
```

* **Step 5: Dashboard Status Check**: In the [Provider Dashboard](https://provider.swanchain.io/), locate your CP using the `cpAccount`. Check that the status is `Online`, and ensure collateral is sufficient (as shown in the example). If so, your CP is running properly. ![image](https://github.com/user-attachments/assets/47049468-d9bb-4aac-8870-6dafa84a3866)

### **Q: How to verify if ECP is running properly?**

* **Step 1: Check Collateral**:

```
computing-provider --repo info
```

![image](https://github.com/user-attachments/assets/92e14ebd-cb46-4b3e-98f7-aa50ad544f0c)

Ensure that the sum of `Collateral` and `Escrow` under the `ECP Balance` is greater than the calculated collateral amount for proper staking.

* **Step 2:Check Versions**:
  * **CP Version**:

```
computing-provider -v
```

Verify the CP version by checking the commit number in the official [go-computing-provider](https://github.com/swanchain/go-computing-provider) repository to confirm if your version is up-to-date or the recommended stable version.

* **Resource-Exporter Version**:

```
kubectl get daemonset resource-exporter-ds -n kube-system -o yaml | grep image:
```

Verify the version of `resource-exporter` by checking the required version in the [official repository](https://github.com/swanchain/go-computing-provider/tree/releases?tab=readme-ov-file#Install-the-Hardware-resource-exporter).

* **Step 3: Check Resource Endpoint**:

```
curl http://<cp-ip>:<port>/api/v1/computing/cp
```

> **Note**: Replace `<cp-ip>` and `<port>` with the corresponding information from your `CP_REPO` configuration file, where `MultiAddress = "/ip4/<ip>/tcp/<port>"`.

* **Step 4: Self-check by submitting a job**:

```
curl --location --request POST 'http://<cp-ip>:<port>/api/v1/computing/cp/ubi' \
--header 'Content-Type: application/json' \
--data-raw '{
    "id": 26384,
    "name": "1000-0-7-26381",
    "type": 1,
    "resource_type": 0,
    "deadline": 2000000,
    "check_code": "check_code-demo",
    "input_param": "https://286cb2c989.acl.swanipfs.com/ipfs/QmTgoX6LkzZTsTjSjXvujzgJEHBLTEg3KMUadQGnyTrNFG",
    "verify_param": "https://286cb2c989.acl.swanipfs.com/ipfs/QmTgoX6LkzZTsTjSjXvujzgJEHBLTEg3KMUadQGnyTrNFG.verify",
    "resource":{"cpu":"10","memory":"5.00 GiB","storage":"10.00 GiB"}
    "signature":"Signing_cpAccountAddress_and_id_with_ownerAddress"
}'
```

* **Dashboard Status Check**: In the [Provider Dashboard](https://provider.swanchain.io/), locate your CP using the `cpAccount`. Check that the status is `Online`, and ensure collateral is sufficient (as shown in the example). If so, your CP is running properly. ![image](https://github.com/user-attachments/assets/087a96f3-a1c3-4607-b802-b343a51246e6)


# Storage Provider

### **Introduction**

**Swan Storage** **Provider** enables hardware owners to make profits on their spare computing resources by releasing them to tenants.

The service Swan provides helps storage providers connect to the Web3 service market, making the Web3 service offering ultimately easier.

Swan IPFS Storage is a web3 version of S3 storage gateway built with IPFS and Filecoin technology for accelerating the mass adoption of decentralized storage by multiple blockchain networks.

### High-Level Design

<figure><img src="/files/ZhLMWMIiX6AXY2uNuNvG" alt=""><figcaption><p>Multi-chain Storage Design</p></figcaption></figure>

To check the current status of Swan Storage Provider network, please check it here <https://console.filswan.com/dashboard#/dashboard>


# Storage Auction System

## Introduction

Filecoin users need to find suitable storage providers in the first instance. They need to actively seek providers, bargain offline, send data files, lock fees, and proceed with payment once file storage is completed as requested.

**Over the course, there remain several key questions:**

1\. Users can't fully understand the specific service quality of storage providers because of limited information available.

2\. The lack of in-depth matching functionality, and diverse data storage needs are making the dealer market opaque.

3\. There are not enough choices available for beginners. It is time-consuming as well as costly to find and compare storage providers that will work best for them.

In this context, having an open and transparent matching system is necessary. Swan's auction system is optimal for simplifying data storage through matching providers and users in need automatically, thereby reducing the learning cost for users.

#### Manual bid vs Auto-bid

**Manual Bid**

There are two types of bids in the Swan system. One is manual bid, and the other is auto-bid. Manual bidding is a system designed for users who are actively involved in the bidding. When bidding manually, users select providers in accordance with their bandwidth, storage capacity, geographic location, and daily processing ability. Similarly, users compare and filter attributes of assorted products on shopping platforms.

Users cannot avoid other users’ interactions because they need to know who they expect to take the deal. Afterward, users can send the deal. It consists of two steps: the first step is to open the deal bid, and the second step is to assign the bid. Users assign transactions to different storage providers to solicit public bids. Providers then store the data as requested after winning the bid. Since this step is open to the public, we call it an “open public deal”, which means that anybody in the system can compete for it.

After several satisfying bids, the user may be willing to build long-term private cooperation with the storage provider. So, they may skip the bidding process and send deals directly to each other in the future. We call this case a “private deal”.

One advantage of the manual bid system is that tipping the tasks makes it more flexible while bidding.

**Autobid**

![Autobid System](/files/-MlN41ty9WBxCNCl3HGS)

The auto bidding system is a reputation-based system. When users sign up as a storage provider, they will be rated based on the data they processed. The more data they process, the higher score they will achieve.

In the auto-bidding system, users are free from hassles like choosing storage providers. The system selects providers automatically while ensuring fairness. When a user sends out a deal to the auto bidding pool, the storage provider will be assigned the deal based on their reputation score. The higher score you have, the more likely they will win a bid.

The Swan bidding system is a matching platform that enables convenient transactions between users and providers. In the era of decentralized storage, Swan ensures a quick pair of users and storage providers for the sake of time-efficient storage and backup services regardless of data scales.

The Swan bidding system increases the earnings of real data storage. It additionally reduces the leverage difficulty to attract more novice users.

The market matcher program distributes the order following a lambda distribution, which means that even if the storage provider scores low, he is still able to get some deals.

**Task**

It is of great importance to conceptualize "task" in the Swan system. A task consists of several deals. Currently, Filecoin only accepts deals of specified sizes, eg., a maximum of 32 gigabytes or 64 gigabytes. If you want to store a data more than one terabyte or 10 terabytes, you need to split it to different deals manually to send them. This could make deal management daunting.

In order to batch send deals, we have created a conception called “tasks”. A task is a combination of deals. Users can name it, label it, and define the curated dataset type for future usage.

**Swan Storage Provider**

The Swan Provider runs on the same node as the lotus miner nodes run, and assists lotus miners to process deals. In order to better share the information with the Flilswan client, [authentication](https://github.com/filswan/gitbook/blob/main/run-swan-provider/broken-reference/README.md) from the Swan platform is required.

Swan provider also keeps your status up to date. With the Swan platform, your client can get your shared information about the file sealing life cycle.

We also provide the Restful API interface for developers to integrate the Swan Provider into their own system.

Read more: <https://github.com/filswan/go-swan-provider>


# Developer Tools

Welcome to the Swan developer tools! If you're already familiar with building on Swan Mainnet and need the tools to get started, you're in the right place. Below, you'll find an overview of the key components in the Swan ecosystem.

### Lagrange: Decentralized NLP Platform

Lagrange(lagrange.computer) is a cutting-edge Web3 platform for natural language processing (NLP) development and deployment. Built on the Swan Chain computing network, it offers:

* Cost-effective alternative to centralized cloud services
* Enhanced security and interoperability
* Decentralized infrastructure for NLP tasks

Learn more about Lagrange in its [documentation](https://docs.lagrangedao.org/).

### Swan IPFS Storage

Developed by the Swan Network, Swan IPFS Storage is a revolutionary storage service compatible with various blockchain networks. Key features include:

* Smart contract integration for improved security
* Decentralized architecture
* Cross-chain compatibility

Explore Swan IPFS Storage capabilities [here](https://swanipfs.com/).

### Swan SDK

The Swan SDK is your go-to toolkit for interacting with the Swan Chain Network Resource. It simplifies:

* Creating and managing computational tasks
* Retrieving hardware information
* Processing payments
* Monitoring task statuses

Dive into the Swan SDK [here](/bulders/tools/swan-sdk).

### Nebula Block Cloud

Nebula Block is a forward-thinking Montreal-based startup, specializing in advanced cloud computing and blockchain infrastructure solutions. Nebula Block offers:

* Secure and scalable computing environments
* Cost-effective solutions for academic and commercial institutions
* Advanced blockchain integration

Visit Nebula Block [here](https://nebulablock.com/).

### Ecosystem Projects

The Swan ecosystem is growing, with projects like Nebula Block leading the way in cloud computing and blockchain infrastructure solutions.

Discover more ecosystem projects [here](#ecosystem-projects).

### Getting Started

Ready to build on Swan Mainnet? Here are some next steps:

1. Set up your development environment using the [Swan SDK](/bulders/tools/swan-sdk)
2. Explore [Lagrange](/bulders/tools/lagrange-dao) for NLP-focused applications
3. Leverage [SWAN IPFS Storage](/bulders/tools/multi-chain-storage) for decentralized storage solutions
4. Connect with the community and other builders in the [ecosystem](/bulders/tools/ecosystem-projects)

Happy building on Swan Mainnet!


# Swan SDK

Get started with Swan SDK

## Overview

The Swan SDK is a toolkit designed to simplify interactions with the Swan Chain Network Resource. It provides a streamlined interface for creating and managing computational tasks, retrieving hardware information, processing payments, and monitoring task statuses.

### Chain Node Web Application

In this example, you will deploy a simple web application on the distributed computing provider network using Swan SDK. At the end of this example, you will have a Chain Node Frontend application running on the Swan network.

#### Create Task and Deploy Application Instances

{% tabs %}
{% tab title="Python" %}

```python
import swan
import json

api_key = '<your_api_key>'
wallet_address = '<WALLET_ADDRESS>'
private_key = '<PRIVATE_KEY>'

swan_orchestrator = swan.resource(
    api_key=api_key, 
    service_name='Orchestrator'
)

result = swan_orchestrator.create_task(
    repo_uri='https://github.com/swanchain/awesome-swanchain/tree/main/ChainNode',
    wallet_address=wallet_address,
    private_key=private_key,
    auto_pay=True,
    instance_type='C1ae.medium',
)

task_uuid = result['task_uuid']
instance_type = result['instance_type']
task_info = swan_orchestrator.get_deployment_info(task_uuid=task_uuid)
print(json.dumps(task_info.to_dict(), indent=2))

### get real url (if no url, please wait for a while, then check again)
result_url = swan_orchestrator.get_real_url(task_uuid)
print(result_url)
```

{% endtab %}

{% tab title="Go" %}

```go
import "github.com/swanchain/go-swan-sdk"

task, err := client.CreateTask(&CreateTaskReq{
    PrivateKey:   "<PRIVATE_KEY>",
    RepoUri:      "https://github.com/swanchain/awesome-swanchain/tree/main/ChainNode",
    Duration:     2 * time.Hour,
    InstanceType: "C1ae.small", 
})

taskUUID := task.Task.UUID

// Get task deployment info
resp, err := client.TaskInfo(taskUUID)

//Get application instances URL
appUrls, err := client.GetRealUrl(taskUUID)
if err != nil {
	log.Fatalln(err)
}
log.Printf("%v", appUrls)
```

{% endtab %}
{% endtabs %}

Sample URL output:

```
['https://0sz7wqp79q.dev2.crosschain.computer', 'https://grxfl2u0cu.cp.filezoo.com.cn', 'https://0ux851gqmz.pvm.nebulablock.com']
```

#### View Running Application

Screenshot:

<figure><img src="/files/6MUzZuahssrRxvdouRw3" alt="Chain Node App"><figcaption></figcaption></figure>

## Documentation and Support

More resources about swan SDK can be found here:

* [Swan Console platform](https://console.swanchain.io)
* [Deploying with Swan SDK](https://docs.swanchain.io/start-here/readme/deploying-with-swan-sdk)
* [Python-swan-sdk](https://github.com/swanchain/python-swan-sdk)
* [Go-swan-sdk](https://github.com/swanchain/go-swan-sdk)
* [Python-swan-sdk-samples](https://github.com/swanchain/python-sdk-docs-samples)
* [Go-swan-sdk-samples](https://github.com/swanchain/go-swan-sdk-samples)

***


# Python Swan SDK

For more detailed samples, consult [SDK Samples](https://github.com/swanchain/python-sdk-docs-samples).

For detailed description of functions, please check [Key Functions](https://github.com/swanchain/python-swan-sdk/blob/main/docs/key_functions.md).

## Orchestrator

Orchestrator allows you to create task to run application instances to the powerful distributed computing providers network.

### Fetch available instance resources

Before using Orchestrator to deploy task, it is necessary to know which instance resources are available. Through `get_instance_resources` you can get a list of available instance resources including their `region` information. From the output list, you can choose an `instance_type` by checking the description for the hardware configuration requirements.

```python
import json
import swan

swan_orchestrator = swan.resource(api_key='<SWAN_API_KEY>', service_name='Orchestrator')

available_resources = swan_orchestrator.get_instance_resources()
print(available_resources)
```

Sample output:

```
[InstanceResource({
  "hardware_id": 0,
  "instance_type": "C1ae.small",
  "description": "CPU only \u00b7 2 vCPU \u00b7 2 GiB",
  "type": "CPU",
  "region": [
    "Quebec-CA",
    "North Carolina-US"
  ],
  "price": "1.2",
  "status": "available",
  "snapshot_id": 1731441600,
  "expiry_time": 1731442218
}), ...]
```

### Create and deploy a task

Deploy a simple application with Swan SDK:

```python
import json
import swan

swan_orchestrator = swan.resource(api_key='<SWAN_API_KEY>', service_name='Orchestrator')

result = swan_orchestrator.create_task(
    repo_uri='https://github.com/swanchain/awesome-swanchain/tree/main/hello_world',
    wallet_address='<WALLET_ADDRESS>',
    private_key='<PRIVATE_KEY>',
    instance_type='C1ae.small',
    auto_pay=True
)
task_uuid = result['task_uuid']
# Get task deployment info
task_deployment_info = swan_orchestrator.get_deployment_info(task_uuid=task_uuid)
print(task_deployment_info)
```

It may take several minutes to get the deployment result:

```python
# Get application instances URL
app_urls = swan_orchestrator.get_real_url(task_uuid)
print(app_urls)
```

A sample output:

```
['https://krfswstf2g.anlu.loveismoney.fun', 'https://l2s5o476wf.cp162.bmysec.xyz', 'https://e2uw19k9uq.cp5.node.study']
```

It shows that this task has three applications. Open the URL in the web browser you will view the application's information if it is running correctly.

### Check information of an existing task

With Orchestrator, you can check information for an existing task to follow up or view task deployment.

```python
import json
import swan

swan_orchestrator = swan.resource(api_key='<SWAN_API_KEY>', service_name='Orchestrator')

# Get an existing task deployment info
task_deployment_info = swan_orchestrator.get_deployment_info(<task_uuid>)
print(task_deployment_info)
```

### Access application instances of an existing task

With Orchestrator, you can easily get the deployed application instances for an existing task.

```python
import json
import swan

swan_orchestrator = swan.resource(api_key='<SWAN_API_KEY>', service_name='Orchestrator')

# Get application instances URL
app_urls = swan_orchestrator.get_real_url(<task_uuid>)
print(app_urls)
```

### Renew an existing task

If you have already submitted payment for the renewal of a task, you can use the `tx_hash` with `renew_task` to extend the task.

```python
import json
import swan

swan_orchestrator = swan.resource(api_key='<SWAN_API_KEY>', service_name='Orchestrator')

renew_result = swan_orchestrator.renew_task(
    task_uuid=<task_uuid>, 
    duration=3600, # Optional: default 3600 seconds (1 hour)
    private_key=<PRIVATE_KEY>
)
print(renew_result)
```

### Terminate an existing task

You can also early terminate an existing task and its application instances. By terminating task, you will stop all the related running application instances and thus you will get refund of the remaining task duration.

```python
import json
import swan

swan_orchestrator = swan.resource(api_key='<SWAN_API_KEY>', service_name='Orchestrator')

# Terminate an existing task (and its application instances)
swan_orchestrator.terminate_task(<task_uuid>)
```


# Special Case: Create ssh login instance

## SSH repo

1. fork GitHub repo: <https://github.com/sonic-chain/sdk-demo>
2. On your local computer, generate ssh key with `ssh-keygen -t rsa -b 4096`
3. Copy the public key as the value of sshkey in deploy.yaml

```yaml
version: "2.0"
type: node-port
services:
  vm:
    image: filswan/ubuntu-ssh-user:22.04
    env:
      - sshkey=<YOUR-LOCAL-SSH-KEY>
      - username=swantouser
    expose:
      - port: 22
      - port: 30002
      - port: 30003
      - port: 30004
      - port: 30005
      - port: 30006
      - port: 30007
deployment:
  vm:
    lagrange:
      count: 1
```

4. Push modification to your GitHub repo

## Deploy SSH Application with Swan SDK

1. Choose a computing provider who can support SSH application

```py
import json
import swan

swan_orchestrator = swan.resource(api_key='<SWAN_API_KEY>', service_name='Orchestrator')

available_instances = swan_orchestrator.get_instance_resources()
print(available_instances)
```

In the output of available resources list, choose a `cp_account_address` in `ssh_ready` list of the instance type you want (such as `C1ae.small`):

```
[InstanceResource({
  "hardware_id": 0,
  "instance_type": "C1ae.small",
  "description": "CPU only \u00b7 2 vCPU \u00b7 2 GiB",
  "type": "CPU",
  "region": [
    "Virginia-US",
    "Quebec-CA",
    "Jakarta-ID",
    "Kowloon City-HK",
    "North Rhine-Westphalia-DE",
    "Seoul-KR",
    "Eastern-HK",
    "Ivano-Frankivsk Oblast-UA",
    "Kowloon-HK",
    "Saxony-DE",
    "Jiangsu-CN",
    "Tokyo-JP",
    "Kuala Lumpur-MY",
    "North West-SG",
    "Central and Western District-HK",
    "Central and Western-HK",
    "National Capital Territory of Delhi-IN",
    "Florida-US"
  ],
  "price": "0.48",
  "status": "available",
  "snapshot_id": 1732047600,
  "expiry_time": 1732048445,
  "ssh_ready": [
    {
      "cp_account_address": "0xEf675CA43Ce25b2594079caCE98C7362733E1F5B",
      "region": "Quebec-CA"
    },
    {
      "cp_account_address": "0x4cbe96669516961Ebaf7225Fe07a34d56c4B2B12",
      "region": "North West-SG"
    },
    {
      "cp_account_address": "0x34378963383667F87b5C185A7b716c2C353EF9d2",
      "region": "Florida-US"
    }
  ]
```

2. Deploy SSH application with the selected CP

Deploy the SSH application to use that `cp_account_address`, put it in the `preferred_cp_list`.

```py
result = swan_orchestrator.create_task(
    repo_uri='<YOUR-GITHUB-REPO-URI-FOR-SSH>',
    wallet_address='<WALLET_ADDRESS>',
    private_key='<PRIVATE_KEY>',
    instance_type='<INSTANCE_TYPE>', #such as 'C1ae.small',
    preferred_cp_list=['SSH-READY-CP-ACCOUNT-ADDRESS']
)
task_uuid = result['task_uuid']
# Get task deployment info
task_deployment_info = swan_orchestrator.get_deployment_info(task_uuid=task_uuid)
print(json.dumps(task_deployment_info.to_dict(), indent=2))
```

Please wait for awhile to get the SSH command by

```py
app_urls = swan_orchestrator.get_real_url(task_uuid)
```

If everything goes well, you will get SSH command result like this:

```
['ssh root@38.80.81.17 -p30001']
```

Then you can run this command in your shell. You will see something like the following output:

```
 _
| |
| |     __ _  __ _ _ __ __ _ _ __   __ _  ___
| |    / _` |/ _` | '__/ _` | '_ \ / _` |/ _ \
| |___| (_| | (_| | | | (_| | | | | (_| |  __/
|______\__,_|\__, |_|  \__,_|_| |_|\__, |\___|
              __/ |                 __/ |
             |___/                 |___/
Welcome to Ubuntu 22.04.4 LTS (GNU/Linux 5.4.0-174-generic x86_64)

 * Documentation:  https://docs.lagrangedao.org
 * Support:        https://discord.com/invite/8vaB6rKSAu

This system has been minimized by removing packages and content that are
not required on a system that users do not log into.

To restore this content, you can run the 'unminimize' command.

The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

root@sdk-demo-e5tv:~#
```


# SWAN Orchestrator SDK - Function and Parameter Reference

## 1. Get Instance Resources

### Method: `swan_orchestrator.get_instance_resources(**kwargs)`

Retrieves a list of instance resources (available or all). Provides a comprehensive reference for instance configurations. [Function Documentation](https://github.com/swanchain/python-sdk-docs-samples/blob/main/compute/get_instance_resources.py)

**Request Syntax:**

```python
response = swan_orchestrator.get_instance_resources()
```

**Parameters:**

| Parameter   | Type    | Required | Description                                                         | Default |
| ----------- | ------- | -------- | ------------------------------------------------------------------- | ------- |
| `available` | Boolean | No       | Indicates whether to show only available resources or all resources | `True`  |

**Usage Notes:**

* When `available` is `True`, returns only available resources
* When `available` is `False`, returns all resource configurations

## 2. Create Task

### Method: `swan_orchestrator.create_task(**kwargs)`

Creates a task on SWAN orchestrator with flexible deployment options. [Function Documentation](https://github.com/swanchain/python-sdk-docs-samples/blob/main/compute/create_task.py)

**Parameters:**

| Parameter           | Type    | Required | Description                                                              | Default        |
| ------------------- | ------- | -------- | ------------------------------------------------------------------------ | -------------- |
| `wallet_address`    | String  | Yes      | Wallet address associated with the newly created task                    | -              |
| `instance_type`     | String  | No       | Instance type of hardware configuration                                  | `'C1ae.small'` |
| `region`            | String  | No       | Region of hardware                                                       | `global`       |
| `duration`          | Integer | No       | Service runtime duration in seconds                                      | 3600 (1 hour)  |
| `app_repo_image`    | String  | No\*     | Demo space name. Automatically sets `auto_pay` to `True` if used         | -              |
| `job_source_uri`    | String  | No\*     | Job source URI for deployment. Overrides `app_repo_image` and `repo_uri` | -              |
| `repo_uri`          | String  | No\*     | Repository URI to be deployed                                            | -              |
| `repo_branch`       | String  | No       | Repository branch to be deployed                                         | -              |
| `auto_pay`          | Boolean | No       | Automatically pays to deploy task                                        | `True`         |
| `private_key`       | String  | No\*\*   | Wallet's private key                                                     | -              |
| `preferred_cp_list` | List    | No       | List of preferred CP account addresses                                   | -              |
| `ip_whitelist`      | List    | No       | List of IP addresses allowed to access the application                   | -              |

**Deployment Priority:**

1. `job_source_uri` (Highest priority)
2. `app_repo_image`
3. `repo_uri`

**Notes:**

* At least one of `job_source_uri`, `app_repo_image`, or `repo_uri` must be provided
* If `auto_pay` is `True`, task deployment is automatic
* If `auto_pay` is `False`, manual payment confirmation is required

## 3. Get Deployment Information

### Method: `swan_orchestrator.get_deployment_info(**kwargs)`

Retrieves deployment information for a specific task. [Function Documentation](https://github.com/swanchain/python-sdk-docs-samples/blob/main/compute/get_task_deployment_info.py)

**Request Syntax:**

```python
response = swan_orchestrator.get_deployment_info(task_uuid="string")
```

**Parameters:**

| Parameter   | Type   | Required | Description                   | Default |
| ----------- | ------ | -------- | ----------------------------- | ------- |
| `task_uuid` | String | Yes      | Unique identifier of the task | -       |

## 4. Get Real URL

### Method: `swan_orchestrator.get_real_url(**kwargs)`

Retrieves the real URL for a specific task.

**Request Syntax:**

```python
response = swan_orchestrator.get_real_url(task_uuid="string")
```

**Parameters:**

| Parameter   | Type   | Required | Description                   | Default |
| ----------- | ------ | -------- | ----------------------------- | ------- |
| `task_uuid` | String | Yes      | Unique identifier of the task | -       |

## 5. Renew Task

### Method: `swan_orchestrator.renew_task(**kwargs)`

Extends the duration of an existing task. [Function Documentation](https://github.com/swanchain/python-sdk-docs-samples/blob/main/compute/renew_task.py)

**Parameters:**

| Parameter     | Type    | Required | Description                                             | Default |
| ------------- | ------- | -------- | ------------------------------------------------------- | ------- |
| `task_uuid`   | String  | Yes      | Unique identifier of the task to extend                 | -       |
| `duration`    | Integer | No       | Extension duration in seconds                           | 0       |
| `tx_hash`     | String  | No\*     | Transaction hash of payment                             | -       |
| `auto_pay`    | Boolean | No       | Automatically pays to extend task                       | `True`  |
| `private_key` | String  | No\*\*   | Wallet's private key (required if `auto_pay` is `True`) | -       |

**Important Notes:**

* If `auto_pay` is `False`, `tx_hash` must be provided
* If `auto_pay` is `True`, `private_key` must be provided

## 6. Terminate Task

### Method: `swan_orchestrator.terminate_task(**kwargs)`

Terminates a task and provides a refund based on remaining time. [Function Documentation](https://github.com/swanchain/python-sdk-docs-samples/blob/main/compute/terminate_task.py)

**Request Syntax:**

```python
response = swan_orchestrator.terminate_task(task_uuid="string")
```

**Parameters:**

| Parameter   | Type   | Required | Description                   | Default |
| ----------- | ------ | -------- | ----------------------------- | ------- |
| `task_uuid` | String | Yes      | Unique identifier of the task | -       |


# Go Swan SDK

This guide details the steps needed to install or update the SWAN SDK for Go. The SDK is a comprehensive toolkit designed to facilitate seamless interactions with the SwanChain API.

## Getting started

**Go Version**

`go-swan-sdk` requires [Go](https://go.dev/) version [1.21](https://go.dev/doc/devel/release#go1.21.0) or above.

**Swan API Key**

To use `swan-sdk`, an Swan API key is required. Steps to get an API Key:

* Go to [Swan Console](https://console.swanchain.io/), switch network to [Swan Chain Mainnet](https://docs.swanchain.io/network-reference/readme).
* Login with your wallet.
* Click `API Keys` -> `Generate API Key`

**Using go-swan-sdk**

With [Go's module support](https://go.dev/wiki/Modules#how-to-use-modules), `go [build|run|test]` automatically fetches the necessary dependencies when you add `import`in your project:

```go
import "github.com/swanchain/go-swan-sdk"
```

To update the SDK use `go get -u` to retrieve the latest version of the SDK:

```sh
go get -u github.com/swanchain/go-swan-sdk
```

## Quickstart

To use `go-swan-sdk`, you must first import it, and you can create and deploy instance applications quickly.

```go
package main

import (
	"github.com/swanchain/go-swan-sdk"
	"log"
	"time"
)

func main() {
	client, err := swan.NewAPIClient("<YOUR_API_KEY>")
	if err != nil {
		log.Fatalf("failed to init swan client, error: %v \n", err)
	}
	task, err := client.CreateTask(&swan.CreateTaskReq{
		PrivateKey:   "<PRIVATE_KEY>",
		RepoUri:      "https://github.com/swanchain/awesome-swanchain/tree/main/hello_world",
		Duration:     2 * time.Hour,
		InstanceType: "C1ae.small",
	})
	taskUUID := task.Task.UUID

	// Get task deployment info
	resp, err := client.TaskInfo(taskUUID)
	if err != nil {
		log.Fatalln(err)
	}
	log.Printf("task info: %+v \n", resp)

	//Get application instances URL
	appUrls, err := client.GetRealUrl(taskUUID)
	if err != nil {
		log.Fatalln(err)
	}
	log.Printf("app urls: %v \n", appUrls)
}
```


# A Sample Tutorial

**New client**

```go
client, err := swan.NewAPIClient("<SWAN_API_KEY>")
```

**Fetch all instance resources**

Through `InstanceResources` you can get a list of available instance resources including their region information. You can select one you want to use.

```go
instances, err := swan.InstanceResources(true)
```

> **Note:** All Instance type list can be found [here](https://github.com/swanchain/go-swan-sdk/blob/main/doc/instance.md).

**Create and deploy a task**

Deploy a application, if you have set `PrivateKey`, this task will be payed automaiclly, and deploy to computing providers on Swan Chain Network:

```go
task, err := client.CreateTask(&CreateTaskReq{
    PrivateKey:   "<YOUR_WALLET_ADDRESS_PRIVATE_KEY>",
    RepoUri:      "<YOUR_PROJECT_GITHUB_URL>",
    Duration:      2 * time.Hour,
    InstanceType: "C1ae.small", 
})

taskUUID := task.Task.UUID
log.Printf("taskUUID: %v", taskUUID)

```

**Access application instances of an existing task**

You can easily get the deployed application instances for an existing task.

```go
// Get application instances URL
appUrls, err := client.GetRealUrl("<TASK_UUID>")
if err != nil {
	log.Fatalln(err)
}
log.Printf("app urls: %v", appUrls)
```

A sample output:

```
['https://krfswstf2g.anlu.loveismoney.fun', 'https://l2s5o476wf.cp162.bmysec.xyz', 'https://e2uw19k9uq.cp5.node.study']
```

It shows that this task has three applications. Visit the URL in the web browser you will view the application's information if it is running correctly.

**Renew duration of an existing task**

`RenewTask` extends the duration of the task before completed

```go
resp, err := client.RenewTask("<TASK_UUID>", <Duration>,"<PRIVATE_KEY>")
```

**Terminate an existing task**

You can early terminate an existing task and its application instances. By terminating task, you will stop all the related running application instances and thus you will get refund of the remaining task duration.

```go
resp, err := client.TerminateTask("<TASK_UUID>")
```

**Check information of an existing task**

You can get the task details by the `taskUUID`

```go
resp, err := client.TaskInfo("<TASK_UUID>")
```

**Check all task list information belonging to a wallet address**

You can get all tasks deployed from one wallet address

```go
total, resp, err := client.Tasks(&TaskQueryReq{
    Wallet: "<WALLET_ADDRESS>",
    Page:   0,
    Size:   10,
})
```

### More Samples

For more pratical samples, consult [go-swan-sdk-samples](https://github.com/swanchain/go-swan-sdk-samples).

### More Resources

More resources about swan SDK can be found

* [Swan Console platform](https://console.swanchain.io)
* [Deploying with Swan SDK](https://docs.swanchain.io/start-here/readme/deploying-with-swan-sdk)
* [Python-swan-sdk](https://github.com/swanchain/python-swan-sdk)
* [Python-swan-sdk-samples](https://github.com/swanchain/python-swan-sdk)

### License

The `go-swan-sdk` is released under the **MIT** license, details of which can be found in the LICENSE file.


# Swan Console

## Overview

[Swan Console](https://console.swanchain.io/) is a powerful web-based platform that revolutionizes application deployment on Swan Chain. Through an intuitive interface, users can seamlessly deploy, manage, and monitor applications across our decentralized infrastructure, making Web3 deployment as simple as traditional cloud services.

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

## Key Features

#### [Marketplace](https://console.swanchain.io/marketplace)

The Marketplace transforms decentralized application deployment into a streamlined experience, enabling:

* One-click deployment of various applications
* Currently featuring Blockchain GPU tasks pool services (Aleo and Iron)
* Automated resource allocation and management
* Real-time monitoring and control

#### [Instance Management](https://console.swanchain.io/instance)

Monitor and manage all your deployments through a centralized dashboard. The Instance panel provides:

* Real-time status monitoring of all running instances
* Detailed performance metrics and analytics
* Resource usage tracking and optimization tools
* Deployment configuration and termination controls

#### [Provider Dashboard](https://console.swanchain.io/providers)

Monitor and manage computing providers through a dedicated interface:

* Provider status monitoring
* Resource allocation tracking
* Performance analytics
* Payment management

#### Developer Tools

A complete toolkit for developers to build and integrate with Swan Chain:

* [Quick Deploy](https://console.swanchain.io/deploy): Streamlined deployment interface for rapid testing and development
* [API Management](https://console.swanchain.io/api-keys): Generate and manage API keys
* [Account Management](https://console.swanchain.io/account): Comprehensive tools for managing your wallet and balance.

***

## Guide

This guide will cover the following topics:

* [How to Get Started](/)
* [Blockchain GPU tasks Deployments Example](/bulders/tools/swan-console/mining-task-example)
* [Manage Instances](/bulders/tools/swan-console/mining-task-example#id-71f9)


# Getting Started

### Prerequisites <a href="#ef4e" id="ef4e"></a>

* A crypto wallet (MetaMask recommended)
* SWANU tokens
* A pool account (e.g., F2Pool for Aleo Blockchain GPU task in this guide)

### 1. Obtaining SWANU Tokens <a href="#id-5d1c" id="id-5d1c"></a>

#### 1.1 Purchase via DEX <a href="#id-2347" id="id-2347"></a>

You can acquire SWANU tokens through the DEX pool at[ ](https://www.geckoterminal.com/swanchain/pools/0x4fd0c2c5360d980d650fe02a19b1460b1802134b)IcecreamSwap: <https://www.geckoterminal.com/swanchain/pools/0x4fd0c2c5360d980d650fe02a19b1460b1802134b>

#### 1.2 Earn Through Computing Resources <a href="#id-7788" id="id-7788"></a>

Alternatively, earn SWANU by contributing your computing resources:

* Deploy ECP (Edge Computing Provider)
* Deploy FCP (Fog Computing Provider)

Learn more about CP deployment here: <https://docs.swanchain.io/bulders/computing-provider>

### 2. Managing Your SWANU Balance <a href="#id-6a71" id="id-6a71"></a>

Swan Chain Console features two distinct balance types:

<figure><img src="https://miro.medium.com/v2/resize:fit:700/0*DTVIX1gxYtcRZsEY" alt="" height="194" width="700"><figcaption></figcaption></figure>

**Available Balance**

* Primary account for storing credits
* Allows unrestricted transfers
* Functions as your main SWANU wallet within the platform

**Escrow Balance**

* Used for all operational costs
* Subject to transfer restrictions
* Required for deploying Blockchain GPU tasks

**Important**: The system automatically deducts fees every 24 hours and transfers them directly to the Computing Provider’s beneficiary address

**Locked Balance**

* A portion of your Escrow Balance that ensures the application can run for at least 12 hours
* Will be released after the application is closed or terminated

**Note**: Before deploying any Blockchain GPU task, your Escrow Balance must have sufficient funds to cover the initial 12-hour locked period

### Critical Account Operations

#### Daily Settlement Process

* Settlement occurs at UTC 00:00 daily
* System automatically deducts fees from Escrow Balance
* Fees are transferred to corresponding Computing Provider's beneficiary address

**Important**: Insufficient balance will trigger automatic task termination

#### Low Balance Protection

* System actively monitors Escrow Balance levels
* When the balance insufficient for current deployment costs:
  * All running tasks will be automatically terminated
  * System prevents new task deployments

**Critical**: Maintain sufficient Escrow Balance to avoid service interruption

### Balance Management Steps <a href="#ba4f" id="ba4f"></a>

To use the platform, you must transfer SWANU from your external wallet to your Available Balance.

1. **Deposit Process**

* Navigate to “Account” in the left panel
* Click “Recharge” to transfer SWANU from your wallet to Available Balance
* Locate the arrow icon between the balance accounts and click to transfer from “Available Balance” to “Escrow Balance”

<figure><img src="https://miro.medium.com/v2/resize:fit:700/0*oVeOPBtONbpS5vbP" alt="" height="189" width="700"><figcaption></figcaption></figure>

**2. Withdrawal Process**

**CRITICAL NOTE:** Withdrawals follow a strict two-step process with mandatory waiting period and specific restrictions.

<figure><img src="https://miro.medium.com/v2/resize:fit:700/0*5yVg-76xPLHGexhe" alt="" height="330" width="700"><figcaption></figcaption></figure>

1. **Escrow to Available Balance**

* Step 1: Request Withdrawal
  * Click the arrow icon (right to left) to transfer from Escrow to Available Balance
  * Status will show as "requested" in the "Transfer" section
* Step 2: Confirm Withdrawal (after 7 days)
  * After 7-day waiting period, confirm the transfer in "Transfer" section
  * Once successful, funds will appear in Available Balance

<figure><img src="https://miro.medium.com/v2/resize:fit:700/1*n4tkbtMlu4XTaxBpV6Q8cA.png" alt=""><figcaption></figcaption></figure>

2. **Available Balance to Wallet**

* Simply click the "Withdraw" button in Available Balance card to withdraw to wallet
* Monitor transaction status in withdrawal history

<figure><img src="https://miro.medium.com/v2/resize:fit:700/1*NUx8UWjJ2RKvaGz3BHaEBA.png" alt="" height="198" width="700"><figcaption></figcaption></figure>

{% hint style="info" %}
**Important Withdrawal Rules:**

* Only one active withdrawal request is permitted per account
* New withdrawal requests automatically invalidate previous ones
* Recommended: Stop all tasks 24 hours before requesting withdrawal
* Ensure sufficient balance for final settlements
  {% endhint %}


# Blockchain GPU Task Example

In this section, we will use Swan Console to launch an example Blockchain GPU tasks deployment on the Swan Network. You can follow the same process for any other tasks.

### 1. Accessing the Marketplace <a href="#id-01f0" id="id-01f0"></a>

The Swan Chain marketplace provides access to various Blockchain GPU tasks pools. To begin:

* Select “Marketplace” from the left panel
* Navigate to the Mining section
* View all supported Blockchain GPU tasks

<figure><img src="https://miro.medium.com/v2/resize:fit:700/1*dOQb-tlz_4bk9ALO8bvF1g.png" alt="" height="327" width="700"><figcaption></figcaption></figure>

### 2. Pool Registration <a href="#id-8b13" id="id-8b13"></a>

Using f2pool as an example:

* Visit[ F2pool’s official guide](https://f2pool.io/mining/guides/how-to-mine-aleo/#2-sign-up-for-an-f2pool-account)
* Complete account registration
* Save your account name — you’ll need it for the deployment process.

### 3. Deployment Configuration <a href="#id-5935" id="id-5935"></a>

### 3.1 Pre-deployment Preparation <a href="#id-57d6" id="id-57d6"></a>

Before proceeding with deployment, you’ll notice a section containing environment variables. These variables are crucial for your deploy operation — they contain the connection details and authentication information needed to connect to the Blockchain GPU tasks pool.

<figure><img src="https://miro.medium.com/v2/resize:fit:700/1*qY6qoGSI2oKXlSPnZYjIIw.png" alt="" height="478" width="700"><figcaption></figcaption></figure>

**Important**: Save these variables securely — you’ll need them for the configuration steps.

### 3.2 Settings Configuration <a href="#id-259c" id="id-259c"></a>

**3.2.1 Aleo Mainnet**

1. Create a unique instance name (no specific naming rules)
2. Click “Add Environment Variables” to create more input fields. Remember that all F2pool images require three essential variables:

* MINER\_URL: stratum+ssl://aleo-asia.f2pool.com:4420
* ACCOUNTNAME: Your registered F2pool account name
* WORKERNAME: A unique identifier for this worker

<figure><img src="https://miro.medium.com/v2/resize:fit:700/0*7GAJelNTO-Nd6BYn" alt="" height="188" width="700"><figcaption></figcaption></figure>

<figure><img src="https://miro.medium.com/v2/resize:fit:700/0*qKqzcRCvdOBdGtyA" alt="" height="225" width="700"><figcaption></figcaption></figure>

**Critical Note**: Even minor typing errors in these variables can prevent successful connection to the mining pool. For detailed information about Aleo task on F2pool, consult the[ official documentation](https://f2pool.io/mining/guides/how-to-mine-aleo/).

**3.2.2 Iron Fish (IRON)**

1. Create a unique instance name (no specific naming rules)

2\. Click “Add Environment Variables” to create more input fields, Remember that all F2pool images require three essential variables:

* MINER\_URL: Choose the server closest to your location
* ACCOUNTNAME: Your F2pool account name
* WORKERNAME: Your chosen worker identifier

<figure><img src="https://miro.medium.com/v2/resize:fit:700/0*pGGSbv4bVLreXHm5" alt="" height="188" width="700"><figcaption></figcaption></figure>

Available MINER\_URL Options:

* North America: stratum+ssl://ironssl-na.f2pool.com:1510
* Europe: stratum+ssl://ironssl-euro.f2pool.com:1510
* Asia: stratum+ssl://ironssl-asia.f2pool.com:1510

For complete Iron task instructions, visit[ F2pool’s Iron Fish guide](https://f2pool.io/mining/guides/how-to-mine-iron-fish/).

### 3.3 Provider Selection <a href="#a831" id="a831"></a>

After setting up your environment variables, you’ll need to choose the hardware specifications for your deploy operation.

<figure><img src="https://miro.medium.com/v2/resize:fit:700/0*zc0_x7GTIc6XlZa6" alt="" height="398" width="700"><figcaption></figcaption></figure>

Swan Chain offers two distinct approaches for selecting a Computing Provider (CP):

1. **Automatic Matching**

* System automatically matches you with suitable Computing Providers
* Recommended for new users

**2. Manual Provider Selection**

* Filter providers based on Geographic location, Hardware pricing and Provider account ID
* **PRO TIP**: Check provider performance metrics via their account ID in the provider dashboard
* **NOTE**: This option gives you more control but requires understanding of provider metrics

<figure><img src="https://miro.medium.com/v2/resize:fit:700/0*_FJH5EGnuiluoYgc" alt="" height="314" width="700"><figcaption></figcaption></figure>

### 4. Final Deployment <a href="#ab5d" id="ab5d"></a>

* Review all configurations thoroughly
* Click “Deploy Now” to initiate the Blockchain GPU task

**Note:** If you see the “Not sufficient balance” notification, please follow the “Managing your SWANU accounts” steps to transfer SWANU.

<figure><img src="https://miro.medium.com/v2/resize:fit:700/0*DuZLFLjsRD5tXhUm" alt="" height="232" width="700"><figcaption></figcaption></figure>

Once you’ve deployed your Blockchain GPU task, give it 3–5 minutes, then head over to your F2pool dashboard. If you see hashrate and Blockchain GPU task data showing up, congrats! Your Blockchain GPU task is up and running.

<figure><img src="https://miro.medium.com/v2/resize:fit:700/0*bcefwN3rs3-wMm3W" alt="" height="319" width="700"><figcaption></figcaption></figure>

### 5. Manage Instances <a href="#id-71f9" id="id-71f9"></a>

Through the Swan Console, you can:

* Monitor deployment status in real time
* View detailed performance metrics
* Terminate Blockchain GPU tasks if needed

### 5.1 **Deployment Dashboard Overview** <a href="#id-71f9" id="id-71f9"></a>

To monitor your deployments on Swan Chain Console:

1. Navigate to “Instance” in the left panel
2. Click on "Instance" or “Mining Task” to view your deployment status
3. Here you can monitor:
   1. Task running status
   2. Resource usage
   3. Connection status
   4. Cost

<figure><img src="https://miro.medium.com/v2/resize:fit:700/0*GBD0Qgdu-sGz4CkS" alt="" height="284" width="700"><figcaption></figcaption></figure>

**Note:** Costs are calculated and deducted every 12 hours. Make sure to maintain sufficient balance in your Escrow account to cover these periodic charges

### 5.2 Terminate **Active Deployment** <a href="#a2ad" id="a2ad"></a>

To close an active deployment:

1. Navigate to the Instance pane
2. Select the target deployment
3. Click the "Terminate" button
4. Confirm the blockchain transaction

<figure><img src="/files/9nwTgKxfEWhI1IR1zdeQ" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/2GjNFnGbXz4DhVLClxvq" alt=""><figcaption></figcaption></figure>

Once terminated:

* All associated costs will cease
* Locked SWANU will be released
* Resources will be deallocated


# Custom Blockchain GPU Task Pools

In this section, we will guide you through the process of setting up custom Blockchain GPU task pools on Swan Chain. This feature allows you to deploy your preferred Blockchain GPU task pool configurations with the same seamless experience as our official pools.

### 1. Accessing the Marketplace <a href="#id-01f0" id="id-01f0"></a>

The Swan Chain marketplace provides access to various Blockchain GPU task pools. To begin:

* Select “Marketplace” from the left panel
* Navigate to the Mining section
* click the "+" icon

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

### 2. Configuration Settings

#### Basic Configuration

1. Create a unique instance name
   * No specific naming rules apply
   * Choose a name that helps you identify this deployment

#### Docker Image Setup

1. In the Docker Image/OS field, enter your Blockchain GPU task container's Docker image
2. Configure essential environment variables, which typically include:

```
MINER_URL: [Your pool's stratum URL]
ACCOUNTNAME: [Your registered pool account name]
WORKERNAME: [A unique identifier for this worker]
```

> **Important**: Ensure your Docker image is properly configured and tested before deployment. Incorrect configurations may result in Blockchain GPU task interruptions.

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

## 3. Provider Selection <a href="#a831" id="a831"></a>

After setting up your environment variables, you’ll need to choose the hardware specifications for your deploy operation.

<figure><img src="https://docs.swanchain.io/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A700%2F0*zc0_x7GTIc6XlZa6&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=58e63629&#x26;sv=1" alt=""><figcaption></figcaption></figure>

Swan Chain offers two distinct approaches for selecting a Computing Provider (CP):

1. **Automatic Matching**

* The system automatically matches you with suitable Computing Providers
* Recommended for new users

**2. Manual Provider Selection**

* Filter providers based on Geographic location, Hardware pricing and Provider account ID
* **PRO TIP**: Check provider performance metrics via their account ID in the provider dashboard
* **NOTE**: This option gives you more control but requires understanding of provider metrics

<figure><img src="https://docs.swanchain.io/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A700%2F0*_FJH5EGnuiluoYgc&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=3ff7fe95&#x26;sv=1" alt=""><figcaption></figcaption></figure>

### 4. Final Deployment <a href="#ab5d" id="ab5d"></a>

* Review all configurations thoroughly
* Click “Deploy Now” to initiate the Blockchain GPU task

**Note:** If you see the “Not sufficient balance” notification, please follow [this guide](/bulders/tools/swan-console/getting-started) to manage your accounts and transfer SWANU.

<figure><img src="https://docs.swanchain.io/~gitbook/image?url=https%3A%2F%2Fmiro.medium.com%2Fv2%2Fresize%3Afit%3A700%2F0*DuZLFLjsRD5tXhUm&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=f6f9d373&#x26;sv=1" alt=""><figcaption></figcaption></figure>

***

### Contributing to Official Blockchain GPU task Pools

Want to see your Docker configuration added to our official Blockchain GPU task pools? We welcome community contributions!

1. Visit our GitHub repository: [awesome-swanchain](https://github.com/swanchain/awesome-swanchain/tree/main)
2. Follow the contribution guidelines
3. Submit a Pull Request with your Blockchain GPU task pool configuration


# Lagrange

Web3 HuggingFace

[Lagrange](https://lagrange.computer) is a decentralized Web3 platform for natural language processing (NLP) development and deployment, built on Swan Chain computing network. It aims to provide a more cost-effective, secure, and interoperable alternative to centralized cloud services like AWS.

Lagrange serves as a decentralized version of Hugging Face, leveraging the decentralized computing resources from Swan Chain and utilizing multichain.storage as the decentralized storage layer to ensure the persistence of important data.

<figure><img src="/files/1vIN3Vd7iBxkKIuZjcpE" alt=""><figcaption></figcaption></figure>

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXc51WhVt0u064TrimhzOhZ4OTspF_qAIanSJzyodELHzcugOBQZz4nvgN4QkSM8vS5gh3BlGsrmLj0f32TQms1pQDzDAYJgDvsjktzQLUldYrpCYGtynALtyjtppOobLMFLyWVUf55zOsx0HR5QwwHGh6Qu?key=Q5864mz9cz0YmHEPYYSbWA" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
*Learn more about Lagrange in*[ *its documentation*](https://docs.lagrangedao.org/)*.*
{% endhint %}

[Lagrange](https://lagrange.computer) leverages the advantages of [Swan Chain](https://swanchain.io/), such as:

* **Cost-Effective:** By utilizing decentralized resources, Lagrange reduces operational costs compared to traditional cloud services.
* **Security:** Ensures data integrity and security through decentralized storage and processing.
* **Interoperability:** Compatible with various blockchain networks and computing providers, enhancing flexibility and scalability.
* **Efficiency:** Facilitates efficient NLP model training and deployment using distributed computing power.

Let’s explore some of the [Spaces](https://lagrange.computer/spaces) built by Lagrange community across categories like AI, gaming, blockchain, and tools.

### **Awesome Spaces**

#### AI Agent

Explore the capabilities of AI agents using Lagrange technology for advanced machine learning applications

* [**Eliza-SwanChain**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/Eliza-swanchain/app)**:** An AI agent using Eliza framework that can answer all questions related to Swan Chain

#### **AI and Creative Spaces**

Harness cutting-edge AI models to generate content and boost your creative projects.

* [**MusicGen**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/MusicGen/app): Create original music tracks using simple text prompts.
* [**Stable Diffusion**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/Stable-Diffusion-Base-LoRA/app): Transform text descriptions into stunning AI-generated images.
* [**Text-to-Speech**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/Text-to-Speech/app): Convert written text into natural-sounding speech effortlessly.
* [**ComfyUI**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/ComfyUI/app): Streamline AI image generation with an intuitive graphical interface.
* [**Llama3-8B-LLM-Chat**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/Llama3-8B-LLM-Chat/app)**:** Meta’s Llama 3, the next iteration of the open-access Llama family.

#### **Gaming Spaces**

Relive classic gaming experiences and challenge yourself with timeless favorites.

* [**Tetris**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/tetris/app): Test your spatial skills with this iconic block-stacking puzzle.
* [**Super Mario**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/Mario/app): Embark on a nostalgic adventure with gaming's most famous plumber.
* [**Pac-Man**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/pac-man/app): Navigate mazes and outmaneuver ghosts in this beloved arcade classic.
* [**2048**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/2048/app): Slide numbered tiles and aim for the elusive 2048 in this addictive challenge.

#### **Blockchain Spaces**

Explore and interact with decentralized technologies using these powerful tools.

* [**Chainnode-RPC**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/chainnode-rpc/app): Access and analyze blockchain data with this comprehensive RPC interface.
* [**Uniswap**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/uniswap/app): Experience decentralized trading on the Ethereum blockchain.

#### **Development Tools**

Enhance your coding workflow with these essential development utilities.

* [**Terminal**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/Terminal/app): Access a versatile command-line interface directly in your browser.
* [**JSON-View**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/Json-view/app): Visualize and interact with JSON data in a user-friendly web environment.
* [**Jupyter**](https://lagrange.computer/spaces/0x231fe9090f4d45413474BDE53a1a0A3Bd5C0ef03/Jupyter-Labs/app): Develop, document, and execute code in an interactive notebook interface.

{% hint style="success" %}
*Exploring more models from the reporitory* [*here*](https://github.com/swanchain/awesome-swanchain)*.*
{% endhint %}

### Contribute to Lagrange

Have an idea for a new space? We welcome contributions from our community!

* [Fork and build your first Space](https://docs.lagrangedao.org/spaces/fork-space)
* [Explore our model repository](https://github.com/swanchain/awesome-swanchain)

Join us in expanding the Lagrange ecosystem and share your innovations with developers worldwide.


# Swan IPFS Storage

[Swan IPFS Storage](https://swanipfs.com)(formerly Multichain Storage), developed by the Swan Network, is a new kind of storage service that works with different blockchain networks. It transcends traditional cloud storage by using smart contracts for enhanced security, reminiscent of an [S3 storage gateway](https://aws.amazon.com/storagegateway/file/s3/) but with the added benefit of decentralization.

{% hint style="info" %}
*Learn more about Swan IPFS Storage in*[ *its documentation*](https://docs.filswan.com/multichain.storage/overview)*.*
{% endhint %}

### Why Choose Swan IPFS Storage? <a href="#id-7e7d" id="id-7e7d"></a>

Swan IPFS Storage offers several advantages over traditional cloud services, such as:

* **Decentralization:** Swan IPFS Storage eliminates the need for intermediaries and third-party providers, giving users full control and ownership over their data. Swan IPFS Storage also prevents censorship and tampering by ensuring that files are replicated and verified across multiple nodes.
* **Interoperability:**&#x53;wan IPFS Storage supports multiple blockchains, including Ethereum, Polygon and more. This means that users can access their files from any chain they prefer, without being locked into a single platform or network.
* **Cost-efficiency:** Swan IPFS Storage reduces the cost of storage by utilizing the spare capacity of existing nodes. Swan IPFS Storage also optimizes the storage allocation and distribution based on the demand and supply of each chain.
* **Scalability:** Swan IPFS Storage can handle large volumes of data and traffic without compromising speed or quality. Swan IPFS Storage also adapts to the changing conditions of each chain, such as congestion, fees, and latency.

### What Can You Store with Swan IPFS Storage? <a href="#c3ad" id="c3ad"></a>

Swan IPFS Storage can store any type of file that can be hosted on a website, such as:

* Images, videos, audio, and other media formats
* PDFs, documents, spreadsheets, and other office files
* JSON, XML, CSV, and other data formats
* HTML, CSS, JavaScript, and other web development languages

Try it here: <https://swanipfs.com>


# Nebula Block Cloud

A leading Web3 Infrastructure Provider

[Nebula Block ](https://nebulablock.com/)is a forward-thinking Montreal-based startup, specializing in advanced cloud computing and blockchain infrastructure solutions. Designed to meet the stringent demands of modern academic and commercial institutions, Nebula Block provides secure, scalable, and cost-effective computing environments.

In addition to its core offerings in cloud computing, Nebula Block is deeply involved in the Web3 space, through its sister company, which provides robust blockchain hosting solutions. This includes comprehensive support for GPU and CPU bare metal servers, as well as data center hosting tailored specifically for blockchain projects.

#### Service Offerings

**1. Cloud Computing Solutions:**

* **Swan Network:** Utilizing Swan Chain computing resources, this service addresses the global needs for computing, storage, and AI, providing a robust infrastructure for a wide range of applications across the globe.

**2. Blockchain Infrastructure Services:**

* **Bare Metal and Cloud Hosting:** High-performance GPU and CPU bare metal servers, specifically optimized for blockchain projects. This service includes secure data center hosting, ensuring that blockchain applications run smoothly and efficiently.
* **Decentralized Computing and Storage:** Provides decentralized infrastructure to support Web3 applications, offering reliability, security, and scalability for next-generation internet services.
* **Blockchain as a Service (BaaS):** Comprehensive blockchain solutions that allow businesses to deploy, manage, and scale blockchain applications without the need for deep technical expertise. This service simplifies blockchain integration for various industries.

**3. Data Center Solutions:**

* **Data Center and Management Suite:** A full suite of data center services, including a 100 PB cloud storage system, 24/7 monitoring, and cloud CRM integration. These services are designed to meet the needs of clients with high-security requirements and large-scale data management needs.
* **Logistics and Equipment Management:** Expertise in handling and shipping high-value equipment (over $100M) to multiple data centers, with support for setup and ongoing management. This service is crucial for clients who require secure and reliable infrastructure deployment.


# Ecosystem Projects

#### Overview

**AI & ML Projects**

1. **ChainML/Theoriq**
   * **Description:** ChainML is an AI research and development company focused on advancing machine learning technologies on the blockchain.
2. **Lilypad**
   * **Description:** Lilypad offers a decentralized, serverless distributed computing platform that enables seamless execution of tasks on the blockchain.
3. **Akave.ai**
   * **Description:** Akave.ai is an L2 storage chain that facilitates the creation of on-chain data lakes for efficient data management and retrieval.
4. **Autonomys (prev. Subspace)**
   * **Description:** Autonomys, formerly known as Subspace, is a decentralized network at the intersection of AI and blockchain, providing advanced data processing capabilities.
5. **KNN3**
   * **Description:** KNN3 Network merges AI and Web3 technologies to offer a suite of products for enhanced data analysis and decentralized applications.
6. **Typox.AI**
   * **Description:** Typox.AI is a platform designed to improve Web3 navigation through the application of AI-driven solutions.
7. **Gitdata.ai**
   * **Description:** GitData.ai is an open-source platform for MLOps, focusing on data management, model training, and deployment on decentralized networks.
8. **AgentLayer**
   * **Description:** AgentLayer is a decentralized network for autonomous AI agents, facilitating efficient task execution and coordination.
9. **OORT**
   * **Description:** OORT is a decentralized cloud platform providing storage, compute, and AI capabilities, enabling robust and scalable cloud solutions.

**Bridge Projects**

1. **Superbridge**
   * **Description:** Superbridge is a decentralized bridge platform designed to facilitate cross-chain interactions and transactions, ensuring interoperability between different blockchain networks.
2. **Comet**
   * **Description:** CometBridge is a cross-chain bridge application that allows users to seamlessly transfer assets and data across various blockchain ecosystems.

Click [here](https://www.swanchain.io/ecosystem/Apps) to access the full suite of Swan Ecosystem projects:<https://www.swanchain.io/ecosystem/Apps>


# Mission 3.0

## Introduction

Mission 3.0 is a next-generation engagement platform designed to empower space owners, users, and communities. By providing a structured and interactive environment, Mission 3.0 facilitates seamless participation in quests, fosters user engagement, and enhances the visibility of projects through **gamified experiences, decentralized identity (DID) integration, and cross-platform interoperability**.

With **new features like AI-generated DID artwork, badge systems, social verification tools, and referral rewards**, Mission 3.0 redefines how Web3 communities grow, collaborate, and thrive.

### **Key Features**

### **For Projects: Powerful Tools to Grow Your Community**

Mission 3.0 equips project teams with everything needed to create engaging experiences and drive meaningful community growth:

1. **Comprehensive Quest Management**
   * Create your project’s customizable branded Quest with logos, banners, social links, and token integrations.
2. **Advanced Analytics Dashboard**
   * Track **DID adoption rates**, badge completion, and referral-driven growth.
   * Monitor social follower changes (X, Discord, Telegram) and Quest Rank trends.
3. **Flexible Quest & Task Creation**
   * Design quests with **social verification** (Discord roles, TG group membership) and **on-chain actions** (NFT ownership, transaction history).
4. **Community Management**
   * Reward top leaderboard users with tokens or exclusive roles.
   * Use **real-time engagement metrics** to refine strategies and boost retention.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXd8oQHHRWxMxZQW3amupWurapeRJpAN16u5ae4JlYDsMo5HMLFCihIbSM2EyxJnOsAB2kXlx5tNvkbwnYtIu-MzQuV7xAqLcC61_tGmrt1X4YnoPWQC4JEVdag-a_mIFIUYe5yJ?key=RorGy8wvhHrk-9_hcsluWYqh" alt=""><figcaption></figcaption></figure>

### **For Users: Discover, Engage, and Earn Across Web3**

Mission 3.0 provides a seamless experience for users to explore the Web3 ecosystem:

1. **Personalized Dashboard**
   * **Mint Your DID**: Generate a unique decentralized identity using AI-powered image generation.
   * Track badges, points, and referral rewards in one unified interface.
2. **Seamless Engagement Flow**
   * Complete tasks with **one-click verification** for Discord roles, TG groups, and on-chain actions.
   * Earn **badges** to prove social credibility (X followers, LinkedIn profiles) or chain activity (NFT holdings).
3. **Community Recognition**
   * Climb **per-Quest leaderboards** to earn recognition and rewards.
   * **Referral Program**: Earn 20% of mint fees when invited users create DIDs (no cap, instant withdrawals).\\

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcYWuf0WuXjWlSdOQGEmDF2oj_ezz_5GddpNZjZq9_7EFYoGtOJ7Z_LRwTqUHHV6U5nOA0mBg80XYrQ0h_D45rH_sGNAa3yTf18OvkLGPmvmsYlsk4Jk_wsoIqr8XT3Yz_Ggef9gQ?key=RorGy8wvhHrk-9_hcsluWYqh" alt=""><figcaption></figcaption></figure>

### **Why Mission 3.0? The Brand Behind the Build**

Mission 3.0 isn’t just about features—it’s about philosophy. In a fragmented Web3 landscape, we bridge the gap between projects and communities through:

1. **Authentic Ownership**
   * **Admins own their Quests**, users own their data and DIDs.
   * Decentralization is foundational: No third-party controls your identity or community.
2. **Community as Currency**
   * Metrics like **Rank** and **DID adoption rates** incentivize meaningful engagement.
   * Badges and leaderboards turn participation into reputation and rewards.
3. **Interoperability by Design**
   * Support for **multi-chain tokens** (EVM, non-EVM) and **cross-platform logins** (Discord, X, TG).
   * DID integration enables seamless identity portability across Web3 applications.
4. **Innovation at the Core**
   * **AI-Powered Creativity**: Users generate unique DID artwork through text prompts.
   * **No-Regret Mechanics**: Permanent DID tags and images ensure authenticity and commitment.\\


# Get Started

## Overview

Mission 3.0 is a next-generation engagement platform designed to empower both users and projects (Space Holders) in the Web3 ecosystem. Whether you’re an individual looking to participate in Quests and earn rewards, or a project aiming to grow and engage your community, Mission 3.0 provides the tools to make it happen.

#### Two Key Roles in Mission 3.0

* **Users (Quest Participants):** Explore Spaces, complete Quests, earn rewards, and build your on-chain identity. Check out tutorial [here](/bulders/mission-3.0/get-started/for-users).
* **Project Owner (Space Holder)**: Create Spaces, launch Quests, track engagement, and manage your Web3 community. Check out tutorial [here](/bulders/mission-3.0/get-started/for-space-holders).

This guide will walk you through how to get started with Mission 3.0, tailored to your role. Whether you're here to discover and complete Quests or launch and manage your own Space, we’ve got you covered!

\
\
\
\\


# For Users

## 1. Get Started

### 1.1 Wallet Connection & Profile Setup

* Step 1: Go to [app.missionhub.io](https://app.missionhub.io/) → Click "Connect Wallet" (top-right).
* Step 2: Choose your wallet (e.g., MetaMask) → Sign the authentication.
* Step 3: Create a nickname, upload a profile image, and optionally bind social accounts (X, Telegram, Discord, LinkedIn) or email.

### 1.2 Navigating the Interface

* Explore Tab: Hover over "Explore" to filter Quests (All/Followed)
* Profile Dropdown: Access your settings, Mission Pass Referrals, and disconnect options.

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

## 2. Joining Quests & Earning Rewards

### 2.1 Discovering Quests

* Step 1: Browse Quest Cards under Explore → Quests.
* Step 2: Click a Quest → View details (tasks, duration, rewards) → Click "Join Quest".\\

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

### 2.2 Completing Tasks

* Step 1: Expand a task → Click the target link (e.g., "Follow our X account").
* Step 2: Complete the action (e.g., retweet, join Discord) → Return to Mission 3.0 → Click "Verify".
* New Task Types:

  * Discord Verification: Verify if you hold a specific role in a server.
  * Telegram Verification: Confirm membership in a group/channel.
  * On-Chain Actions: Verify NFT ownership or transaction history.

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

## 3. Advanced Features

### 3.1 Mint Your DID (Decentralized Identity)

In Mission 3.0, DID (Decentralized Identity) serves as a user-friendly, secure, and interoperable blockchain identity. Holding a DID could unlock exclusive quests and greater rewards in the future.

How to Mint a DID:

1. Go to Mission Pass → Click "Mint Mission Pass".
2. Generate a DID-exclusive image using our AI model.
3. Select your preferred tags and confirm the minting.
4. Each minting attempt costs $4 USD (in ETH equivalent).

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

{% hint style="info" %}
I**mportant Rules:**

* No Regrets Mechanism: Clicking "Mint Now" resets all retry chances, and tags become permanent. You can retry image generation up to three times, but the first one might already be the best—your choice!
* Minting Requirement: Users must reach at least Android Level before minting.
  {% endhint %}

### 3.2 Mission Pass: Your Proof of Human Identity

The Mission Pass system provides a verifiable, decentralized identity that helps users prove authenticity, access premium content, and boost credibility within Mission 3.0.

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

#### **Mission Pass Overview**

* Humanity Progress Bar: Tracks your verification progress.
* Badges: Earned through various identity verifications.
* Referral System: Invite friends and earn 20% of their DID minting fee as a reward.

#### **Social Verification**

* Twitter Age & Followers: Prove your account legitimacy.
* Referral System: Track new users you invited.

#### **On-Chain & NFT Verification**

* Swan Mainnet NFT (Mission): Verify NFT holdings.
* Swan & ETH On-Chain Activity: Prove past interactions.
* Swan Mainnet Airdrop: Confirm past participation.

**Why Complete Verification?** Higher Proof of Human levels unlock exclusive quests, rewards, and leaderboard benefits!

### 3.3 Earn Badges

New Badge Types:

* Social Proof: Verify X followers, account age, or LinkedIn profile.
* Chain Activity: Prove NFT ownership, transaction volume, or cross-chain activity.

How to Claim:

* Complete badge-specific tasks → Check your profile’s "Badges" tab.

### 3.4 Referral Rewards

* Step 1: Copy your referral link/code from your profile.
* Step 2: When a referred user mints their DID, you earn 20% of their mint fee (e.g., 0.8 USD for a 4 USD mint).
* Step 3: Withdraw rewards anytime to your wallet.

<figure><img src="/files/18F2OxMjzh4XZqF1pgOS" alt=""><figcaption></figcaption></figure>

### 3.5 Leaderboards & Competition

* New: Each Quest now has its own leaderboard!
* How to Rank Up:
  * Complete tasks quickly and consistently.
  * Earn bonus points for holding DID or badges.
* Check Rankings: Go to any Quest → Click "Leaderboard".


# For Space Holders

## 1. Setting Up Your Space

### 1.1 Creating a Space

Step 1: Log in [app.missionhub.io](https://app.missionhub.io/) with your admin wallet → Go to "Dashboard".

Step 2: Click "Create Organization" → Fill in:

* Branding: Logo, banner, name, description.
* Social Links: X, Discord, Telegram, etc.
* Token Info (optional): Token address, network, explorer.

### 1.2 Adding Admins & Members

Step 1: Go to Space Settings → Account.

Step 2: Add admins by wallet address → Set permissions (edit/remove).

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXc4BCSFtNxTADvnyQWUUf4IAhvLMktXf7TmdfCkPThApm8B7OdthrgUCy0YsI8rkyCNxWlHTOnwxl2BX24ohRu9BVzHND5Tn36JB5dxC2cCkiTIlyZ3h5asMU5VN7JThoV_TMf0?key=RorGy8wvhHrk-9_hcsluWYqh" alt=""><figcaption></figcaption></figure>

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcU6CUCvPb8a5LCEPs3ke3Jv207PaZ8dbAt0KhzAH-Z1m9gtmSB9_J7vIxA6x2laYXwXJ-gKWsTMMXY5KGHlaZxjvXVN5_-awhyYBBfPSVVO0GyL6Je1aN86ZrlzhjYPYVPD41Z6Q?key=RorGy8wvhHrk-9_hcsluWYqh" alt=""><figcaption></figcaption></figure>

## 2. Designing Advanced Quests

### 2.1 Launching a Quest

Step 1: In your Quest List → Click "Create Quest".

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXenqKh5KGshKNxt9XTDcBOumiUvKh1jr6kfH6n5XFmbYvSqrNsjaiQ82XZBp_DtSHOgldiXHEO5F-SdPVuwjfHksccMqOyqU_MHvvpjfZSFTIZgxfYPxGUflQma-fyIniLhQ3pCyw?key=RorGy8wvhHrk-9_hcsluWYqh" alt=""><figcaption></figcaption></figure>

Step 2: Define:

* Quest Basics: Name, description, tags, duration
* Tasks: Click "Create Task" to add actions:
  * Social Verification: Discord roles, Telegram group membership.
  * On-Chain Verification: NFT ownership, transaction history.

### 2.2 Customizing Tasks

Step 1: Open the Task Creation Window → Fill in:

* Task Name: E.g., "Join Our Discord & Get OG Role".
* Description: Explain requirements clearly.
* Link: Add a target URL (e.g., Discord invite link).
* Advanced Settings:
  * Discord Role ID: Require users to hold a specific role.
  * NFT Contract Address: Verify ownership.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXfAxUKTmUpea_iQm-bPnXlEAALJtJbODhWsHs5yM0Pff0R1ZSg85P0TlF7nnMnYw_JmGtwW3kzpA71qz3oe_RkpCIhWYUucn7n6fGSUul5SgSI_6tT0JQhDviJEtHbpLPpBXUfVGA?key=RorGy8wvhHrk-9_hcsluWYqh" alt=""><figcaption></figcaption></figure>

## 3. Analyzing Performance

### 3.1 Using the Analytics Dashboard

* New Metrics:
  * DID Adoption Rate: % of users with minted DID.
  * Badge Completion: Track badge-specific task success.
  * Referral Impact: Measure user-driven growth.
* Key Actions:
  * Filter data by time (daily/weekly/monthly).
  * Export reports for community updates.

### 3.2 Optimizing Engagement

* Pro Tips:
  * Reward top leaderboard users with tokens or exclusive roles.
  * Partner with other Spaces for cross-promotional Quests.
  * Use AI-generated task ideas (beta feature).


# Network Info

A Full Toolset AI Blockchain

## SWAN Token（Mainnet）

<table data-header-hidden><thead><tr><th width="200"></th><th></th><th></th><th></th></tr></thead><tbody><tr><td><strong>Contract Address</strong></td><td><strong>Layer</strong></td><td><strong>Address</strong></td><td><strong>link</strong></td></tr><tr><td>Swan Token</td><td>L1 （ETH Mainnet）</td><td><code>0x43e3De6745fad70127d7935198311386449fD9dd</code></td><td><a href="https://etherscan.io/token/0x43e3de6745fad70127d7935198311386449fd9dd">https://etherscan.io/token/0x43e3de6745fad70127d7935198311386449fd9dd</a></td></tr><tr><td>Swan Token（Bridged）</td><td>L2 （Swan Chain）</td><td><code>0xBb4eC1b56cB624863298740Fd264ef2f910d5564</code></td><td><a href="https://swanscan.io/address/0xBb4eC1b56cB624863298740Fd264ef2f910d5564">https://swanscan.io/address/0xBb4eC1b56cB624863298740Fd264ef2f910d5564</a></td></tr></tbody></table>

## Mainnet

<table data-header-hidden><thead><tr><th width="282"></th><th></th></tr></thead><tbody><tr><td><strong>Chain ID</strong></td><td>254</td></tr><tr><td><strong>Currency Symbol</strong></td><td>ETH</td></tr><tr><td><strong>Block Explorer URL</strong></td><td><a href="https://swanscan.io/">https://swanscan.io</a><br>（If it fails,try <a href="https://mainnet-explorer.swanchain.io/">https://mainnet-explorer.swanchain.io</a>)</td></tr><tr><td><strong>Chainlist</strong></td><td><a href="https://chainlist.org/chain/254">https://chainlist.org/chain/254</a></td></tr><tr><td><strong>Contract Addresses</strong></td><td>Refer to the <a href="/pages/4B9GAd4sg95K68dijwNJ#mainnet">Contract Addresses pages</a></td></tr><tr><td><strong>Connect Wallet</strong></td><td>Click <a href="https://chainlist.org/chain/254">here</a> to connect your wallet to Swan Chain mainnet</td></tr></tbody></table>

<table><thead><tr><th width="767">RPC List</th></tr></thead><tbody><tr><td><a href="https://mainnet-rpc.swanchain.org">https://mainnet-rpc.swanchain.org</a></td></tr><tr><td><a href="https://mainnet-rpc-01.swanchain.org">https://mainnet-rpc-01.swanchain.org</a></td></tr><tr><td><a href="https://mainnet-rpc-02.swanchain.org">https://mainnet-rpc-02.swanchain.org</a></td></tr><tr><td><a href="https://mainnet-rpc-02.swanchain.org">https://mainnet-rpc-03.swanchain.org</a></td></tr><tr><td><a href="https://mainnet-rpc-02.swanchain.org">https://mainnet-rpc-04.swanchain.org</a></td></tr><tr><td><a href="https://mainnet-rpc01.swanchain.io">https://mainnet-rpc01.swanchain.io</a></td></tr></tbody></table>

{% hint style="info" %}
**Important:** If you experience any issues with any of these RPCs, please switch to another one immediately.
{% endhint %}

{% hint style="info" %}
learn how to [set up your wallet](/swan-chain-campaign/atom-accelerator-race/before-you-get-started/set-up-metamask) and fund your wallet via [bridge](/swan-chain-campaign/swan-saturn-testnet/before-you-get-started/bridge-tokens).
{% endhint %}

## Proxima Testnet

| RPC URL            | <https://rpc-proxima.swanchain.io>                                                                        |
| ------------------ | --------------------------------------------------------------------------------------------------------- |
| Chain ID           | 20241133                                                                                                  |
| Currency Symbol    | ETH                                                                                                       |
| Block Explorer URL | <https://proxima-explorer.swanchain.io/>                                                                  |
| Chainlist          | <https://chainlist.org/chain/20241133>                                                                    |
| Contract Addresses | Refer to the [Contract Addresses pages](/network-reference/contract-addresses#proxima-testnet)            |
| Connect Wallet     | Click [here](https://chainlist.org/chain/20241133) to connect your wallet to Swan Chain (Proxima) testnet |


# Set Up Your Wallet

#### **Step 1: Add Swan Chain to Metamask** <a href="#step-1-add-swan-chain-to-metamask" id="step-1-add-swan-chain-to-metamask"></a>

1. Open MetaMask and click on the network selector at the top left.
2. Select "Add network" and then "Add a network manually."
3. Fill in the details for [Swan Chain Mainnet](/network-reference/readme):

<figure><img src="https://docs.swanchain.io/~gitbook/image?url=https%3A%2F%2F3478205236-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FcvUWH8GhRCqvKwuN0BGF%252Fuploads%252Fgit-blob-42658abed574e46f5d9ad35eafe1721e70cb4b4b%252FMetaMask.png%3Falt%3Dmedia&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=3de08dd7&#x26;sv=1" alt=""><figcaption></figcaption></figure>

1. Click "Save" or "Add" to save the network.

#### **Step 2: Import Tokens** <a href="#step-2-import-tokens" id="step-2-import-tokens"></a>

1. In Metamask, click on "Import tokens" at the bottom of the Tokens tab.
2. Enter the token contract address for SWAN Token:

**0xBb4eC1b56cB624863298740Fd264ef2f910d5564**

The token symbols and decimals should autofill. If not, check the block explorer.

3. Click "Import" to confirm.[<br>](https://docs.swanchain.io/swan-chain/swan-chain-mainnet/swan-credit-token)


# Bridge Token

**Step 1: Purchasing ETH**

Fund your wallet with ETH from any Decentralized Exchange (DEX) or Centralized Exchange (CEX).

Funding your network account is required to use the network. All transactions, including claiming Swan Credit tokens and deploying Spaces, charge a transaction fee. Ensure you have sufficient ETH to cover these costs.

**Step 2: Bridge ETH from Ethereum to Swan Chain**

Go to[ Bridge](https://bridge.swanchain.io/), enter the amount of ETH you wish to bridge, and click on the "Deposit" button.

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

{% hint style="info" %}
Swan Chain's third-party bridges:

<https://memebridge.xyz/#/bridge/?original=Ethereum&target=Swan&symbol=ETH>

<https://owlto.finance/?to=Swan>

<https://superbridge.app/swan-chain>

<https://cometbridge.app/?original=Ethereum&target=Swan&symbol=ETH>
{% endhint %}

**L1 Bridge Address**: `0xed7525946A09056C6AaE29941b8323017382050e`


# Contract Addresses

This reference guide lists all the contract addresses for Mainnet and Testnet

## Mainnet

<table><thead><tr><th width="299">Contract Name</th><th>Contract Address</th></tr></thead><tbody><tr><td>AddressManager</td><td>0x55Aec4EE11dA7d655565cCc2EB3bF21a46C94e6f</td></tr><tr><td>L1BridgeAddress</td><td>0xed7525946A09056C6AaE29941b8323017382050e</td></tr><tr><td>DisputeGameFactoryProxy</td><td>0x2069FC7097b7784FCA21aa459e57E95C0046EeCD</td></tr><tr><td>L1CrossDomainMessenger</td><td>0x76A8Eb93D4a200e8594B1ab1021ab5595CDfB57D</td></tr><tr><td>L1CrossDomainMessengerProxy</td><td>0x15567C4FfD9109795dFf1D9A5233D10aef0738D2</td></tr><tr><td>L1ERC721Bridge</td><td>0x621729Ef0571a76E438689ec2bC88ee8E3f2Beff</td></tr><tr><td>L1ERC721BridgeProxy</td><td>0x1Ccf7e62889E6A93413DEAFC4e390Bd4047bDC32</td></tr><tr><td>L1StandardBridge</td><td>0xc7e1EA328166Eea934429Eaa9F6c55Ef5548Efe7</td></tr><tr><td>L1StandardBridgeProxy</td><td>0xed7525946A09056C6AaE29941b8323017382050e</td></tr><tr><td>L2OutputOracle</td><td>0x0092400cf9cbAC5ABD8518960Cb1F90663607630</td></tr><tr><td>L2OutputOracleProxy</td><td>0x1c22740A0B4511E11D76434A424487862b593901</td></tr><tr><td>OptimismMintableERC20Factory</td><td>0x351ABA1B5B72E6bA8d530740f073993069e7BC69</td></tr><tr><td>OptimismMintableERC20FactoryProxy</td><td>0xE9614162C6128ABD7790C65D711CfC43ea842153</td></tr><tr><td>OptimismPortal</td><td>0x1606beCd26316B935B2dFE31D57C1C0B39f4f52f</td></tr><tr><td>OptimismPortalProxy</td><td>0xBa50434BC5fCC07406b1baD9AC72a4CDf776db15</td></tr><tr><td>ProtocolVersions</td><td>0xE8120ec0E094372Ec1ddcbd9c50F94e74Fa7a3fc</td></tr><tr><td>ProtocolVersionsProxy</td><td>0x9B10a384a8508fd9ecED992815340F8E00F55E6A</td></tr><tr><td>ProxyAdmin</td><td>0xCc8c55Ec2Ea3F3001C049eC934e72b55cf52fBf3</td></tr><tr><td>SafeProxyFactory</td><td>0xa6B71E26C5e0845f74c812102Ca7114b6a896AB2</td></tr><tr><td>SafeSingleton</td><td>0xd9Db270c1B5E3Bd161E8c8503c55cEABeE709552</td></tr><tr><td>SuperchainConfig</td><td>0x704Ad7cb61f3Ff97F790FAA747279244Eb2a1802</td></tr><tr><td>SuperchainConfigProxy</td><td>0xadE916De67511E5C24af4174Be67143d0dA94959</td></tr><tr><td>SystemConfig</td><td>0x7CDAEa613E1D17e78F24CAF6349bCCf2bC364F0a</td></tr><tr><td>SystemConfigProxy</td><td>0x504D56cf68f791B45E3A2e895B0e1562f3431328</td></tr><tr><td>SystemOwnerSafe</td><td>0x6197f64902b9275e6815F9A5b641Ed2291A5d39c</td></tr><tr><td>Swan Token L1 （ETH Mainnet）</td><td>0x43e3De6745fad70127d7935198311386449fD9dd</td></tr><tr><td>Swan Token（Bridged） L2 （Swan Chain）</td><td>0xBb4eC1b56cB624863298740Fd264ef2f910d5564</td></tr></tbody></table>

## Proxima Testnet

<table><thead><tr><th width="298">Contract Name</th><th>Contract Address</th></tr></thead><tbody><tr><td>AddressManager</td><td>0xa0EbCa3D403005Bb0aa65F6BFB8FBA99537D280F</td></tr><tr><td>L1BridgeAddress</td><td>0x9C041e883BE0e3201524e7BA6f7A53B367b5CFb0</td></tr><tr><td>AnchorStateRegistry</td><td>0x13d6011fe9271B8F9A578bD0b52d9B4D5995542C</td></tr><tr><td>AnchorStateRegistryProxy</td><td>0x90781886243c18Fc15C2Ade0D0ddee7bCFcB7777</td></tr><tr><td>DelayedWETH</td><td>0x6f521Ea4CbA93188214B4d449f34007E1bF9a8F3</td></tr><tr><td>DelayedWETHProxy</td><td>0x0F7e2BD539704cB2E77f834eEC94D9Bc89cCEf89</td></tr><tr><td>DisputeGameFactory</td><td>0x9cA7D7Eb3958cD5365BB23e588e0512971D9605a</td></tr><tr><td>DisputeGameFactoryProxy</td><td>0x8d97C5C6a9D7A4a011d2c523f42A69205Fe63AFD</td></tr><tr><td>L1CrossDomainMessenger</td><td>0xC146a6C362bde4198d60a0EbF20a6f6962705572</td></tr><tr><td>L1CrossDomainMessengerProxy</td><td>0x838cdB1Ec7DC624a8ca73F8f68563e0D90e0F4C2</td></tr><tr><td>L1ERC721Bridge</td><td>0xc175F4D16bc733CFeF79cce6584D76B2ba04Bf8b</td></tr><tr><td>L1ERC721BridgeProxy</td><td>0x939344ed5d20950a330D53f82C500216cBd51EA7</td></tr><tr><td>L1StandardBridge</td><td>0xeA42af0090F53dF2c4551a1bcA832Ff00B692C3D</td></tr><tr><td>L1StandardBridgeProxy</td><td>0x9C041e883BE0e3201524e7BA6f7A53B367b5CFb0</td></tr><tr><td>L2OutputOracle</td><td>0xC165A32ca806348ef212e2e17e6356219da4a8c8</td></tr><tr><td>L2OutputOracleProxy</td><td>0x38De75A13033364C985F2156307c2cAED0F7a109</td></tr><tr><td>Mips</td><td>0xE1Dd2CA3548bf1B045e47fc4Aaa1849BEBCD283E</td></tr><tr><td>OptimismMintableERC20Factory</td><td>0xfc7f635986ed11CB85534005b0058505085bC154</td></tr><tr><td>OptimismMintableERC20FactoryProxy</td><td>0x67a07E66F49D784f9896C793Ae2Fa877b43463b0</td></tr><tr><td>OptimismPortal</td><td>0x2d3a0326e956d507227829e8C65e41537156d7a7</td></tr><tr><td>OptimismPortal2</td><td>0x98a12Daa2e08bf7AE0cdF5DE5274E6E661886078</td></tr><tr><td>OptimismPortalProxy</td><td>0x66279763216C7ED5E1d17a174d80DAcBB94D4E06</td></tr><tr><td>PreimageOracle</td><td>0x0469411BBa019dCd6426b6fD887D45831D374BCD</td></tr><tr><td>ProtocolVersions</td><td>0x5cAa2aEeE361c7E048D6C23FB7B18e8908601f07</td></tr><tr><td>ProtocolVersionsProxy</td><td>0x6ea79E21188f2Af66881bb6F408C014C5cBD28d7</td></tr><tr><td>ProxyAdmin</td><td>0xf177c0CB4A84C3dFFEFcDE36F4519ef51Cf12f62</td></tr><tr><td>SafeProxyFactory</td><td>0xa6B71E26C5e0845f74c812102Ca7114b6a896AB2</td></tr><tr><td>SafeSingleton</td><td>0xd9Db270c1B5E3Bd161E8c8503c55cEABeE709552</td></tr><tr><td>SuperchainConfig</td><td>0x5196A89AE040aE5e27385B47b4b19Eb83338b332</td></tr><tr><td>SuperchainConfigProxy</td><td>0x2E8A5AE5E428FF37846590afd2648FeF8D4987EE</td></tr><tr><td>SystemConfig</td><td>0x263CEf36F75046CE10a8737d2dcecaB2D1336421</td></tr><tr><td>SystemConfigProxy</td><td>0xBcD3aff8A93164EFeAd01ddE7b6f19781b19897b</td></tr><tr><td>SystemOwnerSafe</td><td>0x9114CF866E94bdEa0D99bC2D80b71c6D62044031</td></tr></tbody></table>


# Fees

## How do network fees on Swan Chain work?[​](https://docs.base.org/docs/fees#how-do-network-fees-on-base-work) <a href="#how-do-network-fees-on-base-work" id="how-do-network-fees-on-base-work"></a>

Every transaction on Swan Chain consists of two costs: an L2 (execution) fee and an L1 (security) fee. The L2 fee is the cost to execute your transaction on the L2, and the L1 fee is the estimated cost to publish the transaction on the L1. Typically the L1 security fee is higher than the L2 execution fee.

The L1 fee will vary depending on the amount of transactions on the L1. If the timing of your transaction is flexible, you can save costs by submitting transactions during periods of lower gas on the L1 (for example, over the weekend)

Similarly, the L2 fee can increase and decrease depending on how many transactions are being submitted to the L2. This adjustment mechanism has the same implementation as the L1.

For additional details about fee calculation on Swan Chain, please refer to the [op-stack developer documentation](https://community.optimism.io/docs/developers/build/transaction-fees/).

## How to Reduce Gas Fees on Swan Chain with MetaMask

When interacting with the Swan Chain mainnet, you might notice that gas fees can sometimes be higher than expected. This guide will walk you through the process of optimizing your MetaMask settings to significantly reduce these fees

### Step-by-Step Guide

#### 1. Initiate a Transaction

Begin by starting a transaction on the Swan Chain network. When the MetaMask window pops up, don't confirm it immediately.

#### 2. Edit the Estimated Fee

Look for an "Edit" button or link next to the estimated fee. Click on this to open the fee editing window.

<figure><img src="/files/c6hHxi6jA7zZgo09e9nn" alt="" width="375"><figcaption></figcaption></figure>

#### 3. Access Advanced Settings

In the fee editing window, find and click on the "Advanced" option. This will reveal more detailed gas fee settings.

<figure><img src="/files/ZEXMqS6gwAoXGePcCc5p" alt="" width="375"><figcaption></figcaption></figure>

#### 4. Adjust Gas Fee Parameters

Now, you'll see two important fields:

* **Max base fee (GWEI)**
* **Priority fee (GWEI)**

Set both of these values to **0.0015.**

<figure><img src="/files/GtdB3XBSCzgslIZZr1s6" alt="" width="375"><figcaption></figcaption></figure>

#### 5. Save as Default

This is a crucial step to save time in future transactions. Look for a checkbox that says something like "Save these values as my default for the Swan Chain network". Make sure to check this box.

#### 6. Confirm and Save

Click on the "Save" button to confirm your new settings.

#### 7. Complete the Transaction

Now, you can proceed with confirming your transaction. You should notice a significant reduction in the gas fee. You can also visit [swanscan.io](https://swanscan.io) to check your transaction fee.

<figure><img src="/files/43CV1VSgFekwM3BsdtWp" alt="" width="375"><figcaption></figcaption></figure>

### Results

After applying these settings, you should see a dramatic decrease in gas fees. For example:

* Before: Approximately $0.86 \*

  ```
  <figure><img src="../.gitbook/assets/O Transaction Fee.png" alt=""><figcaption></figcaption></figure>
  ```
* After: Approximately $0.25 \*

  ```
  <figure><img src="../.gitbook/assets/O Transaction Fee (1).png" alt=""><figcaption></figcaption></figure>
  ```

This represents a reduction of nearly two-thirds in gas costs!


# Introduction to Swan Chain

A Full Toolset AI Blockchain

SwanChain, initiated in 2021, is the first AI Super Chain dedicated to decentralized AI computing and development. Leveraging OP Super chain technology, Swan Chain integrates Web3 and AI by providing a comprehensive ecosystem that spans computing, storage, and AI applications. This includes specialized marketplaces for computing, storage, and AI agent applications, enabling seamless development, deployment, and scaling of AI models.

SwanChain harnesses underutilized computing power from a global network of community data centers, reducing costs by up to 70% and creating new opportunities to monetize idle resources. Its **AI Agent Market** and advanced toolsets, including inference and development tools, establish SwanChain as a premier AI cloud blockchain. By unifying decentralized infrastructure and AI innovation, SwanChain accelerates the adoption of AI, making development accessible, cost-efficient, and scalable. SwanChain’s mission is to redefine decentralized computing and drive innovation at the intersection of blockchain and artificial intelligence.

#### Core Objectives and Motivation

* **Decentralized AI Computing Market**: At the heart of Swan Chain's ambition is the creation of a marketplace that empowers AI developers with the necessary computational resources for training and deploying sophisticated AI models on AI platforms like [Lagrange](https://lagrange.computer/). This initiative is designed to fill the void between the high demand for premium computing in AI research and the resources available within the blockchain ecosystem.
* **Support for Web3 Projects**: Swan Chain acknowledges the transformative essence of Web3 technologies, aspiring to lay down a foundational infrastructure that underpins the deployment and functioning of decentralized applications (DApps). This includes a suite of decentralized storage solutions, computing power, and ancillary services, all aimed at propelling the decentralized web's expansion.
* **Innovative Ecosystem Products**: The ecosystem of Swan Chain is augmented with groundbreaking products like[ MultiChain.storage](https://www.multichain.storage) for decentralized data storage, the [Lagrange](https://lagrange.computer/) platform for decentralized computing, and a Decentralized Task Orchestrator, which collectively streamline the management and distribution of computing tasks across the network.
* **Universal Basic Income (UBI) Model**: A standout feature of Swan Chain is its commitment to fostering a fair and equitable ecosystem via the implementation of a UBI model for computing providers. This innovative approach guarantees compensation for participants' contributions, promoting inclusivity and sustainability within the network.

#### Enhanced Technologies and Infrastructure

Swan Chain incorporates state-of-the-art technologies to materialize its ambitious objectives:

* **Kubernetes and Blockchain Integration**: Utilizing Kubernetes for container orchestration alongside blockchain for securing transactions and automating processes, Swan Chain establishes a highly efficient, scalable, and secure infrastructure for decentralized computing.
* **Global Data Center Connectivity**: By orchestrating data centers globally, Swan Chain accesses an expansive pool of computational resources, ensuring utmost availability and redundancy for its services.
* **Zero-Knowledge (ZK) Proofs**: Emphasizing security and privacy, Swan Chain adopts ZK proofs for the benchmarking of computing providers and facilitating privacy-preserving transactions within its ecosystem.

#### Swan 2.0: Inference Cloud

Swan Chain is evolving into a **market-driven AI inference marketplace** with [Swan 2.0](https://github.com/swanchain/docs/blob/main/core-concepts/swan-2.0-inference-cloud.md). Building on the network bootstrapped by UBI, Swan 2.0 introduces:

* **Decentralized AI Inference**: An [Inference Marketplace](/core-concepts/market-provider/inference-marketplace) connecting consumers with GPU providers through a WebSocket-based coordination layer and an OpenAI-compatible API (`/v1/chat/completions`, `/v1/embeddings`, etc.)
* **Dual Token Payments**: Consumers can pay with **stablecoins (USDC/USDT)** while providers earn both stablecoin revenue from inference requests and **SWAN token** rewards from contribution-based incentives
* **Contribution-Based Rewards**: A merit-based scoring system replacing UBI, where providers earn proportionally to inference volume, token throughput, uptime, quality, and model diversity
* **Unified Computing Provider Role**: ECP and FCP roles merge into a single Computing Provider (CP) classification, evaluated equally on contribution metrics

{% hint style="info" %}
**Try Swan Inference**: <https://inference.swanchain.io> — 42+ AI models available via a single API key.
{% endhint %}

#### Vision and Future Outlook

Swan Chain is steadfast in its mission to redefine the development, deployment, and scaling of AI and Web3 projects. By offering accessible, secure, and high-performance computing resources, coupled with innovative payment solutions and a ZK computing market, Swan Chain addresses the extant challenges faced by developers and businesses. The platform's dedication to a sustainable and equitable ecosystem, highlighted by its UBI model and the evolution toward market-driven economics in Swan 2.0, paves the way for how decentralized networks can prioritize community welfare and participation.

<figure><img src="/files/qipyDhZ4hmlbqVRzumsu" alt=""><figcaption><p>Layer1, Layer2,Layer3</p></figcaption></figure>

#### Roadmap

{% embed url="<https://gist.github.com/flyworker/9822afc8d7ca236694926bf373008cdc#file-swanroadmap-md>" %}

## Protocol Stack

Cross Chain Computing Protocol

Swan Chain is designed as a full toolset AI Blockchain infrastructure, providing comprehensive solutions across storage, computing, bandwidth, and payments. The protocol stack is a multi-layered architecture that ensures efficient and secure operations within the Swan Chain ecosystem. Below is an overview of each layer in the protocol stack:

### Protocol Layers <a href="#protocol-layers" id="protocol-layers"></a>

<figure><img src="https://docs.swanchain.io/~gitbook/image?url=https%3A%2F%2F3478205236-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FcvUWH8GhRCqvKwuN0BGF%252Fuploads%252Fium2XF6W9oavSZkh3Ze7%252Fimage.png%3Falt%3Dmedia%26token%3Db5526658-f740-432a-8c5f-27ef458328a7&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=c0b8a498&#x26;sv=1" alt=""><figcaption></figcaption></figure>

1. [Consensus Layer](/core-concepts/cross-chain-contracts)—responsible for smart contract execution and payment settlement.
2. [Peer-to-peer (P2P) Network](/core-concepts/peer-to-peer-p2p-network)—defines how nodes locate and connect.
3. [Payment Channels ](/core-concepts/payment-channels)—facilitates fast and low-cost payments in the system.
4. [Service Discovery](/core-concepts/service-discovery) – Server nodes and reputation module for public service
5. [Market Provider](/bulders/market-provider) - Entity that offers various computing and storage tasks to the network
6. [Storage Layer ](/core-concepts/storage-layer)— data stored on public blockchains or content addressable networks.
7. [Computing Layer ](/core-concepts/computing-layer)— how a query is routed to a specific node for computing.
8. [CDN Layer](/core-concepts/cdn-layer) – how data is distributed and hosted on the global network
9. [Governance](/core-concepts/token/governance) —manages schemas, treasure, and disputes.

A Sample implication of Protocol

<figure><img src="https://docs.swanchain.io/~gitbook/image?url=https%3A%2F%2Fcontent.gitbook.com%2Fcontent%2FcvUWH8GhRCqvKwuN0BGF%2Fblobs%2FRsqtyApwksWlUQOPFbhe%2Fimage.png&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=913d832f&#x26;sv=1" alt=""><figcaption></figcaption></figure>


# Swan 2.0: Inference Cloud

Decentralized AI Inference Marketplace — Swan Chain's Next Evolution

## Overview

Swan 2.0 marks Swan Chain's evolution from a UBI-subsidized computing network into a **market-driven AI inference marketplace**. Built as the Inference Cloud, it connects AI model consumers with GPU providers through a decentralized coordination layer, enabling anyone to access AI models via a single API key — or earn stablecoin revenue by sharing their GPU resources.

{% hint style="info" %}
**Try Swan Inference**: <https://inference.swanchain.io>

**New here?** See [How to Use Swan Inference](/core-concepts/swan-2.0-inference-cloud/how-to-use) for a step-by-step guide, or jump to [live pricing comparison](https://inference.swanchain.io/pricing) against Anthropic, Google, and OpenRouter.

Swan 2.0 replaces UBI with inference revenue per [SIP-003](https://github.com/swanchain/governance/discussions/21). UBI tapers to zero over 3 months. See also [SIP-002](https://github.com/swanchain/governance/discussions/16) for the original transition proposal.
{% endhint %}

## What Changes in Swan 2.0

| Aspect                    | Swan 1.0 (UBI Model)      | Swan 2.0 (Inference Cloud)                              |
| ------------------------- | ------------------------- | ------------------------------------------------------- |
| **Provider Rewards**      | Flat UBI sampling         | 95% inference revenue (stablecoins)                     |
| **Payment**               | SWAN tokens only          | Stablecoins (USDC/USDT) + Pay-with-SWAN (20% discount)  |
| **Provider Roles**        | Separate ECP and FCP      | Unified Computing Provider (CP)                         |
| **Collateral**            | SWAN tokens only          | SWAN tokens or Stripe (credit card)                     |
| **Work Verification**     | Random sampling tasks     | Periodic benchmarks (math, code, latency)               |
| **Workloads**             | Training, ZK proofs       | AI inference (LLM, image, audio, embedding, multimodal) |
| **Hardware Requirements** | None (any GPU earned UBI) | Tiered: min 8GB VRAM, legacy GPUs rejected              |

## Architecture

Swan Inference uses a hub-and-spoke architecture where the central platform coordinates between consumers and providers:

```
┌─────────────────────────────────────────────────────────────────┐
│                    External Consumers                            │
│              (Meganova AI, LiteLLM, Direct API)                 │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                      SWAN INFERENCE                              │
│  ┌─────────────────┐          ┌─────────────────────────────┐   │
│  │  REST API        │          │  WebSocket Hub              │   │
│  │  (Port 8100)     │─────────▶│  (Port 8081)                │   │
│  │                  │          │  - Provider connections      │   │
│  │  /api/v1/*       │          │  - Inference dispatch        │   │
│  │  /v1/* (OpenAI)  │          │  - Load balancing            │   │
│  │                  │          │  - Health monitoring          │   │
│  └─────────────────┘          └─────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────┘
                    │                         │
                    ▼ WebSocket               ▼ HTTP (fallback)
┌───────────────────────────────┐  ┌─────────────────────────────┐
│      GPU Providers            │  │   External Endpoints         │
│  (H100, A100, 4090, 3090)    │  │   (vLLM, TGI, OpenAI API)   │
└───────────────────────────────┘  └─────────────────────────────┘
```

**Request Flow:**

1. Consumer sends a request to the REST API
2. The Hub checks for available WebSocket providers
3. If WebSocket providers are available: route via WebSocket (primary path)
4. If no WebSocket providers: route to External Endpoints (fallback)
5. Response includes `X-Swan-Connection-Mode` header indicating which route was used

### Key Components

| Component               | Role                                                               |
| ----------------------- | ------------------------------------------------------------------ |
| **REST API**            | OpenAI-compatible consumer-facing API                              |
| **WebSocket Hub**       | Real-time provider connections, inference dispatch, load balancing |
| **Marketplace Service** | Model catalog, search, pricing                                     |
| **Payment Ledger**      | Off-chain usage tracking, invoicing                                |
| **Benchmark Sampler**   | Periodic quality checks and scoring                                |
| **Settlement Batcher**  | On-chain settlement via MerkleDistributor                          |

## OpenAI-Compatible API

Swan Inference provides a drop-in replacement for OpenAI's API. Any existing OpenAI SDK or integration works with Swan Inference by changing the base URL and API key.

### Supported Endpoints

| Endpoint                   | Description                                      |
| -------------------------- | ------------------------------------------------ |
| `/v1/chat/completions`     | Chat-based text generation (streaming supported) |
| `/v1/embeddings`           | Text embeddings                                  |
| `/v1/images/generations`   | Image generation                                 |
| `/v1/audio/transcriptions` | Audio-to-text transcription                      |
| `/v1/models`               | List available models                            |

### Example Request

```bash
curl https://inference.swanchain.io/v1/chat/completions \
  -H "Authorization: Bearer sk-swan-YOUR-KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-r1-distill-llama-70b",
    "messages": [{"role": "user", "content": "Hello!"}]
  }'
```

## Model Catalog

Swan Inference serves two categories of models with different economics. The live catalog at [inference.swanchain.io/models](https://inference.swanchain.io/models) is the source of truth for current availability and pricing.

### Frontier Gateway

Closed frontier models (Claude, Gemini) proxied at a consistent discount to direct API pricing. These run on the upstream provider's infrastructure — Swan acts as an aggregator, passing on cost savings through bulk agreements and SWAN token incentives.

| Example          | Direct pricing               | Swan pricing   | Savings |
| ---------------- | ---------------------------- | -------------- | ------- |
| Claude Opus 4.6  | $5.00 / $25.00 per 1M tokens | $4.00 / $20.00 | \~20%   |
| Gemini 2.5 Flash | $0.30 / $2.50 per 1M tokens  | $0.18 / $1.50  | \~40%   |

With Pay-with-SWAN, the discount stacks to 50–66% below going direct. See the [pricing comparison](https://inference.swanchain.io/pricing) for the live side-by-side.

### Open-Source on Decentralized GPUs

Open-source models served by Swan's decentralized provider network. This is where Swan's economics structurally beat centralized providers — any qualifying GPU owner (datacenter to consumer hardware) can become a provider and share in inference revenue.

| Example           | Params  | Swan pricing                | Hardware tier |
| ----------------- | ------- | --------------------------- | ------------- |
| Qwen3 Coder 30B   | 30B MoE | $0.05 / $0.10 per 1M tokens | A (24GB)      |
| GLM 4.7 Flash     | —       | $0.05 / $0.36 per 1M tokens | A (24GB)      |
| Sapphira L3.3 70B | 70B     | $0.20 / $0.30 per 1M tokens | S (38GB+)     |
| Whisper Large v3  | —       | $0.003 per minute           | C (8GB+)      |

Open-source models are priced 50–66% below comparable centralized providers via the hardware tier system. See [Hardware Tiers](#hardware-tiers) under Provider Onboarding for the full VRAM-to-model mapping.

### Free Tier

| Parameter         | Specification                      |
| ----------------- | ---------------------------------- |
| Available Models  | Stheno 8B, Qwen3 8B (Tier B only)  |
| Daily Token Limit | 50,000 tokens (\~25 conversations) |
| Rate Limit        | 5 requests per minute              |
| Concurrency       | 1 simultaneous request             |
| Registration      | API key only (free, no KYC)        |
| Upgrade Path      | USDC top-up or Pay-with-SWAN       |

## Payment & Revenue Split

### Dual Deposit Options

Swan 2.0 accepts both stablecoins and SWAN as deposits into a single USD-denominated prepaid balance. SWAN deposits receive a **20% bonus in credits** at deposit time, creating organic buy pressure for the token.

| Deposit Method               | Bonus | Example (depositing $100) |
| ---------------------------- | ----- | ------------------------- |
| USDC/USDT (Stripe or crypto) | 0%    | $100 of credits           |
| SWAN on Swan Mainnet         | +20%  | $120 of credits           |

**Pay-with-SWAN flow:**

1. Consumer deposits SWAN tokens to their per-user deposit address on Swan Mainnet
2. Balance is credited in USD at the current SWAN/USD rate plus a 20% bonus
3. Subsequent inference requests draw from this unified USD balance
4. Providers receive 95% of the per-request fee in their preferred payout currency (USDC or SWAN)
5. 5% goes to the Growth Fund

### Provider-First Revenue Split (95/5)

During the bootstrap phase, Swan adopts an aggressive provider-first model to attract quality hardware:

| Recipient              | Share | Purpose                                                    |
| ---------------------- | ----- | ---------------------------------------------------------- |
| **Computing Provider** | 95%   | Direct payout in stablecoins (USDC/USDT)                   |
| **Growth Fund**        | 5%    | Provider recruitment, integrations, dev tooling, liquidity |
| Protocol Treasury      | 0%    | Deferred until network reaches sustainability threshold    |

The Growth Fund is reinvested into network expansion — provider onboarding bounties, DEX liquidity seeding, and integration grants. Spending is reported monthly with transaction hashes.

### Dynamic Revenue Split Schedule

As network revenue grows, the split adjusts through governance votes:

| Phase         | Daily Revenue    | Provider | Growth Fund  | Treasury |
| ------------- | ---------------- | -------- | ------------ | -------- |
| **Bootstrap** | < $100           | 95%      | 5%           | 0%       |
| Growth        | $100 – $1,000    | 90%      | 5%           | 5%       |
| Maturity      | $1,000 – $10,000 | 85%      | 3% + 2% burn | 10%      |
| Scale         | > $10,000        | 80%      | 2% + 3% burn | 15%      |

Each phase transition requires a governance vote with a 7-day voting period. Revenue thresholds are measured as a 30-day rolling average.

## Quality Assurance

### Benchmarks

The benchmark worker runs periodically (default: every 24 hours) to verify provider quality. Benchmark results expire after **30 days** — providers that miss benchmarks for 30+ days lose qualification and must re-benchmark to resume receiving traffic.

| Test                 | Pass Threshold |
| -------------------- | -------------- |
| **Math Accuracy**    | ≥ 50%          |
| **Code Generation**  | ≥ 50%          |
| **Response Latency** | ≤ 5000ms       |

### Slashing Conditions

| Condition                             | Consequence                                |
| ------------------------------------- | ------------------------------------------ |
| Benchmark failure (1st)               | Warning + 24h suspension from task routing |
| Consecutive failure (2nd)             | 10% collateral slashed                     |
| Consecutive failure (3rd)             | 30% collateral slashed + network removal   |
| Benchmark results expired (> 30 days) | Loses qualification until re-benchmarked   |
| Inference success rate < 80%          | Deprioritized in request routing           |
| Uptime < 90% (30-day rolling)         | Deprioritized in request routing           |

{% hint style="info" %}
**New Provider Grace Period:** Providers registered within the last 7 days are exempt from uptime and success-rate deprioritization. This gives new providers time to build history without being penalized for insufficient data. Benchmark requirements and probation still apply during the grace period.
{% endhint %}

### Health Monitoring

* **Automatic health checks** with configurable thresholds for WebSocket and external endpoints
* **Circuit breaker** to prevent cascading failures
* **Load balancing** with health-aware routing (round-robin, least-connections, or health-aware strategies)
* **Model warmup** to pre-load models and reduce cold-start latency

### Provider Leaderboard

Providers are ranked by a performance-based leaderboard using availability metrics, success rates, and latency.

## Provider Onboarding

### Hardware Tiers

To receive inference traffic and earn revenue, providers must meet minimum hardware requirements:

| Tier      | Min VRAM        | Example Hardware          | Models               | Status                   |
| --------- | --------------- | ------------------------- | -------------------- | ------------------------ |
| **S**     | 38GB+           | L40S, A100, H100          | 70B premium models   | Recruiting new providers |
| **A**     | 24GB            | RTX 4090, 3090, A6000     | 24B–32B agent models | Activate idle inventory  |
| **B**     | 12GB            | RTX 4070 Ti, 3080 Ti      | 8B–12B free tier     | Some current providers   |
| **C**     | 8GB             | RTX 3070, 4060            | Embedding, Whisper   | Lowest qualifying tier   |
| **macOS** | 16GB+ unified   | Apple Silicon M1/M2/M3/M4 | 8B–12B via Ollama    | Entry-level providers    |
| Rejected  | < 8GB or legacy | TESLA P4, GTX 1050 Ti     | None                 | No rewards               |

Legacy GPUs (TESLA P4, GTX 1050 Ti) served the network well during the ZK-task era but cannot serve AI inference workloads at acceptable quality.

{% hint style="info" %}
**macOS Support:** Apple Silicon Macs can serve as providers using Ollama as the inference backend. While datacenter GPUs offer higher throughput, Macs are a low-friction entry point for new providers — no Docker, NVIDIA drivers, or Linux required.
{% endhint %}

### Requirements

**Linux (NVIDIA GPU):**

* GPU meeting at least Tier C requirements (≥ 8GB VRAM)
* Docker 24.0+ with NVIDIA Container Toolkit
* Inference server: SGLang (recommended), vLLM, or Ollama

**macOS (Apple Silicon):**

* Apple Silicon Mac (M1/M2/M3/M4) with 16GB+ unified memory
* Ollama installed (`brew install ollama`)

**Both platforms:**

* Swan's `computing-provider` agent installed
* No public IP, domain, or SSL setup required — providers connect via WebSocket behind NAT/firewall
* Pass initial inference benchmark (math, code, latency)
* Maintain > 50% uptime over a trailing 7-day window

### Registration Flow

1. **Sign up** at the [Swan Inference dashboard](https://inference.swanchain.io/provider-signup) and get a provider API key (`sk-prov-*`)
2. **Start a model server** — SGLang/vLLM (Linux) or Ollama (macOS)
3. **Install and run** the `computing-provider` agent — the setup wizard auto-discovers your models
4. **Pass benchmarks** — automated quality verification runs within minutes of connecting
5. **Admin approval** — most providers are approved within 24 hours
6. **Deposit collateral** via Stripe (credit card) or SWAN tokens on-chain
7. **Start earning** — receive inference requests with a 7-day grace period for full traffic priority

### Collateral

Providers must deposit collateral to become active on the network. Two deposit methods are available:

| Method       | Currency                | Processing             | Refund                                           |
| ------------ | ----------------------- | ---------------------- | ------------------------------------------------ |
| **Stripe**   | Credit/debit card (USD) | Instant                | Refunded to original card (7-day waiting period) |
| **On-chain** | SWAN tokens             | Requires gas (SwanETH) | Returned to wallet (7-day waiting period)        |

See [Computing Provider Collateral](https://github.com/swanchain/docs/blob/main/core-concepts/swan-2.0-inference-cloud/token/computing-provider-collateral/README.md) for details on collateral amounts and the refund waiting period.

## On-Chain Settlement

Swan Inference uses a **MerkleDistributor** smart contract for gas-efficient batch settlement:

1. The platform aggregates provider earnings into daily settlement batches
2. A Merkle tree is computed from all provider balances
3. The Merkle root is submitted on-chain
4. Providers claim their earnings by submitting a Merkle proof

This approach minimizes gas costs by settling many provider payments in a single on-chain transaction.

### Smart Contracts

| Contract               | Address (Swan Chain Mainnet)                 |
| ---------------------- | -------------------------------------------- |
| **ProviderCollateral** | `0x557f306f917009cf83c32b8b32a79202e79948e5` |
| **SWAN Token**         | `0xAF90ac6428775E1Be06BAFA932c2d80119a7bd02` |

{% hint style="info" %}
Swan Chain Mainnet operates on Chain ID **254** with RPC at `https://mainnet-rpc01.swanchain.io`. See [Network Info](https://github.com/swanchain/docs/blob/main/core-concepts/network-reference/readme/README.md) for full details.
{% endhint %}

## UBI Sunset (SIP-003)

Swan 2.0 eliminates UBI entirely per [SIP-003](https://github.com/swanchain/governance/discussions/21). Providers earn solely from inference revenue (95% of fees). The taper schedule:

| Period                             | UBI Level | SWAN/day | Notes                                             |
| ---------------------------------- | --------- | -------- | ------------------------------------------------- |
| Swan 2.0 Launch (Mar 16 – Apr 9)   | 100%      | 58,369   | Platform goes live, governance vote Apr 1–7       |
| Month 1 post-vote (Apr 10 – May 9) | 50%       | 29,185   | Contribution-weighted; legacy hardware earns zero |
| Month 2 post-vote (May 10 – Jun 9) | 20%       | 11,674   | Providers earn primarily from inference           |
| Month 3+ (Jun 10 onwards)          | **0%**    | 0        | UBI permanently off. Inference revenue only.      |

### Why Stop UBI

Under Swan 1.0, 75% of daily UBI went to providers with 0% uptime. SIP-003 redirects all incentives toward GPUs that actually serve inference. The breakeven where inference revenue matches the best current UBI payout is just **$25/day total network revenue**.

### Safety Valve

If the network cannot sustain minimum viable provider economics ($50/day revenue) by Month 3, governance can vote to extend UBI at 25% (contribution-weighted only) for 3 additional months.

## SWAN Token Utility

After UBI stops, SWAN token utility is:

| Utility                 | Description                                                         |
| ----------------------- | ------------------------------------------------------------------- |
| **Pay-with-SWAN**       | 20% inference discount for consumers — creates organic buy pressure |
| **Provider Collateral** | Required deposit to join the network                                |
| **Governance**          | Vote on protocol parameters, revenue splits, and phase transitions  |

## Learn More

* [**Inference Marketplace**](https://github.com/swanchain/docs/blob/main/core-concepts/swan-2.0-inference-cloud/market-provider/inference-marketplace.md) — How the marketplace works: pricing, routing, and settlement
* [**Computing Provider Income**](https://github.com/swanchain/docs/blob/main/core-concepts/swan-2.0-inference-cloud/token/swan-provider-income.md) — Contribution score formula and reward distribution
* [**Computing Provider Collateral**](https://github.com/swanchain/docs/blob/main/core-concepts/swan-2.0-inference-cloud/token/computing-provider-collateral/README.md) — Collateral requirements and slashing
* [**SIP-001: FCP Subsidy Program**](https://github.com/swanchain/governance/discussions/11) — Stage 1 funding for computing providers
* [**SIP-002: Unified CP & Contribution Rewards**](https://github.com/swanchain/governance/discussions/16) — Original transition proposal
* [**SIP-003: Inference Cloud Economics**](https://github.com/swanchain/governance/discussions/21) — Full model catalog, 95/5 revenue split, UBI sunset, Pay-with-SWAN


# How to Use

Step-by-step guide to using Swan 2.0 Inference Cloud as a consumer

This guide walks through using Swan Inference as a developer consuming AI models — starting with a no-signup trial, then creating an account, topping up, and making real API requests.

{% hint style="info" %}
Looking to earn by providing GPU resources instead? See [Become a Provider](/core-concepts/swan-2.0-inference-cloud/become-a-provider) for the step-by-step setup guide.
{% endhint %}

## 0. Try it now — no signup

The fastest way to see Swan Inference in action: open the [playground](https://inference.swanchain.io/playground), pick a model, and send a message. No account, no API key, no credit card.

<figure><img src="/files/hKcQQjnBR1cXoKhUtD0u" alt="Swan Inference playground"><figcaption><p>Playground — runs GLM 4.7 Flash for anonymous visitors, rate-limited per IP.</p></figcaption></figure>

Ready for more? Sign up below to get an API key and start integrating.

## 1. Sign up and get your API key

Create a free account at [inference.swanchain.io/signup](https://inference.swanchain.io/signup) — email and password only, no credit card required.

<figure><img src="/files/PoFZpvoDC41m15T0hujE" alt="Swan Inference signup form"><figcaption><p>Sign up with email and password.</p></figcaption></figure>

After signing up, navigate to **Keys** in the dashboard. Your API key (`sk-swan-*`) is generated automatically — copy it and keep it secret.

<figure><img src="/files/SPLYnxTy2dQTZAufRInq" alt="Dashboard showing API key"><figcaption><p>Your API key appears under Keys in the dashboard.</p></figcaption></figure>

## 2. Top up credits

Inference requests are paid per token, deducted from your account balance in real time. Fund your account via Stripe (credit card) or crypto deposit (USDC / USDT / SWAN on multiple EVM chains).

* **Stripe:** instant processing, minimum deposit $5
* **Crypto:** per-user HD-derived deposit address shared across EVM chains, minimum $1

<figure><img src="/files/Yj6bE7oAxaBdQxLdkBMn" alt="Deposit credits via Stripe or crypto"><figcaption><p>Add funds via Stripe card payment or crypto deposit.</p></figcaption></figure>

### 20% bonus when depositing SWAN

Depositing SWAN tokens on Swan Mainnet credits your account with a **20% bonus on top of the USD value** — $100 of SWAN becomes $120 of credits. Your account balance is a single USD-denominated pool regardless of how it was funded, so there's nothing special to toggle at request time; you simply get more credits per dollar when you deposit SWAN.

Combined with Swan's already-lower per-token pricing, the deposit bonus pushes effective rates roughly 50–66% below going direct to Anthropic or Google for comparable models. Flip the **Pay with: SWAN** toggle on the [pricing page](https://inference.swanchain.io/pricing) to see the effective rate across every model.

<figure><img src="/files/YioXj73ePS4Jn3UQxAOW" alt="Pay-with-SWAN toggle on pricing page"><figcaption><p>Flip the Pay-with toggle to SWAN to preview the effective rate after the 20% deposit bonus.</p></figcaption></figure>

Usage is deducted from your balance per request. View balance, usage, and the transaction ledger under **Billing** in the dashboard.

## 3. Browse models

The [Models page](https://inference.swanchain.io/models) lists every available model with live pricing, context length, and provider count. Click any model for details and code examples.

<figure><img src="/files/HICZSdvP5QIDQ2gsjTPO" alt="Swan Inference models catalog"><figcaption><p>Live models catalog.</p></figcaption></figure>

The [Pricing page](https://inference.swanchain.io/pricing) compares SwanChain's rates side-by-side against Anthropic, Google, OpenRouter, and other providers for hero models — so you can see how prices stack up at a glance.

<figure><img src="/files/FNguey3R4hBRlVWYfnze" alt="Swan Inference pricing comparison"><figcaption><p>Pricing page with competitor comparison.</p></figcaption></figure>

## 4. Make your first inference request

Swan Inference is fully OpenAI-compatible — any existing OpenAI SDK or integration works by changing two things: the base URL and the API key. The examples below use `zai-org/GLM-4.7-Flash`, one of the cheapest hero models at $0.05 input / $0.36 output per 1M tokens.

### curl

```bash
curl https://inference.swanchain.io/v1/chat/completions \
  -H "Authorization: Bearer sk-swan-YOUR-KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "zai-org/GLM-4.7-Flash",
    "messages": [{"role": "user", "content": "Say hello in 5 words."}]
  }'
```

### OpenAI Python SDK

```python
from openai import OpenAI

client = OpenAI(
    base_url="https://inference.swanchain.io/v1",
    api_key="sk-swan-YOUR-KEY",
)

response = client.chat.completions.create(
    model="zai-org/GLM-4.7-Flash",
    messages=[{"role": "user", "content": "Say hello in 5 words."}],
)
print(response.choices[0].message.content)
```

### OpenAI Node.js SDK

```javascript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://inference.swanchain.io/v1",
  apiKey: "sk-swan-YOUR-KEY",
});

const response = await client.chat.completions.create({
  model: "zai-org/GLM-4.7-Flash",
  messages: [{ role: "user", content: "Say hello in 5 words." }],
});
console.log(response.choices[0].message.content);
```

Streaming, embeddings, image generation, and audio transcription all work identically to OpenAI. See [OpenAI-Compatible API](/core-concepts/swan-2.0-inference-cloud#openai-compatible-api) for the full endpoint list.

## Next steps

* [**Inference Marketplace**](/core-concepts/market-provider/inference-marketplace) — deeper on how pricing, routing, and settlement work
* [**Become a Provider**](/core-concepts/swan-2.0-inference-cloud/become-a-provider) — want to earn by sharing GPU resources instead?
* [**API reference**](https://inference.swanchain.io/docs) — full list of endpoints, parameters, and error codes

Questions? Reach the team on [Discord](https://discord.gg/swanchain) or open an issue on [GitHub](https://github.com/swanchain).


# Become a Provider

Step-by-step guide to becoming a GPU Computing Provider on Swan 2.0 Inference Cloud

This guide walks through turning your GPU into an AI inference endpoint on Swan Chain — from starting a local model server, to installing the `computing-provider` agent, to earning stablecoin revenue from real inference traffic.

{% hint style="info" %}
Looking to **consume** models instead of provide? See [How to Use Swan Inference](/core-concepts/swan-2.0-inference-cloud/how-to-use).

For hardware tiers, collateral economics, revenue splits, and slashing rules, see the [Provider Onboarding](/core-concepts/swan-2.0-inference-cloud#provider-onboarding) section of the Swan 2.0 overview. This page focuses on the hands-on setup.
{% endhint %}

## 0. Check prerequisites

Providers connect **outbound** to Swan Inference over WebSocket — **no public IP, domain, or SSL setup is required**. You just need a capable GPU and one of two supported OS/inference-engine stacks:

| Platform                  | Minimum hardware                                           | Inference engine                                                               |
| ------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------ |
| **Linux (NVIDIA)**        | GPU with ≥ 8 GB VRAM (Tier C); 24 GB+ recommended (Tier A) | [SGLang](https://github.com/sgl-project/sglang) (recommended), vLLM, or Ollama |
| **macOS (Apple Silicon)** | M1/M2/M3/M4 with ≥ 16 GB unified memory                    | [Ollama](https://ollama.com)                                                   |

Legacy GPUs (TESLA P4, GTX 1050 Ti, anything < 8 GB VRAM) cannot serve modern inference workloads and will not receive traffic. Full tier-to-model mapping is in [Hardware Tiers](/core-concepts/swan-2.0-inference-cloud#hardware-tiers).

You'll also need:

* **Go 1.22+** to build the `computing-provider` agent
* **Docker 24.0+ with the NVIDIA Container Toolkit** (Linux only)
* A funded wallet or credit card for collateral (step 5)

## 1. Start a model server

Your GPU needs an OpenAI-compatible inference server running locally. Swan Inference will route requests to it via the `computing-provider` agent.

### Linux (NVIDIA) — SGLang

```bash
# Download model weights from HuggingFace
computing-provider models download Qwen/Qwen2.5-7B-Instruct

# Start SGLang serving the model on port 30000
docker run -d --gpus all -p 30000:30000 --ipc=host --name sglang \
  -v ~/.swan/models/Qwen/Qwen2.5-7B-Instruct:/models \
  lmsysorg/sglang:latest \
  python3 -m sglang.launch_server --model-path /models \
    --host 0.0.0.0 --port 30000 \
    --served-model-name Qwen/Qwen2.5-7B-Instruct
```

Verify it's healthy: `curl http://localhost:30000/v1/models`.

### macOS (Apple Silicon) — Ollama

```bash
brew install ollama
ollama serve &
ollama pull qwen2.5:7b
```

Verify it's healthy: `curl http://localhost:11434/api/tags`.

{% hint style="info" %}
The quickstart uses Qwen 2.5 7B as an example, but earnings scale with real token traffic. Browse the [model catalog](https://inference.swanchain.io/models) to find in-demand models with less provider competition.
{% endhint %}

## 2. Install the computing-provider agent

Clone and build from source (mainnet):

```bash
git clone https://github.com/swanchain/computing-provider.git
cd computing-provider
make clean && make mainnet && sudo make install

# Verify
computing-provider --version
```

Full install details including the NVIDIA Container Toolkit setup are in the [`computing-provider` README](https://github.com/swanchain/computing-provider#readme).

## 3. Run the setup wizard

The wizard creates your provider account (or logs you into an existing one), auto-discovers your running model server, and writes `config.toml` and `models.json`:

```bash
computing-provider setup
```

A typical run looks like this (macOS + Ollama):

```
============================================================
              Computing Provider Setup Wizard
============================================================


Step 1/5: Checking Prerequisites
------------------------------------------------------------
[ok] Ollama: ollama version is 0.14.1 (running)
[!] Docker: Docker not running. Please start Docker daemon. (optional - Ollama available)
[ok] GPU: Apple Silicon (Apple M1)

Step 2/5: Initializing Configuration
------------------------------------------------------------

Node Name [demo-provider]: demo-provider
Initialized CP repo at '/Users/swanchain/.swan/computing'.
[ok] Configuration initialized

Step 3/5: Authentication
------------------------------------------------------------

A Swan Inference account is needed to connect your provider to the network.
Do you already have a Swan Inference account [y/N]: n

Create a new Swan Inference account
Email: demo-provider@example.com
Password:

Creating account...
[ok] Account created!

Set up your provider profile
Provider Name [demo-provider]:

Wallet Address (optional, press Enter to skip):
-> Skipped - you can add a wallet later to start earning rewards

Registering your provider...
[ok] Provider registered!
-> Provider ID: 84bca13d-d056-4826-a1ca-ac4d43597a9c
-> Status: pending (your provider will be reviewed before it can earn rewards)

[!] SAVE THIS API KEY - it connects your machine to Swan Inference and is only shown once.

  API Key: sk-prov-535a****fb47

Step 4/5: Discovering Model Servers
------------------------------------------------------------
[ok] Found ollama at localhost:11434
  * qwen3:8b

Matching with Swan Inference models...
[ok]   qwen3:8b -> Qwen/Qwen3-8B (100%)

Step 5/5: Finalizing Setup
------------------------------------------------------------

Select models to enable:

  1) Qwen/Qwen3-8B - ollama @ http://localhost:11434  ~16GB  (local: qwen3:8b)
Enter selections (e.g., 1,3,4) or press Enter for all [all]:
[ok] Updated config.toml
[ok] Created models.json

============================================================
                      Setup Complete!
============================================================

What to do next:
  * Start your provider:  computing-provider run
  * Monitor in browser:   computing-provider dashboard
  * Check connection:     computing-provider inference status
```

**Save the `sk-prov-*` key** — it's shown once and authenticates this provider to the network.

If you already have a `sk-prov-*` key (for example, from the web signup at [inference.swanchain.io/provider-signup](https://inference.swanchain.io/provider-signup)), pass it directly:

```bash
computing-provider setup --api-key=sk-prov-xxxxxxxxxxxx
```

Config files land in `~/.swan/computing/`:

* `config.toml` — WebSocket URL, API key, node name
* `models.json` — mapping from Swan Inference model IDs to your local endpoints

{% hint style="info" %}
Consumer keys (`sk-swan-*`) and provider keys (`sk-prov-*`) are different. The `computing-provider` agent only accepts `sk-prov-*` keys.
{% endhint %}

### Configuration reference

The wizard writes sensible defaults, but if it failed to discover your model server, you run a non-standard port, or you want to serve multiple models, edit these files directly.

**Provider config (`~/.swan/computing/config.toml`)**

```toml
# ~/.swan/computing/config.toml

[API]
Port = 8085
MultiAddress = "/ip4/<PUBLIC_IP>/tcp/<PORT>"
NodeName = "<YOUR_CP_Node_Name>"

[RPC]
SWAN_CHAIN_RPC = "https://rpc-proxima.swanchain.io"

[Inference]
Enable = true
WebSocketURL = "wss://api-ws-dev.swanchain.io"
ApiKey = "sk-prov-YOUR_API_KEY"
Models = ["Qwen/Qwen2.5-7B-Instruct"]
```

**Model endpoints (`~/.swan/computing/models.json`)**

```json
{
  "Qwen/Qwen2.5-7B-Instruct": {
    "endpoint": "http://localhost:30000",
    "gpu_memory": 16000,
    "category": "text-generation"
  },
  "meta-llama/Llama-3.2-3B-Instruct": {
    "endpoint": "http://localhost:11434",
    "gpu_memory": 14000,
    "category": "text-generation",
    "local_model": "llama3.2:3b"
  }
}
```

| Field         | Required | Description                                                              |
| ------------- | -------- | ------------------------------------------------------------------------ |
| `endpoint`    | Yes      | URL of your local inference server (SGLang, vLLM, Ollama)                |
| `gpu_memory`  | Yes      | GPU VRAM used by this model in MB                                        |
| `category`    | Yes      | Model type: `text-generation`, `image`, `embedding`, `audio`             |
| `local_model` | No       | Local model name if different from the key (e.g., Ollama's `qwen2.5:7b`) |
| `api_key`     | No       | API key if your model server requires authentication                     |

The keys in `models.json` must match valid Swan Inference model IDs. Run `computing-provider models catalog` or check the [model catalog](https://inference.swanchain.io/models) for the full list.

The agent watches `models.json` and hot-reloads on change — no restart needed. You can also force a reload:

```bash
curl -X POST http://localhost:8085/api/v1/computing/inference/models/reload
```

## 4. Start the provider and pass benchmarks

Run the agent:

```bash
nohup computing-provider run >> cp.log 2>&1 &
```

Then check your status:

```bash
computing-provider inference status
```

You'll move through these stages automatically:

```
Connect ──▶ Collateral ──▶ Approval ──▶ Active
(instant)   (see step 5)   (< 24 hrs)    (earning)
```

| Stage          | What happens                                                                                                     | Typical duration |
| -------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------- |
| **Connect**    | Agent opens a WebSocket to Swan Inference, registers your models, and auto-runs math / code / latency benchmarks | Instant          |
| **Collateral** | Deposit via Stripe or on-chain SWAN (step 5)                                                                     | Instant          |
| **Approval**   | Admin reviews your benchmark results and collateral                                                              | < 24 hours       |
| **Active**     | Traffic starts flowing — you earn per-request revenue                                                            | Ongoing          |

<figure><img src="/files/qAoby67boHHUdUqGiDUU" alt="Provider activation stages shown in the dashboard"><figcaption><p>The My Provider tab visualizes the activation flow: Start → Connect → Deposit Collateral → Approved → Active &#x26; Earning.</p></figcaption></figure>

## 5. Deposit collateral

Once approved, deposit collateral to unlock full traffic routing. Two options:

| Method       | Currency                    | Processing           | Refund                                      |
| ------------ | --------------------------- | -------------------- | ------------------------------------------- |
| **Stripe**   | Credit/debit card (USD)     | Instant              | 7-day waiting period, back to original card |
| **On-chain** | SWAN tokens on Swan Mainnet | Requires SwanETH gas | 7-day waiting period, back to your wallet   |

```bash
# Show instructions for your account (deposit address, minimum amount)
computing-provider inference deposit

# Verify deposit was seen on-chain
computing-provider inference deposit --check
```

<figure><img src="/files/aLg5t1momeRLxShBbUBM" alt="Provider collateral deposit panel"><figcaption><p>Provider dashboard's Collateral Deposit panel — verify your wallet, then pay the required amount via Stripe or on-chain crypto.</p></figcaption></figure>

Collateral amounts scale with hardware tier and earning multiplier. See [Computing Provider Collateral](/core-concepts/token/computing-provider-collateral) for the full table.

## 6. Monitor earnings and uptime

The Provider dashboard at [inference.swanchain.io/dashboard](https://inference.swanchain.io/dashboard) shows live earnings, request counts, and benchmark history.

<figure><img src="/files/uf2ZlKTtgHClOU993J18" alt="Provider earnings dashboard"><figcaption><p>Earnings dashboard with live request volume, per-model breakdown, and payout history.</p></figcaption></figure>

For a local view, the agent ships its own web dashboard:

```bash
computing-provider dashboard
# → http://localhost:3005
```

Set where payouts go:

```bash
computing-provider inference set-beneficiary 0xYourWalletAddress
```

{% hint style="info" %}
**New Provider Grace Period:** For the first 7 days after activation, uptime and success-rate deprioritization are waived. Use this window to stabilize your setup before full routing weight kicks in.
{% endhint %}

## Switching or adding models

Edit `~/.swan/computing/models.json` — the agent watches this file and hot-reloads without restarting. Start additional model servers on different ports and add them all to the JSON. Full walkthrough with multi-GPU pinning is in the [`computing-provider` README](https://github.com/swanchain/computing-provider#switching-models).

## Troubleshooting

| Symptom                                   | Fix                                                                                                                                                            |
| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `invalid provider API key`                | Verify key starts with `sk-prov-` and check `ApiKey` in `~/.swan/computing/config.toml`                                                                        |
| `WebSocket connection failed`             | Confirm outbound port 443 is open; URL must be `wss://` not `http://`                                                                                          |
| Provider online but no requests           | Model name mismatch — `--served-model-name` must exactly match the key in `models.json` and a model ID in the [catalog](https://inference.swanchain.io/models) |
| `could not select device driver "nvidia"` | Install the NVIDIA Container Toolkit; see [`computing-provider` README](https://github.com/swanchain/computing-provider#install-nvidia-container-toolkit)      |
| Stuck in `pending`                        | Provider needs collateral + passing benchmark + hardware check. Run `computing-provider inference status` to see which condition is missing                    |

Full troubleshooting catalog: [`computing-provider` README — FAQ](https://github.com/swanchain/computing-provider#faq).

## Next steps

* [**Provider Onboarding**](/core-concepts/swan-2.0-inference-cloud#provider-onboarding) — hardware tiers, revenue split, slashing rules
* [**Computing Provider Income**](/core-concepts/token/swan-provider-income) — contribution score formula and reward distribution
* [**Computing Provider Collateral**](/core-concepts/token/computing-provider-collateral) — required amounts and refund process
* [**Inference Marketplace**](/core-concepts/market-provider/inference-marketplace) — how pricing, routing, and settlement work under the hood

Questions? Reach the team on [Discord](https://discord.gg/swanchain) or open an issue on the [`computing-provider` repo](https://github.com/swanchain/computing-provider/issues).


# Provider Notice: Context-Window Integrity FAQ

> **TL;DR:** The context length shown next to your model in the marketplace is a promise to users. If your backend actually serves less (a smaller `num_ctx` / `--max-model-len`), long requests silently break — and the platform detects this. Check your backends today, and upgrade your computing-provider so your real window is reported automatically. Honest small windows are fully supported; misrepresented ones will be capped and can be penalized.

## Why am I reading this?

The marketplace displays each model's **catalog context length** (for example `131K`) on your Model Offerings page. If your backend really serves less, routing still assumes the displayed value — and what happens next depends on your serving engine. Both cases harm users:

* **vLLM / SGLang** — requests longer than `--max-model-len` are rejected with HTTP 400. Users get hard errors on prompts the marketplace said were supported, and every failure counts against your provider quality stats.
* **Ollama / llama.cpp** — worse: nothing fails visibly. When a prompt exceeds `num_ctx`, the runtime **silently discards half the context window** and answers from what remains. The request returns HTTP 200 with a confident answer computed from half of the user's input. Neither you nor the user gets any error signal.

## What should I do right now?

**1. Upgrade your computing-provider.** Recent versions automatically detect your backend's real context window (from vLLM/SGLang's `/v1/models` `max_model_len`) and report it to Swan Inference at registration and on every heartbeat. Once reported, the marketplace displays *your* real window and routing only sends you requests that fit it. For engines that don't expose a window (such as Ollama), set it manually in `models.json`:

```json
{
  "TheDrummer/Cydonia-24B-v4.3": {
    "endpoint": "http://localhost:11434",
    "gpu_memory": 16000,
    "category": "text-generation",
    "local_model": "cydonia:24b",
    "context_length": 32768
  }
}
```

**2. Check every backend's actual setting:**

| Engine | Setting to check                                |
| ------ | ----------------------------------------------- |
| vLLM   | `--max-model-len`                               |
| SGLang | `--context-length`                              |
| Ollama | `num_ctx` (Modelfile) / `OLLAMA_CONTEXT_LENGTH` |

**3. Do the VRAM math before promising a big window.** KV cache is what limits context. A rough rule for 20–30B models: about 80 KB per token at fp16 KV, half that with fp8/q8 KV quantization (`--kv-cache-dtype fp8` on vLLM, `OLLAMA_KV_CACHE_TYPE=q8_0` on Ollama). A 131k window needs roughly 10 GB of KV headroom *after weights* for a single request. If you don't have that, you cannot honestly serve 131k — declare what you can actually hold instead.

## How does the platform detect mismatches?

Two mechanisms:

1. **Truncation monitoring.** Your backend reports `usage.prompt_tokens` on every response. If it is far below the platform's own token estimate for the request, your backend truncated the input. This signature is unmistakable.
2. **Context verification challenges.** The audit system can send a recall-test prompt sized close to your displayed context: a marker at the start of the prompt that the model must repeat at the end. A truncating backend cannot pass, because truncation removes the marker.

## What are the consequences?

The enforcement sequence is designed so that honest providers are never hurt:

1. **First documented mismatch** → you receive a notice, and the displayed context for your offering is **capped to your measured window**. No penalty — users are simply no longer promised what you don't serve.
2. **Continued misrepresentation after notice** → collateral penalty under the standard slashing rules, with the standard appeal window.

**Serving a small context honestly is not an offense and never will be.** Declaring 32k costs you nothing except long-context traffic you couldn't have served correctly anyway. Only misrepresentation is penalized.

## Questions?

Contact the Swan Inference team via the provider dashboard or the usual support channels. If you believe a verification result is wrong, the appeal window applies to every penalty record.


# Consensus Layer

Smart contract execution and payment settlement

***

#### **Overview of the Consensus Layer**

The **Consensus Layer** is responsible for maintaining the integrity and security of the Swan Chain network by validating transactions, securing data, and ensuring consistency across the network. Swan Chain operates on a layered architecture that uses **Ethereum Layer 1** as the foundation for security and finality, while **Layer 2 (OP Stack)** handles scalability and off-chain processing.

#### **Key Components:**

1. **Layer 1 (L1) – Ethereum:**\
   Ethereum serves as the **base consensus layer** that provides security, data availability, and settlement. Swan Chain inherits Ethereum’s robust **Proof-of-Stake (PoS)** consensus mechanism, which ensures that all transactions and data processed on Layer 2 are secure and immutable.
2. **Layer 2 (L2) – Optimism OP Stack:**\
   The **OP Stack** is a modular Layer 2 framework that powers Swan Chain by enabling fast and low-cost transactions while leveraging Ethereum’s security for final settlement. It provides scalability through **Rollups**, which batch multiple transactions into a single one and post it on Ethereum, significantly reducing gas costs and improving throughput.
3. **Layer 3 (L3) – Application-Specific Chains (Optional):**\
   **Layer 3** can be introduced to handle more specialized functionalities, such as privacy, AI-specific workloads, or cross-chain interoperability. This layer builds on top of Layer 2, allowing developers to optimize and customize their applications without compromising security.

Here's a block table that outlines the different layers of Swan Chain's architecture, showing the role and functionality of each layer:

| **Layer**   | **Name**                        | **Functionality**                                                                                                      | **Key Features**                                                                                                                                                                                    |
| ----------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Layer 1** | **Ethereum (Base Layer)**       | Provides the foundational security, data availability, and finality for the entire Swan Chain network.                 | <p>- <strong>Security and Finality</strong> via Proof-of-Stake (PoS) consensus.<br>- <strong>Data Immutability</strong> on Ethereum's blockchain.<br>- Fraud-proof validation.</p>                  |
| **Layer 2** | **Optimism OP Stack (Scaling)** | Scales Swan Chain by handling off-chain computations, reducing gas fees, and increasing transaction speed.             | <p>- <strong>Scalability</strong> through Rollups.<br>- <strong>Fast Transactions</strong> with low latency.<br>- <strong>Low Gas Fees</strong> by batching transactions.</p>                       |
| **Layer 3** | **Application-Specific Layer**  | Provides custom solutions for specific use cases such as AI tasks, enhanced privacy, and cross-chain interoperability. | <p>- <strong>AI Optimization</strong> for task processing.<br>- <strong>Privacy Enhancements</strong> (e.g., Zero-Knowledge Proofs).<br>- <strong>Interoperability</strong> across blockchains.</p> |

***

#### **How Swan Chain Consensus Works:**

1. **Transaction Processing on Layer 2:**
   * Swan Chain’s computational tasks and transactions are processed on **Layer 2 (OP Stack)**, where they are batched and compressed using **Rollup technology**. This reduces computational costs and network congestion while increasing transaction speed.
   * The **Rollups** aggregate multiple transactions and submit them to Ethereum’s Layer 1 for finality and security.
2. **Security and Finality on Layer 1:**
   * After processing on Layer 2, transaction data is submitted to **Ethereum Layer 1**, where it is verified and stored for immutability.
   * Ethereum’s **Proof-of-Stake (PoS)** consensus mechanism ensures that Swan Chain transactions are cryptographically secure, tamper-proof, and finalized with strong guarantees of validity.
3. **Consensus Validation:**
   * Validators in the **Layer 1 network** are responsible for verifying the blocks and ensuring the security of the Swan Chain ecosystem. They confirm the validity of the transactions processed on Layer 2 and store them on Ethereum’s blockchain for long-term record-keeping.
4. **Multi-Layer Security:**
   * **Layer 2 Fraud Proofs:** To ensure the integrity of transactions processed on Layer 2, **fraud proofs** are implemented. If a malicious actor tries to submit an invalid transaction, other validators can challenge it, maintaining the security and reliability of the network.
   * **Data Availability Guarantees:** By leveraging Ethereum’s L1, Swan Chain benefits from Ethereum’s extensive network of validators and its inherent data availability, ensuring the network can scale without compromising data integrity.

***

#### **Benefits of the Swan Chain Consensus Layer:**

1. **Scalability:**
   * By utilizing **Optimism’s OP Stack**, Swan Chain achieves high throughput and low latency, making it suitable for **AI/ML workloads** and large-scale decentralized applications. The L2 Rollup mechanism significantly reduces gas costs while improving transaction speed.
2. **Security and Immutability:**
   * Transactions on Swan Chain are protected by **Ethereum’s PoS** consensus, ensuring that once a transaction is finalized, it is immutable and secure. This provides a strong security foundation for all decentralized applications running on Swan Chain.
3. **Cost Efficiency:**
   * **Layer 2 Rollups** allow multiple transactions to be bundled and posted on Layer 1, minimizing gas fees and making Swan Chain an affordable option for intensive AI computing tasks, model training, and decentralized applications.
4. **Flexibility with Layer 3:**
   * The option to introduce **Layer 3 chains** allows developers to create application-specific chains that optimize performance and security for their unique use cases, such as enhanced privacy, interoperability, or specialized AI processing.

***

***


# Peer-to-peer (P2P) Network

Peer-to-peer (P2P) networks can be used for both distributed storage and distributed computing, providing a robust and fault-tolerant solution for data storage and processing. By combining P2P distributed storage and computing, users can store large amounts of data and process it on the network without the need for a centralized server.

P2P distributed storage and computing systems can be used for a variety of applications, including scientific simulations, data analytics, and machine learning. These systems can also provide a high level of data redundancy and availability, making them a reliable solution for data storage and processing.

Examples of P2P distributed storage and computing systems include:

1. Golem: Golem is a decentralized computing network that allows users to rent their idle computing resources to others on the network. Golem uses a P2P network to distribute computational tasks across multiple nodes, enabling users to perform complex computational tasks without the need for a centralized server.
2. Filecoin: Filecoin is a decentralized storage network that allows users to rent their unused storage space to others on the network. Filecoin uses a P2P network to distribute data across multiple nodes, ensuring that data remains available even if some nodes go offline.
3. MaidSafe: MaidSafe is a decentralized network that provides both distributed storage and c

While P2P distributed storage and computing systems offer many benefits, they also come with some challenges, including security risks, slow retrieval times, and difficulties in managing and maintaining the network. Nonetheless, P2P distributed storage and computing remains an important area of research and development in the field of decentralized systems.


# Payment Channels

The **Swan Chain Payment Channels** are designed to provide an efficient, low-cost, and secure mechanism for payments between **clients** and **computing providers (CPs)** within the Swan Chain ecosystem. Leveging **smart contracts**, these channels enable seamless micropayments and larger transactions without requiring every individual payment to be processed directly on-chain, reducing costs and increasing scalability.

***

#### **Overview of Swan Chain Payment Channels**

Payment Channels allow clients and providers to exchange payments off-chain, which are only settled on-chain when the channel is closed. This approach reduces the need for each transaction to be processed on the blockchain, resulting in significant cost savings and increased transaction speed. **Swan Chain Payment Channels** operate within the ecosystem to pay for computing resources, AI model training, storage, and other services.

***

#### **How Payment Channels Work**

1. **Opening a Payment Channel:**
   * The client and computing provider open a **payment channel** by locking funds in a **smart contract**. The client locks a certain amount of **Swan tokens** will be used to pay for the services rendered by the provider.
   * This amount represents the **total prepaid balance** available for the provider, ensuring that the funds are reserved and can be released automatically upon completion of the job.
2. **Off-Chain Payments:**
   * Once the payment channel is established, the client and provider can make multiple payments off-chain without involving the blockchain for each transaction.
   * For each job (e.g., AI computation, data storage), the client sends a **signed payment update** to the provider, specifying the amount to be paid for that job. These signed updates are cryptographically secured but are not submitted on-chain until the channel is closed.
3. **Challenge Period:**
   * After the provider completes the job, a **challenge period** is triggered, during which the client can verify the quality and completion of the task.
   * If no disputes or challenges arise during this period, the payment update is considered valid, and the funds are automatically transferred from the client to the provider.
4. **Closing the Payment Channel:**
   * When the client or provider decides to close the payment channel, the **final state** (i.e., the total amount paid) is posted to the blockchain. This triggers the settlement process, where the remaining funds are returned to the client, and the provider is paid for all completed jobs.
   * Only the final transaction (closing the channel) is recorded on-chain, reducing transaction costs.
5. **Collateral and Slashing (In Case of Failure):**
   * If the provider fails to complete the job or the client raises a successful challenge, the provider’s **collateral** (locked in a **CPAccount**) is slashed, and the client is refunded for the incomplete job.

***

#### **Payment Channel Flow:**

| **Stage**                         | **Description**                                                                                                                                     |
| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| **1. Channel Opening**            | Client and provider open a channel by locking funds in a smart contract. These funds are used to pay for services over the duration of the channel. |
| **2. Off-Chain Payments**         | The client sends signed payment updates to the provider for each completed job. These transactions happen off-chain, reducing gas fees.             |
| **3. Job Completion & Challenge** | Upon job completion, a challenge period allows the client to verify the results. If no challenge is raised, payments proceed automatically.         |
| **4. Channel Closing**            | When the channel is closed, the final transaction is recorded on-chain, distributing the funds to the provider and refunding any remaining balance. |
| **5. Collateral Slashing**        | If the provider fails to complete the job, their collateral is slashed, and the client is refunded for the incomplete or faulty service.            |

***

#### **Key Features of Swan Chain Payment Channels**

1. **Cost-Efficiency:**
   * By conducting transactions off-chain and settling only the final payment on-chain, Swan Chain’s payment channels drastically reduce **gas fees** and **transaction costs**, making it ideal for frequent micropayments.
2. **Scalability:**
   * Payment channels allow for a large number of **transactions to occur off-chain**, making the system highly scalable and capable of handling many clients and providers with minimal blockchain congestion.
3. **Trustless and Automated Payments:**
   * Payments are secured through **smart contracts** and are only released after successful job completion, making the system **trustless** and ensuring fairness for both parties.
4. **Flexibility:**
   * **Multiple jobs** can be paid for through a single payment channel, and both small micropayments and larger transactions are supported. The payment channels can be closed when needed, providing flexibility in managing ongoing tasks and services.
5. **Security:**
   * All off-chain payment updates are cryptographically secured, and the final settlement is verified on-chain. Additionally, provider **collateral** ensures that providers are financially incentivized to complete their jobs correctly.

***

#### **Use Cases for Swan Chain Payment Channels**

1. **AI Computing and Model Training:**
   * Clients can pay providers for AI model training or inference tasks by submitting payments as jobs are completed, without incurring high transaction fees for each job.
   * Providers are guaranteed payment through the payment channel, allowing them to focus on delivering high-quality computational results.
2. **Decentralized Storage:**
   * Clients can store data on Swan Chain’s decentralized storage network and pay for storage space as they use it, without requiring frequent on-chain transactions.
   * Payment channels enable **real-time** payments for storage use, with the added security of smart contract guarantees.
3. **Streaming and Content Delivery:**
   * Content providers can use payment channels to collect payments for decentralized streaming services or content delivery, ensuring that payments are automated and gas fees are minimized.
4. **Recurring Payments for dApps:**
   * Payment channels are ideal for **subscription-based** services or decentralized applications (dApps) that require recurring payments, such as gaming, content access, or cloud services.

***

#### **How to Open and Use a Payment Channel on Swan Chain**

1. **Step 1: Open a Payment Channel**
   * Both the client and the provider agree to lock a certain amount of **Swan tokens** in the payment channel smart contract.
   * This locks the funds for the duration of the channel, ensuring that payments can be made without additional on-chain transactions.
2. **Step 2: Off-Chain Payments for Jobs**
   * As the provider completes jobs, the client sends **signed payment updates** to the provider. These payment updates reflect the amount owed for each task and are stored off-chain.
3. **Step 3: Verify Job Completion**
   * After the provider finishes a job, the client enters a **challenge period** to verify that the job was completed correctly.
   * If no challenges are raised, the payment update is accepted, and the funds are released from the payment channel.
4. **Step 4: Close the Payment Channel**
   * When either party wants to settle the account, they close the payment channel by submitting the final state of payments to the blockchain.
   * The smart contract automatically **settles the balance**, paying the provider and refunding any unused funds to the client.

***

#### **Benefits of Payment Channels for Clients and Providers**

1. **Clients:**
   * **Lower Fees:** By minimizing on-chain transactions, clients save on gas fees and can make multiple payments without the burden of high costs.
   * **Real-Time Payments:** Clients can pay for completed jobs in real-time, ensuring they only pay for what is delivered.
   * **Security:** Funds are locked in smart contracts, guaranteeing that payments are handled automatically and transparently.
2. **Providers:**
   * **Guaranteed Payment:** Providers are guaranteed payment for completed jobs through the payment channel system, reducing the risk of non-payment.
   * **Incentive to Complete Jobs:** Collateral mechanisms ensure that providers are financially incentivized to deliver high-quality results.


# Service Discovery

Discovery resource from multi chain Network

Decentralized service discovery is a key challenge in blockchain networks, where there is no central authority to manage or maintain a registry of services. In a decentralized system, service discovery needs to be performed by the nodes in the network themselves, without relying on any centralized infrastructure.

One approach to decentralized service discovery in blockchain networks is to use a peer-to-peer (P2P) network, where nodes can broadcast their services to other nodes in the network. This can be achieved using protocols such as the Kademlia distributed hash table (DHT), which allows nodes to store and retrieve data in a decentralized and fault-tolerant way.

In a blockchain network, nodes can register their services on the DHT, and other nodes in the network can discover these services by performing a lookup on the DHT. The DHT can also be used to store metadata about the services, such as the IP address and port number of the service endpoint.

Another approach to decentralized service discovery is to use a decentralized naming system, such as the Ethereum Name Service (ENS). ENS allows users to register human-readable names for their services, which can then be resolved to the corresponding service endpoint using the ENS resolver. ENS is built on top of the Ethereum blockchain, and provides a decentralized and censorship-resistant way to map domain names to service endpoints.

Overall, decentralized service discovery is an important challenge in blockchain networks, and requires innovative solutions to enable efficient and reliable discovery of services in a decentralized and trustless environment.


# Market Provider

#### Market Provider

A Market Provider (MP) in the Swan network is a crucial entity that offers various computing and storage tasks to the network. These tasks can range from storage tasks like dataset management, network tasks like CDN, to GPU tasks such as zk proofs or AI computations. MPs utilize the vast computing resources of Swan's decentralized community and, in return, can earn revenue through commissions or by issuing their own tokens based on the Swan network.

**Key Features of Market Providers:**

1. **Diverse Task Offerings**:
   * **Storage Tasks**: Handling datasets and ensuring efficient, secure storage solutions.
   * **Network Tasks**: Providing content delivery network (CDN) services to enhance data distribution.
   * **GPU Tasks**: Managing complex computations like zk proofs and AI model training.
2. **Utilizing Decentralized Resources**:
   * MPs leverage the distributed computing power of the Swan community, optimizing resource usage and ensuring high performance.
   * This decentralized approach reduces costs and enhances scalability.
3. **Revenue Generation**:
   * **Commissions**: MPs can earn commissions by facilitating various tasks on the network.
   * **Token Issuance**: MPs have the option to publish their own tokens based on the Swan network, creating additional revenue streams.

**Existing Market Providers:**

1. [**Swan Storage Market**](/bulders/storage-provider):
   * Specializes in decentralized storage solutions, managing large datasets and ensuring data integrity and availability.
2. [**Orchestrator AI Market**](/core-concepts/market-provider/decentralized-ai-computing-marketplace):
   * Focuses on AI tasks, providing the necessary infrastructure for training and deploying AI models.
3. [**ZK-UBI ZK Proofing Market**](/core-concepts/market-provider/indexing-and-caching-marketplace):
   * Handles Zero-Knowledge (ZK) proofs, supporting privacy-preserving computations and decentralized identity solutions.
4. [**Inference Marketplace**](/core-concepts/market-provider/inference-marketplace) (Swan 2.0):
   * Provides real-time AI inference through an OpenAI-compatible API, connecting consumers with GPU providers via WebSocket for low-latency model serving across 42+ AI models. Supports dual token payments (stablecoins + SWAN).

#### Advantages of Being a Market Provider:

1. **Access to a Decentralized Ecosystem**:
   * MPs can tap into Swan's extensive network of computing resources, enhancing their service offerings and operational efficiency.
2. **Flexible Revenue Models**:
   * By earning commissions or issuing tokens, MPs can create multiple revenue streams, ensuring financial sustainability and growth.
3. **Innovation and Expansion**:
   * MPs can continuously innovate by introducing new types of tasks and services, expanding their market reach and attracting a diverse user base.
4. **Community Engagement**:
   * MPs contribute to the growth and development of the Swan network, fostering a collaborative and thriving community.

By providing a wide range of tasks and utilizing decentralized resources, Market Providers play a pivotal role in the Swan network, driving innovation and ensuring efficient, scalable, and secure computing and storage solutions.


# Storage Market

[Swan Storage Market ](https://docs.filswan.com/swan-storage-market/overview)simplifies and optimizes the process of finding and utilizing decentralized storage on Filecoin. It addresses key challenges faced by users, such as lack of information on service quality, limited matching functionality, and high costs for beginners.

**Key Features:**

1. **Auction System**:
   * **Manual Bid**: Users can actively select storage providers based on specific criteria like bandwidth, storage capacity, and geographic location, and participate in an open public deal.
   * **Auto-Bid**: A reputation-based system where storage providers are automatically matched with users, ensuring fairness and efficiency.
2. **Transparency and Efficiency**:
   * Open and transparent matching system reduces the learning curve for users.
   * Ensures quick and efficient pairing of users and storage providers, promoting time-efficient storage and backup services.
3. **Task Management**:
   * Introduces the concept of "tasks" to manage and batch send multiple deals, simplifying the process of handling large datasets.
4. **Swan Provider**:
   * Runs on the same node as lotus miner nodes and assists in deal processing.
   * Requires authentication from the Filswan platform for better information sharing.
   * Provides a Restful API interface for easy integration into other systems.

By integrating these features, Swan Storage Market enhances the accessibility and usability of decentralized storage, offering a comprehensive and user-friendly solution for both novice and experienced users.


# AI Computing Marketplace

Globle AI Computing Task Market

The Swan Chain AI Market is a cutting-edge decentralized platform specifically designed to cater to the needs of AI development by streamlining the distribution of AI model training tasks to a global network of computing providers. Utilizing a sophisticated AI auction engine, SwanChain facilitates a transparent and competitive marketplace that operates on blockchain technology.

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

Here’s how the SwanChain AI Market functions:

#### AI Model Training Distribution

SwanChain's AI Market is a conduit for distributing intensive AI training tasks, which require substantial computational resources, including GPUs for processing large datasets and performing complex calculations inherent in machine learning and neural network training.

#### AI Auction Engine

1. **Task Listing**: AI developers or businesses in need of computational power for model training can list their tasks on the platform, providing detailed requirements for processing power, memory, storage, and specific preferences for hardware capabilities.
2. **Bidding System**: Computing providers equipped with the necessary hardware and capabilities review the listed tasks and place competitive bids to offer their services. The bidding system is designed to balance the cost with the quality and efficiency of service.
3. **Provider Selection**: The AI auction engine processes the bids and selects the most appropriate provider based on several factors, including cost, provider reputation, and resource availability. This ensures that AI tasks are assigned to providers who can offer optimal value and performance.

#### Task Execution and Verification

1. **Task Performance**: The chosen provider performs the AI training task using their computational infrastructure. Progress and performance can be monitored through the platform to ensure that the task is carried out according to the agreed-upon standards.
2. **Validation**: Upon task completion, the results are subject to validation to confirm they meet the predefined criteria. The validation process is crucial to maintain high standards and trust within the marketplace.
3. **Reward and Rating**: After successful validation, the platform's smart contract system automatically processes the payment to the provider in $SWAN tokens, the native cryptocurrency of SwanChain. Participants can also rate each other, contributing to a trust-based ecosystem.

#### Advantages of SwanChain AI Market

* **Accessibility**: Developers worldwide can access computational resources without heavy upfront investments in hardware.
* **Economies of Scale**: Providers can leverage idle computational resources, and users benefit from competitive pricing due to the marketplace's scale.
* **Decentralization and Security**: The decentralized nature of blockchain provides enhanced security, transparency, and data integrity.
* **Incentivization**: The use of $SWAN tokens as a form of payment incentivizes participation and investment in the SwanChain ecosystem.

To start contributing your computing resources, click[ here](https://github.com/swanchain/docs/blob/main/core-concepts/market-provider/decentralized-ai-computing-marketplace/broken-reference/README.md). \\


# Orchestrator

Smart contract based AI Task Auction Engine

<figure><img src="/files/y3CXPdYVuMuUhriDw7hj" alt=""><figcaption><p>Swan Computing Auction Engine</p></figcaption></figure>

An AI computing and storage bid market is a decentralized platform where users can post requests for computing power and storage space and hire other users to provide these services. These platforms are built on blockchain technology and use smart contracts to create a transparent and secure marketplace where users can buy and sell computing and storage resources.

In a Web3 computing and storage bid market, users can post requests for computing power or storage space and specify the requirements, budget, and deadline. Other users can then bid on the request, offering their computing or storage resources and proposing a price for providing these services. The user who posted the request can then review the bids and select the one that best meets their needs.

The use of blockchain technology in a Web3 computing and storage bid market provides several benefits, such as:

1. Decentralization: The platform is decentralized, meaning that there is no central authority or intermediary controlling the transactions. This eliminates the need for intermediaries and reduces the risk of fraud.
2. Transparency: Transactions on the platform are transparent and recorded on a distributed ledger, making it difficult to tamper with or manipulate the data.
3. Security: Smart contracts are used to automate the bidding and payment process, ensuring that both parties are protected from fraud or default.
4. Lower transaction fees: Since there are no intermediaries involved, the transaction fees on a Web3 computing and storage bid market are typically lower than those of traditional marketplaces.

Swan bidding market is built on the Filecoin blockchain. Swan provides a platform where users can rent computing power to complete tasks, such as rendering 3D graphics or machine learning algorithms. Users can also rent storage space to store their data. Swan uses a decentralized network of nodes to provide these services, and users can earn cryptocurrency by renting out their computing or storage resources. Swan also provides a matchmaking system that connects users with the computing and storage resources they need.


# Auction Engine

The auction engine is a critical component of the Swan system. It manages the bidding process for tasks, ensuring that tasks are assigned to the most suitable computing providers. Here's a breakdown of its key functionalities:

1. **Load Provider Pool**: The auction engine initially loads all active computing providers into a pool. These providers are potential bidders for tasks.
2. **Place Bid**: When a task is open for bidding, the auction engine allows a computing provider (bidder) to place a bid on the task. The bid is only successful if the task is currently accepting bids, the bidder has not already placed a bid, and the bidder's collateral is sufficient.
3. **Load Tasks from Redis**: The auction engine fetches all tasks from Redis that are in a state where they can accept bids. It also handles state transitions for tasks, such as moving a task from the 'accepting\_bids' state to the 'bidding\_closed' state when the bidding period ends.
4. **Select Bidders**: The auction engine selects bidders based on certain criteria. For example, it might select the bidders with the highest collateral.
5. **Run Bidding Process**: For each task that is open for bidding, the auction engine runs the bidding process. It allows the selected bidders to place their bids on the task.
6. **List Tasks Available for Bidding**: The auction engine can provide a list of all tasks that are currently open for bidding.

The auction engine is designed to be fair and efficient, ensuring that tasks are distributed evenly among computing providers and that the bidding process is competitive. It plays a crucial role in the operation of the Swan network.

The data structure for each task in the platform includes:

* uuid: A unique identifier for the task.
* status: The current status of the task (e.g., open, closed, in progress, completed).
* task\_detail\_cid: A content identifier for the task details, stored on a decentralized storage system like IPFS.
* type: The type or category of the task.
* reference\_id: A reference ID for linking related tasks or resources.
* name: The name or title of the task.
* leading\_job\_id: The ID of the job currently in the leading processing status, used for tracking purposes.
* created\_at: The timestamp when the task was created.
* updated\_at: The timestamp when the task was last updated.
* user\_id: The ID of the user who created the task.

When a user publishes a task, multiple providers (blockchain nodes worldwide) can bid on the task. The Bidding Engine evaluates these bids and assigns the task to several bidders with the potential to complete the task effectively. Once they complete the task, the Bidding Engine assesses the quality of their work, updating the leading\_job\_id as necessary to keep track of the best-performing bidder.

Finally, the provider who delivers the highest-quality work is marked as successful and receives a reward from the task publisher. By employing this mechanism, the Bidding Engine promotes efficiency and transparency in the Decentralized Bidding Marketplace, ensuring that tasks are matched with the most suitable providers and completed to the highest standards.

### Autobid

The Decentralized Bidding Marketplace can be configured to include an auto-bid mode for providers, which allows them to automatically participate in all bids without manual intervention. This feature can be particularly useful for providers who want to streamline their bidding process and maximize their chances of securing tasks.

To enable the auto-bid mode, providers need to set up their capability and resource availability for bidding. This information includes the type of resources they can offer (such as storage, network bandwidth, CPU, and GPU), their capacity for each resource, and any other relevant details that may impact their ability to complete tasks.

When auto-bid mode is enabled, the Bidding Engine automatically pushes tasks to the provider based on their configured capabilities and resource availability. The Bidding Engine evaluates the provider's suitability for each task and includes their bid in the competitive bidding process. This automatic participation ensures that providers have a constant presence in the marketplace and can secure tasks that match their expertise and resources.


# Bidding Task State Machine

The bidding task state machine is a system designed to manage the bidding process for tasks, taking into account task details such as price and timeout. In this setup, each task allows a maximum of three bidders to compete simultaneously, with each bidder being assigned a job to complete.

Bidders have the ability to set a limit on the number of bids they can process at the same time. This feature prevents them from accepting new bids once they reach their specified limit, enabling bidders to effectively manage their workload and participate in multiple tasks without overextending themselves.

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

### States

The Bidding State Machine has several predefined states:

1. **created**: This is the initial state when a task is first created. The task stays in this state until bidding is opened.
2. **accepting\_bids**: In this state, the task is open for bidders to place their bids. The task remains in this state until bidding is closed, the bid is cancelled, or the bid fails.
3. **bidding\_closed**: This state indicates that the bidding process for the task has ended. The task transitions to this state from the 'accepting\_bids' state. From here, the task can either be marked as 'submitted' or 'failed'.
4. **submitted**: This state signifies that the task has been submitted successfully. The task moves to this state from the 'bidding\_closed' state. Once a task is in the 'submitted' state, it can then be completed.
5. **completed**: This is the final state indicating that the task has been completed successfully. The task transitions to this state from the 'submitted' state.
6. **failed**: This state indicates that the task has failed. The task can enter this state from the 'bidding\_closed' state. If a task fails, it can be reset to the 'created' state.
7. **cancelled**: This state signifies that the bid for the task has been cancelled. The task can enter this state from the 'accepting\_bids' state. If a bid is cancelled or fails, the task can be reset to the 'created' state.

The transitions between these states are managed by the state machine, which ensures that the task moves through its lifecycle in a controlled and predictable manner.

* `open_bidding`: Transition from Created to Accepting\_Bids.
* `close_bidding`: Transition from Accepting\_Bids to Processing.
* `cancel_bid`: Transition from Accepting\_Bids to Cancelled.
* `failed_bids`: Transition from Accepting\_Bids to Cancelled.
* `complete_task`: Transition from Submitted to Completed.
* `mark_as_submitted`: Transition from Processing to Submitted.
* `mark_as_failed`: Transition from Processing to Failed.
* `reset_accepting_bids_to_created`: Transition from Accepting\_Bids to Created.
* `reset_failed_bids_to_created`: Transition from Failed to Created.

The Bidding State Machine has defined transitions between states:

### Transition Between States

1. open\_bidding: Transition from 'Created' to 'Accepting\_Bids'.
2. close\_bidding: Transition from 'Accepting\_Bids' to 'Processing'.
3. cancel\_bid: Transition from 'Accepting\_Bids' to 'Cancelled'.
4. failed\_bids: Transition from 'Accepting\_Bids' to 'Cancelled'.
5. complete\_task: Transition from 'Submitted' to 'Completed'.
6. mark\_as\_submitted: Transition from 'Processing' to 'Submitted'.
7. mark\_as\_failed: Transition from 'Processing' to 'Failed'.
8. reset\_accepting\_bids\_to\_created: Transition from 'Accepting\_Bids' to 'Created'.
9. reset\_failed\_bids\_to\_created: Transition from 'Failed' to 'Created'.

### Rules

The bidding task state machine should include the following rules:

* A bidder cannot place a bid if they have exceeded their limit on the number of jobs they can process simultaneously.
* Once a bidder has completed a job, they cannot be assigned any further jobs on the same task.

If the task is cancelled, all bids and jobs associated with the task are cancelled as well


# Inference Marketplace

Decentralized AI Inference Marketplace for Real-Time Model Serving

The Inference Marketplace is Swan Chain's decentralized platform for AI model serving, introduced as part of [Swan 2.0](https://github.com/swanchain/docs/blob/main/core-concepts/swan-2.0-inference-cloud.md). Unlike the existing [AI Computing Marketplace](/core-concepts/market-provider/decentralized-ai-computing-marketplace) which handles training workloads through task auctions, the Inference Marketplace provides **real-time, low-latency AI inference** through persistent WebSocket connections and an OpenAI-compatible API.

## How It Works

### Request Lifecycle

```
Consumer                Swan Inference              Provider
   │                         │                         │
   │  POST /v1/chat/...      │                         │
   │────────────────────────▶│                         │
   │                         │  Select best provider   │
   │                         │  (load balancing)        │
   │                         │                         │
   │                         │  Forward via WebSocket   │
   │                         │────────────────────────▶│
   │                         │                         │  Run inference
   │                         │  Stream response         │
   │                         │◀────────────────────────│
   │  Stream response        │                         │
   │◀────────────────────────│                         │
   │                         │                         │
   │                         │  Record usage            │
   │                         │  (tokens, latency)       │
```

1. **Consumer** sends an inference request via the REST API with their API key
2. **Swan Inference** selects the best available provider using health-aware load balancing
3. The request is forwarded to the provider over a persistent **WebSocket** connection
4. The provider runs inference on their GPU and streams the response back
5. Swan Inference records usage metrics (tokens processed, latency, success/failure)
6. Usage is aggregated for billing and settlement

### Provider Connection Modes

| Mode                   | Description                                                                    | Use Case                                              |
| ---------------------- | ------------------------------------------------------------------------------ | ----------------------------------------------------- |
| **WebSocket Provider** | GPU provider running `computing-provider` agent, connects via WebSocket        | Primary path — no public IP required                  |
| **External Endpoint**  | Existing OpenAI-compatible server (vLLM, TGI, OpenAI API) registered with Swan | Fallback — for providers with existing infrastructure |

The response includes an `X-Swan-Connection-Mode` header indicating which path was used.

## Provider Registration and Collateral

### Registration Flow

1. **Sign up** at the Swan Inference dashboard
2. **Upgrade to provider** and receive a provider API key (`sk-prov-*`)
3. **Deposit collateral** — stablecoin (USDC/USDT on-chain) or USD (via payment gateway)
4. **Connect** via WebSocket using the `computing-provider` agent
5. **Pass benchmark** — initial verification (math, code, latency tests)
6. **Begin serving** — provider becomes active and receives inference requests

### Collateral Options

| Type                       | Method                                          | Verification                              |
| -------------------------- | ----------------------------------------------- | ----------------------------------------- |
| **Stablecoin (USDC/USDT)** | On-chain deposit to ProviderCollateral contract | Automatic on-chain tx verification        |
| **USD**                    | Stripe, PayPal, or bank transfer                | Admin confirmation with payment reference |

Collateral status follows the lifecycle: `pending → confirmed → refund_requested → refunded`

The refund waiting period is **7 days** from the time of request, ensuring all pending settlements are cleared before funds are released.

See [Computing Provider Collateral](/core-concepts/token/computing-provider-collateral) for detailed collateral amounts and slashing rules.

## Request Routing and Load Balancing

Swan Inference routes requests using configurable load balancing strategies:

| Strategy              | Description                                                 |
| --------------------- | ----------------------------------------------------------- |
| **Health-Aware**      | Routes to the provider with the best health score (default) |
| **Round-Robin**       | Distributes requests evenly across providers                |
| **Least-Connections** | Routes to the provider with the fewest active requests      |

Additional routing features:

* **Health monitoring** with automatic circuit breaker for unhealthy providers
* **Model warmup** to pre-load models and reduce cold-start latency
* **Retry and failover** — up to 2 retries with exponential backoff if a provider fails
* **Rate limiting** per API key with tiered limits by model category

### Rate Limits (Default)

| Category  | Requests/min |
| --------- | ------------ |
| LLM       | 200          |
| Image     | 60           |
| Embedding | 500          |
| Other     | 200          |

## Pricing Model

### Consumer Pricing

Pricing varies by model category:

| Category      | Pricing Unit                       | Examples                          |
| ------------- | ---------------------------------- | --------------------------------- |
| **LLM**       | Per input token + per output token | Chat completions, text generation |
| **Embedding** | Per token                          | Text embeddings                   |
| **Image**     | Per request                        | Image generation                  |
| **Audio**     | Per request                        | Transcription                     |

Prices are listed transparently in the model catalog at [inference.swanchain.io/models](https://inference.swanchain.io/models). The default marketplace currency is **USDC**.

### Platform Fee

The platform charges a **5% fee** on each transaction. This fee funds protocol operations, staking rewards, and SWAN token burns.

### Revenue Distribution

When a consumer pays for an inference request:

| Recipient               | Share | Description                         |
| ----------------------- | ----- | ----------------------------------- |
| **Provider**            | 70%   | Paid in the request currency (USDC) |
| **Protocol Treasury**   | 20%   | Funds ecosystem development         |
| **SWAN Buyback & Burn** | 10%   | Deflationary mechanism              |

## Settlement

### Off-Chain Ledger

Usage is tracked in real time on an off-chain payment ledger:

* Every inference request records: tokens processed, latency, model used, provider, consumer
* Provider earnings accumulate in the ledger
* Consumers are billed based on aggregated usage

### On-Chain Settlement

Settlement uses a **MerkleDistributor** smart contract for gas-efficient batch payouts:

1. **Daily batches** — Provider earnings are aggregated into settlement batches
2. **Merkle tree** — A Merkle tree is computed from all provider balances in the batch
3. **On-chain submission** — The Merkle root is submitted to the smart contract
4. **Provider claims** — Providers claim their earnings by submitting a Merkle proof

Settlement status follows: `pending → submitted → confirmed`

This approach settles many provider payments in a single on-chain transaction, minimizing gas costs.

### Minimum Payout

Providers must accumulate a minimum balance (default: **$50**) before a payout is triggered. This prevents dust transactions and reduces gas costs.

## Provider Earnings

Providers earn through two complementary streams:

### 1. Inference Revenue (Stablecoins)

Direct payment for serving inference requests, paid in the consumer's currency (typically USDC). This is the primary revenue stream and scales with the number of requests served.

### 2. Contribution Rewards (SWAN Tokens)

Daily SWAN token rewards allocated proportionally based on the provider's [Contribution Score](https://docs.swanchain.io/core-concepts/market-provider/pages/8Lz745lYUVBMLXhCsbfJ#swan-2.0-market-driven-income). This replaces the legacy UBI model and rewards providers for:

* Inference volume (requests processed)
* Token throughput (tokens generated)
* Uptime and availability
* Quality (success rate, latency)
* Model diversity (number of models served)

### Earnings Dashboard

The provider dashboard provides:

* **Daily/weekly/monthly** earnings views with CSV export
* **Per-model** performance metrics (requests, success rate, tokens processed)
* **Collateral status** and on-chain deposit tracking
* **Wallet verification** via MetaMask for secure payouts

## Subscription Plan

Swan Inference offers a **Pro subscription** alongside the existing pay-as-you-go credit model.

### Pro Plan — $6/month

| Feature            | Pay-As-You-Go           | Pro Subscription                          |
| ------------------ | ----------------------- | ----------------------------------------- |
| Price              | No fee, deposit credits | $6/month                                  |
| Open-source models | Pay per token           | Included (40M tokens/week, 1,500 req/day) |
| Premium models     | Pay per token           | Pay per token (from credit balance)       |
| Images             | Pay per image           | 75/day included                           |
| Payment            | Stripe or crypto        | Stripe (recurring) or crypto prepay       |

Subscriptions can be paid with stablecoins (USDC/USDT) or SWAN token. SWAN payments receive a 10% discount.

### Provider Earnings Under Subscription

Providers earn the same per-token rate for subscription requests as pay-as-you-go. Total provider payouts from subscription requests are capped at the subscription revenue pool ($6 x subscriber count per month). If provider costs exceed the pool, payouts are pro-rated proportionally across providers based on their contribution.

## Public Playground

The platform includes a public playground at [inference.swanchain.io/playground](https://inference.swanchain.io/playground) that allows anyone to try AI inference without an API key. The playground is rate-limited to 5 requests per hour per IP, with a restricted model selection and limited token output. This provides a zero-friction entry point for new users to evaluate the platform before signing up.

## Comparison with AI Computing Marketplace

| Feature        | AI Computing Marketplace | Inference Marketplace         |
| -------------- | ------------------------ | ----------------------------- |
| **Workload**   | Training, batch compute  | Real-time inference           |
| **Latency**    | Minutes to hours         | Milliseconds to seconds       |
| **Allocation** | Task auction (bidding)   | Real-time routing (WebSocket) |
| **Payment**    | Per task                 | Per token / per request       |
| **Connection** | Job-based                | Persistent WebSocket          |
| **API**        | Swan SDK / Orchestrator  | OpenAI-compatible REST API    |

Both marketplaces coexist within the Swan ecosystem, serving different use cases. The Inference Marketplace is optimized for interactive AI applications, while the AI Computing Marketplace handles batch training and compute-intensive tasks.

## Learn More

* [**Swan 2.0: Inference Cloud**](https://github.com/swanchain/docs/blob/main/core-concepts/swan-2.0-inference-cloud.md) — Overview of the Swan 2.0 platform
* [**Computing Provider Income**](/core-concepts/token/swan-provider-income) — Contribution scoring and reward distribution
* [**Computing Provider Collateral**](/core-concepts/token/computing-provider-collateral) — Collateral requirements and slashing


# ZK Proof Marketplace

The Swan Chain ZK market is an embodiment of how distributed computing power, particularly GPUs, can be harnessed to fulfill the demands of Zero-Knowledge (ZK) proof generation on a large scale. By creating a specialized ZK market, Swan Chain offers a platform where these compute-intensive tasks can be outsourced to a global network of computing providers, incentivized by the prospect of earning through the platform's Universal Basic Income (UBI) model. Here's an overview of how this system operates:

#### Global Network of Computing Providers

Swan Chain taps into a worldwide network of computing providers, each contributing their processing power to form a distributed supercomputer of sorts. This decentralized network allows for the parallel processing of tasks, significantly reducing the time required for generating ZK proofs.

<figure><img src="/files/5VIdrjAP0uPfkjIAC3Nv" alt=""><figcaption></figcaption></figure>

#### Utilization of GPU Hardware

Given that GPUs are particularly adept at handling parallelizable tasks, they are ideal for the computation-heavy process of generating ZK proofs. Swan Chain's infrastructure likely includes nodes equipped with high-performance GPUs to accelerate the creation of proofs, making the process more time and cost-efficient.

#### Embedded ZK Market

The embedded ZK market within Swan Chain operates as a marketplace for ZK proof generation. Blockchain protocols and applications that require ZK proofs but lack the computational resources to generate them in-house can outsource these tasks to the Swan Chain network.

#### ZK UBI Mechanism

The computing providers participating in the ZK market are rewarded for their contributions in the native cryptocurrency of Swan Chain, which forms part of their UBI. This UBI serves as a consistent stream of income, providing an economic incentive for maintaining the necessary computational infrastructure and for the continuous provision of processing power.

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

#### Advantages and Innovation

1. **Scalability**: By leveraging a global network of computing providers, Swan Chain can scale its computational capacity up or down based on the current demand for ZK proofs.
2. **Decentralization**: The decentralized nature of the network ensures resilience and robustness, with no single point of failure that could disrupt the generation of ZK proofs.
3. **Incentivization**: The UBI model incentivizes a wide array of providers to join and contribute to the network, ensuring a consistent availability of computational resources.
4. **Cost-Effectiveness**: For blockchain protocols and applications, using Swan Chain's ZK market is likely more cost-effective than developing and maintaining an in-house solution for ZK proof generation.
5. **Privacy and Security**: The use of ZK proofs inherently enhances privacy and security, making Swan Chain's offering particularly appealing for applications that handle sensitive data.


# ZK Task

The ZK (Zero-Knowledge) Task on Swan Chain is an innovative implementation that blends a Universal Basic Income model with the privacy and efficiency of zero-knowledge proofs (ZKPs), underpinned by an embedded ZK market. This integration creates a self-sustaining and privacy-preserving ecosystem for participants who contribute computing resources.

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

#### Concept and Functionality

**ZK Model**: The ZK model within Swan Chain is a groundbreaking economic system designed to provide a guaranteed basic income to network participants. It leverages zero-knowledge proofs to validate the contributions of computing providers without revealing sensitive data.

**Zero-Knowledge Proofs**: ZKPs are a form of cryptographic protocol that allow one party (the prover) to prove to another party (the verifier) that a statement is true, without revealing any information beyond the validity of the statement itself.

[**Embedded ZK Market**](/core-concepts/market-provider/indexing-and-caching-marketplace): Swan Chain integrates a specialized ZK market that serves as a platform for various blockchain protocols in need of ZK computation, such as Aleo, Filecoin, and StarkNet. This market is where tasks requiring ZK proofs are listed and sourced.

#### Workflow

1. **Task Generation**: Blockchain protocols that require ZK computations generate tasks. These could include private transaction verification for Aleo, proof-of-replication for Filecoin, or scalability solutions for StarkNet.
2. **ZK Task Pool**: The generated tasks are pooled into a ZK Task Pool, where they are made available to computing providers on the Swan Network.
3. **Task Completion for Income**: Computing providers on Swan Chain select tasks from the pool, complete the computations, and generate ZK proofs. By completing these tasks, they earn $SWAN, the native cryptocurrency of Swan Chain, as part of their UBI.
4. **Proof Submission and Verification**: Upon completion, providers submit their ZK proofs back to the Swan Chain for verification. This ensures the integrity and validity of the computations performed.
5. **UBI Distribution**: Once verified, the ZK proofs trigger the smart contract-based UBI system to distribute $SWAN to the computing providers, ensuring a steady income stream and incentivizing continuous participation in the network.

<figure><img src="/files/34SEPhIoI6Xma6tHs4tq" alt=""><figcaption><p>ZK task reward Dashboard</p></figcaption></figure>

To get started as a ZK task contributor, click [here](/bulders/market-provider/web3-zk-computing-market/contribute-zk-ubi-task).


# ZK Pool

Swan’s ZK mechanism integrates various ZK-proof computations over time, such as Filecoin commit2, Aleo, StarkNet, Scroll, etc.

The ZK Task Pool serves as a centralized hub for various ZK workloads for CPs:

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

* Storage Providers can contribute their ZK-proof work to enrich the pool of tasks
* Computing Providers can receive tasks from the ZK task pool
* CPs generate proofs recorded on Swan Chain, allowing Storage providers to directly access the proofs they need.

By deeply integrating Filecoin’s intensive workloads and establishing an open task pool, Swan’s ZK tasks brings about mutually reinforcing network collaborations.

## Filecoin Commit 2 (C2) with ZK

[Commit 2](https://docs.filecoin.io/storage-providers/architecture/sealing-pipeline#commit-2) (C2) is an intensive computational step in Filecoin's sector sealing pipeline requiring the generation of a [zk-SNARK](https://docs.filecoin.io/reference/general/glossary#zero-knowledge-succinct-non-interactive-argument-of-knowledge-zk-snark) proof to validate storage commitment.

Swan's ZK mechanism incorporates such heavy workloads into an incentive design that allows [Computing Provider](/bulders/computing-provider/fog-computing-provider-fcp/computing-provider-setup) within the Swan ecosystem to accelerate proofs while earning ZK rewards.

**Key Points about C2**

* C2 involves creating a zk-SNARK proof to validate the miner’s commitment to store sector data.
* It is a GPU-intensive computation, requiring significant compute resources (peak memory of 275GiB for 32GiB sectors).

**Receiving ZK-Tasks**

Computing providers on Swan can follow [this guide ](/bulders/computing-provider/edge-computing-provider-ecp/ecp-setup)to configure themselves to receive and process outsourced Filecoin C2 sector sealing tasks.

Once set up, suitable C2 tasks get automatically assigned based on provider declared capacity.

**Contributing ZK-proof Workloads**

For Storage Providers interested in contributing tasks to this pool, please refer to this guide: [Contribute zk-UBI-task](/bulders/market-provider/web3-zk-computing-market/contribute-zk-ubi-task)

But if you have an independent zero-knowledge proof system that requires robust computational support from the Swan Network, you can directly apply for our DevGrant [here](https://github.com/swanchain/devgrants/issues/new/choose).\\


# Storage Layer

Cross chain Data Availability

<figure><img src="/files/AtaGbGm9cBtqq2yCXRZD" alt=""><figcaption><p>Cross Chain Storage structure</p></figcaption></figure>

Swan, as a prominent player in the decentralized computing domain, has strategically positioned itself to leverage multiple storage solutions, ensuring optimal data availability and versatility. Here's a breakdown of how Swan integrates various storage platforms:

1. **IPFS (InterPlanetary File System)**: Swan utilizes IPFS for decentralized file storage. Given IPFS's peer-to-peer nature, it's an ideal choice for distributing and ensuring the availability of files across a decentralized network. This ensures that data is not only stored securely but is also easily retrievable from any point in the network.
2. **Storj**: Recognizing the increasing demand for media content streaming, Swan integrates Storj, which is optimized for streaming media files. Storj's decentralized cloud storage ensures that media files are delivered seamlessly, providing an uninterrupted streaming experience for users.
3. **Filecoin**: For archiving larger files, Swan leverages the Filecoin network. Filecoin's decentralized storage marketplace is perfect for long-term storage solutions, ensuring that large datasets are securely archived and remain accessible when needed.
4. **BNB GreenField**: As an innovative blockchain and storage platform, BNB GreenField offers a unique approach to data management and ownership. Swan's integration with GreenField further enhances its storage capabilities, allowing for more flexible and efficient data management solutions.
5. **Cross-Chain Contracts**: One of Swan's standout features is its ability to use cross-chain contracts to interact with different storage solution providers. This means that Swan can dynamically choose the best storage solution based on the specific needs of a task, be it decentralized file storage, media streaming, or large file archiving.

In essence, Swan's multi-faceted approach to data availability ensures that it can cater to a wide range of storage needs, from decentralized file sharing to media streaming and large file archiving. By integrating multiple storage platforms and utilizing cross-chain contracts, Swan is setting a new standard for decentralized data storage and management.

For more details about cross chain storage design, please refer to [multichain.storage](https://github.com/filswan/gitbook/blob/main/getting-started/protocol-stack/broken-reference/README.md)


# Computing Layer

Decentralized Computing Power Renting Network

<figure><img src="/files/wViPDTtdp9kp6qX9TQVb" alt=""><figcaption><p>Computing Workflow</p></figcaption></figure>

Swan's Computing Layer is a crucial component of its decentralized cloud computing ecosystem. It's designed to facilitate the execution of computing tasks across a network of providers, ensuring efficiency, reliability, and security. The Computing Layer supports diverse workloads including **AI model training**, **ZK proof generation**, and — with the introduction of [Swan 2.0](https://github.com/swanchain/docs/blob/main/core-concepts/swan-2.0-inference-cloud.md) — **real-time AI inference** through the [Inference Marketplace](/core-concepts/market-provider/inference-marketplace).

{% hint style="info" %}
**Swan 2.0 Update**: The Computing Layer now supports dual token payments. Consumers can pay with **stablecoins (USDC/USDT)** for inference workloads, while providers earn both stablecoin revenue and **SWAN token** rewards based on their [Contribution Score](https://docs.swanchain.io/core-concepts/pages/8Lz745lYUVBMLXhCsbfJ#swan-2.0-market-driven-income).
{% endhint %}

Here's an introduction to the key aspects of the Swan Computing Layer:

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

#### 1. **Computing Providers (CPs)**

Computing Providers are entities within the Swan network that offer computational resources. They must provide collateral in Swan tokens to join the network, ensuring accountability.

#### 2. **Task Submission and Bidding**

Users can submit computing tasks to the network. CPs can bid for these tasks, and jobs are generated for each CP that joins the bid. The system may use a randomized allocation method to fairly distribute jobs among providers.

#### 3. **Execution and Rewarding**

CPs execute the tasks and are rewarded with Swan tokens upon successful completion. The reward mechanism may follow a Proof-of-Work (PoW) auction style, where CPs have a chance to win a ticket if they complete the job.

#### 4. **Collateral and Slashing**

CPs must collateralize a certain amount of Swan tokens to participate in the network. If a CP fails to complete a job as promised, a portion of their collateral is slashed. This incentivizes providers to fulfill their commitments.

#### 5. **Cross-Chain Capability and Payment**

Swan's computing layer has cross-chain capabilities, allowing payments from multiple blockchain tokens. A swap engine converts user-paid tokens to Swan tokens before paying the CPs.

#### 6. **Decentralized and Secure**

The Swan Computing Layer operates in a decentralized manner, leveraging blockchain technology to ensure transparency, security, and trust.

#### 7. **Integration with Other Swan Services**

The Computing Layer is part of a broader ecosystem that includes storage provider selection, data management, and seamless integration from IPFS to the Filecoin network.

<figure><img src="/files/7pKAkmrSjKlZy0giRkcG" alt=""><figcaption><p>Payment in Computing Network</p></figcaption></figure>

#### Conclusion

Swan's Computing Layer represents a significant advancement in decentralized cloud computing. By leveraging blockchain technology and a sophisticated system of task allocation, collateral, and rewards, it offers a scalable and reliable solution for executing computing tasks across a decentralized network. Its integration with other Swan services and its cross-chain capabilities further enhance its appeal as a comprehensive solution for decentralized storage, payment gateway integration, and computing.


# Computing Provider Protocol

Computing Provider Protocol Introduction

The CP Protocol (Computing Provider Protocol) is specifically designed for computing providers (CPs) in the Swan network, aiming to standardize and protocolize the management and invocation of computing resources. A CP can be any third-party individual or organization that provides scalable cloud computing, storage, platform, and application services for enterprises to access on demand.

### Main Features

The CP Protocol is divided into two main categories: **Standard Protocol** and **Extension Protocol**. Each category is designed to meet specific business and technical needs and covers only the protocol layer. For specific code design, please refer to the corresponding SIP (Swan Improvement Proposal) document.

#### Standard Protocol

The core focus of the standard protocol is on standardizing the invocation and management of computing resources to ensure effective management. It includes the following key aspects:

* **Create job**: Specifies the standardized process for deploying tasks on CP resources.
* **Query job details**: Defines the protocol for accessing the execution status and relevant parameters of a task.
* **Renew job**: Provides the standard procedure for task renewal.
* **Terminate job early**: Sets the protocol standard for early termination of tasks.
* **Query CP resources**: Describes how to query and select available computing resources.

#### Extension Protocol

The extension protocol focuses on enhancing the security, customizability, and flexibility of resources. Specific functions include:

* **Query CP resource pricing**: Defines the standard method for querying CP resource pricing information.
* **Query CP whitelist**: Specifies how to manage and query a list of specific users.
* **Query CP blacklist**: Sets out how to maintain and query a blacklist to prevent malicious users from accessing resources.
* **Multi-chain payment verification mechanism**: Describes the verification protocol for using multi-chain payment methods to invoke CP resources.
* **Universal collateral/withdrawal mechanism**: Defines a standard protocol for a general collateral and withdrawal process to facilitate the access and management of market providers.

### Compatibility and Application Extension

According to the design of the CP Protocol, any type of market provider (MP, Market Provider) can develop and design a computing engine that meets their needs based on this protocol. This flexibility ensures that the CP Protocol is not only applicable to current computing providers but also provides foundational support for various new types of computing service models that may emerge in the future.

By introducing the CP Protocol, the Swan network not only enhances the efficiency and security of resource management but also provides flexible configuration options to accommodate the needs of various business scenarios.


# Computing Provider Account

### Overview

`CPAccount` is a smart contract account based on Swan Chain, designed for managing and registering computing providers (CP). Each computing provider that connects to Swan Chain must create a unique account. When an account is created, the `CPAccount` automatically registers with the CP Account Register Contract.

### Features

The contract account provides a range of functions, including ownership management, worker and beneficiary information management, task type updates (supporting extension for additional task types), and multi-address updates. The contract also includes an event mechanism to notify external systems about changes in ownership, worker, multi-address, and task types.

#### Key Functions

* **Ownership Management**: Allows the owner to change the contract's owner address.
* **Worker Management**: Allows the owner to change the worker address.
* **Beneficiary Management**: Allows the owner to change the beneficiary address.
* **Multi-address Management**: Allows the owner to update the multi-address array.
* **Task Type Management**: Allows the owner to update the task type array, supporting extension for additional task types.

#### Account Roles

To ensure the security of the CP Account, the roles are categorised into:

* **Owner**: Manages the CP Account and has permission to change account information such as multi-addresses, worker address, and beneficiary address. The private key of the owner's address does not need to be present on the server for security reasons.
* **Worker**: This address is used for submitting task results and needs to be funded with a certain amount of ETH to pay for gas fees.
* **Beneficiary**: This address receives all earnings from the CP Account and is solely used for receiving funds. For security purposes, the private key of the beneficiary's address should not be stored on the server to maintain isolation.

#### Event Mechanism

* **OwnershipTransferred**: Ownership transfer event, notifying external systems of changes in the owner address.
* **WorkerChanged**: Worker change event, notifying external systems of changes in the worker address.
* **MultiaddrsChanged**: Multi-address change event, notifying external systems of changes in multi-addresses.
* **BeneficiaryChanged**: Beneficiary change event, notifying external systems of changes in the beneficiary address.
* **TaskTypesChanged**: Task type change event, notifying external systems of changes in task types.
* **CPAccountDeployed**: CPAccount deployment event, notifying external systems of the creation and registration of the CPAccount.

**Token Flow Diagram**

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

#### Workflow

1. **Registration**:
   * A new CP deploys the `CPAccount` contract with the required parameters.
   * The CP is registered with the Contract Registry.
2. **Task Assignment and Execution**:
   * Tasks are assigned to the CP by the AI or ZK engines.
   * CP locks the required collateral before starting task execution.
   * Upon task completion, the CP is rewarded, and collateral is released.
3. **Collateral Management**:
   * Collateral is locked before task execution and released upon successful completion.
   * In case of task failure, collateral is slashed as a penalty.
4. **Deposits and Withdrawals**:
   * CPs can deposit tokens into their accounts to maintain sufficient balance for collateral.
   * Withdrawal requests can be made and confirmed after a delay period.

### Source Code

Detailed source code for the `CPAccount` contract can be found [here](https://github.com/swanchain/market-providers/tree/main/computing-provider/account).

### Summary

The `CPAccount` contract provides a robust framework for managing and registering computing providers on Swan Chain. It facilitates secure management of ownership, worker, and beneficiary roles, with flexible support for extending task types. Through its comprehensive functionality and event-driven architecture, it ensures transparency and security in CP Account operations.


# Layer3 Computing Protocol

A Layer3 designed for high performance AI computing

**Introduction**

The Layer3 Computing Protocol aims to aggregate computing jobs submission with reduced gas fees, ensuring efficient data management and scalability. This protocol utilizes IPLD for data storage, generates unique CIDs, and employs a Sequencer for batching and submitting tasks to Swan Chain.

**Key Components**

1. **Data Storage and CID Generation**
2. **Submission of Blob CIDs**
3. **Role of the Sequencer**
   * Receiving Proofs
   * Validating Proofs
   * Batching Proofs
   * Submitting Data
   * Gas Fee Management

#### Detailed Process Flow

**1. Data Storage and CID Generation**

* **Step 1:** Data related to computing tasks and results are stored using the IPLD format.
* **Step 2:** Unique CIDs are generated for these data entries.

**2. Submission of Blob CIDs**

* **Step 1:** Generated CIDs are submitted to smart contracts as blobs.
* **Step 2:** This ensures long-term persistence of job data and results.

**3. Role of the Sequencer**

<figure><img src="/files/1I2FZi5NKXrEBhsSfp3K" alt=""><figcaption></figcaption></figure>

* **Step 1:** CPs submit proofs of completed tasks to the Sequencer.
* **Step 2:** Sequencer validates the received proofs.
* **Step 3:** Valid proofs are batched together by the Sequencer.
* **Step 4:** Sequencer submits the batched data to Swan Chain.
* **Step 5:** AggregateTask contracts are created with blob CIDs.
* **Step 6:** Sequencer manages gas fees, maintaining separate accounts for gas costs.

#### Benefits

* **Reduced Gas Costs:** By batching tasks and submitting them as aggregated blobs, gas costs are minimized, making the system more efficient and cost-effective.
* **Efficient Data Management:** Using IPLD and unique CIDs ensures that data is stored efficiently and can be easily retrieved and validated.
* **Secure and Scalable:** The Sequencer enhances security by validating proofs and aggregating tasks, allowing for scalable and secure job submissions to the Swan Chain.

The Layer3 Computing Protocol provides a robust solution for decentralized computing by optimizing job submissions, reducing gas fees, and ensuring efficient data management. By leveraging IPLD for data storage and employing a Sequencer for validation and batching, the protocol enhances security and scalability, making it a key component of the Swan Chain ecosystem.

#### Example Use Case

* **AI/ML Workloads:** Aggregate multiple AI/ML model training tasks and submit them as a single batch to reduce gas costs.
* **Data Archiving:** Use IPLD to store large datasets, generating unique CIDs for efficient retrieval and long-term persistence.
* **Content Delivery:** Manage and aggregate content delivery tasks, ensuring secure and scalable distribution across the network.

#### Glossary

* **IPLD:** InterPlanetary Linked Data, a format for storing and referencing data.
* **CID:** Content Identifier, a unique identifier for data stored in IPLD.
* **Sequencer:** A component that receives, validates, batches, and submits tasks to the blockchain.
* **CP:** Computing Provider, an entity that provides computing resources and submits proofs of completed tasks.
* **AggregateTask:** A contract on Swan Chain that references aggregated task data using blob CIDs.


# Reputation System

AVS-based Computing Provider Reputation

**1. Overview**

Swan Chain's reputation system is built on **AVS** (Actively Validated Services), which provides decentralized and verifiable data for evaluating the performance and reliability of CPs. The system combines **automated data analysis** and **user feedback** to assess providers across various metrics such as uptime, job completion rates, user claims, and system jobs. The integration of **AVS-based services** ensures the trustless execution of reputation scoring, using blockchain’s inherent properties of transparency, security, and immutability.

***

#### **Key Components of the AVS-Based Reputation System**

The **AVS-based Computing Provider Reputation System** is composed of multiple layers, each responsible for evaluating different aspects of a CP’s performance:

**1.1 Sampling System (AVS-Based)**

The sampling system, powered by **AVSs**, selects random tasks from a verified pool of jobs (e.g., GPU, CPU, ZK jobs). These jobs are sent to CPs for execution, and the system tracks the results in real-time.

* **AVS Data Availability:** Data from these jobs is stored on decentralized data availability layers, ensuring that all performance metrics are verifiable and tamper-proof.
* **Distribution System:** The system distributes tasks to CPs, and AVS ensures transparency by maintaining records of job assignments and completions.

**2.1 Probe System (AVS Monitoring)**

The **Probe System** regularly checks the performance of CPs using AVS-based tools. Every few seconds, the system validates the completion and accuracy of tasks performed by the providers.

* **AVS Validation:** Probes ensure that results are validated on-chain, utilizing AVS capabilities for data verification. The system ensures no tampering or manipulation of job results.

**2.2 Job Settlement System (AVS-Backed Payments)**

Once tasks are completed, the job settlement system determines whether CPs should be paid based on AVS-verified job outcomes.

* **AVS for Automatic Payments:** Payments are made automatically via smart contracts on the Swan Chain network. The reputation score of a CP directly influences the settlement process, and incomplete jobs lead to collateral slashing.

### 2. Components and Scoring

The total reputation score is composed of the following components:

#### Current Version Composition:

| Component                 | Weight | Description                                        |
| ------------------------- | ------ | -------------------------------------------------- |
| Machine Uptime            | 10%    | Availability of the CP based on continuous pinging |
| Join Time                 | 10%    | Longevity of the CP in the system                  |
| System Job Score          | 35%    | Performance on controlled, system-initiated jobs   |
| User Job Score            | 15%    | Success rate of user-initiated jobs                |
| User Request Refund Score | 30%    | Impact of confirmed user claims on jobs            |

#### Rationale for Component Selection and Weighting

The reputation scoring system comprises six key components, each chosen for its unique contribution to assessing Compute Provider (CP) performance. The weighting of each component reflects its relative importance in the overall evaluation.

1. Machine Uptime (10%):
   * Measures basic reliability
   * Critical but not the sole indicator of performance
   * Low weight as it's a minimum expectation
2. Join Time (10%):
   * Reflects CP experience and commitment
   * Balances new entrants vs. established CPs
   * Low weight to avoid overly penalizing new, high-performing CPs
3. User Review Score (10%):
   * Captures user satisfaction
   * Provides qualitative performance insights
   * Lower weight due to potential subjectivity
4. User Claim Score (25%):
   * Indicates serious issues affecting users
   * High weight due to direct impact on service quality
   * Balances user feedback with objective measures
5. System Job Score (30%):
   * Offers controlled, objective performance measurement
   * Highest weight due to standardized evaluation across all CPs
   * Reflects core CP capabilities
6. User Job Score (15%):
   * Measures real-world performance
   * Complements system jobs with diverse, practical scenarios
   * Moderate weight balances importance with potential variability

This balanced approach ensures a comprehensive evaluation of CP performance, considering both objective metrics and user experiences. The weightings prioritize factors directly impacting service quality and reliability, while still accounting for longevity and user satisfaction.

#### 2.1 Scoring Strategies

**Machine Uptime (100 points max)**

* Score = Availability percentage (e.g., 99.9% uptime = 99.9 points)

**Join Time (100 points max)**

* Score = (CP's join time / Oldest CP's join time) \* 100

**System Job Score (100 points max)**

* Initial score: 50
* For each successful job: +10 points
* For each failed job: -20 points
* Score is capped at 100 points and cannot go below 0

**User Request Refund Score (100 points max)**

* Score = \[(Successfully completed jobs - Approved refund jobs) / Successfully completed jobs] \* 100

**User Job Score (100 points max)**

* Score = (Successfully completed jobs / Total number of jobs) \* 100

#### 2.2 Total Reputation Score Calculation

The total reputation score is calculated as follows:

Total Score = SUM(contribution percentage \* score of the category component)

**Example Calculations**

1. Example CP with average performance:

   * Machine Uptime: 99.5 points
   * Join Time: 70 points (joined 70% as long ago as the oldest CP)
   * System Job Score: 80 points
   * User Job Score: 95 points

   Total Score = (99.5 \* 0.10) + (70 \* 0.20) + (80 \* 0.50) + (95 \* 0.20) = 82.95
2. Example CP with excellent performance:

   * Machine Uptime: 99.9 points
   * Join Time: 100 points (oldest CP)
   * System Job Score: 100 points
   * User Job Score: 99 points

   Total Score = (99.9 \* 0.10) + (100 \* 0.20) + (100 \* 0.50) + (99 \* 0.20) = 99.79
3. Example CP with poor performance:

   * Machine Uptime: 95 points
   * Join Time: 30 points (relatively new CP)
   * System Job Score: 60 points
   * User Job Score: 80 points

   Total Score = (95 \* 0.10) + (30 \* 0.20) + (60 \* 0.50) + (80 \* 0.20) = 61.5

### 3. Application of Reputation Scores in Bidder Selection

The total reputation score is used to select bidders for jobs in a way that balances fairness with performance incentives. Here's how the process works:

#### 3.1 Bidder Selection Process

1. Collect Reputation Scores: Gather the reputation scores of all bidders for a job.
2. Normalize Scores: Convert the scores into probabilities by dividing each score by the sum of all scores.
3. Create Cumulative Distribution: Form a cumulative distribution from these probabilities.
4. Random Selection: Generate a random number and use it to select a bidder based on the cumulative distribution.

This method gives bidders with higher reputation scores a greater chance of being selected, while still allowing lower-scored bidders an opportunity to win bids.

#### 3.2 Example

Let's say we have four bidders with the following reputation scores:

* Bidder A: 85
* Bidder B: 92
* Bidder C: 78
* Bidder D: 88

Step 1: Collect Reputation Scores \[85, 92, 78, 88]

Step 2: Normalize Scores Total sum = 85 + 92 + 78 + 88 = 343 Probabilities:

* A: 85/343 ≈ 0.2478
* B: 92/343 ≈ 0.2682
* C: 78/343 ≈ 0.2274
* D: 88/343 ≈ 0.2566

Step 3: Create Cumulative Distribution

* A: 0.2478
* B: 0.2478 + 0.2682 = 0.5160
* C: 0.5160 + 0.2274 = 0.7434
* D: 0.7434 + 0.2566 = 1.0000

Step 4: Random Selection If the random number generated is 0.6, we would select Bidder C, as 0.6 falls between 0.5160 and 0.7434 in the cumulative distribution.

#### 3.3 Advantages of This Approach

1. Performance Incentive: Higher-rated bidders have a better chance of being selected, encouraging CPs to maintain good performance.
2. Fairness: Lower-rated bidders still have a chance to win bids, allowing for potential improvement and preventing monopolization by top-rated CPs.
3. Randomization: The element of randomness helps distribute jobs across a range of CPs, promoting system resilience and diversity.

This selection method ensures that reputation scores have a meaningful impact on job distribution while maintaining a dynamic and fair marketplace for all Compute Providers.

### 4. Monitoring and Reporting

* Implement a Grafana dashboard to show the trend of the total score and all component scores
* The dashboard will display historical data and allow for trend analysis of CP performance over time

### 5. Implementation Details

#### 5.1 Machine Uptime Monitoring

* Implement a continuous pinging system to monitor CP availability
* Update uptime scores in real-time or at regular intervals (e.g., hourly)

#### 5.2 Join Time Tracking

* Store the initial join timestamp for each CP
* Update join time scores daily, considering the current oldest CP as the benchmark

Flow Chart:

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

#### 5.3 System Job Score Design

The System Job Score is a critical component of the CP reputation system, designed to evaluate CP performance based on controlled, system-initiated jobs. This score provides an objective measure of CP reliability and capability.

**5.3.1 Scoring Mechanism**

* The score ranges from 0 to 100 points.
* Each CP starts with an initial score of 50 points.
* Points are added for successful jobs and deducted for failed jobs.
* The score is updated after each system job completion.

**5.3.2 Job Outcome Scoring**

1. Successful Job: +10 points
2. Failed Job: -20 points

**5.3.3 Score Calculation**

After each job:

```
New Score = Previous Score + Points from job outcome
```

The score is capped at a minimum of 0 and a maximum of 100 points.

**5.3.4 Time-based Performance Evaluation**

Implement a time-based evaluation to give more weight to recent performance:

1. Calculate a short-term score (last 7 days).
2. Calculate a medium-term score (last 30 days).
3. Calculate a long-term score (all-time).

The final System Job Score is a weighted average of these three scores:

```
Final Score = (Short-term * 0.5) + (Medium-term * 0.3) + (Long-term * 0.2)
```

**5.3.5 Minimum Job Threshold**

* Require a minimum of 10 completed system jobs before including this score in the total reputation calculation.
* For CPs with fewer than 10 jobs, use the system average for this component.

**5.3.6 Performance Trend Analysis**

Implement a trend analysis to identify improving or declining performance:

1. Calculate the rate of change in score over the last 30 days.
2. Categorize CPs as "Improving," "Stable," or "Declining" based on this trend.
3. Use this information for internal monitoring and potentially for CP feedback.

**5.3.7 Job Distribution and Fairness**

To ensure fair evaluation:

1. Distribute an equal number of jobs to all CPs daily.
2. Ensure a mix of basic, complex, and critical jobs for each CP over time.
3. Randomize job assignment to prevent gaming of the system.

**5.3.8 Score Recovery Mechanism**

Implement a gradual score recovery to allow CPs to improve their standing:

* If a CP maintains a 100% success rate for 7 consecutive days, add a bonus of 5 points to their score (up to the maximum of 100).

**5.3.9 Updated Flow Chart**

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

**5.3.10 Integration with Total Reputation Score**

The System Job Score contributes 30% to the total reputation score in the future version composition, as previously defined.

**5.3.11 Example Calculation**

Let's consider a CP with the following recent performance:

* Short-term score (7 days): 85 points
* Medium-term score (30 days): 75 points
* Long-term score (all-time): 70 points

Final System Job Score = (85 \* 0.5) + (75 \* 0.3) + (70 \* 0.2) = 42.5 + 22.5 + 14 = 79 points

This score would then contribute to 30% of the CP's total reputation score.

#### 5.4 User Job Tracking

* Implement a system to track all user-initiated jobs and their outcomes
* Update user job scores daily based on the latest success rates

Flow Chart:

<figure><img src="/files/11CuU1bNcXPg16Hkxdzl" alt=""><figcaption></figcaption></figure>

## Future Works

### 1. User Review Score Design

The User Review Score aims to incorporate user feedback on completed jobs, providing a measure of user satisfaction with the Compute Provider's (CP) service.

#### 1.1 Scoring Mechanism

* Users can rate completed jobs on a scale of 1 to 5 stars.
* Each rating contributes to a rolling average of the CP's performance.
* The score is normalized to a 0-100 scale.

#### 1.2 Calculation

1. Calculate the average rating:

   ```
   Average Rating = Sum of all ratings / Number of ratings
   ```
2. Normalize to 0-100 scale:

   ```
   User Review Score = (Average Rating / 5) * 100
   ```

#### 1.3 Weighting and Decay

* More recent reviews have a higher weight to reflect current performance.
* Implement a time decay factor: reviews older than 30 days have 50% weight, older than 90 days have 25% weight.

#### 1.4 Minimum Reviews Threshold

* Require a minimum of 5 reviews before including this score in the total reputation calculation.
* For CPs with fewer than 5 reviews, use the system average for this component.

Flow Chart:

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

#### 1.5 User Weighting System

To address the issue of users who consistently provide the lowest job reviews, we'll implement a user weighting system:

1. Track each user's review history.
2. Identify users who consistently give the lowest ratings.
3. Gradually reduce the weight of their reviews in the overall score calculation.

**1.5.1 Consistent Low Rating Identification**

* Define "lowest rating" as 1 star out of 5.
* Track the percentage of 1-star ratings for each user.
* If a user's percentage of 1-star ratings exceeds a threshold (e.g., 80%) over a significant number of reviews (e.g., 10+), flag them for weight reduction.

**1.5.2 Weight Reduction Mechanism**

* Start all users with a weight of 1.0 (100% influence).
* For flagged users, reduce their weight using the following formula:

  ```
  User Weight = max(0.2, 1 - (Percentage of 1-star ratings - Threshold))
  ```

  This ensures their weight never goes below 0.2 (20% influence).

**1.5.3 Weight Recovery**

* If a flagged user starts providing more balanced ratings, gradually increase their weight.
* For every 5 consecutive ratings that are not 1-star, increase their weight by 0.1, up to a maximum of 1.0.

**1.5.4 Integration into Score Calculation**

When calculating the average rating for a CP, use the weighted average:

```
Weighted Average Rating = Sum(Rating * User Weight) / Sum(User Weights)
```

Then proceed with the normalization to the 0-100 scale as before.

#### 1.6 Updated Flow Chart

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

This full user review design addresses the concern about users who consistently give the lowest job reviews. By implementing this weighting system, we ensure that while all feedback is considered, the impact of potentially unfair or overly critical reviews is mitigated. This approach maintains the value of user feedback while protecting Compute Providers from undue negative impact from a small number of extremely critical users.

### 2. User Request Review Score Design

The User Request Review Score reflects the reliability of the CP based on valid claims made by users for issues with completed jobs.

#### 2.1 Scoring Mechanism

* Start with a perfect score of 100.
* Score based on ratio of number of Request Review to number of completions.
* As more tasks are completed, the score will increase

#### 2.2 Calculation

1. For each new claim:

   ```
    Score = [(Successfully completed jobs - Approved refund jobs) / Successfully completed jobs] * 100
   ```

#### 2.3 Request Review Verification Process

* Implement a claim review process to verify the validity of user claims before applying score deductions.
* Manual review for each case.
*

### 3. Integration with Total Reputation Score

#### 3.1 Updated Future Version Composition

| Component         | Weight | Description                                        |
| ----------------- | ------ | -------------------------------------------------- |
| Machine Uptime    | 10%    | Availability of the CP based on continuous pinging |
| Join Time         | 10%    | Longevity of the CP in the system                  |
| User Review Score | 10%    | Feedback provided by users on finished jobs        |
| User Claim Score  | 25%    | Impact of confirmed user claims on jobs            |
| System Job Score  | 30%    | Performance on controlled, system-initiated jobs   |
| User Job Score    | 15%    | Success rate of user-initiated jobs                |

#### 3.2 Updated Total Score Calculation

The total reputation score calculation remains the same, but now includes the new components:

```
Total Score = (Machine Uptime * 0.10) + (Join Time * 0.10) + (User Review Score * 0.10) + 
              (User Claim Score * 0.25) + (System Job Score * 0.30) + (User Job Score * 0.15)
```

#### 3.3 Example Calculation with New Components

Let's consider a CP with the following scores:

* Machine Uptime: 99.5 points
* Join Time: 80 points
* User Review Score: 90 points
* User Claim Score: 95 points
* System Job Score: 85 points
* User Job Score: 92 points

Total Score = (99.5 \* 0.10) + (80 \* 0.10) + (90 \* 0.10) + (95 \* 0.25) + (85 \* 0.30) + (92 \* 0.15) = 9.95 + 8 + 9 + 23.75 + 25.5 + 13.8 = 90 points

This CP would be considered to have excellent overall performance.


# Dynamic Pricing

## 1. Introduction

In the fast-paced world of cloud computing and AI, the demand for GPU resources fluctuates rapidly. Our new dynamic pricing strategy aims to optimize resource allocation by implementing a quadratic demand model. This approach ensures that prices respond more aggressively to high demand, promoting efficient resource utilization and improved accessibility for all users.

### Abstract Workflow

![dynamic\_pricing\_overview.png](/files/xDd9k4hfzHSuhbO5KfZV)

## 2. Why a Quadratic Demand Model?

### Advantages of Quadratic Pricing:

* More responsive to high-demand situations
* Encourages efficient resource usage during peak times
* Provides better price signals to users about resource scarcity
* Allows for more nuanced pricing across different demand levels

## 3. Quadratic Dynamic Pricing Model

Our new model uses a quadratic equation to calculate the demand factor, which is then used to adjust the base price of resources in real-time.

### Core Formula:

```
New Price = Demand Factor * Base Price
```

Where:

* Base Price: The standard price set for the resource
* Demand Factor: A multiplier based on current demand (range: 1.0 to 5.0)

### Demand Factor Calculation:

The demand factor is now calculated using a quadratic function:

```
Demand Factor = 1 + 4 * (w1 * H + w2 * C)^2
```

Where:

* H: Historical usage factor (0 to 1)
* C: Current resource availability factor (0 to 1)
* w1 = 0.35 (weight for historical usage)
* w2 = 0.65 (weight for current availability)

This quadratic formula ensures that the demand factor grows more rapidly as demand increases, with a maximum value of 5.0.

## 4. Base Price Determination

Before applying our dynamic pricing model, we first establish a base price for each type of computing resource. This base price is derived from the prices set by our various Computing Providers (CPs).

### 4.1 Computing Provider Pricing

Each CP sets their own prices for different hardware resources, including:

* CPU (price per core per hour)
* GPU (price per GPU per hour)
* Memory (price per GB per hour)
* Storage (price per GB per hour)

### 4.2 Weighted Arithmetic Mean Calculation

For each type of resource, we calculate a Weighted Arithmetic Mean (WAM) across the available resource from all CPs. This WAM becomes our base price for that resource.

The formula for WAM is:

```
WAM = (Σ (Price_i * Weight_i)) / (Σ Weight_i)
```

Where:

* Price\_i is a unique price point set by one or more CPs
* Weight\_i is the number of CPs that have set their price to Price\_i

This approach ensures that our base price is more heavily influenced by the most common price points among our CPs.

#### Let's look at how different CP prices affect the base price for memory:

```
CP1: $0.010 per GB per hour
CP2: $0.010 per GB per hour
CP3: $0.012 per GB per hour
CP4: $0.010 per GB per hour
CP5: $0.015 per GB per hour
CP6: $0.012 per GB per hour
```

Grouping by unique prices:

```
$0.010: Weight = 3 (set by CP1, CP2, CP4)
$0.012: Weight = 2 (set by CP3, CP6)
$0.015: Weight = 1 (set by CP5)
```

WAM Calculation:

```
WAM = (0.010*3 + 0.012*2 + 0.015*1) / (3 + 2 + 1)
    = 0.069 / 6
    = $0.0115 per GB per hour
```

This WAM of $0.0115 would then be used as the base price for memory in our dynamic pricing calculations.

### 4.3 Composite Base Price

For each hardware configuration we offer, we calculate a composite base price by summing the WAM prices of its components:

```
Base Price = (CPU_WAM * #cores) + (GPU_WAM * #GPUs) + (Memory_WAM * #GB) + (Storage_WAM * #GB)
```

## 5. Components of the Demand Factor

### 5.1 Historical Resource Usage (H)

We analyze the past 30 days of usage data, focusing on patterns in daily and weekly usage.

Calculation:

```
H = (Current Hour Avg Usage - Overall Avg Usage) / (Max Usage - Overall Avg Usage)
```

### 5.2 Current Resource Availability (C)

This factor considers the current occupation rate of resources, but only starts contributing when more than 40% of resources are occupied.

Calculation:

```
If (Occupied Resources / Total Resources) <= 0.4:
    C = 0
Else:
    C = ((Occupied Resources / Total Resources) - 0.4) / 0.6
```

## 6. Price Model

![dynamic\_pricing\_chart.png](/files/dWDy5WzKAr6BKaGPYWrc)

## 7. Example Scenarios

### Scenario 1: Low Demand

* Historical Usage: Low (H = 0.2)
* Current Availability: 45% resources occupied (C = 0.083)

```
Weighted Sum = 0.35 * 0.2 + 0.65 * 0.083 = 0.124
Demand Factor = 1 + 4 * (0.124)^2 = 1.061
For a base price of $10/hour: New Price = 1.061 * $10 = $10.61/hour
```

### Scenario 2: Moderate Demand

* Historical Usage: Average (H = 0.5)
* Current Availability: 70% resources occupied (C = 0.5)

```
Weighted Sum = 0.35 * 0.5 + 0.65 * 0.5 = 0.5
Demand Factor = 1 + 4 * (0.5)^2 = 2.0
For a base price of $10/hour: New Price = 2.0 * $10 = $20/hour
```

### Scenario 3: High Demand

* Historical Usage: High (H = 0.8)
* Current Availability: 90% resources occupied (C = 0.833)

```
Weighted Sum = 0.35 * 0.8 + 0.65 * 0.833 = 0.821
Demand Factor = 1 + 4 * (0.821)^2 = 3.697
For a base price of $10/hour: New Price = 3.697 * $10 = $36.97/hour
```

### Scenario 4: Peak Demand

* Historical Usage: Very High (H = 1.0)
* Current Availability: 100% resources occupied (C = 1.0)

```
Weighted Sum = 0.35 * 1.0 + 0.65 * 1.0 = 1.0
Demand Factor = 1 + 4 * (1.0)^2 = 5.0
For a base price of $10/hour: New Price = 5.0 * $10 = $50/hour
```

## 8. Conclusion

This comprehensive dynamic pricing strategy ensures that our prices reflect both the most common price points among our Computing Providers and the current market demand. By using a frequency-weighted average of CP prices, we establish a fair baseline that represents the consensus pricing in our provider ecosystem. The subsequent application of our quadratic dynamic pricing model then allows us to respond effectively to changes in demand, ensuring efficient resource allocation and maximizing value for all stakeholders in our computing ecosystem. This approach not only captures market trends in resource pricing but also adapts quickly to shifts in user demand, creating a responsive and efficient pricing mechanism.


# CDN Layer

Coming soon...


# Tokenomics

SwanChain Tokenomics and Governance Framework

## Overview

SwanChain introduces a comprehensive tokenomics structure designed to support its ecosystem's growth, incentivize participation, and ensure operational sustainability. This document outlines the strategic allocation, governance mechanisms, planned token release schedule, and specific formulas for the Fog Computing Providers (FCP), Edge Computing Providers (ECP), and Market Providers (MP) to provide a clear understanding of how SwanChain utilizes its native tokens to drive network engagement and development.

### Total Token Supply

* **Total Supply:** 1,000,000,000 Swan Tokens

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

### Token Allocation and Distribution Breakdown

#### 1. Early Purchasers (20%)

* **Purpose:** To fund the initial development and expansion phases of SwanChain.
* **Details:** Early Purchasers provide essential capital for foundational buildout and scaling operations. This funding supports technical development, operational infrastructure, and initial market strategies.
* **Unlock Schedule:**
  * 1.8% unlocked at TGE (Token Generation Event).
  * Remaining tokens distributed linearly over 4–8 quarters after a 6-month cliff.

#### 2. DAO Treasury (20%)

* **Purpose:** To manage investments, cover legal costs, and other financial necessities.
* **Details:** The DAO Treasury is critical for financial management and operational expenditures. It is funded by contributions from market providers and is used for strategic investments and covering essential expenses such as legal fees.
* **Unlock Schedule:**
  * 2% unlocked at TGE .
  * Remaining tokens distributed linearly over 40 quarters.

#### 3. Ecosystem Fund (25%)

* **Purpose:** To support ecosystem growth through grants, projects, and other initiatives.
* **Details:** This fund is crucial for nurturing innovation within the SwanChain ecosystem, providing financial support to developers, startups, and community projects that contribute to the network’s enhancement.
* **Unlock Schedule:**
  * 4% unlocked at TGE.
  * Remaining tokens distributed linearly over 16 quarters.

#### 4. Core Contributors (15%)

* **Purpose:** To reward and retain the developers and team members who are integral to the development and maintenance of SwanChain.
* **Details:** This allocation ensures that the developers and personnel central to SwanChain’s operations are motivated and retained, facilitating ongoing innovation and network maintenance.
* **Unlock Schedule:**
  * 0% unlocked at TGE.
  * Remaining tokens distributed linearly over 12 quarters after a 6-month cliff.

#### 5. Airdrops (20%)

* **Purpose:** To incentivize broad network participation and engagement.
* **Details:** Airdrops distribute Swan tokens widely across the community to stimulate network activity and growth, enhancing user adoption and community vibrancy. 10% of the total supply has been reserved for computing providers over the years. The annual airdrop rate cannot exceed 10% of the current circulation supply.
* 2% unlocked at TGE.
* Remaining tokens distributed linearly over 32 quarters.

### Token Flow Diagram

<figure><img src="/files/xeCEr0hGrjVk2mvm2Kdd" alt=""><figcaption><p>Token Flow Diagram</p></figcaption></figure>

### Governance and Incentives

#### Governance Participation

* **Collateral Requirement:** Community members must stake tokens to participate in governance decisions.
* **Governance Rewards:** Active participants may receive rewards, such as 1% of the DAO Treasury, to incentivize involvement and wise decision-making.


# UBI Allocation Curve

Universal Basic Income (UBI) and Paid Job Compensation for Computing Providers (CP) in Swan Chain

### **Table of Contents**

* [Introduction](https://docs.swanchain.io/core-concepts/token/swan-universal-basic-income-ubi#introduction)
* [Compensation Model](https://docs.swanchain.io/core-concepts/token/swan-universal-basic-income-ubi#compensation-model)
* [Algorithm Implementation](https://docs.swanchain.io/core-concepts/token/swan-universal-basic-income-ubi#algorithm-implementation)
* [Visualization of Income Over Time](https://docs.swanchain.io/core-concepts/token/swan-universal-basic-income-ubi#visualization-of-income-over-time)
  * [Interpretation of the Plots](https://docs.swanchain.io/core-concepts/token/swan-universal-basic-income-ubi#interpretation-of-the-plots)
  * [Data Points Illustration](https://docs.swanchain.io/core-concepts/token/swan-universal-basic-income-ubi#data-points-illustration)
  * [Impact of the Design](https://docs.swanchain.io/core-concepts/token/swan-universal-basic-income-ubi#impact-of-the-design)
  * [Conclusion](https://docs.swanchain.io/core-concepts/token/swan-universal-basic-income-ubi#conclusion)
  * [Future Work](https://docs.swanchain.io/core-concepts/token/swan-universal-basic-income-ubi#future-work)
* [Appendix](https://docs.swanchain.io/core-concepts/token/swan-universal-basic-income-ubi#appendix)
  * [Sample Calculations](https://docs.swanchain.io/core-concepts/token/swan-universal-basic-income-ubi#sample-calculations)

### **Introduction**

Swan Chain is a decentralized network that connects computing providers with users requiring computational resources. To foster early network growth and incentivize CPs to join and contribute resources, a dual compensation mechanism has been designed:

1. **Universal Basic Income (UBI)**: Provides CPs with a predictable token income when their resources are underutilized.
2. **Paid Jobs**: Offers market-priced compensation for computational tasks requested by users.

This mechanism ensures a fair and gradual distribution of tokens to providers, supporting the network's expansion until it reaches a critical mass of user-paid tasks. Importantly, the UBI distribution rate is influenced by the resource usage rate, and CPs earn market-based compensation when engaged in paid jobs.

***

## **Compensation Model**

$$
I(x) = A \cdot x^{B} \cdot e^{-C x} \cdot (1 - u(x)) + P\_{\text{market}}(x) \cdot u(x)
$$

The total daily income $$I(x)$$for a computing provider on day $$( x )$$ comprises two components:

1. **UBI Income** $$y\_{\text{UBI}}(x)$$
2. **Paid Job Income** $$y\_{\text{Paid}}(x)$$

The **UBI income** is modeled using a gamma-like function adjusted by the resource usage rate $$u(x)$$:

$$
y\_{\text{UBI}}(x) = A \cdot x^{B} \cdot e^{-C x} \cdot (1 - u(x))
$$

Where:

* $$A = 20,000$$ (Scaling factor)
* $$B = 0.3100$$ (Growth rate exponent)
* $$C = 0.0017$$ (Decay rate constant)
* $$x$$ is the day number, starting from 1
* $$u(x)$$ is the **resource usage rate** on day$$( x )$$ (ranging from 0 to 1)

The **paid job income** depends on the market demand and the resource utilization:

$$
y\_{\text{Paid}}(x) = P\_{\text{market}}(x) \cdot u(x)
$$

Where:

* $$P\_{\text{market}}(x)$$ is the total market value for computational resources on day $$( x )$$
* $$u(x)$$ represents the proportion of a CP's resources utilized by paid job

#### Defining $$u(x)$$

**(1) Calculate the total duration of real GPU orders across the network**

$$
T\_{day}= \sum\limits\_{i}Task\_{ECP,i}(GPU\_k)  \times  f\_k + \sum\limits\_{j}Task\_{FCP,j}(GPU\_k)  \times  f\_k  \times W\_{FCP}
$$

Where:

* $$Task\_{\text{FCP},i}(GPU\_k)$$ represents the time that the $$i$$-th FCP task uses $$GPU\_k$$.
* $$Task\_{\text{ECP},j}(GPU\_k)$$ represents the time that the $$j$$-th ECP task uses $$GPU\_k$$.
* $$f\_k$$ represents the earnings growth factor
* $$W\_{FCP}$$ represents the FCP resource bonus ratio, currently set at a constant value of 1.2

{% hint style="info" %}
**NOTE:** The value of $$W\_{FCP}$$, 1.2, means that if the same configuration of servers is deployed for FCP, it will generate 20% more earnings than ECP.
{% endhint %}

**（2）Calculate the total available usage time for all GPUs in the network**

$$
T\_{total} =  \sum\limits\_k N\_{ECP}(GPU\_k) \times 24   \times f\_k +  \sum\limits\_k N\_{FCP}(GPU\_k) \times 24   \times f\_k \* W\_{FCP}
$$

Where:

* $$N\_{\text{FCP}}(\text{GPU}\_k)$$represents the number of $$\text{GPU}\_k$$ *in FCP*
* $$N\_{\text{ECP}}(\text{GPU}\_k)$$ represents the number of $$\text{GPU}\_k$$ in ECP.

**(3) Calculate** $$u(x)$$

$$
u(x) = \frac{T\_{\text{day}}}{T\_{\text{total}}}
$$

#### Defining Total Market Value $$P\_{\text{market}}(x)$$

$$P\_{\text{market}}(x)$$ represents the cost in Swan Tokens when all GPUs in the CP are fully utilized:

$$
P\_{market}{(x)} =  \sum\limits\_k N\_{ECP}(GPU\_k)   \times Price({GPU\_k})  \times 24 +  \sum\limits\_k N\_{FCP}(GPU\_k)  \times W\_{FCP} \times Price({GPU\_k})  \times 24
$$

Where:

* $$Price(GPU\_k)$$ is the price of $$GPU\_k$$.
* $$W\_{FCP}$$ represents the FCP resource bonus ratio, currently set at a constant value of 1.2
* $$N\_{\text{FCP}}(\text{GPU}\_k)$$represents the number of $$\text{GPU}\_k$$ *in FCP*
* $$N\_{\text{ECP}}(\text{GPU}\_k)$$ represents the number of $$\text{GPU}\_k$$ in ECP.

## **Algorithm Implementation**

The compensation mechanism proceeds as follows:

1. **Initialization**: Set day $$(x = 1)$$.
2. **Determine Resource Usage Rate**: Calculate $$u(x)$$ based on the CP's resource utilization by paid jobs.
3. **Compute UBI Income**:

$$
y\_{\text{UBI}}(x) = 20,000 \times x^{0.3100} \times e^{-0.0017 x} \times (1 - u(x))
$$

4. **Compute Paid Job Income**:

$$
y\_{\text{Paid}}(x) = P\_{\text{market}}(x) \times u(x)
$$

5. **Calculate Total Income**:

$$
I(x) = y\_{\text{UBI}}(x) + y\_{\text{Paid}}(x)
$$

6. **Distribute Income**: Allocate $$I(x)$$ to CPs based on their resource contributions and utilization.
7. **Increment Day**: Increase $$x$$ by 1.
8. **Repeat**: Continue the process for each subsequent day.

This algorithm ensures that CPs are incentivized to contribute resources to the network, receiving UBI when their resources are underutilized and earning market-based compensation when engaged in paid jobs.

***

## **Visualization of Income Over Time**

#### **Scenarios**

We consider three scenarios to illustrate how CPs' income evolves over time:

1. **No Paid Jobs** $$u(x) = 0$$ : CPs receive income solely from UBI.
2. **Low Paid Job Demand** $$u(x) = 0.1$$: CPs primarily earn UBI income with a small contribution from paid jobs.
3. **Increasing Paid Job Demand**: Resource usage rate $$u(x)$$ increases over time, shifting CPs' income from UBI to paid jobs.

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

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

### **Interpretation of the Plots**

**1. Total Income Over 720 Days**

* **Scenario 1:** $$u(x) = 0$$
  * CPs receive income solely from UBI.
  * The total income decreases gradually over time due to the decay in the UBI function.
* **Scenario 2:** $$u(x) = 0.1$$
  * CPs receive slightly less UBI income than in Scenario 1 due to the 10% resource usage.
  * Paid job income contributes minimally, resulting in a slightly lower total income.
* **Scenario 3:** $$Increasing u(x)$$
  * Initially, total income is similar to Scenario 1.
  * As $$u(x)$$ increases, paid job income increases while UBI income decreases.
  * Total income remains relatively stable or increases slightly, demonstrating that paid job income offsets the reduction in UBI.

**2. Income Components for Scenario 3**

* **UBI Income**:
  * Decreases over time as resource usage rate $$u(x)$$ increases.
  * Reflects the transition from reliance on UBI to paid jobs.
* **Paid Job Income**:
  * Increases over time with the increase in $$u(x)$$ .
  * Compensates for the decrease in UBI income.
* **Total Income Stability**:
  * The sum of UBI and paid job income maintains income stability for CPs.

**3. Resource Usage Rate** $$u(x)$$ **for Scenario 3**

* Shows a smooth increase from 0 to 0.8 over 720 days.
* Reflects the gradual adoption of paid tasks in the network.

### **Data Points Illustration**

Below is a example table of computed token allocations for selected days(assume $$u(x)$$=0):

| Day | Daily UBI (y) | Cumulative UBI |
| --- | ------------- | -------------- |
| 1   | 19,966.03     | 19,966.03      |
| 30  | 54,549.22     | 1,261,976.56   |
| 60  | 64,262.68     | 3,062,143.25   |
| 90  | 69,246.55     | 5,072,341.49   |
| 120 | 71,941.60     | 7,194,431.61   |
| 150 | 73,261.06     | 9,375,212.61   |
| 180 | 73,666.56     | 11,581,013.65  |
| 210 | 73,430.22     | 13,788,817.87  |
| 240 | 72,728.28     | 15,982,188.47  |
| 270 | 71,682.24     | 18,149,084.82  |
| 300 | 70,379.70     | 20,280,565.34  |
| 330 | 68,885.86     | 22,369,958.88  |
| 360 | 67,250.50     | 24,412,305.58  |
| 390 | 65,512.29     | 26,403,963.32  |
| 420 | 63,701.70     | 28,342,321.28  |
| 450 | 61,843.01     | 30,225,585.83  |
| 480 | 59,955.70     | 32,052,616.78  |
| 510 | 58,055.51     | 33,822,799.99  |
| 540 | 56,155.17     | 35,535,946.61  |
| 570 | 54,265.01     | 37,192,212.48  |
| 600 | 52,393.39     | 38,792,032.93  |
| 630 | 50,547.09     | 40,336,069.55  |
| 660 | 48,731.55     | 41,825,166.37  |
| 690 | 46,951.10     | 43,260,313.71  |
| 720 | 45,209.18     | 44,642,617.97  |

Note: The "Cumulative UBI" column represents the definite integral of y(x) from day 1 to the specified day.

{% hint style="warning" %}
This table shows simulated data for UBI distribution calculated under the condition of U(x) = 0. The actual UBI release will dynamically change based on the network CP resource utilization rate.
{% endhint %}

***

### **Impact of the Design**

#### **Incentivizing Optimal Resource Utilization**

* **Adaptive Compensation**: CPs are motivated to engage in paid jobs as they become available, earning higher income through market rates.
* **Resource Availability**: UBI ensures that CPs keep their resources available to the network, even during periods of low demand.

#### **Sustainable Long-Term Distribution**

* **Transition to Market-Based Economy**: As the network matures and paid job demand increases, CPs naturally shift from UBI reliance to market compensation.
* **Controlled Token Issuance**: The decreasing UBI allocation over time prevents token oversupply, maintaining economic stability.

#### **Economic Implications**

* **Income Stability**: CPs benefit from a combination of UBI and paid job income, smoothing income fluctuations.
* **Market Alignment**: Compensation reflects real-time network demand, promoting efficient resource allocation.

***

### **Conclusion**

The combined UBI and paid job compensation model for Swan Chain computing providers effectively balances incentives, supporting early network growth while promoting efficient resource utilization. By dynamically adjusting CPs' income based on resource usage rates and market demand, the model ensures sustainable network development and economic stability as the network transitions to a mature, user-driven ecosystem.

***

### **Future Work**

* **Dynamic Market Pricing**: Implement real-time market pricing mechanisms for paid jobs to reflect supply and demand accurately.
* **Adaptive UBI Parameters**: Explore methods to adjust UBI parameters ( A ), ( B ), and ( C ) based on network growth metrics.
* **Enhanced Monitoring Tools**: Develop systems to track resource usage and job completion accurately, ensuring fair compensation.

***

## **Appendix**

### Sample Calculations

**Scenario 1: No Paid Jobs**

**Day 1:**

* **UBI Income:**\
  $$y\_{\text{UBI}}(1) = 20000 \times 1^{0.31} \times e^{-0.0017 \times 1} \approx 19,965.90 , \text{tokens}$$
* **Paid Job Income:**\
  $$0 , \text{tokens}$$ (No paid job demand)
* **Total Income:**\
  $$I(1) = 19,965.90 + 0 = 19,965.90 , \text{tokens}$$

**Scenario 2: Low Paid Job Demand**

**Day 1:**

* **UBI Income:**\
  $$y\_{\text{UBI}}(1) = 20000 \times 1^{0.31} \times e^{-0.0017 \times 1} \approx 19,965.90 , \text{tokens}$$
* **Paid Job Income:**\
  $$y\_{\text{Paid}}(1) = 50000 \times 0.1 = 5,000 , \text{tokens}$$
* **Total Income:**\
  $$I(1) = 19,965.90 + 5,000 = 24,965.90 , \text{tokens}$$

**Scenario 3: Increasing Paid Job Demand**

**Day 360:**

* **UBI Income:**\
  $$y\_{\text{UBI}}(360) = 20000 \times 360^{0.31} \times e^{-0.0017 \times 360} \approx 13,898.99 , \text{tokens}$$
* **Paid Job Income:**\
  $$y\_{\text{Paid}}(360) = 50000 \times 0.4 = 20,000 , \text{tokens}$$
* **Total Income:**\
  $$I(360) = 13,898.99 + 20,000 = 33,898.99 , \text{tokens}$$

**Day 720:**

* **UBI Income:**\
  $$y\_{\text{UBI}}(720) = 20000 \times 720^{0.31} \times e^{-0.0017 \times 720} \times (1 - 0.8) \approx 2,477.66 , \text{tokens}$$
* **Paid Job Income:**\
  $$y\_{\text{Paid}}(720) = 50000 \times 0.8 = 40,000 , \text{tokens}$$
* **Total Income:**\
  $$I(720) = 2,477.66 + 40,000 = 42,477.66 , \text{tokens}$$

#### Observations

* **Income Stability:** Despite the decrease in UBI income over time, total income remains stable or increases due to higher compensation from paid jobs.
* **Incentive Alignment:** Community participants (CPs) are incentivized to participate in paid jobs without experiencing significant income loss during transitions from UBI reliance to paid employment.

***


# Computing Provider Income

Swan Chain is a decentralized network that connects computing providers with users requiring computational resources. To foster early network growth and incentivize CPs to join and contribute resources, a dual compensation mechanism has been designed:

1. **Universal Basic Income (UBI)**: Provides CPs with a predictable token income when their resources are underutilized.
2. **Paid Jobs**: Offers market-priced compensation for computational tasks requested by users.

This mechanism ensures a fair and gradual distribution of tokens to providers, supporting the network's expansion until it reaches a critical mass of user-paid tasks. Importantly, the UBI distribution rate is influenced by the resource usage rate, and CPs earn market-based compensation when engaged in paid jobs.

### **Total Income**

The total daily income $$I(x)$$for a computing provider on day $$( x )$$ comprises two components:

* **UBI Income** $$y\_{\text{UBI}}(x)$$
* **Paid Job Income** $$y\_{\text{Paid}}(x)$$

$$
I(x) = y\_{\text{UBI}}(x) + y\_{\text{Paid}}(x)
$$

Substituting the expressions for $$y\_{\text{UBI}}(x)$$ and $$y\_{\text{Paid}}(x)$$

$$
I(x) = A \cdot x^{B} \cdot e^{-C x} \cdot (1 - u(x)) + P\_{\text{market}}(x) \cdot u(x)
$$

#### **Resource Usage Rate Impact**

* **When** $$u(x) = 0$$:
  * CP receives full UBI allocation.
  * No income from paid jobs.
* **When** $$u(x) = 1$$:
  * All resources are utilized by paid jobs.
  * CP receives full income from paid jobs.
  * No UBI allocation.
* **Intermediate Values**:
  * CP's income is a combination of UBI and paid job compensation, proportional to resource utilization.

### Individual CP's UBI

To calculate the UBI for a single CP, we consider both the resource usage and completion rates of tasks. UBI allocation is conditional on sufficient resource contribution and performance metrics:

**(1) UBI Workload Calculation**

* Calculate the daily completion rate of a single ECP zk-task: $$P\_{\text{ECP}}$$
* Calculate the completion rate of a single FCP sampling task: $$P\_{\text{FCP}}$$
* Number of GPUs: $$N\_{\text{ECP}}(GPU\_k)$$ and GPU types.
* Calculate the total UBI workload:

$$
UBI\_{\text{total}} = UBI\_{\text{ECP}} + UBI\_{\text{FCP}}
$$

$$
UBI\_{ECP}=\sum\limits\_i (\sum\limits\_k N\_{ECP,i}(GPU\_k) \times f\_k)
$$

$$
UBI\_{FCP}=\sum\limits\_j (\sum\limits\_k N\_{FCP,j}(GPU\_k) \times f\_k) \*W\_{FCP}
$$

**(2) Calculating the UBI for a single CP**:

As an ECP:

$$
UBI\_{\text{ECP},i}(x) = \frac{\sum\limits\_k N\_{\text{ECP},i}(GPU\_k) \times f\_k \times P\_{\text{ECP},i}}{UBI\_{\text{ECP}} + UBI\_{\text{FCP}}} \times y\_{\text{UBI}}(x)
$$

As an FCP:

$$
UBI\_{FCP,i}(x)= \frac{\sum\limits\_k N\_{FCP,i}(GPU\_k) \times f\_k \times P\_{FCP,i} \times W\_{FCP} }{UBI\_{ECP}+UBI\_{FCP}} \times y\_{\text{UBI}}(x)
$$

***

### Conditions for CP to Receive UBI

A CP must meet certain conditions to qualify for UBI:

1. **Sufficient Collateral**:

$$
Collateral\_{ECP}= \sum\limits\_k N\_{ECP}(GPU\_k) \times C\_{base} \times f\_k
$$

$$
Collateral\_{FCP}= \sum\limits\_k N\_{FCP}(GPU\_k) \times C\_{base} \times f\_k  \times W\_{FCP}
$$

Where:

* $$N\_{ECP}(GPU\_k)$$ represents the number of ECP for $$GPU\_k$$
* $$C\_{\text{base}}$$ is the base collateral, with an initial value of 3533 (this value will be dynamically adjusted based on the daily computing units of the entire network; for specific adjustment rules, check [here](/core-concepts/token/computing-provider-collateral/collateral-requirement-and-earning-multiplier))
* $$N\_{\text{FCP}}(\text{GPU}\_k)$$represents the number of $$\text{GPU}\_k$$ *in FCP*
* $$N\_{\text{ECP}}(\text{GPU}\_k)$$ represents the number of $$\text{GPU}\_k$$ in ECP.
* $$W\_{FCP}$$ represents the FCP resource bonus ratio, currently set at a constant value of 1.2

{% hint style="info" %}
**NOTE:** The value of $$W\_{FCP}$$, 1.2, means that if the same configuration of servers is deployed for FCP, it will generate 20% more earnings than ECP.
{% endhint %}

2. **Completion of Basic Test Tasks:**

* FCP: Sampling task
* ECP: ZK task

3. GPU count and type are also factored into the UBI eligibility.

#### Exit Mechanism:

* CP Exit Mechanism If a CP wishes to exit, they must set `taskType` = 100.
  * The CP will no longer receive any tasks and will not incur any collateral deductions.
  * The CP will no longer appear on [the current dashboard list.](https://provider.swanchain.io/overview)
* CPs can request to withdraw their collateral, but this requires a 7-day confirmation period to ensure settlement before the withdrawal is finalized (first `requestWithdraw`, followed by `confirmRequest` after 7 days).

***

## Swan 2.0: Market-Driven Income <a href="#swan-2.0-market-driven-income" id="swan-2.0-market-driven-income"></a>

{% hint style="info" %}
The UBI model described above served as the **bootstrap phase** (Swan 1.0) that built the initial provider network. Swan 2.0 introduces contribution-based rewards that complement and gradually replace UBI. See [SIP-002](https://github.com/swanchain/governance/discussions/16) for the full proposal.
{% endhint %}

With the launch of the [Inference Cloud](https://github.com/swanchain/docs/blob/main/core-concepts/swan-2.0-inference-cloud.md), Computing Provider income transitions from UBI-only to a dual-income model where providers earn based on actual work performed.

### Dual Income Streams

Under Swan 2.0, providers earn through two complementary channels:

1. **Inference Revenue (Stablecoins)** — Direct payment in USDC for serving inference requests through the [Inference Marketplace](/core-concepts/market-provider/inference-marketplace)
2. **Contribution Rewards (SWAN Tokens)** — Daily SWAN token rewards allocated proportionally based on contribution score

When paid inference requests generate protocol revenue, the split is:

| Recipient           | Share                          |
| ------------------- | ------------------------------ |
| Provider            | 70% (paid in request currency) |
| Protocol Treasury   | 20%                            |
| SWAN Buyback & Burn | 10%                            |

### Contribution Score

Each provider receives a daily Contribution Score that determines their share of the SWAN token reward pool:

$$
\text{Contribution\_Score} = W\_{inf} \times \text{norm}(\text{inferences}) + W\_{tok} \times \text{norm}(\text{tokens}) + W\_{up} \times \text{uptime} + W\_{qual} \times \text{quality} + W\_{div} \times \text{diversity}
$$

Where the weights are:

| Component     | Weight | Description                                        |
| ------------- | ------ | -------------------------------------------------- |
| $$W\_{inf}$$  | 0.30   | Inference volume — number of requests processed    |
| $$W\_{tok}$$  | 0.25   | Token throughput — total input + output tokens     |
| $$W\_{up}$$   | 0.20   | Uptime — 30-day uptime percentage                  |
| $$W\_{qual}$$ | 0.15   | Quality — success rate adjusted by latency         |
| $$W\_{div}$$  | 0.10   | Model diversity — number of distinct models served |

And the component scores are:

$$
\text{norm}(x) = \frac{x}{\max(x\_{\text{all providers}})}
$$

$$
\text{uptime\_score} = \frac{\text{uptime}\_{30d}}{100}
$$

$$
\text{quality\_score} = \text{success\_rate} \times (1 - \text{norm}(\text{avg\_latency}))
$$

$$
\text{diversity\_score} = \frac{\text{models\_served}}{\text{max\_models\_in\_catalog}}
$$

### Minimum Contribution Thresholds

To prevent reward fragmentation and gaming:

| Threshold            | Requirement     | Effect if Not Met                  |
| -------------------- | --------------- | ---------------------------------- |
| Minimum Uptime       | 80% over 7 days | Excluded from contribution pool    |
| Minimum Inferences   | 100/week        | Reduced to 50% contribution weight |
| Minimum Success Rate | 90%             | Reduced to 75% contribution weight |
| Minimum Online Hours | 120 hours/week  | Pro-rated availability bonus       |

### 3-Phase Transition

The transition from UBI to contribution-based rewards follows an accelerated 3-month timeline:

**Phase 1: Hybrid Mode (Month 1)**

$$
\text{Daily\_Reward} = \text{UBI\_Base} \times 0.75 \times (1 - u) + \frac{\text{Score}\_i}{\sum \text{Scores}} \times \text{Contribution\_Pool}
$$

Where the Contribution Pool is 25% of the current daily UBI allocation.

**Phase 2: Contribution-Weighted UBI (Month 2)**

$$
\text{Daily\_Reward} = \text{UBI\_Base} \times 0.50 \times \text{availability} + \frac{\text{Score}\_i}{\sum \text{Scores}} \times \text{Contribution\_Pool}
$$

Where the Contribution Pool increases to 50% and availability requires maintaining 95%+ uptime.

**Phase 3: Pure Contribution Mode (Month 3+)**

$$
\text{Daily\_Reward} = \frac{\text{Score}\_i}{\sum \text{Scores}} \times \text{Reward\_Pool} + \text{Availability\_Bonus}
$$

Where the Availability Bonus (10% of the daily pool) incentivizes standby capacity, weighted by hardware tier:

| Hardware Tier            | Multiplier |
| ------------------------ | ---------- |
| RTX 3090 / A4000         | 1.0x       |
| RTX 4090 / A5000 / A6000 | 1.5x       |
| A100                     | 2.5x       |
| H100                     | 4.0x       |

### Payout Structure

| Component                     | Allocation |
| ----------------------------- | ---------- |
| Liquid SWAN                   | 80%        |
| Locked SWAN (3-month vesting) | 20%        |

### Unified Computing Provider (CP) Role

Under Swan 2.0, the legacy ECP and FCP roles merge into a single **Computing Provider (CP)** classification. All providers are evaluated equally based on contribution metrics, regardless of their previous role.

**Migration path for existing providers:**

1. ECPs and FCPs running inference tasks are automatically converted to unified CP role
2. Providers not running inference have a 30-day grace period to onboard to Swan Inference or migrate staked SWAN to SwanFi
3. Hardware requirements: ≥ 24 GB VRAM recommended; ≥ 48 GB VRAM for priority task routing


# Computing Provider Collateral

#### **Introduction**

In the Swan Chain network, Computing Providers (CPs) contribute their computational resources to support the network's decentralized computing infrastructure. To ensure stability and economic security, CPs are required to provide collateral in Swan tokens. This collateral acts as a financial commitment, incentivizing CPs to act in the best interest of the network while also sharing in the economic rewards generated from providing computing power.

#### **Collateral Model**

The collateral amount for each CP is determined by an inverse correlation model based on the total computing power contributed by the CP to the network. The formula for calculating the collateral amount is:

$$
C\_{base} =  \frac{C\_{total}}{CU\_{total}}  + b
$$

$$
CU\_{total} =\max ( \sum\limits\_k N\_{ECP}(GPU\_k)  \times f\_k +  \sum\limits\_k N\_{FCP}(GPU\_k)    \times f\_k \* W\_{FCP}, CU\_0)
$$

$$
\begin{cases}CU\_0 = 3000 \C\_{total} =  \text{Circulating supply of SWAN} \times 20%  \b=200\end{cases}
$$

Where:

* $$W\_{FCP}$$ represents the FCP resource bonus ratio, currently set at a constant value of 1.2
* $$N\_{\text{FCP}}(\text{GPU}\_k)$$represents the number of $$\text{GPU}\_k$$ *in FCP*
* $$N\_{\text{ECP}}(\text{GPU}\_k)$$ represents the number of $$\text{GPU}\_k$$ in ECP.
* $$f\_k$$ represents the earnings growth factor

Currently, the computing units $$CU\_{\text{total}}$$ in the network are capped at (CU\_0 = 3000). If the computing units remain at or below (3000), the base collateral remains constant at:

$$
C\_{\text{base}} = \frac{10,000,000}{3000} + 200 = 3533
$$

Example: If $$CU\_{\text{total}}$$ **increases to 6000**

1. Substitute $$CU\_{\text{total}}$$ = 6000 into the formula:

$$
C\_{\text{base}} = \frac{10,000,000}{6000} + 200
$$

2. Perform the calculation:

$$
C\_{\text{base}} = 1666.67 + 200 = 1866.67
$$

So, if the computing units (CU) exceed 3000, the base collateral amount will start to decrease. In the example where CU is 6000, the base collateral amount is 1867, which is lower than the 3533 calculated earlier when CU was 3000.

#### **Revenue Sharing and APR Calculation**

Once a CP provides collateral, they are eligible to receive revenue generated from both Universal Basic Income (UBI) tokens and paid jobs. The revenue model includes:

1. **UBI Income**: CPs receive UBI tokens as a baseline income for their participation, which is inversely related to their collateral and computing power.
2. **Paid Job Income**: CPs can earn additional revenue by completing paid jobs, which are offered at a market rate determined by user demand.

The **Annual Percentage Rate (APR)** for the CPs is calculated separately for both their operating revenue and collateral revenue:

* **Operator APR**: The revenue generated by CPs for providing computing power divided by their total operational costs.
* **Collateral APR**: Calculated based on the revenue earned by providing collateral relative to the collateral amount itself.

The **total APR** includes both the operator APR and collateral APR, providing a complete picture of the financial returns for CPs participating in the Swan Chain network.

#### **Slashing Mechanism**

To maintain network performance and accountability, CPs are subject to a precise slashing mechanism that penalizes inefficient or unreliable computing services. For each failed task, CPs face graduated penalties:

* Edge Computing Providers (ECP) lose 0.025% of their current full collateral amount per failed task (approximately 0.88 SWAN for a 3080 GPU), with around 48 tasks processed daily.
* Fog Computing Providers (FCP) lose 0.1% of their current full collateral amount per failed task (approximately 3.533 SWAN for a 3080 GPU), with around 14 tasks processed daily.

If a CP's collateral amount falls below the required threshold, they become ineligible to receive Universal Basic Income (UBI) tasks. To mitigate the risk of unexpected task exclusion, CPs are advised to maintain a buffer in their collateral amount.

#### **Impact of Collateral Model**

The negative correlation between collateral and computing power has several benefits:

1. **Incentivizing Scale**: CPs are encouraged to scale up their contributions to the network, as increasing their computing power reduces their collateral requirements.
2. **Risk Mitigation**: Collateral serves as a safeguard, ensuring that CPs have a financial stake in the network's success and discouraging malicious behavior.
3. **Economic Participation**: By allowing CPs to share in both operator and collateral revenue, the model promotes balanced economic participation, where CPs are rewarded not only for their computational contributions but also for their financial commitment.

***

#### Swan 2.0: Updated Collateral Model <a href="#swan-2.0-collateral" id="swan-2.0-collateral"></a>

{% hint style="info" %}
The collateral model above applies to the legacy UBI system (Swan 1.0). Swan 2.0 introduces additional collateral options and updated tiers for the [Inference Cloud](https://github.com/swanchain/docs/blob/main/core-concepts/swan-2.0-inference-cloud.md). See [SIP-002](https://github.com/swanchain/governance/discussions/16) for the full proposal.
{% endhint %}

**Stablecoin Collateral (New in Swan 2.0)**

Swan 2.0 introduces **stablecoin collateral** via the `ProviderCollateral` smart contract. Providers can deposit USDC or USDT on-chain as an alternative to SWAN token collateral:

* **Supported tokens**: USDC, USDT
* **Supported chains**: Swan Chain (mainnet), Base, Ethereum (configurable)
* **Deposit method**: Provider sends tokens to the contract and submits the `tx_hash` for on-chain verification
* **Refund waiting period**: 7 days from request to withdrawal

Providers can also use **USD (off-chain)** via Stripe, PayPal, or bank transfer, with admin confirmation.

Collateral status follows the lifecycle: `pending → confirmed → refund_requested → refunded`

**Updated Collateral Tiers (SIP-002)**

Under the unified Computing Provider (CP) model, collateral requirements are based on hardware tier:

| Hardware Tier            | Minimum SWAN Collateral | Slashing Conditions                           |
| ------------------------ | ----------------------- | --------------------------------------------- |
| RTX 3090 / A4000         | 5,000 SWAN              | Uptime < 50% for 7 days                       |
| RTX 4090 / A5000 / A6000 | 10,000 SWAN             | Repeated failed requests (> 20% failure rate) |
| A100                     | 25,000 SWAN             | Malicious behavior or gaming detected         |
| H100                     | 50,000 SWAN             | Unauthorized hardware changes                 |

{% hint style="warning" %}
These SIP-002 collateral tiers are a draft proposal subject to governance approval. The legacy collateral formula ($$C\_{base}$$ = 3533 SWAN) continues to apply until SIP-002 is ratified.
{% endhint %}

**Benchmark-Based Slashing (Swan 2.0)**

In addition to the existing task-failure slashing, Swan 2.0 introduces benchmark-based slashing for inference providers:

* The benchmark worker runs every **24 hours**, testing math accuracy, code generation, and response latency
* Providers must pass all thresholds (≥ 50% math, ≥ 50% code, ≤ 5000ms latency)
* **Consecutive failures** trigger slashing: configurable percentage (default **10%**) of collateral per consecutive failure
* Providers that fall below the minimum collateral threshold are suspended from receiving inference requests

**Smart Contracts**

| Contract                      | Network            | Address                                      |
| ----------------------------- | ------------------ | -------------------------------------------- |
| **ProviderCollateral (USDC)** | Swan Chain Mainnet | `0x557f306f917009cf83c32b8b32a79202e79948e5` |
| **SWAN Token**                | Swan Chain Mainnet | `0xAF90ac6428775E1Be06BAFA932c2d80119a7bd02` |


# Collateral Requirement and Computing Unit

The base collateral requirement is **3533 $SWAN**. Different GPU models contribute differently to the network and thus have varying **Computing Unit (CU)** and **Collateral Requirements** Per Card (in $SWAN).

### **About Computing Unit (CU)**

CU, or **Computing Unit**, is a fundamental parameter in Swan Chain. It serves as a virtual unit that quantifies the computational resources contributed by **Computing Providers (CPs)**. Additionally, CU plays a critical role in determining the **collateral requirements** for CPs.

#### **Purpose of CU**

The primary function of CU is to calculate the collateral required for CPs, ensuring they maintain sufficient staking to qualify for **UBI rewards** and **task allocations** on Swan Chain. CPs can check their CU value through the [**Provider Dashboard**](https://provider.swanchain.io/).

#### **Collateral Calculation Formula**

The required **collateral** for CPs is determined using the following formula:

$$
Collateral=CU×Base Collateral
$$

where **CU** represents the number of computing units allocated to a CP, and **Base Collateral** is a predefined constant, currently set at **3,533**.

#### **Example Calculation**

For a CP with a **CU value of 100**, given that the **Base Collateral** is **3,533**, the required collateral would be:

$$
100×3,533=353,300
$$

***

### About Collateral Requirement

The Collateral Requirement Per Card (in $SWAN) provided in the table below are for reference only. These figures may change in real-time based on current GPU prices and market conditions

<table data-full-width="false"><thead><tr><th align="center">GPU model</th><th align="center">Computing Unit</th><th align="center">Collateral Requirement Per Card (in $SWAN)</th></tr></thead><tbody><tr><td align="center">H100 NVL</td><td align="center">28</td><td align="center">98924</td></tr><tr><td align="center">H100 PCIe</td><td align="center">28</td><td align="center">98924</td></tr><tr><td align="center">H100 80GB HBM3</td><td align="center">28</td><td align="center">98924</td></tr><tr><td align="center">H100 SXM</td><td align="center">28</td><td align="center">98924</td></tr><tr><td align="center">H200</td><td align="center">19.9</td><td align="center">70306.7</td></tr><tr><td align="center">A100-SXM4-80GB</td><td align="center">13.6</td><td align="center">48048.8</td></tr><tr><td align="center">A100-PCIE-80GB</td><td align="center">12</td><td align="center">42396</td></tr><tr><td align="center">Titan RTX</td><td align="center">8</td><td align="center">28264</td></tr><tr><td align="center">A10G</td><td align="center">8</td><td align="center">28264</td></tr><tr><td align="center">A800 PCIE</td><td align="center">7.3</td><td align="center">25790.9</td></tr><tr><td align="center">L40s</td><td align="center">6.5</td><td align="center">22964.5</td></tr><tr><td align="center">L4</td><td align="center">7.1</td><td align="center">25084.3</td></tr><tr><td align="center">L40</td><td align="center">6.9</td><td align="center">24377.7</td></tr><tr><td align="center">RTX 5090</td><td align="center">7</td><td align="center">24731</td></tr><tr><td align="center">A100 SXM4-40GB</td><td align="center">7</td><td align="center">24731</td></tr><tr><td align="center">A100-PCIE-40GB</td><td align="center">6.9</td><td align="center">24377.7</td></tr><tr><td align="center">A40</td><td align="center">6.6</td><td align="center">23317.8</td></tr><tr><td align="center">Tesla P4</td><td align="center">5.9</td><td align="center">20844.7</td></tr><tr><td align="center">RTX 6000 Ada Generation</td><td align="center">5.7</td><td align="center">20138.1</td></tr><tr><td align="center">RTX 5000 Ada Generation</td><td align="center">5.5</td><td align="center">19431.5</td></tr><tr><td align="center">RTX A6000</td><td align="center">5.1</td><td align="center">18018.3</td></tr><tr><td align="center">A16</td><td align="center">5.1</td><td align="center">18018.3</td></tr><tr><td align="center">Quadro P4000</td><td align="center">5.1</td><td align="center">18018.3</td></tr><tr><td align="center">RTX A4000</td><td align="center">3.7</td><td align="center">13072.1</td></tr><tr><td align="center">RTX 4500Ada</td><td align="center">3.5</td><td align="center">12365.5</td></tr><tr><td align="center">RTX A4500</td><td align="center">3.5</td><td align="center">12365.5</td></tr><tr><td align="center">RTX 4090</td><td align="center">2.9</td><td align="center">10245.7</td></tr><tr><td align="center">RTX 4090 D</td><td align="center">2.9</td><td align="center">10245.7</td></tr><tr><td align="center">RTX 4080</td><td align="center">2.4</td><td align="center">8479.2</td></tr><tr><td align="center">RTX A5000</td><td align="center">2.4</td><td align="center">8479.2</td></tr><tr><td align="center">QUADRO P2000</td><td align="center">2.3</td><td align="center">8125.9</td></tr><tr><td align="center">RTX 4070 SUPER</td><td align="center">2.2</td><td align="center">7772.6</td></tr><tr><td align="center">A30</td><td align="center">2.2</td><td align="center">7772.6</td></tr><tr><td align="center">Q RTX 8000</td><td align="center">2.2</td><td align="center">7772.6</td></tr><tr><td align="center">RTX 3090 Ti</td><td align="center">2.1</td><td align="center">7419.3</td></tr><tr><td align="center">Tesla V100-PCIE-32GB</td><td align="center">2</td><td align="center">7066</td></tr><tr><td align="center">Tesla V100-SXM2-32GB</td><td align="center">2</td><td align="center">7066</td></tr><tr><td align="center">Tesla V100S-PCIE-32GB</td><td align="center">2</td><td align="center">7066</td></tr><tr><td align="center">RTX 4070S Ti</td><td align="center">2</td><td align="center">7066</td></tr><tr><td align="center">GTX 1050 Ti</td><td align="center">2</td><td align="center">7066</td></tr><tr><td align="center">Quadro P6000</td><td align="center">2</td><td align="center">7066</td></tr><tr><td align="center">RTX 4070 Ti</td><td align="center">1.8</td><td align="center">6359.4</td></tr><tr><td align="center">RTX 3080 Ti</td><td align="center">1.8</td><td align="center">6359.4</td></tr><tr><td align="center">RTX 3090</td><td align="center">1.8</td><td align="center">6359.4</td></tr><tr><td align="center">GTX 1050</td><td align="center">1.7</td><td align="center">6006.1</td></tr><tr><td align="center">Tesla V100-SXM2-16GB</td><td align="center">1.6</td><td align="center">5652.8</td></tr><tr><td align="center">RTX 4070</td><td align="center">1.6</td><td align="center">5652.8</td></tr><tr><td align="center">RTX 4080S</td><td align="center">1.5</td><td align="center">5299.5</td></tr><tr><td align="center">A10</td><td align="center">1.5</td><td align="center">5299.5</td></tr><tr><td align="center">RTX 4060</td><td align="center">1.5</td><td align="center">5299.5</td></tr><tr><td align="center">GTX 1080</td><td align="center">1.5</td><td align="center">5299.5</td></tr><tr><td align="center">Tesla V100-PCIE-16GB</td><td align="center">1.4</td><td align="center">4946.2</td></tr><tr><td align="center">Tesla P40</td><td align="center">1.4</td><td align="center">4946.2</td></tr><tr><td align="center">Tesla V100-PCIE-16GB</td><td align="center">1.4</td><td align="center">4946.2</td></tr><tr><td align="center">GH200 SXM</td><td align="center">1.3</td><td align="center">4592.9</td></tr><tr><td align="center">RTX 4060 Ti</td><td align="center">1.2</td><td align="center">4239.6</td></tr><tr><td align="center">GP100</td><td align="center">1.1</td><td align="center">3886.3</td></tr><tr><td align="center">Titan V</td><td align="center">1.1</td><td align="center">3886.3</td></tr><tr><td align="center">RTX 3080</td><td align="center">1</td><td align="center">3533</td></tr><tr><td align="center">Q RTX 5000</td><td align="center">1</td><td align="center">3533</td></tr><tr><td align="center">Q RTX 4000</td><td align="center">1</td><td align="center">3533</td></tr><tr><td align="center">RTX 2080S</td><td align="center">0.9</td><td align="center">3179.7</td></tr><tr><td align="center">RTX 2080</td><td align="center">0.9</td><td align="center">3179.7</td></tr><tr><td align="center">Tesla P100</td><td align="center">0.9</td><td align="center">3179.7</td></tr><tr><td align="center">Titan Xp</td><td align="center">0.9</td><td align="center">3179.7</td></tr><tr><td align="center">GTX 1070 Ti</td><td align="center">0.9</td><td align="center">3179.7</td></tr><tr><td align="center">Quadro P5000</td><td align="center">0.9</td><td align="center">3179.7</td></tr><tr><td align="center">RTX 2080 Ti</td><td align="center">0.9</td><td align="center">3179.7</td></tr><tr><td align="center">CMP 90HX</td><td align="center">0.9</td><td align="center">3179.7</td></tr><tr><td align="center">Titan X</td><td align="center">0.8</td><td align="center">2826.4</td></tr><tr><td align="center">RTX 3060 Ti</td><td align="center">0.8</td><td align="center">2826.4</td></tr><tr><td align="center">RTX 2070</td><td align="center">0.8</td><td align="center">2826.4</td></tr><tr><td align="center">GTX 1080 Ti</td><td align="center">0.8</td><td align="center">2826.4</td></tr><tr><td align="center">RTX 3070</td><td align="center">0.8</td><td align="center">2826.4</td></tr><tr><td align="center">RTX 4000 SFF Ada Generation</td><td align="center">0.7</td><td align="center">2473.1</td></tr><tr><td align="center">Tesla K80</td><td align="center">0.7</td><td align="center">2473.1</td></tr><tr><td align="center">RTX 3070 Ti</td><td align="center">0.6</td><td align="center">2119.8</td></tr><tr><td align="center">RTX 2060S</td><td align="center">0.6</td><td align="center">2119.8</td></tr><tr><td align="center">RTX 3060</td><td align="center">0.6</td><td align="center">2119.8</td></tr><tr><td align="center">Tesla T4</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center">GTX 1060</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center">RTX 3070 laptop</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center">RTX A2000</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center">RTX 3060 laptop</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center">RTX 3050</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center">GTX 1070</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center">GTX 1660</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center">P106-100</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center">GTX 1650 S</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center">GTX 1660 S</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center">GTX 1660 Ti</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center">GTX 1650</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center">P104-100</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center">GTX 980 Ti</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center">GTX 980</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center">GTX 750 Ti</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center">GTX 970</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center">GTX 750</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center">GTX 960</td><td align="center">0.5</td><td align="center">1766.5</td></tr><tr><td align="center"></td><td align="center"></td><td align="center"></td></tr></tbody></table>

**Notes:**

1. GPU model: This column lists different models of GPUs.
2. Computing Unit (CU) : CU refers to the relative computational contribution of each GPU model. A higher CU value indicates that the GPU has a greater capacity for contributing computational resources, which can lead to higher potential earnings.
3. Collateral Requirement Per Card (in $SWAN): This shows the amount of $SWAN tokens required as collateral for each GPU card under normal circumstances.
4. Collateral Requirement Per Card during UBI - 0 (in $SWAN): This represents the amount of $SWAN tokens required as collateral for each GPU card during the initial UBI period (referred to as UBI-0). This amount may differ from the regular collateral requirement.


# DePIN Oracle

#### **Introduction**

The Depin Oracle is a critical component of the Swan Chain network, providing reliable data aggregation and pricing for decentralized computing services. By collecting and processing information from various sources, the Depin Oracle ensures that participants in the Swan Chain ecosystem have access to accurate and up-to-date data, fostering a fair and efficient decentralized computing marketplace.

#### **What is the Depin Oracle?**

The Depin Oracle serves as a data aggregator that gathers GPU market prices from different platforms, such as **vast.ai** and **salade.com**. The gathered data is input into a smart contract daily, providing a baseline reference for the computing market within the Swan Chain network. This mechanism functions similarly to how **Chainlink's pricing oracle** operates in the decentralized finance (DeFi) space by delivering reliable and consistent price information to the network.

#### **Key Functions of the Depin Oracle**

1. **Data Aggregation**: The Depin Oracle collects GPU pricing data from multiple platforms. By leveraging multiple data sources, it ensures that the information provided is both accurate and comprehensive.
2. **Market Price Reference**: The aggregated data is input into a smart contract on a daily basis to create a trusted market price reference. This allows Swan Chain to set fair pricing for computing resources, which is crucial for decentralized computing providers and consumers.
3. **Baseline for Smart Contracts**: The Depin Oracle feeds data directly into the smart contracts that manage payments and resource allocation in the Swan Chain network. This ensures that the prices for computing power are updated consistently, preventing discrepancies and enabling fair compensation for computing providers.

#### **Benefits of the Depin Oracle**

1. **Transparency**: By using an oracle to provide publicly accessible data, the Swan Chain network ensures transparency in pricing. This encourages trust among computing providers, users, and stakeholders, which is essential for a decentralized system.
2. **Fair Pricing**: The Depin Oracle plays a critical role in maintaining fair market pricing for computing resources. By pulling data from various platforms, the oracle reduces the risk of price manipulation and ensures that providers and consumers engage in fair transactions.
3. **Efficient Resource Allocation**: The Depin Oracle enables more efficient allocation of computing resources by providing real-time price information. This means that computing providers are better able to allocate their resources in response to demand, optimizing the overall network's efficiency.

#### **Use Cases in Swan Chain Network**

1. **Decentralized Computing Marketplace**: The Depin Oracle supports the decentralized computing marketplace by providing a trusted reference for GPU pricing. This ensures that computing providers can set appropriate prices for their services based on real-time market conditions.
2. **Token Issuance and Incentive Programs**: By integrating market data into the network's smart contracts, the Depin Oracle also helps with the fair distribution of tokens and incentives. For example, the Universal Basic Income (UBI) tokens distributed to computing providers are based on market conditions that the oracle helps determine.
3. **Risk Management**: The Depin Oracle reduces the risk of relying on a single data source by aggregating data from multiple sources. This mitigates the risk of inaccurate pricing and potential economic losses for computing providers or users in the Swan Chain network.

#### **Conclusion**

The Depin Oracle is an essential component of the Swan Chain network, providing accurate, transparent, and reliable data that underpins the decentralized computing marketplace. By aggregating GPU pricing information from multiple sources and feeding it into smart contracts, the oracle ensures fair pricing, efficient resource allocation, and reduced risks for all network participants. Ultimately, the Depin Oracle helps create a robust, transparent, and equitable ecosystem that supports the growth and sustainability of decentralized computing services on Swan Chain.




---

[Next Page](/llms-full.txt/1)

