# FilSwan 概览

FilSwan is a layer-2 cross-chain solution that helps Web3 projects to integrate data, computing, storage, and payment into one suite.

## Edge Storage and Computing on Web 3.0

![
](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2Fq2XLdHtNTjZxiBkhDozx%2Fimage.png?alt=media\&token=c16dcee7-6c92-42e8-a5f0-33c767b7258c)

FilSwan offers a complete solution that enables web3 developers to integrate decentralized storage, edge computing, and payment across multiple chains with ease.

Since 2018, FilSwan has been dedicated to decentralized storage and computing solutions. Those services are enhanced by edge computing, IPFS/Filecoin, and decentralized ledger technologies. We are building the largest fog computing network in the Metaverse. Our products are adopted by world-renowned universities, the VR/AR industry, and many other high-performance computing companies.

### Turn-key solutions for web3 Developers

* FilSwan offers cutting-edge blockchain storage and computing solutions for web3 decentralized data needs.
* FilSwan reduces queuing time by automatically matching web3 providers and users in need.
* FilSwan offers an alternative to the current mainstream cloud storage that bridges Filecoin and S3.
* FilSwan migrates petabytes of data while ensuring efficiency and cost-effectiveness.

{% embed url="<https://github.com/filswan>" %}

## Core Product

{% content-ref url="/pages/4TGJ5Jqyc5TEkJZXb5gl" %}
[Filswan Platform](/filswan-platform/overview)
{% endcontent-ref %}

{% content-ref url="/pages/fS2ap3oINhwnDekfz6C4" %}
[FS3](/fs3/overview)
{% endcontent-ref %}

{% content-ref url="/pages/lkH44AE3h8QK6QkBeT6t" %}
[Multichain.Storage](/multichain.storage/overview)
{% endcontent-ref %}


# 协议栈


# 跨链共识层


# Peer-to-Peer (P2P) 网络


# 支付频道


# Service Discovery


# 数据市场


# 索引和缓存市场


# Web3 任务bid市场


# 存储层


# 计算层


# CDN 层


# 治理


# 联系我们


# 社交账号&社区

Discord: <http://discord.com/invite/KKGhy8ZqzK>

Telegram: <https://t.me/filswan>

Medium: <https://filswan.medium.com/>

Twitter: <https://twitter.com/0xfilswan>

Facebook: <https://www.facebook.com/Filswan>

YouTube: <https://www.youtube.com/channel/UCcvrZdNqFWYl3FwfcHS9xIg>


# 商业合作

## Partnership&#x20;

If you want your logo shown as FilSwan's ecosystem partner and client, please submit the form below:

[Apply to be a partner or client](https://docs.google.com/forms/d/1ysOaN0LH0go32fETBEKDvX2b8VaG_Wxv2sehdwGcYro/viewform)

Please don't email us to apply - we only respond to applications via the application form.

### How long will it take to get a response?

We aim to respond to applications within a week, but due to the large number of requests, we’re unable to respond to every single applicant.&#x20;


# 概览

FilSwan Platform is a hosted platform for enterprises to integrate their business workflow with the Filecoin network.

![FilSwan Business Solution](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FQYoNvw69f6psMkg3rB4D%2Fimage.png?alt=media\&token=919555f8-e09a-4d55-89fe-c95f664ce37b)


# FilSwan 竞价系统

## Introduction to FilSwan Auction System

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. &#x20;

**Over the course, there remain several key questions:**&#x20;

1\. Users can't fully understand the specific service quality of storage providers because of limited information available.&#x20;

2\. The lack of in-depth matching functionality, and diverse data storage needs are making the dealer market opaque.&#x20;

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.&#x20;

In this context, having an open and transparent matching system is necessary. FilSwan's auction system is optimal for simplifying data storage through matching providers and users in need automatically, thereby reducing the learning cost for users.&#x20;

#### Manual bid vs Auto-bid

**Manual Bid**

There are two types of bids in the FilSwan 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**&#x20;

![Autobid System](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FVfsDI8D8sERRqDwL7oOc%2Fimage.png?alt=media\&token=87aed05c-1231-4f52-b228-900183e40fe4)

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.&#x20;

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.&#x20;

The FileSwan bidding system is a matching platform that enables convenient transactions between users and providers. In the era of decentralized storage, FilSwan ensures a quick pair of users and storage providers for the sake of time-efficient storage and backup services regardless of data scales.&#x20;

The FilSwan bidding system increases the earnings of real data storage. It additionally reduces the leverage difficulty to attract more novice users. &#x20;

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**&#x20;

It is of great importance to conceptualize "task" in the FilSwan 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.&#x20;

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 Provider**&#x20;

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 Filswan platform is required.&#x20;

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>


# Web3自动交易匹配

Web3 Automated Market Match


# 信誉系统

## Reputation Score

### Methodology

#### Reputation Score = Time-based Reachability + Regional Weighted Adjusted Power + General Deals and Verified-Storage Provider Deals

### Reputation Score Formula:

The reputation system can conduct a comprehensive evaluation of various parameters of the nodes. It integrates running time, geographical location, regional influence, quantity, packet loss rate, failure rate, and real-time transaction to perform mathematical weighting. Afterward, it will generate an overall ranking and a quantitative evaluation of storage provider nodes. Growing data storage tasks received by top providers can lead to a more stable running system. Meanwhile, the reputation system ensures a focus on node operation and maintenance, thereby promoting the security and stability of the Filecoin storage network. It keeps users away from the hassle of seeking service providers. &#x20;

* The max score that the storage providers can have is 100 points.
* The score is based on 3 main sets of metrics, each set with a different weight in the total score:
  * Time-based Reachability - 30% weight
  * Regional Weighted Adjusted Power - 10% weight
  * General Deals and Verified-Storage Provider Deals - 60% weight

### 1. Time-based Reachability:

Time-based reachability measures the times of successful and failed requests when storage providers are scanned. The ratio of successful request count to total request count (successful request plus failed request) is the key metric used here.

Request Successful (reachable) = 1

Request Failed (unreachable) = 0

Success Rate = reachable count/ total count

In addition to the overall request success ratio, the latest request performance of storage providers in the recent few scans will be considered. The reason is that the system rewards storage providers based on their recent performances. The ratio of successful request count and total request count during the last 10 scans is calculated to represent the recent behavior. The weight of online reachability of all time and online reachability in the latest scans are 0.7 and 0.3, respectively.

The Reachability score is calculated with the following mathematical formula:

{% hint style="info" %}
Time-based Reachability Score = 30 \* (0.7 \* Online Reachability Total Success Rate + 0.3 \* Online Reachability Top10 Success rate)
{% endhint %}

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FeJ0JA1tybKLgJDueeDln%2Fimage.png?alt=media\&token=b4758e65-4287-4c81-936d-a4fb906e654c)

### **2. Regional Weighted Adjust Power:** <a href="#reputationsystemdesign-2.regionalweightedadjustpower" id="reputationsystemdesign-2.regionalweightedadjustpower"></a>

The regional committed sector proof score is designed to measure the total committed capacity of the miner. The bigger the miner is the more collateral is required, and the technical support effort also increased. The importance of a miner in the region is inversely proportional to the total number of miners in the region, e. g. a miner in a 1-miner region is 10x more important than a miner in a 10-miner region since it is the only service provider.

To emphasize the importance of the miner of the region, we use the regional weighted adjust power to show the weight of the miner in the region.

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FGDF28cJwLJjeU9YbxTiI%2F1.png?alt=media\&token=0751fb70-3690-4300-aabf-27921a7ce576)

The weighted adjust power is calculated with the following mathematical formula:

&#x20;                                         *Location Weight = 0.5 + 0.5 \* exp( -1 \* number of miners in its continents)*

&#x20;                                         *Number Weight  = 0.5+ 0.5 \* exp( -1 \* total adjusted power in its continents / total adjusted power worldwide)*&#x20;

&#x20;                                         *Weighted adjust power = Location Weight \* Number Weight \* adjusted power*

After adjusting the power by the location, the weighted adjusted power is then transformed by a log transformation so that the distribution of log weighed adjusted power is closer to a normal distribution. Then the log weighted adjusted power is normalized using min-max normalization approach.

The normalized log weighted adjust power is calculated with the following mathematical formula:

&#x20;                                       *Normalized Log Weighted Adjusted Power = norm \[log (Weighed Adjusted Power)]*

The normalized result is a number in the interval \[0,1] where 1 is the maximum score. A miner that has a score of 1 is rewarded with 30 reputation points.

The Reachability score is calculated with the following mathematical formula:

{% hint style="info" %}
*Committed Sectors Proof Score = 10\* Normalized Log Weighted Adjusted Power*
{% endhint %}

### 3. General Deals and Verified-Storage Provider Deals:

The 3rd component of the score reflects the proportion in which the Web3 Storage Provider (W3SP) has successfully run the storage deals. Making storage deals is the core of a Web3 Storage Provider (W3SP) and thus this component has the biggest weight in the score. The deals considered here involve both internal deals (swan deals) and external deals (general deals). The Web3 Storage Provider (W3SP) active rate accounts for the key parameter, defined as the ratio of the number of active deals divided by the number of total deals. The active rate for external deals is set to 1 for now and will be updated later on.

A verified Web3 Storage Provider (W3SP) is a Web3 Storage Provider (W3SP) who signed with their Web3 Storage Provider (W3SP)’s signature and email address, they usually also update their contact information in Swan or other platforms.

The deals considered here involve both verified-Storage Provider deals and external deals (general deals). The Web3 Storage Provider (W3SP) active rate accounts for the key parameter, defined as the ratio of the number of active deals divided by the number of total deals. The active rate for external deals is set to 1 for now and will be updated later on.

The verified-Storage Provider active rate is calculated with the following mathematical formula:

Verified-Storage Provider Active Deal Rate = the number of active deals/numbers of total deals After Web3 Storage Providers (W3SP) are ranked by the calculated verified Web3 Storage Provider (W3SP) active rate in increasing order with the method set to "max". In other words, the records that have the same values are ranked using the highest rank (e.g.: If ‘Tom’ and ‘Jerry' are tied in the 2nd and 3rd position with the same value, rank 3 is assigned to them both).

![](https://console.filswan.com/static/img/Methodology3.905c15e.png)

This max ranking method guarantees a base score for each Web3 Storage Provider (W3SP) and leverages more to the Web3 Storage Providers (W3SP) having a larger number of verified-Storage Provider active deals. The verified-Storage Provider active rate rank is then normalized by the division of the number of Web3 Storage Providers (W3SP).

The normalized verified-Storage Provider active rate rank is calculated with the following mathematical formula:

Normalized verified-Storage Provider Active Deal Rate Rank = norm \[Rank\_Max (Verified-Storage Provider Active Rate)]

The normalized verified-Storage Provider active rate is then weighted by another parameter, the sector faculty rate. Deals that fall into faults for some reason will lose weight and Web3 Storage Providers (W3SP) that have fewer faults are assigned more weight. In this scenario, the sector faulty rate is calculated as the ratio of the number of faults divided by the number of total live deals.

The sector faulty rate is calculated with the following mathematical formula:

Sector Faulty Rate = number of fault deals/number of live deals

Thus, the deals score is the weighted sum of verified-Storage Provider deals and external deals with faulty rates considered.

The General deals and verified-Storage Provider deals score is calculated with the following mathematical formula:

General Deals and verified-Storage Provider Deals Score = 60 \* \[0.3 \* 1 + 0.7 \* (1 - Sector Faulty Rate) \* (Normalized verified-Storage Provider Active Rank)]

## **Blacklist Rule**

### Introduction

Miner will be evaluated not only on its reputation score, but also on its recent deal rejection history.  If a miner rejected a large number of deals over a long period of time, its score will be conducted deduction. The deduction is possible to put the miner on the blacklist and unable it to take more deals.&#x20;

### Methodology

The miner's blacklist status is related to a blacklist score (as the **score** in the rest of the document). The score will be deducted when miners reject deals without a satisfying reason.

Each newly registered miner will start from 100 scores. And miner will lose scores on certain rejections (With a threshold of 5 points per day). This makes sure that inactive miners will not receive deals, and reduce the probability of unsuccessful deals occurring.

There are the rejection responses lead to score deduction:

* Filswan being blacklisted: -1
* Unidentified rejection: -0.5
* Unqualified deal: -0.3
* Error message: -0.1
* Deal time out: -0.05

After a miner's score is below 30, the miner will be automatically put on the blacklist.

#### Score recovery

For miners on the blacklist, their score can be recovered by being active. For each day the miner's heartbeat status is **Online**, the miner will gain 1 score until the score reaches 30, and the miner will be removed from the blacklist.

#### Scanning

The miner's deal history will be automatic review each day. Offline deals that are rejected will be scanned for score deduction purposes. And the score will be updated afterwards.


# 主要功能


# 任务管理


# 创建新任务

1. To create a task, go to either **Browse Tasks** or **My Task** and click on the yellow button that says “**Create Task**.”

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FSwrubUzxAJ3lFR8aFBVG%2Fimage.png?alt=media\&token=9d15d88e-6e06-48aa-9653-57e6fdb2d600)

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FVGp5q6FVgwyW46eI4pvP%2Fimage.png?alt=media\&token=9d15d88e-6e06-48aa-9653-57e6fdb2d600)

2\. When creating a task:

* **Task name**. We suggest creating a task name that is descriptive of the task. In the example below, the task name is “Swan Team 5\*32GB verified Task.” Swan Team alerts storage providers that this task is an official deal that is coming from FilSwan and 5\*32G indicates the amount of storage needed for this task.
* **Task description.** Where clients can indicate certain attributes they are looking for when selecting a storage provider and describes to storage providers what the task entails. In the example below, one of the requirements is that the client wants their data to be stored somewhere in Europe.
* **Tags**. Adding tags to the task will help interested storage providers find your task. Tags can be up to 14 characters long and there is a maximum of 5 tags that can be attached to a task.
* **Type**. Select whether your deals are Regular or Verified.
* **Upload CSV**. Upload the CSV file which contains information of the data that you want to be stored by a storage provider.
* **Curated Dataset.** It indicates the source of data that you desired to store in Filecoin network.
* **Open bid**. Determine if the task will be open bid by selecting yes or no.
  * By selecting “Yes,” the task will open bid and all storage providers on the FilSwan platform will be able to view your task in Browse Tasks.
  * If “No” is selected, then a box will appear for you to type in a storage provider ID. This task would then be sent to that specific storage provider and would not be available to other storage providers.
* \*\*Expected time. \*\*Indicate how many days you expect the storage provider to take to complete the task. When storage providers bid on the task, they will indicate if they can complete it by the desired deadline or sooner.
* **Estimated budget**. Estimate a maximum and a minimum amount that you would be willing to pay in FIL to a storage provider for storing your data.

3\. Click the submit button to send out the task to the FilSwan market or a specific storage provider.

![Example of Creating a Task](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FgrTRwJH3XJ7KK5bOgpN2%2Fimage.png?alt=media\&token=1db01456-a59d-4c00-a502-2b6c79b6b5b1)


# Navigate Tasks

**Browse Tasks** shows all available tasks that are open for bids on FilSwan.

* If you are a miner looking for tasks to bid on, this would be the place to look.
* As a client, after you create a task that is open for bids, it will be displayed on Browse Tasks.

![Example of a task that is open for bids on Browse Tasks](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2Faz2wwUAbJ5GMThKolusi%2Fimage.png?alt=media\&token=ba2f1f24-ce6b-499c-a62c-cbecb1dbfc22)

**My Task** displays all tasks that only you have created as a client or tasks you have completed as a miner.

To switch between client and miner, click on the "**As Client**" or "**As Miner**" buttons at the top of the page.

![Example of previous tasks created as a client](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2Few8vNShIPTjFrH1NBoVY%2Fimage.png?alt=media\&token=e0cb72a2-6d39-4780-87ce-533dd3c88545)


# 更新任务

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2Fe2vteQxXPOsPTY15dVGg%2Fimage.png?alt=media\&token=7f7c5daf-9a2e-4313-92a3-3acf323e08a8)


# 分配任务

**Reviewing & Assigning Bids**

After an open bid task has been created, miners will submit bids to obtain that data storage deal. You can review these bids by going to “My Tasks” and clicking on the task name, which is in blue. This will bring you a page with a more detailed layout of that task. To view that task’s bids, click on the bids button at the top of the page.

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MauK7Ig3eWeXC35bZV7%2Fuploads%2FmctH3UxZT5eSnOgXZrp1%2Ffile.png?alt=media)

All bids will be displayed here. Bids can vary, not all will be identical. When reviewing the bids, the proposal, price, completion rate, and days to complete are shown. To see more information about the miner, you can hover your cursor over the miner ID or click on the miner ID to view their profile.

![Example of Bids](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MauK7Ig3eWeXC35bZV7%2Fuploads%2F1C32IgBYep4Fqkvh95UJ%2Ffile.png?alt=media)

Click on the bright green “Assign” button next to the miner you have selected for the task. After clicking on the “Assign” button, a pop-up will appear as shown below. This pop-up will ask for the designated miner’s ID and to upload the CSV file that you want to be stored.

![Example of Pop-up asking to select miner ID and re-upload CSV](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MauK7Ig3eWeXC35bZV7%2Fuploads%2FzFY2JDpCDnmKGRVcvqbQ%2Ffile.png?alt=media)

The reason for re-uploading the CSV file is because when creating a task, anyone can view that task’s CSV file. To prevent anyone and everyone on FilSwan from accessing your data file, you can upload a dummy CSV file when creating the task. Then you upload the real CSV file after you have selected a miner and the pop-up above appears.


# 我的资料


# 注册成为存储提供商

#### To register as a FilSwan storage provider.

1. Go to **My Profile** and select the **As Storage Provider** tab on the top of your avatar.
2. At the bottom of profile information section, you could find a **Your Swan Storage Providers** section.&#x20;
3. Click on the yellow button that says **Manage**. Three blue buttons **Add, Delete, Refresh** will show up.
4. Click on the blue button that says **Add**. Enter your storage provider ID, choose wether you Accept Offline Deal, select where your storage provider is located. Then click the button says **Validation**.

   *<mark style="color:orange;">Note: the default setting of Accept Offline Deal is OFF. Please switch it to ON if you do accept offline deals. This affects your eligibility to AutoBid.</mark>*
5. Then, A **Signature verification** section will show up. Please sign the following message and submit the signature. This ensures authenticity and security for each storage provider owners.&#x20;

   *<mark style="color:blue;">Tips: To get the Signature, you can run</mark> <mark style="color:blue;"></mark><mark style="color:blue;">`lotus wallet sign {address} {message}`</mark> <mark style="color:blue;"></mark><mark style="color:blue;">on a lotus node.</mark>*
6. Once the Signature is provided, click the blue button says **Submit**. Your storage provider will be successfully registered as a FilSwan storage provider.

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FIh4uDU9kkMn0dyzv5PTL%2Fimage.png?alt=media\&token=2b0395a6-3f3d-4d27-ab00-41dfb105acb1)

#### To modify your FilSwan storage provider.

1. At the same place where the yellow button **Manage** located.
2. Click on the **Manage** button. Then, in your storage provider list, the two columns "OFFLINE DEALS" and "LOCATION" will become modifiable.
3. To modify wether your storage provider accept offline deals, click on the **Yes/No** button(the blue one is your current setting); to modify your storage provider location, select the region in the drop-down list.&#x20;
4. Click the blue button says **Save** to save all your modifications.

#### To Delete your FilSwan storage provider

1. At the same place where the yellow button **Manage** located.
2. Click on the **Manage** button. Then clicking on the row of the target storage provider to select the storage provider which you would like to delete.
3. Click the blue button **Delete** which is in the middle of Add and Refresh button.
4. A confirmation pop-up window will show up.
5. Click on the blue button **OK**. Your storage provider will be successfully deleted.


# 寻找存储提供商

On the Dashboard, type in a W3SS ID into the search bar to search for a specific storage provider’s profile. Always click on the W3SS ID to view their profile. The storage provider's profile will provide additional information about their data storage capabilities.

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FPPHVL3XLxp8b7rznXaDe%2Fimage.png?alt=media\&token=14d848ae-830f-4281-b936-3c9f1df8c6c8)

To search for the storage provider’s status (active or offline), you can use the drop-down box to the left of the W3SS ID search bar.

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FgCyXtr38Tb11cVrdH40r%2Fimage.png?alt=media\&token=6746ff16-93cb-40b5-89ea-7ca8bbca9866)

There is another dropdown box to filter storage providers by their location. The available location options are Asia, Africa, North America, South America, Europe, Oceania, and Global. Storage providers who have listed their location as Global have no fixed location for storing your data.

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FesEhTQe3bWyVPdbgVjAQ%2Fimage.png?alt=media\&token=53d0bc3c-8b2c-4805-a73b-6ebbbfe43cce)

All of the storage provider’s information categories are displayed on the Dashboard and can be viewed by scrolling to the right. However, if you are only interested in viewing certain categories, you can use the filter function to view certain columns.

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FxWX8oIdkA30eXh4aPYqu%2Fimage.png?alt=media\&token=2ba92e36-0d07-4dbc-8617-fb756591b672)

Below are all the available categories that can be displayed on the Dashboard when you click on the filter function. You can select the boxes to display the categories relevant to you. The default setting of the Dashboard will be to always display all the categories.

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FCAeON4su25H7N5pU09jX%2Fimage.png?alt=media\&token=0cd3059b-ea96-4ea1-995a-98aa13c47bd4)


# 存储提供商详情

To view a storage provider’s profile, go to the dashboard and click on the storage provider ID, which is in blue text.

\*\*Storage Provider Profile \*\*

The storage provider profile provides more background information to a storage provider. Profile Header and Summary are two sections of the profile that does not appear on the Dashboard. Profile headline is a section you can use to highlight a distinguishing feature of yourself as a storage provider. In the example below, the highlighted feature is “10TB daily sealing power.”

Following the Profile Headline is the Summary, which is used to go further into detail about your capabilities as a miner, such as sealing power, location, fiber and, etc.

Contact Info is used to contact the storage provider if any problems arise during the data storage deal. Users can put any contact method, but most users put their slack username or email.

The more detailed you can be on your profile the more you differentiate yourself from other storage providers. Clients can make better informed decisions with the more volunteered information they have access to.

![Example of Storage Provider Profile](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MauK7Ig3eWeXC35bZV7%2Fuploads%2Fzb9xcmv2GMq9XUOdhL4m%2Ffile.png?alt=media)

**Storage Provider** \*\*Data \*\*

Storage Provider Data shows all the information that is displayed on the Dashboard. Mining Data history can be shown for the past 24 hours, 7 days, 30 days, and 1 year. The past 24 hours are always the default data. To view past data, select the desired time frame that’s listed next to Mining Data.

Hovering or clicking on the question mark adjacent to the “Score” will provide more information about how a miner’s score is calculated. The score is calculated using a reputation system.

![Example of Mining Data](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MauK7Ig3eWeXC35bZV7%2Fuploads%2FguMM5vFuygaH3KbtBHvG%2Ffile.png?alt=media)

\*\*Graphs \*\*

