js-sdk for multichain storage service

Overview

js-mcs-sdk

Made by FilSwan Chat on discord

Table of Contents

Introduction

A client library for the Multi-Chain Storage (MCS) https://mcs.filswan.com service. It provides a convenient interface for working with the MCS API from a web browser or Node.js. This client has the following functionalities:

  • POST    upload file to Filswan IPFS gate way
  • POST    make payment to swan filecoin storage gate way
  • GET       status from filecoin
  • POST    mint asset as NFT
  • GET       list of files uploaded
  • GET       files by cid

Prerequisites

Node.js - v16.13.0 (npm v8.1.0)
Polygon Mumbai Testnet Wallet - Metamask Tutorial
Polygon Mumbai Testnet RPC - Signup via Alchemy

You will also need Testnet USDC and MATIC balance to use this client. Swan Faucet Tutorial

MCS API

For more information about the API usage, check out the MCS API documentation.

Usage

Instructions for developers working with MCS Client and API.

Installation

Install the package using npm

npm install mcs-client

Getting Started

First you should set your private key and RPC-url as environment variables in a .env file

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

Example of uploading a single file using the MCS Client.

require('dotenv').config()
const { mcsClient } = require('mcs-client')

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

async function main() {
  const testFile = JSON.stringify({ address: client.publicKey })
  const fileArray = [{ fileName: 'testFile.json', file: testFile }]

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

main()

Documentation

The following functions documentation will assume you have a MCS client instantiated. Using the client variable for the following examples.

const client = new mcsClient({
  privateKey: process.env.PRIVATE_KEY,
  rpcUrl: process.env.RPC_URL,
})

upload(files, options) - Uploading File(s)

You can use the MCS Client to upload and 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.

const fileArray = [
  { fileName: 'file1', file: fs.createReadStream('./file1.txt') },
  { fileName: 'file2', file: fs.createReadStream('./file2.txt') },
]

//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: 180, // 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 client.upload(fileArray, options)
console.log(uploadResponses)
/* return
    [
      {
        status: 'success',
        code: '200',
        data: {
          payload_cid: 'bafk...',
          ipfs_url: 'https://calibration-ipfs.filswan.com/ipfs/Qm...',
          need_pay: <int>
        }
      },
      {
        status: 'success',
        code: '200',
        data: {
          payload_cid: 'bafk...',
          ipfs_url: 'https://calibration-ipfs.filswan.com/ipfs/Qm...',
          need_pay: <int>
        }
      }
    ]
*/

makePayment(payloadCid, amount) - Pay for File Storage

Use USDC tokens to pay for your unpaid uploaded file. You need the payload_cid of the file. Returns a web3 receipt object

const PAYLOAD_CID = ''

const tx = await client.makePayment(PAYLOAD_CID, '0.05')
console.log(tx.transactionHash)
/* return (tx hash, can view on mumbai polygonscan)
    0x...
*/

Note that amount is a type String. This is to avoid Big Number precision errors when dealing to amounts in Wei

checkStatus(dealCid) - Check File Status from Filecoin

Check the Filecoin storage status of a file using it's deal_cid

PAYLOAD_CID = ''

// search for file info to get deal_cid
const uploadInfo = await client.listUploads(client.publicKey, PAYLOAD_CID)
const dealCid = uploadInfo.data[0].deal_cid

if (dealCid) {
  const fileStatus = await client.checkStatus(dealCid)
  console.log(fileStatus)
} else {
  console.log('deal_cid not found')
}

/* return
{
    status: 'success',
    code: '200',
    data: {
        offline_deal_logs: [ [Object], [Object], [Object], [Object], [Object] ]
    }
}
*/

mintAsset(payloadCid, nft) - Mint Asset as NFT

After you upload a file, you can mint it to Opensea (testnet) as an NFT. First you will need your NFT metadata. Similarly to makePayment this function will return a web3 receipt object

const PAYLOAD_CID = ''
const IPFS_URL = ''

const nft = {
  name: 'File 1', // the name of your NFT
  description: 'This is the first file', // the description of your NFT
  image: IPFS_URL, // asset URI, images will render on Opensea
}

const mintTx = await client.mintAsset(PAYLOAD_CID, nft)
console.log(mintTx)

listUploads(wallet, payloadCid, fileName, pageNumber, pageSize) - View Uploaded Files

This function will return an object of uploaded files. All the parameters have default values, so you can pass no parameters to view all your uploaded files.

console.log(await client.listUploads())

You can search for files, either by payload_cid or by file_name

console.log(await client.listUploads(client.publicKey, payloadCid))
console.log(await client.listUploads(client.publicKey, '', 'file1')

getFileDetails(payloadCid, dealId) View File Details

Using listUploads, you can retreive the payload_cid and deal_id of a file. Calling this function will return an object containing the details of the file.

console.log(await client.getFileDetails(payloadCid, 0))

Contributing

Feel free to join in and discuss. Suggestions are welcome! Open an issue or Join the Discord!

Sponsors

This project is sponsored by Filecoin Foundation

Flink SDK - A data provider offers Chainlink Oracle service for Filecoin Network

You might also like...

microCMS JavaScript SDK.

microCMS JavaScript SDK It helps you to use microCMS from JavaScript and Node.js applications. Getting Started Install Install npm package. $ npm inst

Dec 31, 2022

Temporal-time-utils - This is a library with some reusable functions for Temporal.io TypeScript SDK

temporal-time-utils This is a library with some reusable functions for Temporal.io TypeScript SDK: sleepUntil: sleep to a specific date, instead of by

Oct 18, 2022

Anagolay Network Javascript SDK written in Typescript

Anagolay Network Javascript SDK written in Typescript. This repo will contain the bindings to Anagolay Network with the sane defaults for pallet usage

Nov 26, 2022

Lazerpay SDK allows you accept payments easily in your react application

Lazerpay SDK allows you accept payments easily in your react application

Lazerpay Official react sdk Lazerpay SDK allows you accept payments easily in your react application Installation npm install lazerpay-react Usage imp

Nov 20, 2022

Firebase SDK 9 + Google Sign In + Chrome Extension Manifest Version 3 + Webpack

Firebase SDK 9 + Google Sign In + Chrome Extension Manifest Version 3 + Webpack Demo Find this Chrome Extension Setup and working demo here or on Yout

Dec 28, 2022

The NodeJS server SDK for Charon.

Charon - NodeJS Server SDK This is the NodeJS server SDK for Charon: A new form of secure, passwordless authentication. The SDK currently serves as a

Apr 8, 2022

Codemod scripts to update AWS SDK for JavaScript APIs.

aws-sdk-js-codemod This repository contains a collection of codemod scripts for use with JSCodeshift that help update AWS SDK for JavaScript APIs. The

Jan 2, 2023

NodeJS(TypeScript) SDK For V2EX

NodeJS(TypeScript) SDK For V2EX

Mar 2, 2022

This SDK helps developers get started with the on-chain tools provided by Metaplex.

This SDK helps developers get started with the on-chain tools provided by Metaplex.

Metaplex JavaScript SDK ⛔️ DO NOT USE IN PRODUCTION, THIS SDK IS IN VERY EARLY ALPHA STAGES! This SDK helps developers get started with the on-chain t

Dec 27, 2022
Comments
  • TypeError: Cannot read properties of undefined (reading 'name')

    TypeError: Cannot read properties of undefined (reading 'name')

    When I run the js-mcs-sdk test.js:

    PS C:\Users\12109\Desktop\mcs-client> node .\test.js
    TypeError: Cannot read properties of undefined (reading 'name')
    at FormData._getContentDisposition (C:\Users\12109\node_modules\form-data\lib\form_data.js:227:40)
    at FormData._multiPartHeader (C:\Users\12109\node_modules\form-data\lib\form_data.js:178:33)
    at FormData.append (C:\Users\12109\node_modules\form-data\lib\form_data.js:71:21)
    at uploadPromise (C:\Users\12109\node_modules\mcs-client\helper\upload.js:16:8)
    at C:\Users\12109\node_modules\mcs-client\helper\upload.js:39:7
    at async Promise.all (index 0)
    at async mcsUpload (C:\Users\12109\node_modules\mcs-client\helper\upload.js:52:20)
    at async mcsClient.upload (C:\Users\12109\node_modules\mcs-client\index.js:54:5)
    at async test (C:\Users\12109\Desktop\mcs-client\test.js:21:26)
    C:\Users\12109\Desktop\mcs-client\test.js:22
    console.log(uploadResponse[0].data.payload_cid)
    ^
    
    TypeError: Cannot read properties of undefined (reading '0')
    at test (C:\Users\12109\Desktop\mcs-client\test.js:22:29)
    

    Here is the test.js code :

    require('dotenv').config('C:\\Users\\12109\\.env')
    const fs = require('fs')
    const { mcsClient } = require('mcs-client')
    
    
    const client = new mcsClient({
      privateKey: process.env.PRIVATE_KEY,
    })
    
    const test = async  () => {
      const fileArray = [
        { fileName: 'jstest', file: fs.createReadStream('./jstest.txt') },
      ]
    
      const options = {
        delay: 1000, 
        duration: 180, 
        fileType: 0, 
      }
    
      const uploadResponse = await client.upload(fileArray, options)
      console.log(uploadResponse[0].data.payload_cid)
      console.log(uploadResponse[0].data.ipfs_url)
    }
    
    test()
    

    node and npm version:

    PS C:\Users\12109\Desktop\mcs-client> node -v
    v16.13.1
    PS C:\Users\12109\Desktop\mcs-client> npm -v
    8.1.2
    PS C:\Users\12109\Desktop\mcs-client>
    

    What's wrong with me???

    opened by Jasonwu123 6
  • 支付成功,但网页显示待支付

    支付成功,但网页显示待支付

    require('dotenv').config('./.env')
    const fs = require('fs').promises
    const { mcsClient } = require('mcs-client')
    const client = new mcsClient({
      privateKey: process.env.PRIVATE_KEY,
      rpcUrl: process.env.RPC_URL,
    })
    
    async function main() {
      const payloadCid = 'bafykbzacXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
      const tx = await client.makePayment(payloadCid, '0.001')
      console.log(tx.transactionHash)
    }
    main()
    
    

    运行后 支付成功并输出tx_hash ,可通过浏览器查到交易详情。 但网页依旧显示未支付,且无法手动支付。

    opened by BBQFIL 3
  • help request:  problems paying for storage on poly mumbai testnet

    help request: problems paying for storage on poly mumbai testnet

    Hi,

    I have been having difficulties recently with paying for storage on the testnet even though I believe I have enough funds in wallet. Below is the error and file details (uploaded to IPFS already). Status appears to be always "pending". Please advise. Thanks.

    I have the following fund in test wallet:

    0.0968 MATIC

    197 USDC

    ERROR

    /node_modules/web3-core-helpers/lib/errors.js:28 var err = new Error('Returned error: ' + message); ^

    Error: Returned error: insufficient funds for gas * price + value at Object.ErrorResponse (../node_modules/web3-core-helpers/lib/errors.js:28:19) at ../node_modules/web3-core-requestmanager/lib/index.js:300:36 at ../node_modules/web3-providers-http/lib/index.js:124:13 at processTicksAndRejections (node:internal/process/task_queues:96:5) { data: null }

    UPLOAD FILE DETAILS

    // [ // { // status: 'success', // data: { // source_file_upload_id: 476742, // payload_cid: 'Qmerw1LjXrcm52y6RoTSmFiZHuHqWKzJ5b8dzpkoofuELf', // ipfs_url: 'https://calibration-ipfs.filswan.com/ipfs/Qmerw1LjXrcm52y6RoTSmFiZHuHqWKzJ5b8dzpkoofuELf', // file_size: 19, // w_cid: '8a1c9f2d-853d-49b2-a87b-299fb21f5d92Qmerw1LjXrcm52y6RoTSmFiZHuHqWKzJ5b8dzpkoofuELf' // } // } // ]

    / [ // { // source_file_upload_id: 476742, // car_file_id: 0, // file_name: 'JnK0N.txt', // file_size: 19, // upload_at: 1659664087, // duration: 525, // ipfs_url: 'https://calibration-ipfs.filswan.com/ipfs/Qmerw1LjXrcm52y6RoTSmFiZHuHqWKzJ5b8dzpkoofuELf', // pin_status: 'Pinned', // payload_cid: '', // w_cid: '8a1c9f2d-853d-49b2-a87b-299fb21f5d92Qmerw1LjXrcm52y6RoTSmFiZHuHqWKzJ5b8dzpkoofuELf', // status: 'Pending', // deal_success: false, // is_minted: false, // token_id: null, // mint_address: null, // nft_tx_hash: null, // offline_deal: [] // },

    opened by srblabotw69 1
  • 如何批量上传,批量支付,批量铸造?

    如何批量上传,批量支付,批量铸造?

    require('dotenv').config('./.env')
    const fs = require('fs').promises
    const { mcsClient } = require('mcs-client')
    const client = new mcsClient({
      privateKey: process.env.PRIVATE_KEY,
      rpcUrl: process.env.RPC_URL,
    })
    
    async function main() {
      const fileArray = [
        { fileName: 'AAAA', file: await fs.readFile('./AAAA') },
        { fileName: 'BBBB', file: await fs.readFile('./BBBB') },
        { fileName: 'CCCC', file: await fs.readFile('./CCCC') },
      ]
    
      const options = {
        delay: 1, 
        duration: 525, 
        fileType: 0, 
      }
    
      const uploadResponses = await client.upload(fileArray, options)
      console.log(uploadResponses)
      const payloadCid = uploadResponses[0].data.payload_cid
      const tx = await client.makePayment(payloadCid, '0.002')
      console.log(tx.transactionHash)
    
      const nft = {
        name: 'NFT', 
        description: 'NFT',
        image: uploadResponses[0].data.ipfs_url,
        tx_hash: '0x...',
      }
    
      const mintTx = await client.mintAsset(payloadCid, nft)
      console.log(mintTx)  
    }
    
    main()
    

    这样写只能批量上传,但是只有第一个文件被支付和铸造。 应该怎么改? @rykci

    opened by BBQFIL 0
Releases(v3.1.0)
  • v3.1.0(Dec 1, 2022)

    js-mcs-sdk v3.1.0

    • Minor release for multichain.storage SDK

    What's New

    • Added Buckets functionality
      • Users can create/delete buckets, and add files to them
    • Improved error handling, better error messages for UX
    Source code(tar.gz)
    Source code(zip)
  • v3.0.1(Oct 21, 2022)

  • v3.0.0(Oct 13, 2022)

    js-mcs-sdk v3.0.0

    • Major release for multichain.storage SDK

    What's New

    • no longer uses new mcsSDK. instead use await mcsSDK.initialize
    • automatic login and stores jwt
    • network detection based on rpc url
    • filecoin_price is from chainlink price feed
    Source code(tar.gz)
    Source code(zip)
  • v2.1.0(Jun 30, 2022)

    js-mcs-sdk v2.1.0

    • Minor release for multiminer version of MCS

    What's New

    • making payments with amount '0' will now use average storage price (similar to UI logic)
    • added option to use calibration API for devs
    Source code(tar.gz)
    Source code(zip)
  • v2.0.3(Jun 16, 2022)

    js-mcs-sdk v2.0.3

    • Patch release for multiminer version of MCS

    What's New

    • Add external_url to NFT object so file contents are viewable through Opensea.
      • sdk-test/mintAsset.js code and SDK documentation are updated to reflect this change
    • Fixed token id clashes when minting NFT by using events opposed to totalSupply()
    • Use web3.eth.getGasPrice for more accurate gas prices during transactions
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0(Jun 1, 2022)

    js-mcs-sdk v2.0.0

    • Updated release for multiminer version of MCS

    Features

    • Upload file(s) to MCS
    • Pay for a file
    • Mint a file as an NFT
    • Get uploaded files
    • Get file details
    • Get filecoin storage status for a file

    What's New

    • The API routes and SDK logic was updated to match the multi-miner MCS API.
    • Added more test files in sdk-test to test each feature individually
    Source code(tar.gz)
    Source code(zip)
Owner
FilSwan
Distributed data and computing platform
FilSwan
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Compact library for interacting with Ankr Scan Multichain API.

ankrscan.js Compact SDK for interacting with Ankr Scan MultiChain JSON-RPC API. SDK supports following MultiChain methods: getLogs - logs matching the

Ankr 23 Jan 3, 2023
A Multichain crypto wallet library that supports Ethereum, Solana and other EVM compatible blockchains.

Multichain Crypto Wallet A Multichain crypto wallet library that supports Ethereum, Solana and other EVM compatible blockchains. Installation npm inst

Abdulfatai Suleiman 117 Jan 2, 2023
🚀👩‍🚀This repo contains all the files to follow along and implement a MultiChain NFT MarketPlace! Be sure to watch my Youtube tutorials so you can learn and follow along!

Multi-Chain NFT Marketplace ?? ??‍?? This repo contains all the files to follow along and implement a MultiChain NFT MarketPlace! Be sure to watch my

Net2Dev 30 Jan 5, 2023
The iofod SDK provides developers with the ability to interact with the main iofod interface within the Web worker, enabling rapid development of iofod extensions through the SDK.

iofod-sdk English | 简体中文 The iofod SDK provides developers with the ability to interact with the main iofod interface within the Web worker, enabling

iofod, Inc. 47 Oct 17, 2022
Movehat is a TypeScript SDK for Move on Sui built on top of Sui's TypeScript SDK and our fork of Ian Macalinao's `move-ts`.

Movehat Movehat is a TypeScript SDK for Move on Sui built on top of Sui's TypeScript SDK and our fork of Ian Macalinao's move-ts. Movehat aspires to b

Pentagon 10 Sep 30, 2022
Persistent key/value data storage for your Browser and/or PWA, promisified, including file support and service worker support, all with IndexedDB. Perfectly suitable for your next (PWA) app.

BrowstorJS ?? ?? ?? Persistent key/value data storage for your Browser and/or PWA, promisified, including file support and service worker support, all

Nullix 8 Aug 5, 2022
RESTful service to provide API linting as-a-service

API Linting Service Prerequisites / general idea General idea behind this API implementation is to provide an API as a service based on the awesome sp

Schwarz IT 6 Mar 14, 2022
TypeScript plugin for service-to-service (aka. "functionless") cloud integrations.

Functionless λ< Functionless is a TypeScript plugin that transforms TypeScript code into Service-to-Service (aka. "functionless") integrations, such a

sam 303 Jan 2, 2023