docsUpload

Upload

Uploads and encrypts files to Filecoin with NFT-based access control.

Signature

async upload(data: Uint8Array, options?: UploadOptions): Promise<UploadResult>

Description

The upload function encrypts files using Lit Protocol and stores them on Filecoin via the Synapse network. It supports both public and private files with NFT-based access control. Files are encrypted before storage and can be retrieved using the returned piece CID.

The SDK operates across multiple networks:

  • Filecoin Storage: Calibration testnet for decentralized file storage
  • Smart Contracts: Base Sepolia for NFT access control and permissions
  • Encryption: Lit Protocol Naga Test network for key management

Parameters

ParameterTypeRequiredDescription
dataUint8ArrayYesFile data as Uint8Array
optionsUploadOptionsNoUpload configuration options

UploadOptions

interface UploadOptions {
  fileName?: string;              // File name for metadata
  isPublic?: boolean;            // Public access when encrypted (default: true)
  skipPaymentCheck?: boolean;     // Skip USDFC balance validation
  metadata?: Record<string, any>; // Custom metadata
  onProgress?: (progress: UploadProgress) => void; // Progress callback
  callbacks?: StorageCallbacks;   // Detailed operation callbacks
  serviceProvider?: {             // Manual provider selection (optional)
    providerId?: number;          // Specific provider ID (e.g., 8, 16)
    providerAddress?: string;     // Provider wallet address
    forceCreateDataSet?: boolean; // Force new dataset creation
  };
}

UploadProgress

interface UploadProgress {
  message: string;
  percentage?: number;
  stage?: string;
  bytesProcessed?: number;
}

Returns

Promise<UploadResult> - A Promise that resolves to an object with the following properties:

PropertyTypeDescription
pieceCidstringFilecoin piece CID for file retrieval
dataIdentifierstringSmart contract data identifier
fileSizenumberFile size in bytes
accessTypestring”public” or “private”
encryptedbooleanWhether file is encrypted
datasetCreatedbooleanWhether new dataset was created
contractTxHashstringSmart contract transaction hash

Examples

Public File Upload

import { Synapse } from '@filoz/synapse-sdk';
import { SynapseStorageSDK } from '@keypo/synapse-storage-sdk';
import { ethers } from 'ethers';
 
// Initialize wallet and provider
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY);
const provider = new ethers.JsonRpcProvider('https://api.calibration.node.glif.io/rpc/v1');
const signer = wallet.connect(provider);
 
// Initialize Synapse
const synapse = await Synapse.create({
  signer,
  withCDN: true,
});
 
// Initialize SDK
const sdk = new SynapseStorageSDK(synapse, {
  network: 'calibration',
  rpcUrl: 'https://api.calibration.node.glif.io/rpc/v1',
  encryption: {
    registryAddress: '0x8370eE1a51B5F31cc10E2f4d786Ff20198B10BBE',
    validationAddress: '0x35ADB6b999AbcD5C9CdF2262c7190C7b96ABcE4C',
    bundlerRpcUrl: 'https://rpc.zerodev.app/api/v3/YOUR_PROJECT_ID/chain/84532'
  },
  storage: {
    capacityGB: 10,
    persistenceDays: 30,
    withCDN: true
  }
}, process.env.PRIVATE_KEY);
 
// Upload public file
const fileData = new TextEncoder().encode("Hello, Filecoin!");
const result = await sdk.upload(fileData, {
  fileName: 'hello.txt',
  isPublic: true, // Anyone can decrypt
  metadata: {
    description: 'Test file uploaded via Synapse Storage SDK',
    uploadedAt: new Date().toISOString()
  },
  onProgress: (progress) => {
    console.log(`${progress.percentage || 0}% - ${progress.message}`);
  }
});
 
console.log('Upload successful!');
console.log('Piece CID:', result.pieceCid);

Private File Upload

// Upload private file (NFT required to decrypt)
const result = await sdk.upload(fileData, {
  fileName: 'secret.txt',
  isPublic: false, // NFT required to decrypt
  metadata: {
    description: 'Private test file',
    uploadedAt: new Date().toISOString(),
    accessLevel: 'NFT_REQUIRED'
  },
  onProgress: (progress) => {
    console.log(`${progress.percentage || 0}% - ${progress.message}`);
  }
});
 
console.log('Private file uploaded!');
console.log('Piece CID:', result.pieceCid);
console.log('You own the NFT for this file');

Provider Selection

For better reliability, you can manually specify a storage provider:

const result = await sdk.upload(fileData, {
  fileName: 'reliable-upload.txt',
  isPublic: true,
  serviceProvider: {
    providerId: 16,              // Use zens-ocean provider
    forceCreateDataSet: true     // Create new dataset (costs ~1-2 USDFC)
  },
  onProgress: (progress) => {
    console.log(`${progress.percentage || 0}% - ${progress.message}`);
  }
});

Available Providers (Calibration Testnet):

  • 8 - THCloudAI (reliable)
  • 16 - zens-ocean (reliable)
  • 2 - pspsps
  • 3 - ezpdpz-calib (may have issues)
  • 4 - infrafolio-calib
  • 13 - filstarry-pdp

Detailed Progress Tracking

const result = await sdk.upload(fileData, {
  fileName: 'tracked-upload.txt',
  isPublic: false,
  callbacks: {
    onProviderSelected: (provider) => {
      console.log(`Using provider: ${provider.name}`);
    },
    onDataSetCreationStarted: (tx, statusUrl) => {
      console.log(`Creating dataset: ${tx.hash}`);
    },
    onUploadComplete: (piece) => {
      console.log(`Upload complete: ${piece}`);
    },
    onPieceConfirmed: () => {
      console.log('Piece confirmed and added to dataset');
    }
  }
});

Payment Requirements

Uploads require USDFC tokens for Filecoin storage costs. Check your balance before uploading:

// Check balance
const balances = await sdk.checkBalance();
console.log(`USDFC Balance: ${ethers.formatUnits(balances.usdfcBalance, 6)} USDFC`);
 
// Deposit if needed (costs about 1-2 USDFC per upload)
if (balances.usdfcBalance < 1000000) { // Less than 1 USDFC
  await sdk.deposit(5); // Deposit 5 USDFC
}

Access Control

  • Public files: Anyone can decrypt (great for content distribution)
  • Private files: Only NFT holders can decrypt
  • File owner: Automatically receives NFT upon upload
  • Sharing: Use sdk.share() to mint NFTs for other wallets

Notes

  • All uploads are encrypted before storage on Filecoin
  • Files are stored permanently on the decentralized network
  • Smart contract operations are gasless via ZeroDev paymaster
  • Use the returned pieceCid for downloading files

See Also

  • Download - Download and decrypt files
  • Share - Share private files with other wallets
  • List - List your uploaded files
  • Configuration - SDK configuration options