The graphs in Storage Provider Details give a visual representation of the changes in a Storage Provider Score, Adjusted Storage Power, and Adjusted Storage Growth. The Adjusted Storage Power Growth is often found on the x-axis of the Power Change graph.

The graphs display up to one month of changes.

![Example of Miner Graphs](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MauK7Ig3eWeXC35bZV7%2Fuploads%2FgeFcW9DqwqBDua3hvk5X%2Ffile.png?alt=media)


# DataCap订单续期服务

为了保证有效数据的持续存储，Swan推出Datacap 订单续期服务：[Extend DataCap Terms](https://datacap.swanchain.io/)。该服务将有助于存储提供商保持其10倍算力，延长扇区的到期时间。<br>

所有从[ ](https://console.filswan.com/) [Swan Platform](https://console.swanchain.io/dashboard) 收到的Deals都可以通过这项服务进行DataCap订单续期。

### 要求:

在使用 [Extend DataCap Terms ](https://datacap.swanchain.io/)服务之前，请确保您符合以下要求：

1. 扇区必须处于激活状态；
2. 交易必须来自 [Swan Platform](https://console.swanchain.io/dashboard) 平台；
3. 扇区的校验时间必须在 V17（2383680，2022-11-30 140000 UTC）之后；
4. 确保已安装 `lotus-miner` 1.23.0 或更高版本。

### 延长期限:

1. 扇区的期限时间可延长 180 天、360 天或 540 天。
2. 扇区的最大期限时间不能超过 540 天。

### 如何延长:&#x20;

&#x20;根据 [FIP0045](https://github.com/filecoin-project/FIPs/blob/master/FIPS/fip-0045.md), 如果要延长 DataCap 扇区的有效期，需要两个步骤:

#### **第一步:**&#x20;

**Client**需要更新DataCap扇区中每笔交易的 Claim `TermMax`:

```
lotus send --from <deal_wallet> --method 11  --params-json '{"Terms":[{"Provider":1836766,"ClaimID":13847890,"TermMax":3680640}]}' f06 0
```

#### **第二步:**&#x20;

**存储提供商**需要完成扇区续期操作:

```
lotus-miner sectors extend --extension=1555200  --really-do-it=true --drop-claims=true  --sector-file=[sector_file]
```

Swan 的 [Extend Datacap Terms Service ](https://datacap.swanchain.io/)可帮助您完成[第一步](#di-yi-bu)，而供应商需要执行[第二步](#di-er-bu)。

### 续期教程：

1. 访问 [Extend Datacap Terms Service](https://datacap.swanchain.io/) ；
2. 填写您的存储提供商 ID 并上传您要续期的扇区列表；
3. 选择续期时间并选择要延期的Claim；
4. 支付完成后，提供您的电子邮件和交易 CID提出申请；
5. 申请成功后，您将收到一封确认邮件；
6. FilSwan 团队在确认了支付状态后，将完成DataCap订单续期，并通过电子邮件回复相应的扇区信息；
7. 存储提供商下载扇区文件并自行完成扇区续期。

```
lotus-miner sectors extend --extension=518400 --really-do-it=true --drop-claims=true --sector-file=[sector_file]
```

**The extension days:**

| Days | Epoch   |
| ---- | ------- |
| 180  | 518400  |
| 360  | 1036800 |
| 540  | 1555200 |


# 概览

A smart contract-based cross-chain storage gateway.

### **Introduction**

Multi-Chain storage (MCS) is a smart-contract-based cross-chain storage gateway that is integrated with oracle technology. It accelerates the mass adoption of decentralized storage by bridging multiple blockchain networks.

MCS enables users to pay for Filecoin storage with stable coins and other Mainnet tokens while maintaining data security. Users will also obtain the payment transaction and IPFS information with Filecoin deal ID for future reference.

### **Functions**

MCS is a cutting-edge blockchain storage solution providing a data cache and presidency layer for decentralized data storage needs. With MCS, users can&#x20;

* Upload any data to the Filecoin network and IPFS.
* Pay for storage with stable coins like USDC and other mainnet tokens.
* Mint NFTs directly to OpenSea.
* Access services by connecting a third-party wallet (MetaMask)
* Sent or get deals automatically through the build-in auto-bid system.
* Merge small files to a large CAR file.
* Support to multiple miners for storage.

### **Advantages**

Filecoin is an open-source, public cryptocurrency and digital payment system intended to be a blockchain-based cooperative digital storage and data retrieval method. As a powerful and dynamic distributed cloud storage network, Filecoin is adopted by multiple blockchain projects like Near and Polygon.

However, those individual chains or projects each operate in isolation and can hardly communicate with the others. Global users are consequently facing a large number of networks with different algorithms, transaction types, rules, etc. It prevents users from enjoying the full potential of blockchain technology.

**That is why MCS is working to guarantee the seamless interoperability of blockchains.** Since its launch, MCS has been dedicated to closing the gap by allowing users to swap other tokens to Fil to pay for data storage. MCS will bring data storage to the next level of security, decentralization, and democratization.

{% embed url="<https://github.com/filswan/multi-chain-storage/tree/qa_single_miner>" %}


# Flink

A data provider DAO offers Chainlink Oracle service for Filecoin Network

### Introduction

Flink is a data provider DAO aiming at offering Chainlink Oracle service for the Filecoin Network. Flink offers deal information on multi chains for users who want to store their data on Filecoin.

### **What is Filecoin - Chainlink Data Provider**

Filecoin is the best option for users from blockchains like Ethereum, BSC, and Polygon to store large-scale data off-chain. Users can upload and retrieve data from the Filecoin network via sending deals. However, how to generate a cross-chain proof remains unresolved and has created a gap between users' storage needs and the Fileocin storage solution.

[An External adapter](https://docs.chain.link/docs/external-adapters) can allow access to high-quality data and enable extreme flexibility to connect smart contracts to premium web APIs. With Chainlink external adapter, user can check their deal information on oracle node operators.

{% embed url="<https://github.com/filswan/flink>" %}

### **Sample Use Case**

**Polygon NFTs USDC payment for Filecoin storage**

The general process of saving NFTs on the Filecoin network is:

* Lock a payment on the Polygon network
* Swap tokens to Filecoin agent
* Filecoin agents send NFT in deals to Filecoin storage providers
* Get an on-chain deal ID
* Chainlink oracle broadcasts the proof to Polygon network
* Storage DAO notaries sign the data based on the deal info provided by Chainlink oracle
* NFT payment unlocked to the Filecoin agent

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2F8s2rfZVt4p0WziXJt1Pt%2Fflink%20image.png?alt=media\&token=813dc140-9e34-4c71-a68b-14b35c22d97c)

### **Design Structure**

**Three must-haves to work as a Flink data provider:**

* Data aggregator
* Chainlink external adapter
* Data DAO notary

Several blockchain scanners will first aggregate the data to a unified data provider. Then the chainlink eternal adapter with oracle smart contracts will broadcast the proof to the targeted blockchain network. Afterward, Data notaries will sign the transaction based on the on-chain oracle data. The payment will be triggered once the on-chain proof is relayed from Chainlink oracles.

### **Data aggregator**

When a FIlecoin agent sends the data to a storage provider, the data storage process starts. The storage provider needs to accept the deal and upload an on-chain deal acceptance confirmation, which means the deal is in progress and a deal id will be generated on the Filecoin network.&#x20;

The data aggregator will scan the Filecoin deal information from different data sources and send the information as an API interface. Check the [data](https://github.com/filswan/flink/blob/main/data) directory for the scan-related code. Typical deal info is in this format:

> <http://35.168.51.2:7886/deal/5210178?network=filecoin_mainnet>

```
//{

    "status": "success",
    "data": {
        "deal": {
            "deal_id": 5210178,
            "deal_cid": "",
            "message_cid": "bafy2bzaceaotial6pogwzvm7woh5pf37sivrzm3fmp5teao365jl22z5q4pfc",
            "height": 1697382,
            "piece_cid": "baga6ea4seaqjffbc2mmed2piulix5qfppyuhbqumnppme5ngj3q2ol4udijjqbq",
            "verified_deal": true,
            "storage_price_per_epoch": 0,
            "signature": "",
            "signature_type": "",
            "created_at": 1649227860,
            "piece_size": "1073741824",
            "start_height": 1701360,
            "end_height": 3234661,
            "client": "f1g463yb4ok3lq3tffkvvfmfyngcagpx4kg7c7rei",
            "client_collateral_format": "000000000000000000",
            "provider": "f067375",
            "provider_tag": "",
            "verified_provider": 0,
            "provider_collateral_format": "000000000000000000",
            "status": 0,
            "network_name": "filecoin_mainnet",
            "storage_price": 0
        }
    }
}
```

### **Chainlink External Adapter - DATA DAO**

After the data aggregator gets the deal information, an External adapter is needed for offering API access for data DAO notaries in the next step.

For detailed information about how to build and deployed External Adapter, please check the code in [the adapter](https://github.com/filswan/flink/blob/main/adapter)

### **Data DAO Notary**

Data DAO notary is in charge of signing the multi-sig wallet for unlocking the fund to Filecoin agents.

The DAO contract allows the community to add or remove notaries from the DAO. The DAO notaries will follow these steps before signing:

* get deal\_id by proposal\_cid
* get deal\_id from Chainlink Filecoin adapter
  * if matches trigger DAO signature
    * match client\_address
    * match deal\_cid (proposal\_cid)
  * otherwise, waiting for the next check cycle

### **Roadmap**

* March 14th,2022: The mainnet launch with the Polygon network
* June 6th, 2022: Notary DAO setup


# Multichain.Storage 用户指南

## Requirements <a href="#requirements" id="requirements"></a>

Before you begin this guide, complete the following tasks to make sure you have all of the tools that you need:

* Complete the [Beginner Walkthrough](/multichain.storage/mcp-user-guide/public-testnet) to set up [MetaMask wallet](/multichain.storage/mcp-user-guide/setup-metamask).
* You can obtain Testnet USDC and MATIC from several[ faucets.](/kai-fa-zi-yuan/swan-token-contract)

MCS use both **MATIC** and **USDC** for uploading files to polygon network. We strongly suggest you testing with Testnet first.

## **Instruction**

### **1. Connect to your MetaMask wallet on Mumbai Testnet**

Go to MCS: <https://mcs.filswan.com/>. Click on the **Connect Wallet** button to connect your MetaMask wallet, and make sure to select the corresponding network on the MetaMask wallet. (Currently, we only support the Polygon Mumbai Testnet. In the future, it will be officially launched into the Polygon Mainnet. And we also planned to add other main networks such as Ethereum, BSC, Fantom, etc.)

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2Fi2du4U7tUm2pCyX6sndE%2F1.png?alt=media\&token=96b713fd-4729-40ae-abb0-50b0a5a133df)

### 2. Upload file **to IPFS**

* Click the button of **Upload More** .
* Choose the file you would like to backup to Filecoin Network. The file name and file size will be displayed below upload button.
* An estimated storage cost will be calculated according to the file size, the duration , and the average provider price.
* Based on the real-time DeFi exchange rate which got from Sushi Swap, three lock funds plans are provided to our users. The more funds are locked, the sooner your file will be stored on the Filecoin network. Any overpaid funds will be automatically refunded to users after the deal is on chain and contract collects enough DAO signatures.

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FPo5JNnpAbgdccUiROJd2%2F2.png?alt=media\&token=c2fd8921-99e9-4ea5-9679-e565ffc3fb62)

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FRFolm4MFBvPIRaBOOvHR%2F3.png?alt=media\&token=ad8e270d-a125-4cf8-b9db-864568f22d3a)

After Submitting your request, an uploading window will show up. Uploading time varies depends on the size of your file. Please keep the window open until uploading completes.

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FWCzpk9tGdOWxtFn8xso9%2F4.png?alt=media\&token=3add2c9e-f1b8-4102-9fba-e1b4c316b0be)

### **3. Lock fund with MetaMask**

After the file has been successfully uploaded to IPFS, the next step is Lock funds to the smart contract, using the currency we support. For now, it is 'USDC' token.

Waiting time varies depends on the blockchain congestion.

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FfOwnVZrl0K3he3SO7TAy%2F5.png?alt=media\&token=42ec5721-eb3d-4bf2-a708-1b9c86625987)

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FP5hy8iPkLaCOkU8SUb4Z%2F6.png?alt=media\&token=a434e05a-7e18-4158-99f4-751da9b5d567)

While the payment is completed, a pop-up window with the transaction link shows up. You can either click on the link or check your MetaMask activity to see the transaction at the block explorer.

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FDqyEU4hRO3wIGhRrJ9Mb%2F7.png?alt=media\&token=2a3d9ac9-e325-49b5-bd6d-e299bd57aaee)

{% hint style="info" %}
**TIPS:** If you changed your mind and wanted to select another plan?

No worries, as long as you didn't confirm your payment on MetaMask. Firstly, you need to reject the transaction on MetaMask. Then, go to the 'My Files' page, you will find a PAY button to the corresponding file. By clicking the **PAY** button, you can also complete your payment.
{% endhint %}

### **4. View your files.**

By clicking the **Close** button, it will automatically turn to **My Files** page.

On this page, you can find all the files you have uploaded. It provides you some frequently used informations, such as the file name, status, data cid, provider id, and payment button, etc.&#x20;

{% hint style="info" %}
**TIPS:** With the mouse is hovering over the provider id, it shows you the real-time deal status from blockchain.
{% endhint %}

{% hint style="success" %}
**GOOD TO KNOW:** In order to improve the efficiency, MCS system is using FilSwan's AutoBid function. A qualified and optimal provider will be automatically assigned to your deal. The storage provider will complete following backup procedure, and synchronize the 'Deal status' to our platform.
{% endhint %}

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2F3WHx36PMGftRhld7CGBb%2F8.png?alt=media\&token=0071378b-d9a8-4bb9-b777-ab1f6d81565e)

{% hint style="info" %}
**TIPS:** A search bar is provided on the top of file list. You can search your file by partial file name.&#x20;
{% endhint %}

To view more details, simply click on the **file name**. You can find all the related information on this page, including the IPFS download link, the retrieval from Filecoin Network command, and DAO signature information and status. You won't need to bother to check the deal with a blockchain explorer.:smile:

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FmGdLUcMS0CQb1dPmmdGI%2F9.gif?alt=media\&token=32f6b60f-7dc9-4e66-b7ae-068af2536793)

#### DAO Signature Process:

* When the user's deal is successfully published on blockchain, the deal will be scanned by the DAO organization.&#x20;
* Then, DAO members will sign to agree to unlock the user's funds.&#x20;
* If a specified number of signatures from DAO are collected, the smart contract will unlock the funds.&#x20;
* Part of the locked funds will be used to pay the storage fee, and the remaining will be refunded to user's wallet.

{% hint style="info" %}
**NOTE:** An expire date is set when locking fund to smart contract, the default is 6 days. If the storage failed while the contract expired, you just need to simply hit the REFUND button, the locked fund will be refunded to users in full.&#x20;
{% endhint %}

### 5. NFT

Within MCS, you will be able to use the files you uploaded to mint NFTs if you like. The only requirement is that you have locked fund for the file to the smart contract.

To mint a NFT. You just need to click on the **MINT** button of the corresponding file. A windows will pop up with some pre-generated info, such as IPFS url, file size and lock fund transaction hash. The default NFT name will be the same as the file name, but you can always customize it, and fill in the description at will.

By clicking on the **Mint NFT** button, a MetaMask window will popup for authorization purpose. A little bit gas fee will be consumed to confirm this mint transaction.&#x20;

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FIA3nGfSkXQtaq04kMhY6%2F12.gif?alt=media\&token=15532d1b-2acb-4b46-bf9f-d8196efae21c)

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FfiOATZ33HiQBTdnEfZGH%2F14.png?alt=media\&token=b76d0305-88fc-4952-bff0-c0635fa1be04)

Once the mint process is completed, a View Your NFT window will popup. The transaction hash and a link to view your NFT on OpenSea are provided. You can click on the transaction has and OpenSea links to view more details.

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FoJYaB9lEXtPGYoW22Qal%2F12.png?alt=media\&token=0385c5f8-5c2f-49eb-a25e-237ed6c47f71)

### 6. Billing History

Users can view the billing history of all deals in 'Billing history' page. It covers all the information about the order such as the transaction hash, amount, unlock amount, token, data CID, wallet address, etc.

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2Fy066pKOpT8Oe3OSbGBuk%2F10.png?alt=media\&token=5ccc7b5f-2f09-4774-8bc6-45ed5aa6d18b)


# 公链测试网

## Public Testnet Guide <a href="#docusaurus" id="docusaurus"></a>

In order to make it easy for people to get started using Multi-Chain Storage, we've launched our MCS on the Mumbai testnet.

### Connecting to the chain <a href="#connecting-to-the-chain" id="connecting-to-the-chain"></a>

If you're using Metamask, add a custom RPC network to connect your wallet account to the Mumbai Testnet. [Click here to view more info](/multichain.storage/mcp-user-guide/setup-metamask)

### Observing transactions <a href="#observing-transactions" id="observing-transactions"></a>

If you'd like to see your transactions in action, please check out [block explorer](https://mumbai.polygonscan.com/)!

At there you'll be able to see all the transactions being executed in MCS and also see exactly how much Gas each transaction uses.

#### Important Addresses <a href="#important-addresses" id="important-addresses"></a>

* priceFeedOracleAddress = “”;&#x20;
* swanOracleAddress = “”;&#x20;
* swanPaymentAddress = “0x12EDC75CE16d778Dc450960d5f1a744477ee49a0”;&#x20;
* usdcAddress = “0xe11A86849d99F524cAC3E7A0Ec1241828e332C62";&#x20;
* wFilAddress = “”;&#x20;
* pairAddress = “";


# 设置MetaMask

MetaMask

### 1. Download MetaMask

Click the link <https://metamask.io/download.html> to install MetaMask for your browser.&#x20;

{% hint style="info" %}
**Note:** Depends on if you have a private key or not, you can either import the private key to create a wallet; or, you can create a wallet directly. It's very important to remember the mnemonic and private key. If you lost it, you can also enter the wallet and export the private key.
{% endhint %}

### 2. Add Mumbai Testnet

Add a custom RPC network to connect your wallet account to the Mumbai Testnet, configure Mumbai Testnet parameters as follow:

<table><thead><tr><th width="150">Parameters</th><th>Value</th></tr></thead><tbody><tr><td>Network Name</td><td>Mumbai Testnet</td></tr><tr><td>RPC URL</td><td><p><strong><code>Chrome browser</code></strong></p><p><code>https://rpc-mumbai.matic.today</code> or<br><code>https://matic-mumbai.chainstacklabs.com</code> or<br><code>https://rpc-mumbai.maticvigil.com</code> or<br><code>https://matic-testnet-archive-rpc.bwarelabs.com</code> </p><p></p><p><strong>Firefox browser:</strong><a href="https://rpc-mumbai.matic.today/"> </a></p><p>https://rpc-mumbai.matic.today  or</p><p>https://matic-mumbai.chainstacklabs.com</p></td></tr><tr><td></td><td></td></tr><tr><td></td><td></td></tr><tr><td>ChainID</td><td>80001</td></tr><tr><td>Symbol</td><td>MATIC</td></tr><tr><td>Block Explorer URL</td><td><a href="https://mumbai.polygonscan.com/">https://mumbai.polygonscan.com/</a></td></tr></tbody></table>

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FoDre7kb29xojH49HPLut%2Fimage.png?alt=media\&token=d33907b8-82d7-4c3f-9a15-7c4f2e672037)

After the parameters are configured, click 'Save' button below and successfully add Mumbai Testnet.&#x20;

If you want to add more wallet accounts, you can create them by importing the private key of your existing other wallets; or, you can directly click Create Account, and remember to save the private key after creation.

&#x20;                                               ![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2Fzk819F6s8K6UHXlLalvq%2Fimage.png?alt=media\&token=71a17f47-27b7-4365-9f2c-4bc1c0af978f)

*Reference:* [*https://docs.polygon.technology/docs/develop/network-details/network/*](https://docs.polygon.technology/docs/develop/network-details/network/)


# 用Alchemy RPC URL配置MetaMask

### **1. List your test networks in your Metamask Network List** <a href="#alchemypolygontometamaskinstructions-1.listyourtestnetworksinyourmetamasknetworklist" id="alchemypolygontometamaskinstructions-1.listyourtestnetworksinyourmetamasknetworklist"></a>

This setting is off by default. To turn it on, navigate to Settings > Advanced > Show test networks

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2Fmy4F6wDvzcMW3nRFCJNb%2F2.png?alt=media\&token=5f35e0d9-d0d1-4059-8e54-96a2769b7a0a) ![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2F7fz1Sllwu5dwPNy2yZaG%2F1.png?alt=media\&token=06c22892-740f-4976-9068-722402a656d2) ![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FGHvBKGMhC16RAeiVxQnu%2F3.png?alt=media\&token=df52ec75-8d13-49e7-9bc0-af6db111c857)

### **2. Create Alchemy Mumbai Polygon RPC** <a href="#alchemypolygontometamaskinstructions-2.createalchemymumbaipolygonrpc" id="alchemypolygontometamaskinstructions-2.createalchemymumbaipolygonrpc"></a>

First, you will need to create an account on [Alchemy](https://dashboard.alchemyapi.io). On the Dashboard page, click "+ CREATE APP", configure the app to be on "Polygon Mumbai"

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FMecuEAGX5O3DP1UzHzKw%2F4.png?alt=media\&token=6a7fa8aa-1e28-40e8-8437-1fe2d12effef)

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FNHTwnJGFxPKob0jZBL5r%2F5.png?alt=media\&token=15c14974-3d4b-4c03-a2a3-d5aced89448f)

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FaqeHKhhLRBYshr7SYNZL%2F6.png?alt=media\&token=c14adb49-99e4-43b0-a1cf-481408ee3d12)

### 3. Add the HTTP URL to Metamask <a href="#alchemypolygontometamaskinstructions-3.addthehttpurltometamask" id="alchemypolygontometamaskinstructions-3.addthehttpurltometamask"></a>

On your Alchemy dashboard, click the "VIEW KEY" button to view the RPC URL of your Mumbai node and copy the HTTP. Configure a new Mumbai network on Metamask

* Network Name: Polygon Mumbai (Alchemy Node)
* New RPC URL: *Paste your HTTP from Alchemy Here*
* Chain ID: 80001
* Currency Symbol: MATIC
* Blockchain Explorer URL: <https://mumbai.polygonscan.com/>

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FJh1UNzoMFmjw0jJGetp6%2F7.png?alt=media\&token=539a61c0-5eb2-45b4-87b1-199ffda1e14e) ![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FLik5hbCLXLf870AcCwyr%2F8.png?alt=media\&token=81f4d81d-a887-45e1-b6c3-9a9ce45d5e66) ![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FM7xae5Pt9SUkXvb7t9Ap%2F9.png?alt=media\&token=179771c6-b9a9-4cb2-b15f-30517d04f016)


# 开发人员快速入门

Multi-Chain Storage (hereinafter called the 'MCS') is a suite of Ethereum scaling solutions that enables high-throughput, low cost smart contracts while remaining trustworthy secure.&#x20;

