This tutorial explains how the fs-upload-dapp works—a production-ready Next.js application demonstrating file storage on Filecoin using the synapse-sdk. Instead of building from scratch, you'll explore the core workflows and understand how hooks and utilities power the application. 📚
synapse-sdk is a JS/TS SDK for interacting with Filecoin Synapse - a smart-contract based marketplace for a collection of services derived from the Filecoin ecosystem, such as Filecoin onchain payment service, hot storage service using PDP, retrieval service, etc. 🛠️
- Clone and Setup: 📥
# Clone the repository and start the app
git clone https://github.com/FIL-Builders/fs-upload-dapp
cd fs-upload-dapp
npm install
npm run dev- Prerequisites: 📋
- Node.js 18+ and npm 📦
- A Web3 wallet (like MetaMask) with some test USDFC & tFIL tokens 💰
- Basic knowledge of React and TypeScript 💻
- Basic understanding of blockchain concepts ⛓️
- Acquire Testnet Tokens: 🪙
- tFIL: Filecoin Calibration Faucet for gas fees. ⛽
- tUSDFC: ChainSafe USDFC Faucet (limit $5 per request). 💵
The application is organized into four primary workflows, powered by custom hooks and utilities:
- 💰 Balance & Storage Management:
useBalances,calculateStorageMetrics - 💳 Storage Payments with USDFC:
usePayment - 📤 File Uploads:
useFileUpload,preflightCheck - 🔍 Data Set Resolution:
useDatasets - 📥 File Downloads:
useDownloadPiece
The Synapse payment system uses two complementary allowances:
- Definition: Maximum USDFC the FilecoinWarmStorageService can spend per epoch.
- Purpose: Automates payments to storage providers for ongoing storage.
- Calculation: Proportional to your storage needs - higher storage requirements demand higher epoch rates.
- Definition: Total USDFC that FilecoinWarmStorageService can reserve upfront to guarantee storage provider payments for your target persistence duration.
- Purpose: Secures payment for the entire storage period and enables uninterrupted Proof of Data Possession (PDP) validation.
- Calculation: (Rate allowance × target persistence days) + existing lockup commitments
The calculateStorageMetrics utility calculates payment requirements based on the app configuration:
export const config = {
storageCapacity: 10, // GB, maximum storage capacity
persistencePeriod: 30, // days, data persistence duration
minDaysThreshold: 10, // days, threshold for low-balance warnings
// Whether to use CDN for the storage for faster retrieval
withCDN: true,
};- Higher
storageCapacity→ Increased rate and lockup allowances. 📈 - Longer
persistencePeriod→ Higher lockup allowance (more epochs to cover). ⏰ - Lower
minDaysThreshold→ Earlier warnings about balance depletion.⚠️ withCDN→ Lightning ⚡ fast retrievals for a higher price 💰
Component: StorageManager.tsx
Allows users to monitor balances and manage subscription payments to maintain persistent storage on Filecoin with Proof of Data Possession (PDP).
The component relies on two main hooks:
The useBalances hook provides real-time visibility into:
- Wallet Balances: FIL and USDFC in your wallet
- Synapse Contract Balance: USDFC deposited in Synapse for storage payments
- Storage Usage: Current data stored vs. configured capacity
- Persistence: Days remaining before payment rates are exhausted
Fetching balances and storage metrics via:
const { data, isLoading, isError, error } = useBalances();
const {
filBalance,
usdfcBalance,
filecoinWarmStorageServiceBalance,
persistenceDaysLeft,
isSufficient,
rateNeeded,
lockUpNeeded,
depositNeeded,
} = data;The usePayment hook handles payments with inputs being calculated by the useBalances hook:
- Approve & Deposit USDFC to Synapse payment contract for storage escrow
- Approve FilecoinWarmStorageService to spend USDFC at specified rates for automated payments per epoch
Payment handling via:
const { mutation: paymentMutation, status } = usePayment();
const { mutateAsync: handlePayment } = paymentMutation;
await handlePayment({
lockupAllowance: BigInt(lockUpNeeded),
epochRateAllowance: BigInt(rateNeeded),
depositAmount: BigInt(depositNeeded),
});Component: FileUploader.tsx
The FileUploader component streamlines file uploads using the Synapse SDK.
The useFileUpload hook orchestrates the full process to upload a file using synapse sdk.
-
Preflight Check: Ensures sufficient USDFC balance via
preflightCheck- 💰 Insufficient Balance: Prompts user to deposit more USDFC if current balance is inadequate
- ✅ Balance Verified: Proceeds to next step when sufficient funds are available
-
Data Set Resolution: Finds or creates the dataset for file upload via
getDataset- 🔍 Existing Dataset: Uses the current active dataset if one exists
- ⚡ New Dataset: Creates a new dataset if none exists for the user
-
File Upload: Uploads to Filecoin with PDP (Proof of Data Possession) by interacting with the storage provider that handles the dataset
- 📤 File Transfer: Securely uploads file data to the designated storage provider
- 🔐 Piece Registration: Signs and sends an
addpiecerequest to the storage provider, enabling them to submit the file piece to the dataset for PDP verification
Uploading a file via:
const { uploadFileMutation, progress, status, uploadedInfo } = useFileUpload();
const { mutateAsync: uploadFile } = uploadFileMutation;
// Upload with progress tracking
await uploadFile(selectedFile);Component: ViewDataSets.tsx
The ViewDataSets component provides a dashboard to monitor data sets and manage file downloads.
The useDatasets hook provides visibility into:
- Client Data Sets: All data sets associated with your address
- Provider Details: Information about storage providers
- Data Set Status: Current state and details from provider APIs
Getting datasets via:
const { data, isLoading: isLoadingDatasets } = useDatasets();
const { datasets } = data;
const datasetCIDs = Record<string, string[]>();
datasets.forEach((dataset) => {
if (dataset.details?.pieces) {
datasetCIDs[dataset.railId] = dataset.details.pieces.map(
(piece) => piece.pieceCid
);
}
});The useDownloadPiece hook enables file downloads from storage providers using the file's piece CID and filename. The filename helps determine the correct MIME type for proper browser handling.
Downloading a file via:
const { downloadMutation } = useDownloadPiece(pieceCID, filename);
const { mutateAsync: downloadFile } = downloadMutation;
// Download file
await downloadFile();- 📊 Monitor Storage: Use the data set viewer to track your stored data
- 💡 Optimize Costs: Adjust persistence periods based on usage patterns
- 📈 Scale Up: Increase storage capacity and deposit additional USDFC as your data usage grows
- 🔧 Integrate: Use the patterns to build your own decentralized powered storage applications
- Live Demo: fs-upload-dapp.netlify.app
- Source Code: GitHub Repository
- Synapse SDK: NPM Package
- PDP: PDP Docs
- Payments contract: Payments Contracts
- FilecoinWarmStorageService: FilecoinWarmStorageService Contracts
- USDFC Documentation: Secured Finance


