Quick Start with Synapse SDK
The Synapse SDK is your gateway to Filecoin Onchain Cloud, a decentralized, programmable cloud platform built on Filecoin. The SDK handles all the complexity of blockchain interactions, provider selection, and data management, so you can focus on building your application.
By the end of this guide, you’ll understand how to:
- Install and configure the Synapse SDK
- Connect to Filecoin networks (mainnet and calibration)
- Prepare and fund your storage balance
- Upload and download data
Prerequisites
Section titled “Prerequisites”- FIL for gas fees. On testnet, get tFIL from the Calibration Faucet. For mainnet, see Getting FIL.
- USDFC for storage payments. On testnet, get tUSDFC from the USDFC Faucet. For mainnet, see Getting USDFC.
Installation
Section titled “Installation”The Synapse SDK works in Node.js and the browser. Install it with your preferred package manager:
npm install @filoz/synapse-sdk viempnpm add @filoz/synapse-sdk viemyarn add @filoz/synapse-sdk viembun add @filoz/synapse-sdk viemviem is a peer dependency and must be installed separately.
Quick Start
Section titled “Quick Start”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.
import { class SynapseSynapse, const mainnet: FilecoinChainmainnet } from "@filoz/synapse-sdk"
import { function privateKeyToAccount(privateKey: Hex, options?: PrivateKeyToAccountOptions): PrivateKeyAccountprivateKeyToAccount } from 'viem/accounts'
// 1) Initialize the Synapse SDK
const const synapse: Synapsesynapse = class SynapseSynapse.Synapse.create(options: SynapseOptions): Synapsecreate({
SynapseOptions.account: `0x${string}` | Accountaccount: function privateKeyToAccount(privateKey: Hex, options?: PrivateKeyToAccountOptions): PrivateKeyAccountprivateKeyToAccount('0x...'),
SynapseOptions.source: string | nullsource: 'my-app',
SynapseOptions.chain?: FilecoinChain | undefinedchain: const mainnet: FilecoinChainmainnet, // 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 const file: Uint8Array<ArrayBuffer>file = new var TextEncoder: new () => TextEncoderThe **`TextEncoder`** interface enables you to encode a JavaScript string using UTF-8.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder)TextEncoder().TextEncoder.encode(input?: string): Uint8Array<ArrayBuffer>The **`TextEncoder.encode()`** method takes a string as input, and returns a Uint8Array containing the string encoded using UTF-8.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode)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 const prep: PrepareResultprep = await const synapse: Synapsesynapse.Synapse.storage: StorageManagerstorage.StorageManager.prepare(options: PrepareOptions): Promise<PrepareResult>prepare({
PrepareOptions.pieceSizes: readonly bigint[]pieceSizes: [var BigInt: BigIntConstructor
(value: bigint | boolean | number | string) => bigint
BigInt(const file: Uint8Array<ArrayBuffer>file.Uint8Array<ArrayBuffer>.byteLength: numberThe length in bytes of the array.byteLength)],
})
if (const prep: PrepareResultprep.PrepareResult.transaction: {
depositAmount: bigint;
includesApproval: boolean;
execute: (options?: {
onHash?: (hash: Hash) => void;
}) => Promise<{
hash: Hash;
receipt: import("viem").TransactionReceipt | null;
}>;
} | null
transaction) {
const { const hash: `0x${string}`hash } = await const prep: PrepareResultprep.PrepareResult.transaction: {
depositAmount: bigint;
includesApproval: boolean;
execute: (options?: {
onHash?: (hash: Hash) => void;
}) => Promise<{
hash: Hash;
receipt: import("viem").TransactionReceipt | null;
}>;
}
transaction.execute: (options?: {
onHash?: (hash: Hash) => void;
}) => Promise<{
hash: Hash;
receipt: import("viem").TransactionReceipt | null;
}>
execute()
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`✅ Account funded and approved (tx: ${const hash: `0x${string}`hash})`)
}
// 3) Upload — stores 2 copies across independent providers for durability
const { const pieceCid: PieceCIDpieceCid, const size: numbersize, const complete: booleancomplete, const copies: CopyResult[]copies, const failedAttempts: FailedAttempt[]failedAttempts } = await const synapse: Synapsesynapse.Synapse.storage: StorageManagerstorage.StorageManager.upload(data: UploadPieceStreamingData, options?: StorageManagerUploadOptions): Promise<UploadResult>upload(const file: Uint8Array<ArrayBuffer>file)
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`✅ Upload complete!`);
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`PieceCID: ${const pieceCid: PieceCIDpieceCid}`);
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`Size: ${const size: numbersize} bytes`);
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`Stored on ${const copies: CopyResult[]copies.Array<CopyResult>.length: numberGets or sets the length of the array. This is a number one higher than the highest index in the array.length} providers`);
if (!const complete: booleancomplete) var console: Consoleconsole.Console.warn(...data: any[]): voidThe **`console.warn()`** static method outputs a warning message to the console at the "warning" log level. The message is only displayed to the user if the console is configured to display warning output. In most cases, the log level is configured within the console UI. The message may receive special formatting, such as yellow colors and a warning icon.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static)warn(`${const failedAttempts: FailedAttempt[]failedAttempts.Array<T>.length: numberGets or sets the length of the array. This is a number one higher than the highest index in the array.length} copy attempt(s) failed`);
// 4) Download
const const bytes: Uint8Array<ArrayBufferLike>bytes = await const synapse: Synapsesynapse.Synapse.storage: StorageManagerstorage.StorageManager.download(options: StorageManagerDownloadOptions): Promise<Uint8Array>download({ pieceCid: string | PieceCIDpieceCid })
const const decodedText: stringdecodedText = new var TextDecoder: new (label?: string, options?: TextDecoderOptions) => TextDecoderThe **`TextDecoder`** interface represents a decoder for a specific text encoding, such as UTF-8, ISO-8859-2, or GBK. A decoder takes an array of bytes as input and returns a JavaScript string.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder)TextDecoder().TextDecoder.decode(input?: AllowSharedBufferSource, options?: TextDecodeOptions): stringThe **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode)decode(const bytes: Uint8Array<ArrayBufferLike>bytes);
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`✅ Download successful!`);
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`Downloaded data: ${const decodedText: stringdecodedText}\n`);
var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log("🎉 Data storage and retrieval successful!");Now let’s break down each step…
-
Initialize the SDK
Set up the Synapse SDK with your credentials. In Node.js, you’ll typically use a private key:
constconst synapse: Synapsesynapse =class SynapseSynapse.Synapse.create(options: SynapseOptions): Synapsecreate({SynapseOptions.account: `0x${string}` | Accountaccount:function privateKeyToAccount(privateKey: Hex, options?: PrivateKeyToAccountOptions): PrivateKeyAccountprivateKeyToAccount('0x...'),SynapseOptions.source: string | nullsource: 'my-app',SynapseOptions.chain?: FilecoinChain | undefinedchain:const mainnet: FilecoinChainmainnet, // default is calibration testnet })In the browser, connect to the user’s wallet instead:
import 'viem/window' import {function custom<provider extends EthereumProvider>(provider: provider, config?: CustomTransportConfig): CustomTransportcustom } from 'viem' const [const address: `0x${string}`address] = awaitvar window: Window & typeof globalThisThe **`window`** property of a Window object points to the window object itself. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/window)window.ethereum!.Window.ethereum?: { on: <event extends keyof EIP1193EventMap>(event: event, listener: EIP1193EventMap[event]) => void; removeListener: <event extends keyof EIP1193EventMap>(event: event, listener: EIP1193EventMap[event]) => void; request: EIP1193RequestFn<EIP1474Methods>; } | undefinedrequest({request: <undefined, { method: "eth_requestAccounts"; }, `0x${string}`[]>(args: { method: "eth_requestAccounts"; }, options?: EIP1193RequestOptions | undefined) => Promise<`0x${string}`[]>method: "eth_requestAccounts"method: 'eth_requestAccounts' }) constconst synapse: Synapsesynapse =class SynapseSynapse.Synapse.create(options: SynapseOptions): Synapsecreate({SynapseOptions.account: `0x${string}` | Accountaccount:const address: `0x${string}`address,SynapseOptions.transport?: Transport | undefinedtransport:custom(custom<{ on: <event extends keyof EIP1193EventMap>(event: event, listener: EIP1193EventMap[event]) => void; removeListener: <event extends keyof EIP1193EventMap>(event: event, listener: EIP1193EventMap[event]) => void; request: EIP1193RequestFn<EIP1474Methods>; }>(provider: { on: <event extends keyof EIP1193EventMap>(event: event, listener: EIP1193EventMap[event]) => void; removeListener: <event extends keyof EIP1193EventMap>(event: event, listener: EIP1193EventMap[event]) => void; request: EIP1193RequestFn<EIP1474Methods>; }, config?: CustomTransportConfig): CustomTransportvar window: Window & typeof globalThisThe **`window`** property of a Window object points to the window object itself. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/window)window.ethereum!),Window.ethereum?: { on: <event extends keyof EIP1193EventMap>(event: event, listener: EIP1193EventMap[event]) => void; removeListener: <event extends keyof EIP1193EventMap>(event: event, listener: EIP1193EventMap[event]) => void; request: EIP1193RequestFn<EIP1474Methods>; } | undefinedSynapseOptions.source: string | nullsource: 'my-app',SynapseOptions.chain?: FilecoinChain | undefinedchain:const mainnet: FilecoinChainmainnet, // default is calibration testnet })The
sourceparameter identifies your application. It is stored as metadata on each dataset so that multiple apps sharing the same wallet can distinguish their own data. -
Payment Setup
The
prepare()method calculates the exact deposit needed for your data size and returns a single transaction that handles both funding and approval.To size your deposit, check the up-to-date rates in Pricing and use the storage costs guide for a detailed breakdown.
// Check current USDFC balance constconst walletBalance: bigintwalletBalance = awaitconst synapse: Synapsesynapse.Synapse.payments: PaymentsServicepayments.walletBalance({PaymentsService.walletBalance(options?: { token?: TokenIdentifier; }): Promise<bigint>token?: string | undefinedtoken:TOKENS.const TOKENS: { readonly USDFC: "USDFC"; readonly FIL: "FIL"; }type USDFC: "USDFC"USDFC }); constconst formattedBalance: stringformattedBalance =function formatUnits(value: bigint, options?: FormatUnitsOptions): stringformatUnits(const walletBalance: bigintwalletBalance); // Prepare account constconst prep: PrepareResultprep = awaitconst synapse: Synapsesynapse.Synapse.storage: StorageManagerstorage.StorageManager.prepare(options: PrepareOptions): Promise<PrepareResult>prepare({PrepareOptions.pieceSizes: readonly bigint[]pieceSizes: [1073741824n], // one 1 GiB piece });var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log("Deposit needed:",const prep: PrepareResultprep.PrepareResult.costs: calculateUploadCosts.OutputTypecosts.depositNeeded: bigintdepositNeeded);var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log("Rate per month:",const prep: PrepareResultprep.PrepareResult.costs: calculateUploadCosts.OutputTypecosts.rates.rates: { perEpoch: bigint; perMonth: bigint; }perMonth: bigintperMonth);var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log("Ready to upload:",const prep: PrepareResultprep.PrepareResult.costs: calculateUploadCosts.OutputTypecosts.ready: booleanready); // Execute the transaction if needed (handles deposit + approval in one tx) if (const prep: PrepareResultprep.transaction) { const {PrepareResult.transaction: { depositAmount: bigint; includesApproval: boolean; execute: (options?: { onHash?: (hash: Hash) => void; }) => Promise<{ hash: Hash; receipt: import("viem").TransactionReceipt | null; }>; } | nullconst hash: `0x${string}`hash } = awaitconst prep: PrepareResultprep.transaction.PrepareResult.transaction: { depositAmount: bigint; includesApproval: boolean; execute: (options?: { onHash?: (hash: Hash) => void; }) => Promise<{ hash: Hash; receipt: import("viem").TransactionReceipt | null; }>; }execute();execute: (options?: { onHash?: (hash: Hash) => void; }) => Promise<{ hash: Hash; receipt: import("viem").TransactionReceipt | null; }>var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`Account funded and approved (tx: ${const hash: `0x${string}`hash})`); } -
Store and Download Data
Upload data to decentralized storage and retrieve it:
// Upload data (stores 2 copies by default for durability) constconst file: Uint8Array<ArrayBuffer>file = newvar TextEncoder: new () => TextEncoderThe **`TextEncoder`** interface enables you to encode a JavaScript string using UTF-8. [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder)TextEncoder().TextEncoder.encode(input?: string): Uint8Array<ArrayBuffer>The **`TextEncoder.encode()`** method takes a string as input, and returns a Uint8Array containing the string encoded using UTF-8. [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode)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 {const pieceCid: PieceCIDpieceCid,const complete: booleancomplete,const copies: CopyResult[]copies,const failedAttempts: FailedAttempt[]failedAttempts } = awaitconst synapse: Synapsesynapse.Synapse.storage: StorageManagerstorage.StorageManager.upload(data: UploadPieceStreamingData, options?: StorageManagerUploadOptions): Promise<UploadResult>upload(const file: Uint8Array<ArrayBuffer>file);var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`Stored on ${const copies: CopyResult[]copies.Array<CopyResult>.length: numberGets or sets the length of the array. This is a number one higher than the highest index in the array.length} providers`); if (!const complete: booleancomplete)var console: Consoleconsole.Console.warn(...data: any[]): voidThe **`console.warn()`** static method outputs a warning message to the console at the "warning" log level. The message is only displayed to the user if the console is configured to display warning output. In most cases, the log level is configured within the console UI. The message may receive special formatting, such as yellow colors and a warning icon. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static)warn(`${const failedAttempts: FailedAttempt[]failedAttempts.Array<T>.length: numberGets or sets the length of the array. This is a number one higher than the highest index in the array.length} copy attempt(s) failed`); // Download data from any provider that has it constconst downloadedData: Uint8Array<ArrayBufferLike>downloadedData = awaitconst synapse: Synapsesynapse.Synapse.storage: StorageManagerstorage.StorageManager.download(options: StorageManagerDownloadOptions): Promise<Uint8Array>download({pieceCid: string | PieceCIDpieceCid }); constconst decodedText: stringdecodedText = newvar TextDecoder: new (label?: string, options?: TextDecoderOptions) => TextDecoderThe **`TextDecoder`** interface represents a decoder for a specific text encoding, such as UTF-8, ISO-8859-2, or GBK. A decoder takes an array of bytes as input and returns a JavaScript string. [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder)TextDecoder().TextDecoder.decode(input?: AllowSharedBufferSource, options?: TextDecodeOptions): stringThe **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode)decode(const downloadedData: Uint8Array<ArrayBufferLike>downloadedData);var console: Consoleconsole.Console.log(...data: any[]): voidThe **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)log(`Downloaded data: ${const decodedText: stringdecodedText}`);
Next Steps
Section titled “Next Steps”You’ve just stored and retrieved data on Filecoin. See the Developer Guides overview to find the right approach for your application, then dive into specific topics:
- Preview Packages - Install unreleased builds from a PR, commit, or
master - Upload Pipeline - From simple one-liner to manual store, pull, and commit control
- Storage Operations - Data set management, retrieval, and lifecycle
- Payment Operations - Fund your account and manage storage payments
- Session Keys - Delegate signing to ephemeral keys for better UX
- API Reference - Complete SDK classes, methods, and types
- Example Application - Full-stack upload dapp
Want to understand the protocol? See Foundations & Architecture for how PDP, Filecoin Pay, and the service provider network fit together.
Join the #fil-builders on Filecoin Slack or Telegram for help and discussions.