The following documentation describes how to use MCS, which is currently live on Polygon Mumbai Testnet. Whether you're a developer that just wants to start building or you're curious into digging deeper into the internals of MCS and how it works, this site is the right place for you.

## System Design

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FoLl8rq5a7vvUQfYNgOTJ%2FWID.png?alt=media\&token=dbcbdda8-88a8-48cb-b763-c319e44b71eb)

## How does MCS work? <a href="#how-does-arbitrum-work" id="how-does-arbitrum-work"></a>

If you're looking to discover how MCS works, the best place to begin is by the [User Guide](/multichain.storage/mcp-user-guide) section, which gives a high level overview of MCS's internals. From there, you can jump into more detailed explainers on various components of the system.

## Modules <a href="#docusaurus" id="docusaurus"></a>

**Token Swap:** Token Swap module is in charge of swap the user's token to wrapped token, it can be USDC or other tokens.

1. Users pay USDC or other tokens, which are called user tokens, when uploading a file.
2. MCS uses FIL, which is called wrapped token, to pay when store data to Filecoin network.
3. User tokens should be changed to wrapped token by this module and this step is called token exchange(swap).
4. Token exchange(swap) is done through Sushi Swap which is a DEX.

#### Payment Module:

1. After a file is uploaded, the money to be paid is estimated based on the

   * the average price of all the swan miners;
   * file size;
   * duration;

   Then the estimated amount of money will be locked to the payment contract address, see [Configuration](https://github.com/filswan/multi-chain-payment#Configuration).
2. In unlock step, the amount pay to Filecoin network by swan platform FIL wallet, will be transferred to MCS payment receiver address, see [Configuration](https://github.com/filswan/multi-chain-payment#Configuration).
3. In refund step, the overpayment part that is locked will be returned to user wallet

**Swan Client API:** More information can be found [here](https://github.com/filswan/go-swan-client).

**DAO Signature:** If DAO detects that the file uploaded has been chained, it will trigger a signature operation

**Data DAO:** More information can be found at [Flink](https://github.com/filswan/flink).

**IPFS:** More information can be found [here](https://docs.ipfs.io/).

**Filecoin Storage:** More information can be found [here](https://lotus.filecoin.io/docs/set-up/install/).

## How Can I Start Building <a href="#how-can-i-start-building" id="how-can-i-start-building"></a>

### Prerequisites

* OS: Ubuntu 20.04 LTS
* Mysql5.5+
* [Lotus Node](https://github.com/filswan/multi-chain-payment#Lotus-Node)
* [IPFS Client](https://docs.ipfs.io/install/)

#### Lotus Node

* Lotus node is used for making car files and sending offline deals.
* Install lotus node or louts lite node in the same machine as MCS.
* Lotus full node is too heavy compared with lotus lite node, so lotus lite node is preferred.
* Lotus lite node depends on a lotus node, so ensure that a lotus node exists somewhere when using lotus lite node.

**Option1️⃣** [**install a lotus full node**](https://lotus.filecoin.io/docs/set-up/install/)

**Option2️⃣** [**install a lotus lite node**](https://lotus.filecoin.io/docs/set-up/lotus-lite/#amd-and-intel-based-computers)

### Installation

#### Option1️⃣ **Prebuilt package**: See [release assets](https://github.com/filswan/multi-chain-payment/releases)

```
wget https://github.com/filswan/multi-chain-payment/releases/tag/v1.0.1/install.sh
./install.sh
```

#### Option2️⃣ Source Code

🔔**go 1.16+** is required

```
git clone https://github.com/filswan/multi-chain-payment.git
cd multi-chain-payment
git checkout <release_branch>
./build_from_source.sh
```

### After Installation

* Before executing, you should check your configuration in `~/.swan/mcp/config.toml` to ensure it is right.

```
vi ~/.swan/mcp/config.toml
```

* Before executing, you should check your enviornment variable in `~/.swan/mcp/.env` to ensure it is right.

```
vi ~/.swan/mcp/.env
```

* After set your config and env variable in the related files, you can run `multi-chain-payment` in `./build` directory.

```
./build/multi-chain-payment
```

#### Note

* Logs are in directory `./logs`
* You can add `nohup` before `./multi-chain-payment` to ignore the HUP (hangup) signal and therefore avoid stop when you log out.
* You can add `>> mcp.log` in the command to let all the logs output to `mcp.log`.
* You can add `&` at the end of the command to let the program run in background.
* Such as:

```
nohup ./multi-chain-payment-0.2.1-rc1-unix >> mcp.log &   #After installation from Option 1
nohup ./build/multi-chain-payment >> ./build/mcp.log &    #After installation from Option 2
```

### Configuration

You need to modify the config file and input your config params, the configuration items will be introduced below:

#### config.toml

* **port**: Web api port.
* **release**: When work in release mode: set this to true, otherwise to false and environment. variable GIN\_MODE not to release.
* **swan\_platform\_fil\_wallet**: The wallet address used to pay on the Filecoin network.
* **filink\_url**: Deals data can be searched from here.

**\[lotus]**

* **client\_api\_url**: URL of lotus client web api, such as: `http://[ip]:[port]/rpc/v0`, generally the `[port]` is `1234`. See [Lotus API](https://docs.filecoin.io/reference/lotus-api/#features)
* **client\_access\_token**: Access token of lotus client web api. It should have admin access right. You can get it from your lotus node machine using command `lotus auth create-token --perm admin`. See [Obtaining Tokens](https://docs.filecoin.io/build/lotus/api-tokens/#obtaining-tokens)

**\[ipfs\_server]**

* **download\_url\_prefix**: IPFS server url prefix, such as: `http://[ip]:[port]`. Store car files for downloading by storage provider. Car file url will be `[download_url_prefix]/ipfs/[file_hash]`
* **upload\_url\_prefix**: IPFS server url for uploading files, such as `http://[ip]:[port]`

**\[swan\_task]**

* **dir\_deal**: Output directory for saving generated Car files and CSVs.
* **verified\_deal**: \[true/false] Whether deals in this task are going to be sent as verified.
* **fast\_retrieval**: \[true/false] Indicates that data should be available for fast retrieval.
* **start\_epoch\_hours**: start\_epoch for deals in hours from current time.
* **expired\_days**: expected completion days for storage provider sealing data.
* **max\_price**: Max price willing to pay per GiB/epoch for offline deal.
* **generate\_md5**: \[true/false] Whether to generate MD5 for each car file, note: this is a resource consuming action.

**\[polygon]**

* **rpc\_url**: your polygon network RPC URL.
* **payment\_contract\_address**: swan payment gateway address on polygon to lock money.
* **sushi\_dex\_address**: sushi address on polygon.
* **usdc\_wFil\_pool\_contract**: address to get exchange rate between USDC and wFil from sushi on polygon.
* **dao\_contract\_address**: swan DAO address on polygon, to receive DAO signatures.
* **mcp\_payment\_receiver\_address**: MCS wallet address to receive money from unlock operation.
* **gas\_limit**: gas limit for transaction.
* **unlock\_interval\_minute**: unlock interval in minutes between 2 unlock operations, in cannot be less than 1.

#### .env

* **privateKeyOnPolygon**: private key of the wallet used to execute contract methods on the polygon network and pay for gas.

**Want to learn more? Check out the** [**open source code**](https://github.com/filswan/payment-bridge) **and** [**API**](https://docs.filswan.com/development-resource/mcp-api-1)**. Join the team on** [**Discord**](https://discord.gg/djsVYe4b)**.**

### &#x20;<a href="#setup-local-geth-and-rollup-blockchain" id="setup-local-geth-and-rollup-blockchain"></a>

### &#x20;<a href="#hello-arbitrum" id="hello-arbitrum"></a>


# SDK

## Introduction

MCS SDK is the development kit for Swan MCS developers, providing a convenient interface for working with the MCS API.

* **Zero Cost, Free to Use**
* **Access by Wallet (Metamask)**
* **Seamless Integration, Easy to Implement**

### Current Supported Languages:

* [Javascript](/multichain.storage/developer-quickstart/sdk/js-mcs-sdk)

## Use Case

### Decentralized File Storage (Filecoin)

Files are uploaded using the [IPFS](https://docs.ipfs.io/concepts/what-is-ipfs/) protocol, and are accessible through peers located anywhere in the world. IPFS knows how to find what you ask for using its content address rather than its location (HTTP) address. These uploaded files persist on the [Filecoin](https://filecoin.io/) network thanks to storage providers.

IPFS addresses and moves content, while Filecoin is an incentive layer to persist data.

Although your files may be stored by various storage providers, MCS provides a convenient interface to view all your uploaded files.&#x20;

### Multi-Chain Payment Solution

MCS enables users to pay for Filecoin storage with stable coins and other Mainnet tokens while maintaining data security. Users will also obtain the payment transaction and IPFS information with Filecoin deal ID for future reference.

### Mint Files as NFTs

After your file is uploaded to MCS, your assets can simply be minted as viewable NFTs on Opensea (NFT marketplace). Just give your NFT a name (descriptions are optional) and it will be added to the MCS NFT collection on Opensea!

### Building

Using this SDK, the developers will have more control using the API than they would have using the MCS website. Scripts can be written to upload many files at once, mint multiple NFTs, etc. Developers can create dApps on top of MCS, the possibilities are endless!&#x20;


# js mcs SDK

https\://github.com/filswan/js-mcs-sdk

js-mcs-sdk is a javascript software development kit for the MCS service. It provides a convenient interface for working with the MCS API from a web browser or Node.js.&#x20;

The SDK has the following functionalities:

* POST    upload file to FilSwan IPFS gateway
* POST    make payment to Swan Filecoin storage gateway
* POST    mint asset as NFT
* GET       list of files uploaded
* GET       files by CID
* GET       storage status from Filecoin

{% embed url="<https://github.com/filswan/js-mcs-sdk>" %}

### Sponsors

This project is sponsored by Filecoin Foundation

[Flink SDK - A data provider offers Chainlink Oracle service for Filecoin Network](https://github.com/filecoin-project/devgrants/issues/463)

[![](https://github.com/filswan/flink/raw/main/filecoin.png)](https://github.com/filswan/flink/blob/main/filecoin.png)


# 开始

This guide will explain how to install the js-mcs-sdk and its basic usage

## Prerequisites

* [Node.js](https://nodejs.org/en/) - This SDK was built using version v16.13.0 (npm v8.1.0)
* Polygon Mumbai Testnet Wallet - [Metamask Tutorial](/multichain.storage/mcp-user-guide/setup-metamask)
* Polygon Mumbai Testnet Alchemy RPC - [Alchemy Tutorial](https://docs-cn.filswan.com/multichain.storage/developer-quickstart/sdk/js-mcs-sdk/pages/UNtBNqqwgnrbBqCGTaew#alchemypolygontometamaskinstructions-2.createalchemymumbaipolygonrpc)

Mumbai Testnet USDC and MATIC funds are also necessary - [Swan Faucet Tutorial](/kai-fa-zi-yuan/swan-token-contract/acquire-testnet-usdc-and-matic-tokens)

## Installation

Install the package using npm. It is recommended to create a new directory for a new project. Run the init command to setup a package.json file

```
npm init -y
npm install js-mcs-sdk
```

## Environment Variables

Once you have your Mumbai wallet and RPC URL, create a file named `.env` in your project directory and store your wallet's private key and the RPC URL.

```
PRIVATE_KEY=<PRIVATE_KEY>
RPC_URL=https://polygon-mumbai.g.alchemy.com/v2/<API_KEY>
```

{% hint style="info" %}
Be careful not to expose this information! \
Revealing your private key to others will give them access to your wallet.
{% endhint %}

## Writing SDK Scripts

To begin writing a script utilizing the SDK, create a new `.js` file. Let's create a file named `demo.js`

At the top of this file, require the necessary packages for the script.

```
// demo.js
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')
```

* `require('donenv').config()` will add the variables in your `.env` file to `process.env`
* `const { mcsSDK } = require('js-mcs-sdk')` will require the SDK

Next, after requiring the SDK, we still need to initialize it

```
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')

// set up js-mcs-sdk
const mcs = new mcsSDK({
  privateKey: process.env.PRIVATE_KEY,
  rpcUrl: process.env.RPC_URL,
})
```

Now we can begin using the SDK methods. Since these functions are [asynchronous](https://javascript.info/async-await), we will need to create an `async` function to run the SDK methods.

```
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')

// set up js-mcs-sdk
const mcs = new mcsSDK({
  privateKey: process.env.PRIVATE_KEY,
  rpcUrl: process.env.RPC_URL,
})

async function main() {
  // code snippets found in the documentation go here
}

main()
```

{% hint style="info" %}
This is the boilerplate code for all snippets found in the SDK documentation
{% endhint %}

## Upload File Example

Here is a simple example to upload a single file to MCS. Made a new file named `upload.js`

```
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')

// set up js-mcs-sdk
const mcs = new mcsSDK({
  privateKey: process.env.PRIVATE_KEY,
  rpcUrl: process.env.RPC_URL,
})

async function main() {
  const testFile = JSON.stringify({ address: mcs.publicKey })
  const fileArray = [{ fileName: `${mcs.publicKey}.txt`, file: testFile }]

  const uploadResponse = await mcs.upload(fileArray)
  console.log(uploadResponse)
}

main()
```

Use the command `node upload.js` to run the code. This snippet creates the MCS SDK instance, creates a JSON file with your wallet address, and uploads the file to MCS.


# 上传文件

Upload file(s) to MCS using the MCS SDK

`upload(fileArray, options)`

You can use the upload function to upload an array of file(s) to FilSwan IPFS gateway. The array holds a list of objects, and returns an array of response objects. Using `fs` is a simple way to read the file data. The options object is also optional to customize the upload.

```
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')
const fs = require('fs') // used to read files

// set up js-mcs-sdk
const mcs = new mcsSDK({
  privateKey: process.env.PRIVATE_KEY,
  rpcUrl: process.env.RPC_URL,
})

async function main() {
  // ENTER PARAMETERS
  const PATH_1 = ''
  const PATH_2 = ''
  
  const fileArray = [
    { fileName: 'file1', file: fs.createReadStream(PATH_1) },
    { fileName: 'file2', file: fs.createReadStream(PATH_2) },
  ]
  
  //optional, showing default options
  const options = {
    delay: 1000, // delay between upload API calls for each file. May need to be raised for larger files
    duration: 525, // the number of days to store the file on the Filecoin network.
    fileType: 0, // set to 1 for nft metadata files. type 1 files will not show on the UI.
  }
  
  const uploadResponses = await mcs.upload(fileArray, options)
  console.log(uploadResponses)
}

main()
```

### Parameters

* **fileArray**: array of objects
  * **fileName**: name of file
  * **file**: file contents (using `fs` is a simple way to get the file contents)
* **options**: an optional object can also be passed to specify certain parameters:
  * **delay**: delay in milliseconds between upload API calls. Default is 1000, but may need to be increased for many larger files
  * **duration**: Number of days to store your file on the Filecoin network. (default 525)
  * **fileType**: Files of type one will be hidden from the upload list and the UI. NFT metadata files are type 1. (default 0)

### Return

This function returns an array of the upload API responses.

```
[
  {
    status: 'success',
    data: {
      source_file_upload_id: <ID>,
      payload_cid: <'Qm...'>,
      ipfs_url: <'https://calibration-ipfs.filswan.com/ipfs/Qm...'>,
      file_size: <FILE_SIZE>,
      w_cid: <UNIQUE_CID>
    }
  }, ...
]
```


# 支付存储费用

Pay for storage on MCS

`makePayment(wCid, minAmount, fileSize)`

After a file is uploaded, the file can be paid for by its payload cid. The method takes the w\_payload cid as the first parameter and the minimum amount as the second.

```
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')

// set up js-mcs-sdk
const mcs = new mcsSDK({
  privateKey: process.env.PRIVATE_KEY,
  rpcUrl: process.env.RPC_URL,
})

async function main() {
  // ENTER PARAMETERS
  const W_CID = ''
  const MIN_AMOUNT = '1'
  const FILE_SIZE = ''
   
  const tx = await mcs.makePayment(W_CID, MIN_AMOUNT, FILE_SIZE)
  console.log(tx.transactionHash)
}

main()
```

### Parameters

* **wCid**: unique payload cid of the file
* **minAmount**: minimum amount to pay for the file (in USDC). String value to avoid Big Number precision errors. If minAmount is set to empty string or '0', it will default to calculate and use the average storage price
* **fileSize**: the size of the file

### Return

Returns a web3.js receipt object. In the example above, only the transaction hash from this object is printed.


# 铸造NFT

Mint NFT to MCS Opensea Collection

`mintAsset(sourceFileUploadId, nftObject)`

The following code example mints an uploaded file as a NFT viewable on Opensea. Create an NFT object and provide the payload\_cid of the file. The NFT object follows the [Opensea metadata standards](https://docs.opensea.io/docs/metadata-standards).&#x20;

```
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')

// set up js-mcs-sdk
const mcs = new mcsSDK({
  privateKey: process.env.PRIVATE_KEY,
  rpcUrl: process.env.RPC_URL,
})

async function main() {
  // ENTER PARAMETERS
  const SOURCE_FILE_UPLOAD_ID = 0
  const IPFS_URL = ''
  const NFT_NAME = ''

  const NFT_DESCRIPTION = '' // optional

  const nft = {
    name: NFT_NAME, // the name of your NFT
    image: IPFS_URL, // asset URI, images will render on Opensea
    external_url: IPFS_URL, // Opensea will provide a link to view the source
    description: NFT_DESCRIPTION, // description of your NFT
    attributes: [], // NFT attributes displayed on Opensea
  }

  const mintTx = await mcs.mintAsset(SOURCE_FILE_UPLOAD_ID, nft)
  console.log(mintTx)
}

main()
```

The NFT smart contract can be found in the GitHub repository below:

{% embed url="<https://github.com/filswan/nft>" %}

### Parameters

* **sourceFileUploadId**: upload Id of the file
* **nftObject**: object following Opensea Metadata Standards
  * **name**: name of your NFT (required)
  * **image**: IPFS URL of your file (required)
  * **description**: description of your NFT
  * **external\_url**: viewable link on Opensea UI
  * **attributes**: array of attribute objects you wish to show on Opensea

### Return

Returns the response from the `/mint/info` API

```
{
  status: 'success',
  data: {
    id: <ID>,
    source_file_upload_id: <ID>,
    nft_tx_hash: <'0x...'>,
    mint_address: '0x1A1e5AC88C493e0608C84c60b7bb5f04D9cF50B3',
    token_id: '<ID>',
    create_at: <TIME>,
    update_at: <TIME>
  }
}
```


# 文件列表

View your uploaded files

`getUploads(walletAddress, payloadCid, fileName, orderBy, isAscend, status, isMinted, pageNumber, pageSize)`

The following code example lists a user's uploaded files. The list can be searched by file name, and also be filtered or sorted.

```
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')
const fs = require('fs') // used to read files

// set up js-mcs-sdk
const mcs = new mcsSDK({
  privateKey: process.env.PRIVATE_KEY,
  rpcUrl: process.env.RPC_URL,
})

async function main() {
  // ENTER PARAMETERS
  const FILE_NAME = ''
  const ORDER_BY = ''
  const IS_ASCEND = ''
  const STATUS = ''
  const IS_MINTED = ''
  const PAGE_NUMBER = 1
  const PAGE_SIZE = 10
  
  const uploads = await mcs.getUploads(
    mcs.publicKey,
    FILE_NAME,
    ORDER_BY,
    IS_ASCEND,
    STATUS,
    IS_MINTED,
    PAGE_NUMBER,
    PAGE_SIZE,
  )
  
  console.log(uploads.data.source_file_upload)
}

main()
```

### Parameters

* **walletAddress**: lists the files uploaded by this account (required)
* **fileName**: filter by this file name
* **orderBy**: sort the list by file name, file size, or upload time (default)
* **isAscend**: y for ascending list, otherwise descend (default)
* **status**: Pending, Processing, Refundable, Refunded, Success or other
* **isMinted**: y, n, all (default)
* **pageNumber**: page number (default 1)
* **pageSize**: number of results in a page (default 10)

Only the walletAddress parameter is required, the rest are optional.

### Return

Returns an array containing some details of the file(s).

```
[
  {
    source_file_upload_id: <ID>,
    car_file_id: <ID>,
    file_name: <FILE_NAME>,
    file_size: <FILE_SIZE>,
    upload_at: <TIME>,
    duration: 525,
    ipfs_url: <'https://calibration-ipfs.filswan.com/ipfs/Qm...'>,
    pin_status: 'Pinned',
    payload_cid: <'bafy...'>,
    w_cid: <UNIQUE_CID>,
    status: 'Processing',
    deal_success: <BOOLEAN>,
    is_minted: <BOOLEAN>,
    token_id: <ID>,
    mint_address: '0x1A1e5AC88C493e0608C84c60b7bb5f04D9cF50B3',
    nft_tx_hash: <'0x...'>,
    offline_deal: [ [Object], [Object], [Object], [Object], [Object] ]
  }, ...
]
```


# 获取文件详情

Get Details about a specific file

`getFileDetails(sourceFileUploadId, dealId)`

The following code example gets the file details of an uploaded file. This method takes the upload id of the file, and the deal id of the file. The deal id can be obtained by the getUploads method

```
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')
const fs = require('fs') // used to read files

// set up js-mcs-sdk
const mcs = new mcsSDK({
  privateKey: process.env.PRIVATE_KEY,
  rpcUrl: process.env.RPC_URL,
})

async function main() {
  // ENTER PARAMETERS
  const SOURCE_FILE_UPLOAD_ID = ''
  const DEAL_ID = ''
   
  console.log(await mcs.getFileDetails(SOURCE_FILE_UPLOAD_ID, DEAL_ID))
}

main()
```

### Parameters

* **sourceFileUploadId**: upload id of the file
* **dealId**: deal id of the file

### Return

Returns the response from the `/deal/detail/` API

```
{
  status: 'success',
  data: {
    dao_signature: [ [Object], [Object], [Object], [Object] ],
    dao_threshold: 2,
    source_file_upload_deal: {
      deal_id: <ID>,
      deal_cid: '',
      message_cid: <'bafy...'>,
      height: <NUMBER>,
      piece_cid: <'...'>,
      verified_deal: <BOOLEAN>,
      storage_price_per_epoch: 0,
      signature: '',
      signature_type: '',
      created_at: <TIME>,
      piece_size_format: null,
      start_height: <NUMBER>,
      end_height: <NUMBER>,
      client: <'f...'>,
      client_collateral_format: '000000000000000000',
      provider: <'f...'>,
      provider_tag: '',
      verified_provider: 0,
      provider_collateral_format: '000000000000000000',
      status: 0,
      network_name: 'filecoin_mainnet',
      storage_price: 0,
      ipfs_url: <'https://calibration-ipfs.filswan.com/ipfs/Qm...'>,
      file_name: <FILE_NAME>,
      w_cid: <UNIQUE_CID>,
      car_file_payload_cid: <'bafy...'>,
      locked_at: <TIME>,
      locked_fee: <AMOUNT>,
      unlocked: <BOOLEAN>
    }
  }
}
```


# 获取文件在Filecoin上的状态

Get Filecoin storage status of a file

`getFileStatus(dealId)`

The following code example returns the FIlecoin storage status of a paid file. This method requires the deal id of the deal. This can also be obtained by the getUploads method.

```
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')
const fs = require('fs') // used to read files

// set up js-mcs-sdk
const mcs = new mcsSDK({
  privateKey: process.env.PRIVATE_KEY,
  rpcUrl: process.env.RPC_URL,
})

async function main() {
  // ENTER PARAMETERS
  const DEAL_ID = 0
  
  const mintResponse = await mcs.getFileStatus(DEAL_ID)
  console.log(mintResponse)
}

main()
```

### Parameters

* **dealId**: deal id of the file

### Return

Returns the response from the `/deal/log/` API

```
{
  status: 'success',
  data: {
    offline_deal_log: [ [Object], [Object], [Object], [Object], [Object], [Object] ]
  }
}
```


# SDK安装视频教程

{% embed url="<https://www.youtube.com/watch?v=hLBLwkEy__o>" %}


# python mcs SDK

https\://github.com/filswan/python-mcs-sdk

py-mcs-sdk is a python software development kit for the MCS service. It provides a convenient interface for working with the MCS API.&#x20;

The SDK has the following functionalities:

* POST    upload file to FilSwan IPFS gateway
* POST    make payment to Swan Filecoin storage gateway
* POST    mint asset as NFT
* GET       list of files uploaded
* GET       files by CID
* GET       storage status from Filecoin

{% embed url="<https://github.com/filswan/python-mcs-sdk>" %}

### Sponsors

This project is sponsored by Filecoin Foundation

[Flink SDK - A data provider offers Chainlink Oracle service for Filecoin Network](https://github.com/filecoin-project/devgrants/issues/463)

[![](https://github.com/filswan/flink/raw/main/filecoin.png)](https://github.com/filswan/flink/blob/main/filecoin.png)


# 开始

This guide will explain how to install the python-mcs-sdk and its basic usage

## Prerequisites

* [Web3](https://web3py.readthedocs.io/en/stable/) python package
* Polygon Mumbai Testnet Wallet - [Metamask Tutorial](/multichain.storage/mcp-user-guide/setup-metamask)
* Polygon Mumbai Testnet Alchemy RPC - [Alchemy Tutorial](https://docs-cn.filswan.com/multichain.storage/developer-quickstart/sdk/python-mcs-sdk/pages/UNtBNqqwgnrbBqCGTaew#alchemypolygontometamaskinstructions-2.createalchemymumbaipolygonrpc)
* [pytest](https://docs.pytest.org/en/7.1.x/) package (for testing purposes)

Mumbai Testnet USDC and MATIC funds are also necessary - [Swan Faucet Tutorial](/kai-fa-zi-yuan/swan-token-contract/acquire-testnet-usdc-and-matic-tokens)

## Installation

Install package using pip

```
pip install python-mcs-sdk
```

Or Install the package from [https://github.com/filswan/python-mcs-sdk](https://github.com/filswan/python-mcs-sdk.git).

```
$ git clone https://github.com/filswan/python-mcs-sdk.git
```

Install required packages using pip.

```
pip install -r requirements.txt
```

## Environment Variables

Once you have your Mumbai wallet and RPC URL, store your wallet's private key and the RPC URL.

```
wallet_info = {
  'wallet_address' : <'WALLET_ADDRESS'>
  'private_key' : <'PRIVATE_KEY'>
  'web3_api' : '<'WEB3_API'>
}
```

{% hint style="info" %}
Be careful not to expose this information! \
Revealing your private key to others will give them access to your wallet.
{% endhint %}

## Writing SDK Scripts

To begin writing a script utilizing the SDK, create a new `.py` file. Let's create a file named `demo.py`

At the top of this file, require the necessary packages for the script. (pytest is only necessary if you are running a test)

```
from mcs.api import McsAPI
from mcs.contract import ContractAPI
```

Next, after requiring the SDK, set up the wallet information.

```
wallet_info = {
        'wallet_address' : '*',
        'private_key' : '*',
        'web3_api' : '*',
    }
```

Now we can begin using the SDK methods.


# 上传文件

Upload file(s) to MCS using the MCS SDK

`McsAPI.upload_file(wallet_address, file_path)`

You can use the upload function to upload a single file to FilSwan IPFS gateway. The function takes your MetaMask wallet address and the absolute path of the file for upload.

```
def test_upload_file(wallet_info):
    wallet_address = wallet_info['wallet_address']

    api = McsAPI()
    # upload file to mcs
    file_path = "/*"
    upload_file = api.upload_file(wallet_address, file_path)
```

### Parameters

* wallet\_address: MetaMask wallet address.
* file\_path: Absolute path of the file for upload.

### Return

This function returns the upload API responses. This includes `source_file_upload_id`, `file_size` *and* `w_cid` that will be used for payments.

```
{
  status: 'success',
  data: {
    source_file_upload_id: <ID>,
    payload_cid: <'Qm...'>,
    ipfs_url: <'https://calibration-ipfs.filswan.com/ipfs/Qm...'>,
    file_size: <FILE_SIZE>,
    w_cid: <UNIQUE_CID>
  }
}
```


# Stream Upload Files

Upload large files using stream upload.

`McsAPI.stream_upload_file(wallet_address, file_path)`

Stream upload can be used in the same way as normal upload.

```
def test_stream_upload_file_pay():
    wallet_address = wallet_info['wallet_address']

    api = McsAPI()
    # upload file to mcs
    file_path = "/*"
    upload_file = api.stream_upload_file(wallet_address, file_path)
```

### Parameters

* wallet\_address: MetaMask wallet address.
* file\_path: Absolute path of the file for upload.


# 支付存储费用

Pay for storage on MCS

After a file is uploaded, the file can be paid for by its cid (w\_cid). However, the wallet needs to be verified first, using `ContractAPI.approve_usdc(wallet_address, private_key, "1")`.

```
def test_approve_usdc(wallet_info):
    wallet_address = wallet_info['wallet_address']
    private_key = wallet_info['private_key']
    web3_api = wallet_info['web3_api']
    
    w3_api = ContractAPI(web3_api)
    w3_api.approve_usdc(wallet_address, private_key, "1")
```

### Parameters

* **wallet\_address**: the MetaMask wallet address.
* **private\_key**: wallet private key

Then the payment can be executed using `file_size` and `w_cid`. Which can all be obtained from the response of upload API (or be accessed using file detail API that will be introduced later).

`ContractAPI.upload_file_pay(wallet_address, private_key, file_size, w_cid, rate, params)`

```
def test_upload_file_pay(wallet_info):
    wallet_address = wallet_info['wallet_address']
    private_key = wallet_info['private_key']
    web3_api = wallet_info['web3_api']

    w3_api = ContractAPI(web3_api)
    api = McsAPI()
    # upload file to mcs
    file_path = "/*"
    upload_file = api.upload_file(wallet_address, file_path)
    file_data = upload_file["data"]
    payload_cid, source_file_upload_id, nft_uri, file_size, w_cid = file_data['payload_cid'], file_data[
        'source_file_upload_id'], file_data['ipfs_url'], file_data['file_size'], file_data['w_cid']
    # get the global variable
    params = api.get_params()["data"]
    # get filcoin price
    rate = api.get_price_rate()["data"]
    # upload_file_pay
    w3_api.upload_file_pay(wallet_address, private_key, file_size, w_cid, rate, params)
```

### Parameters

* **wallet\_address**: the MetaMask wallet address.
* **private\_key**: wallet private key
* **file\_size:** the size of the uploaded file.
* **w\_cid**: unique payload CID of the file
* **params**: variables that can be obtained use API.
* **rate**: Filcoin price that can be obtained use API.

### Return

Returns a web3.py receipt object. In the example above, only the transaction hash from this object is printed.


# 铸造NFT

Mint NFT to MCS Opensea Collection

`McsAPI.upload_nft_metadata(wallet_address, filename, nft_uri, tx_hash, file_size)`

`ContractAPI.mint_nft(wallet_address, private_key, meta_url)`

The following code example mints an uploaded file as a NFT viewable on Opensea. Create an NFT object and provide the payload\_cid of the file. The NFT object follows the [Opensea metadata standards](https://docs.opensea.io/docs/metadata-standards).&#x20;

```
def test_mint_nft(wallet_info):
    wallet_address = wallet_info['wallet_address']
    private_key = wallet_info['private_key']
    web3_api = wallet_info['web3_api']
    
    w3_api = ContractAPI(web3_api)
    api = McsAPI()

    # upload file to mcs
    file_path = "/i*"
    filename = "/*"
    upload_file = api.upload_file(wallet_address, file_path)
    file_data = upload_file["data"]
    payload_cid, source_file_upload_id, nft_uri, file_size, w_cid = file_data['payload_cid'], file_data[
        'source_file_upload_id'], file_data['ipfs_url'], file_data['file_size'], file_data['w_cid']
    # get the global variable
    params = api.get_params()["data"]
    # get filcoin price
    rate = api.get_price_rate()["data"]
    # test upload_file_pay contract
    tx_hash = w3_api.upload_file_pay(wallet_address, private_key, 
        file_size, w_cid, rate, params)
    # upload nft metadata
    meta_url = api.upload_nft_metadata(wallet_address, filename, 
        nft_uri, tx_hash, file_size)['data']['ipfs_url']
    # mint nft contract
    tx_hash, token_id = w3_api.mint_nft(wallet_address, private_key, meta_url)
    # update mint info
    api.get_mint_info(source_file_upload_id, None, tx_hash, token_id, wallet_address)
```

### Parameters

* **wallet\_address**: the MetaMask wallet address.
* **private\_key**: wallet private key
* **meta\_url**: can be obtained through `upload_nft_metadata`

### Return

Returns the response from the `/mint/info` API

```
{
  status: 'success',
  data: {
    id: <ID>,
    source_file_upload_id: <ID>,
    nft_tx_hash: <'0x...'>,
    mint_address: '0x1A1e5AC88C493e0608C84c60b7bb5f04D9cF50B3',
    token_id: '<ID>',
    create_at: <TIME>,
    update_at: <TIME>
  }
}
```


# 文件列表

View your uploaded files

`McsAPI.get_user_tasks_deals(self, wallet_address)`

The following code example lists a user's uploaded files. The list can be searched by file name, and also be filtered or sorted.

```
def list_files(wallet_info):
    wallet_address = wallet_info['wallet_address']

    api = McsAPI()
    return api.get_user_tasks_deals(wallet_address)
```

### Parameters

* **wallet\_address**: lists the files uploaded by this account (required)

### Other Parameters of the API&#x20;

Can be used by editing the original get\_user\_tasks\_deals function.

* **file\_name**: filter by this file name
* **order\_by**: sort the list by file name, file size, or upload time (default)
* **is\_ascend**: y for ascending list, otherwise descend (default)
* **status**: Pending, Processing, Refundable, Refunded, Success or other
* **is\_minted**: y, n, all (default)
* **page\_number**: page number (default 1)
* **page\_size**: number of results in a page (default 10)

Only the wallet\_address parameter is required, the rest are optional.

### Return

Returns an array containing some details of the file(s).

```
[
  {
    source_file_upload_id: <ID>,
    car_file_id: <ID>,
    file_name: <FILE_NAME>,
    file_size: <FILE_SIZE>,
    upload_at: <TIME>,
    duration: 525,
    ipfs_url: <'https://calibration-ipfs.filswan.com/ipfs/Qm...'>,
    pin_status: 'Pinned',
    payload_cid: <'bafy...'>,
    w_cid: <UNIQUE_CID>,
    status: 'Processing',
    deal_success: <BOOLEAN>,
    is_minted: <BOOLEAN>,
    token_id: <ID>,
    mint_address: '0x1A1e5AC88C493e0608C84c60b7bb5f04D9cF50B3',
    nft_tx_hash: <'0x...'>,
    offline_deal: [ [Object], [Object], [Object], [Object], [Object] ]
  }, ...
]
```


# 获取文件详情

Get Details about a specific file

`McsAPI.get_payment_info(self, payload_cid, wallet_address, source_file_upload_id)`

The following code example gets the file details of an uploaded file. This method takes the upload id of the file, and the deal id of the file.

```
def file_detail(wallet_info):
    wallet_address = wallet_info['wallet_address']
    private_key = wallet_info['private_key']
    web3_api = wallet_info['web3_api']
    
    w3_api = ContractAPI(web3_api)
    api = McsAPI()

    # upload file to mcs
    file_path = "/i*"
    filename = "/*"
    upload_file = api.upload_file(wallet_address, file_path)
    file_data = upload_file["data"]
    payload_cid, source_file_upload_id, nft_uri, file_size, w_cid = file_data['payload_cid'], file_data[
        'source_file_upload_id'], file_data['ipfs_url'], file_data['file_size'], file_data['w_cid']
    # get deal details
    return deal_detail = api.get_deal_detail(wallet_address, source_file_upload_id)
```

### Parameters

* **source\_file\_upload\_id**: upload id of the file
* **payload\_cid**: not required

### Return

Returns the response from the `/deal/detail/` API

```
{
  status: 'success',
  data: {
    dao_signature: [ [Object], [Object], [Object], [Object] ],
    dao_threshold: 2,
    source_file_upload_deal: {
      deal_id: <ID>,
      deal_cid: '',
      message_cid: <'bafy...'>,
      height: <NUMBER>,
      piece_cid: <'...'>,
      verified_deal: <BOOLEAN>,
      storage_price_per_epoch: 0,
      signature: '',
      signature_type: '',
      created_at: <TIME>,
      piece_size_format: null,
      start_height: <NUMBER>,
      end_height: <NUMBER>,
      client: <'f...'>,
      client_collateral_format: '000000000000000000',
      provider: <'f...'>,
      provider_tag: '',
      verified_provider: 0,
      provider_collateral_format: '000000000000000000',
      status: 0,
      network_name: 'filecoin_mainnet',
      storage_price: 0,
      ipfs_url: <'https://calibration-ipfs.filswan.com/ipfs/Qm...'>,
      file_name: <FILE_NAME>,
      w_cid: <UNIQUE_CID>,
      car_file_payload_cid: <'bafy...'>,
      locked_at: <TIME>,
      locked_fee: <AMOUNT>,
      unlocked: <BOOLEAN>
    }
  }
}
```


# 更多资源

## **Github and NPM** <a href="#sdkusercase-whatisfilecoin" id="sdkusercase-whatisfilecoin"></a>

{% embed url="<https://github.com/filswan/js-mcs-sdk/>" %}

{% embed url="<https://www.npmjs.com/package/js-mcs-sdk>" %}

### What is Filecoin?

<https://docs.filecoin.io/about-filecoin/what-is-filecoin/>

### **What is an NFT?** <a href="#sdkusercase-whatisannft" id="sdkusercase-whatisannft"></a>

<https://support.opensea.io/hc/en-us/articles/360063450733-What-is-a-Non-Fungible-Token-NFT-><br>


# 运行Multichain.Storage节点

In this section, we'll explain the requirements and basics for running your own MCS node.

It's important to note that nodes can fulfill requests for open APIs out-of-the-box using our [Tasks](/filswan-platform/overview/filswan-auction-system) without needing any additional configuration.

If you would like to provide data from an authenticated API, you can add an external adapter to enable connectivity through the MCS node.

{% embed url="<https://github.com/filswan/filecoin-chart>" %}

{% embed url="<https://github.com/filswan/filecoin-docker>" %}

{% embed url="<https://github.com/filswan/filecoin_tools>" %}

## Hardware Requirements

### MCS Node

Your MCS node should be run on a server that has a public IP address.

#### Minimum

To get started running an MCS node, you will need a machine with at least **4 cores** and **4 GB of RAM**.

#### Recommended

The requirements for running an MCS node scale as the number of jobs your node services also scale. For nodes with over 100 jobs, you will need at least **4 cores** and **8GB of RAM**.

### MySQL Database

In addition to running an MCS node, you will also need a PostgreSQL database. Please use a version >= 11, and be sure that your DB host provides access to logs.

#### Minimum

The minimum requirements for the database are **2 cores**, **4GB of RAM**, and **100 GB of storage**.

#### Recommended

Similar to the MCS node, requirements increase as you service more jobs. For more than 100 jobs, your database server will need at least **4 cores**, **16 GB of RAM**, and **100 GB of storage**.

If you run your node on AWS, use an instance type with dedicated core time. [Burstable Performance Instances](https://aws.amazon.com/ec2/instance-types/#Burstable_Performance_Instances) have a limited number of [CPU credits](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-credits-baseline-concepts.html), so you should not use them to run MCS nodes that require consistent performance.

### Ethereum Client

Connectivity to an Ethereum client is also required for communication with the blockchain. If you decide to run your own Ethereum client, you will want to run that on a separate machine. Hardware requirements of Ethereum clients may change over time. You can also use a 3rd party (defined below).

### Filecoin Lotus Client

Connectivity to an Ethereum client is also required for communication with the Filecoin blockchain. If you decide to run your own Ethereum client, you will want to run that on a separate machine. Hardware requirements of Ethereum clients may change over time. You can also use a 3rd party (defined below).

### Chainlink node

Operating a Chainlink node allows you to be part of the Chainlink Network, helping developers build hybrid smart contracts, and giving them access to real-world data and services.

Learn more about Chainlink nodes with our step‑by‑step tutorials and documentation:

**Set Up a Chainlink Node**

Install and run your own node on a local machine or remote server.

[Learn More ![Right arrow](https://docs.chain.link/images/card-icons/navigation-arrow-right.svg)](https://docs.chain.link/docs/running-a-chainlink-node)![](https://uploads-ssl.webflow.com/5e444500cbc42eeb5198206f/5e7898724c71bd62c149df16_Example.svg)

**Fulfill Your First Job Request**

Deploy an Oracle contract and make job requests to your node.

[Learn More ![Right arrow](https://docs.chain.link/images/card-icons/navigation-arrow-right.svg)](https://docs.chain.link/docs/fulfilling-requests)![](https://uploads-ssl.webflow.com/5e444500cbc42eeb5198206f/5e7894ddbc6262c7a18da684_RequestSmall.svg)

**Add External Adapters to Your Node**

Bring high-quality data and premium web APIs to contract developers.

[Learn More ![Right arrow](https://docs.chain.link/images/card-icons/navigation-arrow-right.svg)](https://docs.chain.link/docs/node-operators)

## Running From Source

To run an MCS node from the source, use the [following instructions](https://github.com/smartcontractkit/chainlink#install).

## Using Docker

It's recommended to run the MCS node with [Docker](https://www.docker.com/). This is because we continuously build and deploy the code from our [repository on Github](https://github.com/smartcontractkit/chainlink), which means you don't need a complete development environment to run a node.

### Requirements

* [Docker-CE](https://docs.docker.com/install/). Quick instructions for setting up Docker is below:

```shell
sudo amazon-linux-extras install -y docker
sudo systemctl start docker
sudo gpasswd -a $USER docker
exit
# log in again
```

```shell
curl -sSL https://get.docker.com/ | sh
sudo systemctl start docker
sudo usermod -aG docker $USER
exit
# log in again
```

```shell
curl -sSL https://get.docker.com/ | sh
sudo usermod -aG docker $USER
exit
# log in again
```

```shell
curl -sSL https://get.docker.com/ | sh
sudo systemctl start docker
sudo usermod -aG docker $USER
exit
# log in again
```

```shell
curl -sSL https://get.docker.com/ | sh
sudo usermod -aG docker $USER
exit
# log in again
```

* A fully synced Ethereum client with websockets enabled. Client specific instructions can be found below:
  * [Run Geth](https://github.com/filswan/gitbook/blob/main/run-an-ethereum-client/README.md#geth)
  * [Run OpenEthereum](https://github.com/filswan/gitbook/blob/main/run-an-ethereum-client/README.md#parity)
  * [Use an external service](https://github.com/filswan/gitbook/blob/main/run-an-ethereum-client/README.md#external-services)

#### Create a directory

Once you have your Ethereum client running and fully synced, you're ready to run the MCS node.

Create a local directory to hold the MCS data:

```shell
mkdir ~/.MCS-rinkeby
```

```shell
mkdir ~/.MCS-kovan
```

```shell
mkdir ~/.MCS
```

> ***Other Supported Networks:*** MCS is blockchain agnostic technology. The [LINK Token Contracts](https://github.com/filswan/gitbook/blob/main/link-token-contracts/README.md) page details networks which support the LINK token. You can setup your node to provide data to any of these blockchains.

#### Create an Environment File

Run the following as a command to create an environment file and populate with variables specific to the network you're running on. For a full list of available configuration variables, click [here](https://github.com/filswan/gitbook/blob/main/configuration-variables/README.md).

```shell
echo "ROOT=/MCS
LOG_LEVEL=debug
ETH_CHAIN_ID=4
MCS_TLS_PORT=0
SECURE_COOKIES=false
ALLOW_ORIGINS=*" > ~/.MCS-rinkeby/.env
```

```shell
echo "ROOT=/MCS
LOG_LEVEL=debug
ETH_CHAIN_ID=42
MCS_TLS_PORT=0
SECURE_COOKIES=false
ALLOW_ORIGINS=*" > ~/.MCS-kovan/.env
```

```shell
echo "ROOT=/MCS
LOG_LEVEL=debug
ETH_CHAIN_ID=1
MCS_TLS_PORT=0
SECURE_COOKIES=false
ALLOW_ORIGINS=*" > ~/.MCS/.env
```

#### Set your Ethereum Client URL

> 🚧 Using an external Ethereum client?
>
> If you're using a 3rd party service to connect to the blockchain, skip to the [External Provider](#ethereum-client-as-an-external-provider) section to set the `ETH_URL` environment variable. We provide general guidance, but you will need to obtain the websocket connection string to add to your environment file.

#### Ethereum Client on the Same Machine

Next you need to get the URL for the Ethereum client. The command below will help you obtain the IP address of the container that your Ethereum client is running on. **This will only work if you have started an Ethereum client on the same machine as your** MCS **node.**

```shell
ETH_CONTAINER_IP=$(docker inspect --format '{{ "{{ .NetworkSettings.IPAddress " }}}}' $(docker ps -f name=eth -q))
```

Then run the following command to add the Ethereum client's URL to your environment file. If you are using an external Ethereum client, use the External tab below, and update `$ETH_CONTAINER_IP` to the websocket address used for connectivity.

```shell
echo "ETH_URL=ws://$ETH_CONTAINER_IP:8546" >> ~/.MCS-rinkeby/.env
```

```shell
echo "ETH_URL=ws://$ETH_CONTAINER_IP:8546" >> ~/.chainlink-kovan/.env
```

```shell
echo "ETH_URL=ws://$ETH_CONTAINER_IP:8546" >> ~/.chainlink/.env
```

#### Ethereum Client as an External Provider

If you are using an external provider for connectivity to the Ethereum blockchain or you are running an Ethereum client on a separate instance, you may use the command below for your network. Be sure to update the value for `CHANGEME` to the value given by your provider or the address and port of your separate instance.

```shell
echo "ETH_URL=CHANGEME" >> ~/.chainlink-rinkeby/.env
```

```shell
echo "ETH_URL=CHANGEME" >> ~/.chainlink-kovan/.env
```

```shell
echo "ETH_URL=CHANGEME" >> ~/.chainlink/.env
```

> 🚧 Running Chainlink Node on Ganache
>
> Ganache is a mock testnet and it doesn't work with Chainlink because of that. To use the features of the network, you need to deploy your contract on a real environment: one of the testnets or mainnets. The full list of supported environments can be found [here](https://github.com/filswan/gitbook/blob/main/link-token-contracts/README.md).

#### Set the Remote DATABASE\_URL Config

You will need to connect your Chainlink node with a remote PostgreSQL database. See the [Connecting to a Remote Database](https://github.com/filswan/gitbook/blob/main/connecting-to-a-remote-database/README.md) page for more information. Use the example below to configure your `DATABASE_URL` setting in your environment file, replacing `$VARIABLES` with their actual values.

* `$USERNAME`: The database username (must be owner)
* `$PASSWORD`: The user's password
* `$SERVER`: The server name or IP address of the database server
* `$PORT`: The port that the database is listening on
* `$DATABASE`: The database to use for the Chainlink node (i.e. "postgres")

> 🚧 Important
>
> If you're testing you can add `?sslmode=disable` to the end of your `DATABASE_URL`. However you should *never* do this on a production node.

```shell
echo "DATABASE_URL=postgresql://$USERNAME:$PASSWORD@$SERVER:$PORT/$DATABASE" >> ~/.chainlink-rinkeby/.env
```

```shell
echo "DATABASE_URL=postgresql://$USERNAME:$PASSWORD@$SERVER:$PORT/$DATABASE" >> ~/.chainlink-kovan/.env
```

```shell
echo "DATABASE_URL=postgresql://$USERNAME:$PASSWORD@$SERVER:$PORT/$DATABASE" >> ~/.chainlink/.env
```

####

#### Start the MCS Node

Now you can run the Docker image. Replace `<version>` with your desired version. Tag versions are available in the [Chainlink docker hub](https://hub.docker.com/r/smartcontract/chainlink/tags). *The `latest` version does not work.*

```shell
cd ~/.chainlink-rinkeby && docker run -p 6688:6688 -v ~/.chainlink-rinkeby:/chainlink -it --env-file=.env smartcontract/chainlink:<version> local n
```

```shell
cd ~/.chainlink-kovan && docker run -p 6688:6688 -v ~/.chainlink-kovan:/chainlink -it --env-file=.env smartcontract/chainlink:<version> local n
```

```shell
cd ~/.chainlink && docker run -p 6688:6688 -v ~/.chainlink:/chainlink -it --env-file=.env smartcontract/chainlink:<version> local n
```

> 📘 Local Database
>
> If you're running a local database you may need to add the `--network host` flag to the command above.

The first time running the image, it will ask you for a password and confirmation. This will be your wallet password that you can use to unlock the keystore file generated for you. Then, you'll be prompted to enter an API Email and Password. This will be used to expose the API for the GUI interface, and will be used every time you log into your node. When running the node again, you can supply the `-p` option with a path to a text file containing the wallet key password, and a `-a` option, pointing to a text file containing the API email and password. Instructions on how to do that are [here](https://github.com/filswan/gitbook/blob/main/miscellaneous/README.md#use-password-and-api-files-on-startup).

> 📘 Important
>
> You will need to send some ETH to your node's address in order for it to fulfill requests. You can view your node's ETH address when the node starts up or on the Configuration page of the GUI
>
> You need to send link to the following address for Chainlink Oracle Service
>
> {flink\_service\_contract}: link
>
> {DAO *multisig* wallet *holder address*} : matic
>
> {node\_wallet}: matic

You can now connect to your Chainlink node's UI interface by navigating to <http://localhost:6688>. If using a VPS, you can create a [SSH tunnel](https://www.howtogeek.com/168145/how-to-use-ssh-tunneling/) to your node for `6688:localhost:6688` to enable connectivity to the GUI. Typically this is done with `ssh -i $KEY $USER@$REMOTE-IP -L 6688:localhost:6688 -N`. A SSH tunnel is recommended over opening up ports specific to the Chainlink node to be public facing. See the [Security and Operation Best Practices](https://github.com/filswan/gitbook/blob/main/best-security-practices/README.md) page for more details on how to secure your node.


# Multichain Storage 概述

基于智能合约的跨链存储

### 介绍 <a href="#jie-shao" id="jie-shao"></a>

多链存储（Multichain.Storage）是一基于智能合约的跨链存储，集成了预言机技术。 它通过桥接多个区块链网络来加速分散存储的大规模应用。

Multichain.Storage 使用户能使用稳定币和其他主网代币支付 Filecoin 存储费用，同时保持数据安全。 用户能通过 Filecoin 交易 ID 获取支付信息和 IPFS 信息，以供日后参考。

### 功能 <a href="#gong-neng" id="gong-neng"></a>

MCS 是一项尖端的区块链存储解决方案，为分散的数据存储需求提供数据缓存。&#x20;

使用 MCS，用户可以

* 将任何数据上传到 Filecoin 网络和 IPFS。
* 使用 USDC 和其他主网代币等稳定币支付存储费用。
* 直接铸造NFT到 OpenSea。
* 通过连接第三方钱包（MetaMask）使用服务  。
* 过内置的自动出价系统自动发送或获取交易。
* 合併多个小文件成单个大文件进行发单。
* 支持多矿工进行存储。

### 优势

Filecoin 是一种开源的公共加密货币和数字支付系统，旨在成为一种基于区块链的协作数字存储和数据检索方法。 Filecoin作为一个强大的动态分布式云存储网络，被Near、Polygon等多个区块链项目采用。

但是，这些单独的链或项目各自独立运行，几乎无法相互交流。 全球用户因此面临大量具有不同算法、交易类型、规则的网络，这阻碍了用户充分享受区块链技术的潜力。

**这就是为什么** Multichain.Storage **致力于保证区块链的无缝互操作性。** 自推出以来，Multichain.Storage 一直致力于缩小差距，允许用户将其他代币换成 Fil 以支付数据存储费用。 MCS 将把数据存储带到下一个安全、去中心化和民主化水平。

{% embed url="<https://github.com/filswan/multi-chain-storage/tree/qa_single_miner>" %}


# Flink

数据提供商DAO 为 Filecoin 网络提供 Chainlink Oracle 服务

### 介绍

Flink 是一个数据提供商 DAO，旨在为 Filecoin 网络提供 Chainlink Oracle 服务。 Flink 为想要将数据存储在 Filecoin 上的用户提供多链的交易信息。

### 什么是 Filecoin - Chainlink 数据提供者 <a href="#shen-me-shi-filecoinchainlink-shu-ju-ti-gong-zhe" id="shen-me-shi-filecoinchainlink-shu-ju-ti-gong-zhe"></a>

Filecoin 是以太坊、BSC 和 Polygon 等区块链用户在链下存储大规模数据的最佳选择。 用户可以通过发送交易从 Filecoin 网络上传和检索数据。 但是，如何生成跨链证明仍然没有解决，并且在用户的存储需求和 Fileocin 存储解决方案之间造成了差距。

External adapter 允许访问高质量数据，并实现将智能合约连接到高级 Web API 的极大灵活性。 使用 Chainlink external adapter ，用户可以在预言机节点运营商上查看他们的交易信息。

{% embed url="<https://github.com/filswan/flink>" %}

### 用例 <a href="#yong-li" id="yong-li"></a>

#### 使用USDC支付Polygon上NFT的文件存储费用 <a href="#shi-yong-usdc-zhi-fu-polygon-shang-nft-de-wen-jian-cun-chu-fei-yong" id="shi-yong-usdc-zhi-fu-polygon-shang-nft-de-wen-jian-cun-chu-fei-yong"></a>

在Filecoin网络上保存NFT的一般过程是：

* 在Polygon网络上锁定付款
* 将代币兑换给Filecoin代理者
* Filecoin 代理者发送NFT交易给Filecoin存储提供者
* 获取链上交易ID
* chainlink预言机向Polygon链进行广播证明
* 存储DAO公证人根据chainlink预言机提供的交易信息对数据进行签名
* NFT支付费用解锁到Filecoin代理者

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2F8s2rfZVt4p0WziXJt1Pt%2Fflink%20image.png?alt=media\&token=813dc140-9e34-4c71-a68b-14b35c22d97c)

### 设计结构 <a href="#she-ji-jie-gou" id="she-ji-jie-gou"></a>

作为 Flink 数据提供商的三个必备条件：

* 数据聚合器
* chainlink 外部适配器
* DATA DAO数据公证人

几个区块链扫描器将首先将数据聚合到一个统一的数据提供者。 然后带有预言机智能合约的chainlink外部适配器会将证明广播到目标区块链网络。 之后，数据公证人将根据链上预言机数据签署交易。 一旦从 Chainlink 预言机中继链上证明，付款即被执行。

### 数据聚合器 <a href="#shu-ju-ju-he-qi" id="shu-ju-ju-he-qi"></a>

当 FIlecoin 代理将数据发送到存储提供商时，数据存储过程即开始。 存储提供商需要接受交易并上传链上交易接受确认，这意味着交易正在进行中，并且将在 Filecoin 网络上生成交易 ID。

数据聚合器将扫描来自不同数据源的 Filecoin 交易信息，并将信息作为 API 接口发送。 检查扫描相关代码的 `数据`目录，典型的交易信息采用以下格式：

> <http://35.168.51.2:7886/deal/5210178?network=filecoin_mainnet>

```
//{

    "status": "success",
    "data": {
        "deal": {
            "deal_id": 5210178,
            "deal_cid": "",
            "message_cid": "bafy2bzaceaotial6pogwzvm7woh5pf37sivrzm3fmp5teao365jl22z5q4pfc",
            "height": 1697382,
            "piece_cid": "baga6ea4seaqjffbc2mmed2piulix5qfppyuhbqumnppme5ngj3q2ol4udijjqbq",
            "verified_deal": true,
            "storage_price_per_epoch": 0,
            "signature": "",
            "signature_type": "",
            "created_at": 1649227860,
            "piece_size": "1073741824",
            "start_height": 1701360,
            "end_height": 3234661,
            "client": "f1g463yb4ok3lq3tffkvvfmfyngcagpx4kg7c7rei",
            "client_collateral_format": "000000000000000000",
            "provider": "f067375",
            "provider_tag": "",
            "verified_provider": 0,
            "provider_collateral_format": "000000000000000000",
            "status": 0,
            "network_name": "filecoin_mainnet",
            "storage_price": 0
        }
    }
}
```

### **Chainlink** 外部适配器 **- DATA DAO**

数据聚合器获取交易信息后，下一步需要外部适配器为数据 DAO 公证人提供 API 访问。

有关如何构建和部署 External Adapter 的详细信息，请查看[adapter](https://github.com/filswan/flink/tree/main/adapter)

### **Data DAO** 公证人

Data DAO 公证人负责签署多重签名钱包，以便将资金解锁给 Filecoin 代理。

DAO 合约允许社区在 DAO 中添加或删除公证人。 DAO 公证人在签名前将遵循以下步骤：

* 通过`proposal_cid`获取`deal_id`
* 从 Chainlink Filecoin 适配器获取 deal\_id
  * 如果匹配触发 DAO 签名
    * 匹配客户端地址
    * 匹配 deal\_cid (proposal\_cid)
  * 否则，等待下一个检查周期


# Multichain.Storage Mumbai测试网用户指南

### 要求 <a href="#yao-qiu" id="yao-qiu"></a>

在进行本指南之前，请完成以下任务以确保您拥有所需要的所有工具

* 完成初学者教程，并设置了[ MetaMask](https://docs.filswan.com/multi-chain-storage/mcp-user-guide/setup-metamask)
* 通过[水龙头](https://calibration-faucet.filswan.com/#/dashboard)领取测试网代币USDC和MATIC

MCS 同时使用 **MATIC** 和 **USDC** 将文件上传到Polygon网络。我们强烈建议您先使用测试网进行测试。

### 操作 <a href="#cao-zuo" id="cao-zuo"></a>

#### 1、使用MetaMask钱包Mumbai Testnet连接网站 <a href="#shi-yong-metamask-qian-bao-mumbaitestnet-lian-jie-wang-zhan" id="shi-yong-metamask-qian-bao-mumbaitestnet-lian-jie-wang-zhan"></a>

前往Multichain.Storage: <https://www.multichain.storage>。点击**连接钱包**按钮连接您的MetaMask钱包，并确保在MetaMask钱包上选择相应的网络。（目前，我们只支持Mumbai Testnet测试网。未来，它将正式上线到Polygon主网中。我们还计划增加其他主要网络，如以太坊，BSC，Fantom等。

![img](https://576435799-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MauK7Ig3eWeXC35bZV7%2Fuploads%2FZ7gKfWydrYh1omEgB1ZD%2F1.png?alt=media\&token=96b713fd-4729-40ae-abb0-50b0a5a133df)

#### 2、上传文件**到IPFS** <a href="#shang-chuan-wen-jian-dao-ipfs" id="shang-chuan-wen-jian-dao-ipfs"></a>

* 点击按钮 **上传文件**
* 选择您要备份到Filecoin网络的文件。文件名和文件大小将显示在上传按钮下方。
* 估计的存储成本将根据文件大小和平均提供商价格计算。
* 根据Sushi Swap换算的实时DeFi汇率，为我们的用户提供了三个锁定资金计划。锁定的资金越多，您的文件就越早存储在Filecoin网络上。當交易上链及合同收集足够的DAO签名后，多付的资金将自动退还给用户。

![img](https://576435799-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MauK7Ig3eWeXC35bZV7%2Fuploads%2F0krng3kY3LTd3YnHwWWq%2F2.png?alt=media\&token=c2fd8921-99e9-4ea5-9679-e565ffc3fb62)

![img](https://576435799-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MauK7Ig3eWeXC35bZV7%2Fuploads%2FAwkCZouggOWxFTUWpPXo%2F3.png?alt=media\&token=ad8e270d-a125-4cf8-b9db-864568f22d3a)

提交请求后，将显示一个上传窗口。上传时间因文件大小而异。请保持窗口打开，直到上传完成。

![img](https://576435799-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MauK7Ig3eWeXC35bZV7%2Fuploads%2FSS4EvKDQXFD5ON3jPEmG%2F4.png?alt=media\&token=3add2c9e-f1b8-4102-9fba-e1b4c316b0be)

#### 3、使用MetaMask锁定资金 <a href="#shi-yong-metamask-suo-ding-zi-jin" id="shi-yong-metamask-suo-ding-zi-jin"></a>

文件成功上传到IPFS后，下一步是使用我们支持的货币将资金锁定到智能合约。目前，它是“USDC”代币。

等待时间取决于区块链拥塞。

![img](https://576435799-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MauK7Ig3eWeXC35bZV7%2Fuploads%2FiaPCacSmbEZBtE6TunJ8%2F5.png?alt=media\&token=42ec5721-eb3d-4bf2-a708-1b9c86625987)

![img](https://576435799-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MauK7Ig3eWeXC35bZV7%2Fuploads%2FEWEqh85hvYOBauo91QJa%2F6.png?alt=media\&token=a434e05a-7e18-4158-99f4-751da9b5d567)

付款完成后，将显示一个带有交易链接的弹出窗口。您可以点击链接或检查您的MetaMask活动，在区块浏览器查看交易信息。

![img](https://576435799-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MauK7Ig3eWeXC35bZV7%2Fuploads%2FGk2SrDDQz8tcHxb8oiiv%2F7.png?alt=media\&token=2a3d9ac9-e325-49b5-bd6d-e299bd57aaee)

> \*\*提示：\*\*如果您改变了主意并想选择另一个资金计划？
>
> 只要您没有在MetaMask上确认付款就不用担心。首先，您需要在MetaMask上拒绝交易。然后，转到“我的文件”页面，您将找到相应文件的PAY按钮。通过点击**付款**按钮，您还可以完成付款。

#### 4、查看您的文件 <a href="#cha-kan-nin-de-wen-jian" id="cha-kan-nin-de-wen-jian"></a>

通过单击上图的“**关闭**”按钮，页面将自动转到\*\*“我的文件”\*\*页面。

在此页面上，您可以找到已上传的所有文件。它为您提供了一些常用信息，例如文件名，状态，数据cid，提供商ID和付款按钮等。

> \*\*提示：\*\*鼠标悬停在提供商ID上时，它会显示区块链的实时交易状态。

> \*\*须知事项：\*\*为了提高效率，MCS 系统正在使用 FilSwan 的 AutoBid 功能。每笔交易将自动分配给您一个最佳的提供商。存储提供商将完成以下备份过程，并将“交易状态”同步到我们的平台。

![img](https://576435799-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MauK7Ig3eWeXC35bZV7%2Fuploads%2F9NnTkQ8rKZY3GZqvlnpT%2F8.png?alt=media\&token=0071378b-d9a8-4bb9-b777-ab1f6d81565e)

> **提示：** 文件列表顶部提供了一个搜索栏。 您可以按部分文件名搜索文件。

要查看更多详细信息，只需单击 **文件名** 。 您可以在此页面上找到所有相关信息，包括 IPFS 下载链接、从 Filecoin Network 检索命令以及 DAO 签名信息和状态。 您无需费心於区块链浏览器上检查交易。

![img](https://576435799-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MauK7Ig3eWeXC35bZV7%2Fuploads%2F1gG8qaCyp5jRmTuy0cA1%2F9.gif?alt=media\&token=32f6b60f-7dc9-4e66-b7ae-068af2536793)

DAO 签名流程：

* 当用户的交易成功发布在区块链上时，DAO 组织将扫描该交易。
* DAO 成员将签署同意解锁用户的资金。
* 当 DAO 收集到指定数量的签名，智能合约将解锁资金。
* 部分锁定的资金将用于支付存储费，剩余的将退还到用户的钱包中。

> **注意：** 将资金锁定到智能合约时会设置到期日期，默认为 6 天。 如果合约到期时存储失败，您只需点击 退款 按钮，锁定的资金将全额退还给用户。

#### 5、NFT <a href="#nft" id="nft"></a>

在 MCS 中，您可以使用上传的文件铸造NFT 。 唯一的要求是您已将文件的资金锁定到智能合约。

铸造 NFT。 您只需点击 **铸造** 将弹出一个窗口，其中包含一些预先生成的信息，例如 IPFS url、文件大小和锁定资金交易哈希。 默认的 NFT 名称将与文件名相同，但您可以随时自定义，并随意填写描述。

通过单击 **铸造 NFT** 按钮，将弹出 MetaMask 窗口以进行授权。 确认此铸造交易将消耗一点gas费。

![img](https://576435799-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MauK7Ig3eWeXC35bZV7%2Fuploads%2FHRywEa8RfOBELXXA2JrL%2F12.gif?alt=media\&token=15532d1b-2acb-4b46-bf9f-d8196efae21c)

![img](https://576435799-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MauK7Ig3eWeXC35bZV7%2Fuploads%2FspZYZLPTs0qLYgmi7p8u%2F14.png?alt=media\&token=b76d0305-88fc-4952-bff0-c0635fa1be04)

铸造过程完成后，将弹出查看您的 NFT 窗口。 提供了交易哈希和在 OpenSea 上查看 NFT 的链接。 您可以单击交易和 OpenSea 链接以查看更多详细信息。

![img](https://576435799-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MauK7Ig3eWeXC35bZV7%2Fuploads%2FjodhSTao2WQAjrGaOQC2%2F12.png?alt=media\&token=0385c5f8-5c2f-49eb-a25e-237ed6c47f71)

#### 6、帐单详情 <a href="#zhang-dan-xiang-qing" id="zhang-dan-xiang-qing"></a>

用户可以在“帐单详情”页面查看所有交易的结算历史。 它涵盖了有关订单的所有信息，例如交易哈希、金额、解锁金额、代币、数据 CID、钱包地址等。

![img](https://576435799-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MauK7Ig3eWeXC35bZV7%2Fuploads%2F0jnYeECz99jA5e3OvNCb%2F10.png?alt=media\&token=5ccc7b5f-2f09-4774-8bc6-45ed5aa6d18b)


# Multichain.Storage Polygon 主网用户指南

## 要求

在开始本指南之前，请完成以下任务以确保您拥有所需的所有工具：

拥有一个有效的MetaMask钱包

如果您使用完10GB的免费存储空间，请持有USDC

## 操作步骤

### 1. 使用以下命令连接到您的MetaMask钱包：

打开multichain.storage网站：[multichain.storage](https://multichain.storage/)，点击“connect wallet”按钮连接您的MetaMask钱包，并确保在MetaMask钱包上选择相应的网络（Polygon Mainnet）。目前，我们支持Polygon网络，并很快支持BNB链，Aptos和SUI Network等。

multichain.storage将文件上传到Polygon网络使用 MATIC 和 USDC 。GAS费用为MATIC，而存储费用为USDC。

<figure><img src="https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FSFOulIB1ril8Svko556b%2FAgAACL0wFGzfH9ejup5MOKFGkcNQQXIX.png?alt=media&amp;token=35ba5fdf-bfc8-4f74-80ea-718cd93998c2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FK5FyKjNa9l1BNDBGChYJ%2F2.png?alt=media&amp;token=1b9b3c13-81b7-48b4-9bf5-982e61a857de" alt=""><figcaption></figcaption></figure>

### 2. 上传文件到IPFS

点击按钮 “Upload More” .

选择要备份到Filecoin网络的文件。文件名和文件大小将显示在上传按钮下方。

系统将根据文件大小、持续时间和平均的存储提供商价格进行计算，估计存储成本。

根据Sushi Swap的实时DeFi汇率，我们为用户提供了三个锁定资金计划。锁定的资金越多，您的文件就越早存储在Filecoin网络上。任何超额支付的资金将在交易上链且合约收集到足够的DAO签名后自动退还给用户。

<figure><img src="https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FRy8hYuuyFu8sGtAThyWf%2F3.png?alt=media&amp;token=c411c1a2-d45c-4f66-8925-076451d5783a" alt=""><figcaption></figcaption></figure>

<figure><img src="https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2Frt9p1IUbNpUUFzSJUX0c%2F4.png?alt=media&amp;token=8e4130ac-8d0a-4c10-b82a-18db04d604c6" alt=""><figcaption></figcaption></figure>

提交请求后，将显示一个上传窗口。上传时间因文件大小而异。请保持窗口打开状态，直到上传完成。

<figure><img src="https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2F8legruwQbfL5lz7lNvpu%2F5.png?alt=media&amp;token=276710a2-4645-46e9-9966-5f969ed24a68" alt=""><figcaption></figcaption></figure>

### 3. 使用MetaMask锁定资金

支付存储和锁定资金仅适用于使用您的免费10GB使用完之后。

文件成功上传到IPFS后，下一步是使用USDC代币将资金锁定到智能合约。

等待时间因区块链拥堵情况而异。

<figure><img src="https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FvdPie1IEEFsPx3KGN2O3%2F6.png?alt=media&amp;token=800e8563-54a8-444c-bbee-75646cb1e0c2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FK1xbreraQ2IO5HPFJhyT%2F9.png?alt=media&amp;token=3c015077-9876-4ae0-a09b-384f434184b7" alt=""><figcaption></figcaption></figure>

<figure><img src="https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FPOwUlh4PpOTyb5LkXBEV%2F7.png?alt=media&amp;token=009e60a7-265c-4bfe-987d-ebfeef4bcdfa" alt=""><figcaption></figcaption></figure>

付款完成后，将显示一个带有交易链接的弹出窗口。您可以单击链接在区块浏览器中查看交易和检查您的MetaMask活动。

**提示：**&#x5982;果您改变了主意另有打算？

只要您没有在MetaMask上确认付款，就不用担心。首先，您需要在MetaMask上拒绝该事务。然后，转到“我的文件”页面，您将找到相应文件的PAY按钮。通过单击“**PAY**”按钮，您仍可以完成付款。

### 4. 查看您的文件

通过单击“**Close**”按钮，它将自动转到“**My Files**”页面。

在此页面上，您可以找到已上传的所有文件。它为您提供了一些常用信息，例如文件名，状态，data CID，Provider ID和付款按钮等。

**提示：**&#x9F20;标悬停在Provider ID上时，它会向您显示区块链的实时交易状态。

**注意事项：**&#x4E3A;了提高效率，multichain.storage系统正在使用FilSwan的Auto Bid功能。合格和最佳存储服务提供商将自动分配到您的交易任务。存储提供商将完成以下备份过程，并将“交易状态”同步到我们的平台。

**提示：**&#x6587;件列表顶部提供了搜索栏。您可以按部分文件名搜索文件。

要查看更多详细信息，只需单击**文件名**即可。您可以在此页面上找到所有相关信息，包括IPFS下载链接，从Filecoin网络命令检索以及DAO签名信息和状态。您无需费心在区块浏览器上检查交易。

{% embed url="<https://www.youtube.com/shorts/Z2zzWh1SFF4?feature=share>" %} <br>
{% endembed %}

**DAO签名流程：**

当用户的交易在区块链上成功发布时，DAO组织将扫描该交易。

然后，DAO成员将签署同意解锁用户的资金。

如果从DAO收集了指定数量的签名，智能合约将解锁资金。

部分锁定的资金将用于支付存储费，其余部分将退还到用户的钱包中。

**注意：**&#x5C06;资金锁定到智能合约时，将设置到期日期，默认值为6天。如果在合同到期时存储失败，您只需点击退款按钮，锁定的资金将全额退还给用户。

### 5. NFT

在 multichain.storage 中，如果您愿意，您将能够使用上传的文件 mint NFT 。唯一的要求是您已经将文件的资金锁定到智能合约。

要mint一个NFT，您只需单击相应文件的**MINT**按钮即可。将弹出一个窗口，其中包含一些预先生成的信息，例如IPFS网址，文件大小和锁定资金交易哈希。默认的NFT名称将与文件名相同，但您可以随时对其进行自定义，并随意填写说明。

通过单击 **Mint NFT** 按钮，将弹出一个MetaMask窗口以进行授权,将消耗一点点GAS费来确认此mint交易。

<figure><img src="https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2F0jmO4Y42ly7Wq568PH5L%2F10.png?alt=media&amp;token=67641d00-e8a6-45d0-aa02-695926db4fed" alt=""><figcaption></figcaption></figure>

Mint过程完成后，将弹出“查看您的NFT”窗口，提供了交易哈希值和在OpenSea上查看您的NFT的链接。您可以点击交易链接和OpenSea链接查看更多详细信息。

### 6. 账单历史

用户可以在“账单历史记录”页面中查看所有交易的账单历史记录。它涵盖了有关订单的所有信息，例如交易哈希，金额，解锁金额，支付的Token，Data CID，钱包地址等。


# 开发人员快速入门

多链存储（以下称为“Multichain.Storage”）是一套以太坊扩展解决方案，可实现高吞吐量、低成本的智能合约，同时保持可信赖的安全性。

以下文档描述了如何使用 Multichain.Storage，它目前在 Polygon Mumbai 测试网上运行。 无论您是只想开始构建的开发人员，还是想深入了解 MCS 的内部结构及其工作原理，此站点都是适合您的地方。

### 系统设计 <a href="#xi-tong-she-ji" id="xi-tong-she-ji"></a>

![](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FoLl8rq5a7vvUQfYNgOTJ%2FWID.png?alt=media\&token=dbcbdda8-88a8-48cb-b763-c319e44b71eb)

### MCS 是如何运行的？ <a href="#mcs-shi-ru-he-yun-hang-de" id="mcs-shi-ru-he-yun-hang-de"></a>

如果您想了解 MCS 的运行原理，最好从 用户指南部分开始，它提供了 MCS 内部结构的概述。 从那里，您可以跳转到有关系统各个组件的更详细的解释。

### 模块 <a href="#mo-kuai" id="mo-kuai"></a>

**代币交换：** 代币交换模块负责将用户的代币换成包裹的代币，可以是USDC或其他代币。

1、用户在上传文件时支付 USDC 或其他代币，这些代币称为用户代币。

2、Multichain.Storage 在将数据存储到 Filecoin 网络时使用 FIL（称为包装代币）进行支付。

3、用户代币应通过此模块更改为包装代币，此步骤称为代币交换。

4、代币交换是通过 DEX 的 Sushi Swap 完成的。

**支付模块：**

1、上传文件后，根据 ：

* 矿工平均价格
* 文件大小
* 持续时间

然后估计的金额将被锁定到付款合同地址，请参阅[配置](https://github.com/filswan/multi-chain-payment#Configuration)。

2、在解锁步骤中，通过Swan平台FIL钱包向Filecoin网络支付的金额，将转入MCS支付接收地址，详见[配置](https://github.com/filswan/multi-chain-payment#Configuration)。

3、在退款步骤中，锁定的超额支付部分将返回到用户钱包。

\*\*Swan Client API：\*\*可以找到更多信息 [这里](https://github.com/filswan/go-swan-client)。

\*\*DAO 签名：\*\*如果 DAO 检测到上传的文件已被链接，则会触发签名操作。

\*\*Data DAO：\*\*更多信息可以在 [Flink](https://github.com/filswan/flink)。

\*\*IPFS：\*\*可以找到更多信息 [这里](https://docs.ipfs.io/)。

\*\*Filecoin存储：\*\*可以找到更多信息 [这里](https://lotus.filecoin.io/docs/set-up/install/)。

### 如何开始构建 <a href="#ru-he-kai-shi-gou-jian" id="ru-he-kai-shi-gou-jian"></a>

#### 先决条件 <a href="#xian-jue-tiao-jian" id="xian-jue-tiao-jian"></a>

* 操作系统： Ubuntu 20.04 LTS
* Mysql5.5+
* Lotus 节点
* IPFS Client

**Lotus 节点**

* Lotus 节点用于制作Car文件和发送离线交易。
* 在与 MCS 相同的机器上安装 Lotus 节点或 Lotus lite 节点。
* Lotus全节点相对于Lotus轻节点来说太重了，所以首选Lotus轻节点。
* Lotus lite 节点依赖于一个 Lotus 节点，所以在使用 Lotus lite 节点时要确保某个地方有一个 Lotus 节点。

**Option1️⃣** [安装Lotus全节点](https://lotus.filecoin.io/docs/set-up/install/)

\*\*选项2️⃣ \*\*[安装Lotus轻节点](https://lotus.filecoin.io/docs/set-up/lotus-lite/#amd-and-intel-based-computers)

#### 安装 <a href="#an-zhuang" id="an-zhuang"></a>

\*\*选项1️⃣ 预构建包：\*\*请参阅[**release assets**](https://github.com/filswan/multi-chain-payment/releases)资产

```shell
wget https://github.com/filswan/multi-chain-payment/releases/tag/v1.0.1/install.sh
./install.sh
```

**选项2️⃣ 源代码**

🔔**go 1.16+** 为必填项

```shell
git clone https://github.com/filswan/multi-chain-payment.git
cd multi-chain-payment
git checkout <release_branch>
./build_from_source.sh
```

#### 安装后 <a href="#an-zhuang-hou" id="an-zhuang-hou"></a>

* 在执行之前，您应该在 `~/.swan/mcp/config.toml` 中检查您的配置，以确保它是正确的。

```shell
vi ~/.swan/mcp/config.toml
```

* 在执行之前，您应该在 `~/.swan/mcp/.env` 中检查您的环境变量，以确保它是正确的。

```shell
vi ~/.swan/mcp/.env
```

* 在相关文件中设置配置和 env 变量后，您可以在 `./build` 目录中运行`多链支付`。

```shell
./build/multi-chain-payment
```

**注意**

* 日志位于目录 `./logs 中`
* 您可以在`./multi-chain-payment`之前添加 `nohup`，以忽略 HUP（挂断）信号，从而避免在注销时停止。
* 你可以加 `>> mcp.log`在命令中让所有日志输出到 `mcp.log`.
* 你可以加 `&`在命令末尾让程序在后台运行。
* 如：

```shell
nohup ./multi-chain-payment-0.2.1-rc1-unix >> mcp.log &   #After installation from Option 1
nohup ./build/multi-chain-payment >> ./build/mcp.log &    #After installation from Option 2
```

### 配置 <a href="#pei-zhi" id="pei-zhi"></a>

您需要修改配置文件并输入您的配置参数，下面将介绍配置项：

\*\*config.toml \*\*

* **port**：Web API 端口。
* **release** ：在发布模式下工作时：将此设置为 true，否则设置为 false 和环境。 变量 GIN\_MODE 不释放。
* **swan\_platform\_fil\_wallet** ：用于在 Filecoin 网络上支付的钱包地址。
* **filink\_url** ：可以从这里搜索交易数据。

\*\*Lotus \*\*

* **client\_api\_url** ：lotus 客户端 web api 的 URL，如： `http://[ip]:[port]/rpc/v0`，一般来说 `[port]`是 `1234`. 请参阅 [Lotus API](https://docs.filecoin.io/reference/lotus-api/#features)
* **client\_access\_token** ：lotus 客户端 web api 的访问令牌。 它应该具有管理员访问权限。 您可以使用命令从您的 Lotus 节点机器获取它 `lotus auth create-token --perm admin`. 请参阅 [Obtaining Tokens](https://docs.filecoin.io/build/lotus/api-tokens/#obtaining-tokens)

**ipfs\_server**

* **download\_url\_prefix** ：IPFS 服务器 url 前缀，如： `http://[ip]:[port]`. 存储Car文件以供存储提供商下载。 Car文件网址将是 `[download_url_prefix]/ipfs/[file_hash]`
* **upload\_url\_prefix** ：上传文件的IPFS服务器url，如 `http://[ip]:[port]`

**swan\_task**

* **dir\_deal** ：用于保存生成的 Car 文件和 CSV 的输出目录。
* **verify\_deal** : \[true/false] 此任务中的交易是否为真实数据。
* **fast\_retrieval** : \[true/false] 表示数据应该可用于快速检索。
* **start\_epoch\_hours** : start\_epoch 从当前时间开始以小时为单位的交易。
* **expired\_days** ：存储提供商密封数据的预期完成天数。
* **max\_price** ：愿意为每个 GiB/epoch 支付离线交易的最高价格。
* **generate\_md5** : \[true/false] 是否为每个Car文件生成MD5，注意：这是一个消耗资源的动作。

**Polygon**

* **rpc\_url** ：您的Polygon网络 RPC URL。
* **payment\_contract\_address** ：Polygon上的Swan支付网关地址以锁定资金。
* **sushi\_dex\_address** : Polygon上的寿司地址。
* **usdc\_wFil\_pool\_contract** ：从Polygon上的寿司获取 USDC 和 wFil 之间汇率的地址。
* **dao\_contract\_address** ：Polygon上的Swan DAO 地址，用于接收 DAO 签名。
* **mcp\_payment\_receiver\_address** ：MCS 钱包地址，用于从解锁操作中接收资金。
* **gas\_limit** ：交易的Gas限制。
* **unlock\_interval\_minute** : 2 次解锁操作之间的解锁间隔（分钟），不能小于 1。

\*\*.env \*\*

* **privateKeyOnPolygon** ：钱包的私钥，用于在Polygon网络上执行合约方法并支付 gas。

### &#x20;<a href="#setup-local-geth-and-rollup-blockchain" id="setup-local-geth-and-rollup-blockchain"></a>

### &#x20;<a href="#hello-arbitrum" id="hello-arbitrum"></a>


# SDK

## 介绍 <a href="#jie-shao-2" id="jie-shao-2"></a>

Multichain.Storage SDK 是 Swan Multichain.Storage 开发人员的开发工具包，为使用 MCS API 提供了一个方便的接口。

* **零成本，免费使用**
* **通过钱包访问（Metamask）**
* **无缝集成，易于实施**

#### 当前支持的语言 <a href="#dang-qian-zhi-chi-de-yu-yan" id="dang-qian-zhi-chi-de-yu-yan"></a>

* Javascript


# js-mcs-sdk

https\://github.com/filswan/js-mcs-sdk

js-mcs-sdk 是一个用于 MCS 服务的 javascript 软件开发工具包。 它为从 Web 浏览器或 Node.js 使用 MCS API 提供了一个方便的界面。

SDK 具有以下功能：

* POST 上传文件到 FilSwan IPFS 网关
* POST 支付给 Swan Filecoin 存储网关
* 铸造为 NFT
* 获取上传的文件列表
* 按 CID 获取文件
* 从 Filecoin 获取存储状态

{% embed url="<https://github.com/filswan/js-mcs-sdk>" %}

#### 赞助商 <a href="#zan-zhu-shang" id="zan-zhu-shang"></a>

该项目由 Filecoin 基金会赞助

[Flink SDK - A data provider offers Chainlink Oracle service for Filecoin Network](https://github.com/filecoin-project/devgrants/issues/463)

[![](https://github.com/filswan/flink/raw/main/filecoin.png)](https://github.com/filswan/flink/blob/main/filecoin.png)


# 开始

本指南将解释如何安装 js-mcs-sdk 及其基本用法

#### 先决条件 <a href="#xian-jue-tiao-jian-1" id="xian-jue-tiao-jian-1"></a>

* Node.js - 此 SDK 使用版本 v16.13.0 (npm v8.1.0) 构建
* Polygon Mumbai Testnet 钱包 - [Metamask Tutorial](https://docs.filswan.com/multi-chain-storage/mcp-user-guide/setup-metamask)
* Polygon Mumbai Testnet Alchemy RPC - [Alchemy Tutorial](https://docs.filswan.com/multi-chain-storage/mcp-user-guide/configure-metamask-with-alchemy-rpc-url#alchemypolygontometamaskinstructions-2.createalchemymumbaipolygonrpc)
* Mumbai Testnet USDC和 MATIC 也是必需的-[Swan Faucet Tutorial](https://docs.filswan.com/development-resource/swan-token-contract/acquire-testnet-usdc-and-matic-tokens)

#### 安装 <a href="#an-zhuang-1" id="an-zhuang-1"></a>

使用 npm 安装包。建议为新项目创建新目录。

```shell
npm init -y
npm install js-mcs-sdk
```

#### 环境变量 <a href="#huan-jing-bian-liang" id="huan-jing-bian-liang"></a>

获得Mumbai 测试网钱包和 RPC URL 后，创建一个名为 `.env`并存储你钱包的私钥和 RPC URL。

```shell
PRIVATE_KEY=<PRIVATE_KEY>
RPC_URL=https://polygon-mumbai.g.alchemy.com/v2/<API_KEY>
```

{% hint style="info" %}
小心不要泄露这些信息

向他人透露您的私钥将使他们能够访问您的钱包
{% endhint %}

**编写SDK脚本**

要开始使用 SDK 编写脚本前, 需创建一个新的`.js` 文件。让我们创建一个名为 `demo.js`文件。

此文件的上方需放置脚本所需的套件。

```
// demo.js
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')
```

* `require('donenv').config()` 将加变量在你的 `.env` 文件中以执行`process.env`
* `const { mcsSDK } = require('js-mcs-sdk')` 将引入 SDK

接下来，在引入SDK完成后，需要执行初始化

```
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')

// set up js-mcs-sdk
const mcs = new mcsSDK({
  privateKey: process.env.PRIVATE_KEY,
  rpcUrl: process.env.RPC_URL,
})
```

现在我们可以开始使用SDK工具，由于这个函数是[异步的](https://javascript.info/async-await)，我们需要创建一个`async` 函数来跑SDK工具。

```
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')

// set up js-mcs-sdk
const mcs = new mcsSDK({
  privateKey: process.env.PRIVATE_KEY,
  rpcUrl: process.env.RPC_URL,
})

async function main() {
  // code snippets found in the documentation go here
}

main()
```

{% hint style="info" %}
这是SDK文档中所有片段的样板代码。
{% endhint %}

#### 上传文件示例 <a href="#shang-chuan-wen-jian-shi-li" id="shang-chuan-wen-jian-shi-li"></a>

这是一个将单个文件上传到 MCS 的简单示例。 新建了一个文件名为 `upload.js`

```shell
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')

// set up js-mcs-sdk
const mcs = new mcsSDK({
  privateKey: process.env.PRIVATE_KEY,
  rpcUrl: process.env.RPC_URL,
})

async function main() {
  const testFile = JSON.stringify({ address: mcs.publicKey })
  const fileArray = [{ fileName: `${mcs.publicKey}.txt`, file: testFile }]

  const uploadResponse = await mcs.upload(fileArray)
  console.log(uploadResponse)
}

main()
```

使用命令 `node upload.js`运行代码。 此代码段创建 MCS SDK 实例，使用您的钱包地址创建 JSON 文件，并将文件上传到 MCS。


# 上传文件

使用 MCS SDK 将文件上传到 MCS

```shell
upload(fileArray, options)
```

您可以使用上传功能将文件数组上传到 FilSwan IPFS 网关。该数组保存对象列表，并返回响应对象数组。使用 `fs` 是读取文件数据的简单方法。选项对象也是自定义上载的可选对象。

```
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')
const fs = require('fs') // used to read files

// set up js-mcs-sdk
const mcs = new mcsSDK({
  privateKey: process.env.PRIVATE_KEY,
  rpcUrl: process.env.RPC_URL,
})

async function main() {
  // ENTER PARAMETERS
  const PATH_1 = ''
  const PATH_2 = ''
  
  const fileArray = [
    { fileName: 'file1', file: fs.createReadStream(PATH_1) },
    { fileName: 'file2', file: fs.createReadStream(PATH_2) },
  ]
  
  //optional, showing default options
  const options = {
    delay: 1000, // delay between upload API calls for each file. May need to be raised for larger files
    duration: 525, // the number of days to store the file on the Filecoin network.
    fileType: 0, // set to 1 for nft metadata files. type 1 files will not show on the UI.
  }
  
  const uploadResponses = await mcs.upload(fileArray, options)
  console.log(uploadResponses)
}

main()
```

#### 参数 <a href="#can-shu" id="can-shu"></a>

* **fileArray**： 对象数组
  * **fileName**：文件名
  * **file**：文件内容（使用`fs`是获取文件内容的简单方法）
* **options**：还可以传递可选对象以指定某些参数：
  * **delay**：上传 API 调用之间的延迟（以毫秒为单位）。默认值为 1000，但对于许多较大的文件，可能需要增加
  * **duration**：在Filecoin网络上存储文件的天数。（默认值 525）
  * **fileType**：类型为一的文件将从上传列表和 UI 中隐藏。NFT 元数据文件的类型为 1。（默认值 0）

#### 返回 <a href="#fan-hui" id="fan-hui"></a>

此函数返回上载 API 响应的数组。

```
[
  {
    status: 'success',
    data: {
      source_file_upload_id: <ID>,
      payload_cid: <'Qm...'>,
      ipfs_url: <'https://calibration-ipfs.filswan.com/ipfs/Qm...'>,
      file_size: <FILE_SIZE>,
      w_cid: <UNIQUE_CID>
    }
  }, ...
]
```


# 支付数据存储费用

在 MCS 上支付存储费用

```shell
makePayment(wCid, minAmount, fileSize)
```

上传文件后，文件可以按其有效负载 cid 付费。该方法将有效负载 cid 作为第一个参数，将最小数量作为第二个参数。

```shell
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')

// set up js-mcs-sdk
const mcs = new mcsSDK({
  privateKey: process.env.PRIVATE_KEY,
  rpcUrl: process.env.RPC_URL,
})

async function main() {
  // ENTER PARAMETERS
  const W_CID = ''
  const MIN_AMOUNT = '1'
  const FILE_SIZE = ''
   
  const tx = await mcs.makePayment(W_CID, MIN_AMOUNT, FILE_SIZE)
  console.log(tx.transactionHash)
}

main()
```

#### 参数 <a href="#can-shu-1" id="can-shu-1"></a>

* **wCid**：文件的唯一有效负载
* **minAmount**：为文件支付的最低金额。用于避免大数字精度错误的字符串值
* **fileSize**：文件的大小

#### 返回 <a href="#fan-hui-1" id="fan-hui-1"></a>

返回 web3.js接收对象。在上面的示例中，仅打印来自此对象的事务哈希。

<br>


# Mint NFTs资产

Mint NFT 到 MCS Opensea Collection

Mint NFT 到 MCS Opensea Collection

```
mintAsset(sourceFileUploadId, nftObject)
```

下面的代码示例将上传的文件铸造为在 Opensea 上可查看的 NFT。创建一个 NFT 对象并提供该文件的payload\_cid。NFT 对象遵循[OpenSea元数据标准](https://docs.opensea.io/docs/metadata-standards)。

```
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')

// set up js-mcs-sdk
const mcs = new mcsSDK({
  privateKey: process.env.PRIVATE_KEY,
  rpcUrl: process.env.RPC_URL,
})

async function main() {
  // ENTER PARAMETERS
  const SOURCE_FILE_UPLOAD_ID = 0
  const IPFS_URL = ''
  const NFT_NAME = ''

  const NFT_DESCRIPTION = '' // optional

  const nft = {
    name: NFT_NAME, // the name of your NFT
    image: IPFS_URL, // asset URI, images will render on Opensea
    external_url: IPFS_URL, // Opensea will provide a link to view the source
    description: NFT_DESCRIPTION, // description of your NFT
    attributes: [], // NFT attributes displayed on Opensea
  }

  const mintTx = await mcs.mintAsset(SOURCE_FILE_UPLOAD_ID, nft)
  console.log(mintTx)
}

main()
```

{% embed url="<https://github.com/filswan/nft>" %}

#### Parameters <a href="#parameters" id="parameters"></a>

**sourceFileUploadId**：上传文件的 ID

**nftObject**：遵循 Opensea Metadata Standards 的对象

* **name**：您的 NFT 的名称（必填）
* **image**：文件的 IPFS URL（必填）
* **description**： 您的 NFT 的描述
* **attributes**：您希望在 Opensea 上显示的属性对象数组

#### 返回 <a href="#fan-hui-2" id="fan-hui-2"></a>

返回来自 `/mint/info` API 的响应

```
{
  status: 'success',
  data: {
    id: <ID>,
    source_file_upload_id: <ID>,
    nft_tx_hash: <'0x...'>,
    mint_address: '0x1A1e5AC88C493e0608C84c60b7bb5f04D9cF50B3',
    token_id: '<ID>',
    create_at: <TIME>,
    update_at: <TIME>
  }
}
```


# 列出文件

查看您上传的文件

```
getUploads(walletAddress, payloadCid, fileName, orderBy, isAscend, status, isMinted, pageNumber, pageSize)
```

下面的代码示例列出用户上载的文件。该列表可以按文件名搜索，也可以进行筛选或排序。

```
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')
const fs = require('fs') // used to read files

// set up js-mcs-sdk
const mcs = new mcsSDK({
  privateKey: process.env.PRIVATE_KEY,
  rpcUrl: process.env.RPC_URL,
})

async function main() {
  // ENTER PARAMETERS
  const FILE_NAME = ''
  const ORDER_BY = ''
  const IS_ASCEND = ''
  const STATUS = ''
  const IS_MINTED = ''
  const PAGE_NUMBER = 1
  const PAGE_SIZE = 10
  
  const uploads = await mcs.getUploads(
    mcs.publicKey,
    FILE_NAME,
    ORDER_BY,
    IS_ASCEND,
    STATUS,
    IS_MINTED,
    PAGE_NUMBER,
    PAGE_SIZE,
  )
  
  console.log(uploads.data.source_file_upload)
}

main()
```

#### 参数 <a href="#can-shu-2" id="can-shu-2"></a>

**walletAddress**：列出此帐户上传的文件（必填）

**fileName**：按此文件名筛选

**orderBy**：按文件名、文件大小或上传时间（默认）对列表进行排序

**isAscend**：y 表示升序列表，否则为降序（默认）

**status**： 待处理， 正在处理， 可退款， 已退款， 成功或其他

**isMinted**： y， n， all （默认）

**pageNumber**：页码（默认为 1）

**pageSize**：页面中的结果数（默认为 10）

只有钱包地址参数是必需的，其余的是可选的。

#### 返回 <a href="#fan-hui-3" id="fan-hui-3"></a>

返回一个数组，其中包含文件的一些详细信息。

```
[
  {
    source_file_upload_id: <ID>,
    car_file_id: <ID>,
    file_name: <FILE_NAME>,
    file_size: <FILE_SIZE>,
    upload_at: <TIME>,
    duration: 525,
    ipfs_url: <'https://calibration-ipfs.filswan.com/ipfs/Qm...'>,
    pin_status: 'Pinned',
    payload_cid: <'bafy...'>,
    w_cid: <UNIQUE_CID>,
    status: 'Processing',
    deal_success: <BOOLEAN>,
    is_minted: <BOOLEAN>,
    token_id: <ID>,
    mint_address: '0x1A1e5AC88C493e0608C84c60b7bb5f04D9cF50B3',
    nft_tx_hash: <'0x...'>,
    offline_deal: [ [Object], [Object], [Object], [Object], [Object] ]
  }, ...
]
```


# 获取文件详细信息

获取有关特定文件的详细信息

```
getFileDetails(sourceFileUploadId, dealId)
```

下面的代码示例获取上载的文件的文件详细信息。此方法获取文件的上传 ID 和文件的交易 ID。交易 ID 可以通过 getUploads 方法获取

```
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')
const fs = require('fs') // used to read files

// set up js-mcs-sdk
const mcs = new mcsSDK({
  privateKey: process.env.PRIVATE_KEY,
  rpcUrl: process.env.RPC_URL,
})

async function main() {
  // ENTER PARAMETERS
  const SOURCE_FILE_UPLOAD_ID = ''
  const DEAL_ID = ''
   
  console.log(await mcs.getFileDetails(SOURCE_FILE_UPLOAD_ID, DEAL_ID))
}

main()
```

* **sourceFileUploadId**：文件的上传 ID
* **dealId**： 文件的 deal id

#### 返回 <a href="#fan-hui-4" id="fan-hui-4"></a>

返回来自 `/deal/detail/` API 的响应

```
{
  status: 'success',
  data: {
    dao_signature: [ [Object], [Object], [Object], [Object] ],
    dao_threshold: 2,
    source_file_upload_deal: {
      deal_id: <ID>,
      deal_cid: '',
      message_cid: <'bafy...'>,
      height: <NUMBER>,
      piece_cid: <'...'>,
      verified_deal: <BOOLEAN>,
      storage_price_per_epoch: 0,
      signature: '',
      signature_type: '',
      created_at: <TIME>,
      piece_size_format: null,
      start_height: <NUMBER>,
      end_height: <NUMBER>,
      client: <'f...'>,
      client_collateral_format: '000000000000000000',
      provider: <'f...'>,
      provider_tag: '',
      verified_provider: 0,
      provider_collateral_format: '000000000000000000',
      status: 0,
      network_name: 'filecoin_mainnet',
      storage_price: 0,
      ipfs_url: <'https://calibration-ipfs.filswan.com/ipfs/Qm...'>,
      file_name: <FILE_NAME>,
      w_cid: <UNIQUE_CID>,
      car_file_payload_cid: <'bafy...'>,
      locked_at: <TIME>,
      locked_fee: <AMOUNT>,
      unlocked: <BOOLEAN>
    }
  }
}
```


# 获取文件的Filecoin状态

获取文件的Filecoin存储状态

```
getFileStatus(dealId)
```

下面的代码示例返回付费文件的 FIlecoin 存储状态。此方法需要交易的成交 ID。这也可以通过 getUploads 方法获得。

```
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')
const fs = require('fs') // used to read files

// set up js-mcs-sdk
const mcs = new mcsSDK({
  privateKey: process.env.PRIVATE_KEY,
  rpcUrl: process.env.RPC_URL,
})

async function main() {
  // ENTER PARAMETERS
  const DEAL_ID = 0
  
  const mintResponse = await mcs.getFileStatus(DEAL_ID)
  console.log(mintResponse)
}

main()
```

#### 参数 <a href="#can-shu-4" id="can-shu-4"></a>

* **dealId**： 文件的 deal id

#### 返回 <a href="#fan-hui-5" id="fan-hui-5"></a>

返回来自 `/deal/log/` API 的响应

```
{
  status: 'success',
  data: {
    offline_deal_log: [ [Object], [Object], [Object], [Object], [Object], [Object] ]
  }
}
```


# 其他资源

#### Github 和 NPM <a href="#github-he-npm" id="github-he-npm"></a>

{% embed url="<https://github.com/filswan/js-mcs-sdk/tree/multiminer>" %}

{% embed url="<https://www.npmjs.com/package/js-mcs-sdk>" %}

### 什么是Filecoin?

<https://docs.filecoin.io/about-filecoin/what-is-filecoin/>

### 什么是**NFT?** <a href="#sdkusercase-whatisannft" id="sdkusercase-whatisannft"></a>

<https://support.opensea.io/hc/en-us/articles/360063450733-What-is-a-Non-Fungible-Token-NFT-><br>


# 概览

## Introduction

Web3 service providers provide service for different blockchains including but not limited to Filecoin, AR, Polygon RPC service. With FilSwan service provide, we connected to web3 service market to make the web3 service offering ultimated easier.

Typical Web3 markets are:

* [Filecoin Deal Market](#filecoin-deal-market)
* [Pocket Network RPC market](#pocket-network)
* Ocean Protocol Data market

#### **Filecoin Deal Market**

[*Filecoin*](https://filecoin.io/) is making the web more secure and efficient with a decentralized data storage marketplace, protocol, and cryptocurrency.

[Filecoin Storage Market ](https://spec.filecoin.io/systems/filecoin_markets/storage_market/)subsystem is the data entry point into the network. Storage miners only earn power from data stored in a storage deal and all deals live on the Filecoin network. A deal is only valid when it is posted on chain with signatures from both parties and at the time of posting, there are sufficient balances for both parties locked up to honor the deal in terms of deal price and deal collateral.

Swan Provider runs on the same node as lotus miner nodes running and assistant lotus miner process deals. It makes it easy for miners to manage tasks, import deals, and synchronize deals with the Swan platform.

In order better share the information with the Flilswan client, authentication from the Filswan platform is required.

![Swan Provider Business Flow](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FtiPiQuhsGHx1sYBjlmUQ%2Fimage.png?alt=media\&token=579d86e8-b9be-48f4-a452-0347f2b18a35)

![Swan Provider System Architect](https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2F6ZOtcJ6za60WKi1ZZq6z%2Fimage.png?alt=media\&token=2e82cae4-4a1a-4dce-b5c5-65baf11fe24b)

#### Pocket Network(Coming Soon)

[*Pocket*](https://www.pokt.network/) provides RPC access to Ethereum, Polygon, and a dozen more blockchain *networks*. Everything from testnets to mainnets to any open-source interface.

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


# 功能

Swan Provider监听来自Swan平台的离线交易。提供以下功能：

* 使用aria2作为下载服务自动下载离线交易。
* 下载完成后使用lotus导入交易。
* 同步交易状态到 [Swan Platform](https://www.filswan.com/)，让客户端和矿工了解状态的实时变化。
* 来自FilSwan竞价市场的自动或手动竞价任务。


# 使用指南

{% content-ref url="/pages/DGRG3HI9IXey8ATtO1Qu" %}
[前提条件](/swan-provider/shi-yong-zhi-nan/qian-ti-tiao-jian)
{% endcontent-ref %}

{% content-ref url="/pages/qFR2jf5ueyQLs0xMnGc7" %}
[安装](/swan-provider/shi-yong-zhi-nan/an-zhuang)
{% endcontent-ref %}

{% content-ref url="/pages/WjNVPSHtOYPZq4vjLMAr" %}
[配置并运行](/swan-provider/shi-yong-zhi-nan/pei-zhi-bing-yun-xing)
{% endcontent-ref %}

{% content-ref url="/pages/9unr0HqxR9aBomcSgmWk" %}
[Swan Provider 视频教程](/swan-provider/shi-yong-zhi-nan/video-tutorial)
{% endcontent-ref %}


# 前提条件

* Aria2 服务

**启动 Lotus-miner**

在启动 `swan-provider`之前，请确保 `Lotus-miner` 正常运行。您需要使用 `Lotus-miner` 令牌导入订单。

```
lotus-miner auth create-token --perm write
```

注意，请保持 `Lotus-miner` 在后台运行! 生成的令牌位于 `$LOTUS_MINER_PATH/token` 请参考：[Lotus: API tokens](https://lotus.filecoin.io/reference/basics/api-access/)

**Aria2 服务**

```
sudo apt install aria2
```


# 安装

您可以通过环境变量设置 `$SWAN_PATH`，默认 `~/.swan`：

```
export SWAN_PATH="/data/.swan"
```

#### 选项1️⃣ **预构建包**: 参照 [release assets](https://github.com/filswan/go-swan-provider/releases)

**构建指南**

```
wget --no-check-certificate https://raw.githubusercontent.com/filswan/go-swan-provider/release-2.1.0-rc1/install.sh
chmod +x ./install.sh
./install.sh
```

**配置和运行**

* 编辑配置文件 **\~/.swan/provider/config.toml**, 参考 [此处](/swan-provider/shi-yong-zhi-nan/pei-zhi-bing-yun-xing)
* 在后台运行 `swan-provider`

```
ulimit -SHn 1048576
export SWAN_PATH="/data/.swan"
nohup swan-provider-2.1.0-rc1-linux-amd64 daemon >> swan-provider.log 2>&1 & 
```

#### 选项2️⃣ 从源代码构建

构建 `swan-provider` 需要安装以下依赖包:

```
curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -
```

```
sudo apt-get install -y nodejs
```

```
sudo apt install mesa-opencl-icd ocl-icd-opencl-dev gcc git bzr jq pkg-config curl clang build-essential hwloc libhwloc-dev wget -y && sudo apt upgrade -y
```

* Go(需要 **1.18.1+**)

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

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

* Rustup

```
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
```

**构建指南**

```
git clone https://github.com/filswan/go-swan-provider.git
cd go-swan-provider
git checkout release-2.1.0-rc1
./build_from_source.sh
```


# 配置并运行

您需要根据不同的 `market_version` 进行配置。

```
port = 8888
release = true                               	# 在 release 模式下运行时: 设置为 true, 否则设置为 false and 环境变量 GIN_MODE not to release

[lotus]
client_api_url = "http://[ip]:[port]/rpc/v0"    # lotus 客户端 web API 的 Url, 通常 [port] 为 1234
client_api_token = ""                           # lotus 客户端 web API 的 token (lotus auth api-info --perm=admin)
market_api_url = "http://[ip]:[port]/rpc/v0"   	# lotus market web API 的 Url，通常 [port] 为 2345，当 market 和 miner 没有分离的时候, 它也是 miner web API 的 URL
market_access_token = ""                        # lotus market web API 的 token，当 market 和 miner 没有分离的时候, 它也是 miner web API 的 token

[aria2]
aria2_download_dir = "%%ARIA2_DOWNLOAD_DIR%%"   # 离线订单文件的下载目录
aria2_candidate_dirs = ["/tmp"]                 # 离线订单所需 CAR 文件的查询目录
aria2_host = "127.0.0.1"                        # Aria2 服务地址
aria2_port = 6800                               # Aria2 服务端口
aria2_secret = "my_aria2_secret"                # 必须与 aria2.conf 中的 RPC-secure 为同一个值
aria2_auto_delete_car_file= false               # 当订单状态变为 Active 或 Error 时，CAR文件将被自动删除
aria2_max_downloading_tasks = 10                # Aria2 最大并行下载数 默认：10

[main]
market_version = "1.1"                          # 订单版本为 1.1 或 1.2, 配置(market_version=1.1) 将被弃用，很快会被删除 (默认: "1.1")，如果设置为 1.2，需要设置 [market] 部分
api_url = "https://go-swan-server.filswan.com"  # Swan API 地址。生产环境地址为 "https://go-swan-server.filswan.com"
api_key = ""                                    # api 密钥。从 Filswan -> "My Profile"->"Developer Settings"获得
access_token = ""                               # Token，从 Filswan -> "My Profile"->"Developer Settings"获得
miner_fid = "f0xxxx"                            # Filecoin MinerID, 此 ID 必须被添加到 Swan Storage providers 列表，添加方式：Swan Platform -> "My Profile" -> "As Storage Provider" -> "Manage" -> "Add"
import_interval = 600                           # 600 秒或 10 分钟。导入每个订单的时间间隔
scan_interval = 600                             # 600 秒或 10 分钟。扫描所有进行中的订单并在 Swan Platform 上更新状态的时间间隔
api_heartbeat_interval = 300                    # 300 秒或 5 分钟。发送心跳的时间间隔。

[bid]
bid_mode = 1									# 0: 手动, 1: 自动
expected_sealing_time = 1920					# 1920 epoch 或 16 小时。 订单的预期封装时长。过早开始将会被拒绝。
start_epoch = 2880            					# 2880 epoch 或 24 小时。 当前 epoch 的相对值
auto_bid_deal_per_day = 600   				    # 上面配置的 miner_fid 每日可接受自动竞价订单的最大数量

[market]
collateral_wallet = ""                          # 质押订单用到的钱包
publish_wallet = ""                             # 发送 PublishStorageDeals 消息的钱包地址
```

**(1) `market_version = "1.1"` 时**，存储提供商会使用 lotus 内置的 Market 导入订单。因此，无需设置 `[market]` 部分。

**(2) `market_version = "1.2"` 时**, 存储提供商会使用 `Boost` 中的 Market 导入订单, 因此须确保存储提供商状态是可接入的。具体的配置步骤如下：

* &#x20;在 miner 配置中禁用 market 子系统：

```
vi $LOTUS_MINER_PATH/config.toml
```

```
[Subsystems] 
 EnableMarkets = false
```

* 配置 `$SWAN_PATH/provider/config.toml` 中的 `[market]` 部分
* 初始化 Market repo 到 `$SWAN_PATH/provider/boost`：

```
export SWAN_PATH="/data/.swan"
swan-provider daemon 
```

* 配置 `[Libp2p]` 部分

  (1) 确保 `swan-provider` 和 `boostd` 没有运行

  ```
   kill -9 $(ps -ef | grep -E 'swan-provider|boostd' | grep -v grep | awk '{print$2}' )
  ```

  (2) 编辑 boost 的配置文件`$SWAN_PATH/provider/boost/config.toml`：

  ```
   [Libp2p]
     ListenAddresses = ["/ip4/0.0.0.0/tcp/24001", "/ip6/::/tcp/24001"]   # Binding address for the libp2p host
     AnnounceAddresses = ["/ip4/209.94.92.3/tcp/24001"]                  # Addresses to explicitly announce to other peers. If not specified, all interface addresses are announced
  ```

  (3) 在后台运行 `swan-provider`

  ```
   ulimit -SHn 1048576
   export SWAN_PATH="/data/.swan"
   nohup swan-provider daemon >> swan-provider.log 2>&1 & 
  ```
* 发布存储提供商的 Multiaddrs 和 PeerID:

  * 获取方式： `boostd --boost-repo=$SWAN_PATH/provider/boost net listen`

  ```
  lotus-miner actor set-addrs /ip4/<ip>/tcp/<port>   
  ```

  * 获取方式： `boostd --boost-repo=$SWAN_PATH/provider/boost net id`

  ```
  lotus-miner actor set-peer-id <PeerID> 
  ```
* 设置接单条件

```
export SWAN_PATH="/data/.swan"
swan-provider set-ask --price=0 --verified-price=0 --min-piece-size=256 --max-piece-size=34359738368
```

* 设置 `[market].publish_wallet` 为控制地址：

```
export OLD_CONTROL_ADDRESS=`lotus-miner actor control list  --verbose | awk '{print $3}' | grep -v key | tr -s '\n'  ' '`
```

```
lotus-miner actor control set --really-do-it $[market].publish_wallet $OLD_CONTROL_ADDRESS
```

* 给 `collateral_wallet` Market Actor 充值

```
lotus wallet market add --from=<YOUR_WALLET> --address=<collateral_wallet> <amount>
```

> **注意:**
>
> * 日志位于 `./logs` 目录下

### 与 Swan Provider 交互

`swan-provider` 命令让您可以与运行中的 Swan Provider 进行交互。 检查您当前使用的 swan-provider 版本

```
swan-provider version
```


# Swan Provider 视频教程

{% hint style="info" %}
观看视频前请确保您已满足安装配置Swan Provider的[前提](https://app.gitbook.com/o/-Ma7_tf6L8A170GHT9fr/s/ge3NMJs0WFB5ALcsdmfX/~/changes/GhYG3nqG03gpAMPiUTOe/swan-provider/kai-shi-shi-yong/qian-ti)。
{% endhint %}

{% hint style="info" %}
获取更多信息，请访问 [go-swan-provider github](https://github.com/filswan/go-swan-provider/tree/release-0.2.1) 。
{% endhint %}

{% embed url="<https://www.youtube.com/watch?v=MkwbKtMJ4qw>" %}


# 常见问题

{% content-ref url="/pages/ixY2xBaCdKX2oGwoKV45" %}
[1. Storage Provider 绑定新账号](/swan-provider/chang-jian-wen-ti/1.-storage-provider-bang-ding-xin-zhang-hao)
{% endcontent-ref %}

{% content-ref url="/pages/pswmU7jEOiRu8nlKs2qO" %}
[2. 如何检查您的 Storage Provider 连通性/稳定性](/swan-provider/chang-jian-wen-ti/2.-ru-he-jian-cha-nin-de-storage-provider-lian-tong-xing-wen-ding-xing)
{% endcontent-ref %}

{% content-ref url="/pages/Sd77bRJNFXOy1xVB2ZgT" %}
[3. 如何暂停接受自动竞价订单](/swan-provider/chang-jian-wen-ti/3.-ru-he-zan-ting-jie-shou-zi-dong-jing-jia-ding-dan)
{% endcontent-ref %}

{% content-ref url="/pages/JzLNVrN9nUay7hDoW94k" %}
[4. aria2\_download\_dir 和aria2\_candidate\_dirs 的区别](/swan-provider/chang-jian-wen-ti/4.-aria2downloaddir-he-aria2candidatedirs-de-qu-bie)
{% endcontent-ref %}

{% content-ref url="/pages/NWcysGtx5Bkouhe07bK4" %}
[5. Boostd 正常运行情况下如何配置从 Swan Provider 接收订单](/swan-provider/chang-jian-wen-ti/5.-boostd-zheng-chang-yun-hang-qing-kuang-xia-ru-he-pei-zhi-cong-swan-provider-jie-shou-ding-dan)
{% endcontent-ref %}

{% content-ref url="/pages/KMBJn8xkDQJzoCdPIs25" %}
[6. 接单过程中总出现拒绝信息](/swan-provider/chang-jian-wen-ti/6.-jie-dan-guo-cheng-zhong-zong-chu-xian-ju-jue-xin-xi)
{% endcontent-ref %}

{% content-ref url="/pages/XNCWZIkVf9vYAIt8Sn6A" %}
[7. 如何检查 aria2 是否在运行？](/swan-provider/chang-jian-wen-ti/7.-ru-he-jian-cha-aria2-shi-fou-zai-yun-xing)
{% endcontent-ref %}

{% content-ref url="/pages/cq0Uf2gkzIxaqqXtB9A4" %}
[8. Swan Platform 无响应](/swan-provider/chang-jian-wen-ti/8.-swan-platform-wu-xiang-ying)
{% endcontent-ref %}

{% content-ref url="/pages/vVypwRXL2oe4hdCLFcji" %}
[9. Storage Provider 状态显示“Offline/离线”](/swan-provider/chang-jian-wen-ti/9.-storage-provider-zhuang-tai-xian-shi-offline-li-xian)
{% endcontent-ref %}

{% content-ref url="/pages/w3vo0Pj08eZ0wp628kn5" %}
[10. 如何检查任务状态](/swan-provider/chang-jian-wen-ti/10.-ru-he-jian-cha-ren-wu-zhuang-tai)
{% endcontent-ref %}

{% content-ref url="/pages/Gv8Xt69JZkoqexB7Af8u" %}
[11. 如何配置 Storage Provider Market](/swan-provider/chang-jian-wen-ti/11.-ru-he-pei-zhi-storage-provider-market)
{% endcontent-ref %}

{% content-ref url="/pages/lGBANRKWA4duSEBoNALh" %}
[12. 如何设置接单条件](/swan-provider/chang-jian-wen-ti/12.-ru-he-she-zhi-jie-dan-tiao-jian)
{% endcontent-ref %}


# 1. Storage Provider 绑定新账号

一个存储提供商只能绑定一个账号，如需换绑，请发送邮件到 <contact@fogmeta.com>，我们需要对您进行身份验证。

**邮件主题：**&#x53;torage Provider 账号换绑

**邮件内容：**

1）简述您当前遇到的情况&#x20;

2）提供您的 Storage Provider ID

如遇任何问题，请在 [FilSwan Discord](https://filswan.com/discord) 频道联系我们。


# 2. 如何检查您的 Storage Provider 连通性/稳定性

1. 打开[此链接](< https://console.filswan.com/#/tools/checkDataCap>)；
2. 在 “Check Storage Provider Connectivity/查看存储提供商的连通性” 一栏输入您的存储提供商 ID，点击“Check/检查”；

<figure><img src="https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FfmbwKvo1D6kFwStAEZbd%2Fimage.png?alt=media&amp;token=3b491bca-3fcb-4d75-ab50-51c1050fe0ba" alt=""><figcaption></figcaption></figure>

结果返回的速度快慢反映了您的Storage Provider稳定与否。

如遇任何问题，请在 [FilSwan Discord](https://filswan.com/discord) 频道联系我们。


# 3. 如何暂停接受自动竞价订单

如果您不想接单，可以设置配置文件 `config.toml` 中 `[bid].bid_mode = 0`，配置完成需要重新启动 Swan Provider。另外，可以修改配置 `[bid].auto_bid_deal_per_day = 100` 来设置允许每天接收的订单数量。

如遇任何问题，请在 [FilSwan Discord](https://filswan.com/discord) 频道联系我们。


# 4. aria2\_download\_dir 和aria2\_candidate\_dirs 的区别

在最新版本 2.2.0-rc1 中，

* `aria2_download_dir` 是唯一的 CAR 文件下载路径；
* `aria2_candidate_dirs` 是 CAR 文件可以预先存在的路径，通过 Swan Provider 下载的文件不会保存在这个路径下；

如果存储提供商的订单的 CAR 文件都是通过 Swan Provider 下载得到的，可以将`aria2_download_dir`和`aria2_candidate_dirs`设置为同一个；

如果 Storage Provider 订单 CAR 文件是在订单发送之前提前存储在本地路径，这些路径可以配置在`aria2_candidate_dirs`中，并且支持多个目录，订单发送以后，Swan Provider 会优先从`aria2_candidate_dirs`目录中查找订单对应的 CAR 文件。

> 注：为了充分利用单个路径的数据读取性能，目前 Swan Provider 会限制单个路径只能有一个文件会被导入。

如遇任何问题，请在 [FilSwan Discord](https://filswan.com/discord) 频道联系我们。


# 5. Boostd 正常运行情况下如何配置从 Swan Provider 接收订单

1. 根据[此步骤](https://github.com/filswan/go-swan-provider/blob/main/README-CN.md#%E5%AE%89%E8%A3%85)安装 Swan Provider
2. 将 `Boostd`repo 移动到 `$SWAN_PATH` 并将 `boostd` 二进制文件移到 `/usr/local/bin/`:

```
mkdir $SWAN_PATH/provider/boost
mv ~/.boost/* $SWAN_PATH/provider/boost/mv boostd /usr/local/bin/
```

3. 打开[此链接](https://github.com/filswan/go-swan-provider/blob/main/README-CN.md#%E9%85%8D%E7%BD%AE%E5%B9%B6%E8%BF%90%E8%A1%8C)根据步骤配置 `config.toml`&#x20;
4. 启动 Swan Provider

```
ulimit -SHn 1048576
export SWAN_PATH = "/data/.swan"
nohup swan-provider daemon >> swan-provider.log 2>&1 &
```

如遇任何问题，请在 [FilSwan Discord](https://filswan.com/discord) 频道联系我们。


# 6. 接单过程中总出现拒绝信息

首先，可以通过以下命令行查看订单是否被拒绝：

```
lotus-miner stroage-deals list -v| grep <deal_cid>
```

如果订单被拒绝，可以通过如下图所示，在存储提供商的config文件里的`[Dealmaking]`下查看接单的过滤设置是否有误。

```
[Dealmaking]
  Filter = "/home/test/dealfilter.pl"
```

你可以在`dealfilter.pl` 下的 `denylist` 中查看被过滤的地址并对其进行添加/删除。

```
#!/usr/bin/perl

use warnings;
use strict;
use 5.014;

# Uncomment this to lock down the miner entirely
# print "Miner currently upgrading - BACK SOON";
# exit 1;

# A list of wallets you do not want to deal with
# For example this enty will prevent a shady ribasushi
# character from storing things on your miner
my $denylist = { map {( $_ => 1 )} qw(
  f3qpseg3qlpckug75qqas6jsce4up6kg5bo4yaefwnxo4fwx2n5f7jpkkrzy37jxnshkd6mazxso2rxfoax111
)};

use JSON::PP 'decode_json';

my $deal = eval { decode_json(do{ local $/; <> }) };
if( ! defined $deal ) {
  print "Deal proposal JSON parsing failed: $@";
  exit 1;
}

if( $denylist->{$deal->{Proposal}{Client}} ) {
  print "Deals from client wallet $deal->{Proposal}{Client} are not welcome";
  exit 1;
}

exit 0;
```

如遇任何问题，请在 [FilSwan Discord](https://filswan.com/discord) 频道联系我们。


# 7. 如何检查 aria2 是否在运行？

`ps -ef | grep aria2`

如遇任何问题，请在 [FilSwan Discord](https://filswan.com/discord) 频道联系我们。


# 8. Swan Platform 无响应

请检查 `api_url` 是否正确，应为 `https://go-swan-server.filswan.com`

如遇任何问题，请在 [FilSwan Discord](https://filswan.com/discord) 频道联系我们。


# 9. Storage Provider 状态显示“Offline/离线”

如果您的存储提供商ID状态显示“Offline/离线”（如下图）

<figure><img src="https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FeTsnpRjFyUlsLNR1km4K%2Fimage.png?alt=media&amp;token=f5037c46-eabd-497b-9de6-a002bf50525f" alt=""><figcaption></figcaption></figure>

请检查您的Storage Provider连通性，参考此处👇

{% content-ref url="/pages/pswmU7jEOiRu8nlKs2qO" %}
[2. 如何检查您的 Storage Provider 连通性/稳定性](/swan-provider/chang-jian-wen-ti/2.-ru-he-jian-cha-nin-de-storage-provider-lian-tong-xing-wen-ding-xing)
{% endcontent-ref %}

若结果显示“Storage provider is unreachable/存储提供商无法接通”（如下图）

<figure><img src="https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2F3RH7M2sc5KsUiU24HTCu%2Fimage.png?alt=media&amp;token=76994527-4d97-4a5a-825e-df8895b21366" alt=""><figcaption></figcaption></figure>

请根据以下文档进行配置，配置完成后再次检查连通性。正常连通时，检查结果将显示红框内所列条目。

<figure><img src="https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FRSUANW5mlGFnBiqJ3lnM%2Fimage.png?alt=media&amp;token=53e7e734-c2de-4a26-9da3-c5c643c7ab9a" alt=""><figcaption></figcaption></figure>

如遇任何问题，请在 [FilSwan Discord](https://filswan.com/discord) 频道联系我们。


# 10. 如何检查任务状态

1. 打开 FilSwan "Launch Console"
2. 点击 "My Task > As Storage Provider", 在右侧检查 "TASK STATUS"。

<figure><img src="https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FSwjZ3TnMhoSpx91W41YB%2Fimage.png?alt=media&amp;token=a276fc39-8d58-4dc6-a20a-e4bcc9b50287" alt=""><figcaption></figcaption></figure>

如需查看各个订单的状态，请点击任务名称，进入任务详情页面查看。

<figure><img src="https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FWpa1QlCrcq6prkAlRNp1%2Fimage.png?alt=media&amp;token=53735953-6301-4de6-84ad-9bb6f7386a83" alt=""><figcaption></figcaption></figure>

如遇任何问题，请在 [FilSwan Discord](https://filswan.com/discord) 频道联系我们。


# 11. 如何配置 Storage Provider Market

如何配置 Lotu-miner Market

假设 `Lotus-miner`的公网IP为`123.123.73.123`。

## 1. 启用 Market 功能

修改`$LOTUS_MINER_PATH/config.toml`文件中的以下内容：

```
[Subsystems]
 EnableMarkets = true
```

## 2. Lotus-miner IP 配置

修改`$LOTUS_MINER_PATH/config.toml`文件中的以下内容：

将`ListenAddresses`中的IP改为`123.123.73.123`（即公网IP地址），端口自己指定一个固定端口，例如: `1024`；

```toml
[Libp2p]
 ListenAddresses = ["/ip4/123.123.73.123/tcp/1024", "/ip6/::/tcp/0"]
```

更改配置以后，需要重启`Lotus-miner`。

## 3. 发布 Multiaddress

将您的 Multiaddress（上面一步配置的 `ListenAddresses`）发布到链上，以便其他节点可以直接与其通信并发送订单：

```
lotus-miner actor set-addrs /ip4/123.123.73.123/tcp/1024
```

等待消息链上确认后，可通过以下命令查看结果:

```
lotus state miner-info [f0xxxx]
```

## 4. Storage Market Actor 充值

```
lotus wallet market add --from=<钱包地址> --address=<矿工号>
```

## 5. 检查 Lotus-miner 的连通性

访问：

```
https://console.filswan.com/#/tools/checkDataCap
```

输入Storage Provider ID 检查连通性，如无异常，将显示如下。

<figure><img src="https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FhSwb9vyKeq9AnNDu5Bff%2Fimage.png?alt=media&amp;token=c5e4b3b4-e679-4229-8690-94bad504090b" alt=""><figcaption></figcaption></figure>

## 6. 设置 Lotus-miner 接单条件

```
lotus-miner storage-deals set-ask --price 0 --verified-price 0 --min-piece-size 56KiB --max-piece-size 32GiB
```

## 7. 过滤 client（可选项）

```
[Dealmaking]
 Filter = "jq -e '.Proposal.Client == \"f1nslxql4pck5pq7hddlzym3orxlx35wkepzjkm3i\" or .Proposal.Client == \"f1stghxhdp2w53dym2nz2jtbpk6ccd4l2lxgmezlq\" or .Proposal.Client == \"f1mcr5xkgv4jdl3rnz77outn6xbmygb55vdejgbfi\" or .Proposal.Client == \"f1qiqdbbmrdalbntnuapriirduvxu5ltsc5mhy7si\" '"
```

如遇任何问题，请在 [FilSwan Discord](https://filswan.com/discord) 频道联系我们。


# 12. 如何设置接单条件

验证订单最小为1MiB，因此需要进行如下设置：

```
lotus-miner storage-deals set-ask --price 0 --verified-price 0 --min-piece-size 1MiB --max-piece-size 32GiB
```

如遇任何问题，请在 [FilSwan Discord](https://filswan.com/discord) 频道联系我们。


# 概览

## 如果您想使用Swan客户端工具发单

#### Swan客户端工具提供以下功能：

* 通过Lotus、Graphsplit、或IPFS将源文件生成 CAR 文件；
* 生成元数据，如 CAR 文件的URL, 交易开始高度(start epoch)等，并以 JSON 格式保存到元数据文件;
* 使用元数据 JSON 文件发起交易;
* 生成包含交易 CID、存储提供者 ID 等数据的最终 JSON 文件，供存储提供者导入交易;
* 在 FilSwan 平台上创建任务和离线交易;
* 自动将交易发送给参与自动竞价的存储提供者。


# 基本概念须知

### 任务 <a href="#task" id="task"></a>

* 一个任务可以包含一个或多个Car文件
* 每个Car文件可以发送给一个或多个矿工
* 为任务中的每个Car文件设置矿工的接单模式
  * **Auto-bid**: `task.bid_mode=1`, 市场匹配器将基于声誉系统和任务中Car文件最大副本数量的需要，自动为每个Car文件分配矿工。
  * **Manual-bid**: `task.bid_mode=0`, 竞价人中标后，任务持有人需要向中标者发起任务(交易)。
  * **None-bid**: `task.bid_mode=2`, 需要将任务中每个Car文件发送给指定的矿工。
* 任务状态:
  * **Created**: 任务创建后，不管它是什么类型，它的初始状态都是`created`。
  * **ActionRequired**: 自动竞价任务（也就是`task.bid_mode=1`）有一些信息缺失或无效：

    * MaxPrice:缺失或不是一个有效的数字
    * FastRetrieval: 缺失
    * Type: 缺失，或没有有效值

    🔔 需要解决上述问题，并将任务状态更改为`Created`，以便参与运行市场匹配器下一轮匹配中去。

### CAR文件 <a href="#task" id="task"></a>

* Car文件是发送给矿工的一个独立单元
* 每个Car文件可以发送给一个或多个矿工
* Car文件可将源文件通过Lotus、Graph-split或IPFS生成
* Car文件最大为64GB
* Car文件状态:
  * **Created**: 任务创建后，任务中所有Car文件都处于这种状态
  * **ActionRequired**:自动竞价任务（也就是`task.bid_mode=1`）有一些信息缺失或无效：
    * FileSize: 缺失或不是一个有效的数字
    * FileUrl: 缺失
    * StartEpoch: 缺失，或当前值无效、小于0或小于当前高度(currentEpoch)
    * PayloadCid: 缺失
    * PieceCid: 缺失
  * **Assigned**: 当其任务处于自动竞价模式时，即`task.bid_mode=1`，表示一个Car文件已经被市场匹配器自动分配给一些矿工。

### 离线交易 <a href="#offline-deal" id="offline-deal"></a>

* 离线交易是指将Car文件发送给矿工的交易
* 离线交易状态:
  * **Assigned**: 只有在自动竞价模式，即`task.bid_mode=1`，当一个Car文件被分配给一个矿工时，一个离线交易记录被创建，它的状态是`Assigned`。
  * **Created**: 对于所有的竞价模式，Car文件发送给矿工后，对应的交易状态为 `Created`.
  * **…**: 还有其他几种状态，由Swan Provider和Swan Platform生成和使用，它们对所有竞价模式的任务具有相同的含义。
* 这个工具的每一步都会生成一个JSON文件，其中包含如下所示的文件信息:

```
[
 {
  "Uuid": "",
  "SourceFileName": "srcFiles",
  "SourceFilePath": "[source file path]",
  "SourceFileMd5": "",
  "SourceFileSize": 5231342,
  "CarFileName": "bafybeidezzxpy3lrvzz2py56vasl7modkss4v56qwh67tzhetsn2qh3aem.car",
  "CarFilePath": "[car file path]",
  "CarFileMd5": "30fc76af655688cc6ef49bbb96ce938a",
  "CarFileUrl": "[car file url]",
  "CarFileSize": 5234921,
  "PayloadCid": "bafybeidezzxpy3lrvzz2py56vasl7modkss4v56qwh67tzhetsn2qh3aem",
  "PieceCid": "baga6ea4seaqfbtlhrfnzuhbmwnjw4a7ovtjijae32g25o56jcuidk2fdzrjgmoi",
  "StartEpoch": null,
  "SourceId": null,
  "Deals": null
 }
]
```

```
[
 {
  "Uuid": "072f8d4a-b79e-42b7-9452-3b8d1d41c11c",
  "SourceFileName": "",
  "SourceFilePath": "",
  "SourceFileMd5": "",
  "SourceFileSize": 0,
  "CarFileName": "",
  "CarFilePath": "",
  "CarFileMd5": "",
  "CarFileUrl": "[car file url]",
  "CarFileSize": 5234921,
  "PayloadCid": "bafybeidezzxpy3lrvzz2py56vasl7modkss4v56qwh67tzhetsn2qh3aem",
  "PieceCid": "baga6ea4seaqfbtlhrfnzuhbmwnjw4a7ovtjijae32g25o56jcuidk2fdzrjgmoi",
  "StartEpoch": null,
  "SourceId": 2,
  "Deals": [
   {
    "DealCid": "bafyreih2feyqpckrsmjnwgkm44el45obi3em7cjh7udkq6jgp4flkce6ra",
    "MinerFid": "t03354",
    "StartEpoch": 575856
   }
  ]
 }
]
```

* 在每个步骤中生成的这个JSON文件将在其下一步中使用，并可用于将来重建graph。
* 生成`Uuid`是为了将来建立索引


# 使用指南

Swan Client 是一个重要的 Web3 工具包，提供不同的工具帮助用户连接到 Web3 世界，包含以下功能:

* Filecoin 交易发送引擎
* 区块链 RPC 服务 (Pocket Network 提供支持)

{% content-ref url="/pages/7pXljBFopaI5Fuaw5mqV" %}
[Filecoin 交易发送引擎](/swan-client/chuang-jian-ren-wu-liu-cheng/filecoin-jiao-yi-fa-song-yin-qing)
{% endcontent-ref %}

{% content-ref url="/pages/eTpUOr1kpLS2mRd0hMPj" %}
[区块链 RPC 服务](/swan-client/chuang-jian-ren-wu-liu-cheng/qu-kuai-lian-rpc-fu-wu)
{% endcontent-ref %}


# Filecoin 交易发送引擎

作为 Filecoin 网络的 PiB 级数据载入工具，Swan Client 可以帮助用户处理数据，并将数据发送给 Filecoin 网络中的存储提供商。 主要功能及步骤如下

* 通过 graphsplit, lotus, IPFS, 或 ipfs-car 从源文件生成 CAR 文件
* 将 CAR 文件上传至 IPFS 服务器，并生成发送离线订单需要的元数据文件 (JSON 和 CSV)
* 基于元数据文件发送离线订单
* 生成一个最终元数据文件，供存储提供商导入订单
* 在 [Swan Platform](https://console.filswan.com/#/dashboard) 上创建任务和离线订单

  **(存储供应商可以通过** [**Swan Provider**](https://github.com/filswan/go-swan-provider/tree/release-2.1.0-rc1) **自动导入订单)**

Swan Client 支持创建三种不同的任务，帮助用户将数据发送至存储供应商。从源文件到成功发送订单的整个流程如下：

<figure><img src="https://462127002-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fge3NMJs0WFB5ALcsdmfX%2Fuploads%2FIlKHJGJiIv5BJWWnkBln%2Fimage.png?alt=media&amp;token=f34439ed-26d8-4740-a5b6-8638f64c4c96" alt=""><figcaption></figcaption></figure>

{% content-ref url="/pages/MImi1QFAxVZf8JYF7V9s" %}
[安装](/swan-client/chuang-jian-ren-wu-liu-cheng/filecoin-jiao-yi-fa-song-yin-qing/an-zhuang)
{% endcontent-ref %}

{% content-ref url="/pages/yJtoRGcvtK4jJEmZy0U9" %}
[配置](/swan-client/chuang-jian-ren-wu-liu-cheng/filecoin-jiao-yi-fa-song-yin-qing/pei-zhi)
{% endcontent-ref %}

{% content-ref url="/pages/MVE0ezftXO9YBd0kx2NY" %}
[前提条件](/swan-client/chuang-jian-ren-wu-liu-cheng/filecoin-jiao-yi-fa-song-yin-qing/qian-ti-tiao-jian)
{% endcontent-ref %}

{% content-ref url="/pages/dOH8JPFg6EC0h2i8rvd9" %}
[生成 CAR 文件](/swan-client/chuang-jian-ren-wu-liu-cheng/filecoin-jiao-yi-fa-song-yin-qing/sheng-cheng-car-wen-jian)
{% endcontent-ref %}

{% content-ref url="/pages/s7wonWHm2oKrQ4o8FpHC" %}
[上传 CAR 文件到 IPFS](/swan-client/chuang-jian-ren-wu-liu-cheng/filecoin-jiao-yi-fa-song-yin-qing/shang-chuan-car-wen-jian-dao-ipfs)
{% endcontent-ref %}

{% content-ref url="/pages/hGjjohbOwIQngOlccfrb" %}
[创建任务](/swan-client/chuang-jian-ren-wu-liu-cheng/filecoin-jiao-yi-fa-song-yin-qing/chuang-jian-ren-wu)
{% endcontent-ref %}


# 安装

## **安装包**

参考 [release assets](https://github.com/filswan/go-swan-client/releases)

```shell
mkdir swan-client
cd swan-client
wget --no-check-certificate https://github.com/filswan/go-swan-client/releases/download/v2.1.0-rc1/install.sh
chmod +x install.sh
./install.sh
```

## **源代码**

:bell:需要 **go 1.18.1+**

```shell
git clone https://github.com/filswan/go-swan-client.git
cd go-swan-client
git checkout release-2.1.0-rc1
./build_from_source.sh
```

从源代码安装后，二进制文件 `swan-client` 位于 `./build` 目录下


# 配置

创建任务前，需要在 `~/.swan/client/config.toml` 中更新配置项。

```shell
vi ~/.swan/client/config.toml
```

```
    [lotus]
    client_api_url = "http://[ip]:[port]/rpc/v0"   # lotus 客户端 web API 的 Url, 通常 [port] 是 1234
    client_access_token = ""                       # lotus 客户端 web API 的 Token 令牌, 需要管理员权限

    [main]
    market_version = "1.1"                         # 订单版本为 1.1 或 1.2。此配置 (market_version=1.1) 将被弃用，很快会被删除 (默认: "1.1")。
    api_url = "https://go-swan-server.filswan.com" # Swan API 地址。生产环境默认为： `https://go-swan-server.filswan.com`. 如果 `[sender].offline_swan=true`，则可忽略。
    api_key = ""                                   # Swan API key. 获取方式：[Swan Platform](https://console.filswan.com/#/dashboard) -> "My Profile"->"Developer Settings"。 如果 `[sender].offline_swan=true`，则可忽略。
    access_token = ""                              # Swan API token. 获取方式： [Swan Platform](https://console.filswan.com/#/dashboard) -> "My Profile"->"Developer Settings"。如果 `[sender].offline_swan=true`，则可忽略。

    [ipfs_server]
    download_url_prefix = "http://[ip]:[port]"     # IPFS 服务器 URL 前缀，存储 CAR 文件供存储提供商下载。 下载链接为 `[download_url_prefix]/ipfs/[dataCID]`
    upload_url_prefix = "http://[ip]:[port]"       # 供上传文件的 IPFS 服务 URL，

    [sender]
    offline_swan = false                           # 是否在 [Swan Platform](https://console.filswan.com/#/dashboard) 上创建任务，当设置为 true 时, 仅生成元数据供存储提供商导入订单。
    verified_deal = true                           # 是否作为‘verified’订单发送
    fast_retrieval = true                          # 是否要求存储提供商支持文件快速取回
    skip_confirmation = false                      # 是否在每个订单发送前跳过手动确认
    generate_md5 = false                           # 是否为每个 CAR 文件和源文件生成 md5值（非常消耗资源）
    wallet = ""                                    # 发送离线订单使用的钱包
    max_price = "0"                                # Max price willing to pay per GiB/epoch for offline deals 愿意为离线订单当中的每GiB每个epoch 支付的最高价格
    start_epoch_hours = 96                         # 订单将在多少小时后开始 (默认 96 小时)
    expire_days = 4                                # 订单将在多少天后过期 (默认 4 天)
    duration = 1512000                             # 要求存储提供商存储数据的时长，以区块高度为单位(30s/区块), 默认 1512000.
    start_deal_time_interval = 500                 # 每个订单发送的时间间隔，默认: 500ms
```


# 前提条件

如果你已经在 `config.toml`中设置了`market_version = "1.2"`，则须完成以下步骤：

* 导入客户端钱包私钥到 `$SWAN_PATH`(default: `~/.swan`):

```
    swan-client wallet import wallet.key
```

* 给客户端钱包的 Market Actor 充值，以便发送订单：

```
    lotus wallet market add --from <address> --address <market_address> <amount>
```

**Note：** 如果您使用的是 `market_version = "1.2"`, 请确保存储提供商使用的 `swan-provider` 版本为 [v2.1.0-rc1](https://github.com/filswan/go-swan-provider/releases/tag/v2.1.0-rc1) 及以上。




---

[Next Page](/llms-full.txt/1)

