Quick Start with Synapse SDK
The Synapse SDK is your gateway to Filecoin Onchain Cloud — a decentralized, programmable cloud platform built on Filecoin. This comprehensive guide will walk you through everything you need to know to start building with the SDK.
The Synapse SDK provides an interface to Filecoin’s decentralized services ecosystem:
- 🚀 Recommended Usage: Use the high-level
Synapseclass for a streamlined experience with sensible defaults - 🔧 Composable Components: Import and use individual components for fine-grained control over specific functionality
The SDK handles all the complexity of blockchain interactions, provider selection, and data management, so you can focus on building your application.
What You’ll Learn
Section titled “What You’ll Learn”By the end of this guide, you’ll understand how to:
- Install and configure the Synapse SDK
- Connect to Filecoin networks (mainnet and calibration)
- Manage payments and allowances
- Upload and download data with Synapse SDK
- Use advanced features like CDN and custom providers
Prerequisites
Section titled “Prerequisites”Before installing the Synapse SDK, make sure you have the following:
- Node.js 20 or higher installed.
- A supported package manager (npm, yarn, or pnpm).
- Added Filecoin Calibration into you MetaMask.
Get Test Tokens
Section titled “Get Test Tokens”Before you start building with Synapse SDK, you’ll need to request test tokens from faucets to pay transaction fees and storage fees. For the calibration testnet:
Get tFIL tokens:
- Visit the Filecoin Calibration Faucet
- Enter your wallet address to receive free tFIL tokens
- You need FIL for gas fees
Get test USDFC tokens:
- Visit the Filecoin Calibration USDFC Faucet
- Enter your wallet address to receive free test USDFC tokens
- You need USDFC for storage payments
Installation
Section titled “Installation”The Synapse SDK requires Node.js 20+ and can be installed via npm, yarn, or pnpm:
npm install @filoz/synapse-sdk viemNote: viem is a peer dependency and must be installed separately.
Quick Start Example
Section titled “Quick Start Example”The Synapse class provides a complete, easy-to-use interface for interacting with Filecoin storage services.
Get started with storage in just a few lines of code.
// @lib: esnext,domimport { Synapse } from "@filoz/synapse-sdk"import { mainnet } from "@filoz/synapse-core/chains"import { privateKeyToAccount } from 'viem/accounts'
async function main() { // 1) Initialize the Synapse SDK const synapse = Synapse.create({ account: privateKeyToAccount('0x...'), source: 'my-app', chain: mainnet, // default is calibration testnet // Uncomment for high-performance incentive-aligned data retrievability through Filecoin Beam // withCDN: true })
// 2) Prepare account (single tx handles deposit + approval) const file = new TextEncoder().encode( `🚀 Welcome to decentralized storage on Filecoin Onchain Cloud! Your data is safe here. 🌍 You need to make sure to meet the minimum size requirement of 127 bytes per upload.` ); const prep = await synapse.storage.prepare({ dataSize: BigInt(file.byteLength), }) if (prep.transaction) { const { hash } = await prep.transaction.execute() console.log(`✅ Account funded and approved (tx: ${hash})`) }
// 3) Upload — stores 2 copies across independent providers for durability const { pieceCid, size, complete, copies, failedAttempts } = await synapse.storage.upload(file) console.log(`✅ Upload complete!`); console.log(`PieceCID: ${pieceCid}`); console.log(`Size: ${size} bytes`); console.log(`Stored on ${copies.length} providers`); if (!complete) console.warn(`${failedAttempts.length} copy attempt(s) failed`);
// 4) Download const bytes = await synapse.storage.download({ pieceCid }) const decodedText = new TextDecoder().decode(bytes); console.log(`✅ Download successful!`); console.log(`Downloaded data: ${decodedText}\n`); console.log("🎉 Data storage and retrieval successful!");}
main().then(() => { console.log("✅ Storage workflow completed successfully!");}).catch((error) => { console.error("❌ Error occurred:"); console.error(error.message); // Clear error description console.error(error.cause); // Underlying error if any});What you just did:
- ✅ Initialized Synapse SDK for Filecoin Calibration
- ✅ Computed the exact deposit and approval needed for your data size
- ✅ Executed a single transaction to fund and approve (if needed)
- ✅ Uploaded data with 2 copies across independent providers for durability
- ✅ Retrieved it using only the content address (from any provider that has it)
Now let’s break down each step…
1: Initialize the SDK
Section titled “1: Initialize the SDK”First, set up the Synapse SDK with your credentials. We use wallet private key here as an example, but you can definitely inject signer from any wallet providers, such as MetaMask or wallet connect.
// @lib: esnext,domimport { Synapse } from "@filoz/synapse-sdk";import { privateKeyToAccount } from 'viem/accounts'// ---cut---// Initialize SDK with your private key and RPC endpointconst synapse = Synapse.create({ account: privateKeyToAccount('0x...'), source: 'my-app' })The source parameter identifies your application. It is stored as metadata on each dataset so that multiple apps sharing the same wallet can distinguish their own data.
2: Payment Setup
Section titled “2: Payment Setup”Before storing data, you need to ensure your account is funded and the storage service is approved. The prepare() method calculates the exact deposit needed for your data size and returns a single transaction that handles both funding and approval.
// @lib: esnext,domimport { Synapse, TOKENS, formatUnits } from "@filoz/synapse-sdk";import { privateKeyToAccount } from 'viem/accounts'const synapse = Synapse.create({ account: privateKeyToAccount('0x...'), source: 'my-app' })
// ---cut---// Check current USDFC balanceconst walletBalance = await synapse.payments.walletBalance({ token: TOKENS.USDFC });const formattedBalance = formatUnits(walletBalance);
// Prepare account — computes exact deposit + approval for your data sizeconst prep = await synapse.storage.prepare({ dataSize: 1073741824n, // 1 GiB});
console.log("Deposit needed:", prep.costs.depositNeeded);console.log("Rate per month:", prep.costs.rate.perMonth);console.log("Ready to upload:", prep.costs.ready);
// Execute the transaction if needed (handles deposit + approval in one tx)if (prep.transaction) { const { hash } = await prep.transaction.execute(); console.log(`✅ Account funded and approved (tx: ${hash})`);}3: Store and Download Data
Section titled “3: Store and Download Data”Now you can upload data to decentralized storage and retrieve it:
// @lib: esnext,domimport { Synapse } from "@filoz/synapse-sdk";import { privateKeyToAccount } from 'viem/accounts'const synapse = Synapse.create({ account: privateKeyToAccount('0x...'), source: 'my-app' })// ---cut---// Upload data — stores 2 copies by default for durabilityconst file = new TextEncoder().encode( `🚀 Welcome to decentralized storage on Filecoin Onchain Cloud! Your data is safe here. 🌍 You need to make sure to meet the minimum size requirement of 127 bytes per upload.`);const { pieceCid, complete, copies, failedAttempts } = await synapse.storage.upload(file);console.log(`Stored on ${copies.length} providers`);if (!complete) console.warn(`${failedAttempts.length} copy attempt(s) failed`);
// Download data from any provider that has itconst downloadedData = await synapse.storage.download({ pieceCid });const decodedText = new TextDecoder().decode(downloadedData);
console.log(`Downloaded data: ${decodedText}`);What’s Next?
Section titled “What’s Next?”Congratulations! You’ve successfully stored and retrieved data using the Synapse SDK. But this is just the beginning - the SDK offers many powerful features for building decentralized applications:
Key Features
Section titled “Key Features”| Category | Features |
|---|---|
| 🗄️ Advanced Storage | CDN Integration: Enable fast global content delivery |
| Metadata Management: Tag and organize your data | |
| Batch Operations: Upload multiple files efficiently | |
| 💰 Payment Management | Automated Settlements: Handle payment rails automatically |
| Cost Estimation: Preview storage costs before uploading | |
| Allowance Management: Control spending limits | |
| 🛠️ Developer Tools | Session Keys: Improve user experience with delegated signing |
| Progress Callbacks: Track upload/download progress | |
| Error Handling: Comprehensive error management | |
| 🌐 Network Integration | Provider Discovery: Find optimal storage providers |
| Proof Verification: Verify data integrity with PDP | |
| Subgraph Integration: Query blockchain data efficiently |
Quick Examples
Section titled “Quick Examples”Advanced Storage with Contexts
Section titled “Advanced Storage with Contexts”For more control over provider selection and data set management:
// @lib: esnext,domimport { Synapse } from "@filoz/synapse-sdk";import { privateKeyToAccount } from 'viem/accounts'const synapse = Synapse.create({ account: privateKeyToAccount('0x...'), source: 'my-app' })const file = new TextEncoder().encode( `🚀 Welcome to decentralized storage on Filecoin Onchain Cloud! Your data is safe here. 🌍 You need to make sure to meet the minimum size requirement of 127 bytes per upload.`);// ---cut---// Create a storage context with specific providerconst context = await synapse.storage.createContext({ providerId: 1n, // Use specific provider withCDN: true, // Enable CDN for faster retrieval metadata: { category: "documents", version: "1.0", },});
// Upload to this specific contextconst result = await context.upload(file);
// Download from this contextconst downloaded = await context.download({ pieceCid: result.pieceCid });-
providerId: By specifying
providerId, you tell Synapse SDK to store (and later retrieve) your data specifically with that provider. -
withCDN: Setting
withCDN: trueenables Filecoin Beam, the decentralized retrieval and delivery layer. So global users can download data faster, and pay-by-egress billing. -
metadata: Attach custom key-value pairs to your data set for easy categorization, tagging, or later querying. This metadata is stored on-chain and can be used by apps or indexing systems.
Finding Service Providers
Section titled “Finding Service Providers”// @lib: esnext,domimport { Synapse } from "@filoz/synapse-sdk";import { privateKeyToAccount } from 'viem/accounts'const synapse = Synapse.create({ account: privateKeyToAccount('0x...'), source: 'my-app' })// ---cut---// Get all approved providersconst storageInfo = await synapse.storage.getStorageInfo();const providers = storageInfo.providers;
console.log("Available providers:");providers.forEach((provider) => { console.table({ ID: provider.id, Name: provider.name, Description: provider.description, Active: provider.isActive, ProviderAddress: provider.serviceProvider, PDPServiceURL: provider.pdp.serviceURL, });});Explore More
Section titled “Explore More”Ready to dive deeper? Check out these comprehensive guides:
- Core Concepts - Understand the architecture, PDP, and Filecoin Pay protocols
- Storage Operations - Complete guide to uploading, downloading, and managing data sets
- Payment Management - Learn about deposits, approvals, and monitoring costs
Developer Resources
Section titled “Developer Resources”- Example Application - Full-stack upload application
API Reference
Section titled “API Reference”For complete API documentation, see the API Reference which covers:
- All SDK classes and methods
- TypeScript interfaces and types
- Configuration options
- Error handling patterns
Community & Support
Section titled “Community & Support”- GitHub: Report issues and contribute
- Slack: Join the
#fil-builderson Filecoin Slack for help and discussions - Telegram: Join
FIL Builderson Telegram