# 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 `Synapse` class 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

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

Before installing the Synapse SDK, make sure you have the following:

- **[Node.js](https://nodejs.org/en) 20 or higher** installed.
- A **supported package manager** (npm, yarn, or pnpm).
- Added [Filecoin **Calibration**](https://chainlist.org/chain/314159) into you MetaMask.

### 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](https://faucet.calibnet.chainsafe-fil.io/funds.html)
- 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](https://forest-explorer.chainsafe.dev/faucet/calibnet_usdfc)
- Enter your wallet address to receive free test USDFC tokens
- You need USDFC for storage payments

## Installation

The Synapse SDK requires Node.js 20+ and can be installed via npm, yarn, or pnpm:

```bash
npm install @filoz/synapse-sdk viem
```

Note: `viem` is a peer dependency and must be installed separately.

:::tip[Other Languages?]
Looking for Python or Go? Check out [Community Projects](/resources/community-projects/) for community-maintained SDKs.
:::

## Quick Start Example

The [`Synapse`](/reference/filoz/synapse-sdk/synapse/classes/synapse/) class provides a complete, easy-to-use interface for interacting with Filecoin storage services.

:::note[Keep your private key safe]
Instead of hardcoding `privateKey` in the code, you should always consider to store and access it from `.env` files. And never commit your private key.
:::

Get started with storage in just a few lines of code.

```ts twoslash
// @lib: esnext,dom
import { Synapse, parseUnits } from "@filoz/synapse-sdk"
import { privateKeyToAccount } from 'viem/accounts'

async function main() {
  // 1) Initialize the Synapse SDK
  const synapse = Synapse.create({ 
    account: privateKeyToAccount('0x...') 
    // Uncomment for high-performance incentive-aligned data retrievability through Filecoin Beam
    // withCDN: true
  })

  // 2) Fund & approve (single tx)
  const hash = await synapse.payments.depositWithPermitAndApproveOperator({
    amount: parseUnits("2.5"), // 2.5 USDFC (covers 1TiB of storage for 30 days)
  })
  await synapse.client.waitForTransactionReceipt({ hash })
  console.log(`✅ USDFC deposit and Warm Storage service approval successful!`);

  // 3) Upload
  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 { pieceCid, size } = await synapse.storage.upload(file)
  console.log(`✅ Upload complete!`);
  console.log(`PieceCID: ${pieceCid}`);
  console.log(`Size: ${size} bytes`);

  // 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
- ✅ Deposited USDFC as payment tokens
- ✅ Authorized the storage service to use the token
- ✅ Uploaded data to decentralized storage
- ✅ Retrieved it using only the content address

Now let's break down each step...

### 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.

```ts twoslash
// @lib: esnext,dom
import { Synapse } from "@filoz/synapse-sdk";
import { privateKeyToAccount } from 'viem/accounts'
// ---cut---
// Initialize SDK with your private key and RPC endpoint
const synapse = Synapse.create({ account: privateKeyToAccount('0x...') })
```

### 2: Payment Setup

Before storing data, you need to deposit USDFC tokens in your payments account. The amount you deposit is entirely up to your anticipated storage and retrieval needs.
:::note[Pricing]
To size your deposit, check the up‑to‑date rates in [**Pricing**](/introduction/about/#pricing) and use the [storage costs calculator](/developer-guides/storage/storage-costs/#detailed-calculator-guide) for a precise estimate.
:::

```ts twoslash
// @lib: esnext,dom
import { Synapse, TOKENS, formatUnits, parseUnits } from "@filoz/synapse-sdk";
import { privateKeyToAccount } from 'viem/accounts'
const synapse = Synapse.create({ account: privateKeyToAccount('0x...') })

// ---cut---
// Check current USDFC balance
const walletBalance = await synapse.payments.walletBalance({ token:TOKENS.USDFC });
const formattedBalance = formatUnits(walletBalance);

// Deposit USDFC for payment and approve Warm Storage service
const hash = await synapse.payments.depositWithPermitAndApproveOperator({
  amount: parseUnits("2.5"), // Deposit amount: 2.5 USDFC (covers 1TiB of storage for 30 days)
});
await synapse.client.waitForTransactionReceipt({ hash });
console.log(`✅ USDFC deposit and Warm Storage service approval successful!`);
```

### 3: Store and Download Data

Now you can upload data to decentralized storage and retrieve it:

```ts twoslash
// @lib: esnext,dom
import { Synapse } from "@filoz/synapse-sdk";
import { privateKeyToAccount } from 'viem/accounts'
const synapse = Synapse.create({ account: privateKeyToAccount('0x...') })
// ---cut---
// Upload data - SDK automatically selects provider and creates data set if needed
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 { pieceCid } = await synapse.storage.upload(file);

// Download data from any provider that has it
const downloadedData = await synapse.storage.download({ pieceCid });
const decodedText = new TextDecoder().decode(downloadedData);

console.log(`Downloaded data: ${decodedText}`);
```

## 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

| 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](https://github.com/FIL-Builders/fwss-subgraph)**: Query blockchain data efficiently |

#### Quick Examples

##### Advanced Storage with Contexts

For more control over provider selection and data set management:

```ts twoslash
// @lib: esnext,dom
import { Synapse } from "@filoz/synapse-sdk";
import { privateKeyToAccount } from 'viem/accounts'
const synapse = Synapse.create({ account: privateKeyToAccount('0x...') })
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 provider
const 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 context
const result = await context.upload(file);

// Download from this context
const 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: true` enables **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

```ts twoslash
// @lib: esnext,dom
import { Synapse } from "@filoz/synapse-sdk";
import { privateKeyToAccount } from 'viem/accounts'
const synapse = Synapse.create({ account: privateKeyToAccount('0x...') })
// ---cut---
// Get all approved providers
const 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

Ready to dive deeper? Check out these comprehensive guides:

- **[Core Concepts](/core-concepts/architecture/)** - Understand the architecture, PDP, and Filecoin Pay protocols
- **[Storage Operations](/developer-guides/storage/storage-operations/)** - Complete guide to uploading, downloading, and managing data sets
- **[Payment Management](/developer-guides/payments/payment-operations/)** - Learn about deposits, approvals, and monitoring costs

#### Developer Resources

- **[Example Application](https://github.com/FIL-Builders/fs-upload-dapp)** - Full-stack upload application

#### API Reference

For complete API documentation, see the [API Reference](/reference/filoz/synapse-sdk/toc/) which covers:

- All SDK classes and methods
- TypeScript interfaces and types
- Configuration options
- Error handling patterns

#### Community & Support

- **GitHub**: [Report issues and contribute](https://github.com/FilOzone/synapse-sdk)
- **Slack**: Join the `#fil-builders` on [Filecoin Slack](https://filecoin.io/slac) for help and discussions
- **Telegram**: Join `FIL Builders` on [Telegram](https://t.me/+Xj6_zTPfcUA4MGQ1)