agentleFS
0gfoundation0gfoundation/0g-agent-skills/skills/storage/download-file/SKILL.md

download-file

Skill15 starsChanged 2 months agoMITView on GitHub

Download and verify files from 0G decentralized storage using a root hash. Supports verified downloads with Merkle proof validation to ensure data integrity.

  • Reads credentials

The file

We split this skill into the rules it gives an agent

5 rules. About 0 are common, 2 are distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Create an Indexer instance

    line 23
  2. Very specific:

    Call indexer.download() with the root hash, output path, and verified flag

    line 24
  3. Very specific:

    Use verified downloads in production (third param = true)

    line 31
  4. Distinctive:

    Check output directory exists before download

    line 33
  5. Distinctive:

    Use unverified downloads for critical data

    line 38

≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Download File from 0G Storage

Metadata

  • Category: storage
  • SDK: @0gfoundation/0g-storage-ts-sdk ^1.2.12, ethers 6.13.1
  • Activation Triggers: "download file", "retrieve from 0G", "get file", "fetch from storage"

Purpose

Download and verify files from 0G decentralized storage using a root hash. Supports verified downloads with Merkle proof validation to ensure data integrity.

Prerequisites

  • Node.js >= 18
  • @0gfoundation/0g-storage-ts-sdk installed
  • Root hash of the file to download
  • .env with STORAGE_INDEXER

Quick Workflow

  1. Create an Indexer instance
  2. Call indexer.download() with the root hash, output path, and verified flag
  3. The file is downloaded and optionally verified via Merkle proofs

Core Rules

ALWAYS

  • Use verified downloads in production (third param = true)
  • Validate root hash format before downloading
  • Check output directory exists before download
  • Handle download errors gracefully

NEVER

  • Use unverified downloads for critical data
  • Assume a root hash is valid without checking
  • Download to paths without write permissions

Code Examples

Basic Download

import { Indexer } from '@0gfoundation/0g-storage-ts-sdk';
import 'dotenv/config';

async function downloadFile(rootHash: string, outputPath: string): Promise<void> {
  const indexer = new Indexer(process.env.STORAGE_INDEXER!);

  // Download with Merkle verification (recommended)
  // Note: download() can throw errors (e.g., JsonRpcError) in addition to returning them
  try {
    const err = await indexer.download(rootHash, outputPath, true);
    if (err) throw err;
  } catch (error: any) {
    throw new Error(`Download failed: ${error.message}`);
  }
  console.log(`Downloaded to ${outputPath}`);
}

// Usage
await downloadFile('0xabc123...', './downloads/my-file.pdf');

Download with Validation

import { Indexer } from '@0gfoundation/0g-storage-ts-sdk';
import * as fs from 'fs';
import * as path from 'path';
import 'dotenv/config';

async function downloadWithValidation(rootHash: string, outputPath: string): Promise<void> {
  if (!process.env.STORAGE_INDEXER) {
    throw new Error('STORAGE_INDEXER not set in .env');
  }

  // Validate root hash format
  if (!rootHash.startsWith('0x') || rootHash.length < 10) {
    throw new Error('Invalid root hash format');
  }

  // Ensure output directory exists
  const dir = path.dirname(outputPath);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }

  const indexer = new Indexer(process.env.STORAGE_INDEXER!);

  try {
    // download() can throw OR return an error — handle both
    const err = await indexer.download(rootHash, outputPath, true);
    if (err) throw err;
    console.log(`Downloaded and verified: ${outputPath}`);

    const stats = fs.statSync(outputPath);
    console.log(`File size: ${stats.size} bytes`);
  } catch (error: any) {
    if (error.message?.includes('not found') || error.message?.includes('JsonRpc')) {
      throw new Error(`File not found for root hash: ${rootHash}`);
    }
    throw error;
  }
}

Batch Download

async function downloadBatch(
  files: Array<{ rootHash: string; outputPath: string }>,
): Promise<void> {
  const indexer = new Indexer(process.env.STORAGE_INDEXER!);

  const results = await Promise.allSettled(
    files.map(async ({ rootHash, outputPath }) => {
      const err = await indexer.download(rootHash, outputPath, true);
      if (err) throw err;
    }),
  );

  results.forEach((result, i) => {
    if (result.status === 'fulfilled') {
      console.log(`Downloaded: ${files[i].outputPath}`);
    } else {
      console.error(`Failed: ${files[i].rootHash} — ${result.reason}`);
    }
  });
}

Anti-Patterns

// BAD: Unverified download in production
await indexer.download(rootHash, outputPath, false);

// BAD: No error handling — download() can THROW in addition to returning errors
await indexer.download(rootHash, outputPath, true);
// If file doesn't exist, throws JsonRpcError!

// GOOD: Proper error handling
try {
  const err = await indexer.download(rootHash, outputPath, true);
  if (err) throw err;
} catch (error) {
  console.error('Download failed:', error);
}

// BAD: Downloading to non-existent directory
await indexer.download(rootHash, '/nonexistent/path/file.txt', true);

Common Errors & Fixes

ErrorCauseFix
file not foundInvalid or non-existent root hashVerify the root hash is correct
verification failedData integrity check failedRe-download or report issue
ENOENTOutput directory doesn't existCreate directory with fs.mkdirSync
EACCESNo write permissionCheck file system permissions
indexer not availableWrong indexer URLCheck STORAGE_INDEXER in .env

Related Skills

  • Upload File — upload files to get root hashes
  • Merkle Verification — verify data integrity
  • Compute + Storage — AI with storage I/O

References

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.