# Decentralised Storage

The Prismon SDK provides a  function to interact with Walrus-protocol for storing data, enabling developers to store and retrieve data (blobs) on the blockchain. This client integrates with Solana wallets and the Prismon backend to facilitate secure transactions and data management.

This document explains how to initialize and use the Prismon to perform operations like storing and retrieving blobs.

## Overview

The Prismon Blob Storage SDK provides simple methods for storing and retrieving data (both files and text) on the decentralized storage network. This documentation covers both the `storeBlob` and `retrieveBlob` methods with complete usage examples.

Key features:

* **Store Blob**: Upload data (e.g., text, JSON) to the Solana blockchain with configurable storage options.
* **Retrieve Blob**: Fetch stored data using a unique blob ID.
* **JWT Authentication**: Set authentication tokens for secure API requests.

***

### Authentication

All methods require an authenticated wallet:

```typescript
import { useWallet } from '@solana/wallet-adapter-react';

function MyComponent() {
  const { publicKey, signTransaction } = useWallet();
  
  // Wallet props needed for all operations
  const wallet = {
    publicKey: publicKey?.toString(),
    signTransaction
  };
}
```

### Storing Data (`storeBlob`)

Method signature

```typescript
storeBlob(
  data: string | File,  // The content to store
  fileName: string,     // Name to associate with the content
  options: StoreBlobOptions,
  wallet: WalletProps
): Promise<SolanaApiResponse<StoreBlobResponse>>
```

#### Parameters

| Parameter  | Type               | Description                                       |
| ---------- | ------------------ | ------------------------------------------------- |
| `data`     | `string \| File`   | The content to store (text string or File object) |
| `fileName` | `string`           | Name to associate with the stored content         |
| `options`  | `StoreBlobOptions` | Storage configuration options                     |
| `wallet`   | `WalletProps`      | Authenticated wallet object                       |

#### `StoreBlobOptions`

```typescript
interface StoreBlobOptions {
  epochs?: number;          // Storage duration in epochs (default: 1)
  sendObjectTo?: string;    // Optional address to send the blob object to
  deletable?: boolean;      // Whether the blob can be deleted (default: false)
}
```

#### Usage Examples

**1. Storing Text Data**

```typescript
const response = await client.solana.storeBlob(
  "Hello, Prismon!", 
  "greeting.txt",
  {
    epochs: 5,  // Store for 5 epochs
    deletable: true
  },
  wallet
);

if (response.success) {
  console.log("Stored with blob ID:", response.data.blobId);
}
```

**2. Storing a File**

```typescript
// Get file from input
const fileInput = document.getElementById('file-upload') as HTMLInputElement;
const file = fileInput.files?.[0];

if (file) {
  const response = await client.solana.storeBlob(
    file,
    file.name,
    {
      sendObjectTo: "0x123...",  // Address to receive the blob object
      epochs: 10
    },
    wallet
  );
}
```

### Retrieving Data (`retrieveBlob`)

### Method signature

```typescript
retrieveBlob(
  blobId: string,        // The ID of the blob to retrieve
  wallet: WalletProps,   // Authenticated wallet
  options?: {            // Optional retrieval options
    autoHandle?: boolean;          // Auto-download files (default: true)
    defaultFileName?: string;      // Fallback filename if none provided
    onFileDownload?: (fileName: string) => void;  // Download callback
    onTextContent?: (text: string) => void;       // Text content callback
    contentDisposition?: string;   // Force download/inline behavior
    contentType?: string;          // Override content type
  }
): Promise<SolanaApiResponse<BlobContentData> | string | void>
```

#### Usage Examples

**1. Basic Retrieval (Auto-handling)**

```typescript
// Automatically downloads files or returns text
await retrieveBlob("16HpsjB1hRxr4Y3NSu3hzfr1xqj2jmuu4dudO3tsPhA", wallet);
```

#### 2. Handling Results Manually

```typescript
const response = await client.solana.retrieveBlob(blobId, wallet, { autoHandle: false });

if (response.success) {
  if (response.data.isFile) {
    // Download the file
    const url = URL.createObjectURL(response.data.content);
    const a = document.createElement('a');
    a.href = url;
    a.download = response.data.fileName || 'download';
    a.click();
  } else {
    // Handle text content
    const text = await response.data.content.text();
    console.log(text);
  }
}
```

**3. With Callbacks**

```typescript
await client.solana.retrieveBlob(blobId, wallet, {
  defaultFileName: 'backup.pdf',
  onFileDownload: (fileName) => {
    console.log(`Download started: ${fileName}`);
    // Track download analytics
  },
  onTextContent: (text) => {
    setContent(text);  // Update state in React component
  }
});
```

**4. Force Download with Specific Name**

```typescript
// Will always download as "report.pdf" regardless of original name
await client.solana.retrieveBlob(blobId, wallet, {
  contentDisposition: 'attachment; filename="report.pdf"'
});
```

### Convenience Methods

#### `downloadBlob`

Simplified method specifically for file downloads:

```typescript
downloadBlob(
  blobId: string,
  wallet: WalletProps,
  fileName?: string,  // Optional override filename
  options?: Omit<RetrieveBlobOptions, 'autoHandle'>
): Promise<void>
```

#### Example:

```typescript
await client.solana.downloadBlob(
  "16HpsjB1hRxr4Y3NSu3hzfr1xqj2jmuu4dudO3tsPhA",
  wallet,
  "annual-report.pdf"
);
```

#### `getBlobAsText`

Simplified method for text content:

```typescript
getBlobAsText(
  blobId: string,
  wallet: WalletProps,
  options?: Omit<RetrieveBlobOptions, 'autoHandle'>
): Promise<string>
```

Example:

```typescript
const content = await client.solana.getBlobAsText(blobId, wallet);
console.log("File content:", content);
```

### Error Handling

All methods return consistent error responses:

```typescript
interface SolanaApiResponse<T = any> {
  success: boolean;
  data?: T;
  error?: string;
  details?: any;
}
```

### Best Practices

1. **Always check wallet connection** before attempting operations
2. **Provide meaningful filenames** when storing content
3. **Use callbacks** for better user feedback during downloads
4. **Handle errors gracefully** - both network errors and API errors
5. **Clean up object URLs** when done with file downloads
6. **Specify storage duration** (`epochs`) appropriate to your use case


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lucky-israel.gitbook.io/prismon-docs/features/markdown.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
