Skip to content

Commit

Permalink
Merge pull request #19 from filswan/develop
Browse files Browse the repository at this point in the history
release 4.1.1
  • Loading branch information
rykci authored Jan 24, 2023
2 parents 6e14cd0 + a302f1f commit d5e1f4d
Show file tree
Hide file tree
Showing 19 changed files with 489 additions and 373 deletions.
187 changes: 97 additions & 90 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,58 +1,30 @@
# js-mcs-sdk
# Multichain Storage SDK - Javascript

[![Made by FilSwan](https://img.shields.io/badge/made%20by-FilSwan-green.svg)](https://www.filswan.com/)
[![Chat on discord](https://img.shields.io/badge/join%20-discord-brightgreen.svg)](https://discord.com/invite/KKGhy8ZqzK)

A javascript software development kit for the Multi-Chain Storage (MCS) https://www.multichain.storage/ service. It provides a convenient interface for working with the MCS API from a web browser or Node.js. This SDK has the following functionalities:

# Table of Contents <!-- omit in toc -->

- [Introduction](#introduction)
- [For Onchain Storage](#for-onchain-storage)
- [For Buckets Storage](#for-buckets-storage)
- [Getting Started](#getting-started)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Examples](#examples)
- [Examples](#examples)
- [For Onchain Storage](#for-onchain-storage)
- [For Buckets Storage](#for-buckets-storage)
- [Functions](#functions)
- [Contributing](#contributing)

<a name="introduction"></a>

# ℹ️ Introduction

A javascript software development kit for the Multi-Chain Storage (MCS) https://www.multichain.storage/ service. It provides a convenient interface for working with the MCS API from a web browser or Node.js. This SDK has the following functionalities:

## For Onchain Storage

- **POST** Upload file to Filswan IPFS gateway
- **GET** List of files uploaded
- **GET** Files by cid
- **GET** Status from filecoin
- **CONTRACT** Make payment to swan filecoin storage gateway
- **CONTRACT** Mint asset as NFT

## For Buckets Storage

- **POST** Create a bucket
- **POST** Create a folder
- **POST** Upload File to the bucket
- **POST** Rename bucket
- **GET** Delete bucket
- **GET** Bucket List
- **GET** File List
- **GET** File information
- **GET** Delete File

<a name="getting-started"></a>

# 🆕 Getting Started
## 🆕 Getting Started

## Prerequisites
### Prerequisites

- [Node.js](https://nodejs.org/en/) - v16.13.0 (npm v8.1.0) \
- Polygon Wallet - [Metamask Tutorial](https://docs.filswan.com/getting-started/beginner-walkthrough/public-testnet/setup-metamask) \
- Polygon Mainnet RPC endpoint - https://polygon-rpc.com (USDC and Matic are required if you want to make payment.)
- API Key and Access Token - Obtained via https://multichain.storage
- [Node.js](https://nodejs.org/en/) - v16.13.0 (npm v8.1.0)
- API Key and Access Token - Generated via https://multichain.storage

## Installation
### Installation

In a new working directory, use `npm init -y` to initialize a Node.js project.
Install the package using npm
Expand All @@ -62,87 +34,122 @@ npm init -y
npm install js-mcs-sdk
```

<a name="examples"></a>
### Setup Credentials

# 👨‍💻 Examples
Create a .env file that includes the following content. Optionally include your wallet's private key and RPC-url.

Here is the demo to get you started; you can get more information in the [SDK documentation.](https://docs.filswan.com/multi-chain-storage/developer-quickstart/sdk)
```bash
API_KEY='<API_KEY>'
ACCESS_TOKEN='<ACCESS_TOKEN>'

1. Set Up Environment Variables
# for onchain storage only
PRIVATE_KEY='<PRIVATE_KEY>'
RPC_URL='<RPC_URL>'
```

Create a .env file that includes the following content. Optionally include your wallet's private key and RPC-url.
### Initialize SDK

```bash
API_KEY='<API_KEY>'
ACCESS_TOKEN='<ACCESS_TOKEN>'
```js
require('dotenv').config()
const { mcsSDK } = require('js-mcs-sdk')

# optional
PRIVATE_KEY='<PRIVATE_KEY>'
RPC_URL='<RPC_URL>'
```
async function main() {
// initialize js-mcs-sdk
const mcs = await mcsSDK.initialize({
apiKey: process.env.API_KEY,
accessToken: process.env.ACCESS_TOKEN,
chainName: 'polygon.mainnet',
})
}

1. **_The `RPC_URL` is the one mentioned above_**
2. **_`PRIVATE_KEY` will be obtained from the wallet_**
3. **_The `API_KEY` and `ACCESS_TOKEN` can be generated from the Settings page on [multichain.storage](#https://www.multichain.storage/)_**
main()
```

2) Initalize SDK
<a name="examples"></a>

To begin using the SDK, we first need to require the package at the top of the script and call the `initialize` function
## 👨‍💻 Examples

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

async function main() {
// initialize js-mcs-sdk
const mcs = await mcsSDK.initialize({
apiKey: process.env.API_KEY,
accessToken: process.env.ACCESS_TOKEN,
})
}
- Create a bucket

main()
```
```js
let bucketData = await mcs.createBucket(<BUCKET_NAME>)
console.log(bucketData)
```

Optionally, you can pass `privateKey` to use the onChain Storage upload and payment functions and pass `rpcUrl` if you wish to use your own RPC URL (this SDK uses https://polygon-rpc.com/ by default).
- Upload a file to the bucket

### For Onchain Storage
```js
let fileData = mcs.uploadToBucket(<FILE_PATH>, <BUCKET_UID>, prefix="")
console.log(fileData)
```

- Upload File to Onchain storage
For more examples, please see the [SDK documentation.](https://docs.filswan.com/multi-chain-storage/developer-quickstart/sdk)

```js
console.log(await mcs.upload([{ fileName: <FILE_NAME>, file: fs.createReadStream(<FILE_PATH>) }]))
```
### Onchain Storage

### For Bucket Storage
Onchain storage is designed for storing file information in the smart contract. It requires payment for each file.

- Create a bucket
To use certain Onchain Storage features (upload, payment, minting), you will need to set up the web3 environment first.

```js
console.log(await mcs.createBucket(<BUCKET_NAME>))
```
- Setup Web3

- Upload a file to the bucket
```js
await mcs.setupWeb3(process.env.PRIVATE_KEY, process.env.RPC_URL)
console.log(mcs.web3Initialized) // true
```

```js
console.log(mcs.uploadToBucket(<FILE_PATH>,<BUCKET_UID>,prefix=''))
```
- Upload File to Onchain storage

_The prefix field defines the file-folder relationship, leaving it blank if the file exists directly in the Bucket or the folder name if the file exists in a folder that already exists in the Bucket._
```js
let uploadResponse = await mcs.upload([{ fileName: <FILE_NAME>, file: fs.createReadStream(<FILE_PATH>) }])
console.log(uploadResponse)
```

**_You have to create a bucket before you upload a file._**
- Pay for file storage
after uploading, the response should return the `source_file_upload_id` and the file size.
```js
let tx = await mcs.makePayment(<SOURCE_FILE_UPLOAD_ID>, <FILE_SIZE>)
console.log(transaction hash: ' + tx.transactionHash)
```

**_Note that if you upload a file with the prefix field defined in a folder that has not yet been created, you will not be able to see the file until you create a folder with the same name._**
<a name="functions"></a>

For more examples, please see the [SDK documentation.](https://docs.filswan.com/multi-chain-storage/developer-quickstart/sdk)
## ℹ️ Functions

### For Onchain Storage

---

- **POST** Upload file to Filswan IPFS gateway
- **GET** List of files uploaded
- **GET** Files by cid
- **GET** Status from filecoin
- **CONTRACT** Make payment to swan filecoin storage gateway
- **CONTRACT** Mint asset as NFT

### For Buckets Storage

---

- **POST** Create a bucket
- **POST** Create a folder
- **POST** Upload File to the bucket
- **POST** Rename bucket
- **GET** Delete bucket
- **GET** Bucket List
- **GET** File List
- **GET** File information
- **GET** Delete File

<a name="contributing"></a>

# 🌐 Contributing
## 🌐 Contributing

Feel free to join in and discuss. Suggestions are welcome! [Open an issue](https://github.com/filswan/js-mcs-sdk/issues) or [Join the Discord](https://discord.com/invite/KKGhy8ZqzK)!

## Sponsors
### Sponsors

Filecoin Foundation sponsors this project

Expand Down
3 changes: 1 addition & 2 deletions sdk-test/makePayment.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ const { mcsSDK } = require('js-mcs-sdk')
async function main() {
const SOURCE_FILE_UPLOAD_ID = ''
const FILE_SIZE = ''
const MIN_AMOUNT = '' // leave blank for estimated price

const mcs = await mcsSDK.initialize({
privateKey: process.env.PRIVATE_KEY,
Expand All @@ -14,7 +13,7 @@ async function main() {

console.log('version:', mcs.version)

const tx = await mcs.makePayment(SOURCE_FILE_UPLOAD_ID, MIN_AMOUNT, FILE_SIZE)
const tx = await mcs.makePayment(SOURCE_FILE_UPLOAD_ID, FILE_SIZE)
console.log('transaction hash: ' + tx.transactionHash)
}

Expand Down
31 changes: 14 additions & 17 deletions sdk-test/mcs.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,13 @@ describe('MCS SDK', function () {
expect(mcs)
})

it('Should add private key', async () => {
it('Should setup web3', async () => {
expect(mcs.walletAddress).to.be.undefined
await mcs.addPrivateKey(process.env.PRIVATE_KEY)
await mcs.setupWeb3(process.env.PRIVATE_KEY)
expect(mcs.walletAddress)
})

xdescribe('MCS functions', () => {
describe('Onchain Storage functions', () => {
it('Should upload a file', async () => {
const testFile = JSON.stringify({ address: mcs.walletAddress })
const fileArray = [
Expand All @@ -65,7 +65,7 @@ describe('MCS SDK', function () {
})

it('Should pay for file', async () => {
await mcs.makePayment(sourceFileUploadId, '', size)
await mcs.makePayment(sourceFileUploadId, size)
})

it('Should mint NFT', async () => {
Expand Down Expand Up @@ -93,27 +93,26 @@ describe('MCS SDK', function () {
})
})

describe('Buckets functions', () => {
describe('Bucket Storage functions', () => {
let bucketUid
describe('Buckets', () => {
it('Should remove test-bucket', async () => {
let buckets = await mcs.getBuckets()
let testBucket = buckets.data.find(
(b) => b.BucketName === 'test-bucket',
(b) => b.bucket_name === 'test-bucket',
)

if (testBucket) {
await mcs.deleteBucket(testBucket.BucketUid)
await mcs.deleteBucket(testBucket.bucket_uid)
}

buckets = await mcs.getBuckets()
testBucket = buckets.data.find((b) => b.BucketName === 'test-bucket')
testBucket = buckets.data.find((b) => b.bucket_name === 'test-bucket')

expect(testBucket).to.be.undefined
})
it('Should create a new bucket', async () => {
let bucket = await mcs.createBucket('test-bucket')

bucketUid = bucket.data

expect(bucket.status).to.equal('success')
Expand All @@ -134,7 +133,6 @@ describe('MCS SDK', function () {
let upload = await mcs.uploadToBucket(`./${fileName}`, bucketUid, '')

fileId = upload.data.file_id

expect(upload.status).to.equal('success')
})

Expand All @@ -147,7 +145,6 @@ describe('MCS SDK', function () {

it('Should download a file from bucket', async () => {
let res = await mcs.downloadFile(fileId, './download')

const data = await fs.readFile(`./download/${fileName}`, 'utf8')
expect(data).to.equal(fileName)
})
Expand Down Expand Up @@ -196,19 +193,19 @@ describe('MCS SDK', function () {
let upload = await mcs.uploadToBucket(`./f1`, bucketUid, 'test-folder')

let bucketInfo = (await mcs.getBuckets()).data.find(
(buckets) => buckets.BucketUid === bucketUid,
(buckets) => buckets.bucket_uid === bucketUid,
)
expect(bucketInfo.FileNumber).to.equal(3)
expect(bucketInfo.file_number).to.equal(3)
})

it('Should delete the folder', async () => {
let folder = (await mcs.getFileList(bucketUid)).FileList.find(
(file) => file.Name === 'test-folder',
let folder = (await mcs.getFileList(bucketUid)).file_list.find(
(file) => file.name === 'test-folder',
)
let res = await mcs.deleteFile(folder.ID)
let res = await mcs.deleteFile(folder.id)
let updatedList = await mcs.getFileList(bucketUid)
expect(res.status).to.equal('success')
expect(updatedList.Count).to.equal(0)
expect(updatedList.count).to.equal(0)
})
})
})
Expand Down
Loading

0 comments on commit d5e1f4d

Please sign in to comment.