upload-file
Skill15 starsChanged 58 days agoMITView on GitHub
Upload files to 0G decentralized storage using the ZgFile API and Indexer. Files are split into chunks, organized as a Merkle tree, and distributed across storage nodes. Returns a root hash for later retrieval.
- Reads credentials
2 other projects use a version of this.
Adopted by
Most recently taken up by
- a1ecbr0wn/obsidian-mcp-braintheir own version, first seen Nov 1, 2026
- mia-cx/skillstheir own version, first seen Oct 16, 2026
Other versions2 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 2
- mia-cx/skills★ 4same name
- a1ecbr0wn/obsidian-mcp-brain★ 1same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository26 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- agent-accountsSkill
- agent-reputationSkill
- deploy-agentSkill
- interact-agentSkill
- manage-agentSkill
- deploy-contractSkill
- interact-contractSkill
- scaffold-projectSkill
- account-managementSkill
- embeddingsSkill
- fine-tuningSkill
- image-editingSkill
- provider-discoverySkill
- speech-to-textSkill
- streaming-chatSkill
- text-to-imageSkill
- video-generationSkill
- compute-plus-storageSkill
- storage-plus-chainSkill
- 0g-pc-setupSkill
- 0g-pc-switch-modelSkill
- 0g-pc-uninstallSkill
- download-fileSkill
- merkle-verificationSkill
The file
We split this skill into the rules it gives an agent
5 rules. About 0 are common, 1 is distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 25
Create an Indexer instance
- Very specific: line 26
Create a ZgFile from the file path
- Distinctive: line 39
Use try/finally to ensure file handles are closed
- Very specific: line 40
Read the upload result by field: result.txHash, result.rootHash, result.txSeq
- Very specific: line 47
Treat the first element of the upload() result as a transaction-hash string — it is an object
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 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.
Files
Upload File to 0G Storage
Metadata
- Category: storage
- SDK:
@0gfoundation/0g-storage-ts-sdk^1.2.12,ethers6.13.1 - Activation Triggers: "upload file", "store on 0G", "ZgFile", "save to storage"
Purpose
Upload files to 0G decentralized storage using the ZgFile API and Indexer. Files are split into chunks, organized as a Merkle tree, and distributed across storage nodes. Returns a root hash for later retrieval.
Prerequisites
- Node.js >= 18
@0gfoundation/0g-storage-ts-sdkandethersinstalled- Funded wallet with 0G tokens
.envwithPRIVATE_KEY,RPC_URL,STORAGE_INDEXER
Quick Workflow
- Initialize ethers provider and wallet from
.env - Create an
Indexerinstance - Create a
ZgFilefrom the file path - Generate the Merkle tree (computes root hash)
- Upload via the Indexer
- Close the file handle (critical!)
- Return/store the root hash
Core Rules
ALWAYS
- Generate the Merkle tree BEFORE uploading
- Close file handles after upload (
file.close()) - Store root hashes — they are the ONLY way to retrieve files later
- Use try/finally to ensure file handles are closed
- Read the upload result by field:
result.txHash,result.rootHash,result.txSeq - Load private keys from environment variables
NEVER
- Skip Merkle tree generation before upload
- Forget to close
ZgFilehandles (causes memory leaks) - Treat the first element of the
upload()result as a transaction-hash string — it is an object - Hardcode private keys in source code
- Lose the root hash (data becomes irretrievable)
Code Examples
Basic File Upload
import { ZgFile, Indexer } from '@0gfoundation/0g-storage-ts-sdk';
import { ethers } from 'ethers';
import 'dotenv/config';
async function uploadFile(filePath: string): Promise<string> {
const provider = new ethers.JsonRpcProvider(process.env.RPC_URL);
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!, provider);
const indexer = new Indexer(process.env.STORAGE_INDEXER!);
const file = await ZgFile.fromFilePath(filePath);
try {
const [tree, err] = await file.merkleTree();
if (err) throw new Error(`Merkle tree error: ${err}`);
const rootHash = tree!.rootHash();
console.log('Root hash:', rootHash);
// upload() resolves to [result, error]. `result` is an OBJECT, not a hash
// string, and it is a UNION of two shapes:
// single file -> { txHash, rootHash, txSeq }
// fragmented file -> { txHashes, rootHashes, txSeqs }
// Narrow with an `in` check before reading either shape.
const [result, uploadErr] = await indexer.upload(file, process.env.RPC_URL!, wallet);
if (uploadErr) throw new Error(`Upload failed: ${uploadErr.message}`);
const txHash = 'txHash' in result ? result.txHash : result.txHashes[0];
const uploadedRoot = 'rootHash' in result ? result.rootHash : result.rootHashes[0];
console.log('Upload tx:', txHash);
console.log('Root hash from upload:', uploadedRoot); // matches `rootHash` above
return rootHash;
} finally {
await file.close();
}
}
// Usage
const rootHash = await uploadFile('./my-document.pdf');
console.log('Stored with root hash:', rootHash);Upload from Buffer
import { ZgFile, Indexer } from '@0gfoundation/0g-storage-ts-sdk';
import { ethers } from 'ethers';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import 'dotenv/config';
async function uploadBuffer(data: Buffer, filename: string): Promise<string> {
const provider = new ethers.JsonRpcProvider(process.env.RPC_URL);
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!, provider);
const indexer = new Indexer(process.env.STORAGE_INDEXER!);
// SDK requires file path — write buffer to temp file
const tempPath = path.join(os.tmpdir(), `0g-upload-${Date.now()}-${filename}`);
fs.writeFileSync(tempPath, data);
const file = await ZgFile.fromFilePath(tempPath);
try {
const [tree, err] = await file.merkleTree();
if (err) throw new Error(`Merkle tree error: ${err}`);
const rootHash = tree!.rootHash();
const [, uploadErr] = await indexer.upload(file, process.env.RPC_URL!, wallet);
if (uploadErr) throw new Error(`Upload failed: ${uploadErr.message}`);
return rootHash;
} finally {
await file.close();
fs.unlinkSync(tempPath); // Clean up temp file
}
}
// Usage
const jsonData = Buffer.from(JSON.stringify({ key: 'value' }));
const rootHash = await uploadBuffer(jsonData, 'data.json');Upload with Progress and Error Handling
import { ZgFile, Indexer } from '@0gfoundation/0g-storage-ts-sdk';
import { ethers } from 'ethers';
import * as fs from 'fs';
import 'dotenv/config';
async function uploadWithValidation(filePath: string): Promise<string> {
// Validate environment
if (!process.env.PRIVATE_KEY) throw new Error('PRIVATE_KEY not set in .env');
if (!process.env.RPC_URL) throw new Error('RPC_URL not set in .env');
if (!process.env.STORAGE_INDEXER) throw new Error('STORAGE_INDEXER not set in .env');
// Validate file exists
if (!fs.existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
const stats = fs.statSync(filePath);
if (stats.size === 0) throw new Error('Cannot upload empty file');
console.log(`Uploading ${filePath} (${stats.size} bytes)...`);
const provider = new ethers.JsonRpcProvider(process.env.RPC_URL);
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!, provider);
// Check wallet balance
const balance = await provider.getBalance(wallet.address);
if (balance === 0n) throw new Error('Wallet has no 0G tokens');
const indexer = new Indexer(process.env.STORAGE_INDEXER!);
const file = await ZgFile.fromFilePath(filePath);
try {
console.log('Generating Merkle tree...');
const [tree, err] = await file.merkleTree();
if (err) throw new Error(`Merkle tree generation failed: ${err}`);
const rootHash = tree!.rootHash();
console.log('Root hash:', rootHash);
console.log('Uploading to 0G Storage...');
const [result, uploadErr] = await indexer.upload(file, process.env.RPC_URL!, wallet);
if (uploadErr) throw new Error(`Upload failed: ${uploadErr.message}`);
const txHash = 'txHash' in result ? result.txHash : result.txHashes[0];
console.log('Upload complete! Tx:', txHash);
return rootHash;
} finally {
await file.close();
}
}Anti-Patterns
// BAD: Missing file.close() — memory leak
const file = await ZgFile.fromFilePath('data.txt');
const [tree] = await file.merkleTree();
await indexer.upload(file, process.env.RPC_URL!, wallet);
// file.close() never called!
// BAD: Uploading without Merkle tree
const file = await ZgFile.fromFilePath('data.txt');
await indexer.upload(file, process.env.RPC_URL!, wallet); // May fail or produce invalid upload
await file.close();
// BAD: Hardcoded private key
const wallet = new ethers.Wallet('0xabc123...', provider);
// BAD: Not storing root hash
await indexer.upload(file, process.env.RPC_URL!, wallet); // Root hash lost!
// BAD: Wrong upload signature (missing RPC URL)
await indexer.upload(file, wallet); // TypeError — must pass RPC URL as second argCommon Errors & Fixes
| Error | Cause | Fix |
Merkle tree error | Empty or corrupted file | Verify file exists and has content |
insufficient funds | Wallet has no 0G tokens | Fund wallet from faucet (testnet) |
indexer not available | Wrong indexer URL | Check STORAGE_INDEXER in .env |
ENOENT: no such file | Invalid file path | Verify file path is correct |
connection refused | RPC endpoint down | Check network status or try alt RPC |
Related Skills
- Download File — retrieve uploaded files
- Merkle Verification — verify data integrity
- Storage + Chain — on-chain references
References
- Storage Patterns
- Network Config
- Security Patterns
- 0G Storage SDK Docs
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
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.

